ghostlight-dungeon: cut the duplicated incident-route scan, add Custody, Dependency, conservation, and evidenced admission

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<SubjectId, BTreeMap<EntityId,
  Quantity>>` and `dependencies: BTreeMap<SubjectId, BTreeSet<
  DependencyTarget>>`: 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 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-04 18:48:22 +02:00
commit 48de96b0a4
4 changed files with 1950 additions and 68 deletions

View file

@ -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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<String, ControllerError> {
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]

View file

@ -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(&not_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(_))
));
}
}

File diff suppressed because it is too large Load diff

View file

@ -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<EntityId>),
Route(Ref<EdgeId>),
Subject(Ref<SubjectId>),
}
/// 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<String>) -> 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<EdgeId>,
cost: Cost,
},
Transfer {
from: Ref<SubjectId>,
to: Ref<SubjectId>,
resource: Ref<EntityId>,
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<SubjectId>,
from_resource: Ref<EntityId>,
into_resource: Ref<EntityId>,
qty: Quantity,
},
Consume {
holder: Ref<SubjectId>,
resource: Ref<EntityId>,
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<SubjectId>,
resource: Ref<EntityId>,
qty: Quantity,
evidence: EvidenceRef,
},
Bind {
subject: Ref<SubjectId>,
target: DependencyRef,
},
Release {
subject: Ref<SubjectId>,
target: DependencyRef,
},
}
/// Empty on purpose: an `Option<PatchAnswer>` 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<R: Ord + Clone>(deltas: &BTreeMap<R, LedgerDelta>) -> Option<R> {
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<Id: Copy>(reference: &Ref<Id>) -> Key<Id> {
}
}
/// [`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<EntityId>),
Route(Key<EdgeId>),
Subject(Key<SubjectId>),
}
#[derive(Clone, Debug)]
struct RouteCandidate {
from: Key<EntityId>,
@ -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<EntityId>,
index: &BTreeMap<DraftHandle, RefKind>,
entities: &BTreeMap<EntityId, EntityRecord>,
mismatches: &mut Vec<Mismatch>,
) -> Option<Key<EntityId>> {
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<DraftHandle, RefKind>,
state: &super::WorldState,
mismatches: &mut Vec<Mismatch>,
) -> Option<TargetKey> {
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<SubjectId>, Key<EntityId>), Quantity>,
holder: &Key<SubjectId>,
resource: &Key<EntityId>,
) -> 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<SubjectId>, Key<EntityId>), Quantity>,
holder: &Key<SubjectId>,
resource: &Key<EntityId>,
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<SubjectId>, Key<EntityId>), 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<SubjectId>, 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<Key<EntityId>, LedgerDelta> = BTreeMap::new();
let mut declared_places: Vec<(DraftHandle, Key<EntityId>)> = 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>| -> EntityId {
let entity_id_of = |key: &Key<EntityId>| -> 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<DraftHandle, EdgeId> = 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();