From 0f21a4900c1adbdc93943d73ae9f0ba4aca624da Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 4 Sep 2026 20:36:56 +0200 Subject: [PATCH] Soul: falsify pass-4 bands, the shared catalog id, and journal-side forgery Four test-only additions, plus one two-slot fixture entry: - `soul_only_the_selected_bands_effects_are_committed` closes verification contract 10's discriminating case. The existing tests prove an empty band commits nothing and a one-slot entry lowers what it declares; neither separates a slot the proposer offered from a slot the draw admitted. The new `carry_split` entry declares two slots on disjoint bands, both proposed within ceiling, and each band is reached by searching for a command id before the envelope is built rather than by retrying commits. - `soul_a_forged_band_or_effect_in_the_journal_dies_at_replay` names the layer. `verify_state_shape` bounds a band index and refuses effects under an empty band; it does not re-derive the draw. The forgery is re-digested into a contiguous chain and dies at `apply_committed_command`'s effect equality. - `soul_a_shared_catalog_id_is_gated_by_the_scope_grant` pins that an affordance id names a catalog entry every grantee shares, so grant membership per scope is what gates: the same `convene` id commits for its grantee and is denied for a controller-driven scope that does not hold it. - `soul_a_stored_role_spec_over_an_optional_subject_kind_round_trips` proves the adjacently tagged `RefKind` survives the `to_vec_named` path that a stored `RoleSpec { kind: Subject(None) }` writes through. Co-Authored-By: Claude Fable 5.1 --- crates/ghostlight-dungeon/src/world/action.rs | 147 +++++++++++++++ .../ghostlight-dungeon/src/world/journal.rs | 108 +++++++++++ crates/ghostlight-dungeon/src/world/mod.rs | 168 ++++++++++++++++-- 3 files changed, 405 insertions(+), 18 deletions(-) diff --git a/crates/ghostlight-dungeon/src/world/action.rs b/crates/ghostlight-dungeon/src/world/action.rs index db4faf9..0a057cc 100644 --- a/crates/ghostlight-dungeon/src/world/action.rs +++ b/crates/ghostlight-dungeon/src/world/action.rs @@ -1022,6 +1022,153 @@ mod tests { ); } + /// Soul: contract 10's discriminating case. `a_zero_effect_band_commits_ + /// nothing_but_the_event` proves an empty band commits nothing, and + /// `a_committed_event_carries_the_exact_lowered_operations` proves a + /// one-slot entry lowers what it declares — neither separates a slot the + /// proposer offered from a slot the draw admitted. This entry declares two + /// slots on disjoint bands and proposes both within their ceilings: only + /// the drawn band's slot may appear in `event.effects`, and the other slot + /// must move no partition. Both bands are exercised, so neither branch + /// passes by never being taken. + #[test] + fn soul_only_the_selected_bands_effects_are_committed() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = bench(directory.path(), "SelectedBand"); + let split_id = affordance_named(&bench.active, "carry_split"); + let split = DecisionInvocation { + affordance: split_id, + bindings: vec![ + binding("from", Target::Subject(bench.clerk)), + binding("recipient", Target::Subject(bench.keeper)), + binding("place", Target::Entity(bench.yard)), + binding("resource", Target::Entity(bench.tithe)), + ], + proposed: vec![ + ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(2)), + }, + ProposedEffect { + slot: 1, + magnitude: Magnitude::Quantity(Quantity(1)), + }, + ], + speech: None, + }; + let mut seen: BTreeSet = BTreeSet::new(); + + for wanted in [0usize, 1] { + // The draw is a pure function of the pre-commit revision and the + // command id, so the command id that reaches a band is findable + // before the envelope is built rather than hunted by retrying. + let opportunity = bench.clerk_opportunity(); + let command_id = (0..256) + .map(|_| CommandId::issue()) + .find(|candidate| { + exercise(&bench.kernel.state, *candidate, &opportunity, &split) + .expect("the invocation is admissible") + .band + == wanted + }) + .expect("a two-band entry reaches both bands over 256 command ids"); + + let before_clerk = bench.held(bench.clerk); + let before_keeper = bench.held(bench.keeper); + let caller = CallerId::Controller(opportunity.controller_id); + let receipt = bench + .kernel + .submit( + command( + &bench.active, + command_id, + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation: split.clone(), + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .expect("the invocation commits"); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + bench.refresh(); + let event = bench + .kernel + .state + .events + .last() + .expect("the committed event") + .clone(); + assert_eq!(event.band, wanted); + seen.insert(event.band); + match event.band { + 0 => { + assert_eq!( + event.effects, + vec![ResolvedOp::Transfer { + from: bench.clerk, + to: bench.keeper, + resource: bench.tithe, + qty: Quantity(2), + }] + ); + assert_eq!(bench.held(bench.clerk), before_clerk - 2); + assert_eq!(bench.held(bench.keeper), before_keeper + 2); + } + 1 => { + assert_eq!( + event.effects, + vec![ResolvedOp::Consume { + holder: bench.clerk, + resource: bench.tithe, + qty: Quantity(1), + }] + ); + assert_eq!(bench.held(bench.clerk), before_clerk - 1); + assert_eq!(bench.held(bench.keeper), before_keeper); + } + other => panic!("the entry declares two bands, drew {other}"), + } + } + + assert_eq!( + seen.len(), + 2, + "both declared bands must be reachable across command ids" + ); + } + + /// Soul: `RoleSpec` persists inside the catalog, so `RefKind` had to become + /// serializable this pass. An internally tagged newtype over an `Option` + /// does not serialize; this one is adjacently tagged, and a stored + /// `Subject(None)` role is what would fault on first write if that were + /// wrong. The fixture catalog carries four such roles. + #[test] + fn soul_a_stored_role_spec_over_an_optional_subject_kind_round_trips() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "OptionalSubjectKind"); + let entry = bench + .kernel + .state + .affordance_catalog + .get(&bench.carry) + .expect("the fixture entry"); + assert!( + entry + .roles + .iter() + .any(|spec| spec.kind == RefKind::Subject(None)) + ); + + // The state row encoder and the digest owner are the same `to_vec_named` + // path the store writes through. + let encoded = rmp_serde::to_vec_named(&bench.kernel.state).expect("the state encodes"); + let decoded: WorldState = rmp_serde::from_slice(&encoded).expect("the state decodes"); + assert_eq!(decoded.affordance_catalog, bench.kernel.state.affordance_catalog); + assert!(digest(&bench.kernel.state).is_ok()); + } + #[test] fn a_forged_band_or_forged_effect_does_not_apply() { let directory = tempfile::tempdir().unwrap(); diff --git a/crates/ghostlight-dungeon/src/world/journal.rs b/crates/ghostlight-dungeon/src/world/journal.rs index 3736584..c1e2d5a 100644 --- a/crates/ghostlight-dungeon/src/world/journal.rs +++ b/crates/ghostlight-dungeon/src/world/journal.rs @@ -958,6 +958,114 @@ mod tests { )); } + /// Soul: `a_forged_band_or_forged_effect_does_not_apply` proves the live + /// `apply_effect` arm re-derives. `verify_state_shape` does not re-derive a + /// band — it only bounds the index and refuses effects under an empty band — + /// so the layer that kills a persisted forgery is replay effect-equality. + /// This forges a committed decision inside the journal, re-digests it into a + /// contiguous chain, and asserts recovery refuses it. + #[test] + fn soul_a_forged_band_or_effect_in_the_journal_dies_at_replay() { + use crate::world::tests::{ + activate, admit_custody, admit_topology, affordance_named, auth_principal, command, + opportunity_for, owner, + }; + use crate::world::{ + AuthenticatedCaller, DecisionInvocation, Magnitude, ProposedEffect, Quantity, + RoleBinding, Target, + }; + + let forge = |kind: &str, mutate: &dyn Fn(&mut crate::world::DecisionEvent)| { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create( + &path, + crate::world::tests::creation(CommandId::new(), "ForgedDecision"), + &authenticated, + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + let active = activate(&mut kernel); + let entry = affordance_named(&active, kind); + let opportunity = opportunity_for(&active, custody.holder); + let caller = CallerId::Controller(opportunity.controller_id); + let command_id = CommandId::new(); + let role = |name: &str, target| RoleBinding { + role: crate::world::Role(name.into()), + target, + }; + kernel + .submit( + command( + &active, + command_id, + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation: DecisionInvocation { + affordance: entry, + 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, + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap(); + + // The honest journal recovers. + assert!(verify_history(&kernel.state, &kernel.journal.commits).is_ok()); + + let mut forged_head = kernel.state.clone(); + let mut forged_commits = kernel.journal.commits.clone(); + let forged = forged_commits.get_mut(&command_id).unwrap(); + let WorldEffect::DecisionExercised { event, .. } = &mut forged.effect else { + panic!("expected an exercised decision effect"); + }; + mutate(event); + let forged_event = event.clone(); + *forged_head.events.last_mut().unwrap() = forged_event; + forged.digest = commit_digest(forged).unwrap(); + forged_head.last_commit_digest = Some(forged.digest.clone()); + forged_head.state_digest = String::new(); + forged_head.state_digest = crate::world::state_digest(&forged_head).unwrap(); + (forged_head, forged_commits) + }; + + // A band the seed did not draw, held inside a chain that verifies. + let (head, commits) = forge("carry_chance", &|event| { + event.band = (event.band + 1) % 3; + }); + assert!(matches!( + verify_history(&head, &commits), + Err(JournalError::Corrupt(_)) + )); + + // A magnitude the ceiling admitted but the lowering never produced. + let (head, commits) = forge("carry", &|event| { + let Some(crate::world::ResolvedOp::Transfer { qty, .. }) = event.effects.first_mut() + else { + panic!("expected a lowered transfer"); + }; + *qty = Quantity(1); + }); + assert!(matches!( + verify_history(&head, &commits), + Err(JournalError::Corrupt(_)) + )); + } + #[test] fn replay_rejects_genesis_that_does_not_derive_from_its_creation_command() { let directory = tempfile::tempdir().unwrap(); diff --git a/crates/ghostlight-dungeon/src/world/mod.rs b/crates/ghostlight-dungeon/src/world/mod.rs index f0cdae1..b5193a4 100644 --- a/crates/ghostlight-dungeon/src/world/mod.rs +++ b/crates/ghostlight-dungeon/src/world/mod.rs @@ -2429,6 +2429,66 @@ mod tests { /// 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_roles() -> Vec { + 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), + }, + ] + } + + /// Two slots on disjoint bands: band 0 names only the transfer, band 1 only + /// the consume. Both slots are proposed on every invocation, so the entry + /// separates what a proposer offered from what a draw admitted. + fn split_variant() -> Declaration { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("carry-split"), + kind: AffordanceKindName("carry_split".into()), + roles: carry_roles(), + preconditions: Vec::new(), + effect_slots: vec![ + EffectSlot { + op_kind: ComponentOpKind::Transfer, + roles: vec![ + Role("from".into()), + Role("recipient".into()), + Role("resource".into()), + ], + bounds: Bounds::Quantity(Quantity(3)), + }, + EffectSlot { + op_kind: ComponentOpKind::Consume, + roles: vec![Role("from".into()), Role("resource".into())], + bounds: Bounds::Quantity(Quantity(3)), + }, + ], + outcome_bands: vec![ + OutcomeBand { + weight: 1, + effects: vec![0], + }, + OutcomeBand { + weight: 1, + effects: vec![1], + }, + ], + carries_speech: false, + }) + } + fn carry_variant( handle: &str, kind: &str, @@ -2438,24 +2498,7 @@ mod tests { 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), - }, - ], + roles: carry_roles(), preconditions, effect_slots: vec![EffectSlot { op_kind: ComponentOpKind::Transfer, @@ -2566,6 +2609,7 @@ mod tests { }, ], ), + split_variant(), ] } @@ -3878,6 +3922,94 @@ mod tests { assert_eq!(kernel.snapshot().unwrap(), active); } + /// Soul: an `AffordanceId` now names a catalog entry, not a subject's copy + /// of one — the three genesis subjects share Speak's single id. So the id + /// cannot be what gates: grant membership for the invoking scope is. The + /// same `convene` id commits for the scope that holds it and is denied for + /// one that does not. + #[test] + fn soul_a_shared_catalog_id_is_gated_by_the_scope_grant() { + let dir = tempfile::tempdir().unwrap(); + let (mut kernel, _) = WorldKernel::create( + dir.path().join("world.cc"), + creation(CommandId::new(), "SharedCatalogIds"), + &auth_principal(owner()), + ) + .unwrap(); + let active = activate(&mut kernel); + let speak = affordance_named(&active, "speak"); + let convened = affordance_named(&active, "convene"); + + // One entry, one id, every genesis subject a grantee. + assert_eq!(active.subjects.len(), 3); + assert!( + active + .subjects + .iter() + .all(|subject| subject.affordances.contains(&speak)) + ); + assert!( + active + .opportunities + .iter() + .all(|opportunity| opportunity.affordance_ids.contains(&speak)) + ); + let holders: Vec = active + .subjects + .iter() + .filter(|subject| subject.affordances.contains(&convened)) + .map(|subject| subject.id) + .collect(); + assert_eq!(holders.len(), 1); + + let invoke = |kernel: &mut WorldKernel, snapshot: &WorldSnapshot, subject: SubjectId| { + let opportunity = opportunity_for(snapshot, subject); + let caller = CallerId::Controller(opportunity.controller_id); + kernel.submit( + command( + snapshot, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation: DecisionInvocation { + affordance: convened, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Utterance::new("The council convenes.").unwrap()), + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + }; + + // The grantee's scope commits with that id. + assert!(matches!( + invoke(&mut kernel, &active, holders[0]).unwrap(), + SubmitReceipt::Applied(_) + )); + + // A scope that does not hold the entry is denied the very same id, and + // nothing commits. + let after = kernel.snapshot().unwrap(); + // A controller-driven scope, so the denial is the grant check rather + // than the human lane's caller check reached first. + let stranger = after + .subjects + .iter() + .find(|subject| { + !subject.affordances.contains(&convened) && subject.human_controller.is_none() + }) + .expect("a controller-driven subject without the grant") + .id; + assert!(matches!( + invoke(&mut kernel, &after, stranger).unwrap_err(), + KernelError::AffordanceDenied + )); + assert_eq!(kernel.snapshot().unwrap(), after); + } + #[test] fn a_stale_grant_rejects_but_a_distant_route_reaches_admission_instead() { let dir = tempfile::tempdir().unwrap();