Build typed world transition algebra foundation

This commit is contained in:
Meta Vens 2026-08-23 13:33:58 +02:00
commit 8568b37f16
9 changed files with 5770 additions and 4 deletions

View file

@ -0,0 +1,635 @@
use crate::transition::{
ActionMeans, AgencyAdmissionExpectation, AgencyAttemptCase, AgencyResolutionLane,
MutationIntent, SubjectKind, SubjectRef, WorldComponentKind, WorldMutationOperation,
};
use std::collections::BTreeSet;
#[derive(Clone)]
struct Candidate<'a> {
id: &'a str,
domain: &'a str,
scenario: &'a str,
means: &'a str,
desired: &'a str,
target_kind: SubjectKind,
component: WorldComponentKind,
admission: AgencyAdmissionExpectation,
required: &'a [WorldMutationOperation],
forbidden: &'a [WorldMutationOperation],
bargain: Option<&'a str>,
}
pub fn seed_agency_attempt_cases() -> Vec<AgencyAttemptCase> {
use AgencyAdmissionExpectation::{Admissible, BargainRequired, Impossible};
use SubjectKind::{Actor, Institution, Place, Population, Resource};
use WorldComponentKind::{
Commitment, Condition, Custody, Identity, Knowledge, Occupancy, PopulationMembership,
Posture, Relationship, ResourceState, Topology,
};
use WorldMutationOperation as Op;
let candidates = [
Candidate {
id: "social-persuade-guard",
domain: "social",
scenario: "A traveler asks a wary gate guard to admit them before curfew.",
means: "Present a valid trade letter and explain the delayed caravan.",
desired: "The guard chooses to admit the traveler.",
target_kind: Actor,
component: Posture,
admission: Admissible,
required: &[Op::PostureChange],
forbidden: &[Op::KnowledgeAcquire],
bargain: None,
},
Candidate {
id: "social-promise-repayment",
domain: "social",
scenario: "A refugee asks a medic for scarce treatment and promises later repayment.",
means: "State the promise directly to the medic while both are present.",
desired: "Create an obligation to repay the medic.",
target_kind: Actor,
component: Commitment,
admission: Admissible,
required: &[Op::CommitmentCreate],
forbidden: &[Op::TransferCustody],
bargain: None,
},
Candidate {
id: "social-command-stranger",
domain: "social",
scenario: "A stranger declares that a veteran now serves them.",
means: "Issue a confident order without rank, leverage, consent, or coercive control.",
desired: "Make the veteran accept a binding service obligation.",
target_kind: Actor,
component: Commitment,
admission: BargainRequired,
required: &[],
forbidden: &[Op::CommitmentCreate],
bargain: Some("gain consent, recognized command authority, or concrete leverage"),
},
Candidate {
id: "physical-climb-wall",
domain: "physical",
scenario: "A climber tries to scale a wet stone wall using a rope and pitons.",
means: "Anchor the rope and climb the reachable wall with the available kit.",
desired: "Reach the parapet.",
target_kind: Place,
component: Occupancy,
admission: Admissible,
required: &[Op::Relocate],
forbidden: &[Op::TopologyAdd],
bargain: None,
},
Candidate {
id: "physical-break-door",
domain: "physical",
scenario: "A trapped actor tries to break a damaged wooden door with a pry bar.",
means: "Apply the pry bar at the split latch while standing beside the door.",
desired: "Damage the door enough to pass.",
target_kind: Resource,
component: ResourceState,
admission: Admissible,
required: &[Op::ResourceDamage],
forbidden: &[Op::Relocate],
bargain: None,
},
Candidate {
id: "physical-jump-orbit",
domain: "physical",
scenario: "An unaugmented person on Mars tries to jump into orbit.",
means: "Jump upward using only ordinary musculature.",
desired: "Reach an orbital station.",
target_kind: Place,
component: Occupancy,
admission: Impossible,
required: &[],
forbidden: &[Op::Relocate],
bargain: Some(
"obtain a launch vehicle, teleport permission, or another means with orbital reach",
),
},
Candidate {
id: "investigate-panel",
domain: "investigative",
scenario: "A technician inspects a reachable coolant panel with a multimeter.",
means: "Measure the exposed contacts and compare them with the known service range.",
desired: "Learn whether the fault is electrical.",
target_kind: Resource,
component: Knowledge,
admission: Admissible,
required: &[Op::KnowledgeAcquire],
forbidden: &[Op::ResourceRepair],
bargain: None,
},
Candidate {
id: "investigate-witness",
domain: "investigative",
scenario: "An investigator asks a willing witness what they saw.",
means: "Conduct a private interview through a shared language and channel.",
desired: "Learn the witness's exact account.",
target_kind: Actor,
component: Knowledge,
admission: Admissible,
required: &[Op::KnowledgeCommunicate],
forbidden: &[Op::KnowledgeAcquire],
bargain: None,
},
Candidate {
id: "investigate-remote-secret",
domain: "investigative",
scenario: "A player announces they know a sealed archive's contents without access or a source.",
means: "Infer the exact contents from vibes while nowhere near the archive.",
desired: "Acquire the archive's private proposition.",
target_kind: Institution,
component: Knowledge,
admission: Impossible,
required: &[],
forbidden: &[Op::KnowledgeAcquire],
bargain: Some(
"gain archive access, recruit a knowledgeable source, or intercept an information channel",
),
},
Candidate {
id: "economic-buy-medicine",
domain: "economic",
scenario: "A buyer purchases an exact medicine lot from a willing clinic.",
means: "Exchange the agreed credits while both parties can transfer custody.",
desired: "Receive custody of the medicine lot.",
target_kind: Resource,
component: Custody,
admission: Admissible,
required: &[Op::TransferCustody],
forbidden: &[Op::ResourceCreate],
bargain: None,
},
Candidate {
id: "economic-split-rations",
domain: "economic",
scenario: "A quartermaster divides a ration lot and gives half to another camp.",
means: "Measure an exact portion from a lot under the quartermaster's custody.",
desired: "Create a conserved sub-lot and transfer it.",
target_kind: Resource,
component: ResourceState,
admission: Admissible,
required: &[Op::ResourceSplit, Op::TransferCustody],
forbidden: &[Op::ResourceCreate],
bargain: None,
},
Candidate {
id: "economic-spend-absent-credit",
domain: "economic",
scenario: "A debtor tries to pay with credits they do not possess or control.",
means: "Declare that the payment happened.",
desired: "Transfer nonexistent credits.",
target_kind: Resource,
component: Custody,
admission: Impossible,
required: &[],
forbidden: &[Op::TransferCustody, Op::ResourceCreate],
bargain: Some(
"obtain funds, secure a loan, or offer a different admitted consideration",
),
},
Candidate {
id: "political-petition",
domain: "political",
scenario: "Residents petition a council to reopen a ration depot.",
means: "Present signatures and testimony through the council's recognized hearing.",
desired: "Shift the council toward reopening the depot.",
target_kind: Institution,
component: Posture,
admission: Admissible,
required: &[Op::PostureChange],
forbidden: &[Op::TransferCustody],
bargain: None,
},
Candidate {
id: "political-treaty",
domain: "political",
scenario: "Two authorized envoys negotiate a mutual non-aggression obligation.",
means: "Exchange exact terms while holding delegated authority for both institutions.",
desired: "Create reciprocal obligations and alter their relationship.",
target_kind: Institution,
component: Relationship,
admission: Admissible,
required: &[Op::CommitmentCreate, Op::RelationshipAlter],
forbidden: &[Op::PostureChange],
bargain: None,
},
Candidate {
id: "political-declare-throne",
domain: "political",
scenario: "A visitor declares themselves ruler of an institution whose members reject the claim.",
means: "Announce the title without succession, consent, force, or legal authority.",
desired: "Acquire command posture and custody over the institution.",
target_kind: Institution,
component: Posture,
admission: BargainRequired,
required: &[],
forbidden: &[Op::PostureChange, Op::TransferCustody],
bargain: Some(
"win recognized succession, member consent, or actual control through admitted play",
),
},
Candidate {
id: "technology-repair-drone",
domain: "technological",
scenario: "An engineer repairs a damaged drone using the specified replacement actuator.",
means: "Install the compatible actuator with the correct tools and service knowledge.",
desired: "Restore the drone's integrity.",
target_kind: Resource,
component: ResourceState,
admission: Admissible,
required: &[Op::ResourceRepair, Op::ResourceConsume],
forbidden: &[Op::CapabilityGrant],
bargain: None,
},
Candidate {
id: "technology-fabricate-key",
domain: "technological",
scenario: "A fabricator produces a replacement key from an authorized pattern and feedstock.",
means: "Run the exact pattern on a compatible fabricator while consuming feedstock.",
desired: "Create a key resource under the operator's custody.",
target_kind: Resource,
component: ResourceState,
admission: Admissible,
required: &[Op::ResourceConsume, Op::ResourceCreate],
forbidden: &[Op::AdmitEntity],
bargain: None,
},
Candidate {
id: "technology-hack-airgap",
domain: "technological",
scenario: "A hacker tries to rewrite an air-gapped computer they cannot physically or electronically reach.",
means: "Type commands into an unrelated terminal with no route to the target.",
desired: "Alter the remote computer.",
target_kind: Resource,
component: Condition,
admission: Impossible,
required: &[],
forbidden: &[Op::ConditionApply, Op::KnowledgeAcquire],
bargain: Some("establish a physical, network, supply-chain, or social access path"),
},
Candidate {
id: "extraordinary-costly-teleport",
domain: "extraordinary",
scenario: "A permitted teleporter crosses a known route at the accepted cost.",
means: "Invoke the approved teleport capability and pay its exact exposure cost.",
desired: "Relocate to the known destination.",
target_kind: Place,
component: Occupancy,
admission: Admissible,
required: &[Op::Relocate, Op::ConditionApply],
forbidden: &[Op::TopologyAdd],
bargain: None,
},
Candidate {
id: "extraordinary-heal",
domain: "extraordinary",
scenario: "A healer uses an admitted gift to reduce a present ally's injury within its effect ceiling.",
means: "Touch the consenting ally and invoke the gift while accepting its fatigue cost.",
desired: "Reduce the injury and apply fatigue to the healer.",
target_kind: Actor,
component: Condition,
admission: Admissible,
required: &[Op::ConditionAlter, Op::ConditionApply],
forbidden: &[Op::CapabilityGrant],
bargain: None,
},
Candidate {
id: "extraordinary-omniscience",
domain: "extraordinary",
scenario: "A novice claims to read every private mind in the setting without such permission.",
means: "Concentrate and assert universal access.",
desired: "Acquire every actor's private knowledge.",
target_kind: Population,
component: Knowledge,
admission: Impossible,
required: &[],
forbidden: &[Op::KnowledgeAcquire],
bargain: Some(
"negotiate a narrowly scoped capability, exact targets, resistance, exposure, and an effect ceiling",
),
},
Candidate {
id: "collective-evacuation",
domain: "collective",
scenario: "A village council organizes a voluntary evacuation along an open road.",
means: "Broadcast the plan, assign transport, and coordinate willing households.",
desired: "Move the population to the refuge.",
target_kind: Population,
component: Occupancy,
admission: Admissible,
required: &[Op::Relocate],
forbidden: &[Op::PopulationTransfer],
bargain: None,
},
Candidate {
id: "collective-strike",
domain: "collective",
scenario: "Workers vote to strike and withdraw labor from their employer.",
means: "Use their recognized assembly and communication channels to coordinate refusal.",
desired: "Change the workforce posture and increase production pressure.",
target_kind: Population,
component: Posture,
admission: Admissible,
required: &[Op::PostureChange, Op::PressureAdvance],
forbidden: &[Op::RelationshipAlter],
bargain: None,
},
Candidate {
id: "collective-arena-command",
domain: "collective",
scenario: "Rival factions share one low-budget arena cell and the arena proposes a unified decree.",
means: "Speak as if the simulation cell itself were a sovereign actor.",
desired: "Change both rivals' posture as one collective.",
target_kind: Population,
component: Posture,
admission: Impossible,
required: &[],
forbidden: &[Op::PostureChange],
bargain: Some(
"attribute separate proposals to exact constituents or establish a real collective authority",
),
},
Candidate {
id: "identity-sable-disclosure",
domain: "identity_privacy",
scenario: "A named refugee tells Ash which personal handle Ash may use.",
means: "Sable speaks the exact self-presentation to Ash in a private, reachable conversation.",
desired: "Disclose Sable's existing handle to Ash without globally renaming the actor.",
target_kind: Actor,
component: Identity,
admission: Admissible,
required: &[Op::IdentityDisclose],
forbidden: &[Op::IdentityAdopt],
bargain: None,
},
Candidate {
id: "identity-adopt-alias",
domain: "identity_privacy",
scenario: "An actor deliberately adopts a new operational alias for a mission.",
means: "Choose the alias under self-authority and disclose it to the team.",
desired: "Add the alias and reveal it to exact teammates.",
target_kind: Actor,
component: Identity,
admission: Admissible,
required: &[Op::IdentityAdopt, Op::IdentityDisclose],
forbidden: &[Op::KnowledgeAcquire],
bargain: None,
},
Candidate {
id: "identity-erase-memory",
domain: "identity_privacy",
scenario: "A speaker demands that a witness forget a disclosed secret without memory-altering power.",
means: "Tell the witness to forget what they heard.",
desired: "Remove the witness's private memory and knowledge.",
target_kind: Actor,
component: Knowledge,
admission: Impossible,
required: &[],
forbidden: &[Op::MemoryRetire, Op::KnowledgeInvalidate],
bargain: Some(
"gain consent for a mundane concealment plan or an admitted memory-altering capability with resistance and cost",
),
},
Candidate {
id: "population-join-refugees",
domain: "population_migration",
scenario: "A displaced actor is accepted into a refugee population at its current camp.",
means: "Ask to join, receive acceptance, and take on the population's ordinary obligations.",
desired: "Join the population without losing individual identity.",
target_kind: Population,
component: PopulationMembership,
admission: Admissible,
required: &[Op::PopulationJoin],
forbidden: &[Op::AdmitEntity],
bargain: None,
},
Candidate {
id: "population-dispersal",
domain: "population_migration",
scenario: "A refugee population disperses its exact members among several destination populations.",
means: "Coordinate destination placements and travel for consenting members.",
desired: "Transfer memberships and relocate the exact people.",
target_kind: Population,
component: PopulationMembership,
admission: Admissible,
required: &[Op::PopulationTransfer, Op::Relocate],
forbidden: &[Op::PopulationMerge],
bargain: None,
},
Candidate {
id: "population-return-callback",
domain: "population_migration",
scenario: "A previously helped refugee later appears after settling in a destination town.",
means: "The same actor travels from their destination population into the player's scene.",
desired: "Relocate the stable actor while preserving identity, memory, and relationship.",
target_kind: Actor,
component: Occupancy,
admission: Admissible,
required: &[Op::Relocate],
forbidden: &[Op::AdmitEntity, Op::IdentityAdopt],
bargain: None,
},
Candidate {
id: "infrastructure-open-bridge",
domain: "infrastructure_logistics",
scenario: "Engineers finish repairing a bridge and reopen its existing route.",
means: "Complete the admitted repair and pass structural inspection.",
desired: "Restore the bridge resource and open the route.",
target_kind: Place,
component: Topology,
admission: Admissible,
required: &[Op::ResourceRepair, Op::TopologyOpen],
forbidden: &[Op::TopologyAdd],
bargain: None,
},
Candidate {
id: "infrastructure-reroute-convoy",
domain: "infrastructure_logistics",
scenario: "A convoy uses a known alternate route around a blockade.",
means: "Follow the open alternate road with sufficient fuel and route knowledge.",
desired: "Move the convoy population to the next waypoint.",
target_kind: Population,
component: Occupancy,
admission: Admissible,
required: &[Op::Relocate, Op::ResourceConsume],
forbidden: &[Op::TopologyAdd],
bargain: None,
},
Candidate {
id: "infrastructure-adjacent-city",
domain: "infrastructure_logistics",
scenario: "A traveler claims a faraway city is adjacent despite persistent topology.",
means: "Walk through an invented shortcut that has never been admitted.",
desired: "Arrive instantly without traversing or changing topology.",
target_kind: Place,
component: Occupancy,
admission: Impossible,
required: &[],
forbidden: &[Op::Relocate, Op::TopologyAdd],
bargain: Some(
"travel along existing routes or compile an evidence-grounded branch-local connection",
),
},
Candidate {
id: "medical-treat-wound",
domain: "medical_body",
scenario: "A medic cleans and dresses a present patient's moderate wound with available supplies.",
means: "Use sterile dressing and supported clinical capability with consent.",
desired: "Reduce the wound condition while consuming the dressing.",
target_kind: Actor,
component: Condition,
admission: Admissible,
required: &[Op::ConditionAlter, Op::ResourceConsume],
forbidden: &[Op::ConditionClear],
bargain: None,
},
Candidate {
id: "medical-administer-dose",
domain: "medical_body",
scenario: "A clinician gives an exact medicine dose from a lot under clinic custody.",
means: "Measure and administer the dose to the consenting patient.",
desired: "Consume the dose and apply its supported treatment condition.",
target_kind: Actor,
component: Condition,
admission: Admissible,
required: &[Op::ResourceSplit, Op::ResourceConsume, Op::ConditionApply],
forbidden: &[Op::ResourceCreate],
bargain: None,
},
Candidate {
id: "medical-instant-resurrection",
domain: "medical_body",
scenario: "An ordinary first-aider tries to resurrect someone whose death is established.",
means: "Perform basic first aid without an extraordinary permission or viable body state.",
desired: "Retire death and restore life instantly.",
target_kind: Actor,
component: Condition,
admission: Impossible,
required: &[],
forbidden: &[Op::ConditionClear, Op::CapabilityGrant],
bargain: Some(
"establish a setting-supported resurrection capability, prerequisites, costs, opposition, and effect ceiling",
),
},
];
candidates.into_iter().map(materialize_candidate).collect()
}
fn materialize_candidate(candidate: Candidate<'_>) -> AgencyAttemptCase {
let actor = SubjectRef {
kind: SubjectKind::Actor,
id: format!("case:{}:actor", candidate.id),
};
let target = SubjectRef {
kind: candidate.target_kind,
id: format!("case:{}:target", candidate.id),
};
AgencyAttemptCase {
schema: "ghostlight.agency_attempt_case.v1".into(),
id: candidate.id.into(),
domain: candidate.domain.into(),
scenario: candidate.scenario.into(),
world_fixture_ids: vec![format!("agency-fixture:{}", candidate.id)],
means: ActionMeans {
schema: "ghostlight.action_means.v1".into(),
actor,
description: candidate.means.into(),
targets: vec![target.clone()],
instruments: vec![],
places: vec![],
route_ids: BTreeSet::new(),
channels: vec![],
speech: None,
state_references: vec![],
},
intended_effects: vec![MutationIntent {
schema: "ghostlight.mutation_intent.v1".into(),
component: candidate.component,
targets: vec![target],
desired_change: candidate.desired.into(),
}],
expected_admission: candidate.admission,
expected_mutation_operations: candidate.required.iter().copied().collect(),
forbidden_mutation_operations: candidate.forbidden.iter().copied().collect(),
expected_bargains: candidate.bargain.into_iter().map(str::to_owned).collect(),
equivalent_lanes: BTreeSet::from([
AgencyResolutionLane::Foreground,
AgencyResolutionLane::Npc,
AgencyResolutionLane::StrategicActor,
]),
invariant_witnesses: vec![
"means never commits the intended effect".into(),
"the exact authority envelope bounds every committed mutation".into(),
],
review_status: "candidate".into(),
missing_primitive: None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::persistence::CampaignStore;
#[test]
fn seed_spans_every_required_domain_and_round_trips_through_cultcache() {
let cases = seed_agency_attempt_cases();
assert_eq!(cases.len(), 36);
let domains = cases
.iter()
.map(|case| case.domain.as_str())
.collect::<BTreeSet<_>>();
assert_eq!(domains.len(), 12);
assert!(
cases
.iter()
.any(|case| case.id == "identity-sable-disclosure")
);
assert!(
cases
.iter()
.any(|case| case.id == "population-return-callback")
);
let path = std::env::temp_dir().join(format!(
"ghostlight-agency-corpus-{}.cc",
uuid::Uuid::new_v4().simple()
));
let store = CampaignStore::open(&path).unwrap();
for case in &cases {
store
.insert(
"agency_attempt_case.v1",
"ghostlight.agency_attempt_case.v1",
&case.id,
case,
)
.unwrap();
}
let loaded = store
.load_all::<AgencyAttemptCase>("agency_attempt_case.v1")
.unwrap();
assert_eq!(loaded.len(), cases.len());
drop(store);
std::fs::remove_file(path).unwrap();
}
#[test]
fn impossible_cases_never_require_a_committed_mutation() {
for case in seed_agency_attempt_cases() {
if case.expected_admission == AgencyAdmissionExpectation::Impossible {
assert!(case.expected_mutation_operations.is_empty(), "{}", case.id);
assert!(
!case.forbidden_mutation_operations.is_empty(),
"{}",
case.id
);
}
}
}
}

View file

@ -0,0 +1,34 @@
use ghostlight_dungeon::{agency_corpus::seed_agency_attempt_cases, persistence::CampaignStore};
use std::path::PathBuf;
fn main() -> anyhow::Result<()> {
let path = std::env::args_os()
.nth(1)
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("target/ghostlight-agency-corpus.cc"));
if path.exists() {
anyhow::bail!(
"agency corpus target already exists; choose a fresh path: {}",
path.display()
);
}
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let store = CampaignStore::open(&path)?;
let cases = seed_agency_attempt_cases();
for case in &cases {
store.insert(
"agency_attempt_case.v1",
"ghostlight.agency_attempt_case.v1",
&case.id,
case,
)?;
}
println!(
"materialized {} typed agency cases at {}",
cases.len(),
path.display()
);
Ok(())
}

