Close patch resolution before any canonical ID allocates
Cut: DraftSubjectHandle, validate_handle, NewDecisionSubject, GenesisSubjectBinding, canonicalize_subjects, issue_genesis, normalize_label, assignment_matches_new, the 116-line zip-and-compare body of WorldState::genesis, the non-test SubjectId/ControllerId/ AffordanceId::issue bodies, and the KernelError variants NoSubjects, EmptySubjectHandle, EmptySubjectLabel, DuplicateSubjectHandle, and NoAffordances. Add world/patch.rs: typed EntityId/EdgeId namespaces beside SubjectId, Ref<Id> with draft handles, WorldPatch declarations, uninhabited ComponentOp and PatchAnswer, and resolve_declarations as the one owner of handle indexing, kind checking, reference resolution, and allocation for both admission lanes. It returns the complete deterministic Vec<Mismatch> and allocates only after that set is empty, so a rejected patch mints nothing. IDs derive from sha256 over namespace, world ID, command ID, and handle, which is what lets journal replay recompute reduce() and require effect equality. CommandBody::AdmitPatch and WorldEffect::PatchAdmitted join the reducer; WorldCreated now carries the same ResolvedPatch payload, and both lanes mutate through one admit_resolved. WorldState gains entities and edges partitions, SubjectState gains authority_scope, and the state and commit schema strings move to foundation.v1 and foundation.v2, which refuses a pre-pass store rather than migrating it. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
parent
807ba24a89
commit
d74d6ad3d7
5 changed files with 1403 additions and 351 deletions
|
|
@ -3343,8 +3343,8 @@ mod tests {
|
|||
use super::*;
|
||||
use crate::world::{
|
||||
AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, ControllerId, CreateWorld,
|
||||
DecisionScope, DraftSubjectHandle, EventId, NewController, NewDecisionSubject, PrincipalId,
|
||||
SubjectKind, WorldId, WorldPhase,
|
||||
DecisionScope, Declaration, DraftHandle, EventId, NewController, PrincipalId,
|
||||
SubjectDeclaration, SubjectKind, WorldId, WorldPatch, WorldPhase,
|
||||
};
|
||||
use std::{
|
||||
collections::BTreeSet,
|
||||
|
|
@ -3898,13 +3898,18 @@ mod tests {
|
|||
id: CommandId::new(),
|
||||
owner: owner.clone(),
|
||||
title: "Controller Fixture".into(),
|
||||
subjects: vec![NewDecisionSubject {
|
||||
handle: DraftSubjectHandle::new("subject"),
|
||||
label: "Subject".into(),
|
||||
kind: SubjectKind::Person,
|
||||
controller,
|
||||
affordances: BTreeSet::from([AffordanceKind::Speak]),
|
||||
}],
|
||||
patch: WorldPatch {
|
||||
declarations: vec![Declaration::Subject(SubjectDeclaration {
|
||||
handle: DraftHandle::new("subject"),
|
||||
label: "Subject".into(),
|
||||
kind: SubjectKind::Person,
|
||||
controller,
|
||||
affordances: BTreeSet::from([AffordanceKind::Speak]),
|
||||
authority_scope: None,
|
||||
})],
|
||||
operations: Vec::new(),
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
},
|
||||
&authenticated,
|
||||
)
|
||||
|
|
@ -4468,31 +4473,38 @@ mod tests {
|
|||
id: CommandId::new(),
|
||||
owner: owner.clone(),
|
||||
title: "Midnight Roll Call".into(),
|
||||
subjects: vec![
|
||||
NewDecisionSubject {
|
||||
handle: DraftSubjectHandle::new("roll-caller"),
|
||||
label: "Iris, the midnight roll caller".into(),
|
||||
kind: SubjectKind::Person,
|
||||
controller: NewController::Human {
|
||||
principal: human.clone(),
|
||||
},
|
||||
affordances: BTreeSet::from([AffordanceKind::Speak]),
|
||||
},
|
||||
NewDecisionSubject {
|
||||
handle: DraftSubjectHandle::new("watch-officer"),
|
||||
label: "Mara, a watch officer who answers direct roll calls aloud in one short sentence".into(),
|
||||
kind: SubjectKind::Person,
|
||||
controller: NewController::NarrativePersona,
|
||||
affordances: BTreeSet::from([AffordanceKind::Speak]),
|
||||
},
|
||||
NewDecisionSubject {
|
||||
handle: DraftSubjectHandle::new("signal-council"),
|
||||
label: "The Signal Council, which answers direct roll calls aloud with one short operational sentence".into(),
|
||||
kind: SubjectKind::Institution,
|
||||
controller: NewController::OperationalAgent,
|
||||
affordances: BTreeSet::from([AffordanceKind::Speak]),
|
||||
},
|
||||
],
|
||||
patch: WorldPatch {
|
||||
declarations: vec![
|
||||
Declaration::Subject(SubjectDeclaration {
|
||||
handle: DraftHandle::new("roll-caller"),
|
||||
label: "Iris, the midnight roll caller".into(),
|
||||
kind: SubjectKind::Person,
|
||||
controller: NewController::Human {
|
||||
principal: human.clone(),
|
||||
},
|
||||
affordances: BTreeSet::from([AffordanceKind::Speak]),
|
||||
authority_scope: None,
|
||||
}),
|
||||
Declaration::Subject(SubjectDeclaration {
|
||||
handle: DraftHandle::new("watch-officer"),
|
||||
label: "Mara, a watch officer who answers direct roll calls aloud in one short sentence".into(),
|
||||
kind: SubjectKind::Person,
|
||||
controller: NewController::NarrativePersona,
|
||||
affordances: BTreeSet::from([AffordanceKind::Speak]),
|
||||
authority_scope: None,
|
||||
}),
|
||||
Declaration::Subject(SubjectDeclaration {
|
||||
handle: DraftHandle::new("signal-council"),
|
||||
label: "The Signal Council, which answers direct roll calls aloud with one short operational sentence".into(),
|
||||
kind: SubjectKind::Institution,
|
||||
controller: NewController::OperationalAgent,
|
||||
affordances: BTreeSet::from([AffordanceKind::Speak]),
|
||||
authority_scope: None,
|
||||
}),
|
||||
],
|
||||
operations: Vec::new(),
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
},
|
||||
&owner_caller,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -12,8 +12,8 @@ use std::{
|
|||
};
|
||||
use thiserror::Error;
|
||||
|
||||
const STATE_ROW: &str = "world_state.foundation.v0";
|
||||
const COMMIT_ROW: &str = "world_commit.foundation.v1";
|
||||
const STATE_ROW: &str = "world_state.foundation.v1";
|
||||
const COMMIT_ROW: &str = "world_commit.foundation.v2";
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub(super) enum JournalError {
|
||||
|
|
@ -445,13 +445,37 @@ fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> {
|
|||
"world ontology is empty or has split subject/controller ownership".into(),
|
||||
));
|
||||
}
|
||||
for entity in state.entities.values() {
|
||||
if !super::patch::is_canonical_text(&entity.label) {
|
||||
return Err(JournalError::Corrupt(
|
||||
"entity label is empty or noncanonical".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
if state.edges.values().any(|edge| {
|
||||
!state.entities.contains_key(&edge.from) || !state.entities.contains_key(&edge.to)
|
||||
}) {
|
||||
return Err(JournalError::Corrupt(
|
||||
"edge endpoint references an unknown entity".into(),
|
||||
));
|
||||
}
|
||||
let mut controller_ids = BTreeSet::new();
|
||||
for (subject_id, subject) in &state.subjects {
|
||||
if subject.label.trim().is_empty() || subject.label.trim() != subject.label {
|
||||
if !super::patch::is_canonical_text(&subject.label) {
|
||||
return Err(JournalError::Corrupt(
|
||||
"subject label is empty or noncanonical".into(),
|
||||
));
|
||||
}
|
||||
if let Some(entity_id) = subject.authority_scope
|
||||
&& state
|
||||
.entities
|
||||
.get(&entity_id)
|
||||
.is_none_or(|entity| entity.kind != super::EntityKind::Place)
|
||||
{
|
||||
return Err(JournalError::Corrupt(
|
||||
"subject authority scope does not name a canonical place".into(),
|
||||
));
|
||||
}
|
||||
let scope = super::DecisionScope {
|
||||
subject_id: *subject_id,
|
||||
};
|
||||
|
|
@ -611,8 +635,8 @@ mod tests {
|
|||
use super::*;
|
||||
use crate::world::{
|
||||
AffordanceKind, AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, CreateWorld,
|
||||
DraftSubjectHandle, NewController, NewDecisionSubject, PrincipalId, SubjectKind,
|
||||
WorldKernel,
|
||||
Declaration, DraftHandle, EntityDeclaration, EntityId, EntityKind, NewController,
|
||||
PrincipalId, Ref, SubjectDeclaration, SubjectKind, WorldKernel, WorldPatch,
|
||||
};
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
|
|
@ -620,6 +644,14 @@ mod tests {
|
|||
value: u8,
|
||||
}
|
||||
|
||||
fn owner_patch(subject: SubjectDeclaration) -> WorldPatch {
|
||||
WorldPatch {
|
||||
declarations: vec![Declaration::Subject(subject)],
|
||||
operations: Vec::new(),
|
||||
evidence: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_rejects_an_alternate_messagepack_shape() {
|
||||
let row = CultCacheEnvelope {
|
||||
|
|
@ -642,15 +674,16 @@ mod tests {
|
|||
id: CommandId::new(),
|
||||
owner: owner.clone(),
|
||||
title: "Before".into(),
|
||||
subjects: vec![NewDecisionSubject {
|
||||
handle: DraftSubjectHandle::new("owner"),
|
||||
patch: owner_patch(SubjectDeclaration {
|
||||
handle: DraftHandle::new("owner"),
|
||||
label: "Owner".into(),
|
||||
kind: SubjectKind::Person,
|
||||
controller: NewController::Human {
|
||||
principal: owner.clone(),
|
||||
},
|
||||
affordances: BTreeSet::from([AffordanceKind::Speak]),
|
||||
}],
|
||||
authority_scope: None,
|
||||
}),
|
||||
};
|
||||
let (mut kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap();
|
||||
let snapshot = kernel.snapshot().unwrap();
|
||||
|
|
@ -711,6 +744,82 @@ mod tests {
|
|||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_forged_patch_effect_does_not_apply() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("world.cc");
|
||||
let owner = PrincipalId::new("owner@example.test");
|
||||
let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone()));
|
||||
let creation = CreateWorld {
|
||||
id: CommandId::new(),
|
||||
owner: owner.clone(),
|
||||
title: "Kharad".into(),
|
||||
patch: owner_patch(SubjectDeclaration {
|
||||
handle: DraftHandle::new("owner"),
|
||||
label: "Owner".into(),
|
||||
kind: SubjectKind::Person,
|
||||
controller: NewController::Human {
|
||||
principal: owner.clone(),
|
||||
},
|
||||
affordances: BTreeSet::from([AffordanceKind::Speak]),
|
||||
authority_scope: None,
|
||||
}),
|
||||
};
|
||||
let (mut kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap();
|
||||
let snapshot = kernel.snapshot().unwrap();
|
||||
let command_id = CommandId::new();
|
||||
kernel
|
||||
.submit(
|
||||
CommandEnvelope {
|
||||
id: command_id,
|
||||
world_id: snapshot.world_id,
|
||||
expected_revision: snapshot.revision,
|
||||
caller: CallerId::Principal(owner),
|
||||
body: CommandBody::AdmitPatch {
|
||||
answers: None,
|
||||
patch: WorldPatch {
|
||||
declarations: vec![
|
||||
Declaration::Entity(EntityDeclaration {
|
||||
handle: DraftHandle::new("rhythm-road"),
|
||||
label: "The Rhythm Road".into(),
|
||||
kind: EntityKind::Place,
|
||||
}),
|
||||
Declaration::Subject(SubjectDeclaration {
|
||||
handle: DraftHandle::new("rhythm-authority"),
|
||||
label: "The Rhythm Authority".into(),
|
||||
kind: SubjectKind::Institution,
|
||||
controller: NewController::OperationalAgent,
|
||||
affordances: BTreeSet::from([AffordanceKind::Speak]),
|
||||
authority_scope: Some(Ref::Draft(DraftHandle::new(
|
||||
"rhythm-road",
|
||||
))),
|
||||
}),
|
||||
],
|
||||
operations: Vec::new(),
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
},
|
||||
},
|
||||
&authenticated,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
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::PatchAdmitted { resolved } = &mut forged.effect else {
|
||||
panic!("expected an admitted patch effect");
|
||||
};
|
||||
resolved.subjects[0].subject.authority_scope = Some(EntityId::issue());
|
||||
forged.digest = commit_digest(forged).unwrap();
|
||||
forged_head.last_commit_digest = Some(forged.digest.clone());
|
||||
|
||||
assert!(matches!(
|
||||
verify_history(&forged_head, &forged_commits),
|
||||
Err(JournalError::Corrupt(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replay_rejects_genesis_that_does_not_derive_from_its_creation_command() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
|
|
@ -722,13 +831,14 @@ mod tests {
|
|||
id: creation_id,
|
||||
owner: owner.clone(),
|
||||
title: "Admitted".into(),
|
||||
subjects: vec![NewDecisionSubject {
|
||||
handle: DraftSubjectHandle::new("owner"),
|
||||
patch: owner_patch(SubjectDeclaration {
|
||||
handle: DraftHandle::new("owner"),
|
||||
label: "Owner".into(),
|
||||
kind: SubjectKind::Person,
|
||||
controller: NewController::Human { principal: owner },
|
||||
affordances: BTreeSet::from([AffordanceKind::Speak]),
|
||||
}],
|
||||
authority_scope: None,
|
||||
}),
|
||||
};
|
||||
let (kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap();
|
||||
let mut forged_head = kernel.state.clone();
|
||||
|
|
@ -749,10 +859,10 @@ mod tests {
|
|||
let mut binding_forged_head = kernel.state.clone();
|
||||
let mut binding_forged_commits = kernel.journal.commits.clone();
|
||||
let binding_forged = binding_forged_commits.get_mut(&creation_id).unwrap();
|
||||
let WorldEffect::WorldCreated { bindings, .. } = &mut binding_forged.effect else {
|
||||
let WorldEffect::WorldCreated { resolved, .. } = &mut binding_forged.effect else {
|
||||
panic!("expected genesis effect");
|
||||
};
|
||||
bindings[0].subject.label = "Not the creation subject".into();
|
||||
resolved.subjects[0].subject.label = "Not the creation subject".into();
|
||||
binding_forged.digest = commit_digest(binding_forged).unwrap();
|
||||
binding_forged_head.last_commit_digest = Some(binding_forged.digest.clone());
|
||||
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
use super::{
|
||||
AffordanceKind, AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, CommandId,
|
||||
CreateWorld, CreateWorldIntent, CreationReceipt, DecisionInvocation, DecisionOpportunity,
|
||||
DraftSubjectHandle, KernelError, NewController, NewDecisionSubject, PrincipalCommandIntent,
|
||||
PrincipalId, SubjectKind, SubmitReceipt, WorldKernel, WorldSnapshot, journal, prepare_creation,
|
||||
Declaration, DraftHandle, KernelError, NewController, PrincipalCommandIntent, PrincipalId,
|
||||
SubjectDeclaration, SubjectKind, SubmitReceipt, WorldKernel, WorldPatch, WorldSnapshot,
|
||||
journal, prepare_creation,
|
||||
};
|
||||
use crate::app_session::VerifiedPrincipalEvidence;
|
||||
use std::collections::BTreeSet;
|
||||
|
|
@ -79,39 +80,52 @@ impl WorldMailbox {
|
|||
principal: &VerifiedPrincipalEvidence,
|
||||
) -> Result<CreationReceipt, MailboxError> {
|
||||
let principal_id = PrincipalId::new(principal.account_subject_hash());
|
||||
let mut subjects = vec![NewDecisionSubject {
|
||||
handle: DraftSubjectHandle::new("first-person"),
|
||||
label: input.human_subject_label,
|
||||
kind: SubjectKind::Person,
|
||||
controller: NewController::Human {
|
||||
// Ingress owns label normalization; the reducer only admits canonical
|
||||
// labels.
|
||||
let declare = |handle: &str, label: String, kind, controller| {
|
||||
Declaration::Subject(SubjectDeclaration {
|
||||
handle: DraftHandle::new(handle),
|
||||
label: label.trim().to_owned(),
|
||||
kind,
|
||||
controller,
|
||||
affordances: BTreeSet::from([AffordanceKind::Speak]),
|
||||
authority_scope: None,
|
||||
})
|
||||
};
|
||||
let mut declarations = vec![declare(
|
||||
"first-person",
|
||||
input.human_subject_label,
|
||||
SubjectKind::Person,
|
||||
NewController::Human {
|
||||
principal: principal_id.clone(),
|
||||
},
|
||||
affordances: BTreeSet::from([AffordanceKind::Speak]),
|
||||
}];
|
||||
)];
|
||||
if let Some(label) = input.narrative_persona_label {
|
||||
subjects.push(NewDecisionSubject {
|
||||
handle: DraftSubjectHandle::new("narrative-persona"),
|
||||
declarations.push(declare(
|
||||
"narrative-persona",
|
||||
label,
|
||||
kind: SubjectKind::Person,
|
||||
controller: NewController::NarrativePersona,
|
||||
affordances: BTreeSet::from([AffordanceKind::Speak]),
|
||||
});
|
||||
SubjectKind::Person,
|
||||
NewController::NarrativePersona,
|
||||
));
|
||||
}
|
||||
if let Some(label) = input.operational_agent_label {
|
||||
subjects.push(NewDecisionSubject {
|
||||
handle: DraftSubjectHandle::new("operational-agent"),
|
||||
declarations.push(declare(
|
||||
"operational-agent",
|
||||
label,
|
||||
kind: SubjectKind::Institution,
|
||||
controller: NewController::OperationalAgent,
|
||||
affordances: BTreeSet::from([AffordanceKind::Speak]),
|
||||
});
|
||||
SubjectKind::Institution,
|
||||
NewController::OperationalAgent,
|
||||
));
|
||||
}
|
||||
self.create_authenticated(
|
||||
CreateWorld {
|
||||
id: input.id,
|
||||
owner: principal_id.clone(),
|
||||
title: input.title,
|
||||
subjects,
|
||||
patch: WorldPatch {
|
||||
declarations,
|
||||
operations: Vec::new(),
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
},
|
||||
AuthenticatedCaller::verified_principal(principal_id),
|
||||
)
|
||||
|
|
@ -432,8 +446,8 @@ async fn run_owner(mut owned: OwnedWorld, mut receiver: mpsc::Receiver<Request>)
|
|||
mod tests {
|
||||
use super::*;
|
||||
use crate::world::{
|
||||
AffordanceKind, CallerId, CommandBody, DraftSubjectHandle, NewController,
|
||||
NewDecisionSubject, PrincipalId, SubjectKind, WorldId,
|
||||
AffordanceKind, CallerId, CommandBody, Declaration, DraftHandle, Mismatch, NewController,
|
||||
PrincipalId, SubjectDeclaration, SubjectKind, WorldId,
|
||||
};
|
||||
use std::{collections::BTreeSet, path::PathBuf};
|
||||
use tempfile::TempDir;
|
||||
|
|
@ -447,15 +461,20 @@ mod tests {
|
|||
id,
|
||||
owner: PrincipalId::new("owner"),
|
||||
title: title.into(),
|
||||
subjects: vec![NewDecisionSubject {
|
||||
handle: DraftSubjectHandle::new("operator"),
|
||||
label: "Operator".into(),
|
||||
kind: SubjectKind::Person,
|
||||
controller: NewController::Human {
|
||||
principal: PrincipalId::new("owner"),
|
||||
},
|
||||
affordances: BTreeSet::from([AffordanceKind::Speak]),
|
||||
}],
|
||||
patch: WorldPatch {
|
||||
declarations: vec![Declaration::Subject(SubjectDeclaration {
|
||||
handle: DraftHandle::new("operator"),
|
||||
label: "Operator".into(),
|
||||
kind: SubjectKind::Person,
|
||||
controller: NewController::Human {
|
||||
principal: PrincipalId::new("owner"),
|
||||
},
|
||||
affordances: BTreeSet::from([AffordanceKind::Speak]),
|
||||
authority_scope: None,
|
||||
})],
|
||||
operations: Vec::new(),
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -532,11 +551,21 @@ mod tests {
|
|||
let authenticated = authenticated_owner();
|
||||
let (mailbox, task) = WorldMailbox::open(&path).unwrap();
|
||||
let mut invalid = creation(CommandId::new(), "Invalid");
|
||||
invalid.subjects.push(invalid.subjects[0].clone());
|
||||
assert!(matches!(
|
||||
mailbox.create_fixture(invalid, &authenticated).await,
|
||||
Err(MailboxError::Kernel(KernelError::DuplicateSubjectHandle))
|
||||
));
|
||||
invalid
|
||||
.patch
|
||||
.declarations
|
||||
.push(invalid.patch.declarations[0].clone());
|
||||
let Err(MailboxError::Kernel(KernelError::PatchRejected(rejected))) =
|
||||
mailbox.create_fixture(invalid, &authenticated).await
|
||||
else {
|
||||
panic!("expected a rejected creation patch");
|
||||
};
|
||||
assert_eq!(
|
||||
rejected,
|
||||
vec![Mismatch::DuplicateHandle {
|
||||
handle: DraftHandle::new("operator")
|
||||
}]
|
||||
);
|
||||
assert!(matches!(
|
||||
mailbox.snapshot().await,
|
||||
Err(MailboxError::Kernel(KernelError::WorldNotCreated))
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@
|
|||
mod controllers;
|
||||
mod journal;
|
||||
mod mailbox;
|
||||
mod patch;
|
||||
|
||||
pub(crate) use controllers::{
|
||||
ControllerError, ControllerModels, ControllerOpenError, ControllerPendingReason,
|
||||
|
|
@ -16,6 +17,11 @@ pub(crate) use controllers::{
|
|||
SourceRange, SubmissionDisposition, TranslationGapSummary,
|
||||
};
|
||||
pub(crate) use mailbox::{MailboxError, WorldMailbox};
|
||||
pub(crate) use patch::{
|
||||
Declaration, DraftHandle, EntityDeclaration, EntityKind, Mismatch, PatchAnswer, Ref,
|
||||
SubjectDeclaration, WorldPatch,
|
||||
};
|
||||
use patch::{EdgeRecord, EntityRecord, ResolvedPatch};
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
|
@ -26,8 +32,8 @@ use std::path::Path;
|
|||
use thiserror::Error;
|
||||
use uuid::Uuid;
|
||||
|
||||
const STATE_SCHEMA: &str = "ghostlight.world_state.foundation.v0";
|
||||
const COMMIT_SCHEMA: &str = "ghostlight.world_commit.foundation.v1";
|
||||
const STATE_SCHEMA: &str = "ghostlight.world_state.foundation.v1";
|
||||
const COMMIT_SCHEMA: &str = "ghostlight.world_commit.foundation.v2";
|
||||
|
||||
macro_rules! opaque_uuid {
|
||||
($name:ident) => {
|
||||
|
|
@ -42,6 +48,8 @@ macro_rules! opaque_uuid {
|
|||
opaque_uuid!(WorldId);
|
||||
opaque_uuid!(CommandId);
|
||||
opaque_uuid!(SubjectId);
|
||||
opaque_uuid!(EntityId);
|
||||
opaque_uuid!(EdgeId);
|
||||
opaque_uuid!(ControllerId);
|
||||
opaque_uuid!(AffordanceId);
|
||||
opaque_uuid!(EventId);
|
||||
|
|
@ -76,18 +84,31 @@ impl WorldId {
|
|||
}
|
||||
}
|
||||
|
||||
// Subject, entity, controller, and affordance IDs are derived, never drawn.
|
||||
// `patch::derive_id` is the only allocator; these fixtures exist so tests can
|
||||
// name an ID that no partition holds.
|
||||
#[cfg(test)]
|
||||
impl SubjectId {
|
||||
fn issue() -> Self {
|
||||
Self(Uuid::new_v4())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl EntityId {
|
||||
fn issue() -> Self {
|
||||
Self(Uuid::new_v4())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl ControllerId {
|
||||
fn issue() -> Self {
|
||||
Self(Uuid::new_v4())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl AffordanceId {
|
||||
fn issue() -> Self {
|
||||
Self(Uuid::new_v4())
|
||||
|
|
@ -110,16 +131,6 @@ impl PrincipalId {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[serde(transparent)]
|
||||
struct DraftSubjectHandle(String);
|
||||
|
||||
impl DraftSubjectHandle {
|
||||
fn new(value: impl Into<String>) -> Self {
|
||||
Self(value.into())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(crate) enum WorldPhase {
|
||||
|
|
@ -151,27 +162,18 @@ pub(crate) enum AffordanceKind {
|
|||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
enum NewController {
|
||||
pub(crate) enum NewController {
|
||||
Human { principal: PrincipalId },
|
||||
NarrativePersona,
|
||||
OperationalAgent,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
struct NewDecisionSubject {
|
||||
handle: DraftSubjectHandle,
|
||||
label: String,
|
||||
kind: SubjectKind,
|
||||
controller: NewController,
|
||||
affordances: BTreeSet<AffordanceKind>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
struct CreateWorld {
|
||||
id: CommandId,
|
||||
owner: PrincipalId,
|
||||
title: String,
|
||||
subjects: Vec<NewDecisionSubject>,
|
||||
patch: WorldPatch,
|
||||
}
|
||||
|
||||
/// Unattributed creation intent. World ingress derives ownership, controller
|
||||
|
|
@ -292,12 +294,19 @@ pub(crate) enum CommandBody {
|
|||
DeclineDecision {
|
||||
opportunity: DecisionOpportunity,
|
||||
},
|
||||
AdmitPatch {
|
||||
/// Structurally `None` until boundary answers exist: `PatchAnswer` is
|
||||
/// uninhabited.
|
||||
answers: Option<PatchAnswer>,
|
||||
patch: WorldPatch,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
struct SubjectState {
|
||||
label: String,
|
||||
kind: SubjectKind,
|
||||
authority_scope: Option<EntityId>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
|
|
@ -374,6 +383,8 @@ struct WorldState {
|
|||
title: String,
|
||||
draft_approvals: BTreeSet<PrincipalId>,
|
||||
subjects: BTreeMap<SubjectId, SubjectState>,
|
||||
entities: BTreeMap<EntityId, EntityRecord>,
|
||||
edges: BTreeMap<EdgeId, EdgeRecord>,
|
||||
controller_assignments: BTreeMap<DecisionScope, ControllerAssignment>,
|
||||
affordance_grants: BTreeMap<AffordanceId, AffordanceGrant>,
|
||||
events: Vec<DecisionEvent>,
|
||||
|
|
@ -381,22 +392,16 @@ struct WorldState {
|
|||
last_commit_digest: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
struct GenesisSubjectBinding {
|
||||
handle: DraftSubjectHandle,
|
||||
subject_id: SubjectId,
|
||||
subject: SubjectState,
|
||||
controller: ControllerAssignment,
|
||||
affordances: BTreeMap<AffordanceId, AffordanceGrant>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
enum WorldEffect {
|
||||
WorldCreated {
|
||||
owner: PrincipalId,
|
||||
title: String,
|
||||
bindings: Vec<GenesisSubjectBinding>,
|
||||
resolved: ResolvedPatch,
|
||||
},
|
||||
PatchAdmitted {
|
||||
resolved: ResolvedPatch,
|
||||
},
|
||||
DraftApproved {
|
||||
principal: PrincipalId,
|
||||
|
|
@ -542,16 +547,8 @@ pub(crate) enum KernelError {
|
|||
EmptyTitle,
|
||||
#[error("world owner or human controller principal must be canonical and nonempty")]
|
||||
EmptyPrincipal,
|
||||
#[error("world creation requires at least one decision subject")]
|
||||
NoSubjects,
|
||||
#[error("decision subject handle must be canonical and nonempty")]
|
||||
EmptySubjectHandle,
|
||||
#[error("decision subject label must not be empty")]
|
||||
EmptySubjectLabel,
|
||||
#[error("decision subject handles must be unique")]
|
||||
DuplicateSubjectHandle,
|
||||
#[error("every decision subject requires at least one affordance")]
|
||||
NoAffordances,
|
||||
#[error("patch rejected: {0:?}")]
|
||||
PatchRejected(Vec<Mismatch>),
|
||||
#[error("spoken action must not be empty")]
|
||||
EmptySpeech,
|
||||
#[error("command targets another world")]
|
||||
|
|
@ -639,9 +636,10 @@ struct WorldKernel {
|
|||
|
||||
struct PreparedCreation {
|
||||
command: CreateWorld,
|
||||
world_id: WorldId,
|
||||
owner: PrincipalId,
|
||||
title: String,
|
||||
subjects: Vec<NewDecisionSubject>,
|
||||
resolved: ResolvedPatch,
|
||||
}
|
||||
|
||||
fn prepare_creation(
|
||||
|
|
@ -655,12 +653,24 @@ fn prepare_creation(
|
|||
if &input.owner != authenticated_principal {
|
||||
return Err(KernelError::AuthenticationMismatch);
|
||||
}
|
||||
let subjects = canonicalize_subjects(&input.subjects)?;
|
||||
let title = normalize_title(&input.title)?;
|
||||
// The world's own identity is not world structure, and it feeds every
|
||||
// derived ID, so it is minted before resolution rather than by it.
|
||||
let world_id = WorldId::issue();
|
||||
let resolved = patch::resolve_declarations(
|
||||
&BTreeMap::new(),
|
||||
&BTreeMap::new(),
|
||||
world_id,
|
||||
input.id,
|
||||
&input.patch,
|
||||
true,
|
||||
)
|
||||
.map_err(KernelError::PatchRejected)?;
|
||||
Ok(PreparedCreation {
|
||||
world_id,
|
||||
owner: input.owner.clone(),
|
||||
title,
|
||||
subjects,
|
||||
resolved,
|
||||
command: input,
|
||||
})
|
||||
}
|
||||
|
|
@ -670,8 +680,12 @@ impl WorldKernel {
|
|||
empty: journal::EmptyWorldJournal,
|
||||
prepared: PreparedCreation,
|
||||
) -> Result<(Self, CreationReceipt), KernelError> {
|
||||
let world_id = WorldId::issue();
|
||||
let effect = issue_genesis(prepared.owner, prepared.title, prepared.subjects);
|
||||
let world_id = prepared.world_id;
|
||||
let effect = WorldEffect::WorldCreated {
|
||||
owner: prepared.owner,
|
||||
title: prepared.title,
|
||||
resolved: prepared.resolved,
|
||||
};
|
||||
let mut state = WorldState::genesis(world_id, &prepared.command, &effect)?;
|
||||
let mut genesis = WorldCommit {
|
||||
schema: COMMIT_SCHEMA.into(),
|
||||
|
|
@ -932,9 +946,30 @@ fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result<WorldEffect,
|
|||
opportunity: current,
|
||||
})
|
||||
}
|
||||
CommandBody::AdmitPatch { answers: _, patch } => {
|
||||
require_phase(state, WorldPhase::Draft)?;
|
||||
require_owner(state, &command.caller)?;
|
||||
let resolved = patch::resolve_declarations(
|
||||
&state.subjects,
|
||||
&state.entities,
|
||||
state.world_id,
|
||||
command.id,
|
||||
patch,
|
||||
admits_human(state),
|
||||
)
|
||||
.map_err(KernelError::PatchRejected)?;
|
||||
Ok(WorldEffect::PatchAdmitted { resolved })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A human principal joins `required_approvers`, so only the lane that builds
|
||||
/// revision 0 from nothing may bind one. The predicate reads state, never the
|
||||
/// caller.
|
||||
fn admits_human(state: &WorldState) -> bool {
|
||||
state.revision == 0 && state.subjects.is_empty()
|
||||
}
|
||||
|
||||
impl WorldState {
|
||||
fn genesis(
|
||||
world_id: WorldId,
|
||||
|
|
@ -944,7 +979,7 @@ impl WorldState {
|
|||
let WorldEffect::WorldCreated {
|
||||
owner,
|
||||
title,
|
||||
bindings,
|
||||
resolved,
|
||||
} = effect
|
||||
else {
|
||||
return Err(KernelError::Invariant(
|
||||
|
|
@ -953,85 +988,27 @@ impl WorldState {
|
|||
};
|
||||
validate_principal(&command.owner)?;
|
||||
let expected_title = normalize_title(&command.title)?;
|
||||
let expected_subjects = canonicalize_subjects(&command.subjects)?;
|
||||
if owner != &command.owner
|
||||
|| title != &expected_title
|
||||
|| bindings.len() != expected_subjects.len()
|
||||
{
|
||||
if owner != &command.owner || title != &expected_title {
|
||||
return Err(KernelError::Invariant(
|
||||
"genesis effect does not match the admitted creation command".into(),
|
||||
));
|
||||
}
|
||||
|
||||
let mut handles = BTreeSet::new();
|
||||
let mut subjects = BTreeMap::new();
|
||||
let mut assignments = BTreeMap::new();
|
||||
let mut controller_ids = BTreeSet::new();
|
||||
let mut grants = BTreeMap::new();
|
||||
let mut scope_kinds = BTreeSet::new();
|
||||
for (binding, expected) in bindings.iter().zip(&expected_subjects) {
|
||||
let affordance_kinds: BTreeSet<_> = binding
|
||||
.affordances
|
||||
.values()
|
||||
.map(|grant| grant.kind)
|
||||
.collect();
|
||||
if binding.handle != expected.handle
|
||||
|| binding.subject.label != expected.label
|
||||
|| binding.subject.kind != expected.kind
|
||||
|| !assignment_matches_new(&binding.controller, &expected.controller)
|
||||
|| binding.affordances.len() != expected.affordances.len()
|
||||
|| affordance_kinds != expected.affordances
|
||||
{
|
||||
return Err(KernelError::Invariant(
|
||||
"genesis binding does not derive from its creation subject".into(),
|
||||
));
|
||||
}
|
||||
validate_handle(&binding.handle)?;
|
||||
if !handles.insert(binding.handle.clone()) {
|
||||
return Err(KernelError::DuplicateSubjectHandle);
|
||||
}
|
||||
if normalize_label(&binding.subject.label)? != binding.subject.label {
|
||||
return Err(KernelError::Invariant(
|
||||
"genesis subject label is not canonical".into(),
|
||||
));
|
||||
}
|
||||
let scope = DecisionScope {
|
||||
subject_id: binding.subject_id,
|
||||
};
|
||||
validate_assignment(&binding.controller)?;
|
||||
if !controller_ids.insert(binding.controller.id()) {
|
||||
return Err(KernelError::Invariant(
|
||||
"genesis controller ID collision".into(),
|
||||
));
|
||||
}
|
||||
if binding.affordances.is_empty() {
|
||||
return Err(KernelError::NoAffordances);
|
||||
}
|
||||
if subjects
|
||||
.insert(binding.subject_id, binding.subject.clone())
|
||||
.is_some()
|
||||
|| assignments
|
||||
.insert(scope, binding.controller.clone())
|
||||
.is_some()
|
||||
{
|
||||
return Err(KernelError::Invariant(
|
||||
"genesis subject or scope ID collision".into(),
|
||||
));
|
||||
}
|
||||
for (affordance_id, grant) in &binding.affordances {
|
||||
if grant.scope != scope {
|
||||
return Err(KernelError::Invariant(
|
||||
"genesis affordance is bound to another scope".into(),
|
||||
));
|
||||
}
|
||||
if !scope_kinds.insert((scope, grant.kind))
|
||||
|| grants.insert(*affordance_id, grant.clone()).is_some()
|
||||
{
|
||||
return Err(KernelError::Invariant(
|
||||
"genesis affordance ID or kind collision".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
// The same re-derive-and-compare that `apply_committed_command` runs for
|
||||
// every other command. Deterministic allocation is what lets one
|
||||
// equality replace a field-by-field binding zip.
|
||||
let expected = patch::resolve_declarations(
|
||||
&BTreeMap::new(),
|
||||
&BTreeMap::new(),
|
||||
world_id,
|
||||
command.id,
|
||||
&command.patch,
|
||||
true,
|
||||
)
|
||||
.map_err(KernelError::PatchRejected)?;
|
||||
if &expected != resolved {
|
||||
return Err(KernelError::Invariant(
|
||||
"genesis effect does not derive from its creation command".into(),
|
||||
));
|
||||
}
|
||||
|
||||
let mut state = Self {
|
||||
|
|
@ -1042,93 +1019,120 @@ impl WorldState {
|
|||
owner: owner.clone(),
|
||||
title: title.clone(),
|
||||
draft_approvals: BTreeSet::new(),
|
||||
subjects,
|
||||
controller_assignments: assignments,
|
||||
affordance_grants: grants,
|
||||
subjects: BTreeMap::new(),
|
||||
entities: BTreeMap::new(),
|
||||
edges: BTreeMap::new(),
|
||||
controller_assignments: BTreeMap::new(),
|
||||
affordance_grants: BTreeMap::new(),
|
||||
events: Vec::new(),
|
||||
state_digest: String::new(),
|
||||
last_commit_digest: None,
|
||||
};
|
||||
admit_resolved(&mut state, resolved)?;
|
||||
state.state_digest = state_digest(&state)?;
|
||||
Ok(state)
|
||||
}
|
||||
}
|
||||
|
||||
fn canonicalize_subjects(
|
||||
inputs: &[NewDecisionSubject],
|
||||
) -> Result<Vec<NewDecisionSubject>, KernelError> {
|
||||
if inputs.is_empty() {
|
||||
return Err(KernelError::NoSubjects);
|
||||
/// The only writer of the subject, entity, controller, and grant partitions.
|
||||
/// Both admission lanes mutate through it, and it re-derives every structural
|
||||
/// claim from `state`, so an effect that skipped resolution dies here.
|
||||
fn admit_resolved(state: &mut WorldState, resolved: &ResolvedPatch) -> Result<(), KernelError> {
|
||||
if resolved.subjects.is_empty() && resolved.entities.is_empty() {
|
||||
return Err(KernelError::Invariant(
|
||||
"admitted patch carries no canonical change".into(),
|
||||
));
|
||||
}
|
||||
let mut handles = BTreeSet::new();
|
||||
let mut result = Vec::with_capacity(inputs.len());
|
||||
for input in inputs {
|
||||
validate_handle(&input.handle)?;
|
||||
if !handles.insert(input.handle.clone()) {
|
||||
return Err(KernelError::DuplicateSubjectHandle);
|
||||
let humans_admitted = admits_human(state);
|
||||
for entity in &resolved.entities {
|
||||
if !patch::is_canonical_text(&entity.entity.label) {
|
||||
return Err(KernelError::Invariant(
|
||||
"admitted entity label is not canonical".into(),
|
||||
));
|
||||
}
|
||||
if input.affordances.is_empty() {
|
||||
return Err(KernelError::NoAffordances);
|
||||
if state
|
||||
.entities
|
||||
.insert(entity.entity_id, entity.entity.clone())
|
||||
.is_some()
|
||||
{
|
||||
return Err(KernelError::Invariant(
|
||||
"admitted entity ID collision".into(),
|
||||
));
|
||||
}
|
||||
if let NewController::Human { principal } = &input.controller {
|
||||
validate_principal(principal)?;
|
||||
}
|
||||
result.push(NewDecisionSubject {
|
||||
handle: input.handle.clone(),
|
||||
label: normalize_label(&input.label)?,
|
||||
kind: input.kind,
|
||||
controller: input.controller.clone(),
|
||||
affordances: input.affordances.clone(),
|
||||
});
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn issue_genesis(
|
||||
owner: PrincipalId,
|
||||
title: String,
|
||||
subjects: Vec<NewDecisionSubject>,
|
||||
) -> WorldEffect {
|
||||
let bindings = subjects
|
||||
.into_iter()
|
||||
.map(|input| {
|
||||
let subject_id = SubjectId::issue();
|
||||
let scope = DecisionScope { subject_id };
|
||||
let controller_id = ControllerId::issue();
|
||||
let controller = match input.controller {
|
||||
NewController::Human { principal } => ControllerAssignment::Human {
|
||||
controller_id,
|
||||
principal,
|
||||
},
|
||||
NewController::NarrativePersona => {
|
||||
ControllerAssignment::NarrativePersona { controller_id }
|
||||
}
|
||||
NewController::OperationalAgent => {
|
||||
ControllerAssignment::OperationalAgent { controller_id }
|
||||
}
|
||||
};
|
||||
let affordances = input
|
||||
.affordances
|
||||
.into_iter()
|
||||
.map(|kind| (AffordanceId::issue(), AffordanceGrant { scope, kind }))
|
||||
.collect();
|
||||
GenesisSubjectBinding {
|
||||
handle: input.handle,
|
||||
subject_id,
|
||||
subject: SubjectState {
|
||||
label: input.label,
|
||||
kind: input.kind,
|
||||
},
|
||||
controller,
|
||||
affordances,
|
||||
}
|
||||
})
|
||||
let mut controller_ids: BTreeSet<ControllerId> = state
|
||||
.controller_assignments
|
||||
.values()
|
||||
.map(ControllerAssignment::id)
|
||||
.collect();
|
||||
WorldEffect::WorldCreated {
|
||||
owner,
|
||||
title,
|
||||
bindings,
|
||||
let mut scope_kinds: BTreeSet<(DecisionScope, AffordanceKind)> = state
|
||||
.affordance_grants
|
||||
.values()
|
||||
.map(|grant| (grant.scope, grant.kind))
|
||||
.collect();
|
||||
for subject in &resolved.subjects {
|
||||
let scope = DecisionScope {
|
||||
subject_id: subject.subject_id,
|
||||
};
|
||||
if !patch::is_canonical_text(&subject.subject.label) {
|
||||
return Err(KernelError::Invariant(
|
||||
"admitted subject label is not canonical".into(),
|
||||
));
|
||||
}
|
||||
validate_assignment(&subject.controller)?;
|
||||
if matches!(subject.controller, ControllerAssignment::Human { .. }) && !humans_admitted {
|
||||
return Err(KernelError::Invariant(
|
||||
"only world genesis may bind a human controller".into(),
|
||||
));
|
||||
}
|
||||
if subject.affordances.is_empty() {
|
||||
return Err(KernelError::Invariant(
|
||||
"admitted subject has no affordance".into(),
|
||||
));
|
||||
}
|
||||
if let Some(entity_id) = subject.subject.authority_scope
|
||||
&& state
|
||||
.entities
|
||||
.get(&entity_id)
|
||||
.is_none_or(|entity| entity.kind != EntityKind::Place)
|
||||
{
|
||||
return Err(KernelError::Invariant(
|
||||
"admitted authority scope does not name a canonical place".into(),
|
||||
));
|
||||
}
|
||||
if !controller_ids.insert(subject.controller.id()) {
|
||||
return Err(KernelError::Invariant(
|
||||
"admitted controller ID collision".into(),
|
||||
));
|
||||
}
|
||||
if state
|
||||
.subjects
|
||||
.insert(subject.subject_id, subject.subject.clone())
|
||||
.is_some()
|
||||
|| state
|
||||
.controller_assignments
|
||||
.insert(scope, subject.controller.clone())
|
||||
.is_some()
|
||||
{
|
||||
return Err(KernelError::Invariant(
|
||||
"admitted subject or scope ID collision".into(),
|
||||
));
|
||||
}
|
||||
for (affordance_id, grant) in &subject.affordances {
|
||||
if grant.scope != scope
|
||||
|| !scope_kinds.insert((scope, grant.kind))
|
||||
|| state
|
||||
.affordance_grants
|
||||
.insert(*affordance_id, grant.clone())
|
||||
.is_some()
|
||||
{
|
||||
return Err(KernelError::Invariant(
|
||||
"admitted affordance is unscoped or collides".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> {
|
||||
|
|
@ -1264,15 +1268,6 @@ fn normalize_title(value: &str) -> Result<String, KernelError> {
|
|||
}
|
||||
}
|
||||
|
||||
fn normalize_label(value: &str) -> Result<String, KernelError> {
|
||||
let value = value.trim();
|
||||
if value.is_empty() {
|
||||
Err(KernelError::EmptySubjectLabel)
|
||||
} else {
|
||||
Ok(value.to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
fn validated_invocation(value: &DecisionInvocation) -> Result<DecisionInvocation, KernelError> {
|
||||
let action = match &value.action {
|
||||
DecisionAction::Speak { text } if text.trim().is_empty() => {
|
||||
|
|
@ -1294,14 +1289,6 @@ fn validate_principal(value: &PrincipalId) -> Result<(), KernelError> {
|
|||
}
|
||||
}
|
||||
|
||||
fn validate_handle(value: &DraftSubjectHandle) -> Result<(), KernelError> {
|
||||
if value.0.trim().is_empty() || value.0.trim() != value.0 {
|
||||
Err(KernelError::EmptySubjectHandle)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_assignment(value: &ControllerAssignment) -> Result<(), KernelError> {
|
||||
if let ControllerAssignment::Human { principal, .. } = value {
|
||||
validate_principal(principal)?;
|
||||
|
|
@ -1309,20 +1296,6 @@ fn validate_assignment(value: &ControllerAssignment) -> Result<(), KernelError>
|
|||
Ok(())
|
||||
}
|
||||
|
||||
fn assignment_matches_new(assignment: &ControllerAssignment, expected: &NewController) -> bool {
|
||||
match (assignment, expected) {
|
||||
(
|
||||
ControllerAssignment::Human { principal, .. },
|
||||
NewController::Human {
|
||||
principal: expected,
|
||||
},
|
||||
) => principal == expected,
|
||||
(ControllerAssignment::NarrativePersona { .. }, NewController::NarrativePersona)
|
||||
| (ControllerAssignment::OperationalAgent { .. }, NewController::OperationalAgent) => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_effect(
|
||||
state: &mut WorldState,
|
||||
caller: &CallerId,
|
||||
|
|
@ -1334,6 +1307,16 @@ fn apply_effect(
|
|||
"world genesis cannot be applied as a mutable effect".into(),
|
||||
));
|
||||
}
|
||||
WorldEffect::PatchAdmitted { resolved } => {
|
||||
if state.phase != WorldPhase::Draft
|
||||
|| caller != &CallerId::Principal(state.owner.clone())
|
||||
{
|
||||
return Err(KernelError::Invariant(
|
||||
"admitted patch does not satisfy draft authority".into(),
|
||||
));
|
||||
}
|
||||
admit_resolved(state, resolved)?;
|
||||
}
|
||||
WorldEffect::DraftApproved { principal } => {
|
||||
if state.phase != WorldPhase::Draft
|
||||
|| caller != &CallerId::Principal(principal.clone())
|
||||
|
|
@ -1431,64 +1414,69 @@ fn commit_digest(commit: &WorldCommit) -> Result<String, KernelError> {
|
|||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn owner() -> PrincipalId {
|
||||
pub(super) fn owner() -> PrincipalId {
|
||||
PrincipalId::new("owner@example.test")
|
||||
}
|
||||
|
||||
fn player() -> PrincipalId {
|
||||
pub(super) fn player() -> PrincipalId {
|
||||
PrincipalId::new("player@example.test")
|
||||
}
|
||||
|
||||
fn auth_principal(principal: PrincipalId) -> AuthenticatedCaller {
|
||||
pub(super) fn auth_principal(principal: PrincipalId) -> AuthenticatedCaller {
|
||||
AuthenticatedCaller::fixture(CallerId::Principal(principal))
|
||||
}
|
||||
|
||||
fn subject(
|
||||
pub(super) fn subject(
|
||||
handle: &str,
|
||||
label: &str,
|
||||
kind: SubjectKind,
|
||||
controller: NewController,
|
||||
) -> NewDecisionSubject {
|
||||
NewDecisionSubject {
|
||||
handle: DraftSubjectHandle::new(handle),
|
||||
) -> Declaration {
|
||||
Declaration::Subject(SubjectDeclaration {
|
||||
handle: DraftHandle::new(handle),
|
||||
label: label.into(),
|
||||
kind,
|
||||
controller,
|
||||
affordances: BTreeSet::from([AffordanceKind::Speak]),
|
||||
}
|
||||
authority_scope: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn creation(id: CommandId, title: &str) -> CreateWorld {
|
||||
pub(super) fn creation(id: CommandId, title: &str) -> CreateWorld {
|
||||
CreateWorld {
|
||||
id,
|
||||
owner: owner(),
|
||||
title: title.into(),
|
||||
subjects: vec![
|
||||
subject(
|
||||
"player",
|
||||
"The Player",
|
||||
SubjectKind::Person,
|
||||
NewController::Human {
|
||||
principal: player(),
|
||||
},
|
||||
),
|
||||
subject(
|
||||
"persona",
|
||||
"The Witness",
|
||||
SubjectKind::Person,
|
||||
NewController::NarrativePersona,
|
||||
),
|
||||
subject(
|
||||
"operator",
|
||||
"The Council",
|
||||
SubjectKind::Institution,
|
||||
NewController::OperationalAgent,
|
||||
),
|
||||
],
|
||||
patch: WorldPatch {
|
||||
operations: Vec::new(),
|
||||
evidence: Vec::new(),
|
||||
declarations: vec![
|
||||
subject(
|
||||
"player",
|
||||
"The Player",
|
||||
SubjectKind::Person,
|
||||
NewController::Human {
|
||||
principal: player(),
|
||||
},
|
||||
),
|
||||
subject(
|
||||
"persona",
|
||||
"The Witness",
|
||||
SubjectKind::Person,
|
||||
NewController::NarrativePersona,
|
||||
),
|
||||
subject(
|
||||
"operator",
|
||||
"The Council",
|
||||
SubjectKind::Institution,
|
||||
NewController::OperationalAgent,
|
||||
),
|
||||
],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn command(
|
||||
pub(super) fn command(
|
||||
snapshot: &WorldSnapshot,
|
||||
id: CommandId,
|
||||
caller: CallerId,
|
||||
|
|
@ -1503,7 +1491,7 @@ mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
fn submit_owner(
|
||||
pub(super) fn submit_owner(
|
||||
kernel: &mut WorldKernel,
|
||||
snapshot: &WorldSnapshot,
|
||||
body: CommandBody,
|
||||
|
|
@ -1521,7 +1509,7 @@ mod tests {
|
|||
.unwrap()
|
||||
}
|
||||
|
||||
fn activate(kernel: &mut WorldKernel) -> WorldSnapshot {
|
||||
pub(super) fn activate(kernel: &mut WorldKernel) -> WorldSnapshot {
|
||||
let genesis = kernel.snapshot().unwrap();
|
||||
submit_owner(kernel, &genesis, CommandBody::ApproveDraft);
|
||||
let after_owner = kernel.snapshot().unwrap();
|
||||
|
|
@ -2150,11 +2138,18 @@ mod tests {
|
|||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("world.cc");
|
||||
let mut invalid = creation(CommandId::new(), "Nope");
|
||||
invalid.subjects[1].handle = invalid.subjects[0].handle.clone();
|
||||
assert!(matches!(
|
||||
WorldKernel::create(&path, invalid, &auth_principal(owner())),
|
||||
Err(KernelError::DuplicateSubjectHandle)
|
||||
));
|
||||
invalid.patch.declarations[1] = invalid.patch.declarations[0].clone();
|
||||
let Err(KernelError::PatchRejected(rejected)) =
|
||||
WorldKernel::create(&path, invalid, &auth_principal(owner()))
|
||||
else {
|
||||
panic!("expected a rejected creation patch");
|
||||
};
|
||||
assert_eq!(
|
||||
rejected,
|
||||
vec![Mismatch::DuplicateHandle {
|
||||
handle: DraftHandle::new("player")
|
||||
}]
|
||||
);
|
||||
assert!(
|
||||
WorldKernel::create(
|
||||
&path,
|
||||
|
|
|
|||
906
crates/ghostlight-dungeon/src/world/patch.rs
Normal file
906
crates/ghostlight-dungeon/src/world/patch.rs
Normal file
|
|
@ -0,0 +1,906 @@
|
|||
//! Closed-patch resolution: the one owner of draft handles, reference kinds, and
|
||||
//! canonical ID allocation for every admission lane.
|
||||
//!
|
||||
//! A patch names structure two ways and no other way: an exact canonical ID that
|
||||
//! already keys a partition, or a draft handle declared in the same patch.
|
||||
//! Resolution accumulates the complete mismatch set first and allocates only
|
||||
//! after that set is empty, so a rejected patch never mints an ID.
|
||||
|
||||
use super::{
|
||||
AffordanceGrant, AffordanceId, AffordanceKind, CommandId, ControllerAssignment, ControllerId,
|
||||
DecisionScope, EntityId, NewController, SubjectId, SubjectKind, SubjectState, WorldId,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::{BTreeMap, BTreeSet, btree_map::Entry};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(crate) enum EntityKind {
|
||||
Place,
|
||||
Resource,
|
||||
Fact,
|
||||
Channel,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(crate) enum EdgeKind {
|
||||
Route,
|
||||
Relation,
|
||||
Commitment,
|
||||
Pressure,
|
||||
}
|
||||
|
||||
/// Namespace plus declared kind of a draft handle. A reference states the kind it
|
||||
/// expects; resolution refuses a handle that answers with another one.
|
||||
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[serde(tag = "namespace", rename_all = "snake_case")]
|
||||
pub(crate) enum RefKind {
|
||||
Subject(SubjectKind),
|
||||
Entity(EntityKind),
|
||||
Edge(EdgeKind),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[serde(transparent)]
|
||||
pub(crate) struct DraftHandle(String);
|
||||
|
||||
impl DraftHandle {
|
||||
pub(super) fn new(value: impl Into<String>) -> Self {
|
||||
Self(value.into())
|
||||
}
|
||||
}
|
||||
|
||||
/// A reference is an exact canonical ID or a handle resolved in the same patch.
|
||||
/// There is no third form and no `From<String>`.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(tag = "ref", content = "value", rename_all = "snake_case")]
|
||||
pub(crate) enum Ref<Id> {
|
||||
Existing(Id),
|
||||
Draft(DraftHandle),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[serde(transparent)]
|
||||
pub(crate) struct EvidenceRef(String);
|
||||
|
||||
/// Pass 1 declares subjects and entities. `authority_scope` is the single
|
||||
/// reference-bearing field: an institution's jurisdiction over a place.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct SubjectDeclaration {
|
||||
pub(crate) handle: DraftHandle,
|
||||
pub(crate) label: String,
|
||||
pub(crate) kind: SubjectKind,
|
||||
pub(crate) controller: NewController,
|
||||
pub(crate) affordances: BTreeSet<AffordanceKind>,
|
||||
pub(crate) authority_scope: Option<Ref<EntityId>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct EntityDeclaration {
|
||||
pub(crate) handle: DraftHandle,
|
||||
pub(crate) label: String,
|
||||
pub(crate) kind: EntityKind,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub(crate) enum Declaration {
|
||||
Subject(SubjectDeclaration),
|
||||
Entity(EntityDeclaration),
|
||||
}
|
||||
|
||||
/// Empty on purpose: a `Vec<ComponentOp>` can only be empty, so "no components
|
||||
/// yet" is compile-enforced instead of runtime-checked.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub(crate) enum ComponentOp {}
|
||||
|
||||
/// Empty on purpose: an `Option<PatchAnswer>` can only be `None`, so the
|
||||
/// answers-are-None rule is compile-enforced.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub(crate) enum PatchAnswer {}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct WorldPatch {
|
||||
pub(crate) declarations: Vec<Declaration>,
|
||||
pub(crate) operations: Vec<ComponentOp>,
|
||||
pub(crate) evidence: Vec<EvidenceRef>,
|
||||
}
|
||||
|
||||
/// One named structural check that a patch failed. A rejection carries the
|
||||
/// complete set, never the first failure, and is never persisted.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub(crate) enum Mismatch {
|
||||
EmptyHandle {
|
||||
position: usize,
|
||||
},
|
||||
DuplicateHandle {
|
||||
handle: DraftHandle,
|
||||
},
|
||||
EmptyLabel {
|
||||
handle: DraftHandle,
|
||||
},
|
||||
UnresolvedDraft {
|
||||
handle: DraftHandle,
|
||||
expected: RefKind,
|
||||
},
|
||||
WrongKind {
|
||||
handle: DraftHandle,
|
||||
expected: RefKind,
|
||||
actual: RefKind,
|
||||
},
|
||||
UnknownCanonical {
|
||||
handle: DraftHandle,
|
||||
expected: RefKind,
|
||||
},
|
||||
UnadmittedController {
|
||||
handle: DraftHandle,
|
||||
},
|
||||
NoAffordances {
|
||||
handle: DraftHandle,
|
||||
},
|
||||
EmptyEvidence {
|
||||
position: usize,
|
||||
},
|
||||
CanonicalCollision {
|
||||
handle: DraftHandle,
|
||||
},
|
||||
NoCanonicalChange,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub(super) struct EntityRecord {
|
||||
pub(super) label: String,
|
||||
pub(super) kind: EntityKind,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub(super) struct EdgeRecord {
|
||||
pub(super) kind: EdgeKind,
|
||||
pub(super) from: EntityId,
|
||||
pub(super) to: EntityId,
|
||||
}
|
||||
|
||||
/// The handle-to-ID binding table for one subject. The handle is commit-scoped
|
||||
/// provenance; it never enters `WorldState`.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub(super) struct ResolvedSubject {
|
||||
pub(super) handle: DraftHandle,
|
||||
pub(super) subject_id: SubjectId,
|
||||
pub(super) subject: SubjectState,
|
||||
pub(super) controller: ControllerAssignment,
|
||||
pub(super) affordances: BTreeMap<AffordanceId, AffordanceGrant>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub(super) struct ResolvedEntity {
|
||||
pub(super) handle: DraftHandle,
|
||||
pub(super) entity_id: EntityId,
|
||||
pub(super) entity: EntityRecord,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub(super) struct ResolvedPatch {
|
||||
pub(super) subjects: Vec<ResolvedSubject>,
|
||||
pub(super) entities: Vec<ResolvedEntity>,
|
||||
pub(super) evidence: Vec<EvidenceRef>,
|
||||
}
|
||||
|
||||
const SUBJECT_NAMESPACE: &str = "ghostlight.id.subject.v1";
|
||||
const ENTITY_NAMESPACE: &str = "ghostlight.id.entity.v1";
|
||||
const CONTROLLER_NAMESPACE: &str = "ghostlight.id.controller.v1";
|
||||
const AFFORDANCE_NAMESPACE: &str = "ghostlight.id.affordance.v1";
|
||||
|
||||
const PLACE: RefKind = RefKind::Entity(EntityKind::Place);
|
||||
|
||||
/// The only canonical ID allocator. Deterministic on purpose: journal replay
|
||||
/// recomputes `reduce` and requires effect equality, so a reduce arm can never
|
||||
/// draw a `Uuid::new_v4`. Preimage fields are length-prefixed where they are
|
||||
/// variable-width, so the concatenation is unambiguous.
|
||||
fn derive_id(
|
||||
namespace: &str,
|
||||
world_id: WorldId,
|
||||
command_id: CommandId,
|
||||
handle: &DraftHandle,
|
||||
discriminator: Option<&str>,
|
||||
) -> Uuid {
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(namespace.as_bytes());
|
||||
hasher.update(world_id.0.as_bytes());
|
||||
hasher.update(command_id.0.as_bytes());
|
||||
hasher.update((handle.0.len() as u64).to_be_bytes());
|
||||
hasher.update(handle.0.as_bytes());
|
||||
if let Some(discriminator) = discriminator {
|
||||
hasher.update(discriminator.as_bytes());
|
||||
}
|
||||
let mut bytes = [0u8; 16];
|
||||
bytes.copy_from_slice(&hasher.finalize()[..16]);
|
||||
Uuid::from_bytes(bytes)
|
||||
}
|
||||
|
||||
fn affordance_slug(kind: AffordanceKind) -> &'static str {
|
||||
match kind {
|
||||
AffordanceKind::Speak => "speak",
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn is_canonical_text(value: &str) -> bool {
|
||||
!value.trim().is_empty() && value.trim() == value
|
||||
}
|
||||
|
||||
/// The one resolution owner for every admission lane. `admits_human` is true
|
||||
/// only where a human principal may still join the draft-approver set, which is
|
||||
/// genesis alone; the caller derives it from the empty-state predicate.
|
||||
pub(super) fn resolve_declarations(
|
||||
state_subjects: &BTreeMap<SubjectId, SubjectState>,
|
||||
state_entities: &BTreeMap<EntityId, EntityRecord>,
|
||||
world_id: WorldId,
|
||||
command_id: CommandId,
|
||||
patch: &WorldPatch,
|
||||
admits_human: bool,
|
||||
) -> Result<ResolvedPatch, Vec<Mismatch>> {
|
||||
let mut mismatches = Vec::new();
|
||||
let mut index: BTreeMap<DraftHandle, RefKind> = BTreeMap::new();
|
||||
|
||||
for (position, declaration) in patch.declarations.iter().enumerate() {
|
||||
let (handle, label, kind) = match declaration {
|
||||
Declaration::Subject(subject) => (
|
||||
&subject.handle,
|
||||
&subject.label,
|
||||
RefKind::Subject(subject.kind),
|
||||
),
|
||||
Declaration::Entity(entity) => {
|
||||
(&entity.handle, &entity.label, RefKind::Entity(entity.kind))
|
||||
}
|
||||
};
|
||||
let named = is_canonical_text(&handle.0);
|
||||
if !named {
|
||||
mismatches.push(Mismatch::EmptyHandle { position });
|
||||
}
|
||||
if !is_canonical_text(label) {
|
||||
mismatches.push(Mismatch::EmptyLabel {
|
||||
handle: handle.clone(),
|
||||
});
|
||||
}
|
||||
if named {
|
||||
match index.entry(handle.clone()) {
|
||||
Entry::Vacant(slot) => {
|
||||
slot.insert(kind);
|
||||
}
|
||||
Entry::Occupied(_) => mismatches.push(Mismatch::DuplicateHandle {
|
||||
handle: handle.clone(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
if let Declaration::Subject(subject) = declaration {
|
||||
if subject.affordances.is_empty() {
|
||||
mismatches.push(Mismatch::NoAffordances {
|
||||
handle: handle.clone(),
|
||||
});
|
||||
}
|
||||
if let NewController::Human { principal } = &subject.controller
|
||||
&& (!admits_human || super::validate_principal(principal).is_err())
|
||||
{
|
||||
mismatches.push(Mismatch::UnadmittedController {
|
||||
handle: handle.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (position, evidence) in patch.evidence.iter().enumerate() {
|
||||
if !is_canonical_text(&evidence.0) {
|
||||
mismatches.push(Mismatch::EmptyEvidence { position });
|
||||
}
|
||||
}
|
||||
|
||||
for declaration in &patch.declarations {
|
||||
let Declaration::Subject(subject) = declaration else {
|
||||
continue;
|
||||
};
|
||||
let Some(reference) = &subject.authority_scope else {
|
||||
continue;
|
||||
};
|
||||
match reference {
|
||||
Ref::Draft(named) => match index.get(named) {
|
||||
None => mismatches.push(Mismatch::UnresolvedDraft {
|
||||
handle: named.clone(),
|
||||
expected: PLACE,
|
||||
}),
|
||||
Some(kind) if *kind != PLACE => mismatches.push(Mismatch::WrongKind {
|
||||
handle: named.clone(),
|
||||
expected: PLACE,
|
||||
actual: *kind,
|
||||
}),
|
||||
Some(_) => {}
|
||||
},
|
||||
Ref::Existing(entity_id) => match state_entities.get(entity_id) {
|
||||
None => mismatches.push(Mismatch::UnknownCanonical {
|
||||
handle: subject.handle.clone(),
|
||||
expected: PLACE,
|
||||
}),
|
||||
Some(record) if record.kind != EntityKind::Place => {
|
||||
mismatches.push(Mismatch::WrongKind {
|
||||
handle: subject.handle.clone(),
|
||||
expected: PLACE,
|
||||
actual: RefKind::Entity(record.kind),
|
||||
});
|
||||
}
|
||||
Some(_) => {}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
if patch.declarations.is_empty() {
|
||||
mismatches.push(Mismatch::NoCanonicalChange);
|
||||
}
|
||||
|
||||
if !mismatches.is_empty() {
|
||||
mismatches.sort();
|
||||
return Err(mismatches);
|
||||
}
|
||||
|
||||
// No canonical ID exists above this line. Allocation starts only now.
|
||||
let mut collisions = Vec::new();
|
||||
let mut entities = Vec::new();
|
||||
let mut allocated: BTreeMap<DraftHandle, EntityId> = BTreeMap::new();
|
||||
for declaration in &patch.declarations {
|
||||
let Declaration::Entity(entity) = declaration else {
|
||||
continue;
|
||||
};
|
||||
let entity_id = EntityId(derive_id(
|
||||
ENTITY_NAMESPACE,
|
||||
world_id,
|
||||
command_id,
|
||||
&entity.handle,
|
||||
None,
|
||||
));
|
||||
if state_entities.contains_key(&entity_id) {
|
||||
collisions.push(Mismatch::CanonicalCollision {
|
||||
handle: entity.handle.clone(),
|
||||
});
|
||||
}
|
||||
allocated.insert(entity.handle.clone(), entity_id);
|
||||
entities.push(ResolvedEntity {
|
||||
handle: entity.handle.clone(),
|
||||
entity_id,
|
||||
entity: EntityRecord {
|
||||
label: entity.label.clone(),
|
||||
kind: entity.kind,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
let mut subjects = Vec::new();
|
||||
for declaration in &patch.declarations {
|
||||
let Declaration::Subject(input) = declaration else {
|
||||
continue;
|
||||
};
|
||||
let subject_id = SubjectId(derive_id(
|
||||
SUBJECT_NAMESPACE,
|
||||
world_id,
|
||||
command_id,
|
||||
&input.handle,
|
||||
None,
|
||||
));
|
||||
if state_subjects.contains_key(&subject_id) {
|
||||
collisions.push(Mismatch::CanonicalCollision {
|
||||
handle: input.handle.clone(),
|
||||
});
|
||||
}
|
||||
let scope = DecisionScope { subject_id };
|
||||
let controller_id = ControllerId(derive_id(
|
||||
CONTROLLER_NAMESPACE,
|
||||
world_id,
|
||||
command_id,
|
||||
&input.handle,
|
||||
None,
|
||||
));
|
||||
let controller = match input.controller.clone() {
|
||||
NewController::Human { principal } => ControllerAssignment::Human {
|
||||
controller_id,
|
||||
principal,
|
||||
},
|
||||
NewController::NarrativePersona => {
|
||||
ControllerAssignment::NarrativePersona { controller_id }
|
||||
}
|
||||
NewController::OperationalAgent => {
|
||||
ControllerAssignment::OperationalAgent { controller_id }
|
||||
}
|
||||
};
|
||||
let affordances = input
|
||||
.affordances
|
||||
.iter()
|
||||
.map(|kind| {
|
||||
let affordance_id = AffordanceId(derive_id(
|
||||
AFFORDANCE_NAMESPACE,
|
||||
world_id,
|
||||
command_id,
|
||||
&input.handle,
|
||||
Some(affordance_slug(*kind)),
|
||||
));
|
||||
(affordance_id, AffordanceGrant { scope, kind: *kind })
|
||||
})
|
||||
.collect();
|
||||
let authority_scope = match &input.authority_scope {
|
||||
None => None,
|
||||
Some(Ref::Existing(entity_id)) => Some(*entity_id),
|
||||
Some(Ref::Draft(named)) => Some(
|
||||
*allocated
|
||||
.get(named)
|
||||
.expect("a draft place reference resolved above"),
|
||||
),
|
||||
};
|
||||
subjects.push(ResolvedSubject {
|
||||
handle: input.handle.clone(),
|
||||
subject_id,
|
||||
subject: SubjectState {
|
||||
label: input.label.clone(),
|
||||
kind: input.kind,
|
||||
authority_scope,
|
||||
},
|
||||
controller,
|
||||
affordances,
|
||||
});
|
||||
}
|
||||
|
||||
if !collisions.is_empty() {
|
||||
collisions.sort();
|
||||
return Err(collisions);
|
||||
}
|
||||
|
||||
Ok(ResolvedPatch {
|
||||
subjects,
|
||||
entities,
|
||||
evidence: patch.evidence.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::world::tests::{
|
||||
activate, auth_principal, command, creation, owner, player, submit_owner,
|
||||
};
|
||||
use crate::world::{
|
||||
CallerId, CommandBody, CommandId, KernelError, SubmitReceipt, WorldKernel, WorldPhase,
|
||||
};
|
||||
|
||||
fn entity(handle: &str, label: &str, kind: EntityKind) -> Declaration {
|
||||
Declaration::Entity(EntityDeclaration {
|
||||
handle: DraftHandle::new(handle),
|
||||
label: label.into(),
|
||||
kind,
|
||||
})
|
||||
}
|
||||
|
||||
fn institution(handle: &str, label: &str, scope: Option<Ref<EntityId>>) -> Declaration {
|
||||
Declaration::Subject(SubjectDeclaration {
|
||||
handle: DraftHandle::new(handle),
|
||||
label: label.into(),
|
||||
kind: SubjectKind::Institution,
|
||||
controller: NewController::OperationalAgent,
|
||||
affordances: BTreeSet::from([AffordanceKind::Speak]),
|
||||
authority_scope: scope,
|
||||
})
|
||||
}
|
||||
|
||||
fn patch_of(declarations: Vec<Declaration>) -> WorldPatch {
|
||||
WorldPatch {
|
||||
declarations,
|
||||
operations: Vec::new(),
|
||||
evidence: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn admit(patch: WorldPatch) -> CommandBody {
|
||||
CommandBody::AdmitPatch {
|
||||
answers: None,
|
||||
patch,
|
||||
}
|
||||
}
|
||||
|
||||
fn draft_world(directory: &std::path::Path) -> WorldKernel {
|
||||
WorldKernel::create(
|
||||
directory.join("world.cc"),
|
||||
creation(CommandId::new(), "Kharad"),
|
||||
&auth_principal(owner()),
|
||||
)
|
||||
.expect("draft world")
|
||||
.0
|
||||
}
|
||||
|
||||
/// The jurisdiction reference names a place that no declaration and no
|
||||
/// partition provides. Nothing commits and nothing is allocated.
|
||||
#[test]
|
||||
fn run_115_jurisdiction_reference_is_rejected_and_allocates_nothing() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let mut kernel = draft_world(directory.path());
|
||||
let before = kernel.snapshot().unwrap();
|
||||
let commits_before = kernel.journal.commit_count();
|
||||
|
||||
let error = kernel
|
||||
.submit(
|
||||
command(
|
||||
&before,
|
||||
CommandId::new(),
|
||||
CallerId::Principal(owner()),
|
||||
admit(patch_of(vec![institution(
|
||||
"rhythm-authority",
|
||||
"The Rhythm Authority",
|
||||
Some(Ref::Draft(DraftHandle::new("kharad-rhythm-road"))),
|
||||
)])),
|
||||
),
|
||||
&auth_principal(owner()),
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
let KernelError::PatchRejected(mismatches) = error else {
|
||||
panic!("expected a rejected patch");
|
||||
};
|
||||
assert_eq!(
|
||||
mismatches,
|
||||
vec![Mismatch::UnresolvedDraft {
|
||||
handle: DraftHandle::new("kharad-rhythm-road"),
|
||||
expected: PLACE,
|
||||
}]
|
||||
);
|
||||
assert_eq!(kernel.snapshot().unwrap(), before);
|
||||
assert_eq!(kernel.journal.commit_count(), commits_before);
|
||||
assert!(kernel.state.entities.is_empty());
|
||||
assert_eq!(kernel.state.subjects.len(), before.subjects.len());
|
||||
}
|
||||
|
||||
/// The same patch with the place declared beside the institution is one
|
||||
/// atomic commit: both records land and the reference resolves to the
|
||||
/// place's allocated ID.
|
||||
#[test]
|
||||
fn the_same_patch_with_the_place_declared_commits_atomically() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let mut kernel = draft_world(directory.path());
|
||||
let before = kernel.snapshot().unwrap();
|
||||
let commits_before = kernel.journal.commit_count();
|
||||
|
||||
let receipt = submit_owner(
|
||||
&mut kernel,
|
||||
&before,
|
||||
admit(patch_of(vec![
|
||||
entity("kharad-rhythm-road", "The Rhythm Road", EntityKind::Place),
|
||||
institution(
|
||||
"rhythm-authority",
|
||||
"The Rhythm Authority",
|
||||
Some(Ref::Draft(DraftHandle::new("kharad-rhythm-road"))),
|
||||
),
|
||||
])),
|
||||
);
|
||||
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
|
||||
|
||||
let after = kernel.snapshot().unwrap();
|
||||
assert_eq!(after.revision, before.revision + 1);
|
||||
assert_eq!(kernel.journal.commit_count(), commits_before + 1);
|
||||
assert_eq!(kernel.state.entities.len(), 1);
|
||||
let (place_id, record) = kernel.state.entities.iter().next().unwrap();
|
||||
assert_eq!(record.label, "The Rhythm Road");
|
||||
assert_eq!(record.kind, EntityKind::Place);
|
||||
let admitted = kernel
|
||||
.state
|
||||
.subjects
|
||||
.values()
|
||||
.find(|subject| subject.label == "The Rhythm Authority")
|
||||
.expect("the institution is admitted");
|
||||
assert_eq!(admitted.authority_scope, Some(*place_id));
|
||||
}
|
||||
|
||||
/// A handle of the wrong namespace kind is a runtime mismatch. The
|
||||
/// cross-namespace canonical case is a compile error instead:
|
||||
/// `Ref::<EntityId>::Existing(subject_id)` does not compile, because
|
||||
/// `SubjectId`, `EntityId`, and `EdgeId` are distinct newtypes with no
|
||||
/// conversion between them and no public `Uuid` constructor.
|
||||
#[test]
|
||||
fn a_draft_handle_of_the_wrong_kind_is_rejected() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let mut kernel = draft_world(directory.path());
|
||||
let before = kernel.snapshot().unwrap();
|
||||
let commits_before = kernel.journal.commit_count();
|
||||
|
||||
let error = kernel
|
||||
.submit(
|
||||
command(
|
||||
&before,
|
||||
CommandId::new(),
|
||||
CallerId::Principal(owner()),
|
||||
admit(patch_of(vec![
|
||||
entity("rhythm-tithe", "The Rhythm Tithe", EntityKind::Resource),
|
||||
institution(
|
||||
"rhythm-authority",
|
||||
"The Rhythm Authority",
|
||||
Some(Ref::Draft(DraftHandle::new("rhythm-tithe"))),
|
||||
),
|
||||
])),
|
||||
),
|
||||
&auth_principal(owner()),
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
let KernelError::PatchRejected(mismatches) = error else {
|
||||
panic!("expected a rejected patch");
|
||||
};
|
||||
assert_eq!(
|
||||
mismatches,
|
||||
vec![Mismatch::WrongKind {
|
||||
handle: DraftHandle::new("rhythm-tithe"),
|
||||
expected: PLACE,
|
||||
actual: RefKind::Entity(EntityKind::Resource),
|
||||
}]
|
||||
);
|
||||
assert_eq!(kernel.journal.commit_count(), commits_before);
|
||||
assert_eq!(kernel.snapshot().unwrap(), before);
|
||||
}
|
||||
|
||||
/// Rejection carries the complete failed-check set, not the first failure,
|
||||
/// and repairing exactly that set is enough to commit.
|
||||
#[test]
|
||||
fn rejection_returns_every_failed_check_and_repairing_exactly_those_commits() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let mut kernel = draft_world(directory.path());
|
||||
let before = kernel.snapshot().unwrap();
|
||||
|
||||
let broken = patch_of(vec![
|
||||
entity("rhythm-road", "The Rhythm Road", EntityKind::Place),
|
||||
entity("rhythm-road", " ", EntityKind::Place),
|
||||
institution(
|
||||
"rhythm-authority",
|
||||
"The Rhythm Authority",
|
||||
Some(Ref::Draft(DraftHandle::new("cavity-yard"))),
|
||||
),
|
||||
Declaration::Subject(SubjectDeclaration {
|
||||
handle: DraftHandle::new("late-arrival"),
|
||||
label: "A Late Arrival".into(),
|
||||
kind: SubjectKind::Person,
|
||||
controller: NewController::Human {
|
||||
principal: player(),
|
||||
},
|
||||
affordances: BTreeSet::from([AffordanceKind::Speak]),
|
||||
authority_scope: None,
|
||||
}),
|
||||
]);
|
||||
let error = kernel
|
||||
.submit(
|
||||
command(
|
||||
&before,
|
||||
CommandId::new(),
|
||||
CallerId::Principal(owner()),
|
||||
admit(broken),
|
||||
),
|
||||
&auth_principal(owner()),
|
||||
)
|
||||
.unwrap_err();
|
||||
let KernelError::PatchRejected(mismatches) = error else {
|
||||
panic!("expected a rejected patch");
|
||||
};
|
||||
let mut expected = vec![
|
||||
Mismatch::DuplicateHandle {
|
||||
handle: DraftHandle::new("rhythm-road"),
|
||||
},
|
||||
Mismatch::EmptyLabel {
|
||||
handle: DraftHandle::new("rhythm-road"),
|
||||
},
|
||||
Mismatch::UnresolvedDraft {
|
||||
handle: DraftHandle::new("cavity-yard"),
|
||||
expected: PLACE,
|
||||
},
|
||||
Mismatch::UnadmittedController {
|
||||
handle: DraftHandle::new("late-arrival"),
|
||||
},
|
||||
];
|
||||
expected.sort();
|
||||
assert_eq!(mismatches, expected);
|
||||
assert_eq!(kernel.journal.commit_count(), 1);
|
||||
|
||||
let repaired = patch_of(vec![
|
||||
entity("rhythm-road", "The Rhythm Road", EntityKind::Place),
|
||||
entity("cavity-yard", "The Cavity Yard", EntityKind::Place),
|
||||
institution(
|
||||
"rhythm-authority",
|
||||
"The Rhythm Authority",
|
||||
Some(Ref::Draft(DraftHandle::new("cavity-yard"))),
|
||||
),
|
||||
Declaration::Subject(SubjectDeclaration {
|
||||
handle: DraftHandle::new("late-arrival"),
|
||||
label: "A Late Arrival".into(),
|
||||
kind: SubjectKind::Person,
|
||||
controller: NewController::NarrativePersona,
|
||||
affordances: BTreeSet::from([AffordanceKind::Speak]),
|
||||
authority_scope: None,
|
||||
}),
|
||||
]);
|
||||
let receipt = submit_owner(&mut kernel, &before, admit(repaired));
|
||||
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
|
||||
assert_eq!(kernel.state.entities.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_patch_is_no_canonical_change() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let mut kernel = draft_world(directory.path());
|
||||
let before = kernel.snapshot().unwrap();
|
||||
|
||||
let error = kernel
|
||||
.submit(
|
||||
command(
|
||||
&before,
|
||||
CommandId::new(),
|
||||
CallerId::Principal(owner()),
|
||||
admit(patch_of(Vec::new())),
|
||||
),
|
||||
&auth_principal(owner()),
|
||||
)
|
||||
.unwrap_err();
|
||||
let KernelError::PatchRejected(mismatches) = error else {
|
||||
panic!("expected a rejected patch");
|
||||
};
|
||||
assert_eq!(mismatches, vec![Mismatch::NoCanonicalChange]);
|
||||
assert_eq!(kernel.snapshot().unwrap(), before);
|
||||
assert_eq!(kernel.journal.commit_count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn admit_patch_in_active_is_rejected() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let mut kernel = draft_world(directory.path());
|
||||
let active = activate(&mut kernel);
|
||||
let commits_before = kernel.journal.commit_count();
|
||||
|
||||
let error = kernel
|
||||
.submit(
|
||||
command(
|
||||
&active,
|
||||
CommandId::new(),
|
||||
CallerId::Principal(owner()),
|
||||
admit(patch_of(vec![entity(
|
||||
"rhythm-road",
|
||||
"The Rhythm Road",
|
||||
EntityKind::Place,
|
||||
)])),
|
||||
),
|
||||
&auth_principal(owner()),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
error,
|
||||
KernelError::WrongPhase {
|
||||
expected: WorldPhase::Draft,
|
||||
actual: WorldPhase::Active,
|
||||
}
|
||||
));
|
||||
assert_eq!(kernel.journal.commit_count(), commits_before);
|
||||
assert_eq!(kernel.snapshot().unwrap(), active);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn admit_patch_from_a_non_owner_is_rejected() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let mut kernel = draft_world(directory.path());
|
||||
let before = kernel.snapshot().unwrap();
|
||||
let commits_before = kernel.journal.commit_count();
|
||||
|
||||
let error = kernel
|
||||
.submit(
|
||||
command(
|
||||
&before,
|
||||
CommandId::new(),
|
||||
CallerId::Principal(player()),
|
||||
admit(patch_of(vec![entity(
|
||||
"rhythm-road",
|
||||
"The Rhythm Road",
|
||||
EntityKind::Place,
|
||||
)])),
|
||||
),
|
||||
&auth_principal(player()),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(error, KernelError::Unauthorized));
|
||||
assert_eq!(kernel.journal.commit_count(), commits_before);
|
||||
assert_eq!(kernel.snapshot().unwrap(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restart_replay_after_a_committed_patch_is_exact() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("world.cc");
|
||||
let (mut kernel, _) = WorldKernel::create(
|
||||
&path,
|
||||
creation(CommandId::new(), "Kharad"),
|
||||
&auth_principal(owner()),
|
||||
)
|
||||
.unwrap();
|
||||
let before = kernel.snapshot().unwrap();
|
||||
let envelope = command(
|
||||
&before,
|
||||
CommandId::new(),
|
||||
CallerId::Principal(owner()),
|
||||
admit(patch_of(vec![
|
||||
entity("rhythm-road", "The Rhythm Road", EntityKind::Place),
|
||||
institution(
|
||||
"rhythm-authority",
|
||||
"The Rhythm Authority",
|
||||
Some(Ref::Draft(DraftHandle::new("rhythm-road"))),
|
||||
),
|
||||
])),
|
||||
);
|
||||
kernel
|
||||
.submit(envelope.clone(), &auth_principal(owner()))
|
||||
.unwrap();
|
||||
let committed = kernel.snapshot().unwrap();
|
||||
let world_id = committed.world_id;
|
||||
drop(kernel);
|
||||
|
||||
let mut reopened = WorldKernel::open(&path, world_id).unwrap();
|
||||
assert_eq!(reopened.snapshot().unwrap(), committed);
|
||||
assert!(matches!(
|
||||
reopened.submit(envelope, &auth_principal(owner())).unwrap(),
|
||||
SubmitReceipt::AlreadyApplied(_)
|
||||
));
|
||||
}
|
||||
|
||||
/// One allocator, a pure function of `(world_id, command_id, handle)`: the
|
||||
/// same handle text under two commands gets two IDs, and the same command
|
||||
/// re-resolved gets the same ones.
|
||||
#[test]
|
||||
fn genesis_and_admit_patch_share_one_allocator() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let mut kernel = draft_world(directory.path());
|
||||
let before = kernel.snapshot().unwrap();
|
||||
let genesis_player = before
|
||||
.subjects
|
||||
.iter()
|
||||
.find(|subject| subject.label == "The Player")
|
||||
.expect("the genesis player subject")
|
||||
.id;
|
||||
|
||||
let patch = patch_of(vec![Declaration::Subject(SubjectDeclaration {
|
||||
handle: DraftHandle::new("player"),
|
||||
label: "Another Player".into(),
|
||||
kind: SubjectKind::Person,
|
||||
controller: NewController::NarrativePersona,
|
||||
affordances: BTreeSet::from([AffordanceKind::Speak]),
|
||||
authority_scope: None,
|
||||
})]);
|
||||
submit_owner(&mut kernel, &before, admit(patch.clone()));
|
||||
let admitted = *kernel
|
||||
.state
|
||||
.subjects
|
||||
.iter()
|
||||
.find(|(_, subject)| subject.label == "Another Player")
|
||||
.expect("the admitted subject")
|
||||
.0;
|
||||
assert_ne!(admitted, genesis_player);
|
||||
|
||||
let world_id = before.world_id;
|
||||
let command_id = CommandId::new();
|
||||
let first = resolve_declarations(
|
||||
&BTreeMap::new(),
|
||||
&BTreeMap::new(),
|
||||
world_id,
|
||||
command_id,
|
||||
&patch,
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
let second = resolve_declarations(
|
||||
&BTreeMap::new(),
|
||||
&BTreeMap::new(),
|
||||
world_id,
|
||||
command_id,
|
||||
&patch,
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(first, second);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue