Aetherlight AL2b-2a: after genesis only Play writes; worlds are born Active

CallerId is { Principal, Play }; one require_play gate at the top of reduce and
apply_effect replaces the capability table, the owner's post-genesis doors and
the Clock capability. The consumer lane (ConsumerId, PatchGround, mirrors,
confine_to_ground, operation_ground), the draft phase and approvals,
VerifiedPrincipalEvidence, the dead intents and the never-mute and Retire-side
refusals are deleted. GrantsOutsideControl becomes GrantsToRetired; a grant row
exists iff the subject holds a verb. require_ruler is genesis-only
(forbid_rulings_at_genesis). Schema consumer.v9. Tests of deleted lanes are
deleted, the rest go through submit_play.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
soul 2026-11-20 00:22:36 +01:00
commit be556e8a86
6 changed files with 715 additions and 2763 deletions

View file

@ -251,8 +251,8 @@ pub(super) fn exercise(
}
/// The synthetic handle every minted claim allocates under. It is synthesized
/// only in Active and declarations are Draft-only, so no world-declared handle
/// can collide with it.
/// in an act, which declares nothing, so no world-declared handle can collide
/// with it.
const SPEECH_HANDLE: &str = "ghostlight.speech";
/// The speech index, passed as `derive_id`'s discriminator. It is `0` for every
@ -1015,9 +1015,9 @@ mod tests {
};
use crate::tests::{
ADMIT_KIND, COMMAND_KIND, Civic, LEVY_KIND, OPENING_BALANCE, SEIZURE_GRIEVANCE, Topology,
WARDEN_OFFICE, act, act_command, activate, affordance_named, authority_kind, civic_world,
WARDEN_OFFICE, act, act_command, affordance_named, authority_kind, civic_world,
command, custody_world, grant_to, grievance, office, operations, over_place,
over_subject, play_caller, reject_owner, submit_owner,
over_subject, play_caller, reject_play, submit_play,
};
use crate::{
AffordanceKindName, AuthenticatedCaller, AuthoredSource, CommandBody, Confidence,
@ -1230,7 +1230,7 @@ mod tests {
// restores the two-hop cost: the check reads the live graph rather than
// anything the proposal was bound against.
let before = bench.kernel.snapshot().unwrap();
submit_owner(
submit_play(
&mut bench.kernel,
&before,
operations(vec![ComponentOp::OpenRoute {
@ -1241,7 +1241,7 @@ mod tests {
assert!(bench.try_exercise(&near).is_ok());
let before = bench.kernel.snapshot().unwrap();
submit_owner(
submit_play(
&mut bench.kernel,
&before,
operations(vec![ComponentOp::CloseRoute {
@ -1721,7 +1721,7 @@ mod tests {
fn the_kernel_speak_entry_commits_its_utterance_and_no_operation() {
let directory = tempfile::tempdir().unwrap();
let mut kernel = custody_kernel(directory.path(), "SpeakEntry");
let _topology = activate(&mut kernel);
let _topology = kernel.snapshot().unwrap();
let active = kernel.snapshot().unwrap();
let speak = affordance_named(&active, "speak");
let human = active
@ -1898,14 +1898,14 @@ mod tests {
fn admit(&mut self, ops: Vec<ComponentOp>) {
let before = self.kernel.snapshot().unwrap();
let receipt = submit_owner(&mut self.kernel, &before, operations(ops));
let receipt = submit_play(&mut self.kernel, &before, operations(ops));
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
self.refresh();
}
fn refuse(&mut self, ops: Vec<ComponentOp>) -> Vec<crate::Mismatch> {
let before = self.kernel.snapshot().unwrap();
reject_owner(&mut self.kernel, &before, operations(ops))
reject_play(&mut self.kernel, &before, operations(ops))
}
}
@ -2024,7 +2024,7 @@ mod tests {
let mut draft = custody_kernel(draft_directory.path(), "ReservedRole");
let before = draft.snapshot().unwrap();
let handle = DraftHandle::new("thief");
let rejected = reject_owner(
let rejected = reject_play(
&mut draft,
&before,
CommandBody::AdmitPatch {

View file

@ -102,12 +102,12 @@ fn admit(kernel: &mut WorldKernel, patch: WorldPatch) -> Result<SubmitReceipt, K
command(
&snapshot,
CommandId::new(),
CallerId::Principal(owner()),
CallerId::Play,
CommandBody::AdmitPatch {
patch,
},
),
&auth_principal(owner()),
&crate::AuthenticatedCaller::verified_play(),
)
}
@ -500,7 +500,7 @@ fn submit_as(
)
}
/// A bound Draft world whose revision has moved past genesis: one owner patch
/// A bound world whose revision has moved past genesis: one Play patch
/// that adds a dead-end place.
fn advanced_grammar_world() -> (tempfile::TempDir, WorldKernel, crate::EntityId) {
let extra = [("hail", verb(RenderPath::Conversation, &[]))];
@ -540,8 +540,7 @@ fn advanced_grammar_world() -> (tempfile::TempDir, WorldKernel, crate::EntityId)
type Door = (&'static str, CallerId);
/// Each door refuses an outside kind and a wrong role signature, typed, and the
/// refusal leaves the revision where it was. The owner and the consumer declare
/// in Draft only; Play declares in Active.
/// refusal leaves the revision where it was.
fn refuse_at_each_door(kernel: &mut WorldKernel, doors: Vec<Door>) {
for (door, caller) in doors {
let revision = kernel.state.revision;
@ -565,33 +564,15 @@ fn refuse_at_each_door(kernel: &mut WorldKernel, doors: Vec<Door>) {
}
#[test]
fn every_admission_door_refuses_outside_the_grammar_after_the_revision_has_moved() {
fn play_refuses_outside_the_grammar_after_the_revision_has_moved() {
let (_dir, mut kernel, _) = advanced_grammar_world();
assert_eq!(kernel.state.revision, 1);
let draft_doors = vec![
("owner", CallerId::Principal(owner())),
(
"consumer",
CallerId::System(crate::SystemCapability::Consumer {
consumer: crate::ConsumerId::of_name("grammar-door"),
}),
),
];
refuse_at_each_door(&mut kernel, draft_doors);
crate::tests::activate(&mut kernel);
assert!(
kernel.state.revision > 1,
"the world has moved past genesis"
);
let active_doors = vec![
("play", CallerId::System(crate::SystemCapability::Play)),
];
refuse_at_each_door(&mut kernel, active_doors);
refuse_at_each_door(&mut kernel, vec![("play", CallerId::Play)]);
// The same path admits what the grammar carries, so the refusals above are
// the grammar's and not a closed door.
let receipt = submit_as(
&mut kernel,
CallerId::System(crate::SystemCapability::Play),
CallerId::Play,
patch_of(vec![declare("hail", "hail", &[])]),
)
.unwrap();
@ -670,7 +651,7 @@ fn an_effect_resolved_elsewhere_cannot_install_an_entry_outside_the_grammar() {
let result = crate::apply_effect(
&mut state,
CommandId::new(),
&CallerId::Principal(owner()),
&CallerId::Play,
&crate::WorldEffect::PatchAdmitted {
resolved,
},

View file

@ -6,11 +6,11 @@ use crate::patch::{
AccessKind, ComponentOp, Cost, Declaration, DraftHandle, EntityDeclaration, EntityKind,
ImportKey, Mismatch, Ref, RouteDeclaration,
};
use crate::tests::{activate, auth_principal, command, creation, owner};
use crate::tests::{auth_principal, command, creation, owner};
use crate::{
CallerId, CommandBody, CommandId, ConsumerId, CreateWorld, EntityId, KernelError,
CallerId, CommandBody, CommandId, CreateWorld, EntityId, KernelError,
NewController, SubjectDeclaration, SubjectKind, SubmitReceipt,
SystemCapability, WorldKernel, WorldPatch,
WorldKernel, WorldPatch,
};
use std::collections::BTreeSet;
@ -88,16 +88,14 @@ fn commons(kernel: &WorldKernel) -> EntityId {
*kernel.state.entities.keys().next().unwrap()
}
/// A mirror subject: the one shape every door may declare, since it needs no
/// catalog grant.
fn mirror(handle: &str, import_key: Option<ImportKey>, place: EntityId) -> Declaration {
/// A keyed subject that holds no verbs: legal, since a subject may be declared
/// with none, and the lightest declaration an import can make.
fn keyed(handle: &str, import_key: Option<ImportKey>, place: EntityId) -> Declaration {
Declaration::Subject(SubjectDeclaration {
handle: DraftHandle::new(handle),
label: format!("The {handle}"),
kind: SubjectKind::Person,
controller: NewController::External {
consumer: ConsumerId::of_name("import-key"),
},
controller: NewController::OperationalAgent,
affordances: BTreeSet::new(),
position: Some(Ref::Existing(place)),
import_key,
@ -154,24 +152,23 @@ fn one_patch_cannot_declare_two_subjects_with_one_import_key() {
let beta = Some(key("aetheria.ship", "Beta"));
let error = submit_as(
&mut kernel,
CallerId::Principal(owner()),
CallerId::Play,
patch_of(vec![
mirror("first", beta.clone(), place),
mirror("second", beta, place),
keyed("first", beta.clone(), place),
keyed("second", beta, place),
]),
);
assert_eq!(rejected(error), vec![duplicate("second")]);
assert_eq!(kernel.state.revision, revision, "a refusal moved the world");
}
/// The fixture world past genesis but still in Draft: the owner has added an
/// unwalked place.
/// The fixture world past genesis: Play has added an unwalked place.
fn advanced_keyed_world() -> (tempfile::TempDir, WorldKernel, EntityId) {
let (dir, mut kernel) = keyed_world();
let place = commons(&kernel);
submit_as(
&mut kernel,
CallerId::Principal(owner()),
CallerId::Play,
patch_of(vec![
Declaration::Entity(EntityDeclaration {
handle: DraftHandle::new("dead-end"),
@ -201,8 +198,7 @@ fn advanced_keyed_world() -> (tempfile::TempDir, WorldKernel, EntityId) {
}
/// Each door names the held key, typed, and the refusal leaves the revision
/// where it was. The owner and the consumer declare in Draft only; Play
/// declares in Active.
/// where it was.
fn refuse_held_key_at_each_door(
kernel: &mut WorldKernel,
place: EntityId,
@ -213,7 +209,7 @@ fn refuse_held_key_at_each_door(
let result = submit_as(
kernel,
caller,
patch_of(vec![mirror("copy", Some(alpha()), place)]),
patch_of(vec![keyed("copy", Some(alpha()), place)]),
);
assert_eq!(rejected(result), vec![held("copy")], "{door}");
assert_eq!(
@ -223,12 +219,6 @@ fn refuse_held_key_at_each_door(
}
}
fn consumer() -> CallerId {
CallerId::System(SystemCapability::Consumer {
consumer: ConsumerId::of_name("import-key"),
})
}
#[test]
fn a_held_import_key_is_refused_at_every_door_after_the_revision_has_moved() {
let (_dir, mut kernel, dead_end) = advanced_keyed_world();
@ -236,33 +226,22 @@ fn a_held_import_key_is_refused_at_every_door_after_the_revision_has_moved() {
refuse_held_key_at_each_door(
&mut kernel,
dead_end,
vec![
("owner", CallerId::Principal(owner())),
("consumer", consumer()),
],
);
activate(&mut kernel);
refuse_held_key_at_each_door(
&mut kernel,
dead_end,
vec![
("play", CallerId::System(SystemCapability::Play)),
],
vec![("play", CallerId::Play)],
);
// The same doors admit an unheld key, so the refusals are the key's; and
// what a door admitted is held against every later door.
let fresh = key("aetheria.ship", "Gamma");
let receipt = submit_as(
&mut kernel,
CallerId::System(SystemCapability::Play),
patch_of(vec![mirror("fresh", Some(fresh.clone()), dead_end)]),
CallerId::Play,
patch_of(vec![keyed("fresh", Some(fresh.clone()), dead_end)]),
)
.unwrap();
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
let again = submit_as(
&mut kernel,
CallerId::System(SystemCapability::Play),
patch_of(vec![mirror("fresh-again", Some(fresh), dead_end)]),
CallerId::Play,
patch_of(vec![keyed("fresh-again", Some(fresh), dead_end)]),
);
assert_eq!(rejected(again), vec![held("fresh-again")]);
}
@ -274,8 +253,8 @@ fn a_held_import_key_is_refused_in_a_later_patch() {
let revision = kernel.state.revision;
let error = submit_as(
&mut kernel,
CallerId::Principal(owner()),
patch_of(vec![mirror("again", Some(alpha()), place)]),
CallerId::Play,
patch_of(vec![keyed("again", Some(alpha()), place)]),
);
assert_eq!(rejected(error), vec![held("again")]);
assert_eq!(kernel.state.revision, revision);
@ -296,7 +275,7 @@ fn a_retired_subjects_import_key_is_never_reissued() {
.id;
submit_as(
&mut kernel,
CallerId::Principal(owner()),
CallerId::Play,
WorldPatch {
declarations: Vec::new(),
operations: vec![ComponentOp::Retire {
@ -321,8 +300,8 @@ fn a_retired_subjects_import_key_is_never_reissued() {
);
let error = submit_as(
&mut kernel,
CallerId::Principal(owner()),
patch_of(vec![mirror("reborn", Some(alpha()), place)]),
CallerId::Play,
patch_of(vec![keyed("reborn", Some(alpha()), place)]),
);
assert_eq!(rejected(error), vec![held("reborn")]);
}
@ -347,11 +326,11 @@ fn keys_that_differ_in_any_way_are_distinct_records() {
let declarations = forgeries
.iter()
.enumerate()
.map(|(index, forged)| mirror(&format!("forged-{index}"), Some(forged.clone()), place))
.map(|(index, forged)| keyed(&format!("forged-{index}"), Some(forged.clone()), place))
.collect();
submit_as(
&mut kernel,
CallerId::Principal(owner()),
CallerId::Play,
patch_of(declarations),
)
.expect("nine distinct keys beside the held one are admitted together");
@ -361,8 +340,8 @@ fn keys_that_differ_in_any_way_are_distinct_records() {
for (index, forged) in forgeries.iter().enumerate() {
let again = submit_as(
&mut kernel,
CallerId::Principal(owner()),
patch_of(vec![mirror("repeat", Some(forged.clone()), place)]),
CallerId::Play,
patch_of(vec![keyed("repeat", Some(forged.clone()), place)]),
);
assert_eq!(rejected(again), vec![held("repeat")], "forgery {index}");
}
@ -390,8 +369,8 @@ fn a_malformed_import_key_is_refused_without_echoing_it() {
for (index, bad) in cases.iter().enumerate() {
let set = rejected(submit_as(
&mut kernel,
CallerId::Principal(owner()),
patch_of(vec![mirror("bad", Some(bad.clone()), place)]),
CallerId::Play,
patch_of(vec![keyed("bad", Some(bad.clone()), place)]),
));
assert_eq!(set, vec![malformed("bad")], "case {index}");
let spelled = format!("{set:?}");
@ -409,11 +388,11 @@ fn a_malformed_import_key_is_refused_without_echoing_it() {
let declarations = at_limit
.iter()
.enumerate()
.map(|(index, limit)| mirror(&format!("edge-{index}"), Some(limit.clone()), place))
.map(|(index, limit)| keyed(&format!("edge-{index}"), Some(limit.clone()), place))
.collect();
submit_as(
&mut kernel,
CallerId::Principal(owner()),
CallerId::Play,
patch_of(declarations),
)
.expect("keys of exactly 200 bytes per part are admitted");
@ -427,7 +406,7 @@ fn the_subjects_map_refuses_a_second_subject_for_one_key_even_when_resolved_else
crate::patch::resolve_patch(
&kernel.state,
CommandId::new(),
&patch_of(vec![mirror(
&patch_of(vec![keyed(
handle,
Some(key("aetheria.ship", "Omega")),
place,
@ -444,7 +423,7 @@ fn the_subjects_map_refuses_a_second_subject_for_one_key_even_when_resolved_else
crate::apply_effect(
&mut state,
CommandId::new(),
&CallerId::Principal(owner()),
&CallerId::Play,
&effect(first),
)
.unwrap();
@ -452,7 +431,7 @@ fn the_subjects_map_refuses_a_second_subject_for_one_key_even_when_resolved_else
let result = crate::apply_effect(
&mut state,
CommandId::new(),
&CallerId::Principal(owner()),
&CallerId::Play,
&effect(second),
);
assert!(
@ -525,8 +504,8 @@ fn a_record_key_is_one_canonical_spelling() {
let submit = |kernel: &mut WorldKernel, handle: &str, record: &str| {
submit_as(
kernel,
CallerId::Principal(owner()),
patch_of(vec![mirror(
CallerId::Play,
patch_of(vec![keyed(
handle,
Some(key("aetheria.ship", record)),
place,
@ -573,8 +552,8 @@ fn a_lore_page_path_with_spaces_is_a_record_key() {
let declare = |kernel: &mut WorldKernel, handle: &str| {
submit_as(
kernel,
CallerId::Principal(owner()),
patch_of(vec![mirror(
CallerId::Play,
patch_of(vec![keyed(
handle,
Some(key("aetheria.lore", record)),
place,
@ -591,8 +570,8 @@ fn a_loaded_state_with_a_bad_import_key_is_refused() {
let place = commons(&kernel);
submit_as(
&mut kernel,
CallerId::Principal(owner()),
patch_of(vec![mirror(
CallerId::Play,
patch_of(vec![keyed(
"beta",
Some(key("aetheria.ship", "Beta")),
place,
@ -640,8 +619,8 @@ fn admitting_a_resolved_effect_refuses_two_subjects_with_one_key() {
&kernel.state,
CommandId::new(),
&patch_of(vec![
mirror("first", Some(key("aetheria.ship", "Beta")), place),
mirror("second", Some(key("aetheria.ship", "Gamma")), place),
keyed("first", Some(key("aetheria.ship", "Beta")), place),
keyed("second", Some(key("aetheria.ship", "Gamma")), place),
]),
)
.expect("two distinct keys resolve")
@ -677,8 +656,8 @@ fn a_decomposable_character_is_refused_in_nfd_at_every_position() {
let submit = |kernel: &mut WorldKernel, handle: &str, record: String| {
submit_as(
kernel,
CallerId::Principal(owner()),
patch_of(vec![mirror(
CallerId::Play,
patch_of(vec![keyed(
handle,
Some(key("aetheria.lore", &record)),
place,
@ -711,3 +690,18 @@ fn a_decomposable_character_is_refused_in_nfd_at_every_position() {
"the genesis key and one NFC key per position are held, no NFD key"
);
}
#[test]
fn the_owner_door_is_closed_to_a_keyed_declaration() {
let (_dir, mut kernel) = keyed_world();
let place = commons(&kernel);
let revision = kernel.state.revision;
let error = submit_as(
&mut kernel,
CallerId::Principal(owner()),
patch_of(vec![keyed("fresh", Some(key("aetheria.ship", "Gamma")), place)]),
)
.unwrap_err();
assert!(matches!(error, KernelError::Unauthorized), "{error:?}");
assert_eq!(kernel.state.revision, revision);
}

View file

@ -428,10 +428,9 @@ pub(super) fn verify_history(
// Authority is re-decided here for free: `apply_committed_command`
// re-runs `reduce` against the pre-commit state and requires effect
// equality, then `apply_effect`, and both of those call
// `require_patch_author` and `confine_to_ground`. A forged row
// claiming a confined caller for a patch outside its ground
// fails replay rather than being admitted by a reducer that trusts the
// recorded caller. A third statement of the same rule here would be a
// `require_play`. A forged row recording the owner as the caller of
// a post-genesis command fails replay rather than being admitted by a
// reducer that trusts the recorded caller. A third statement of the same rule here would be a
// third owner of one decision.
apply_committed_command(&mut replay, commit)?;
// Two chain checks one state cannot make: the clock never runs
@ -494,7 +493,6 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError>
super::validate_principal(&state.owner).map_err(kernel_error)?;
if state.subjects.is_empty()
|| state.controller_assignments.len() != state.subjects.len()
|| state.affordance_grants.is_empty()
{
return Err(JournalError::Corrupt(
"world ontology is empty or has split subject/controller ownership".into(),
@ -815,7 +813,7 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError>
.get(&scope)
.ok_or_else(|| JournalError::Corrupt("decision subject has no controller".into()))?;
super::validate_assignment(assignment).map_err(kernel_error)?;
// A mirror has no controller id, so it joins no uniqueness set.
// A retired subject has no controller id, so it joins no uniqueness set.
if let Some(controller_id) = assignment.id()
&& !controller_ids.insert(controller_id)
{
@ -833,31 +831,21 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError>
"controller assignment references an unknown subject".into(),
));
}
// A grant row is a verb list: non-empty, for a live subject, catalog
// entries only. A subject holding no verb holds no row.
for (scope, granted) in &state.affordance_grants {
if !state.controller_assignments.contains_key(scope)
|| super::is_retired(state, scope.subject_id)
|| granted.is_empty()
|| granted
.iter()
.any(|affordance_id| !state.affordance_catalog.contains_key(affordance_id))
{
return Err(JournalError::Corrupt(
"affordance grant is empty, unscoped, or names no catalog entry".into(),
"affordance grant is empty, unscoped, retired, or names no catalog entry".into(),
));
}
}
// Both ways, the pairing `admit_resolved` decided: a mirror holds no grant,
// and every controller-bearing scope holds one.
if state
.controller_assignments
.iter()
.any(|(scope, assignment)| {
state.affordance_grants.contains_key(scope) != assignment.mode().is_some()
})
{
return Err(JournalError::Corrupt(
"controller assignment and affordance grant do not pair".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() {
@ -867,20 +855,6 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError>
));
}
}
// Approval shape holds only in Draft. Once the world is Active, the
// approvals that admitted it are frozen history: they are judged once by
// `reduce`'s `ActivateWorld` arm and after that by replay, not re-judged
// here against the present-day controller roster. Retiring the human
// (PA.f32) or adding a later human-controlled subject must not make a
// past activation retroactively corrupt.
if state.phase == super::WorldPhase::Draft {
let required = super::required_approvers(state);
if !state.draft_approvals.is_subset(&required) {
return Err(JournalError::Corrupt(
"draft approvals do not match canonical controller ownership".into(),
));
}
}
let mut event_ids = BTreeSet::new();
let mut claimed = BTreeSet::new();
let mut previous_event_revision = 0;
@ -1091,10 +1065,12 @@ mod tests {
id: command_id,
world_id: snapshot.world_id,
expected_revision: snapshot.revision,
caller: CallerId::Principal(owner),
body: CommandBody::ApproveDraft,
caller: CallerId::Play,
body: CommandBody::AdvanceTime {
minutes: crate::TickMinutes::new(1).unwrap(),
},
},
&authenticated,
&AuthenticatedCaller::verified_play(),
)
.unwrap();
@ -1104,7 +1080,9 @@ mod tests {
let CommittedCommand::WorldCommand(command) = &mut command_forged.command else {
panic!("expected a world command");
};
command.body = CommandBody::ActivateWorld;
command.body = CommandBody::AdvanceTime {
minutes: crate::TickMinutes::new(2).unwrap(),
};
command_forged.digest = commit_digest(command_forged).unwrap();
command_forged_head.last_commit_digest = Some(command_forged.digest.clone());
@ -1131,7 +1109,10 @@ mod tests {
let mut effect_forged_head = kernel.state.clone();
let mut effect_forged_commits = kernel.journal.commits.clone();
let effect_forged = effect_forged_commits.get_mut(&command_id).unwrap();
effect_forged.effect = WorldEffect::WorldActivated;
let WorldEffect::TimeAdvanced { to, .. } = &mut effect_forged.effect else {
panic!("expected a time effect");
};
*to = crate::FictionalMinutes(99);
effect_forged.digest = commit_digest(effect_forged).unwrap();
effect_forged_head.last_commit_digest = Some(effect_forged.digest.clone());
@ -1173,7 +1154,7 @@ mod tests {
id: command_id,
world_id: snapshot.world_id,
expected_revision: snapshot.revision,
caller: CallerId::Principal(owner),
caller: CallerId::Play,
body: CommandBody::AdmitPatch {
patch: WorldPatch {
declarations: vec![
@ -1198,7 +1179,7 @@ mod tests {
},
},
},
&authenticated,
&AuthenticatedCaller::verified_play(),
)
.unwrap();
@ -1270,8 +1251,8 @@ mod tests {
}
/// A store written under an older schema is refused at open: both
/// `consumer.v4` strings and the pre-cut `consumer.v6` ones. No migration,
/// no dual read.
/// `consumer.v4` strings and the pre-cut `consumer.v6` and `consumer.v8`
/// ones. No migration, no dual read.
#[test]
fn a_store_written_under_an_older_schema_is_refused() {
for (row_type, schema) in [
@ -1279,6 +1260,8 @@ mod tests {
(COMMIT_ROW, "ghostlight.world_commit.consumer.v4"),
(STATE_ROW, "ghostlight.world_state.consumer.v6"),
(COMMIT_ROW, "ghostlight.world_commit.consumer.v6"),
(STATE_ROW, "ghostlight.world_state.consumer.v8"),
(COMMIT_ROW, "ghostlight.world_commit.consumer.v8"),
] {
let row = CultCacheEnvelope {
key: "state".into(),
@ -1298,10 +1281,10 @@ mod tests {
}
}
/// A world whose history includes an owner's clock advance, reopened from
/// its own store rows.
/// A world whose history includes a patch and a clock advance, both Play's,
/// reopened from its own store rows.
fn clock_history() -> (tempfile::TempDir, WorldKernel) {
use crate::tests::{activate, auth_principal, creation, owner, submit_owner};
use crate::tests::{auth_principal, creation, owner, submit_play};
use crate::TickMinutes;
let directory = tempfile::tempdir().unwrap();
@ -1311,8 +1294,27 @@ mod tests {
&auth_principal(owner()),
)
.unwrap();
let snapshot = activate(&mut kernel);
submit_owner(
let snapshot = kernel.snapshot().unwrap();
submit_play(
&mut kernel,
&snapshot,
CommandBody::AdmitPatch {
patch: crate::WorldPatch {
declarations: vec![crate::patch::Declaration::Entity(
crate::patch::EntityDeclaration {
handle: crate::patch::DraftHandle::new("annex"),
label: "The Annex".into(),
kind: crate::patch::EntityKind::Place,
container: None,
},
)],
operations: Vec::new(),
evidence: Vec::new(),
},
},
);
let snapshot = kernel.snapshot().unwrap();
submit_play(
&mut kernel,
&snapshot,
CommandBody::AdvanceTime {
@ -1333,10 +1335,10 @@ mod tests {
rows
}
/// Replay re-derives the owner's clock advance: the honest history reopens
/// to the same state digest and reading, and the store on disk does too.
/// Replay re-derives Play's patch and clock advance: the honest history
/// reopens to the same state digest and reading, and the store on disk does too.
#[test]
fn a_history_with_an_owner_clock_advance_replays_exactly() {
fn a_history_with_a_patch_and_a_clock_advance_replays_exactly() {
let (directory, kernel) = clock_history();
let honest: Vec<WorldCommit> = kernel.journal.commits.values().cloned().collect();
let (_, replayed, commits) =
@ -1356,46 +1358,57 @@ mod tests {
/// A stored command is not believed about who made it. The forgery re-seals
/// the commit around its rewrite and the head's last commit digest names the
/// re-sealed commit, so no digest can answer for the check; the control, the
/// same re-sealing around the honest caller, replays.
/// same re-sealing around the honest caller, replays. Both Play's doors are
/// forged: a patch row and a clock row recorded as the owner's.
#[test]
fn a_clock_advance_forged_to_another_caller_fails_replay() {
use crate::tests::human_principal;
fn a_commit_forged_to_the_owner_fails_replay() {
use crate::tests::owner;
let (_directory, kernel) = clock_history();
let honest: Vec<WorldCommit> = kernel.journal.commits.values().cloned().collect();
let forge = |rewrite: &dyn Fn(&mut WorldCommit)| -> (WorldState, Vec<WorldCommit>) {
let mut head = kernel.state.clone();
// Re-seals the rewritten commit and every later one around it, so the
// chain of previous-commit digests agrees and only the caller check is
// left to refuse the history.
let forge = |is_row: &dyn Fn(&WorldEffect) -> bool,
rewrite: &dyn Fn(&mut WorldCommit)|
-> (WorldState, Vec<WorldCommit>) {
let mut forged: Vec<WorldCommit> = honest.clone();
let clock_row = forged
.iter_mut()
.filter(|commit| matches!(commit.effect, WorldEffect::TimeAdvanced { .. }))
.collect::<Vec<_>>();
let [commit] = <[&mut WorldCommit; 1]>::try_from(clock_row)
.expect("the history holds exactly one clock row");
assert_eq!(
commit.resulting_revision, head.revision,
"the clock row is the head commit"
);
rewrite(commit);
commit.digest = commit_digest(commit).unwrap();
head.last_commit_digest = Some(commit.digest.clone());
forged.sort_by_key(|commit| commit.resulting_revision);
let rows: Vec<usize> = (0..forged.len())
.filter(|index| is_row(&forged[*index].effect))
.collect();
let [at] = <[usize; 1]>::try_from(rows)
.expect("the history holds exactly one such row");
rewrite(&mut forged[at]);
for index in at..forged.len() {
if index > at {
forged[index].previous_commit_digest = Some(forged[index - 1].digest.clone());
}
forged[index].digest = commit_digest(&forged[index]).unwrap();
}
let mut head = kernel.state.clone();
head.last_commit_digest = forged.last().map(|commit| commit.digest.clone());
(head, forged)
};
let patch_row = |effect: &WorldEffect| matches!(effect, WorldEffect::PatchAdmitted { .. });
let clock_row = |effect: &WorldEffect| matches!(effect, WorldEffect::TimeAdvanced { .. });
let (head, control) = forge(&|_| {});
recover(rows_of(&head, &control), None).expect("a consistent re-sealed store replays");
for is_row in [&patch_row as &dyn Fn(&WorldEffect) -> bool, &clock_row] {
let (head, control) = forge(is_row, &|_| {});
recover(rows_of(&head, &control), None)
.expect("a consistent re-sealed store replays");
let (head, forged) = forge(&|commit| {
if let CommittedCommand::WorldCommand(command) = &mut commit.command {
command.caller = CallerId::Principal(human_principal());
}
});
let error = recover(rows_of(&head, &forged), None)
.expect_err("a clock advance forged to a non-owner replayed");
let JournalError::Corrupt(detail) = error else {
panic!("unexpected refusal: {error:?}");
};
assert!(detail.contains("Unauthorized") || detail.contains("does not own"), "{detail}");
let (head, forged) = forge(is_row, &|commit| {
if let CommittedCommand::WorldCommand(command) = &mut commit.command {
command.caller = CallerId::Principal(owner());
}
});
let error = recover(rows_of(&head, &forged), None)
.expect_err("a commit forged to the owner replayed");
let JournalError::Corrupt(_) = error else {
panic!("unexpected refusal: {error:?}");
};
}
}
/// The tick is re-derived at replay by the same function that produced it,
@ -1403,9 +1416,9 @@ mod tests {
/// its command. The clock chain refuses a rewritten reading the same way.
#[test]
fn a_forged_motion_does_not_replay() {
use crate::tests::{activate, auth_principal, command, owner};
use crate::tests::{auth_principal, command, owner};
use crate::{
AuthenticatedCaller, CallerId, CommandBody, FictionalMinutes, SystemCapability,
AuthenticatedCaller, CallerId, CommandBody, FictionalMinutes,
TickMinutes,
};
@ -1418,9 +1431,9 @@ mod tests {
&authenticated,
)
.unwrap();
let active = activate(&mut kernel);
let active = kernel.snapshot().unwrap();
let command_id = CommandId::new();
let caller = CallerId::System(SystemCapability::Clock);
let caller = CallerId::Play;
kernel
.submit(
command(
@ -1455,7 +1468,7 @@ mod tests {
/// to move a different subject no longer reduces from its command.
#[test]
fn a_forged_relocate_effect_does_not_apply() {
use crate::tests::{activate, admit_topology, auth_principal, command, owner};
use crate::tests::{admit_topology, auth_principal, command, owner};
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("world.cc");
@ -1467,14 +1480,14 @@ mod tests {
)
.unwrap();
let topology = admit_topology(&mut kernel);
let active = activate(&mut kernel);
let active = kernel.snapshot().unwrap();
let command_id = CommandId::new();
kernel
.submit(
command(
&active,
command_id,
CallerId::Principal(owner()),
CallerId::Play,
CommandBody::AdmitPatch {
patch: WorldPatch {
declarations: Vec::new(),
@ -1486,7 +1499,7 @@ mod tests {
},
},
),
&authenticated,
&AuthenticatedCaller::verified_play(),
)
.unwrap();
@ -1519,7 +1532,7 @@ mod tests {
#[test]
fn soul_a_forged_band_or_effect_in_the_journal_dies_at_replay() {
use crate::tests::{
activate, admit_custody, admit_topology, affordance_named, auth_principal, command,
admit_custody, admit_topology, affordance_named, auth_principal, command,
owner, play_caller,
};
use crate::{
@ -1539,7 +1552,7 @@ mod tests {
.unwrap();
let topology = admit_topology(&mut kernel);
let custody = admit_custody(&mut kernel, &topology);
let active = activate(&mut kernel);
let active = kernel.snapshot().unwrap();
let entry = affordance_named(&active, kind);
let caller = play_caller();
let command_id = CommandId::new();
@ -2048,8 +2061,8 @@ mod tests {
#[test]
fn a_relocation_never_corrupts_a_civic_store() {
use crate::tests::{
LEVY_KIND, auth_principal, civic_world, operations, over_subject, owner, reject_owner,
submit_owner,
LEVY_KIND, auth_principal, civic_world, operations, over_subject, owner, reject_play,
submit_play,
};
use crate::{ComponentOp, Mismatch, SubmitReceipt};
@ -2066,7 +2079,7 @@ mod tests {
let admit = |kernel: &mut WorldKernel, ops: Vec<ComponentOp>| {
let before = kernel.snapshot().unwrap();
assert!(matches!(
submit_owner(kernel, &before, operations(ops)),
submit_play(kernel, &before, operations(ops)),
SubmitReceipt::Applied(_)
));
verify_state_shape(&kernel.state).expect("the committed store keeps its shape");
@ -2097,7 +2110,7 @@ mod tests {
assert!(place_covers(&kernel));
let before = kernel.snapshot().unwrap();
assert_eq!(
reject_owner(&mut kernel, &before, operations(name_farmer())),
reject_play(&mut kernel, &before, operations(name_farmer())),
vec![Mismatch::OverlappingJurisdiction { operation: 0 }]
);
@ -2150,12 +2163,12 @@ mod custody_tests {
.unwrap();
let topology = admit_topology(&mut kernel);
let custody = admit_custody(&mut kernel, &topology);
let active = crate::tests::activate(&mut kernel);
let active = kernel.snapshot().unwrap();
let envelope = command(
&active,
CommandId::new(),
CallerId::Principal(owner()),
CallerId::Play,
CommandBody::AdmitPatch {
patch: WorldPatch {
declarations: Vec::new(),
@ -2170,7 +2183,7 @@ mod custody_tests {
},
);
let SubmitReceipt::Applied(receipt) =
kernel.submit(envelope.clone(), &authenticated).unwrap()
kernel.submit(envelope.clone(), &crate::AuthenticatedCaller::verified_play()).unwrap()
else {
panic!("expected an applied transfer");
};
@ -2181,7 +2194,7 @@ mod custody_tests {
let mut reopened = WorldKernel::open(&path, world_id).unwrap();
assert_eq!(reopened.snapshot().unwrap(), accepted);
assert_eq!(
reopened.submit(envelope, &authenticated).unwrap(),
reopened.submit(envelope, &crate::AuthenticatedCaller::verified_play()).unwrap(),
SubmitReceipt::AlreadyApplied(receipt)
);
}
@ -2205,7 +2218,7 @@ mod custody_tests {
.unwrap();
let topology = admit_topology(&mut kernel);
let custody = admit_custody(&mut kernel, &topology);
let active = crate::tests::activate(&mut kernel);
let active = kernel.snapshot().unwrap();
let carry = affordance_named(&active, "carry");
let caller = play_caller();
@ -2289,34 +2302,57 @@ mod custody_tests {
);
}
/// PA.f39, M9: the Draft-only approval shape clause is defence in depth,
/// so it is pinned directly on `verify_state_shape` rather than only
/// through a full submit path. A fresh Draft world's approvals pass; a
/// forged principal outside `required_approvers` does not.
/// A grant row is a verb list for a live subject: each clause of the shape
/// check is pinned on `verify_state_shape` directly, one forged state per
/// clause, so deleting any one of them fails a case.
#[test]
fn draft_approvals_outside_required_approvers_is_corrupt() {
fn a_malformed_grant_row_is_corrupt() {
use crate::tests::{auth_principal, creation, owner};
use crate::{AffordanceId, ControllerAssignment, DecisionScope, SubjectId};
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("world.cc");
let (kernel, _) = WorldKernel::create(
&path,
creation(CommandId::new(), "PAf39ApprovalShape"),
creation(CommandId::new(), "GrantRows"),
&auth_principal(owner()),
)
.unwrap();
assert_eq!(kernel.state.phase, crate::WorldPhase::Draft);
verify_state_shape(&kernel.state)
.expect("a fresh Draft world has a canonical approval shape");
verify_state_shape(&kernel.state).expect("a fresh world has canonical grant rows");
let held = *kernel.state.affordance_grants.keys().next().unwrap();
let mut forged = kernel.state.clone();
forged
.draft_approvals
.insert(crate::PrincipalId::new("interloper@example.test"));
assert!(
matches!(verify_state_shape(&forged), Err(JournalError::Corrupt(_))),
"an approval outside the required set passed the shape check"
);
let corrupt = |name: &str, forge: &dyn Fn(&mut WorldState)| {
let mut forged = kernel.state.clone();
forge(&mut forged);
assert!(
matches!(verify_state_shape(&forged), Err(JournalError::Corrupt(_))),
"{name} passed the shape check"
);
};
corrupt("a grant row for a retired subject", &|state| {
state
.controller_assignments
.insert(held, ControllerAssignment::Retired);
});
corrupt("an empty grant row", &|state| {
state.affordance_grants.get_mut(&held).unwrap().clear();
});
corrupt("a grant row for no subject", &|state| {
let verbs = state.affordance_grants[&held].clone();
state.affordance_grants.insert(
DecisionScope {
subject_id: SubjectId::issue(),
},
verbs,
);
});
corrupt("a grant row naming an uncataloged verb", &|state| {
state
.affordance_grants
.get_mut(&held)
.unwrap()
.insert(AffordanceId::issue());
});
}
/// A chain holding `Acted` commits recovers and verifies on reopen, and an
@ -2324,7 +2360,7 @@ mod custody_tests {
#[test]
fn an_acted_chain_reopens_and_a_foreign_actor_is_corrupt() {
use crate::tests::{
act, activate, auth_principal, creation, first_grant, owner, speak,
act, auth_principal, creation, first_grant, owner, speak,
};
let directory = tempfile::tempdir().unwrap();
@ -2335,7 +2371,7 @@ mod custody_tests {
&auth_principal(owner()),
)
.unwrap();
let active = activate(&mut kernel);
let active = kernel.snapshot().unwrap();
let actor = *active.subjects.first().map(|subject| &subject.id).unwrap();
act(
&mut kernel,
@ -2371,21 +2407,21 @@ mod custody_tests {
);
}
/// Stores written at the previous schema ids (v7) are refused outright,
/// Stores written at the previous schema ids (v8) are refused outright,
/// state row and commit row each on their own: reverting either constant
/// to v7 would let its half of the store in.
/// to v8 would let its half of the store in.
#[test]
fn v7_state_and_commit_rows_are_refused() {
use crate::tests::{act, activate, auth_principal, creation, first_grant, owner, speak};
fn v8_state_and_commit_rows_are_refused() {
use crate::tests::{act, auth_principal, creation, first_grant, owner, speak};
let directory = tempfile::tempdir().unwrap();
let (mut kernel, _) = WorldKernel::create(
directory.path().join("world.cc"),
creation(CommandId::new(), "SchemaV7"),
creation(CommandId::new(), "SchemaV8"),
&auth_principal(owner()),
)
.unwrap();
let active = activate(&mut kernel);
let active = kernel.snapshot().unwrap();
let actor = active.subjects[0].id;
act(&mut kernel, actor, speak(first_grant(&active, actor), "Counted.")).unwrap();
let commits: Vec<WorldCommit> = kernel.journal.commits.values().cloned().collect();
@ -2398,8 +2434,8 @@ mod custody_tests {
let state_row = |schema: &str| {
envelope(STATE_ROW, schema, kernel.state.world_id.key(), &kernel.state).unwrap()
};
assert_eq!(STATE_SCHEMA, "ghostlight.world_state.consumer.v8");
assert_eq!(COMMIT_SCHEMA, "ghostlight.world_commit.consumer.v8");
assert_eq!(STATE_SCHEMA, "ghostlight.world_state.consumer.v9");
assert_eq!(COMMIT_SCHEMA, "ghostlight.world_commit.consumer.v9");
recover(
[commit_rows(COMMIT_SCHEMA), vec![state_row(STATE_SCHEMA)]].concat(),
None,
@ -2408,17 +2444,17 @@ mod custody_tests {
for (what, rows) in [
(
"v7 state row",
"v8 state row",
[
commit_rows(COMMIT_SCHEMA),
vec![state_row("ghostlight.world_state.consumer.v7")],
vec![state_row("ghostlight.world_state.consumer.v8")],
]
.concat(),
),
(
"v7 commit rows",
"v8 commit rows",
[
commit_rows("ghostlight.world_commit.consumer.v7"),
commit_rows("ghostlight.world_commit.consumer.v8"),
vec![state_row(STATE_SCHEMA)],
]
.concat(),
@ -2437,7 +2473,7 @@ mod custody_tests {
#[test]
fn a_non_speech_event_with_a_foreign_actor_is_corrupt() {
use crate::tests::{
act, activate, admit_custody, admit_topology, affordance_named, auth_principal,
act, admit_custody, admit_topology, affordance_named, auth_principal,
creation, owner,
};
use crate::{DecisionInvocation, Magnitude, ProposedEffect, Quantity, Role, RoleBinding, Target};
@ -2451,7 +2487,7 @@ mod custody_tests {
.unwrap();
let topology = admit_topology(&mut kernel);
let custody = admit_custody(&mut kernel, &topology);
let active = activate(&mut kernel);
let active = kernel.snapshot().unwrap();
let role = |name: &str, target| RoleBinding {
role: Role(name.into()),
target,
@ -2507,7 +2543,6 @@ mod custody_tests {
.unwrap();
let topology = admit_topology(&mut kernel);
let custody = admit_custody(&mut kernel, &topology);
crate::tests::activate(&mut kernel);
verify_state_shape(&kernel.state).expect("the admitted world has a canonical shape");
let mut zero = kernel.state.clone();
@ -2571,12 +2606,12 @@ mod custody_tests {
// `Admit` and its evidence are Draft-only, so the opening balance is
// already on the log before activation.
let custody = admit_custody(&mut kernel, &topology);
let active = crate::tests::activate(&mut kernel);
let active = kernel.snapshot().unwrap();
let envelope = command(
&active,
CommandId::new(),
CallerId::Principal(owner()),
CallerId::Play,
CommandBody::AdmitPatch {
patch: WorldPatch {
declarations: Vec::new(),
@ -2612,7 +2647,7 @@ mod custody_tests {
},
);
let SubmitReceipt::Applied(receipt) =
kernel.submit(envelope.clone(), &authenticated).unwrap()
kernel.submit(envelope.clone(), &crate::AuthenticatedCaller::verified_play()).unwrap()
else {
panic!("expected an applied custody patch");
};
@ -2629,7 +2664,7 @@ mod custody_tests {
assert_eq!(reopened.state.dependencies, dependencies);
assert_eq!(reopened.state.state_digest, digest);
assert_eq!(
reopened.submit(envelope, &authenticated).unwrap(),
reopened.submit(envelope, &crate::AuthenticatedCaller::verified_play()).unwrap(),
SubmitReceipt::AlreadyApplied(receipt)
);
}
@ -2650,7 +2685,6 @@ mod custody_tests {
.unwrap();
let topology = admit_topology(&mut kernel);
let custody = admit_custody(&mut kernel, &topology);
crate::tests::activate(&mut kernel);
verify_state_shape(&kernel.state).expect("the admitted world has a canonical shape");
// A place is not a resource, so a resource dependency naming one dangles.
@ -2690,10 +2724,10 @@ mod custody_tests {
/// A world with one routine, one past-due goal, and a commit chain that
/// reaches them: the fixture the two clock-forgery checks below need.
fn ticking_world(path: &std::path::Path) -> (WorldKernel, super::super::SubjectId, CommandId) {
use crate::tests::{activate, auth_principal, command, operations, owner};
use crate::tests::{auth_principal, command, operations, owner};
use crate::{
AuthenticatedCaller, CallerId, CommandBody, CommitmentKind, ComponentOp,
FictionalMinutes, Ref, SystemCapability, TickMinutes,
FictionalMinutes, Ref, TickMinutes,
};
let authenticated = auth_principal(owner());
@ -2703,7 +2737,7 @@ mod custody_tests {
&authenticated,
)
.unwrap();
let active = activate(&mut kernel);
let active = kernel.snapshot().unwrap();
let subject = active.subjects.first().expect("a seeded subject").id;
let snapshot = kernel.snapshot().unwrap();
kernel
@ -2711,7 +2745,7 @@ mod custody_tests {
command(
&snapshot,
CommandId::new(),
CallerId::Principal(owner()),
CallerId::Play,
operations(vec![
ComponentOp::CreateCommitment {
subject: Ref::Existing(subject),
@ -2733,12 +2767,12 @@ mod custody_tests {
},
]),
),
&authenticated,
&AuthenticatedCaller::verified_play(),
)
.unwrap();
let tick_id = CommandId::new();
let caller = CallerId::System(SystemCapability::Clock);
let caller = CallerId::Play;
let snapshot = kernel.snapshot().unwrap();
kernel
.submit(

File diff suppressed because it is too large Load diff

View file

@ -257,7 +257,7 @@ pub struct AffordanceKindName(pub String);
#[serde(transparent)]
pub struct Role(pub(crate) String);
/// What a role must be bound to. `RefKind` is reused rather than mirrored: it
/// What a role must be bound to. `RefKind` is reused rather than restated: it
/// already spells subject, entity kind, and edge kind, so the binding kind-check
/// and the declaration kind-check are one predicate.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
@ -1241,20 +1241,18 @@ pub(crate) enum ComponentOp {
target: Ref<SubjectId>,
},
/// Ends a subject for good: no grants, no position, no audience, its
/// history kept. Only the owner and `Play` may write it.
/// history kept. Play's alone, like every post-genesis patch.
Retire {
subject: Ref<SubjectId>,
},
/// Grants one more standing catalog entry to an existing subject. Only the
/// owner (including the seed lane, the owner in Draft) and `Play` may
/// write it: a grant is authority, not structure, so a confined author is
/// refused whatever ground the subject stands on.
/// Grants one more standing catalog entry to an existing subject. Play's
/// alone.
GrantAffordance {
subject: Ref<SubjectId>,
affordance: Ref<AffordanceId>,
},
/// Revokes a grant. Refused if it would leave a controlled subject with
/// none: a controlled subject is never left mute.
/// Revokes a grant. A subject left with no verb holds no grant row and
/// simply cannot act.
RevokeAffordance {
subject: Ref<SubjectId>,
affordance: Ref<AffordanceId>,
@ -1394,12 +1392,6 @@ pub enum Mismatch {
UnadmittedController {
handle: DraftHandle,
},
/// A declared subject's controller and affordance grant do not pair: a
/// mirror was granted an affordance, or an ordinary controller was granted
/// none. `admit_resolved` re-decides the same rule.
ControllerGrantMismatch {
site: Site,
},
EmptyEvidence {
position: usize,
},
@ -1628,27 +1620,11 @@ pub enum Mismatch {
UnknownCommitment {
operation: usize,
},
/// A jurisdictional author wrote outside its jurisdiction. The owner is
/// unconfined and never sees this.
OutsideJurisdiction {
site: Site,
},
/// A `Ruled` fact or a `Mint` was written by a caller other than the play
/// authority.
RuledWithoutAuthority {
site: Site,
},
/// `Retire` named an `ExternallyControlled` subject: a mirror is owned by
/// another world, so this one cannot retire it.
RetiresAMirror {
operation: usize,
},
/// `Retire` named a `Human`-controlled subject while the world is still in
/// `Draft`. A human's Draft approval cannot be removed by removing the
/// human; the same retire is admitted once the world is `Active`.
RetiresAnApprover {
operation: usize,
},
/// `Communicate`, `AcquireKnowledge`, `Forget`, or `InstallIncumbent`
/// named a retired subject as the one acting, learning, forgetting, or
/// taking office. A retired subject is a body, not an actor: it may still
@ -1657,15 +1633,9 @@ pub enum Mismatch {
RetiredSubjectActed {
operation: usize,
},
/// `GrantAffordance` or `RevokeAffordance` named a retired or an
/// `ExternallyControlled` subject: neither holds a grant this patch may
/// touch.
GrantsOutsideControl {
operation: usize,
},
/// A `RevokeAffordance` that would leave a controlled subject with no
/// affordance at all: a subject is never left mute.
WouldLeaveSubjectMute {
/// `GrantAffordance` or `RevokeAffordance` named a retired subject: it
/// holds no grant this patch may touch.
GrantsToRetired {
operation: usize,
},
}
@ -3225,15 +3195,6 @@ pub(super) fn resolve_patch(
}
}
if let Declaration::Subject(subject) = declaration {
// Both ways. A mirror receives no controller, so it may hold no
// affordance; every other controller must hold one.
if matches!(subject.controller, NewController::External { .. })
!= subject.affordances.is_empty()
{
mismatches.push(Mismatch::ControllerGrantMismatch {
site: Site::Declaration(handle.clone()),
});
}
if let NewController::Human { principal } = &subject.controller
&& (!admits_human || super::validate_principal(principal).is_err())
{
@ -3361,39 +3322,18 @@ pub(super) fn resolve_patch(
)
})
.collect();
// `Retire` and the affordance grant operations read and write these three
// candidates. `retired` and `mirrors` seed from the committed
// `ControllerAssignment`, which the resolver otherwise never reads: a
// declared subject can only ever be a fresh, unretired controller (or a
// freshly declared mirror, added below), so drafts start out of both sets.
// `affordance_holdings` seeds from committed `affordance_grants` and is
// extended below for a subject this same patch declares.
// `Retire` and the affordance grant operations read and write these
// candidates. `retired` seeds from the committed `ControllerAssignment`,
// which the resolver otherwise never reads: a declared subject is always
// fresh and unretired, so drafts start out of the set. `affordance_holdings`
// seeds from committed `affordance_grants` and is extended below for a
// subject this same patch declares.
let mut retired: BTreeSet<Key<SubjectId>> = state
.controller_assignments
.keys()
.filter(|scope| super::is_retired(state, scope.subject_id))
.map(|scope| Key::Existing(scope.subject_id))
.collect();
let mut mirrors: BTreeSet<Key<SubjectId>> = state
.controller_assignments
.iter()
.filter(|(_, assignment)| {
matches!(assignment, ControllerAssignment::ExternallyControlled { .. })
})
.map(|(scope, _)| Key::Existing(scope.subject_id))
.collect();
// Tracked the same way as `mirrors`: seeded from the committed human
// controller, extended below for a subject this same patch declares as
// `NewController::Human`. `Retire` refuses a Draft-phase approver out of
// this set instead of relying solely on the apply-time re-check, which
// otherwise only catches a genesis patch that declares and retires the
// human in the same breath after `open_owner` has already committed.
let mut humans: BTreeSet<Key<SubjectId>> = state
.controller_assignments
.iter()
.filter(|(_, assignment)| assignment.human_principal().is_some())
.map(|(scope, _)| Key::Existing(scope.subject_id))
.collect();
let mut affordance_holdings: BTreeMap<Key<SubjectId>, BTreeSet<Key<AffordanceId>>> = state
.affordance_grants
.iter()
@ -3607,12 +3547,6 @@ pub(super) fn resolve_patch(
if !granted.is_empty() {
affordance_holdings.insert(Key::Draft(subject.handle.clone()), granted);
}
if matches!(subject.controller, NewController::External { .. }) {
mirrors.insert(Key::Draft(subject.handle.clone()));
}
if matches!(subject.controller, NewController::Human { .. }) {
humans.insert(Key::Draft(subject.handle.clone()));
}
if let Some(reference) = &subject.position
&& let Some(place) = resolve_entity(
Site::Declaration(subject.handle.clone()),
@ -3932,35 +3866,12 @@ pub(super) fn resolve_patch(
) else {
continue;
};
if mirrors.contains(&subject_key) {
mismatches.push(Mismatch::RetiresAMirror {
operation: position,
});
continue;
}
if retired.contains(&subject_key) {
mismatches.push(Mismatch::NoOperationEffect {
operation: position,
});
continue;
}
// A human's Draft approval cannot be removed by removing the
// human: `required_approvers` reads the live controller
// assignment and `Retired` carries no human principal, so an
// owner could otherwise retire the human, approve alone, and
// activate. Once the world is Active, approvals are frozen
// history judged by replay, and the human's subject may die.
// `humans` tracks a subject declared as `NewController::Human`
// in this same patch exactly as `mirrors` tracks a freshly
// declared mirror, so a genesis patch that declares and
// retires the human in one breath is refused here rather than
// only by the apply-time re-check after admission.
if state.phase == super::WorldPhase::Draft && humans.contains(&subject_key) {
mismatches.push(Mismatch::RetiresAnApprover {
operation: position,
});
continue;
}
retired.insert(subject_key.clone());
positions.remove(&subject_key);
affordance_holdings.remove(&subject_key);
@ -4410,11 +4321,9 @@ pub(super) fn resolve_patch(
else {
continue;
};
// A grant is authority over the catalog, not structure over
// ground: retirement and a mirror both hold no grant a patch
// may touch, whatever confinement later decides.
if retired.contains(&subject_key) || mirrors.contains(&subject_key) {
mismatches.push(Mismatch::GrantsOutsideControl {
// A retired subject holds no grant a patch may touch.
if retired.contains(&subject_key) {
mismatches.push(Mismatch::GrantsToRetired {
operation: position,
});
continue;
@ -4434,14 +4343,11 @@ pub(super) fn resolve_patch(
.or_default()
.insert(affordance_key);
} else {
let granted = affordance_holdings.entry(subject_key).or_default();
if granted.len() == 1 {
mismatches.push(Mismatch::WouldLeaveSubjectMute {
operation: position,
});
continue;
}
let granted = affordance_holdings.entry(subject_key.clone()).or_default();
granted.remove(&affordance_key);
if granted.is_empty() {
affordance_holdings.remove(&subject_key);
}
}
}
ComponentOp::OpenOffice {
@ -5178,10 +5084,6 @@ pub(super) fn resolve_patch(
NewController::OperationalAgent => ControllerAssignment::OperationalAgent {
controller_id: controller_id(),
},
// No controller id is derived, because there is no controller.
NewController::External { consumer } => {
ControllerAssignment::ExternallyControlled { consumer }
}
};
let granted = input
.affordances
@ -5811,12 +5713,12 @@ pub(super) fn containment_terminates(
mod tests {
use super::*;
use crate::tests::{
ADMIT_KIND, FIXTURE_ENTITIES, LEVY_KIND, activate, admit_topology, authority_kind,
ADMIT_KIND, FIXTURE_ENTITIES, LEVY_KIND, admit_topology, authority_kind,
auth_principal, civic_world, command, creation, grant_to, human_principal, office,
over_place, owner, reject_owner, speak_entry, submit_owner,
over_place, owner, reject_play, speak_entry, submit_play,
};
use crate::{
CallerId, CommandBody, CommandId, KernelError, SubmitReceipt, WorldKernel, WorldPhase,
AuthenticatedCaller, CallerId, CommandBody, CommandId, KernelError, SubmitReceipt, WorldKernel,
};
fn entity(handle: &str, label: &str, kind: EntityKind) -> Declaration {
@ -5989,7 +5891,7 @@ mod tests {
},
),
] {
let rejected = reject_owner(
let rejected = reject_play(
&mut kernel,
&before,
admit(patch_of(vec![catalog_entry(
@ -6005,7 +5907,7 @@ mod tests {
}
// No effect slots and no speech: the entry could never change anything.
let rejected = reject_owner(
let rejected = reject_play(
&mut kernel,
&before,
admit(patch_of(vec![catalog_entry(
@ -6028,7 +5930,7 @@ mod tests {
// A `Transfer` takes three referents, not two.
assert_eq!(
reject_owner(
reject_play(
&mut kernel,
&before,
admit(patch_of(vec![catalog_entry(
@ -6050,7 +5952,7 @@ mod tests {
// Its third referent is a resource, not a place.
assert_eq!(
reject_owner(
reject_play(
&mut kernel,
&before,
admit(patch_of(vec![catalog_entry(
@ -6076,7 +5978,7 @@ mod tests {
// A `Transfer` carries a quantity, so an unbounded slot has no ceiling.
assert_eq!(
reject_owner(
reject_play(
&mut kernel,
&before,
admit(patch_of(vec![catalog_entry(
@ -6095,7 +5997,7 @@ mod tests {
// A slot naming a role the entry does not declare.
assert_eq!(
reject_owner(
reject_play(
&mut kernel,
&before,
admit(patch_of(vec![catalog_entry(
@ -6137,7 +6039,7 @@ mod tests {
};
assert_eq!(
reject_owner(
reject_play(
&mut kernel,
&before,
admit(patch_of(vec![granting("verb")]))
@ -6152,7 +6054,7 @@ mod tests {
assert_eq!(kernel.state.subjects.len(), subjects_before);
// Declaring the entry in the same patch commits both atomically.
let receipt = submit_owner(
let receipt = submit_play(
&mut kernel,
&before,
admit(patch_of(vec![
@ -6191,7 +6093,7 @@ mod tests {
let mut kernel = draft_world(directory.path());
let before = kernel.snapshot().unwrap();
let slot = transfer_slot(vec!["from", "to", "goods"], Bounds::Quantity(Quantity(2)));
let rejected = reject_owner(
let rejected = reject_play(
&mut kernel,
&before,
admit(patch_of(vec![
@ -6220,7 +6122,7 @@ mod tests {
// A kind name outside the tool-name alphabet is refused for the same
// reason: it becomes a generated tool name.
let rejected = reject_owner(
let rejected = reject_play(
&mut kernel,
&before,
admit(patch_of(vec![catalog_entry(
@ -6266,7 +6168,7 @@ mod tests {
command(
&before,
CommandId::new(),
CallerId::Principal(owner()),
CallerId::Play,
admit(patch_of(vec![institution(
&kernel,
"rhythm-authority",
@ -6274,7 +6176,7 @@ mod tests {
Some(Ref::Draft(DraftHandle::new("kharad-rhythm-road"))),
)])),
),
&auth_principal(owner()),
&AuthenticatedCaller::verified_play(),
)
.unwrap_err();
@ -6321,7 +6223,7 @@ mod tests {
Some(Ref::Draft(draft("kharad-rhythm-road"))),
),
]);
let receipt = submit_owner(&mut kernel, &before, admit(patch));
let receipt = submit_play(&mut kernel, &before, admit(patch));
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
let after = kernel.snapshot().unwrap();
@ -6376,7 +6278,7 @@ mod tests {
command(
&before,
CommandId::new(),
CallerId::Principal(owner()),
CallerId::Play,
admit(patch_of(vec![
entity("rhythm-tithe", "The Rhythm Tithe", EntityKind::Resource),
institution(
@ -6387,7 +6289,7 @@ mod tests {
),
])),
),
&auth_principal(owner()),
&AuthenticatedCaller::verified_play(),
)
.unwrap_err();
@ -6441,10 +6343,10 @@ mod tests {
command(
&before,
CommandId::new(),
CallerId::Principal(owner()),
CallerId::Play,
admit(broken),
),
&auth_principal(owner()),
&AuthenticatedCaller::verified_play(),
)
.unwrap_err();
let KernelError::PatchRejected(mismatches) = error else {
@ -6489,7 +6391,7 @@ mod tests {
import_key: None,
}),
]);
let receipt = submit_owner(&mut kernel, &before, admit(repaired));
let receipt = submit_play(&mut kernel, &before, admit(repaired));
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
assert_eq!(kernel.state.entities.len(), 3);
}
@ -6505,10 +6407,10 @@ mod tests {
command(
&before,
CommandId::new(),
CallerId::Principal(owner()),
CallerId::Play,
admit(patch_of(Vec::new())),
),
&auth_principal(owner()),
&AuthenticatedCaller::verified_play(),
)
.unwrap_err();
let KernelError::PatchRejected(mismatches) = error else {
@ -6532,7 +6434,7 @@ mod tests {
command(
&before,
CommandId::new(),
CallerId::Principal(owner()),
CallerId::Play,
admit(patch_of(vec![
contained("yard", "The Cavity Yard", "road"),
contained("road", "The Rhythm Road", "gate"),
@ -6540,7 +6442,7 @@ mod tests {
entity("orphan", " ", EntityKind::Place),
])),
),
&auth_principal(owner()),
&AuthenticatedCaller::verified_play(),
)
.unwrap_err();
let KernelError::PatchRejected(mismatches) = error else {
@ -6577,14 +6479,14 @@ mod tests {
command(
&before,
CommandId::new(),
CallerId::Principal(owner()),
CallerId::Play,
admit(patch_of(vec![
entity("yard", "The Cavity Yard", EntityKind::Place),
entity("tithe", "The Rhythm Tithe", EntityKind::Resource),
route("ramp", "The Yard Ramp", "yard", "tithe", 12),
])),
),
&auth_principal(owner()),
&AuthenticatedCaller::verified_play(),
)
.unwrap_err();
let KernelError::PatchRejected(mismatches) = error else {
@ -6617,7 +6519,7 @@ mod tests {
command(
&before,
CommandId::new(),
CallerId::Principal(owner()),
CallerId::Play,
admit(WorldPatch {
declarations: vec![Declaration::Route(RouteDeclaration {
handle: draft("free-ride"),
@ -6634,7 +6536,7 @@ mod tests {
evidence: Vec::new(),
}),
),
&auth_principal(owner()),
&AuthenticatedCaller::verified_play(),
)
.unwrap_err();
let KernelError::PatchRejected(mismatches) = error else {
@ -6660,7 +6562,7 @@ mod tests {
let directory = tempfile::tempdir().unwrap();
let mut kernel = draft_world(directory.path());
let topology = admit_topology(&mut kernel);
let active = activate(&mut kernel);
let active = kernel.snapshot().unwrap();
let commits_before = kernel.journal.commit_count();
for (edge_id, expected) in [
@ -6676,13 +6578,13 @@ mod tests {
command(
&active,
CommandId::new(),
CallerId::Principal(owner()),
CallerId::Play,
admit(operations_of(vec![ComponentOp::Relocate {
subject: Ref::Existing(topology.walker),
via: Ref::Existing(edge_id),
}])),
),
&auth_principal(owner()),
&AuthenticatedCaller::verified_play(),
)
.unwrap_err();
let KernelError::PatchRejected(mismatches) = error else {
@ -6715,7 +6617,7 @@ mod tests {
// directly over the chamber the hall contains, so a resolver that
// still counted the dead lend would see two distinct, overlapping
// `GrantKey`s (not one collapsed duplicate) and refuse.
let receipt = submit_owner(
let receipt = submit_play(
&mut kernel,
&before,
admit(operations_of(vec![
@ -6745,7 +6647,7 @@ mod tests {
// `topology.walker` already exists and already stands at `yard`, so
// this delegation patch is operations-only: no declaration.
let delegated = submit_owner(
let delegated = submit_play(
&mut kernel,
&before,
admit(operations_of(vec![
@ -6769,7 +6671,7 @@ mod tests {
let after_delegation = kernel.snapshot().unwrap();
let commits_before = kernel.journal.commit_count();
let mismatches = reject_owner(
let mismatches = reject_play(
&mut kernel,
&after_delegation,
admit(operations_of(vec![
@ -6796,11 +6698,11 @@ mod tests {
let directory = tempfile::tempdir().unwrap();
let mut kernel = draft_world(directory.path());
let topology = admit_topology(&mut kernel);
let active = activate(&mut kernel);
let active = kernel.snapshot().unwrap();
let entities_before = kernel.state.entities.clone();
let edges_before = kernel.state.edges.clone();
let receipt = submit_owner(
let receipt = submit_play(
&mut kernel,
&active,
admit(operations_of(vec![ComponentOp::Relocate {
@ -6840,18 +6742,18 @@ mod tests {
)
.unwrap();
let topology = admit_topology(&mut kernel);
let active = activate(&mut kernel);
let active = kernel.snapshot().unwrap();
let envelope = command(
&active,
CommandId::new(),
CallerId::Principal(owner()),
CallerId::Play,
admit(operations_of(vec![ComponentOp::Relocate {
subject: Ref::Existing(topology.walker),
via: Ref::Existing(topology.ramp),
}])),
);
kernel
.submit(envelope.clone(), &auth_principal(owner()))
.submit(envelope.clone(), &AuthenticatedCaller::verified_play())
.unwrap();
let committed = kernel.snapshot().unwrap();
let world_id = committed.world_id;
@ -6866,7 +6768,7 @@ mod tests {
})
);
assert!(matches!(
reopened.submit(envelope, &auth_principal(owner())).unwrap(),
reopened.submit(envelope, &AuthenticatedCaller::verified_play()).unwrap(),
SubmitReceipt::AlreadyApplied(_)
));
}
@ -6953,7 +6855,7 @@ mod tests {
let envelope = command(
&before,
CommandId::new(),
CallerId::Principal(owner()),
CallerId::Play,
admit(patch_of(vec![
entity("rhythm-road", "The Rhythm Road", EntityKind::Place),
institution(
@ -6965,7 +6867,7 @@ mod tests {
])),
);
kernel
.submit(envelope.clone(), &auth_principal(owner()))
.submit(envelope.clone(), &AuthenticatedCaller::verified_play())
.unwrap();
let committed = kernel.snapshot().unwrap();
let world_id = committed.world_id;
@ -6974,7 +6876,7 @@ mod tests {
let mut reopened = WorldKernel::open(&path, world_id).unwrap();
assert_eq!(reopened.snapshot().unwrap(), committed);
assert!(matches!(
reopened.submit(envelope, &auth_principal(owner())).unwrap(),
reopened.submit(envelope, &AuthenticatedCaller::verified_play()).unwrap(),
SubmitReceipt::AlreadyApplied(_)
));
}
@ -7003,7 +6905,7 @@ mod tests {
position: None,
import_key: None,
})]);
submit_owner(&mut kernel, &before, admit(patch.clone()));
submit_play(&mut kernel, &before, admit(patch.clone()));
let admitted = *kernel
.state
.subjects
@ -7041,7 +6943,7 @@ mod tests {
command(
&before,
command_id,
CallerId::Principal(owner()),
CallerId::Play,
admit(patch_of(vec![institution(
&kernel,
"rhythm-authority",
@ -7049,7 +6951,7 @@ mod tests {
Some(Ref::Draft(DraftHandle::new("kharad-rhythm-road"))),
)])),
),
&auth_principal(owner()),
&AuthenticatedCaller::verified_play(),
)
.unwrap_err();
assert!(matches!(error, KernelError::PatchRejected(_)));
@ -7173,7 +7075,7 @@ mod tests {
let forged_error = super::super::apply_effect(
&mut candidate,
CommandId::issue(),
&CallerId::Principal(owner()),
&CallerId::Play,
&super::super::WorldEffect::PatchAdmitted {
resolved: forged,
},
@ -7186,20 +7088,20 @@ mod tests {
super::super::apply_effect(
&mut candidate,
CommandId::issue(),
&CallerId::Principal(owner()),
&CallerId::Play,
&honest,
)
.unwrap();
let stale_error = super::super::apply_effect(
&mut candidate,
CommandId::issue(),
&CallerId::Principal(owner()),
&CallerId::Play,
&honest,
)
.unwrap_err();
assert!(matches!(stale_error, KernelError::Invariant(_)));
// A non-owner caller never reaches admission.
// A non-Play caller never reaches admission.
let mut candidate = kernel.state.clone();
let unauthorized = super::super::apply_effect(
&mut candidate,
@ -7208,7 +7110,7 @@ mod tests {
&honest,
)
.unwrap_err();
assert!(matches!(unauthorized, KernelError::Invariant(_)));
assert!(matches!(unauthorized, KernelError::Unauthorized));
assert_eq!(candidate, kernel.state);
}
@ -7226,13 +7128,13 @@ mod tests {
command(
&before,
CommandId::new(),
CallerId::Principal(owner()),
CallerId::Play,
admit(patch_of(vec![
entity("hollow", "The Hollow", EntityKind::Place),
route("noose", "The Noose", "hollow", "hollow", 4),
])),
),
&auth_principal(owner()),
&AuthenticatedCaller::verified_play(),
)
.unwrap_err();
let KernelError::PatchRejected(mismatches) = error else {
@ -7250,7 +7152,7 @@ mod tests {
// declared here rather than borrowed from a genesis accident.
let before = kernel.snapshot().unwrap();
let speak = speak_entry(&kernel);
submit_owner(
submit_play(
&mut kernel,
&before,
admit(patch_of(vec![Declaration::Subject(SubjectDeclaration {
@ -7263,7 +7165,7 @@ mod tests {
import_key: None,
})])),
);
let active = activate(&mut kernel);
let active = kernel.snapshot().unwrap();
let commits_before = kernel.journal.commit_count();
let unplaced = *kernel
.state
@ -7279,13 +7181,13 @@ mod tests {
command(
&active,
CommandId::new(),
CallerId::Principal(owner()),
CallerId::Play,
admit(operations_of(vec![ComponentOp::Relocate {
subject: Ref::Existing(unplaced),
via: Ref::Existing(topology.ramp),
}])),
),
&auth_principal(owner()),
&AuthenticatedCaller::verified_play(),
)
.unwrap_err();
let KernelError::PatchRejected(mismatches) = error else {
@ -7300,7 +7202,7 @@ mod tests {
command(
&active,
CommandId::new(),
CallerId::Principal(owner()),
CallerId::Play,
admit(operations_of(vec![
ComponentOp::OpenRoute {
route: Ref::Existing(topology.ramp),
@ -7314,7 +7216,7 @@ mod tests {
},
])),
),
&auth_principal(owner()),
&AuthenticatedCaller::verified_play(),
)
.unwrap_err();
let KernelError::PatchRejected(mismatches) = error else {
@ -7340,7 +7242,6 @@ mod tests {
let directory = tempfile::tempdir().unwrap();
let mut kernel = draft_world(directory.path());
let topology = admit_topology(&mut kernel);
activate(&mut kernel);
for edge_id in [topology.span, topology.shutter, topology.toll] {
let forged = super::super::WorldEffect::PatchAdmitted {
resolved: ResolvedPatch {
@ -7361,7 +7262,7 @@ mod tests {
let error = super::super::apply_effect(
&mut candidate,
CommandId::issue(),
&CallerId::Principal(owner()),
&CallerId::Play,
&forged,
)
.unwrap_err();