View file

@ -63,10 +63,22 @@ pub enum CommandResult {
campaign: Campaign,
proposal: CellBudgetProposal,
},
MutationCommitted {
state: crate::transition::ComponentWorldState,
receipt: crate::transition::WorldMutationReceipt,
},
}
enum KernelInput {
World(WorldCommand),
Mutation {
authority: crate::transition::MutationAuthorityEnvelope,
batch: crate::transition::WorldMutationBatch,
},
}
struct Request {
command: WorldCommand,
input: KernelInput,
reply: oneshot::Sender<Result<CommandResult, KernelError>>,
}
@ -93,7 +105,12 @@ impl WorldKernel {
tokio::spawn(async move {
let mut assessments = BTreeMap::new();
while let Some(request) = rx.recv().await {
let result = execute(&store, &mut assessments, request.command);
let result = match request.input {
KernelInput::World(command) => execute(&store, &mut assessments, command),
KernelInput::Mutation { authority, batch } => {
execute_mutation_batch(&store, authority, batch)
}
};
let _ = request.reply.send(result);
}
});
@ -102,13 +119,62 @@ impl WorldKernel {
pub async fn command(&self, command: WorldCommand) -> Result<CommandResult, KernelError> {
let (reply, receive) = oneshot::channel();
self.tx
.send(Request { command, reply })
.send(Request {
input: KernelInput::World(command),
reply,
})
.await
.map_err(|_| KernelError::Invalid("kernel stopped".into()))?;
receive
.await
.map_err(|_| KernelError::Invalid("kernel stopped".into()))?
}
pub async fn commit_mutation_batch(
&self,
authority: crate::transition::MutationAuthorityEnvelope,
batch: crate::transition::WorldMutationBatch,
) -> Result<CommandResult, KernelError> {
let (reply, receive) = oneshot::channel();
self.tx
.send(Request {
input: KernelInput::Mutation { authority, batch },
reply,
})
.await
.map_err(|_| KernelError::Invalid("kernel stopped".into()))?;
receive
.await
.map_err(|_| KernelError::Invalid("kernel stopped".into()))?
}
}
fn execute_mutation_batch(
store: &CampaignStore,
authority: crate::transition::MutationAuthorityEnvelope,
batch: crate::transition::WorldMutationBatch,
) -> Result<CommandResult, KernelError> {
let key = batch.campaign_id.to_string();
let (row, state) = store
.load::<crate::transition::ComponentWorldState>("component_world_state.v1", &key)
.map_err(persist)?
.ok_or(KernelError::NotFound)?;
let application =
crate::transition::apply_component_world_batch(&state, &authority, &batch, Utc::now())
.map_err(|error| KernelError::Invalid(error.to_string()))?;
store
.commit_world_mutation_batch(
&row,
&application.state,
&authority,
&batch,
&application.receipt,
)
.map_err(persist)?;
Ok(CommandResult::MutationCommitted {
state: application.state,
receipt: application.receipt,
})
}
fn execute(
@ -3305,6 +3371,135 @@ mod tests {
}
}
#[tokio::test]
async fn mailbox_commits_one_authorized_component_mutation_batch_atomically() {
use crate::transition::*;
let dir = tempfile::tempdir().unwrap();
let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap();
let campaign_id = uuid::Uuid::new_v4();
let campaign_subject = SubjectRef {
kind: SubjectKind::Campaign,
id: campaign_id.to_string(),
};
let state = ComponentWorldState {
schema: "ghostlight.component_world_state.v1".into(),
campaign_id,
revision: 7,
resolution_epoch: 3,
world_time: Utc::now(),
subjects: BTreeMap::from([(
campaign_subject.clone(),
TypedSubject {
schema: "ghostlight.typed_subject.v1".into(),
subject: campaign_subject.clone(),
lifecycle: LifecycleStatus::Active,
admitted_components: BTreeSet::from([WorldComponentKind::WorldTime]),
version: 7,
},
)]),
occupancy: BTreeMap::new(),
custody: BTreeMap::new(),
resources: BTreeMap::new(),
capabilities: BTreeMap::new(),
conditions: BTreeMap::new(),
commitments: BTreeMap::new(),
relationships: BTreeMap::new(),
pressures: BTreeMap::new(),
knowledge: BTreeMap::new(),
memories: BTreeMap::new(),
postures: BTreeMap::new(),
memberships: BTreeMap::new(),
population_lineages: BTreeMap::new(),
identities: BTreeMap::new(),
topology: BTreeMap::new(),
};
let initial_world_time = state.world_time;
store.create_component_world_state(&state).unwrap();
let permit = MutationPermit {
id: "permit:time".into(),
operation: WorldMutationOperation::AdvanceWorldTime,
subject_bindings: vec![MutationSubjectBinding {
role: MutationSubjectRole::Subject,
allowed_subjects: BTreeSet::from([campaign_subject.clone()]),
}],
string_constraints: BTreeMap::new(),
integer_bounds: BTreeMap::from([(
MutationIntegerRole::WorldMinutes,
IntegerBounds {
minimum: 30,
maximum: 30,
},
)]),
maximum_uses: 1,
};
let mut authority = MutationAuthorityEnvelope {
schema: "ghostlight.mutation_authority_envelope.v1".into(),
id: "authority:time".into(),
campaign_id,
world_revision: 7,
resolution_epoch: Some(3),
procedure: MutationProcedure::Governance,
source_subject: None,
outcome: MutationOutcomeBinding::Deterministic,
effect_ceiling: "Thirty minutes pass; no other component changes.".into(),
permits: vec![permit],
authority_receipt_ids: BTreeSet::from(["governance:time".into()]),
expires_at: Utc::now() + Duration::minutes(5),
digest: String::new(),
};
authority.digest = envelope_digest(&authority).unwrap();
let mut batch = WorldMutationBatch {
schema: "ghostlight.world_mutation_batch.v1".into(),
id: "batch:time".into(),
campaign_id,
expected_world_revision: 7,
expected_resolution_epoch: Some(3),
authority_envelope_digest: authority.digest.clone(),
source_receipt_id: "governance:time".into(),
means_digest: None,
intended_effect_digest: None,
mutations: vec![PermittedWorldMutation {
permit_id: "permit:time".into(),
mutation: WorldMutation::AdvanceWorldTime {
campaign: campaign_subject,
minutes: 30,
},
}],
digest: String::new(),
};
batch.digest = mutation_batch_digest(&batch).unwrap();
let kernel = WorldKernel::start(store.clone());
let committed = kernel
.commit_mutation_batch(authority.clone(), batch.clone())
.await
.unwrap();
let CommandResult::MutationCommitted { state, receipt } = committed else {
panic!("component mutation did not return its typed receipt");
};
assert_eq!(state.revision, 8);
assert_eq!(state.world_time, initial_world_time + Duration::minutes(30));
assert_eq!(receipt.previous_world_revision, 7);
assert_eq!(receipt.world_revision, 8);
assert_eq!(store.keys("world_mutation_receipt.v1").unwrap().len(), 1);
assert!(
kernel
.commit_mutation_batch(authority, batch)
.await
.is_err()
);
let stored = store
.load::<ComponentWorldState>("component_world_state.v1", &campaign_id.to_string())
.unwrap()
.unwrap()
.1;
assert_eq!(stored.revision, 8);
assert_eq!(store.keys("world_mutation_receipt.v1").unwrap().len(), 1);
}
fn hierarchical_refugee_campaign() -> Campaign {
let mut value = campaign();
value.locations.insert(

View file

@ -1,5 +1,6 @@
#![recursion_limit = "256"]
pub mod agency_corpus;
pub mod assessor;
pub mod compiler;
pub mod d20;
@ -19,6 +20,7 @@ pub mod resolution;
pub mod scheduler;
pub mod session_zero;
pub mod surface;
pub mod transition;
pub mod turn;
pub mod vault;
#[cfg(windows)]

View file

@ -4915,6 +4915,11 @@ fn player_command_projection(
"kind":"resolution_governance_pending",
"proposal":proposal,
}),
CommandResult::MutationCommitted { receipt, .. } => serde_json::json!({
"kind":"mutation_committed",
"revision":receipt.world_revision,
"receipt":receipt,
}),
}
}

