From 48de96b0a4b646370f8a40958fe5ff0f639119ff Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 4 Sep 2026 18:48:22 +0200 Subject: [PATCH] ghostlight-dungeon: cut the duplicated incident-route scan, add Custody, Dependency, conservation, and evidenced admission MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The cut first. `controllers.rs::typed_incident_routes` recomputed by hand the same incident-route set `scope_digest` computed in `mod.rs`, two scans in two modules held together by a comment. Both are gone. `mod.rs::scope_components` is now the single owner of "what components does this subject's verification read"; `scope_digest` and `snapshot` both consume it, and the controller view reads `SubjectSnapshot.incident_routes` and resolves IDs against the snapshot. `ScopePreimage`'s `position` and `routes` fields fold into one `components` field. Three candidate mismatch names are refused before they exist: `CustodyNotHeld` (absence is zero, so it is the boundary case of `InsufficientCustody`), `DependencyTargetKind` (a target of the wrong kind is `WrongKind`), and `DependencyDuplicate` / `DependencyNotBound` (an operation that changes nothing is `NoOperationEffect`, which pass 2 already owns). The addition. - `WorldState` gains `holdings: BTreeMap>` and `dependencies: BTreeMap>`: subject-keyed partitions following `positions`, not `EdgeRecord` variants. `EdgeRecord`, `EdgeKind`, `ResolvedRoute`, and the seven accessors are untouched. Absence is zero at both levels, so no stored `Quantity(0)`, no empty inner map, and a duplicate holding is unrepresentable because a map key is unique. - `Quantity(u64)`: unsigned, no unit, no maximum. Subtraction is `checked_sub` and fails as `InsufficientCustody`; addition is `checked_add` and fails as `QuantityOverflow`. No saturating arithmetic. - `ComponentOp` and `ResolvedOp` gain `Transfer`, `Transform`, `Consume`, `Admit`, `Bind`, `Release`. `Transform` is 1:1 by construction: one `qty` spent and gained, so a ratio has nowhere to be written. No `ResolvedOp` carries a resulting balance; every arm re-derives its precondition from the committed partitions at apply time. - `Mismatch` gains `InsufficientCustody`, `ZeroQuantity`, `QuantityOverflow`, `AdmitWithoutEvidence`, `SelfDependency`, and `CustodyNotConserved`, appended after the pass-2 variants so single-item assertions keep their ordering. - `patch::check_ledger` is the one statement of conservation: `after == before + admitted + gained - consumed - spent`, over `u128` accumulators. `resolve_patch` seeds a fourth candidate map beside containers, routes, and positions, records each admitted operation's terms, and verdicts the ledger after the operation loop and before the emptiness gate. `admit_resolved` re-derives the same equation over the committed partitions, so a forged `PatchAdmitted` that reaches `apply_effect` without passing the resolver dies with `Invariant("custody does not conserve")`. `Transfer` contributes to no term: the equation proves it. - Evidenced admission. `EvidenceRef` gains a constructor and crosses the facade. An `Admit` is valid when its ref is canonical text and the identical ref appears in the same patch's `evidence` list; otherwise `AdmitWithoutEvidence`. The kernel checks no store and no digest — retrieval and receipt authenticity belong to the retrieval organ — but the ref rides inside the digested, hash-chained commit, so it cannot be altered or dropped afterwards. There is no holdings declaration field: `Admit` with evidence is the only creation path, in every lane including genesis. Evidence is Draft-only, so `Admit` is Draft-only in this pass, with no second gate. - Replay shape. Every `holdings` key names a canonical subject, every inner key a `Resource` entity at a nonzero quantity, no inner map empty; every `dependencies` key names a canonical subject with a non-empty set of canonical, distinct targets. - Snapshot and typed view. `WorldSnapshot` gains `resources`; `SubjectSnapshot` gains `holdings`, `dependencies`, and `incident_routes`, all the acting subject's own. `typed_view` gains a `holdings` block with labels resolved only for what this subject holds, and a `dependencies` block carrying target kind and ID with no label and no target state. The hand-written `available_tools` string is unchanged; the derived tool catalog is a later pass. - Schema bump to `ghostlight.world_state.custody.v1` / `ghostlight.world_commit.custody.v1` and the matching journal rows. A pre-pass store fails `recover` with an unadmitted row type. No migration adapter. Deviations from the Imagination spec, each decided here: - `resolve_place` generalizes into `resolve_entity(expected_kind)` rather than gaining a `resolve_resource` sibling. Two eight-line wrappers around one body bought nothing; the four place call sites pass the kind. - Spec test 1 asks for a forged `Transfer` whose debit and credit differ. `ResolvedOp::Transfer` carries one `qty`, so that is unrepresentable — which is the outcome the shape was chosen for. The test proves the reachable forgery (a transfer the holder cannot cover leaves `holdings` byte-identical) and falsifies `check_ledger` directly beside it. - Spec test 14 asserts against `verify_state_shape` rather than `verify_history`. Mutating a committed holding also breaks replay equality, so routing through `verify_history` would pass even with the shape clauses deleted. - Spec test 11's visible half lives in `controllers.rs`, where `SelectedDecision` is, extending the existing typed-view non-leakage test; its kernel half is the world-level test of the same name. - `EvidenceRef::new` is `#[cfg(test)]`. No `AdmitPatch` ingress exists yet, so every caller that builds a patch today is a test; the gate comes off in the same commit as the first production patch author. The type itself crosses the facade, as `ComponentOp::Admit` requires. No external-owner field, no unit, rate, or recipe field anywhere, no new crate or dependency, no compatibility shim. cargo test -p ghostlight-dungeon --bin ghostlight-dungeon world:: 91 passed, 0 failed, 1 ignored (75 before this commit). cargo test -p ghostlight-dungeon: 126 passed + 1, 0 failed, 1 ignored. Co-Authored-By: Claude Fable 5.1 --- .../src/world/controllers.rs | 116 +- .../ghostlight-dungeon/src/world/journal.rs | 190 ++- crates/ghostlight-dungeon/src/world/mod.rs | 1042 ++++++++++++++++- crates/ghostlight-dungeon/src/world/patch.rs | 670 ++++++++++- 4 files changed, 1950 insertions(+), 68 deletions(-) diff --git a/crates/ghostlight-dungeon/src/world/controllers.rs b/crates/ghostlight-dungeon/src/world/controllers.rs index ec0c881..8d5adfd 100644 --- a/crates/ghostlight-dungeon/src/world/controllers.rs +++ b/crates/ghostlight-dungeon/src/world/controllers.rs @@ -8,8 +8,8 @@ use crate::world::{ AffordanceId, AffordanceKind, CommandId, CommitReceipt, ControllerMode, DecisionAction, - DecisionInvocation, DecisionOpportunity, KernelError, MailboxError, SubjectId, SubjectSnapshot, - SubmitReceipt, WorldMailbox, WorldSnapshot, + DecisionInvocation, DecisionOpportunity, DependencyTarget, KernelError, MailboxError, + SubjectId, SubjectSnapshot, SubmitReceipt, WorldMailbox, WorldSnapshot, }; use async_trait::async_trait; use chrono::Utc; @@ -2567,7 +2567,9 @@ impl SelectedDecision { "permission": { "speak": true, }, - "routes": self.typed_incident_routes(), + "routes": self.typed_routes(), + "holdings": self.typed_holdings(), + "dependencies": self.typed_dependencies(), "visible_events": self.typed_visible_events(), })) .map_err(|error| ControllerError::Serialization(error.to_string())) @@ -2590,15 +2592,19 @@ impl SelectedDecision { ) } - /// The routes incident to that place: the same set the scope digest reads. - fn typed_incident_routes(&self) -> Vec { - let Some(place) = self.subject.position else { - return Vec::new(); - }; - self.snapshot - .routes + /// The routes incident to that place, named by the kernel rather than + /// recomputed here: the same set the scope digest reads, because both come + /// from the one `scope_components` derivation. + fn typed_routes(&self) -> Vec { + self.subject + .incident_routes .iter() - .filter(|route| route.from == place || route.to == place) + .filter_map(|edge_id| { + self.snapshot + .routes + .iter() + .find(|route| route.id == *edge_id) + }) .map(|route| { json!({ "id": route.id, @@ -2613,6 +2619,45 @@ impl SelectedDecision { .collect() } + /// Only the acting subject's own holdings. No other subject's, and no + /// resource gazetteer: labels are resolved for what this subject holds and + /// for nothing else. + fn typed_holdings(&self) -> Vec { + self.subject + .holdings + .iter() + .map(|(resource, quantity)| { + let label = self + .snapshot + .resources + .iter() + .find(|candidate| candidate.id == *resource) + .map(|candidate| candidate.label.clone()); + json!({"id": resource, "label": label, "quantity": quantity}) + }) + .collect() + } + + /// The acting subject's dependencies, with no label and no target state. A + /// target's label would name places, routes, or subjects this subject may + /// not know, and a dependency on a closed route appears here unmarked: the + /// crisis is the world's to derive, not this view's to editorialize. + fn typed_dependencies(&self) -> Vec { + self.subject + .dependencies + .iter() + .map(|target| match target { + DependencyTarget::Resource(id) => { + json!({"target_kind": "resource", "target_id": id}) + } + DependencyTarget::Route(id) => json!({"target_kind": "route", "target_id": id}), + DependencyTarget::Subject(id) => { + json!({"target_kind": "subject", "target_id": id}) + } + }) + .collect() + } + fn visible_stimulus(&self) -> Result { serde_json::to_string_pretty(&self.projector_visible_events()?) .map_err(|error| ControllerError::Serialization(error.to_string())) @@ -3574,6 +3619,9 @@ mod tests { human_controller: None, affordances: BTreeMap::from([(AffordanceKind::Speak, speak_affordance)]), position: None, + holdings: BTreeMap::new(), + dependencies: BTreeSet::new(), + incident_routes: Vec::new(), }; let speaker = SubjectSnapshot { id: speaker_id, @@ -3584,6 +3632,9 @@ mod tests { human_controller: None, affordances: BTreeMap::new(), position: None, + holdings: BTreeMap::new(), + dependencies: BTreeSet::new(), + incident_routes: Vec::new(), }; let snapshot = WorldSnapshot { world_id: opportunity.world_id, @@ -3595,6 +3646,7 @@ mod tests { required_approvers: BTreeSet::new(), subjects: vec![actor.clone(), speaker], places: Vec::new(), + resources: Vec::new(), routes: Vec::new(), events: vec![crate::world::DecisionEvent { id: EventId::for_command(CommandId::new()), @@ -3653,7 +3705,10 @@ mod tests { /// and a route that touches neither endpoint stay out of the surface. #[test] fn soul_the_typed_view_exposes_only_the_actors_place_and_incident_routes() { - use crate::world::{AccessKind, Cost, EdgeId, EntityId, PlaceSnapshot, RouteSnapshot}; + use crate::world::{ + AccessKind, Cost, EdgeId, EntityId, PlaceSnapshot, Quantity, ResourceSnapshot, + RouteSnapshot, + }; let actor_id = SubjectId::issue(); let other_id = SubjectId::issue(); @@ -3693,6 +3748,9 @@ mod tests { human_controller: None, affordances: BTreeMap::from([(AffordanceKind::Speak, speak_affordance)]), position: Some(yard), + holdings: BTreeMap::new(), + dependencies: BTreeSet::new(), + incident_routes: vec![first_edge], }; let other = SubjectSnapshot { id: other_id, @@ -3703,6 +3761,9 @@ mod tests { human_controller: None, affordances: BTreeMap::new(), position: Some(vault), + holdings: BTreeMap::new(), + dependencies: BTreeSet::new(), + incident_routes: vec![second_edge], }; let named_place = |id, label: &str| PlaceSnapshot { id, @@ -3732,6 +3793,7 @@ mod tests { named_place(road, "The Rhythm Road"), named_place(vault, "The Sealed Vault"), ], + resources: Vec::new(), routes: vec![ named_route(first_edge, "The Yard Ramp", yard, road), named_route(second_edge, "The Vault Stair", road, vault), @@ -3761,11 +3823,41 @@ mod tests { } // A subject standing nowhere gets a null place and no routes at all. + // `scope_components` derives both together, so the fixture clears both. let mut unplaced = selected; unplaced.subject.position = None; + unplaced.subject.incident_routes.clear(); let view = unplaced.typed_view().unwrap(); assert!(!view.contains("The Cavity Yard")); assert!(!view.contains("The Yard Ramp")); + + // Holdings are the acting subject's own, with labels resolved only for + // what it holds; a dependency carries its target kind and ID and no + // label at all, because a target's name may be something this subject + // does not know. A dependency on a closed route appears unmarked. + let mut custodial = unplaced; + let tithe = EntityId::issue(); + let hoard = EntityId::issue(); + custodial.snapshot.resources = vec![ + ResourceSnapshot { + id: tithe, + label: "The Rhythm Tithe".into(), + }, + ResourceSnapshot { + id: hoard, + label: "The Vault Hoard".into(), + }, + ]; + custodial.subject.holdings = BTreeMap::from([(tithe, Quantity(7))]); + custodial.subject.dependencies = BTreeSet::from([DependencyTarget::Route(second_edge)]); + let view = custodial.typed_view().unwrap(); + assert!(view.contains("The Rhythm Tithe")); + assert!(view.contains(r#""quantity": 7"#)); + assert!(view.contains(r#""target_kind": "route""#)); + assert!(view.contains(encoded_id(&second_edge).unwrap().as_str())); + for leaked in ["The Vault Hoard", "The Vault Stair"] { + assert!(!view.contains(leaked), "the typed view leaked `{leaked}`"); + } } #[test] diff --git a/crates/ghostlight-dungeon/src/world/journal.rs b/crates/ghostlight-dungeon/src/world/journal.rs index 6d309ec..a52e80b 100644 --- a/crates/ghostlight-dungeon/src/world/journal.rs +++ b/crates/ghostlight-dungeon/src/world/journal.rs @@ -12,8 +12,8 @@ use std::{ }; use thiserror::Error; -const STATE_ROW: &str = "world_state.topology.v1"; -const COMMIT_ROW: &str = "world_commit.topology.v1"; +const STATE_ROW: &str = "world_state.custody.v1"; +const COMMIT_ROW: &str = "world_commit.custody.v1"; #[derive(Debug, Error)] pub(super) enum JournalError { @@ -487,6 +487,46 @@ fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> { )); } } + let is_resource = |entity_id: &super::EntityId| { + state + .entities + .get(entity_id) + .is_some_and(|record| record.kind == super::EntityKind::Resource) + }; + // Absence is zero and one slot holds one pair, so a store satisfying these + // clauses cannot carry a zero, an empty holder, a duplicate, or a dangling + // holding — with no scan for any of them. + for (subject_id, held) in &state.holdings { + if !state.subjects.contains_key(subject_id) + || held.is_empty() + || held + .iter() + .any(|(resource, quantity)| !is_resource(resource) || quantity.0 == 0) + { + return Err(JournalError::Corrupt( + "holding does not name a canonical subject and resource at a nonzero quantity" + .into(), + )); + } + } + for (subject_id, targets) in &state.dependencies { + let target_is_canonical = |target: &super::DependencyTarget| match target { + super::DependencyTarget::Resource(entity_id) => is_resource(entity_id), + super::DependencyTarget::Route(edge_id) => state.edges.contains_key(edge_id), + super::DependencyTarget::Subject(other) => { + other != subject_id && state.subjects.contains_key(other) + } + }; + if !state.subjects.contains_key(subject_id) + || targets.is_empty() + || !targets.iter().all(target_is_canonical) + { + return Err(JournalError::Corrupt( + "dependency does not name a canonical subject and a distinct canonical target" + .into(), + )); + } + } let mut controller_ids = BTreeSet::new(); for (subject_id, subject) in &state.subjects { if !super::patch::is_canonical_text(&subject.label) { @@ -1083,3 +1123,149 @@ mod tests { ); } } + +#[cfg(test)] +mod custody_tests { + use super::*; + use crate::world::{ + CallerId, CommandBody, CommandId, ComponentOp, EntityKind, Quantity, Ref, SubmitReceipt, + WorldKernel, WorldPatch, + tests::{admit_custody, admit_topology, auth_principal, command, creation, owner}, + }; + + /// Replay re-derives the custody partitions from the commit log alone: a + /// world reopened after a transfer is byte-identical, and the transfer's own + /// envelope is idempotent. + #[test] + fn restart_replay_after_a_transfer_is_exact() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let authenticated = auth_principal(owner()); + let (mut kernel, _) = + WorldKernel::create(&path, creation(CommandId::new(), "Replay"), &authenticated) + .unwrap(); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + let active = crate::world::tests::activate(&mut kernel); + + let envelope = command( + &active, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }], + evidence: Vec::new(), + }, + }, + ); + let SubmitReceipt::Applied(receipt) = + kernel.submit(envelope.clone(), &authenticated).unwrap() + else { + panic!("expected an applied transfer"); + }; + let accepted = kernel.snapshot().unwrap(); + let world_id = accepted.world_id; + drop(kernel); + + let mut reopened = WorldKernel::open(&path, world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), accepted); + assert_eq!( + reopened.submit(envelope, &authenticated).unwrap(), + SubmitReceipt::AlreadyApplied(receipt) + ); + } + + /// A store written at the pass-2 schema is refused outright. There is no + /// migration adapter, and the refusal is the behaviour. + #[test] + fn a_store_from_the_previous_schema_is_refused() { + let row = CultCacheEnvelope { + key: "state".into(), + r#type: "world_state.topology.v1".into(), + payload: Vec::new(), + stored_at: Utc::now().to_rfc3339(), + schema_id: Some("ghostlight.world_state.topology.v1".into()), + }; + let error = recover(vec![row], None).unwrap_err(); + let JournalError::Corrupt(message) = error else { + panic!("expected a corrupt store"); + }; + assert!( + message.contains("unadmitted row type"), + "unexpected refusal: {message}" + ); + } + + /// Absence is zero and one slot holds one pair, so a stored zero, an empty + /// holder, and a holding on something that is not a resource are each + /// corrupt at replay. + /// + /// Deviation from the spec's wording, decided here: the assertion is against + /// `verify_state_shape`, which owns these clauses. Routing through + /// `verify_history` would also fail on replay-equality, so it would pass + /// even if the shape clauses were deleted — which is the opposite of a + /// falsification. + #[test] + fn a_zero_or_dangling_holding_is_corrupt() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let authenticated = auth_principal(owner()); + let (mut kernel, _) = + WorldKernel::create(&path, creation(CommandId::new(), "Shape"), &authenticated) + .unwrap(); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + crate::world::tests::activate(&mut kernel); + verify_state_shape(&kernel.state).expect("the admitted world has a canonical shape"); + + let mut zero = kernel.state.clone(); + zero.holdings + .get_mut(&custody.holder) + .unwrap() + .insert(custody.tithe, Quantity(0)); + assert!(matches!( + verify_state_shape(&zero), + Err(JournalError::Corrupt(_)) + )); + + let mut emptied = kernel.state.clone(); + emptied.holdings.get_mut(&custody.holder).unwrap().clear(); + assert!(matches!( + verify_state_shape(&emptied), + Err(JournalError::Corrupt(_)) + )); + + let mut not_a_resource = kernel.state.clone(); + assert_eq!( + not_a_resource.entities[&topology.yard].kind, + EntityKind::Place + ); + not_a_resource + .holdings + .get_mut(&custody.holder) + .unwrap() + .insert(topology.yard, Quantity(1)); + assert!(matches!( + verify_state_shape(¬_a_resource), + Err(JournalError::Corrupt(_)) + )); + + let mut dangling = kernel.state.clone(); + dangling.dependencies.insert( + custody.holder, + BTreeSet::from([crate::world::DependencyTarget::Subject(custody.holder)]), + ); + assert!(matches!( + verify_state_shape(&dangling), + Err(JournalError::Corrupt(_)) + )); + } +} diff --git a/crates/ghostlight-dungeon/src/world/mod.rs b/crates/ghostlight-dungeon/src/world/mod.rs index 045ca3a..b83d686 100644 --- a/crates/ghostlight-dungeon/src/world/mod.rs +++ b/crates/ghostlight-dungeon/src/world/mod.rs @@ -18,12 +18,12 @@ pub(crate) use controllers::{ }; pub(crate) use mailbox::{MailboxError, WorldMailbox}; pub(crate) use patch::{ - AccessKind, Cost, Declaration, DraftHandle, EntityDeclaration, EntityKind, Mismatch, - PatchAnswer, Position, Ref, SubjectDeclaration, WorldPatch, + AccessKind, Cost, Declaration, DependencyTarget, DraftHandle, EntityDeclaration, EntityKind, + EvidenceRef, Mismatch, PatchAnswer, Position, Quantity, Ref, SubjectDeclaration, WorldPatch, }; #[cfg(test)] -use patch::{ComponentOp, RouteDeclaration}; -use patch::{EdgeRecord, EntityRecord, ResolvedOp, ResolvedPatch}; +use patch::{ComponentOp, DependencyRef, RouteDeclaration}; +use patch::{EdgeRecord, EntityRecord, LedgerDelta, ResolvedOp, ResolvedPatch}; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; @@ -34,8 +34,8 @@ use std::path::Path; use thiserror::Error; use uuid::Uuid; -pub(crate) const STATE_SCHEMA: &str = "ghostlight.world_state.topology.v1"; -pub(crate) const COMMIT_SCHEMA: &str = "ghostlight.world_commit.topology.v1"; +pub(crate) const STATE_SCHEMA: &str = "ghostlight.world_state.custody.v1"; +pub(crate) const COMMIT_SCHEMA: &str = "ghostlight.world_commit.custody.v1"; /// Compatibility tag derived from [`STATE_SCHEMA`]: the trailing /// `-` pair (e.g. `foundation-v1`). Callers that publish a @@ -262,8 +262,7 @@ struct ScopePreimage<'a> { subject_id: SubjectId, controller: &'a ControllerAssignment, affordances: BTreeMap, - position: Option<&'a Position>, - routes: BTreeMap, + components: &'a ScopeComponents, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] @@ -427,6 +426,12 @@ struct WorldState { entities: BTreeMap, edges: BTreeMap, positions: BTreeMap, + /// What each subject holds. Absence is zero at both levels: no stored + /// `Quantity(0)` and no empty inner map, so a duplicate holding is + /// unrepresentable and "nothing" has one shape. + holdings: BTreeMap>, + /// What each subject depends on. Never empty for a present key. + dependencies: BTreeMap>, controller_assignments: BTreeMap, affordance_grants: BTreeMap, events: Vec, @@ -510,6 +515,18 @@ pub(crate) struct SubjectSnapshot { pub(crate) human_controller: Option, pub(crate) affordances: BTreeMap, pub(crate) position: Option, + /// This subject's own holdings and dependencies, and the routes incident to + /// its place: exactly what its scope digest reads, lowered from the one + /// `scope_components` owner. + pub(crate) holdings: BTreeMap, + pub(crate) dependencies: BTreeSet, + pub(crate) incident_routes: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct ResourceSnapshot { + pub(crate) id: EntityId, + pub(crate) label: String, } #[derive(Clone, Debug, PartialEq, Eq)] @@ -541,6 +558,7 @@ pub(crate) struct WorldSnapshot { pub(crate) required_approvers: BTreeSet, pub(crate) subjects: Vec, pub(crate) places: Vec, + pub(crate) resources: Vec, pub(crate) routes: Vec, pub(crate) events: Vec, pub(crate) opportunities: Vec, @@ -1064,6 +1082,8 @@ impl WorldState { entities: BTreeMap::new(), edges: BTreeMap::new(), positions: BTreeMap::new(), + holdings: BTreeMap::new(), + dependencies: BTreeMap::new(), controller_assignments: BTreeMap::new(), affordance_grants: BTreeMap::new(), events: Vec::new(), @@ -1262,15 +1282,133 @@ fn admit_resolved(state: &mut WorldState, resolved: &ResolvedPatch) -> Result<() } } } + // A forged `PatchAdmitted` reaches this function without ever passing the + // resolver, so conservation is re-derived here over the committed + // partitions, against the same equation, with `before` read from state + // rather than from anything the effect asserts. + let mut deltas: BTreeMap = BTreeMap::new(); for operation in &resolved.operations { - apply_operation(state, operation)?; + for resource in operation_resources(operation) { + deltas.entry(resource).or_default().before = resource_total(state, resource); + } + } + for operation in &resolved.operations { + apply_operation(state, operation, &resolved.evidence)?; + match operation { + ResolvedOp::Transform { + from_resource, + into_resource, + qty, + .. + } => { + deltas.entry(*from_resource).or_default().spent += u128::from(qty.0); + deltas.entry(*into_resource).or_default().gained += u128::from(qty.0); + } + ResolvedOp::Consume { resource, qty, .. } => { + deltas.entry(*resource).or_default().consumed += u128::from(qty.0); + } + ResolvedOp::Admit { resource, qty, .. } => { + deltas.entry(*resource).or_default().admitted += u128::from(qty.0); + } + _ => {} + } + } + for (resource, delta) in &mut deltas { + delta.after = resource_total(state, *resource); + } + if patch::check_ledger(&deltas).is_some() { + return Err(KernelError::Invariant("custody does not conserve".into())); } Ok(()) } +/// Every resource an operation names, so `admit_resolved` can read its committed +/// total before touching it. +fn operation_resources(operation: &ResolvedOp) -> Vec { + match operation { + ResolvedOp::Transfer { resource, .. } + | ResolvedOp::Consume { resource, .. } + | ResolvedOp::Admit { resource, .. } => vec![*resource], + ResolvedOp::Transform { + from_resource, + into_resource, + .. + } => vec![*from_resource, *into_resource], + _ => Vec::new(), + } +} + +fn resource_total(state: &WorldState, resource: EntityId) -> u128 { + state + .holdings + .values() + .filter_map(|held| held.get(&resource)) + .map(|quantity| u128::from(quantity.0)) + .sum() +} + +/// What a holder holds. Absence is zero. +fn held(state: &WorldState, holder: SubjectId, resource: EntityId) -> u64 { + state + .holdings + .get(&holder) + .and_then(|held| held.get(&resource)) + .map_or(0, |quantity| quantity.0) +} + +/// Zero removes the resource key, and an emptied holder removes the holder key, +/// so `holdings` has exactly one representation of nothing. +fn set_held(state: &mut WorldState, holder: SubjectId, resource: EntityId, value: u64) { + if value == 0 { + let empty = if let Some(held) = state.holdings.get_mut(&holder) { + held.remove(&resource); + held.is_empty() + } else { + false + }; + if empty { + state.holdings.remove(&holder); + } + } else { + state + .holdings + .entry(holder) + .or_default() + .insert(resource, Quantity(value)); + } +} + +/// Whether a subject and a resource are both canonical and of the right kind. +fn custody_referents_exist(state: &WorldState, holder: SubjectId, resource: EntityId) -> bool { + state.subjects.contains_key(&holder) + && state + .entities + .get(&resource) + .is_some_and(|record| record.kind == EntityKind::Resource) +} + +fn dependency_target_exists(state: &WorldState, target: DependencyTarget) -> bool { + match target { + DependencyTarget::Resource(entity_id) => state + .entities + .get(&entity_id) + .is_some_and(|record| record.kind == EntityKind::Resource), + DependencyTarget::Route(edge_id) => state.edges.contains_key(&edge_id), + DependencyTarget::Subject(subject_id) => state.subjects.contains_key(&subject_id), + } +} + /// The component half of admission. Every precondition is re-derived from the /// partitions, so a forged operation cannot assert a move the topology refuses. -fn apply_operation(state: &mut WorldState, operation: &ResolvedOp) -> Result<(), KernelError> { +fn apply_operation( + state: &mut WorldState, + operation: &ResolvedOp, + evidence: &[EvidenceRef], +) -> Result<(), KernelError> { + let insufficient = || KernelError::Invariant("holder does not hold enough".into()); + let overflow = || KernelError::Invariant("holding would overflow".into()); + let unknown = || KernelError::Invariant("custody operation names no canonical referent".into()); + let zero = || KernelError::Invariant("custody operation moves nothing".into()); match operation { ResolvedOp::Relocate { subject_id, @@ -1322,10 +1460,172 @@ fn apply_operation(state: &mut WorldState, operation: &ResolvedOp) -> Result<(), } route.set_cost(*cost); } + ResolvedOp::Transfer { + from, + to, + resource, + qty, + } => { + if !custody_referents_exist(state, *from, *resource) || !state.subjects.contains_key(to) + { + return Err(unknown()); + } + if qty.0 == 0 || from == to { + return Err(zero()); + } + let remaining = held(state, *from, *resource) + .checked_sub(qty.0) + .ok_or_else(insufficient)?; + let credited = held(state, *to, *resource) + .checked_add(qty.0) + .ok_or_else(overflow)?; + set_held(state, *from, *resource, remaining); + set_held(state, *to, *resource, credited); + } + ResolvedOp::Transform { + holder, + from_resource, + into_resource, + qty, + } => { + if !custody_referents_exist(state, *holder, *from_resource) + || !custody_referents_exist(state, *holder, *into_resource) + { + return Err(unknown()); + } + if qty.0 == 0 || from_resource == into_resource { + return Err(zero()); + } + let remaining = held(state, *holder, *from_resource) + .checked_sub(qty.0) + .ok_or_else(insufficient)?; + let gained = held(state, *holder, *into_resource) + .checked_add(qty.0) + .ok_or_else(overflow)?; + set_held(state, *holder, *from_resource, remaining); + set_held(state, *holder, *into_resource, gained); + } + ResolvedOp::Consume { + holder, + resource, + qty, + } => { + if !custody_referents_exist(state, *holder, *resource) { + return Err(unknown()); + } + if qty.0 == 0 { + return Err(zero()); + } + let remaining = held(state, *holder, *resource) + .checked_sub(qty.0) + .ok_or_else(insufficient)?; + set_held(state, *holder, *resource, remaining); + } + ResolvedOp::Admit { + holder, + resource, + qty, + evidence: cited, + } => { + if !custody_referents_exist(state, *holder, *resource) { + return Err(unknown()); + } + if qty.0 == 0 { + return Err(zero()); + } + if !evidence.contains(cited) { + return Err(KernelError::Invariant( + "admitted quantity cites no evidence in its patch".into(), + )); + } + let admitted = held(state, *holder, *resource) + .checked_add(qty.0) + .ok_or_else(overflow)?; + set_held(state, *holder, *resource, admitted); + } + ResolvedOp::Bind { subject, target } | ResolvedOp::Release { subject, target } => { + let bind = matches!(operation, ResolvedOp::Bind { .. }); + if !state.subjects.contains_key(subject) || !dependency_target_exists(state, *target) { + return Err(unknown()); + } + if *target == DependencyTarget::Subject(*subject) { + return Err(KernelError::Invariant( + "a subject cannot depend on itself".into(), + )); + } + let bound = state + .dependencies + .get(subject) + .is_some_and(|targets| targets.contains(target)); + if bound == bind { + return Err(KernelError::Invariant( + "dependency operation changes nothing".into(), + )); + } + if bind { + state + .dependencies + .entry(*subject) + .or_default() + .insert(*target); + } else { + let empty = if let Some(targets) = state.dependencies.get_mut(subject) { + targets.remove(target); + targets.is_empty() + } else { + false + }; + if empty { + state.dependencies.remove(subject); + } + } + } } Ok(()) } +/// Exactly the components a subject's verification reads. One owner, consumed by +/// the scope digest and by the snapshot, so the two cannot drift. `routes` is +/// every edge whose `from` or `to` is the subject's place: an inbound route +/// decides who can arrive, and reading too little is a correctness hole while +/// reading too much only costs an extra rejection. `holdings` and `dependencies` +/// are the acting subject's own; a counterparty's holdings do not enter, because +/// a transfer changes both subjects' components and so changes both digests. +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] +pub(super) struct ScopeComponents { + position: Option, + routes: BTreeMap, + holdings: BTreeMap, + dependencies: BTreeSet, +} + +fn scope_components(state: &WorldState, subject_id: SubjectId) -> ScopeComponents { + let position = state.positions.get(&subject_id).copied(); + let routes = position + .map(|position| { + state + .edges + .iter() + .filter(|(_, record)| { + let (from, to) = record.endpoints(); + from == position.place || to == position.place + }) + .map(|(edge_id, record)| (*edge_id, record.clone())) + .collect() + }) + .unwrap_or_default(); + ScopeComponents { + position, + routes, + holdings: state.holdings.get(&subject_id).cloned().unwrap_or_default(), + dependencies: state + .dependencies + .get(&subject_id) + .cloned() + .unwrap_or_default(), + } +} + fn snapshot(state: &WorldState) -> Result { let subjects = state .subjects @@ -1343,6 +1643,7 @@ fn snapshot(state: &WorldState) -> Result { .filter(|(_, grant)| grant.scope == scope) .map(|(affordance_id, grant)| (grant.kind, *affordance_id)) .collect(); + let components = scope_components(state, *subject_id); Ok(SubjectSnapshot { id: *subject_id, label: subject.label.clone(), @@ -1351,10 +1652,10 @@ fn snapshot(state: &WorldState) -> Result { controller_mode: controller.mode(), human_controller: controller.human_principal().cloned(), affordances, - position: state - .positions - .get(subject_id) - .map(|position| position.place), + position: components.position.map(|position| position.place), + holdings: components.holdings, + dependencies: components.dependencies, + incident_routes: components.routes.into_keys().collect(), }) }) .collect::, KernelError>>()?; @@ -1368,6 +1669,15 @@ fn snapshot(state: &WorldState) -> Result { container: record.container, }) .collect(); + let resources = state + .entities + .iter() + .filter(|(_, record)| record.kind == EntityKind::Resource) + .map(|(entity_id, record)| ResourceSnapshot { + id: *entity_id, + label: record.label.clone(), + }) + .collect(); let routes = state .edges .iter() @@ -1394,6 +1704,7 @@ fn snapshot(state: &WorldState) -> Result { required_approvers: required_approvers(state), subjects, places, + resources, routes, events: state.events.clone(), opportunities: derive_opportunities(state)?, @@ -1434,10 +1745,8 @@ fn derive_opportunities(state: &WorldState) -> Result, .collect() } -/// The sole producer of a `ScopeDigest`. `routes` holds every edge whose `from` -/// or `to` is the subject's place: an inbound route decides who can arrive, and -/// reading too little is a correctness hole while reading too much only costs an -/// extra rejection. +/// The sole producer of a `ScopeDigest`. The components it reads come from +/// `scope_components`, which the snapshot reads too. fn scope_digest(state: &WorldState, scope: DecisionScope) -> Result { let controller = state .controller_assignments @@ -1449,27 +1758,13 @@ fn scope_digest(state: &WorldState, scope: DecisionScope) -> Result Declaration { + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: EntityKind::Resource, + container: None, + }) + } + + fn holder(handle: &str, label: &str, place: EntityId) -> Declaration { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: SubjectKind::Institution, + controller: NewController::OperationalAgent, + affordances: BTreeSet::from([AffordanceKind::Speak]), + position: Some(Ref::Existing(place)), + }) + } + + /// Declarations and evidence are Draft-only, so the resources, the holders, + /// and the one evidenced `Admit` that creates the opening balance all land + /// before activation. There is no holdings declaration field: quantity is + /// created by `Admit` and by nothing else, in this lane as in every other. + pub(super) fn custody_patch(topology: &Topology) -> WorldPatch { + WorldPatch { + declarations: vec![ + resource("tithe", "The Rhythm Tithe"), + resource("ingot", "The Cut Ingot"), + holder("clerk", "The Ledger Clerk", topology.yard), + holder("keeper", "The Gate Keeper", topology.gate), + ], + operations: vec![ComponentOp::Admit { + holder: Ref::Draft(DraftHandle::new("clerk")), + resource: Ref::Draft(DraftHandle::new("tithe")), + qty: Quantity(OPENING_BALANCE), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }], + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], + } + } + + pub(super) fn admit_custody(kernel: &mut WorldKernel, topology: &Topology) -> Custody { + let before = kernel.snapshot().unwrap(); + let receipt = submit_owner( + kernel, + &before, + CommandBody::AdmitPatch { + answers: None, + patch: custody_patch(topology), + }, + ); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + let entity = |label: &str| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared resource") + .0 + }; + let subject = |label: &str| { + *kernel + .state + .subjects + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared holder") + .0 + }; + Custody { + tithe: entity("The Rhythm Tithe"), + ingot: entity("The Cut Ingot"), + holder: subject("The Ledger Clerk"), + counterparty: subject("The Gate Keeper"), + } + } + + /// Topology, custody, then activation: everything a custody test needs, in + /// the one order the phase rules allow. + pub(super) fn custody_world(kernel: &mut WorldKernel) -> (Topology, Custody, WorldSnapshot) { + let topology = admit_topology(kernel); + let custody = admit_custody(kernel, &topology); + let active = activate(kernel); + (topology, custody, active) + } + + /// Submits as owner and returns the complete mismatch set. + pub(super) fn reject_owner( + kernel: &mut WorldKernel, + snapshot: &WorldSnapshot, + body: CommandBody, + ) -> Vec { + let error = kernel + .submit( + command( + snapshot, + CommandId::new(), + CallerId::Principal(owner()), + body, + ), + &auth_principal(owner()), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch, got {error:?}"); + }; + mismatches + } + + pub(super) fn operations(operations: Vec) -> CommandBody { + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations, + evidence: Vec::new(), + }, + } + } + pub(super) fn opportunity_for( snapshot: &WorldSnapshot, subject_id: SubjectId, @@ -3119,3 +3549,547 @@ mod tests { assert_eq!(kernel.snapshot().unwrap(), active); } } + +#[cfg(test)] +mod custody_tests { + use super::tests::{ + OPENING_BALANCE, TITHE_RECEIPT, activate, admit_custody, admit_topology, auth_principal, + command, creation, custody_world, operations, opportunity_for, owner, reject_owner, + submit_owner, + }; + use super::*; + + fn custody_kernel(path: &Path, title: &str) -> WorldKernel { + WorldKernel::create( + path.join("world.cc"), + creation(CommandId::new(), title), + &auth_principal(owner()), + ) + .expect("a created world") + .0 + } + + fn holding(kernel: &WorldKernel, holder: SubjectId, resource: EntityId) -> u64 { + held(&kernel.state, holder, resource) + } + + /// A forged `PatchAdmitted` never passes the resolver, so `admit_resolved` + /// re-derives every custody precondition from the committed partitions and + /// commits nothing when one fails. + /// + /// Deviation from the spec's wording, decided here: `ResolvedOp::Transfer` + /// carries one `qty`, so "a transfer whose debit and credit differ" is + /// unrepresentable — which is the stronger outcome that shape was chosen + /// for. The reachable forgery is a transfer the holder cannot cover, and + /// the conservation equation itself is falsified directly beside it. + #[test] + fn a_non_conserving_transfer_effect_does_not_apply() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Forged"); + let (_, custody, _) = custody_world(&mut kernel); + let before = kernel.state.holdings.clone(); + + let mut candidate = kernel.state.clone(); + let forged = WorldEffect::PatchAdmitted { + resolved: ResolvedPatch { + subjects: Vec::new(), + entities: Vec::new(), + routes: Vec::new(), + operations: vec![ResolvedOp::Transfer { + from: custody.holder, + to: custody.counterparty, + resource: custody.tithe, + qty: Quantity(OPENING_BALANCE + 1), + }], + evidence: Vec::new(), + }, + }; + let error = + apply_effect(&mut candidate, &CallerId::Principal(owner()), &forged).unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + assert_eq!(candidate.holdings, before); + + // The conservation equation is the one owner, and it refuses a ledger + // that does not balance regardless of which operation produced it. + let unbalanced = BTreeMap::from([( + custody.tithe, + LedgerDelta { + before: 7, + after: 9, + admitted: 1, + ..LedgerDelta::default() + }, + )]); + assert_eq!(patch::check_ledger(&unbalanced), Some(custody.tithe)); + let balanced = BTreeMap::from([( + custody.tithe, + LedgerDelta { + before: 7, + after: 8, + admitted: 1, + ..LedgerDelta::default() + }, + )]); + assert_eq!(patch::check_ledger(&balanced), None); + } + + /// Creation of quantity is attributable: an `Admit` whose ref is not in the + /// patch's own evidence list mints nothing and allocates no ID. + #[test] + fn an_admit_without_evidence_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Unevidenced"); + let topology = admit_topology(&mut kernel); + let before = kernel.snapshot().unwrap(); + let commits = kernel.journal.commit_count(); + + let mismatches = reject_owner( + &mut kernel, + &before, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("tithe"), + label: "The Rhythm Tithe".into(), + kind: EntityKind::Resource, + container: None, + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("clerk"), + label: "The Ledger Clerk".into(), + kind: SubjectKind::Institution, + controller: NewController::OperationalAgent, + affordances: BTreeSet::from([AffordanceKind::Speak]), + position: Some(Ref::Existing(topology.yard)), + }), + ], + operations: vec![ComponentOp::Admit { + holder: Ref::Draft(DraftHandle::new("clerk")), + resource: Ref::Draft(DraftHandle::new("tithe")), + qty: Quantity(4), + evidence: EvidenceRef::new("receipt:never-listed"), + }], + evidence: Vec::new(), + }, + }, + ); + + assert_eq!( + mismatches, + vec![Mismatch::AdmitWithoutEvidence { operation: 0 }] + ); + assert!(kernel.state.holdings.is_empty()); + assert_eq!(kernel.journal.commit_count(), commits); + assert_eq!(kernel.snapshot().unwrap(), before); + } + + #[test] + fn a_transfer_moves_the_exact_quantity_and_nothing_else() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Transfer"); + let (_, custody, active) = custody_world(&mut kernel); + let entities = kernel.state.entities.clone(); + let edges = kernel.state.edges.clone(); + let positions = kernel.state.positions.clone(); + + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }]), + ); + + assert_eq!(holding(&kernel, custody.holder, custody.tithe), 4); + assert_eq!(holding(&kernel, custody.counterparty, custody.tithe), 3); + assert_eq!(resource_total(&kernel.state, custody.tithe), 7); + assert_eq!(kernel.state.entities, entities); + assert_eq!(kernel.state.edges, edges); + assert_eq!(kernel.state.positions, positions); + } + + /// Absence is zero at both levels, so emptying a holding removes the + /// resource key and emptying a holder removes the holder key. + #[test] + fn consume_reduces_the_holding_and_emptying_removes_the_key() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Consume"); + let (_, custody, active) = custody_world(&mut kernel); + + let after_three = submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Consume { + holder: Ref::Existing(custody.holder), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }]), + ); + assert!(matches!(after_three, SubmitReceipt::Applied(_))); + assert_eq!(holding(&kernel, custody.holder, custody.tithe), 4); + + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::Consume { + holder: Ref::Existing(custody.holder), + resource: Ref::Existing(custody.tithe), + qty: Quantity(4), + }]), + ); + assert!(!kernel.state.holdings.contains_key(&custody.holder)); + let subject = kernel + .snapshot() + .unwrap() + .subjects + .into_iter() + .find(|subject| subject.id == custody.holder) + .expect("the holder is in the snapshot"); + assert!(subject.holdings.is_empty()); + } + + #[test] + fn a_transform_conserves_one_for_one() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Transform"); + let (_, custody, active) = custody_world(&mut kernel); + + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Transform { + holder: Ref::Existing(custody.holder), + from_resource: Ref::Existing(custody.tithe), + into_resource: Ref::Existing(custody.ingot), + qty: Quantity(5), + }]), + ); + + assert_eq!(holding(&kernel, custody.holder, custody.tithe), 2); + assert_eq!(holding(&kernel, custody.holder, custody.ingot), 5); + assert_eq!(resource_total(&kernel.state, custody.tithe), 2); + assert_eq!(resource_total(&kernel.state, custody.ingot), 5); + } + + #[test] + fn spending_more_than_held_is_rejected_with_insufficient_custody() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Insufficient"); + let (_, custody, _) = custody_world(&mut kernel); + let too_much = Quantity(OPENING_BALANCE + 1); + let attempts = [ + ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: too_much, + }, + ComponentOp::Transform { + holder: Ref::Existing(custody.holder), + from_resource: Ref::Existing(custody.tithe), + into_resource: Ref::Existing(custody.ingot), + qty: too_much, + }, + ComponentOp::Consume { + holder: Ref::Existing(custody.holder), + resource: Ref::Existing(custody.tithe), + qty: too_much, + }, + ]; + + for attempt in attempts { + let snapshot = kernel.snapshot().unwrap(); + let commits = kernel.journal.commit_count(); + let mismatches = reject_owner(&mut kernel, &snapshot, operations(vec![attempt])); + assert_eq!( + mismatches, + vec![Mismatch::InsufficientCustody { operation: 0 }] + ); + assert_eq!(kernel.journal.commit_count(), commits); + assert_eq!(kernel.snapshot().unwrap(), snapshot); + } + } + + /// A holder with no entry holds zero: there is no second name for it and no + /// zero entry anywhere in the snapshot. + #[test] + fn an_absent_holding_is_zero() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Absent"); + let (_, custody, active) = custody_world(&mut kernel); + + let mismatches = reject_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Consume { + holder: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(1), + }]), + ); + assert_eq!( + mismatches, + vec![Mismatch::InsufficientCustody { operation: 0 }] + ); + let counterparty = kernel + .snapshot() + .unwrap() + .subjects + .into_iter() + .find(|subject| subject.id == custody.counterparty) + .expect("the counterparty is in the snapshot"); + assert!(counterparty.holdings.is_empty()); + } + + #[test] + fn a_zero_quantity_operation_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Zero"); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + + // `Admit` is Draft-only, because Active refuses a patch carrying + // evidence, so its zero case is proven before activation. + let draft = kernel.snapshot().unwrap(); + let mismatches = reject_owner( + &mut kernel, + &draft, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Admit { + holder: Ref::Existing(custody.holder), + resource: Ref::Existing(custody.tithe), + qty: Quantity(0), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }], + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], + }, + }, + ); + assert_eq!(mismatches, vec![Mismatch::ZeroQuantity { operation: 0 }]); + + let active = activate(&mut kernel); + for attempt in [ + ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(0), + }, + ComponentOp::Consume { + holder: Ref::Existing(custody.holder), + resource: Ref::Existing(custody.tithe), + qty: Quantity(0), + }, + ] { + let snapshot = kernel.snapshot().unwrap(); + let mismatches = reject_owner(&mut kernel, &snapshot, operations(vec![attempt])); + assert_eq!(mismatches, vec![Mismatch::ZeroQuantity { operation: 0 }]); + } + assert_eq!(kernel.snapshot().unwrap(), active); + } + + #[test] + fn dependency_bind_and_release_round_trip() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Dependency"); + let (_, custody, active) = custody_world(&mut kernel); + let before = kernel.state.dependencies.clone(); + + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Resource(Ref::Existing(custody.tithe)), + }]), + ); + assert_eq!( + kernel.state.dependencies.get(&custody.holder), + Some(&BTreeSet::from([DependencyTarget::Resource(custody.tithe)])) + ); + + let bound = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &bound, + operations(vec![ComponentOp::Release { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Resource(Ref::Existing(custody.tithe)), + }]), + ); + assert_eq!(kernel.state.dependencies, before); + assert!(!kernel.state.dependencies.contains_key(&custody.holder)); + } + + /// A bind that changes nothing is `NoOperationEffect`, the name pass 2 + /// already owns; a subject bound to itself is `SelfDependency`. + #[test] + fn a_duplicate_dependency_bind_is_rejected_as_no_effect() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Duplicate"); + let (_, custody, active) = custody_world(&mut kernel); + + let bind = ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Resource(Ref::Existing(custody.tithe)), + }; + submit_owner(&mut kernel, &active, operations(vec![bind.clone()])); + + let bound = kernel.snapshot().unwrap(); + assert_eq!( + reject_owner(&mut kernel, &bound, operations(vec![bind])), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + assert_eq!( + reject_owner( + &mut kernel, + &bound, + operations(vec![ComponentOp::Release { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Resource(Ref::Existing(custody.ingot)), + }]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + assert_eq!( + reject_owner( + &mut kernel, + &bound, + operations(vec![ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Subject(Ref::Existing(custody.holder)), + }]), + ), + vec![Mismatch::SelfDependency { operation: 0 }] + ); + } + + /// Pass 3 owns the representation of a dependency, not its consequence. A + /// dependency on a closed route commits and shows up in the subject's + /// components; nothing rejects it and nothing fires from it. + #[test] + fn a_dependency_on_a_closed_route_is_representable_and_visible() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Closed"); + let (topology, custody, active) = custody_world(&mut kernel); + assert!(!kernel.state.edges[&topology.shutter].is_open()); + + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Route(Ref::Existing(topology.shutter)), + }]), + ); + + let subject = kernel + .snapshot() + .unwrap() + .subjects + .into_iter() + .find(|subject| subject.id == custody.holder) + .expect("the holder is in the snapshot"); + assert_eq!( + subject.dependencies, + BTreeSet::from([DependencyTarget::Route(topology.shutter)]) + ); + } + + /// The digest reads the acting subject's own holdings and dependencies, and + /// only its own: a counterparty's churn does not move it. + #[test] + fn scope_digest_reads_holdings_and_dependencies() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "ScopeCustody"); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + activate(&mut kernel); + let scope = DecisionScope { + subject_id: custody.holder, + }; + let base = scope_digest(&kernel.state, scope).unwrap(); + + let mut spent = kernel.state.clone(); + set_held(&mut spent, custody.holder, custody.tithe, 1); + assert_ne!(scope_digest(&spent, scope).unwrap(), base); + + let mut gained = kernel.state.clone(); + set_held(&mut gained, custody.holder, custody.ingot, 1); + assert_ne!(scope_digest(&gained, scope).unwrap(), base); + + let mut bound = kernel.state.clone(); + bound + .dependencies + .entry(custody.holder) + .or_default() + .insert(DependencyTarget::Resource(custody.tithe)); + assert_ne!(scope_digest(&bound, scope).unwrap(), base); + + let mut elsewhere = kernel.state.clone(); + set_held(&mut elsewhere, custody.counterparty, custody.tithe, 9); + elsewhere + .dependencies + .entry(custody.counterparty) + .or_default() + .insert(DependencyTarget::Resource(custody.ingot)); + assert_eq!(scope_digest(&elsewhere, scope).unwrap(), base); + } + + /// A proposal bound while its subject held seven must not commit after + /// someone took six. Custody churn rejects more bound proposals than route + /// churn did; that is the binding working. + #[test] + fn a_spend_bound_to_a_stale_balance_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Stale"); + let (_, custody, active) = custody_world(&mut kernel); + let bound = opportunity_for(&active, custody.holder); + + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(6), + }]), + ); + + let moved = kernel.snapshot().unwrap(); + let commits = kernel.journal.commit_count(); + let error = kernel + .submit( + command( + &moved, + CommandId::new(), + CallerId::Controller(bound.controller_id), + CommandBody::ExerciseDecision { + opportunity: bound.clone(), + invocation: DecisionInvocation { + affordance_id: bound.affordance_ids[0], + action: DecisionAction::Speak { + text: "The tithe is short.".into(), + }, + }, + }, + ), + &AuthenticatedCaller::fixture(CallerId::Controller(bound.controller_id)), + ) + .unwrap_err(); + + assert!(matches!(error, KernelError::ScopeChanged { .. })); + assert_eq!(kernel.journal.commit_count(), commits); + assert_eq!(kernel.snapshot().unwrap(), moved); + } +} diff --git a/crates/ghostlight-dungeon/src/world/patch.rs b/crates/ghostlight-dungeon/src/world/patch.rs index 1729a42..5b3d875 100644 --- a/crates/ghostlight-dungeon/src/world/patch.rs +++ b/crates/ghostlight-dungeon/src/world/patch.rs @@ -51,6 +51,39 @@ pub(crate) struct Cost(pub(crate) u32); /// One year of minutes; bounds path sums. pub(super) const MAX_ROUTE_COST: u32 = 525_600; +/// A conserved count. Unsigned because a holding can never be negative: a signed +/// type would make "owes 3 iron" representable and push the real check to runtime +/// anyway. Subtraction is `checked_sub` and its failure is `InsufficientCustody`; +/// addition is `checked_add` and its failure is `QuantityOverflow`. No saturating +/// arithmetic anywhere, because a silent clamp is a silent conservation break. +/// There is no maximum: nothing sums quantities across resources, so the honest +/// bound is the type's. There is no unit, because a unit is where prices enter. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct Quantity(pub(crate) u64); + +/// What a subject depends on. A dependency is a bare relation: no magnitude, no +/// kind beyond its target namespace, no clock, no cost. The variant selects the +/// resolver, so the target kind is carried by the type rather than checked after +/// the fact. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "target", content = "id", rename_all = "snake_case")] +pub(crate) enum DependencyTarget { + Resource(EntityId), + Route(EdgeId), + Subject(SubjectId), +} + +/// The proposal-time twin of [`DependencyTarget`], carrying references rather +/// than canonical IDs. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "target", content = "ref", rename_all = "snake_case")] +pub(crate) enum DependencyRef { + Resource(Ref), + Route(Ref), + Subject(Ref), +} + /// Where a subject stands. One place, derived from nothing else. #[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] #[serde(deny_unknown_fields)] @@ -112,6 +145,16 @@ pub(crate) enum Site { #[serde(transparent)] pub(crate) struct EvidenceRef(String); +impl EvidenceRef { + /// Gated because no `AdmitPatch` ingress exists yet: every caller that + /// builds a patch today is a test. It loses the gate in the same commit as + /// the first production patch author. + #[cfg(test)] + pub(super) fn new(value: impl Into) -> Self { + Self(value.into()) + } +} + /// `position` is the subject's presence: one place it stands in. A subject /// declared without one is unplaced until a later pass gives placement an owner. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] @@ -174,6 +217,46 @@ pub(crate) enum ComponentOp { route: Ref, cost: Cost, }, + Transfer { + from: Ref, + to: Ref, + resource: Ref, + qty: Quantity, + }, + /// One-for-one relabel: the same `qty` leaves `from_resource` and arrives in + /// `into_resource`, held by the same subject. A ratio would be a recipe, and + /// recipes belong to the consumer that owns production; the op shape makes a + /// non-conserving transform unrepresentable rather than merely checkable. A + /// world that needs lossy conversion writes `Transform` plus `Consume`, and + /// both terms then appear in the ledger. + Transform { + holder: Ref, + from_resource: Ref, + into_resource: Ref, + qty: Quantity, + }, + Consume { + holder: Ref, + resource: Ref, + qty: Quantity, + }, + /// The only creation path for quantity, in every lane including genesis. Its + /// `evidence` must appear in the same patch's `evidence` list, which makes + /// creation attributable; the commit chain then makes it tamper-evident. + Admit { + holder: Ref, + resource: Ref, + qty: Quantity, + evidence: EvidenceRef, + }, + Bind { + subject: Ref, + target: DependencyRef, + }, + Release { + subject: Ref, + target: DependencyRef, + }, } /// Empty on purpose: an `Option` can only be `None`, so the @@ -261,6 +344,33 @@ pub(crate) enum Mismatch { NoOperationEffect { operation: usize, }, + /// The holder does not hold enough. Absence is zero, so "holds none at all" + /// is this variant at the boundary rather than a second name. + InsufficientCustody { + operation: usize, + }, + /// A custody operation naming `Quantity(0)`: it moves nothing. + ZeroQuantity { + operation: usize, + }, + /// A credit that would leave a holding above `u64::MAX`. + QuantityOverflow { + operation: usize, + }, + /// An `Admit` whose `EvidenceRef` is not listed in this patch's `evidence`. + AdmitWithoutEvidence { + operation: usize, + }, + /// A `Bind` or `Release` naming the acting subject as its own target. + SelfDependency { + operation: usize, + }, + /// The candidate ledger does not balance for this resource: the total after + /// the patch is not the total before plus what was admitted and gained, less + /// what was consumed and spent. + CustodyNotConserved { + resource: RefName, + }, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] @@ -376,6 +486,76 @@ pub(super) enum ResolvedOp { edge_id: EdgeId, cost: Cost, }, + Transfer { + from: SubjectId, + to: SubjectId, + resource: EntityId, + qty: Quantity, + }, + Transform { + holder: SubjectId, + from_resource: EntityId, + into_resource: EntityId, + qty: Quantity, + }, + Consume { + holder: SubjectId, + resource: EntityId, + qty: Quantity, + }, + Admit { + holder: SubjectId, + resource: EntityId, + qty: Quantity, + evidence: EvidenceRef, + }, + Bind { + subject: SubjectId, + target: DependencyTarget, + }, + Release { + subject: SubjectId, + target: DependencyTarget, + }, +} + +/// One resource's movement across a whole patch. Accumulators are `u128` so an +/// intermediate total cannot overflow while a stored per-holder `Quantity` stays +/// `u64`. +#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)] +pub(super) struct LedgerDelta { + pub(super) before: u128, + pub(super) after: u128, + pub(super) admitted: u128, + pub(super) consumed: u128, + pub(super) gained: u128, + pub(super) spent: u128, +} + +/// The only statement of custody conservation, called by the resolver over the +/// candidate map and again by `admit_resolved` over the committed partitions. +/// Returns the first resource whose ledger does not balance, in key order, so +/// the verdict is deterministic. +/// +/// `Transfer` contributes to no term: its correctness is *proven by* this +/// equation, because a transfer that moved a different amount out than in breaks +/// the total for that resource. `Transform` contributes the same `qty` to one +/// `spent` and one `gained`, so the one-for-one rule is this equation restricted +/// to a single operation. Nothing else states conservation anywhere. +pub(super) fn check_ledger(deltas: &BTreeMap) -> Option { + deltas + .iter() + .find(|(_, delta)| { + let credited = delta + .before + .checked_add(delta.admitted) + .and_then(|total| total.checked_add(delta.gained)); + let expected = credited + .and_then(|total| total.checked_sub(delta.consumed)) + .and_then(|total| total.checked_sub(delta.spent)); + expected != Some(delta.after) + }) + .map(|(resource, _)| resource.clone()) } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] @@ -422,6 +602,15 @@ fn key_of(reference: &Ref) -> Key { } } +/// [`DependencyTarget`] over candidate keys, so a dependency on a structure this +/// patch declares is checked before any ID is minted. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum TargetKey { + Resource(Key), + Route(Key), + Subject(Key), +} + #[derive(Clone, Debug)] struct RouteCandidate { from: Key, @@ -470,28 +659,32 @@ pub(super) fn is_valid_cost(cost: Cost) -> bool { (1..=MAX_ROUTE_COST).contains(&cost.0) } -fn resolve_place( +/// The one entity resolver. `expected` names the kind the referring site +/// requires; a handle or ID that answers with another kind is `WrongKind`. +fn resolve_entity( site: Site, + expected_kind: EntityKind, reference: &Ref, index: &BTreeMap, entities: &BTreeMap, mismatches: &mut Vec, ) -> Option> { + let expected = RefKind::Entity(expected_kind); match reference { Ref::Draft(named) => match index.get(named) { None => { mismatches.push(Mismatch::UnresolvedDraft { site, referent: named.clone(), - expected: PLACE, + expected, }); None } - Some(kind) if *kind != PLACE => { + Some(kind) if *kind != expected => { mismatches.push(Mismatch::WrongKind { site, referent: RefName::Entity(reference.clone()), - expected: PLACE, + expected, actual: *kind, }); None @@ -500,17 +693,14 @@ fn resolve_place( }, Ref::Existing(entity_id) => match entities.get(entity_id) { None => { - mismatches.push(Mismatch::UnknownCanonical { - site, - expected: PLACE, - }); + mismatches.push(Mismatch::UnknownCanonical { site, expected }); None } - Some(record) if record.kind != EntityKind::Place => { + Some(record) if record.kind != expected_kind => { mismatches.push(Mismatch::WrongKind { site, referent: RefName::Entity(reference.clone()), - expected: PLACE, + expected, actual: RefKind::Entity(record.kind), }); None @@ -604,6 +794,59 @@ fn resolve_route( } } +fn resolve_dependency_target( + site: Site, + target: &DependencyRef, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> Option { + match target { + DependencyRef::Resource(reference) => resolve_entity( + site, + EntityKind::Resource, + reference, + index, + &state.entities, + mismatches, + ) + .map(TargetKey::Resource), + DependencyRef::Route(reference) => { + resolve_route(site, reference, index, &state.edges, mismatches).map(TargetKey::Route) + } + DependencyRef::Subject(reference) => { + resolve_subject(site, reference, index, &state.subjects, mismatches) + .map(TargetKey::Subject) + } + } +} + +/// What a holder holds in the candidate map. Absence is zero, at both levels. +fn candidate_held( + holdings: &BTreeMap<(Key, Key), Quantity>, + holder: &Key, + resource: &Key, +) -> u64 { + holdings + .get(&(holder.clone(), resource.clone())) + .map_or(0, |quantity| quantity.0) +} + +/// Zero removes the slot, so one representation of nothing survives the patch. +fn candidate_set( + holdings: &mut BTreeMap<(Key, Key), Quantity>, + holder: &Key, + resource: &Key, + value: u64, +) { + let slot = (holder.clone(), resource.clone()); + if value == 0 { + holdings.remove(&slot); + } else { + holdings.insert(slot, Quantity(value)); + } +} + /// The one resolution owner for every admission lane: declarations, references, /// topology admission, and operation preconditions. Every check runs against the /// complete candidate graph — what the world already holds plus what this patch @@ -704,6 +947,36 @@ pub(super) fn resolve_patch( .iter() .map(|(subject_id, position)| (Key::Existing(*subject_id), Key::Existing(position.place))) .collect(); + let mut holdings: BTreeMap<(Key, Key), Quantity> = state + .holdings + .iter() + .flat_map(|(subject_id, held)| { + held.iter().map(move |(entity_id, quantity)| { + ( + (Key::Existing(*subject_id), Key::Existing(*entity_id)), + *quantity, + ) + }) + }) + .collect(); + let seeded_holdings = holdings.clone(); + let mut dependencies: BTreeSet<(Key, TargetKey)> = state + .dependencies + .iter() + .flat_map(|(subject_id, bound)| { + bound.iter().map(move |target| { + ( + Key::Existing(*subject_id), + match target { + DependencyTarget::Resource(id) => TargetKey::Resource(Key::Existing(*id)), + DependencyTarget::Route(id) => TargetKey::Route(Key::Existing(*id)), + DependencyTarget::Subject(id) => TargetKey::Subject(Key::Existing(*id)), + }, + ) + }) + }) + .collect(); + let mut deltas: BTreeMap, LedgerDelta> = BTreeMap::new(); let mut declared_places: Vec<(DraftHandle, Key)> = Vec::new(); for declaration in &patch.declarations { @@ -721,8 +994,9 @@ pub(super) fn resolve_patch( expected: PLACE, actual: RefKind::Entity(entity.kind), }); - } else if let Some(parent) = resolve_place( + } else if let Some(parent) = resolve_entity( Site::Declaration(entity.handle.clone()), + EntityKind::Place, reference, &index, &state.entities, @@ -734,8 +1008,9 @@ pub(super) fn resolve_patch( } Declaration::Subject(subject) => { if let Some(reference) = &subject.position - && let Some(place) = resolve_place( + && let Some(place) = resolve_entity( Site::Declaration(subject.handle.clone()), + EntityKind::Place, reference, &index, &state.entities, @@ -746,15 +1021,17 @@ pub(super) fn resolve_patch( } } Declaration::Route(route) => { - let from = resolve_place( + let from = resolve_entity( Site::Declaration(route.handle.clone()), + EntityKind::Place, &route.from, &index, &state.entities, &mut mismatches, ); - let to = resolve_place( + let to = resolve_entity( Site::Declaration(route.handle.clone()), + EntityKind::Place, &route.to, &index, &state.entities, @@ -900,9 +1177,299 @@ pub(super) fn resolve_patch( candidate.cost = *cost; } } + ComponentOp::Transfer { + from, + to, + resource, + qty, + } => { + let from_key = resolve_subject( + Site::Operation(position), + from, + &index, + &state.subjects, + &mut mismatches, + ); + let to_key = resolve_subject( + Site::Operation(position), + to, + &index, + &state.subjects, + &mut mismatches, + ); + let resource_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + resource, + &index, + &state.entities, + &mut mismatches, + ); + if qty.0 == 0 { + mismatches.push(Mismatch::ZeroQuantity { + operation: position, + }); + } + let (Some(from_key), Some(to_key), Some(resource_key)) = + (from_key, to_key, resource_key) + else { + continue; + }; + if from_key == to_key { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + continue; + } + if qty.0 == 0 { + continue; + } + let held = candidate_held(&holdings, &from_key, &resource_key); + let Some(remaining) = held.checked_sub(qty.0) else { + mismatches.push(Mismatch::InsufficientCustody { + operation: position, + }); + continue; + }; + let Some(credited) = + candidate_held(&holdings, &to_key, &resource_key).checked_add(qty.0) + else { + mismatches.push(Mismatch::QuantityOverflow { + operation: position, + }); + continue; + }; + candidate_set(&mut holdings, &from_key, &resource_key, remaining); + candidate_set(&mut holdings, &to_key, &resource_key, credited); + // A transfer contributes to no ledger term: the equation proves + // it, because moving a different amount out than in breaks the + // resource's total. + deltas.entry(resource_key).or_default(); + } + ComponentOp::Transform { + holder, + from_resource, + into_resource, + qty, + } => { + let holder_key = resolve_subject( + Site::Operation(position), + holder, + &index, + &state.subjects, + &mut mismatches, + ); + let from_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + from_resource, + &index, + &state.entities, + &mut mismatches, + ); + let into_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + into_resource, + &index, + &state.entities, + &mut mismatches, + ); + if qty.0 == 0 { + mismatches.push(Mismatch::ZeroQuantity { + operation: position, + }); + } + let (Some(holder_key), Some(from_key), Some(into_key)) = + (holder_key, from_key, into_key) + else { + continue; + }; + if from_key == into_key { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + continue; + } + if qty.0 == 0 { + continue; + } + let Some(remaining) = + candidate_held(&holdings, &holder_key, &from_key).checked_sub(qty.0) + else { + mismatches.push(Mismatch::InsufficientCustody { + operation: position, + }); + continue; + }; + let Some(gained) = + candidate_held(&holdings, &holder_key, &into_key).checked_add(qty.0) + else { + mismatches.push(Mismatch::QuantityOverflow { + operation: position, + }); + continue; + }; + candidate_set(&mut holdings, &holder_key, &from_key, remaining); + candidate_set(&mut holdings, &holder_key, &into_key, gained); + deltas.entry(from_key).or_default().spent += u128::from(qty.0); + deltas.entry(into_key).or_default().gained += u128::from(qty.0); + } + ComponentOp::Consume { + holder, + resource, + qty, + } => { + let holder_key = resolve_subject( + Site::Operation(position), + holder, + &index, + &state.subjects, + &mut mismatches, + ); + let resource_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + resource, + &index, + &state.entities, + &mut mismatches, + ); + if qty.0 == 0 { + mismatches.push(Mismatch::ZeroQuantity { + operation: position, + }); + } + let (Some(holder_key), Some(resource_key)) = (holder_key, resource_key) else { + continue; + }; + if qty.0 == 0 { + continue; + } + let Some(remaining) = + candidate_held(&holdings, &holder_key, &resource_key).checked_sub(qty.0) + else { + mismatches.push(Mismatch::InsufficientCustody { + operation: position, + }); + continue; + }; + candidate_set(&mut holdings, &holder_key, &resource_key, remaining); + deltas.entry(resource_key).or_default().consumed += u128::from(qty.0); + } + ComponentOp::Admit { + holder, + resource, + qty, + evidence, + } => { + let holder_key = resolve_subject( + Site::Operation(position), + holder, + &index, + &state.subjects, + &mut mismatches, + ); + let resource_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + resource, + &index, + &state.entities, + &mut mismatches, + ); + if qty.0 == 0 { + mismatches.push(Mismatch::ZeroQuantity { + operation: position, + }); + } + let evidenced = is_canonical_text(&evidence.0) && patch.evidence.contains(evidence); + if !evidenced { + mismatches.push(Mismatch::AdmitWithoutEvidence { + operation: position, + }); + } + let (Some(holder_key), Some(resource_key)) = (holder_key, resource_key) else { + continue; + }; + if qty.0 == 0 || !evidenced { + continue; + } + let Some(admitted) = + candidate_held(&holdings, &holder_key, &resource_key).checked_add(qty.0) + else { + mismatches.push(Mismatch::QuantityOverflow { + operation: position, + }); + continue; + }; + candidate_set(&mut holdings, &holder_key, &resource_key, admitted); + deltas.entry(resource_key).or_default().admitted += u128::from(qty.0); + } + ComponentOp::Bind { subject, target } | ComponentOp::Release { subject, target } => { + let bind = matches!(operation, ComponentOp::Bind { .. }); + let subject_key = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let target_key = resolve_dependency_target( + Site::Operation(position), + target, + &index, + state, + &mut mismatches, + ); + let (Some(subject_key), Some(target_key)) = (subject_key, target_key) else { + continue; + }; + if target_key == TargetKey::Subject(subject_key.clone()) { + mismatches.push(Mismatch::SelfDependency { + operation: position, + }); + continue; + } + let slot = (subject_key, target_key); + if dependencies.contains(&slot) == bind { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else if bind { + dependencies.insert(slot); + } else { + dependencies.remove(&slot); + } + } } } + // Conservation, over the complete candidate after every operation has been + // applied in order. Never per operation: a patch whose operations + // individually balance but whose net does not is impossible, and an + // intermediate negative was already caught above as `InsufficientCustody`. + for (resource_key, delta) in &mut deltas { + delta.before = seeded_holdings + .iter() + .filter(|((_, resource), _)| resource == resource_key) + .map(|(_, quantity)| u128::from(quantity.0)) + .sum(); + delta.after = holdings + .iter() + .filter(|((_, resource), _)| resource == resource_key) + .map(|(_, quantity)| u128::from(quantity.0)) + .sum(); + } + if let Some(resource) = check_ledger(&deltas) { + mismatches.push(Mismatch::CustodyNotConserved { + resource: RefName::Entity(match resource { + Key::Existing(entity_id) => Ref::Existing(entity_id), + Key::Draft(handle) => Ref::Draft(handle), + }), + }); + } + if patch.declarations.is_empty() && patch.operations.is_empty() { mismatches.push(Mismatch::NoCanonicalChange); } @@ -952,12 +1519,12 @@ pub(super) fn resolve_patch( }, }); } - let place_id = |key: &Key| -> EntityId { + let entity_id_of = |key: &Key| -> EntityId { match key { Key::Existing(entity_id) => *entity_id, Key::Draft(handle) => *allocated_entities .get(handle) - .expect("a draft place reference resolved above"), + .expect("a draft entity reference resolved above"), } }; for (resolved, declaration) in entities @@ -975,7 +1542,7 @@ pub(super) fn resolve_patch( resolved.entity.container = declaration .container .as_ref() - .map(|reference| place_id(&key_of(reference))); + .map(|reference| entity_id_of(&key_of(reference))); } let mut allocated_routes: BTreeMap = BTreeMap::new(); @@ -1002,8 +1569,8 @@ pub(super) fn resolve_patch( edge_id, edge: EdgeRecord::Route { label: route.label.clone(), - from: place_id(&key_of(&route.from)), - to: place_id(&key_of(&route.to)), + from: entity_id_of(&key_of(&route.from)), + to: entity_id_of(&key_of(&route.to)), access: route.access, cost: route.cost, open: true, @@ -1074,7 +1641,7 @@ pub(super) fn resolve_patch( controller, affordances, position: input.position.as_ref().map(|reference| Position { - place: place_id(&key_of(reference)), + place: entity_id_of(&key_of(reference)), }), }); } @@ -1095,6 +1662,19 @@ pub(super) fn resolve_patch( .expect("a draft route reference resolved above"), } }; + let target_of = |target: &DependencyRef| -> DependencyTarget { + match target { + DependencyRef::Resource(reference) => { + DependencyTarget::Resource(entity_id_of(&key_of(reference))) + } + DependencyRef::Route(reference) => { + DependencyTarget::Route(edge_id_of(&key_of(reference))) + } + DependencyRef::Subject(reference) => { + DependencyTarget::Subject(subject_id_of(&key_of(reference))) + } + } + }; let operations = patch .operations .iter() @@ -1113,6 +1693,56 @@ pub(super) fn resolve_patch( edge_id: edge_id_of(&key_of(route)), cost: *cost, }, + ComponentOp::Transfer { + from, + to, + resource, + qty, + } => ResolvedOp::Transfer { + from: subject_id_of(&key_of(from)), + to: subject_id_of(&key_of(to)), + resource: entity_id_of(&key_of(resource)), + qty: *qty, + }, + ComponentOp::Transform { + holder, + from_resource, + into_resource, + qty, + } => ResolvedOp::Transform { + holder: subject_id_of(&key_of(holder)), + from_resource: entity_id_of(&key_of(from_resource)), + into_resource: entity_id_of(&key_of(into_resource)), + qty: *qty, + }, + ComponentOp::Consume { + holder, + resource, + qty, + } => ResolvedOp::Consume { + holder: subject_id_of(&key_of(holder)), + resource: entity_id_of(&key_of(resource)), + qty: *qty, + }, + ComponentOp::Admit { + holder, + resource, + qty, + evidence, + } => ResolvedOp::Admit { + holder: subject_id_of(&key_of(holder)), + resource: entity_id_of(&key_of(resource)), + qty: *qty, + evidence: evidence.clone(), + }, + ComponentOp::Bind { subject, target } => ResolvedOp::Bind { + subject: subject_id_of(&key_of(subject)), + target: target_of(target), + }, + ComponentOp::Release { subject, target } => ResolvedOp::Release { + subject: subject_id_of(&key_of(subject)), + target: target_of(target), + }, }) .collect();