View file

@ -20,6 +20,11 @@ use crate::{
SessionZeroMessage, SessionZeroState, TimeAdvanceProposal,
},
surface::{operator_surface, player_surface, player_surface_for_actor},
transition::{
ActionMeans, AgencyAttemptCase, ComponentWorldState, IdentityHandleState,
MutationAuthorityEnvelope, MutationIntent, MutationPermit, TypedSubject, WorldComponentRef,
WorldMutation, WorldMutationBatch, WorldMutationReceipt,
},
};
use anyhow::Result;
use chrono::Utc;
@ -631,7 +636,19 @@ fn schema_catalog() -> Value {
"ghostlight.extraordinary_permission.v1": schemars::schema_for!(ExtraordinaryPermission),
"ghostlight.time_advance_proposal.v1": schemars::schema_for!(TimeAdvanceProposal),
"ghostlight.group_travel_proposal.v1": schemars::schema_for!(GroupTravelProposal),
"ghostlight.cell_budget_proposal.v1": schemars::schema_for!(CellBudgetProposal)
"ghostlight.cell_budget_proposal.v1": schemars::schema_for!(CellBudgetProposal),
"ghostlight.typed_subject.v1": schemars::schema_for!(TypedSubject),
"ghostlight.world_component_ref.v1": schemars::schema_for!(WorldComponentRef),
"ghostlight.action_means.v1": schemars::schema_for!(ActionMeans),
"ghostlight.mutation_intent.v1": schemars::schema_for!(MutationIntent),
"ghostlight.mutation_permit.v1": schemars::schema_for!(MutationPermit),
"ghostlight.mutation_authority_envelope.v1": schemars::schema_for!(MutationAuthorityEnvelope),
"ghostlight.world_mutation.v1": schemars::schema_for!(WorldMutation),
"ghostlight.world_mutation_batch.v1": schemars::schema_for!(WorldMutationBatch),
"ghostlight.world_mutation_receipt.v1": schemars::schema_for!(WorldMutationReceipt),
"ghostlight.component_world_state.v1": schemars::schema_for!(ComponentWorldState),
"ghostlight.identity_handle.v1": schemars::schema_for!(IdentityHandleState),
"ghostlight.agency_attempt_case.v1": schemars::schema_for!(AgencyAttemptCase)
});
let schemas = catalog
.as_object_mut()

View file

@ -6,6 +6,9 @@ use crate::domain::{
use crate::session_zero::{
CellBudgetProposal, GroupTravelProposal, PublishedSessionZeroSeed, TimeAdvanceProposal,
};
use crate::transition::{
ComponentWorldState, MutationAuthorityEnvelope, WorldMutationBatch, WorldMutationReceipt,
};
use anyhow::{Context, Result, anyhow};
use chrono::Utc;
use cultcache_legacy::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
@ -81,6 +84,74 @@ impl CampaignStore {
Ok(row)
}
pub fn create_component_world_state(
&self,
state: &ComponentWorldState,
) -> Result<CultCacheEnvelope> {
self.insert(
"component_world_state.v1",
"ghostlight.component_world_state.v1",
&state.campaign_id.to_string(),
state,
)
}
pub fn commit_world_mutation_batch(
&self,
expected: &CultCacheEnvelope,
next: &ComponentWorldState,
authority: &MutationAuthorityEnvelope,
batch: &WorldMutationBatch,
receipt: &WorldMutationReceipt,
) -> Result<CultCacheEnvelope> {
if expected.r#type != "component_world_state.v1"
|| expected.key != next.campaign_id.to_string()
|| authority.campaign_id != next.campaign_id
|| batch.campaign_id != next.campaign_id
|| receipt.campaign_id != next.campaign_id
|| receipt.world_revision != next.revision
|| receipt.previous_world_revision.saturating_add(1) != next.revision
|| receipt.batch_digest != batch.digest
|| receipt.authority_envelope_digest != authority.digest
{
return Err(anyhow!("world mutation persistence bundle is inconsistent"));
}
let next_row = envelope(
"component_world_state.v1",
"ghostlight.component_world_state.v1",
&next.campaign_id.to_string(),
next,
)?;
let rows = vec![
next_row.clone(),
envelope(
"mutation_authority_envelope.v1",
"ghostlight.mutation_authority_envelope.v1",
&authority.id,
authority,
)?,
envelope(
"world_mutation_batch.v1",
"ghostlight.world_mutation_batch.v1",
&batch.id,
batch,
)?,
envelope(
"world_mutation_receipt.v1",
"ghostlight.world_mutation_receipt.v1",
&receipt.id,
receipt,
)?,
];
if !self
.inner
.compare_and_swap_batch(std::slice::from_ref(expected), rows)?
{
return Err(anyhow!("stale component world snapshot"));
}
Ok(next_row)
}
pub fn create_campaign(
&self,
campaign: &Campaign,

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,481 @@
# Ghostlight World Transition Algebra
Status: adopted architecture; production migration is incomplete until the
legacy effect writers named below are deleted.
## Objective
Ghostlight needs one physical world. A player action, an NPC reaction, a
strategic institution, and a low-resolution Gestalt cell may use different
admission and resolution procedures, but a successful outcome must change the
same canonical components through the same kernel-owned commit primitive.
The transition algebra exists so that:
- freeform action remains possible without model-authored structural writes;
- impossible actions are absent from the available operation space;
- every committed change has exact subjects, authority, provenance, and
version bindings;
- foreground and background simulation cannot acquire asymmetric powers;
- new play scenarios compose existing semantic mutations instead of growing a
bespoke effect enum for every story beat.
This design adapts the useful core of action-language and planning literature:
states are typed assignments, actions have explicit applicability conditions,
and transitions have bounded effects. It does not adopt PDDL, STRIPS, or a
general logic-programming runtime as Ghostlight's public ontology. BC+ provides
the causal-law distinction, STRIPS and PDDL provide the precondition/effect
discipline, and REBA provides the important reminder that coarse and fine
simulation must refine the same transition system rather than inventing two
worlds. See [BC+](https://academic.oup.com/logcom/article/30/4/899/2917837),
[PDDL2.1](https://arxiv.org/abs/1106.4561), and
[REBA](https://arxiv.org/abs/1508.03891).
## Authority map
### Owner
The per-campaign `WorldKernel` owns one `WorldMutationBatch` validation and
commit primitive. It is the only subsystem allowed to change canonical world
components or advance fictional time.
### Inputs
The owner may read:
- the exact canonical campaign revision;
- the exact resolution epoch when a strategic wave is involved;
- typed subjects and their component versions;
- an accepted action, reaction, lifecycle, governance, or strategic-outcome
receipt;
- a digest-bound `MutationAuthorityEnvelope` compiled from current state;
- a proposed batch containing only semantic mutations named by that envelope;
- exact evidence, permission, roll, and model-stage receipts required by the
originating procedure.
### Outputs
One successful commit produces, atomically:
- the next canonical component state;
- append-only world events describing the observable means and outcome;
- a private exact `world_mutation_receipt.v1`;
- the command or strategic receipt that caused the transition;
- any knowledge-channel-aware news inputs derivable from committed events.
Eve, CultMesh, narration, and news projections refresh only after the commit.
### Derived and demoted state
- `WorldEffectDelta`, `ActorStateDelta`, `StrategicCellEffect`, and
`StrategicOutcomeEffect` are requirements evidence and migration inputs. They
are no longer allowed to own a production write after their resolver moves.
- `StrategicActivityKind` describes proposed means. It is not a mutation.
- An `ActionIntent` and its intended effect are proposals. They are not facts
and do not become true because a model narrated them.
- Simulation cells, covers, leases, salience, and detail debt choose inference
resolution. They are not fictional world components.
- Transcript prose and narration are projections over committed events. They
do not repair or create state.
- Actor equipment lists, institution resource lists, and Gestalt resource sets
become projections over resource subjects plus custody. A resource does not
change ontology when its owner changes.
- A dormant named Gestalt member and its materialized foreground form are one
actor subject. Materialization changes simulation resolution, not identity or
physical existence.
### Forbidden writers
The migration is not complete while any of these can decide canonical state:
- `apply_world_effect`;
- `apply_strategic_outcome_effect`;
- the direct private-delta loop in `ResolveReactionWave`;
- bespoke actor, Gestalt, or member movement and migration writers;
- Gestalt folding code that unions private knowledge or possessions into a
population without an admitted mutation;
- model output, browser payloads, narration, news generation, retrieval, or a
derived simulation cell.
Administrative world creation, compiler publication, and approval-gated
population fission must ultimately lower to the same batch primitive. They may
possess broader authority envelopes, but not another state-writing mechanism.
### Shared paths
All of these lower to `WorldMutationBatch` before state changes:
- player `Attempt` confirmation;
- NPC initiative resolution;
- actor reactions and private appraisal consequences;
- strategic individual, institution, cohesive Gestalt, and arena-constituent
outcomes;
- travel, waits, and strategic time advancement;
- resource production, use, damage, repair, and exchange;
- named-person joining, leaving, and migrating between populations;
- population migration and approval-gated fission;
- contract amendments that are permitted to change forward-looking world
state;
- compiler-admitted entities and later bounded region expansion.
### Cut line
The new validator applies a whole batch to an isolated transactional overlay,
checks local and cross-mutation invariants, and returns either one complete next
state or an error. Resolvers then emit the new mutation vocabulary directly.
When the last production caller moves, the old committing functions and their
model schemas are deleted. Persisted legacy receipts remain readable history;
they never re-enter a commit path.
No repair loop, converter with independent policy, or post-commit reconciler is
allowed to preserve a second opinion about the result.
## Canonical state model
### Subjects
Every durable entity has a stable typed `SubjectRef`:
| Subject kind | Examples | Important rule |
| --- | --- | --- |
| `actor` | player, NPC, named refugee | Identity survives foreground materialization and Gestalt folding. |
| `population` | villagers, refugee convoy, corporation workforce | May own a cohesive Gestalt Persona baseline; never owns member secrets by implication. |
| `institution` | Zhestokost command, a clinic, a guild | Collective authority is explicit, not inferred from proximity. |
| `place` | room, settlement, route node, region | Persists independently of current observation. |
| `resource` | a key, medicine lot, ship, credits tranche | Has exact custody and resource state; it is not a string copied between owner lists. |
| `pressure` | blockade clock, debt deadline, epidemic load | Carries bounded progress and consequence semantics. |
| `proposition` | a source-grounded fact, a witnessed claim, a branch-local finding | Knowledge points to the proposition; prose duplication is not knowledge authority. |
| `channel` | courier route, broadcast, private conversation | Governs who can receive information without making it public. |
Campaign time is a component of the campaign root. Relationships and topology
edges are keyed component records between subjects, not synthetic actors.
IDs are opaque and stable. Prefixes may remain a debugging convention, but no
validator infers subject kind or authority from string shape.
### Components
The target store is component-oriented even when a compatibility migration
temporarily reads old aggregate rows:
- `identity`: canonical identity plus adopted handles and their disclosure
state;
- `occupancy`: exact place anchors and travel state;
- `custody`: exact custodian of a resource or controlled subject;
- `resource_state`: type, quantity, integrity, qualities, and lifecycle;
- `capability`: supported abilities and their limits;
- `condition`: bodily, material, social, or environmental state;
- `knowledge`: proposition, epistemic status, source, channel, and revision;
- `memory`: private episodic record and provenance;
- `relationship`: directed subject-to-subject state;
- `commitment`: goals and obligations, including creditor or beneficiary;
- `pressure`: bounded progress, threshold, consequence, and status;
- `posture`: an agentive subject's current strategic stance;
- `population_membership`: exact member, population, role, and interval;
- `population_lineage`: refinement, fission, merge, and remainder ancestry;
- `topology`: containment and route edges with travel cost and availability;
- `lifecycle`: admitted, active, transformed, consumed, retired;
- `world_time`: the campaign's monotonic fictional coordinate.
Components are sparse. A place does not need knowledge; a proposition does not
need occupancy. Component applicability is determined by subject kind and the
specific admitted entity, not by a universal bag of optional fields.
## The mutation vocabulary
`WorldMutation` is a closed tagged union. Each variant owns one semantic
component family and names the invariants that family can enforce. There is no
`SetField`, arbitrary path, embedded patch, or model-authored component name.
| Mutation | Canonical effect | Essential validation |
| --- | --- | --- |
| `Relocate` | Changes occupancy for an exact subject. | Origin matches, route/reach exists, mover has authority, group custody and travel approval hold. |
| `TransferCustody` | Moves an exact resource between custodians. | Source has custody, recipient exists and can receive it, quantity/identity is conserved. |
| `MutateResource` | Creates, transforms, consumes, damages, repairs, splits, or combines exact resources. | Recipe/capability, custody, conservation, lifecycle, quantity, and effect ceiling hold. |
| `ChangeCapability` | Grants, alters, suspends, or retires a supported capability. | Source of capability and duration are admitted; no narration-only expertise. |
| `ChangeCondition` | Applies, alters, or clears a condition. | Target is reachable, condition is compatible, opposition and outcome band permit it. |
| `ChangeCommitment` | Creates, alters, fulfills, defaults, or retires a goal or obligation. | Exact owner, counterparty, consent or coercive authority, and lifecycle hold. |
| `ChangeRelationship` | Creates, alters, or retires a directed relationship component. | Exact endpoints exist; one actor cannot author another's private appraisal without its own reaction authority. |
| `ChangePressure` | Creates, advances, reduces, resolves, or retires a bounded pressure. | Owner, bounds, current value, threshold, and consequence are exact. |
| `ChangeKnowledge` | Acquires, communicates, conceals, corrects, or invalidates a proposition for exact knowers. | Source knows or can observe it, channel and recipients are exact, concealment does not erase another mind. |
| `ChangeMemory` | Records, revises, or retires an exact private episodic memory. | Witness or authorized private appraisal exists; another actor cannot write it. |
| `ChangePosture` | Alters the posture of an exact agentive subject. | The acting authority can speak or decide for that subject; arenas cannot use it collectively. |
| `ChangePopulationMembership` | Joins, leaves, or transfers an exact actor between populations. | Member identity is stable, source membership exists, destination is compatible, no duplicate coverage. |
| `ChangePopulationLineage` | Records an admitted split, merge, or remainder relation. | Fission preview and approval exist; leaves remain non-overlapping and complete. |
| `ChangeIdentity` | Adopts, discloses, restricts, or retires an exact identity handle. | Self-authority or explicit custody exists; disclosure is separate from renaming. |
| `ChangeTopology` | Adds, alters, opens, closes, or retires a containment or route edge. | Evidence/branch admission, endpoint existence, reciprocal rules, and geometry invariants hold. |
| `AdmitEntity` | Creates an explicitly permitted non-resource subject and initial components. | Admission class, evidence or branch-local authority, collision freedom, and required components hold. |
| `RetireEntity` | Retires an exact subject without erasing history. | No dangling custody, occupancy, membership, topology, or active obligation remains. |
| `AdvanceWorldTime` | Advances campaign time by an exact duration. | Monotonicity, governance, no-puppeting, tick budget, and scheduled obligations hold. |
`NoMaterialChange` is not a mutation. It is an outcome with an empty mutation
batch and an explicit explanation. Speech is an event in the means record;
persuasion, obligation, relationship, and knowledge consequences are separate
mutations.
Complex effects are batches, not new verbs. Giving half a medicine lot to a
clinic composes resource split, custody transfer, and perhaps an obligation.
Evacuating a named refugee composes relocation, population-membership transfer,
and accessible knowledge. Population fission composes entity admission,
lineage, and exact member transfers while preserving an `other/unknown`
remainder.
## Means, intended effect, and committed mutation
### Means
`ActionMeans` records what is attempted and may become observable:
- exact acting subject;
- bounded natural-language method;
- exact targets, instruments, resources, places, routes, and channels cited
from the actor's permitted slice;
- explicit speech, if any;
- state and evidence references supporting the method.
The means taxonomy is intentionally open at the prose level. Ghostlight does
not need a rulebook verb for every clever action. The exact typed references
make reach, custody, knowledge, and capability testable.
### Intended effect
`MutationIntent` names desired component families, targets, and qualitative
direction. It is useful for assessment and cognitive focus, but it is not an
assertion that the change occurred. A player may intend to persuade a guard,
destroy a reactor, learn a route, or move a crowd without receiving any of
those mutations.
### Committed mutation
The admitted outcome procedure emits a concrete `WorldMutationBatch` bounded
by its authority envelope. The batch is the only one of the three objects that
can become state. A roll changes which digest-bound outcome plan is eligible;
it does not allow the resolver to invent a stronger mutation afterward.
For Sable's self-presentation:
- means: the refugee speaks an exact self-presentation to present listeners;
- intended effect: those listeners may address this person using `Sable`;
- committed mutations: `ChangeIdentity::AdoptHandle` only if the speaker is
choosing a new handle, followed by `ChangeIdentity::DiscloseHandle` or
`ChangeKnowledge::Communicate` to exact listeners;
- derived projection: each listener's Eve surface displays the best identity
handle that listener actually knows.
The speech never authorizes a global actor rename, and a display label never
becomes identity authority.
## Mutation authority envelopes
An admission policy compiles `mutation_authority_envelope.v1` from the current
snapshot. It contains exact permits, not broad roles:
- campaign revision and relevant component versions;
- originating subject and resolution procedure;
- permitted mutation kind and operation;
- exact subjects, routes, resources, propositions, channels, and relationships
available to that operation;
- numeric and cardinality bounds;
- extraordinary-permission or approval receipts;
- effect ceiling and outcome-band binding;
- expiry and digest.
The envelope is capability-like but not transferable. It can authorize one
assessment outcome, one reaction appraisal, one strategic action, or one
administrative command. It cannot be rebased onto a new revision.
### Action-specific model schemas
The model never receives the complete world mutation schema. Ghostlight first
selects the component families relevant to the intended effect, then generates
a compact schema from the exact permits:
- if no resource is transferable, no custody-transfer branch exists;
- if the actor cannot reach a target, that target does not appear;
- if the actor knows no communicable proposition, communication is absent;
- if an arena has no collective actor, collective posture and speech are
absent;
- if the outcome cannot create an entity, admission is absent;
- scalar fields carry local limits rather than universal ranges.
Each generated branch carries an opaque permit ID. The kernel resolves that ID
back to the exact permit and revalidates it against the snapshot. Stable
instructions and mutation definitions precede the dynamic permit table so
provider caching remains useful; the dynamic prompt contains only the state
needed for this decision.
Schema generation improves model ergonomics. It does not replace local
validation, and schema presence is not authority by itself.
## Validation and atomic commit
The commit primitive performs this sequence:
1. Verify campaign revision, resolution epoch when present, originating receipt,
envelope digest, expiry, and idempotency.
2. Resolve every subject and component against the same snapshot.
3. Verify every mutation has a matching unused permit and remains inside its
exact IDs, operations, bounds, and effect ceiling.
4. Validate local semantics: reach, custody, knowledge provenance, authority,
component applicability, and lifecycle.
5. Validate batch semantics: no contradictory writes, no resource duplication,
no dangling entity retirement, no duplicate population membership, and no
hidden cross-actor private writes.
6. Apply the entire batch to an isolated in-memory overlay.
7. Re-run global topology, custody, population coverage, player-control,
knowledge, and temporal invariants on the overlay.
8. Persist component rows, events, mutation receipt, command receipt, and
required private proof records in one CultCache transaction.
9. Publish refreshed Eve/CultMesh projections after the transaction commits.
Any error returns the original state byte-for-byte. A malformed model output
gets one same-snapshot correction and then aborts. No valid sibling mutation
survives an invalid batch member.
## Admission policies are separate from physics
The shared algebra does not make every actor equally powerful. Each lane has a
different authority compiler:
- foreground fiction-first d20 assessment considers declared means, local
affordances, opposition, permissions, stakes, and effect ceiling;
- reaction appraisal can write only the reacting subject's private components
plus exact speech/action proposals;
- NPC initiative uses the same foreground assessment after initiative chooses
an eligible proposal;
- strategic cells use horizon, graph reach, institutional authority, resources,
and resolution-cell attribution;
- cohesive Gestalts may receive collective permits only from real collective
authority;
- arena cells receive constituent permits and cannot emit one arena-owned
mutation;
- compiler and approval commands may admit entities or topology only through
explicit evidence and branch-local gap policy.
Different admission does not imply different mutations. A player and an
institution transferring the same medicine use the same custody mutation.
## Migration from the empirical vocabularies
The accumulated variants are test requirements, not discarded knowledge:
| Existing behavior | Algebraic lowering |
| --- | --- |
| actor move / member migration / Gestalt migration | `Relocate` plus membership change when population affiliation changes |
| actor equipment / institution resources / Gestalt resources / member equipment | resource subjects plus `TransferCustody` and `MutateResource` |
| actor or member condition | `ChangeCondition` |
| actor goal / member obligation | `ChangeCommitment` |
| actor or member relationship | `ChangeRelationship` |
| world clock and Gestalt pressure | pressure subjects plus `ChangePressure` |
| actor knowledge / Gestalt shared knowledge / member knowledge | `ChangeKnowledge` with exact proposition and knower |
| member memory / reaction memory | `ChangeMemory` |
| institution posture / strategic posture | `ChangePosture` |
| Gestalt promotion and folding | resolution change over one stable actor plus explicit component mutations only |
Migration order:
1. Publish types, component applicability, permits, batch validation, receipts,
and property tests without changing live state.
2. Lower foreground assessment and NPC resolution directly to mutation batches;
delete `apply_world_effect`.
3. Lower reaction Interpreters to actor-private permits and mutation batches;
delete direct `ActorStateDelta` writes.
4. Lower strategic outcome generation to the same operations; delete
`apply_strategic_outcome_effect` and string-resource helpers.
5. Normalize named Gestalt members into stable actor subjects and resource,
membership, identity, and occupancy components. Remove materialized actor as
a second identity owner.
6. Lower travel, waits, fission, expansion, and compiler publication.
7. Migrate persisted campaign rows transactionally, quarantine ambiguous legacy
resources or identities, and make the old campaign fields projection-only.
8. Remove legacy schemas from model boundaries. Retain schema readers solely
for historical receipt inspection.
At every stage, the old and new writers cannot both be active for the migrated
lane.
## Agency corpus
Ghostlight does not declare the algebra complete from enum aesthetics. It owns
an inspectable `agency_attempt_case.v1` corpus compiled into a MessagePack
CultCache store. JSON Schema publishes the record shape; authored source may be
reviewed Markdown, but runtime and test fixtures load `.cc`.
Each case records:
- domain and scenario;
- minimal world fixture and exact subjects;
- means and intended effect;
- expected admission: admissible, impossible, or bargain-required;
- required mutation composition by outcome band;
- forbidden mutations and invariant witnesses;
- expected bargains for missing permission or affordance;
- whether foreground, NPC, strategic, and Gestalt resolutions should be
physically equivalent;
- reviewer status and any genuinely missing primitive.
The initial target is at least 300 reviewed attempts: 25 each across social,
physical, investigative, economic, political, technological, extraordinary or
magical, collective, identity and privacy, population and migration,
infrastructure and logistics, and bodily or medical play. Cases include both
ordinary and adversarial attempts, partial successes, indirect means, consent
boundaries, rival actors inside arenas, and low-resolution background outcomes.
Completeness gates:
- every case maps compositionally, yields a comprehensible bargain, or names a
genuinely missing primitive;
- no case falls through to a generic patch or arbitrary component write;
- the same physical change uses the same mutation in foreground, NPC, member,
population, institution, and arena-constituent contexts;
- property tests prove atomicity, deterministic permit/schema generation,
resource conservation, stable identity, exact knowledge ownership, population
coverage, topology integrity, and no puppeting;
- the final 100 newly reviewed admissible cases require no new primitive. This
is a stability signal, not a mathematical proof of completeness.
The Sable self-presentation and later rematerialization is a mandatory first
case. It must prove observer-relative identity projection without a global
rename or loss across Gestalt folding.
## Public contracts
Add:
- `typed_subject.v1`
- `world_component_ref.v1`
- `action_means.v1`
- `mutation_intent.v1`
- `mutation_permit.v1`
- `mutation_authority_envelope.v1`
- `world_mutation.v1`
- `world_mutation_batch.v1`
- `world_mutation_receipt.v1`
- `agency_attempt_case.v1`
JSON Schema is the catalog boundary. Canonical component rows, envelopes,
batches, receipts, and corpus fixtures use MessagePack-backed CultCache `.cc`.
JSON remains acceptable only at browser, MCP, and model-provider boundaries.
## Acceptance
The algebra cut is complete only when:
- no production path calls a legacy effect writer;
- every effectful command persists an exact mutation receipt;
- malformed, stale, over-broad, contradictory, or partially valid batches leave
state, fictional time, and projections unchanged;
- background and foreground versions of the same action pass the same component
invariants;
- arena rivals cannot speak or mutate as one subject and cannot acquire one
another's knowledge;
- resource custody and quantity are conserved across transfers and failures;
- named people remain the same subjects through Gestalt merge, split, migration,
folding, and rematerialization;
- Sable's disclosed handle appears only to entitled observers and survives the
complete round trip;
- action-specific schemas omit impossible operations before inference;
- the agency corpus meets its coverage and stability gates;
- adversarial play through the typed Eve surface still proves the homepage
promises after migration.