From d7fba90c712a25e6c04aa88a7ecf8f7877422a71 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 4 Sep 2026 23:53:58 +0200 Subject: [PATCH] Give the world a clock, commitments, pressure, boundaries, and scale Ontology widening pass 7. The world acquires a fictional clock advanced by exactly one command body; promises acquire a due date; an unmet promise becomes stored pressure; pressure orders whose turn it is without deciding whether a turn exists; and the places the world has not grown into become derivable rather than noticed. Co-Authored-By: Claude Opus 5 --- crates/ghostlight-dungeon/src/eve.rs | 38 +- crates/ghostlight-dungeon/src/runtime.rs | 43 +- crates/ghostlight-dungeon/src/world/action.rs | 310 +++++-- crates/ghostlight-dungeon/src/world/clock.rs | 209 +++++ .../src/world/controllers.rs | 55 +- .../ghostlight-dungeon/src/world/journal.rs | 129 ++- .../ghostlight-dungeon/src/world/mailbox.rs | 26 +- crates/ghostlight-dungeon/src/world/mod.rs | 869 +++++++++++++++++- crates/ghostlight-dungeon/src/world/patch.rs | 799 +++++++++++++++- 9 files changed, 2305 insertions(+), 173 deletions(-) create mode 100644 crates/ghostlight-dungeon/src/world/clock.rs diff --git a/crates/ghostlight-dungeon/src/eve.rs b/crates/ghostlight-dungeon/src/eve.rs index 43bf63a..89f5d03 100644 --- a/crates/ghostlight-dungeon/src/eve.rs +++ b/crates/ghostlight-dungeon/src/eve.rs @@ -182,7 +182,7 @@ pub(crate) fn authenticated_surface( children.push(json!({ "id":"world.summary", "kind":"card", - "props":{"title":world.title,"subtitle":format!("{:?} · revision {}", world.phase, world.revision)}, + "props":{"title":world.title,"subtitle":format!("{:?} · revision {} · minute {}", world.phase, world.revision, world.now.0)}, "children":[{ "id":"world.summary.body", "kind":"text", @@ -232,6 +232,30 @@ pub(crate) fn authenticated_surface( } } WorldPhase::Active => { + if world.owner == crate::world::PrincipalId::new(account) { + children.extend([ + json!({ + "id":"world.advance_time.minutes", + "kind":"control.input.number", + "props":{"label":"Advance minutes","min":1,"max":525_600}, + "stateBindings":[local_draft("minutes", "number")], + "children":[] + }), + command_button( + "world.advance_time", + "Advance time", + "world.advance_time", + json!({}), + &["minutes"], + ), + ]); + commands.push(command_descriptor( + "world.advance_time", + "ghostlight.world_advance_time.v0", + &["minutes"], + "WorldMailbox", + )); + } let story = operator_log .iter() .filter_map(|event| { @@ -315,9 +339,19 @@ pub(crate) fn authenticated_surface( continue; }; has_controller_command = true; + // The kernel owns the order; the head is simply the + // first row it returned. + let head = world + .opportunities + .first() + .is_some_and(|first| first.scope == opportunity.scope); children.push(command_button( &format!("world.controller.act.{index}"), - &format!("Let {} act", subject.label), + &format!( + "Let {} act{}", + subject.label, + if head { " (next)" } else { "" } + ), "world.controller.act", json!({"opportunity":opportunity}), &[], diff --git a/crates/ghostlight-dungeon/src/runtime.rs b/crates/ghostlight-dungeon/src/runtime.rs index 8e4d35f..cdaad5d 100644 --- a/crates/ghostlight-dungeon/src/runtime.rs +++ b/crates/ghostlight-dungeon/src/runtime.rs @@ -14,7 +14,7 @@ use crate::{ ControllerPendingReason, ControllerRunner, ControllerWorkCustody, CreateWorldIntent, DecisionInvocation, DecisionOpportunity, KernelError, MailboxError, NarrativeRun, OperationalRun, PrincipalCommandIntent, PrincipalId, Statement, SubmissionDisposition, - SubmitReceipt, WorldMailbox, WorldSnapshot, + SubmitReceipt, TickMinutes, WorldMailbox, WorldSnapshot, }, }; use anyhow::{Context, bail, ensure}; @@ -87,6 +87,12 @@ struct SpeakPayload { affordance_id: AffordanceId, } +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct AdvanceTimePayload { + minutes: u32, +} + #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] struct EmptyPayload {} @@ -248,6 +254,7 @@ pub(crate) async fn run(state_root_binding: Option) -> anyhow::Result<( _ => bail!("managed runtime health authority is partial"), }; tokio::spawn(maintain_mesh_projection(state.clone())); + tokio::spawn(advance_world_clock(state.clone())); let app = app_router(state.clone(), web_root); tracing::info!(address = %bound_address, "Ghostlight Dungeon world owner serving"); let server = axum::serve( @@ -1249,6 +1256,15 @@ async fn execute_world( }, } } + "world.advance_time" => { + let payload: AdvanceTimePayload = serde_json::from_value(invocation.payload.clone()) + .map_err(|error| RuntimeCommandError::Payload(error.to_string()))?; + CommandBody::AdvanceTime { + minutes: TickMinutes::new(payload.minutes).ok_or_else(|| { + RuntimeCommandError::Payload("time span is outside one year of minutes".into()) + })?, + } + } operation => { return Err(RuntimeCommandError::Payload(format!( "unknown world operation {operation}" @@ -1424,6 +1440,31 @@ async fn maintain_mesh_projection(state: AppState) { } } +/// How often the tick task submits, and how many fictional minutes each +/// submission names. The wall clock decides *when* to submit and this constant +/// decides *how many minutes* the command carries; neither reaches `reduce`. +const CLOCK_TICK_INTERVAL: Duration = Duration::from_secs(60); +const CLOCK_TICK_MINUTES: u32 = 60; + +/// The world clock's only driver. A refused tick — no world yet, a Draft world, +/// a stale revision — is logged and skipped: the next tick re-reads live state. +async fn advance_world_clock(state: AppState) { + let Some(minutes) = TickMinutes::new(CLOCK_TICK_MINUTES) else { + tracing::error!("the configured clock tick is outside one year of minutes"); + return; + }; + let mut interval = tokio::time::interval(CLOCK_TICK_INTERVAL); + interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + interval.tick().await; + loop { + interval.tick().await; + match state.world.submit_clock(CommandId::new(), minutes).await { + Ok(_) => {} + Err(error) => tracing::debug!(%error, "world clock tick was not admitted"), + } + } +} + async fn revision_events(State(state): State) -> impl IntoResponse { let mut revisions = state.revisions.subscribe(); let stream = async_stream::stream! { diff --git a/crates/ghostlight-dungeon/src/world/action.rs b/crates/ghostlight-dungeon/src/world/action.rs index 31a569e..869ffbd 100644 --- a/crates/ghostlight-dungeon/src/world/action.rs +++ b/crates/ghostlight-dungeon/src/world/action.rs @@ -7,13 +7,13 @@ //! draws a band, and the draw goes through the one `digest()` owner. use super::patch::{ - self, Affordance, Audience, AudienceSpec, Bounds, ComponentOpKind, Cost, Precondition, - Quantity, RefKind, Role, WorldPatch, + self, Affordance, Audience, AudienceSpec, BoundPrecondition, Bounds, CommitmentKind, + ComponentOpKind, Cost, Precondition, Quantity, RefKind, Role, WorldPatch, }; use super::{ AffordanceId, AuthorityGrant, AuthorityTarget, CommandId, DecisionEvent, DecisionInvocation, - DecisionOpportunity, EdgeId, EntityId, EventId, GrantedAffordance, KernelError, Magnitude, - SubjectId, Target, WorldId, WorldState, digest, + DecisionOpportunity, EdgeId, EntityId, EventId, FictionalMinutes, GrantedAffordance, + KernelError, Magnitude, SubjectId, Target, WorldId, WorldState, digest, }; use serde::Serialize; use std::collections::{BTreeMap, BTreeSet}; @@ -106,6 +106,10 @@ pub(crate) enum ActionMismatch { CannotReach { precondition: usize, }, + /// The actor holds no commitment of that kind to the bound referent. + NotCommitted { + precondition: usize, + }, } /// The band draw's whole preimage. Five fields, none of them from the @@ -152,7 +156,7 @@ pub(super) fn exercise( } let band = select_band(state, command_id, granted.id, entry)?; - let operations = lower(entry, band, invocation, &bindings)?; + let operations = lower(entry, band, actor, state.now, invocation, &bindings)?; let mut effects = if operations.is_empty() { Vec::new() } else { @@ -166,6 +170,7 @@ pub(super) fn exercise( operations, evidence: Vec::new(), }, + None, ) .map_err(KernelError::PatchRejected)? .operations @@ -342,7 +347,10 @@ fn live_kind(state: &WorldState, target: Target) -> Option { } /// Stage 3, in declaration order, each failure carrying its index so a test can -/// name the exact precondition that refused. +/// name the exact precondition that refused. Role binding is this caller's job: +/// each declared `Precondition` is lowered through stage 2's bindings into a +/// `BoundPrecondition` and handed to the one evaluator. A precondition whose +/// role stage 2 left unbound is skipped here, because stage 2 already named it. fn check_preconditions( state: &WorldState, actor: SubjectId, @@ -352,106 +360,174 @@ fn check_preconditions( rejections: &mut Vec, ) { for (index, precondition) in entry.preconditions.iter().enumerate() { - match precondition { - Precondition::Present { at } => { - let Some(Target::Entity(place)) = bindings.get(at).copied() else { - continue; - }; - if state.positions.get(&actor).map(|position| position.place) != Some(place) { - rejections.push(ActionMismatch::ActorNotPresent { - precondition: index, - }); - } - } - Precondition::Reachable { to, within } => { - let Some(Target::Entity(place)) = bindings.get(to).copied() else { - continue; - }; - if !reachable(state, actor, authority, place, *within) { - rejections.push(ActionMismatch::TargetUnreachable { - precondition: index, - }); - } - } - Precondition::Holds { resource, at_least } => { - let Some(Target::Entity(entity_id)) = bindings.get(resource).copied() else { - continue; - }; - let held = state - .holdings - .get(&actor) - .and_then(|held| held.get(&entity_id)) - .map_or(0, |quantity| quantity.0); - if held < at_least.0 { - rejections.push(ActionMismatch::InsufficientHolding { - precondition: index, - }); - } - } - Precondition::Authorized { over, kind } => { - let Some(target) = bindings.get(over).copied() else { - continue; - }; - if !authority - .iter() - .any(|grant| &grant.kind == kind && super::covers(state, grant.over, target)) - { - rejections.push(ActionMismatch::NotAuthorized { - precondition: index, - }); - } - } - Precondition::HasStanding { grievance } => { - if !state.redress.get(grievance).is_some_and(|forum| { - super::covers(state, forum.standing, Target::Subject(actor)) - }) { - rejections.push(ActionMismatch::NoStanding { - precondition: index, - }); - } - } - Precondition::Knows { fact, at_least } => { - let Some(Target::Entity(entity_id)) = bindings.get(fact).copied() else { - continue; - }; - if !state - .knowledge - .get(&actor) - .and_then(|held| held.get(&entity_id)) - .is_some_and(|held| held.confidence >= *at_least) - { - rejections.push(ActionMismatch::FactUnknown { - precondition: index, - }); - } - } - Precondition::CanBroadcast { via } => { - let Some(audience) = bound_audience(via, bindings) else { - continue; - }; - if !super::can_broadcast(state, actor, &audience) { - rejections.push(ActionMismatch::NoAudience { - precondition: index, - }); - } - } - Precondition::CanReach { subject, via } => { - let Some(Target::Subject(target)) = bindings.get(subject).copied() else { - continue; - }; - let Some(audience) = bound_audience(via, bindings) else { - continue; - }; - if !super::audience(state, actor, &audience).contains(&target) { - rejections.push(ActionMismatch::CannotReach { - precondition: index, - }); - } - } + let Some(bound) = bind_precondition(precondition, bindings) else { + continue; + }; + if let Some(mismatch) = evaluate(state, actor, authority, index, &bound) { + rejections.push(mismatch); } } } +/// The catalog's role indirection lowered to canonical referents. `None` means +/// a role is unbound or bound to the wrong namespace, which stage 2 named. +fn bind_precondition( + precondition: &Precondition, + bindings: &BTreeMap, +) -> Option { + let place = |role: &Role| match bindings.get(role)? { + Target::Entity(entity_id) => Some(*entity_id), + _ => None, + }; + Some(match precondition { + Precondition::Present { at } => BoundPrecondition::Present { at: place(at)? }, + Precondition::Reachable { to, within } => BoundPrecondition::Reachable { + to: place(to)?, + within: *within, + }, + Precondition::Holds { resource, at_least } => BoundPrecondition::Holds { + resource: place(resource)?, + at_least: *at_least, + }, + Precondition::Authorized { over, kind } => BoundPrecondition::Authorized { + over: bindings.get(over).copied()?, + kind: kind.clone(), + }, + Precondition::HasStanding { grievance } => BoundPrecondition::HasStanding { + grievance: grievance.clone(), + }, + Precondition::Knows { fact, at_least } => BoundPrecondition::Knows { + fact: place(fact)?, + at_least: *at_least, + }, + Precondition::CanBroadcast { via } => BoundPrecondition::CanBroadcast { + via: bound_audience(via, bindings)?, + }, + Precondition::CanReach { subject, via } => BoundPrecondition::CanReach { + subject: match bindings.get(subject)? { + Target::Subject(subject_id) => *subject_id, + _ => return None, + }, + via: bound_audience(via, bindings)?, + }, + Precondition::Committed { to, kind } => BoundPrecondition::Committed { + to: match bindings.get(to)? { + Target::Subject(subject_id) => *subject_id, + _ => return None, + }, + kind: *kind, + }, + }) +} + +/// The one precondition reader, over referents that are already canonical. +/// Returns the complete set in declaration order; an empty set is "all hold". +/// The tick reads only its emptiness — an `ActionMismatch` never surfaces to +/// anyone from there. +pub(super) fn preconditions_hold( + state: &WorldState, + actor: SubjectId, + checks: &[BoundPrecondition], +) -> Vec { + let components = super::scope_components(state, actor); + let authority = super::effective_authority(&components.authority, &components.delegated); + checks + .iter() + .enumerate() + .filter_map(|(index, check)| evaluate(state, actor, &authority, index, check)) + .collect() +} + +/// One check against committed state. `index` is the position within the slice +/// the caller passed in, which is what every `precondition: usize` means. +fn evaluate( + state: &WorldState, + actor: SubjectId, + authority: &BTreeSet, + index: usize, + check: &BoundPrecondition, +) -> Option { + let holds = match check { + BoundPrecondition::Present { at } => { + return (state.positions.get(&actor).map(|position| position.place) != Some(*at)) + .then_some(ActionMismatch::ActorNotPresent { + precondition: index, + }); + } + BoundPrecondition::Reachable { to, within } => { + return (!reachable(state, actor, authority, *to, *within)).then_some( + ActionMismatch::TargetUnreachable { + precondition: index, + }, + ); + } + BoundPrecondition::Holds { resource, at_least } => { + state + .holdings + .get(&actor) + .and_then(|held| held.get(resource)) + .map_or(0, |quantity| quantity.0) + >= at_least.0 + } + BoundPrecondition::Authorized { over, kind } => { + return (!authority + .iter() + .any(|grant| &grant.kind == kind && super::covers(state, grant.over, *over))) + .then_some(ActionMismatch::NotAuthorized { + precondition: index, + }); + } + BoundPrecondition::HasStanding { grievance } => { + return (!state.redress.get(grievance).is_some_and(|forum| { + super::covers(state, forum.standing, Target::Subject(actor)) + })) + .then_some(ActionMismatch::NoStanding { + precondition: index, + }); + } + BoundPrecondition::Knows { fact, at_least } => { + return (!state + .knowledge + .get(&actor) + .and_then(|held| held.get(fact)) + .is_some_and(|held| held.confidence >= *at_least)) + .then_some(ActionMismatch::FactUnknown { + precondition: index, + }); + } + BoundPrecondition::CanBroadcast { via } => { + return (!super::can_broadcast(state, actor, via)).then_some( + ActionMismatch::NoAudience { + precondition: index, + }, + ); + } + BoundPrecondition::CanReach { subject, via } => { + return (!super::audience(state, actor, via).contains(subject)).then_some( + ActionMismatch::CannotReach { + precondition: index, + }, + ); + } + // A linear scan of one subject's own small map. No key lookup is needed + // and none is offered, which is why a `CommitmentKey` never has to be + // guessable. + BoundPrecondition::Committed { to, kind } => { + return (!state.commitments.get(&actor).is_some_and(|held| { + held.values().any(|commitment| { + commitment.counterparty == Some(*to) && commitment.kind == *kind + }) + })) + .then_some(ActionMismatch::NotCommitted { + precondition: index, + }); + } + }; + (!holds).then_some(ActionMismatch::InsufficientHolding { + precondition: index, + }) +} + /// The catalog's role indirection lowered to the canonical audience: the entry /// names a role, the invoker binds a channel to it, and every reader of reach /// sees one shape. `None` means the role is unbound, which stage 2 already named. @@ -704,6 +780,8 @@ fn select_band( fn lower( entry: &Affordance, band: usize, + actor: SubjectId, + now: FictionalMinutes, invocation: &DecisionInvocation, bindings: &BTreeMap, ) -> Result, KernelError> { @@ -775,6 +853,34 @@ fn lower( }) }; operations.push(match &slot.op_kind { + // `due` is computed here, so a proposer cannot set one, and the + // pressure source is the acting subject, so it cannot be forged. + ComponentOpKind::CreateCommitment { + kind, + horizon, + period, + } => patch::ComponentOp::CreateCommitment { + subject: subject(0)?, + counterparty: Some(subject(1)?), + kind: *kind, + due: now.checked_add(*horizon).ok_or_else(malformed)?, + period: *period, + checks: Vec::new(), + }, + ComponentOpKind::AdvancePressure { by } => patch::ComponentOp::AdvancePressure { + source: patch::PressureSourceRef::Subject(patch::Ref::Existing(actor)), + target: subject(0)?, + by: *by, + }, + ComponentOpKind::ReducePressure { by } => patch::ComponentOp::ReducePressure { + source: patch::PressureSourceRef::Subject(patch::Ref::Existing(actor)), + target: subject(0)?, + by: *by, + }, + ComponentOpKind::ResolvePressure => patch::ComponentOp::ResolvePressure { + source: patch::PressureSourceRef::Subject(patch::Ref::Existing(actor)), + target: subject(0)?, + }, ComponentOpKind::Relocate => patch::ComponentOp::Relocate { subject: subject(0)?, via: edge(1)?, diff --git a/crates/ghostlight-dungeon/src/world/clock.rs b/crates/ghostlight-dungeon/src/world/clock.rs new file mode 100644 index 0000000..af9d9e0 --- /dev/null +++ b/crates/ghostlight-dungeon/src/world/clock.rs @@ -0,0 +1,209 @@ +//! The world clock and the motion one tick produces. +//! +//! One entry point into the reducer, [`derive_motion`], reached from `reduce`'s +//! `AdvanceTime` arm and from `apply_effect`'s `TimeAdvanced` arm, so a forged +//! tick is re-derived by the same function that produced the honest one. It is +//! pure over `(state, to)`: no wall clock, no entropy, no caller value beyond +//! the span. + +use super::patch::{Commitment, CommitmentKey, CommitmentKind, DependencyTarget, MAX_ROUTE_COST}; +use super::{PressureMagnitude, PressureSource, SubjectId, WorldState, action}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +/// Minutes since genesis. Monotonic, kernel-owned, world-level. `u64` because a +/// world clock has no bound; `Cost` is `1..=MAX_ROUTE_COST` because it weighs +/// one edge, and reusing it here would put an edge's bound on the world's age. +#[derive( + Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, +)] +#[serde(transparent)] +pub(crate) struct FictionalMinutes(pub(crate) u64); + +impl FictionalMinutes { + pub(crate) fn checked_add(self, span: TickMinutes) -> Option { + self.0.checked_add(u64::from(span.0)).map(Self) + } + + /// Minutes elapsed since an earlier reading. Saturating because the caller + /// is the attention order, which reads a stamp `verify_state_shape` already + /// holds to `<= now`. + pub(crate) fn since(self, earlier: Self) -> u64 { + self.0.saturating_sub(earlier.0) + } +} + +/// The span one `AdvanceTime` names. Constructor-checked `1..=MAX_ROUTE_COST` +/// (one year of minutes), reusing pass 2's constant as a span bound rather than +/// an edge bound: an unbounded span lets one command jump the clock past every +/// due date in the world and makes the size of a commit a caller-chosen number. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[serde(transparent)] +pub(crate) struct TickMinutes(u32); + +impl TickMinutes { + pub(crate) fn new(minutes: u32) -> Option { + (1..=MAX_ROUTE_COST) + .contains(&minutes) + .then_some(Self(minutes)) + } + + pub(crate) fn minutes(self) -> u32 { + self.0 + } +} + +/// Everything one tick moves, stated as outcomes rather than deltas so the +/// effect says what the world became. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct Motion { + /// Routines that fulfilled, in `(subject, key)` order. + pub(crate) fulfilled: Vec, + /// Pressure rows written, in `(target, source)` order, with the resulting + /// magnitude — not the delta. + pub(crate) pressed: Vec, +} + +impl Motion { + pub(crate) fn is_empty(&self) -> bool { + self.fulfilled.is_empty() && self.pressed.is_empty() + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct RoutineFulfilled { + pub(crate) subject: SubjectId, + pub(crate) key: CommitmentKey, + pub(crate) next_due: FictionalMinutes, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct PressureWritten { + pub(crate) target: SubjectId, + pub(crate) source: PressureSource, + pub(crate) magnitude: PressureMagnitude, +} + +/// The whole magnitude policy, in one place, with no per-world tuning. A +/// blocked routine raises none at all: it retries on the next tick, which is +/// what keeps an unattended subject free of spurious pressure. +mod step { + pub(super) const OBLIGATION_PAST_DUE: u32 = 1; + pub(super) const GOAL_PAST_DUE: u32 = 1; + pub(super) const DEPENDENCY_UNAVAILABLE: u32 = 1; +} + +/// Three stages, each reading only committed `state` and `to`. No stage sees +/// another stage's writes, which is what makes this a one-pass total function +/// with no ordering hazard and no partial state to reason about. +/// +/// Pressure accrues per command, not per minute: one thousand one-minute ticks +/// and one thousand-minute tick over the same span produce different +/// magnitudes. The kernel stays an exact function of the command sequence, and +/// the tick cadence is one operational constant in `runtime.rs`. +pub(super) fn derive_motion(state: &WorldState, to: FictionalMinutes) -> Motion { + let mut fulfilled = Vec::new(); + let mut pressed: BTreeMap<(SubjectId, PressureSource), u32> = BTreeMap::new(); + + for (subject, held) in &state.commitments { + for (key, commitment) in held { + if commitment.due > to { + continue; + } + match commitment.kind { + CommitmentKind::Routine => { + if let Some(next_due) = routine_rolls(state, *subject, commitment) { + fulfilled.push(RoutineFulfilled { + subject: *subject, + key: *key, + next_due, + }); + } + } + CommitmentKind::Obligation | CommitmentKind::Goal => { + let step = if commitment.kind == CommitmentKind::Obligation { + step::OBLIGATION_PAST_DUE + } else { + step::GOAL_PAST_DUE + }; + let source = PressureSource::Commitment { + subject: *subject, + key: *key, + }; + *pressed.entry((*subject, source)).or_default() += step; + } + } + } + } + + for (subject, targets) in &state.dependencies { + for target in targets { + if dependency_unavailable(state, *subject, *target) { + let source = PressureSource::Dependency(*target); + *pressed.entry((*subject, source)).or_default() += step::DEPENDENCY_UNAVAILABLE; + } + } + } + + Motion { + fulfilled, + pressed: pressed + .into_iter() + .map(|((target, source), step)| PressureWritten { + target, + source, + magnitude: PressureMagnitude( + state + .pressures + .get(&target) + .and_then(|held| held.get(&source)) + .map_or(0, |magnitude| magnitude.0) + .saturating_add(step), + ), + }) + .collect(), + } +} + +/// A routine fulfils when every one of its checks holds, and its `due` then +/// rolls forward by exactly one period per command. Catch-up arithmetic would +/// make the number of fulfilments a function of the operator's tick cadence in +/// a second place; one roll converges over subsequent ticks. +fn routine_rolls( + state: &WorldState, + subject: SubjectId, + commitment: &Commitment, +) -> Option { + if !action::preconditions_hold(state, subject, &commitment.checks).is_empty() { + return None; + } + commitment.due.checked_add(commitment.period?) +} + +/// Whether a subject's dependency is currently failing it. A closed route is a +/// supply failure; an unusable one is a permission question, and reading +/// authority here would drag `effective_authority` into every tick for every +/// dependency in the world. +pub(super) fn dependency_unavailable( + state: &WorldState, + subject: SubjectId, + target: DependencyTarget, +) -> bool { + match target { + DependencyTarget::Route(edge_id) => !state + .edges + .get(&edge_id) + .is_some_and(super::EdgeRecord::is_open), + // Absence is zero, per pass 3: the depender holds none of what it + // depends on. + DependencyTarget::Resource(entity_id) => !state + .holdings + .get(&subject) + .is_some_and(|held| held.contains_key(&entity_id)), + // The subject it depends on is nowhere in the world's topology. + DependencyTarget::Subject(other) => !state.positions.contains_key(&other), + } +} diff --git a/crates/ghostlight-dungeon/src/world/controllers.rs b/crates/ghostlight-dungeon/src/world/controllers.rs index daf4484..8d7dfa1 100644 --- a/crates/ghostlight-dungeon/src/world/controllers.rs +++ b/crates/ghostlight-dungeon/src/world/controllers.rs @@ -47,8 +47,8 @@ const MAX_CONNECTOR_FRAME_BYTES: usize = 1_052_672; const REQUEST_EXPIRY: Duration = Duration::from_secs(300); const TOOL_STEP_BUDGET: usize = 4; const PERSONA_WORD_BUDGET: usize = 180; -const CONTROLLER_WORK_ROW: &str = "controller_work.v5"; -const CONTROLLER_WORK_SCHEMA: &str = "ghostlight.controller_work.v5"; +const CONTROLLER_WORK_ROW: &str = "controller_work.v6"; +const CONTROLLER_WORK_SCHEMA: &str = "ghostlight.controller_work.v6"; /// The Interpreter's byte-span capture tool. It is not the generated `speak` /// affordance tool: one captures an utterance out of preserved prose, the other @@ -2586,6 +2586,7 @@ impl SelectedDecision { "label": self.subject.label, "kind": self.subject.kind, }, + "now": self.snapshot.now, "permission": catalog_permissions(&self.granted), })) .map_err(|error| ControllerError::Serialization(error.to_string())) @@ -2614,10 +2615,43 @@ impl SelectedDecision { "redress": self.typed_redress(), "knowledge": self.typed_knowledge(), "channels": self.typed_channels(), + "now": self.snapshot.now, + "commitments": self.typed_commitments(), + "pressures": self.typed_pressures(), })) .map_err(|error| ControllerError::Serialization(error.to_string())) } + /// The acting subject's own promises. IDs, not labels: resolving a + /// counterparty's name is a `Knowledge` question. + fn typed_commitments(&self) -> Vec { + self.subject + .commitments + .iter() + .map(|commitment| { + json!({ + "key": commitment.key, + "kind": commitment.kind, + "counterparty": commitment.counterparty, + "due": commitment.due, + "period": commitment.period, + "past_due": commitment.past_due, + }) + }) + .collect() + } + + /// Pressure on self. Pressure this subject sources is another subject's + /// state and never enters: the actor already sees the commitment that + /// produced it. + fn typed_pressures(&self) -> Vec { + self.subject + .pressures + .iter() + .map(|pressure| json!({"source": pressure.source, "magnitude": pressure.magnitude})) + .collect() + } + /// The acting subject's own jurisdictions, with no label resolved for /// anything inside a target: a jurisdiction may name places and subjects /// this subject has never heard of, and label resolution is a `Knowledge` @@ -3763,6 +3797,7 @@ fn purpose_name(purpose: InferencePurpose) -> &'static str { #[cfg(test)] mod tests { use super::*; + use crate::world::WorldScaleIntentRef; use crate::world::patch::{kernel_speak_entry, kernel_speak_grant}; /// The granted catalog every controller fixture works against: the @@ -4007,6 +4042,8 @@ mod tests { spoken_at: Some(40), }], controls: BTreeSet::new(), + commitments: Vec::new(), + pressures: Vec::new(), }; let speaker = SubjectSnapshot { id: speaker_id, @@ -4033,6 +4070,8 @@ mod tests { spoken_at: None, }], controls: BTreeSet::new(), + commitments: Vec::new(), + pressures: Vec::new(), }; let snapshot = WorldSnapshot { world_id: opportunity.world_id, @@ -4050,6 +4089,9 @@ mod tests { opportunities: vec![opportunity.clone()], state_digest: "sha256:projector-must-not-see-this-digest".into(), last_commit_digest: Some("sha256:projector-must-not-see-the-commit".into()), + now: crate::world::FictionalMinutes::default(), + boundaries: Vec::new(), + scale_deficit: Vec::new(), }; let selected = SelectedDecision { snapshot, @@ -4240,6 +4282,8 @@ mod tests { redress: Vec::new(), knowledge: Vec::new(), controls: BTreeSet::new(), + commitments: Vec::new(), + pressures: Vec::new(), }; let other = SubjectSnapshot { id: other_id, @@ -4259,6 +4303,8 @@ mod tests { redress: Vec::new(), knowledge: Vec::new(), controls: BTreeSet::new(), + commitments: Vec::new(), + pressures: Vec::new(), }; let named_place = |id, label: &str| PlaceSnapshot { id, @@ -4297,6 +4343,9 @@ mod tests { opportunities: vec![opportunity.clone()], state_digest: "sha256:state".into(), last_commit_digest: None, + now: crate::world::FictionalMinutes::default(), + boundaries: Vec::new(), + scale_deficit: Vec::new(), }; let selected = SelectedDecision { snapshot, @@ -4857,6 +4906,7 @@ mod tests { operations: Vec::new(), evidence: Vec::new(), }, + scale_intent: WorldScaleIntentRef::default(), }, &authenticated, ) @@ -5467,6 +5517,7 @@ mod tests { operations: Vec::new(), evidence: Vec::new(), }, + scale_intent: WorldScaleIntentRef::default(), }, &owner_caller, ) diff --git a/crates/ghostlight-dungeon/src/world/journal.rs b/crates/ghostlight-dungeon/src/world/journal.rs index d7390a4..6f26a9d 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.knowledge.v1"; -const COMMIT_ROW: &str = "world_commit.knowledge.v1"; +const STATE_ROW: &str = "world_state.commitment.v1"; +const COMMIT_ROW: &str = "world_commit.commitment.v1"; #[derive(Debug, Error)] pub(super) enum JournalError { @@ -389,6 +389,7 @@ fn verify_history( let mut replay = WorldState::genesis(state.world_id, genesis_command, &genesis.effect) .map_err(kernel_error)?; verify_state_shape(&replay)?; + verify_commitments_are_future(&replay, &BTreeMap::new())?; if replay.state_digest != genesis.resulting_state_digest { return Err(JournalError::Corrupt( "genesis resulting state digest is invalid".into(), @@ -409,7 +410,18 @@ fn verify_history( "commit chain is not contiguous or verifiable".into(), )); } + let previous_now = replay.now; + let previous_commitments = replay.commitments.clone(); apply_committed_command(&mut replay, commit)?; + // Two chain checks one state cannot make: the clock never runs + // backwards, and it advances only on a tick. + let advanced = matches!(commit.effect, WorldEffect::TimeAdvanced { .. }); + if replay.now < previous_now || (replay.now > previous_now) != advanced { + return Err(JournalError::Corrupt( + "the world clock moved without a time-advanced commit, or ran backwards".into(), + )); + } + verify_commitments_are_future(&replay, &previous_commitments)?; replay.revision = commit.resulting_revision; replay.state_digest = state_digest(&replay).map_err(kernel_error)?; if replay.state_digest != commit.resulting_state_digest { @@ -427,6 +439,28 @@ fn verify_history( Ok(()) } +/// The replay-side twin of `Mismatch::CommitmentDueInThePast`: every commitment +/// key this commit introduced is due after the post-commit clock. Replay already +/// reconstructs both sides, so this is a set difference over one partition. +fn verify_commitments_are_future( + state: &WorldState, + before: &BTreeMap>, +) -> Result<(), JournalError> { + for (subject_id, held) in &state.commitments { + for (key, commitment) in held { + let existed = before + .get(subject_id) + .is_some_and(|previous| previous.contains_key(key)); + if !existed && commitment.due <= state.now { + return Err(JournalError::Corrupt( + "a commitment was born at or after its own due date".into(), + )); + } + } + } + Ok(()) +} + fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> { if state.schema != STATE_SCHEMA { return Err(JournalError::Corrupt("invalid state schema".into())); @@ -601,6 +635,89 @@ fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> { )); } } + // Commitments, pressures, attention stamps, and the authored scale target. + // Absence is the only spelling of nothing at every level, so a store + // satisfying these clauses carries no empty inner map, no zero magnitude, + // and no dangling row — with no scan for any of them. + for (subject_id, held) in &state.commitments { + let commitment_is_canonical = |commitment: &super::Commitment| { + (commitment.kind == super::CommitmentKind::Routine) == commitment.period.is_some() + && (commitment.kind == super::CommitmentKind::Routine + || commitment.checks.is_empty()) + && match commitment.counterparty { + Some(counterparty) => { + counterparty != *subject_id + && state.subjects.contains_key(&counterparty) + && commitment.kind != super::CommitmentKind::Goal + } + None => true, + } + && commitment + .checks + .iter() + .all(|check| super::bound_precondition_is_live(state, check)) + }; + if !state.subjects.contains_key(subject_id) + || held.is_empty() + || !held.values().all(commitment_is_canonical) + { + return Err(JournalError::Corrupt( + "a commitment does not name a canonical promisor, counterparty, shape, or check" + .into(), + )); + } + } + for (target, held) in &state.pressures { + let source_is_live = |source: &super::PressureSource| match source { + super::PressureSource::Commitment { subject, key } => state + .commitments + .get(subject) + .is_some_and(|commitments| commitments.contains_key(key)), + super::PressureSource::Dependency(dependency) => state + .dependencies + .get(target) + .is_some_and(|targets| targets.contains(dependency)), + super::PressureSource::Subject(subject_id) => state.subjects.contains_key(subject_id), + }; + if !state.subjects.contains_key(target) + || held.is_empty() + || held + .iter() + .any(|(source, magnitude)| magnitude.0 == 0 || !source_is_live(source)) + { + return Err(JournalError::Corrupt( + "a pressure row does not name a canonical target, live source, and nonzero \ + magnitude" + .into(), + )); + } + } + if state + .last_opportunity_at + .iter() + .any(|(subject_id, stamp)| !state.subjects.contains_key(subject_id) || *stamp > state.now) + { + return Err(JournalError::Corrupt( + "an attention stamp names an unknown subject or a future minute".into(), + )); + } + if state + .scale_intent + .jurisdictions + .keys() + .any(|root| !is_place(root)) + || state + .scale_intent + .jurisdictions + .values() + .map(|weight| u64::from(*weight)) + .sum::() + > 1000 + { + return Err(JournalError::Corrupt( + "the scale intent names a non-place root or distributes more than the whole".into(), + )); + } // The civic subgraph, in the slot the deleted `authority_scope` check // occupied: a jurisdiction names live ground under a canonical kind, an // office sits on an institution and lends something to a person who holds @@ -867,6 +984,7 @@ fn kernel_error(error: KernelError) -> JournalError { #[cfg(test)] mod tests { use super::*; + use crate::world::WorldScaleIntentRef; use crate::world::patch::kernel_speak_grant; use crate::world::tests::speak_entry; use crate::world::{ @@ -920,6 +1038,7 @@ mod tests { affordances: kernel_speak_grant(), position: None, }), + scale_intent: WorldScaleIntentRef::default(), }; let (mut kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap(); let snapshot = kernel.snapshot().unwrap(); @@ -1000,6 +1119,7 @@ mod tests { affordances: kernel_speak_grant(), position: None, }), + scale_intent: WorldScaleIntentRef::default(), }; let (mut kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap(); let snapshot = kernel.snapshot().unwrap(); @@ -1042,7 +1162,7 @@ mod tests { let mut forged_head = kernel.state.clone(); let mut forged_commits = kernel.journal.commits.clone(); let forged = forged_commits.get_mut(&command_id).unwrap(); - let WorldEffect::PatchAdmitted { resolved } = &mut forged.effect else { + let WorldEffect::PatchAdmitted { resolved, .. } = &mut forged.effect else { panic!("expected an admitted patch effect"); }; resolved.subjects[0].position = Some(Position { @@ -1100,7 +1220,7 @@ mod tests { let mut forged_head = kernel.state.clone(); let mut forged_commits = kernel.journal.commits.clone(); let forged = forged_commits.get_mut(&command_id).unwrap(); - let WorldEffect::PatchAdmitted { resolved } = &mut forged.effect else { + let WorldEffect::PatchAdmitted { resolved, .. } = &mut forged.effect else { panic!("expected an admitted patch effect"); }; let crate::world::ResolvedOp::Relocate { subject_id, .. } = &mut resolved.operations[0] @@ -1244,6 +1364,7 @@ mod tests { affordances: kernel_speak_grant(), position: None, }), + scale_intent: WorldScaleIntentRef::default(), }; let (kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap(); let mut forged_head = kernel.state.clone(); diff --git a/crates/ghostlight-dungeon/src/world/mailbox.rs b/crates/ghostlight-dungeon/src/world/mailbox.rs index b8dd80e..cf0a6b5 100644 --- a/crates/ghostlight-dungeon/src/world/mailbox.rs +++ b/crates/ghostlight-dungeon/src/world/mailbox.rs @@ -3,7 +3,8 @@ use super::{ CreateWorldIntent, CreationReceipt, DecisionInvocation, DecisionOpportunity, Declaration, DraftHandle, EntityDeclaration, EntityKind, KernelError, NewController, OperatorEvent, PrincipalCommandIntent, PrincipalId, Ref, SubjectDeclaration, SubjectKind, SubmitReceipt, - WorldKernel, WorldPatch, WorldSnapshot, journal, patch::kernel_speak_grant, prepare_creation, + SystemCapability, TickMinutes, WorldKernel, WorldPatch, WorldScaleIntentRef, WorldSnapshot, + journal, patch::kernel_speak_grant, prepare_creation, }; use crate::app_session::VerifiedPrincipalEvidence; use std::path::Path; @@ -156,6 +157,9 @@ impl WorldMailbox { operations: Vec::new(), evidence: Vec::new(), }, + // World ingress authors no scale target: the intent names + // jurisdiction roots, and genesis declares only the commons. + scale_intent: WorldScaleIntentRef::default(), }, AuthenticatedCaller::verified_principal(principal_id), ) @@ -306,6 +310,24 @@ impl WorldMailbox { .await } + /// The clock port. Stamped, like every opportunity-bearing command, because + /// the tick task cannot know the live revision either. It is visible inside + /// the world subtree and unreachable from runtime ingress, which builds + /// `CallerId::Principal` from verified evidence and nothing else. + pub(crate) async fn submit_clock( + &self, + command_id: CommandId, + minutes: TickMinutes, + ) -> Result { + self.submit_stamped( + command_id, + CallerId::System(SystemCapability::Clock), + CommandBody::AdvanceTime { minutes }, + AuthenticatedCaller::verified_system(SystemCapability::Clock), + ) + .await + } + #[cfg(test)] pub(super) async fn create_fixture( &self, @@ -671,6 +693,7 @@ mod tests { operations: Vec::new(), evidence: Vec::new(), }, + scale_intent: WorldScaleIntentRef::default(), } } @@ -1078,6 +1101,7 @@ mod tests { operations: Vec::new(), evidence: Vec::new(), }, + scale_intent: WorldScaleIntentRef::default(), }, &authenticated, ) diff --git a/crates/ghostlight-dungeon/src/world/mod.rs b/crates/ghostlight-dungeon/src/world/mod.rs index e4239f1..9b6fb78 100644 --- a/crates/ghostlight-dungeon/src/world/mod.rs +++ b/crates/ghostlight-dungeon/src/world/mod.rs @@ -6,12 +6,14 @@ //! opportunities, reduction, or persistence. mod action; +mod clock; mod controllers; mod journal; mod mailbox; mod patch; pub(crate) use action::ActionMismatch; +pub(crate) use clock::{FictionalMinutes, Motion, TickMinutes}; pub(crate) use controllers::{ ControllerError, ControllerModels, ControllerOpenError, ControllerPendingReason, ControllerRunner, ControllerWorkCustody, NarrativeCapture, NarrativeDecision, NarrativePending, @@ -21,16 +23,19 @@ pub(crate) use controllers::{ pub(crate) use mailbox::{ControllerPort, MailboxError, WorldMailbox}; pub(crate) use patch::{ AccessKind, Affordance, AffordanceKindName, Audience, AuthoredSource, AuthorityGrant, - AuthorityKindName, AuthorityTarget, Bounds, ChannelRecord, ComponentOpKind, Confidence, Cost, - Declaration, DependencyTarget, DraftHandle, EffectSlot, EntityDeclaration, EntityKind, - EvidenceRef, FactRecord, FactStanding, Forum, GrievanceKindName, Knowledge, KnowledgeSource, - Mismatch, Office, OfficeName, OutcomeBand, PatchAnswer, Position, Precondition, Quantity, - Reach, Ref, RefKind, Role, RoleSpec, Statement, SubjectDeclaration, WorldPatch, + AuthorityKindName, AuthorityTarget, BoundPrecondition, Bounds, ChannelRecord, Commitment, + CommitmentKey, CommitmentKind, ComponentOpKind, Confidence, Cost, Declaration, + DependencyTarget, DraftHandle, EffectSlot, EntityDeclaration, EntityKind, EvidenceRef, + FactRecord, FactStanding, Forum, GrievanceKindName, JurisdictionKey, Knowledge, + KnowledgeSource, Mismatch, Office, OfficeName, OutcomeBand, PatchAnswer, Position, + Precondition, PressureMagnitude, PressureSource, Quantity, Reach, Ref, RefKind, Role, RoleSpec, + Statement, SubjectDeclaration, WorldPatch, WorldScaleIntent, WorldScaleIntentRef, }; #[cfg(test)] use patch::{ AffordanceDeclaration, AudienceRef, AudienceSpec, ChannelDeclaration, ComponentOp, - DependencyRef, FactDeclaration, FactStandingRef, ReachRef, RouteDeclaration, + DependencyRef, FactDeclaration, FactStandingRef, PreconditionRef, PressureSourceRef, ReachRef, + RouteDeclaration, }; #[cfg(test)] pub(crate) use patch::{AuthorityGrantRef, AuthorityTargetRef}; @@ -45,8 +50,8 @@ use std::path::Path; use thiserror::Error; use uuid::Uuid; -pub(crate) const STATE_SCHEMA: &str = "ghostlight.world_state.knowledge.v1"; -pub(crate) const COMMIT_SCHEMA: &str = "ghostlight.world_commit.knowledge.v1"; +pub(crate) const STATE_SCHEMA: &str = "ghostlight.world_state.commitment.v1"; +pub(crate) const COMMIT_SCHEMA: &str = "ghostlight.world_commit.commitment.v1"; /// Compatibility tag derived from [`STATE_SCHEMA`]: the trailing /// `-` pair (e.g. `foundation-v1`). Callers that publish a @@ -195,6 +200,9 @@ struct CreateWorld { owner: PrincipalId, title: String, patch: WorldPatch, + /// Authored once, here, and never mutated: `CommandBody::AdmitPatch` carries + /// no intent, so write-once is the command shape rather than a check. + scale_intent: WorldScaleIntentRef, } /// Unattributed creation intent. World ingress derives ownership, controller @@ -213,6 +221,15 @@ pub(crate) struct CreateWorldIntent { enum CallerId { Principal(PrincipalId), Controller(ControllerId), + /// An internal capability. Never derived from session evidence, never + /// minted by ingress, and admitted for exactly one command body. + System(SystemCapability), +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +enum SystemCapability { + Clock, } #[derive(Clone, Debug)] @@ -233,6 +250,14 @@ impl AuthenticatedCaller { } } + /// Visible only inside the `world` subtree and called only by + /// `WorldMailbox::submit_clock`. Runtime ingress cannot reach it. + fn verified_system(capability: SystemCapability) -> Self { + Self { + caller: CallerId::System(capability), + } + } + #[cfg(test)] fn fixture(caller: CallerId) -> Self { Self { caller } @@ -375,11 +400,17 @@ pub(crate) enum CommandBody { opportunity: DecisionOpportunity, }, AdmitPatch { - /// Structurally `None` until boundary answers exist: `PatchAnswer` is - /// uninhabited. + /// Draft answers nothing. Active must answer a currently derived + /// boundary or a jurisdiction whose deficit is nonzero, and the commit + /// must satisfy what it answered. answers: Option, patch: WorldPatch, }, + /// The world's only clock advance. Owner or the clock capability, and the + /// clock capability may do nothing else. + AdvanceTime { + minutes: TickMinutes, + }, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] @@ -503,6 +534,22 @@ struct WorldState { /// neither a subject nor a referent, so it enters no scope digest and is /// admission-only state. redress: BTreeMap, + /// What each subject has promised. Never empty for a present key. + commitments: BTreeMap>, + /// Pressure *on* each subject, keyed target-major then source. Never empty + /// for a present key; no stored zero magnitude. + pressures: BTreeMap>, + /// When each subject was last given a decision opportunity it consumed. + /// Absence means never. The debt term of the attention order and nothing + /// else. + last_opportunity_at: BTreeMap, + /// Minutes since genesis. The world's only clock, advanced by exactly one + /// command body and read by no wall clock. It enters `state_digest` and no + /// `ScopePreimage`: it is world truth, and it is read by no precondition, so + /// a tick that only advances pressure moves no proposal's binding. + now: FictionalMinutes, + /// The authored scale target, written once by genesis and never mutated. + scale_intent: WorldScaleIntent, controller_assignments: BTreeMap, /// What an affordance *is*. World-authored, Draft-only, written by /// `admit_resolved` alone. @@ -524,6 +571,9 @@ enum WorldEffect { resolved: ResolvedPatch, }, PatchAdmitted { + /// What this commit answered, so `apply_effect` re-decides the same + /// rule `reduce` decided and then proves the answer was satisfied. + answers: Option, resolved: ResolvedPatch, }, DraftApproved { @@ -541,6 +591,15 @@ enum WorldEffect { DecisionDeclined { opportunity: DecisionOpportunity, }, + /// The first effect that mutates state for subjects other than one scope. + /// Its gate is the clock capability or the owner, and `apply_effect` + /// re-derives the whole motion, so a forged fulfilment, magnitude, row, or + /// target is one comparison rather than a clause apiece. + TimeAdvanced { + minutes: TickMinutes, + to: FictionalMinutes, + motion: Motion, + }, } /// The exact raw command admitted by the world owner. This is the sole @@ -619,6 +678,32 @@ pub(crate) struct SubjectSnapshot { /// The channels this subject controls, by id. Not their reach: who else is /// in earshot is a question about other subjects. pub(crate) controls: BTreeSet, + /// Digest-bound, lowered from the one `scope_components` call `snapshot` + /// already makes, so view and digest cannot drift. + pub(crate) commitments: Vec, + /// Pressure on self. View-only: read by no precondition, so covered by no + /// digest. Pressure this subject *sources* is excluded — it is another + /// subject's state, and the actor already sees the commitment that produced + /// it. + pub(crate) pressures: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct CommitmentSnapshot { + pub(crate) key: CommitmentKey, + pub(crate) kind: CommitmentKind, + pub(crate) counterparty: Option, + pub(crate) due: FictionalMinutes, + pub(crate) period: Option, + /// Derived in `snapshot` so a controller does not recompute it against a + /// clock it must be handed anyway. + pub(crate) past_due: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct PressureSnapshot { + pub(crate) source: PressureSource, + pub(crate) magnitude: PressureMagnitude, } /// What a subject knows of one fact. `standing` carries no `EvidenceRef`: a @@ -712,7 +797,17 @@ pub(crate) struct WorldSnapshot { pub(crate) places: Vec, pub(crate) resources: Vec, pub(crate) routes: Vec, + /// Already ordered by pressure, then attention debt, then id: one owner, so + /// Eve, the mesh projection, and any future driver read the same order and + /// none computes its own. pub(crate) opportunities: Vec, + /// Everyone in a world shares the clock, and no controller can read a `due` + /// without it. + pub(crate) now: FictionalMinutes, + /// The elaborator's surface. There is no global pressure register and no + /// commitment gazetteer. + pub(crate) boundaries: Vec, + pub(crate) scale_deficit: Vec, pub(crate) state_digest: String, pub(crate) last_commit_digest: Option, } @@ -847,6 +942,12 @@ pub(crate) enum KernelError { CorruptJournal(String), #[error("private reducer invariant failed: {0}")] Invariant(String), + #[error("an active patch must answer a derived boundary or a nonzero deficit")] + AnswerRequired, + #[error("this world derives no such boundary or deficit")] + AnswerNotDerived, + #[error("the admitted patch does not satisfy the boundary or deficit it answered")] + AnswerNotSatisfied, } impl KernelError { @@ -908,6 +1009,7 @@ fn prepare_creation( &WorldState::empty(world_id, input.owner.clone(), title.clone()), input.id, &input.patch, + Some(&input.scale_intent), ) .map_err(KernelError::PatchRejected)?; Ok(PreparedCreation { @@ -1121,6 +1223,10 @@ impl WorldKernel { } fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result { + // The one admission rule for internal capabilities, stated here and again + // at the top of `apply_effect`: `reduce` decides and `apply_effect` + // re-decides, which is how every gate in this file is written. + require_system_capability(&command.caller, &command.body)?; match &command.body { CommandBody::ApproveDraft => { require_phase(state, WorldPhase::Draft)?; @@ -1184,27 +1290,107 @@ fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result { + CommandBody::AdvanceTime { minutes } => { + // There is no time in Draft: a world under construction has no due + // dates to cross. + require_phase(state, WorldPhase::Active)?; + require_clock_caller(state, &command.caller)?; + let to = state + .now + .checked_add(*minutes) + .ok_or_else(|| KernelError::Serialization("world clock overflow".into()))?; + // A tick with an empty motion is still a commit: the clock moved, + // which is a canonical change. That is why the clock is a state + // field rather than a patch operation. + Ok(WorldEffect::TimeAdvanced { + minutes: *minutes, + to, + motion: clock::derive_motion(state, to), + }) + } + CommandBody::AdmitPatch { answers, patch } => { require_owner(state, &command.caller)?; - // Draft admits declarations, evidence, and operations; Active admits - // operations only. The patch lane therefore structurally cannot mint - // the claim every utterance asserts, which is why `action::exercise` - // is the second `derive_id` call site. - if state.phase == WorldPhase::Active - && !(patch.declarations.is_empty() && patch.evidence.is_empty()) - { - return Err(KernelError::WrongPhase { - expected: WorldPhase::Draft, - actual: WorldPhase::Active, - }); - } - let resolved = patch::resolve_patch(state, command.id, patch) + require_answer( + state, + answers.as_ref(), + !(patch.declarations.is_empty() && patch.evidence.is_empty()), + )?; + let resolved = patch::resolve_patch(state, command.id, patch, None) .map_err(KernelError::PatchRejected)?; - Ok(WorldEffect::PatchAdmitted { resolved }) + Ok(WorldEffect::PatchAdmitted { + answers: answers.clone(), + resolved, + }) } } } +/// A system capability is admitted for exactly one command body and nothing +/// else. Stated once here, reached by `reduce` and by `apply_effect`. +fn require_system_capability(caller: &CallerId, body: &CommandBody) -> Result<(), KernelError> { + match caller { + CallerId::System(SystemCapability::Clock) + if !matches!(body, CommandBody::AdvanceTime { .. }) => + { + Err(KernelError::Unauthorized) + } + _ => Ok(()), + } +} + +/// The owner may tick from Eve; the tick task may tick with no session. Nothing +/// else may tick. +fn require_clock_caller(state: &WorldState, caller: &CallerId) -> Result<(), KernelError> { + if caller == &CallerId::System(SystemCapability::Clock) { + Ok(()) + } else { + require_owner(state, caller) + } +} + +/// Answering is what lets an Active patch declare. Draft answers nothing: +/// `SeedRequest` — the ontology's draft-phase answer — is not inhabited, so +/// genesis and draft elaboration answer nothing. In Active, a patch that only +/// changes components of existing structure is the operator's hand and answers +/// nothing; a patch that declares or admits evidence is elaboration, and +/// elaboration answers a boundary the kernel currently derives or a +/// jurisdiction whose deficit is nonzero. +fn require_answer( + state: &WorldState, + answers: Option<&PatchAnswer>, + declares: bool, +) -> Result<(), KernelError> { + match (state.phase, answers) { + (WorldPhase::Draft, None) => Ok(()), + (WorldPhase::Draft, Some(_)) => Err(KernelError::AnswerNotDerived), + (WorldPhase::Active, None) if declares => Err(KernelError::AnswerRequired), + (WorldPhase::Active, None) => Ok(()), + (WorldPhase::Active, Some(PatchAnswer::Boundary(claimed))) => { + exact_boundary(state, claimed).map(|_| ()) + } + (WorldPhase::Active, Some(PatchAnswer::Deficit(jurisdiction))) => { + if jurisdiction_deficit(state, *jurisdiction)? > 0 { + Ok(()) + } else { + Err(KernelError::AnswerNotDerived) + } + } + } +} + +/// The total deficit of one jurisdiction, which is what an answer must strictly +/// reduce. +fn jurisdiction_deficit( + state: &WorldState, + jurisdiction: JurisdictionKey, +) -> Result { + Ok(derive_scale_deficit(state)? + .into_iter() + .filter(|row| row.jurisdiction == jurisdiction) + .map(|row| u64::from(row.deficit)) + .sum()) +} + /// A human principal joins `required_approvers`, so only the lane that builds /// revision 0 from nothing may bind one. The predicate reads state, never the /// caller. It takes the two fields it inspects rather than a whole @@ -1240,6 +1426,11 @@ impl WorldState { authority: BTreeMap::new(), selection: BTreeMap::new(), redress: BTreeMap::new(), + commitments: BTreeMap::new(), + pressures: BTreeMap::new(), + last_opportunity_at: BTreeMap::new(), + now: FictionalMinutes::default(), + scale_intent: WorldScaleIntent::default(), controller_assignments: BTreeMap::new(), affordance_catalog: BTreeMap::new(), affordance_grants: BTreeMap::new(), @@ -1275,8 +1466,13 @@ impl WorldState { // every other command. Deterministic allocation is what lets one // equality replace a field-by-field binding zip. let mut state = Self::empty(world_id, owner.clone(), title.clone()); - let expected = patch::resolve_patch(&state, command.id, &command.patch) - .map_err(KernelError::PatchRejected)?; + let expected = patch::resolve_patch( + &state, + command.id, + &command.patch, + Some(&command.scale_intent), + ) + .map_err(KernelError::PatchRejected)?; if &expected != resolved { return Err(KernelError::Invariant( "genesis effect does not derive from its creation command".into(), @@ -1497,6 +1693,9 @@ fn admit_resolved(state: &mut WorldState, resolved: &ResolvedPatch) -> Result<() )); } } + if let Some(intent) = &resolved.scale_intent { + state.scale_intent = intent.clone(); + } apply_operations(state, &resolved.operations, &resolved.evidence) } @@ -2150,10 +2349,176 @@ fn apply_operation( } seat.controller = *controller; } + ResolvedOp::CreateCommitment { + subject, + key, + commitment, + } => { + if !state.subjects.contains_key(subject) + || !commitment_is_live(state, *subject, commitment) + { + return Err(KernelError::Invariant( + "a commitment names no live promisor, counterparty, or check".into(), + )); + } + if state + .commitments + .entry(*subject) + .or_default() + .insert(*key, commitment.clone()) + .is_some() + { + return Err(KernelError::Invariant("commitment key collision".into())); + } + } + ResolvedOp::DischargeCommitment { subject, key } => { + // One removal, two writes, one owner: the commitment and every + // pressure row it sourced. + let discharged = || KernelError::Invariant("discharge names no live commitment".into()); + let held = state.commitments.get_mut(subject).ok_or_else(discharged)?; + held.remove(key).ok_or_else(discharged)?; + let empty = held.is_empty(); + if empty { + state.commitments.remove(subject); + } + let sourced = PressureSource::Commitment { + subject: *subject, + key: *key, + }; + state.pressures.retain(|_, held| { + held.remove(&sourced); + !held.is_empty() + }); + } + ResolvedOp::AdvancePressure { source, target, by } + | ResolvedOp::ReducePressure { source, target, by } => { + let advancing = matches!(operation, ResolvedOp::AdvancePressure { .. }); + if !state.subjects.contains_key(target) || !pressure_source_is_live(state, source) { + return Err(unknown()); + } + let current = state + .pressures + .get(target) + .and_then(|held| held.get(source)) + .map_or(0, |magnitude| magnitude.0); + let next = if advancing { + current.saturating_add(by.0) + } else { + current.saturating_sub(by.0) + }; + if next == current { + return Err(KernelError::Invariant( + "pressure operation changes nothing".into(), + )); + } + set_pressure(state, *target, *source, next); + } + ResolvedOp::ResolvePressure { source, target } => { + if state + .pressures + .get(target) + .is_none_or(|held| !held.contains_key(source)) + { + return Err(KernelError::Invariant( + "pressure operation changes nothing".into(), + )); + } + set_pressure(state, *target, *source, 0); + } } Ok(()) } +/// Zero removes the source key, and an emptied target removes the target key, +/// so `pressures` has exactly one representation of nothing. +fn set_pressure(state: &mut WorldState, target: SubjectId, source: PressureSource, value: u32) { + if value == 0 { + let empty = if let Some(held) = state.pressures.get_mut(&target) { + held.remove(&source); + held.is_empty() + } else { + false + }; + if empty { + state.pressures.remove(&target); + } + } else { + state + .pressures + .entry(target) + .or_default() + .insert(source, PressureMagnitude(value)); + } +} + +/// Whether every referent a commitment names is live and its shape holds. +/// Re-derived over the committed partitions, because a forged effect reaches +/// `apply_operation` without ever passing the resolver. +fn commitment_is_live(state: &WorldState, subject: SubjectId, commitment: &Commitment) -> bool { + let counterparty_is_live = match commitment.counterparty { + Some(counterparty) => { + counterparty != subject + && state.subjects.contains_key(&counterparty) + && commitment.kind != CommitmentKind::Goal + } + None => true, + }; + counterparty_is_live + && (commitment.kind == CommitmentKind::Routine) == commitment.period.is_some() + && (commitment.kind == CommitmentKind::Routine || commitment.checks.is_empty()) + && commitment.due > state.now + && commitment + .checks + .iter() + .all(|check| bound_precondition_is_live(state, check)) +} + +fn bound_precondition_is_live(state: &WorldState, check: &BoundPrecondition) -> bool { + let is_kind = |entity_id: &EntityId, kind: EntityKind| { + state + .entities + .get(entity_id) + .is_some_and(|record| record.kind == kind) + }; + let audience_is_live = |via: &Audience| match via { + Audience::Colocated => true, + Audience::Channel(entity_id) => state.channels.contains_key(entity_id), + }; + match check { + BoundPrecondition::Present { at } => is_kind(at, EntityKind::Place), + BoundPrecondition::Reachable { to, within } => { + is_kind(to, EntityKind::Place) && patch::is_valid_cost(*within) + } + BoundPrecondition::Holds { resource, .. } => is_kind(resource, EntityKind::Resource), + BoundPrecondition::Authorized { over, kind } => { + patch::is_civic_name(&kind.0) + && match over { + Target::Subject(subject_id) => state.subjects.contains_key(subject_id), + Target::Entity(entity_id) => is_kind(entity_id, EntityKind::Place), + Target::Edge(edge_id) => state.edges.contains_key(edge_id), + } + } + BoundPrecondition::HasStanding { grievance } => patch::is_civic_name(&grievance.0), + BoundPrecondition::Knows { fact, .. } => is_kind(fact, EntityKind::Fact), + BoundPrecondition::CanBroadcast { via } => audience_is_live(via), + BoundPrecondition::CanReach { subject, via } => { + state.subjects.contains_key(subject) && audience_is_live(via) + } + BoundPrecondition::Committed { to, .. } => state.subjects.contains_key(to), + } +} + +fn pressure_source_is_live(state: &WorldState, source: &PressureSource) -> bool { + match source { + PressureSource::Commitment { subject, key } => state + .commitments + .get(subject) + .is_some_and(|held| held.contains_key(key)), + PressureSource::Dependency(target) => dependency_target_exists(state, *target), + PressureSource::Subject(subject_id) => state.subjects.contains_key(subject_id), + } +} + /// The label every minted claim carries. A label is a name, not a transcript: /// the statement is never copied into it and the label is never derived from /// it. Labels resolve no references, so identical labels across every claim @@ -2369,6 +2734,11 @@ pub(super) struct ScopeComponents { /// a thousand digests per membership change, which is whole-world binding by /// the front door. controls: BTreeMap, + /// This subject's own commitments. `Precondition::Committed` reads them, so + /// the digest must bind them. Pressure, the clock, and the attention stamp + /// stay out: no precondition reads any of the three, so a tick that only + /// advances pressure invalidates no in-flight proposal. + commitments: BTreeMap, } /// Whether an authority target covers a referent. The one statement of @@ -2500,6 +2870,11 @@ fn scope_components(state: &WorldState, subject_id: SubjectId) -> ScopeComponent .filter(|(_, record)| record.controller == Some(subject_id)) .map(|(entity_id, record)| (*entity_id, record.clone())) .collect(), + commitments: state + .commitments + .get(&subject_id) + .cloned() + .unwrap_or_default(), } } @@ -2638,6 +3013,28 @@ fn snapshot(state: &WorldState) -> Result { redress, knowledge, controls: components.controls.into_keys().collect(), + commitments: components + .commitments + .into_iter() + .map(|(key, commitment)| CommitmentSnapshot { + key, + kind: commitment.kind, + counterparty: commitment.counterparty, + due: commitment.due, + period: commitment.period, + past_due: commitment.due <= state.now, + }) + .collect(), + pressures: state + .pressures + .get(subject_id) + .into_iter() + .flatten() + .map(|(source, magnitude)| PressureSnapshot { + source: *source, + magnitude: *magnitude, + }) + .collect(), }) }) .collect::, KernelError>>()?; @@ -2696,12 +3093,326 @@ fn snapshot(state: &WorldState) -> Result { places, resources, routes, - opportunities: derive_opportunities(state)?, + opportunities: order_opportunities(state, derive_opportunities(state)?), + now: state.now, + boundaries: derive_boundaries(state)?, + scale_deficit: derive_scale_deficit(state)?, state_digest: state.state_digest.clone(), last_commit_digest: state.last_commit_digest.clone(), }) } +/// A place in the world's causal reach that the world has not yet grown into. +/// Derived, never stored, and cleared by no writer: a boundary stops being +/// derived when its predicate stops holding. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "boundary", rename_all = "snake_case")] +pub(crate) enum CausalBoundary { + UnelaboratedDestination { + route: EdgeId, + place: EntityId, + scope: BoundaryDigest, + }, + MissingStructure { + subject: SubjectId, + key: CommitmentKey, + scope: BoundaryDigest, + }, + /// Declared, never derived: no relations partition exists. Answering one is + /// `AnswerNotDerived`. + PolityInCausalRange { + subject: SubjectId, + scope: BoundaryDigest, + }, + /// Declared, never derived: no population membership and no slice concept + /// exists. Answering one is `AnswerNotDerived`. + IndividuationRequired { + population: SubjectId, + scope: BoundaryDigest, + }, +} + +/// The digest of exactly the components that derive one boundary, produced by +/// the one `digest()` owner, in the `ScopeDigest` idiom. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct BoundaryDigest(String); + +#[derive(Serialize)] +struct UnelaboratedDestinationPreimage<'a> { + world_id: WorldId, + route: &'a EdgeRecord, + place: &'a EntityRecord, + contained: BTreeSet, + occupants: BTreeSet, + incident: BTreeSet, +} + +#[derive(Serialize)] +struct MissingStructurePreimage<'a> { + world_id: WorldId, + subject: SubjectId, + key: CommitmentKey, + commitment: &'a Commitment, + counterparty_authority: BTreeSet, + redress: &'a BTreeMap, +} + +/// Beside `derive_opportunities`, and reached from `snapshot` and from +/// `reduce`'s `AdmitPatch` arm. The same shape as the opportunity derivation, +/// not the same function: the inputs and the consumers differ, and a shared +/// derivation returning a sum type would be a generic helper wearing a name. +fn derive_boundaries(state: &WorldState) -> Result, KernelError> { + let mut boundaries = Vec::new(); + for (edge_id, record) in &state.edges { + let (from, to) = record.endpoints(); + for place in [from, to] { + let contained: BTreeSet = state + .entities + .iter() + .filter(|(_, entity)| entity.container == Some(place)) + .map(|(entity_id, _)| *entity_id) + .collect(); + let occupants: BTreeSet = state + .positions + .iter() + .filter(|(_, position)| position.place == place) + .map(|(subject_id, _)| *subject_id) + .collect(); + let incident: BTreeSet = state + .edges + .iter() + .filter(|(_, candidate)| { + let (candidate_from, candidate_to) = candidate.endpoints(); + candidate_from == place || candidate_to == place + }) + .map(|(candidate_id, _)| *candidate_id) + .collect(); + if !contained.is_empty() + || !occupants.is_empty() + || incident.len() != 1 + || !incident.contains(edge_id) + { + continue; + } + let entity = state + .entities + .get(&place) + .ok_or_else(|| KernelError::Invariant("a route names no canonical place".into()))?; + boundaries.push(CausalBoundary::UnelaboratedDestination { + route: *edge_id, + place, + scope: BoundaryDigest(digest(&UnelaboratedDestinationPreimage { + world_id: state.world_id, + route: record, + place: entity, + contained, + occupants, + incident, + })?), + }); + } + } + // A commitment the counterparty can neither command nor litigate. Both + // clauses read the civic partitions through their own predicates, so + // jurisdiction lent by an office counts and no second covering rule exists. + // A `Goal` derives nothing: a promise to oneself needs no forum. + for (subject, held) in &state.commitments { + for (key, commitment) in held { + let Some(counterparty) = commitment.counterparty else { + continue; + }; + let counterparty_authority = subject_authority(state, counterparty); + let commandable = counterparty_authority + .iter() + .any(|grant| covers(state, grant.over, Target::Subject(*subject))); + let litigable = state + .redress + .values() + .any(|forum| covers(state, forum.standing, Target::Subject(counterparty))); + if commandable || litigable { + continue; + } + boundaries.push(CausalBoundary::MissingStructure { + subject: *subject, + key: *key, + scope: BoundaryDigest(digest(&MissingStructurePreimage { + world_id: state.world_id, + subject: *subject, + key: *key, + commitment, + counterparty_authority, + redress: &state.redress, + })?), + }); + } + } + Ok(boundaries) +} + +/// The sole validator of a claimed boundary, mirroring `exact_opportunity`. +fn exact_boundary( + state: &WorldState, + claimed: &CausalBoundary, +) -> Result { + derive_boundaries(state)? + .into_iter() + .find(|current| current == claimed) + .ok_or(KernelError::AnswerNotDerived) +} + +/// One region's count for one subject kind. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) struct ScaleDeficitRow { + pub(crate) jurisdiction: JurisdictionKey, + pub(crate) kind: SubjectKind, + pub(crate) target: u32, + pub(crate) qualified: u32, + pub(crate) deficit: u32, +} + +/// Whether a subject counts toward the world's scale target. Three of the four +/// clauses cannot currently fail — the world-level phase gate, the one- +/// controller rule, and the non-empty grant set are already enforced elsewhere +/// — so `Goal` carries the whole discrimination at this pass. The conjunction +/// is written once anyway, because retirement and grant revocation make two of +/// the clauses live later and a scattered count would then be wrong in three +/// places. "Executable" is structural, never "preconditions currently hold": +/// evaluating them per subject per snapshot would make the deficit flicker as +/// routes open and close. +fn qualifies(state: &WorldState, subject_id: SubjectId) -> bool { + let scope = DecisionScope { subject_id }; + state.phase == WorldPhase::Active + && state.controller_assignments.contains_key(&scope) + && state + .affordance_grants + .get(&scope) + .is_some_and(|granted| !granted.is_empty()) + && state.commitments.get(&subject_id).is_some_and(|held| { + held.values() + .any(|commitment| commitment.kind == CommitmentKind::Goal) + }) +} + +/// Derived in `snapshot`, never stored. `snapshot` is the recount: it already +/// re-derives everything, and a second after-every-commit step would be a +/// second owner. Only admitted subjects reduce it, so a rejected patch leaves +/// it visible, which is free — a rejection mutates nothing. +fn derive_scale_deficit(state: &WorldState) -> Result, KernelError> { + let mut counted: BTreeMap<(JurisdictionKey, SubjectKind), u32> = BTreeMap::new(); + for (subject_id, subject) in &state.subjects { + if !qualifies(state, *subject_id) { + continue; + } + match state.positions.get(subject_id) { + // A subject under nested roots counts toward both: layered + // jurisdiction applied to counting. + Some(position) => { + for root in state.scale_intent.jurisdictions.keys() { + if patch::covers_place(&state.entities, *root, position.place) { + *counted + .entry((JurisdictionKey::PlaceSubtree(*root), subject.kind)) + .or_default() += 1; + } + } + } + // Counted, visible, and reducing no target. + None => { + *counted + .entry((JurisdictionKey::Unplaced, subject.kind)) + .or_default() += 1; + } + } + } + let mut rows: BTreeMap<(JurisdictionKey, SubjectKind), ScaleDeficitRow> = BTreeMap::new(); + for (kind, world_target) in &state.scale_intent.targets { + for (root, permille) in &state.scale_intent.jurisdictions { + let jurisdiction = JurisdictionKey::PlaceSubtree(*root); + let target = u32::try_from( + u64::from(*world_target) + .checked_mul(u64::from(*permille)) + .ok_or_else(|| KernelError::Invariant("scale target overflow".into()))? + / 1000, + ) + .map_err(|_| KernelError::Invariant("scale target overflow".into()))?; + let qualified = counted + .get(&(jurisdiction, *kind)) + .copied() + .unwrap_or_default(); + rows.insert( + (jurisdiction, *kind), + ScaleDeficitRow { + jurisdiction, + kind: *kind, + target, + qualified, + deficit: target.saturating_sub(qualified), + }, + ); + } + } + for ((jurisdiction, kind), qualified) in counted { + rows.entry((jurisdiction, kind)) + .or_insert(ScaleDeficitRow { + jurisdiction, + kind, + target: 0, + qualified, + deficit: 0, + }) + .qualified = qualified; + } + Ok(rows + .into_values() + .filter(|row| row.target > 0 || row.qualified > 0) + .collect()) +} + +/// A pure re-ordering of `derive_opportunities`' output: same values, same +/// length, same set. Never a filter — filtering by readiness would drag +/// precondition reads into `ScopePreimage`, and a tick could then withdraw an +/// opportunity a controller is mid-inference on, which `exact_opportunity` +/// would report as `OpportunityMismatch` rather than the honest `ScopeChanged`. +/// +/// A subject never attended sorts ahead of every subject that has, and a +/// subject with no pressure still climbs one tick at a time, so the order +/// starves nobody. `SubjectId` is the final tiebreak, so the order is total and +/// identical on every machine. +fn order_opportunities( + state: &WorldState, + mut opportunities: Vec, +) -> Vec { + opportunities.sort_by_key(|opportunity| { + let subject_id = opportunity.scope.subject_id; + ( + std::cmp::Reverse(pressure_total(state, subject_id)), + std::cmp::Reverse(attention_debt(state, subject_id)), + subject_id, + ) + }); + opportunities +} + +fn pressure_total(state: &WorldState, subject_id: SubjectId) -> u64 { + state + .pressures + .get(&subject_id) + .into_iter() + .flat_map(BTreeMap::values) + .fold(0u64, |total, magnitude| { + total.saturating_add(u64::from(magnitude.0)) + }) +} + +/// Minutes since this subject last consumed an opportunity. Absence is +/// `u64::MAX`: never attended outranks every subject that has. +fn attention_debt(state: &WorldState, subject_id: SubjectId) -> u64 { + state + .last_opportunity_at + .get(&subject_id) + .map_or(u64::MAX, |stamp| state.now.since(*stamp)) +} + fn derive_opportunities(state: &WorldState) -> Result, KernelError> { if state.phase != WorldPhase::Active { return Ok(Vec::new()); @@ -2906,21 +3617,52 @@ fn apply_effect( caller: &CallerId, effect: &WorldEffect, ) -> Result<(), KernelError> { + // The capability rule `reduce` decided, re-decided here against the effect + // the command produced. + if matches!(caller, CallerId::System(SystemCapability::Clock)) + && !matches!(effect, WorldEffect::TimeAdvanced { .. }) + { + return Err(KernelError::Unauthorized); + } match effect { WorldEffect::WorldCreated { .. } => { return Err(KernelError::Invariant( "world genesis cannot be applied as a mutable effect".into(), )); } - WorldEffect::PatchAdmitted { resolved } => { - if caller != &CallerId::Principal(state.owner.clone()) - || (state.phase == WorldPhase::Active && !resolved.declares_nothing()) - { + WorldEffect::PatchAdmitted { answers, resolved } => { + if caller != &CallerId::Principal(state.owner.clone()) { return Err(KernelError::Invariant( "admitted patch does not satisfy admission authority".into(), )); } + require_answer(state, answers.as_ref(), !resolved.declares_nothing())?; + // The deficit before the write, so "strictly decreased" is a + // comparison rather than a claim the effect makes. + let before = match answers { + Some(PatchAnswer::Deficit(jurisdiction)) => { + jurisdiction_deficit(state, *jurisdiction)? + } + _ => 0, + }; admit_resolved(state, resolved)?; + // What makes "a commit clears exactly the boundary it answers" + // structural rather than hoped for. "Nothing else clears one" is + // true by construction: boundaries are derived and no writer + // clears one. + match answers { + Some(PatchAnswer::Boundary(answered)) => { + if exact_boundary(state, answered).is_ok() { + return Err(KernelError::AnswerNotSatisfied); + } + } + Some(PatchAnswer::Deficit(jurisdiction)) => { + if jurisdiction_deficit(state, *jurisdiction)? >= before { + return Err(KernelError::AnswerNotSatisfied); + } + } + None => {} + } } WorldEffect::DraftApproved { principal } => { if state.phase != WorldPhase::Draft @@ -2975,6 +3717,9 @@ fn apply_effect( if !event.effects.is_empty() { apply_operations(state, &event.effects, &[])?; } + state + .last_opportunity_at + .insert(current.scope.subject_id, state.now); } WorldEffect::DecisionDeclined { opportunity } => { let current = exact_opportunity(state, opportunity)?; @@ -2989,6 +3734,51 @@ fn apply_effect( "decline effect does not match exact opportunity authority".into(), )); } + // A decline consumed the turn: a controller that keeps declining + // must not keep the head of the queue. + state + .last_opportunity_at + .insert(current.scope.subject_id, state.now); + } + WorldEffect::TimeAdvanced { + minutes, + to, + motion, + } => { + require_phase(state, WorldPhase::Active)?; + require_clock_caller(state, caller)?; + let derived_to = state + .now + .checked_add(*minutes) + .ok_or_else(|| KernelError::Serialization("world clock overflow".into()))?; + // The whole motion is re-derived rather than trusted field by + // field, so a forged fulfilment, magnitude, row, and target are one + // comparison. + if derived_to != *to || clock::derive_motion(state, derived_to) != *motion { + return Err(KernelError::Invariant( + "time effect does not derive from the world clock".into(), + )); + } + state.now = *to; + for rolled in &motion.fulfilled { + let commitment = state + .commitments + .get_mut(&rolled.subject) + .and_then(|held| held.get_mut(&rolled.key)) + .ok_or_else(|| { + KernelError::Invariant("a fulfilled routine has no commitment".into()) + })?; + commitment.due = rolled.next_due; + } + // No inner map is ever left empty, because `derive_motion` emits no + // zero magnitude. + for written in &motion.pressed { + state + .pressures + .entry(written.target) + .or_default() + .insert(written.source, written.magnitude); + } } } Ok(()) @@ -3155,6 +3945,7 @@ mod tests { }), ], }, + scale_intent: WorldScaleIntentRef::default(), } } @@ -6343,7 +7134,9 @@ mod custody_tests { qty: Quantity(OPENING_BALANCE + 1), }], evidence: Vec::new(), + scale_intent: None, }, + answers: None, }; let error = apply_effect( &mut candidate, @@ -6929,7 +7722,9 @@ mod custody_tests { channels: Vec::new(), operations, evidence: Vec::new(), + scale_intent: None, }, + answers: None, }; let transfer = |qty: u64| ResolvedOp::Transfer { from: custody.holder, @@ -8606,14 +9401,8 @@ mod soul_knowledge_tests { ) .unwrap_err(); assert!( - matches!( - error, - KernelError::WrongPhase { - expected: WorldPhase::Draft, - actual: WorldPhase::Active, - } - ), - "an active world admitted a declaration: {error:?}" + matches!(error, KernelError::AnswerRequired), + "an active world admitted an unanswered declaration: {error:?}" ); assert_eq!(kernel.state, before); drop(kernel); diff --git a/crates/ghostlight-dungeon/src/world/patch.rs b/crates/ghostlight-dungeon/src/world/patch.rs index 2162a36..a258d9c 100644 --- a/crates/ghostlight-dungeon/src/world/patch.rs +++ b/crates/ghostlight-dungeon/src/world/patch.rs @@ -11,6 +11,7 @@ //! Resolution accumulates the complete mismatch set first and allocates only //! after that set is empty, so a rejected patch never mints an ID. +use super::clock::{FictionalMinutes, TickMinutes}; use super::{ AffordanceId, CommandId, ControllerAssignment, ControllerId, EdgeId, EntityId, NewController, SubjectId, SubjectKind, SubjectState, WorldId, @@ -426,10 +427,199 @@ pub(crate) enum AudienceSpec { Channel(Role), } +/// What a subject has promised. The kernel branches on this twice — the tick +/// behaves differently per kind and the scale count reads `Goal` — so it is a +/// closed enum rather than a world-declared name. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub(crate) enum CommitmentKind { + Routine, + Obligation, + Goal, +} + +/// Deterministic from the creating command and the operation's index within +/// that command's lowered operations. No `EdgeId`: nothing references a +/// commitment by identity, so a structural key is the whole answer. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub(crate) struct CommitmentKey { + pub(crate) command: CommandId, + pub(crate) index: u32, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct Commitment { + pub(crate) kind: CommitmentKind, + /// `None` is a promise to oneself: a personal `Goal`. A counterparty equal + /// to the subject is refused. + pub(crate) counterparty: Option, + /// Absolute. "Past due" is `due <= now`: one comparison, no countdown + /// fanned across the partition. + pub(crate) due: FictionalMinutes, + /// Required for `Routine` — that is what makes it recur — and forbidden + /// otherwise. On auto-fulfilment `due` rolls forward by this. + pub(crate) period: Option, + /// What must hold for a `Routine` to auto-fulfil. Role-free canonical + /// checks. Empty for `Obligation` and `Goal`. + pub(crate) checks: Vec, +} + +/// Nonzero by construction; saturating in both directions. A separate newtype +/// from [`super::Magnitude`], which is an effect ceiling and shares nothing with +/// this but a word. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct PressureMagnitude(pub(crate) u32); + +/// Target-major, because every reader is: the attention order reads pressure +/// *on* a subject and the typed view shows pressure on self. Source-major has no +/// reader. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "from", rename_all = "snake_case")] +pub(crate) enum PressureSource { + /// A past-due commitment. Carries the promisor and the structural key. + Commitment { + subject: SubjectId, + key: CommitmentKey, + }, + /// An unavailable dependency of the pressed subject. This is how a closed + /// route in one realm becomes a political problem in another without anyone + /// deciding that it should be. + Dependency(DependencyTarget), + /// Another subject, pressing directly through an affordance effect. + Subject(SubjectId), +} + +/// The proposal-time twin of [`PressureSource`]. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "from", rename_all = "snake_case")] +pub(crate) enum PressureSourceRef { + Commitment { + subject: Ref, + key: CommitmentKey, + }, + Dependency(DependencyRef), + Subject(Ref), +} + +/// The role-free canonical twin of [`Precondition`]. A `Precondition` names +/// roles; a `BoundPrecondition` names referents, so a commitment's checks are +/// storable with no second binding path and one evaluator serves both the +/// invocation pipeline and the tick. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "precondition", rename_all = "snake_case")] +pub(crate) enum BoundPrecondition { + Present { + at: EntityId, + }, + Reachable { + to: EntityId, + within: Cost, + }, + Holds { + resource: EntityId, + at_least: Quantity, + }, + Authorized { + over: super::Target, + kind: AuthorityKindName, + }, + HasStanding { + grievance: GrievanceKindName, + }, + Knows { + fact: EntityId, + at_least: Confidence, + }, + CanBroadcast { + via: Audience, + }, + CanReach { + subject: SubjectId, + via: Audience, + }, + Committed { + to: SubjectId, + kind: CommitmentKind, + }, +} + +/// The proposal-time twin of [`BoundPrecondition`], carried by +/// `CreateCommitment` so a patch may name a check over structure it declares. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "precondition", rename_all = "snake_case")] +pub(crate) enum PreconditionRef { + Present { + at: Ref, + }, + Reachable { + to: Ref, + within: Cost, + }, + Holds { + resource: Ref, + at_least: Quantity, + }, + Authorized { + over: AuthorityTargetRef, + kind: AuthorityKindName, + }, + HasStanding { + grievance: GrievanceKindName, + }, + Knows { + fact: Ref, + at_least: Confidence, + }, + CanBroadcast { + via: AudienceRef, + }, + CanReach { + subject: Ref, + via: AudienceRef, + }, + Committed { + to: Ref, + kind: CommitmentKind, + }, +} + +/// The authored scale target: how many qualified subjects of each kind the +/// world means to hold, and how that target distributes over jurisdiction +/// roots. Written once by genesis and never mutated. Not a component of any +/// referent, so not a `Declaration` and not a partition. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct WorldScaleIntent { + /// Target qualified subjects per kind, world-wide. + pub(crate) targets: BTreeMap, + /// Jurisdiction roots and their share, in permille. Weights distribute the + /// target and never raise it: the sum is checked `<= 1000`. + pub(crate) jurisdictions: BTreeMap, +} + +/// The genesis-lane twin: the intent names places the same patch declares, and +/// there is no other way to name them before they exist. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct WorldScaleIntentRef { + pub(crate) targets: BTreeMap, + pub(crate) jurisdictions: BTreeMap, +} + +/// One counted region of the scale deficit. `Unplaced` is the residual: a +/// subject standing nowhere is counted and visible while reducing no target. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "jurisdiction", content = "root", rename_all = "snake_case")] +pub(crate) enum JurisdictionKey { + PlaceSubtree(EntityId), + Unplaced, +} + /// What must already be true of committed state before an invocation is -/// admitted. Only the ones whose components exist: `Committed` lands in the pass -/// that adds `Commitment`. A variant whose only behaviour would be to be refused -/// is a placeholder wearing a check. +/// admitted. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "precondition", rename_all = "snake_case")] pub(crate) enum Precondition { @@ -457,6 +647,10 @@ pub(crate) enum Precondition { /// The referent bound to `subject` is inside that audience. Addressing does /// not narrow the audience: a telling still lands on everyone in it. CanReach { subject: Role, via: AudienceSpec }, + /// The acting subject holds a commitment of `kind` to the referent bound to + /// `to`. This is what lets a world author an affordance whose legitimacy is + /// a promise rather than a jurisdiction. + Committed { to: Role, kind: CommitmentKind }, } /// Exactly the operations an affordance may propose. `Admit` is absent because @@ -500,6 +694,24 @@ pub(crate) enum ComponentOpKind { confidence: Confidence, }, Forget, + /// The kind, the horizon, and the period are fixed on the variant, so a + /// proposer's only degree of freedom stays magnitude. `due` is + /// `now + horizon`, computed by the kernel at lowering: an absolute due on + /// a catalog entry would be a fixed date the world outgrows. + CreateCommitment { + kind: CommitmentKind, + horizon: TickMinutes, + period: Option, + }, + /// The source is fixed to the acting subject, so it cannot be forged. A + /// world authoring `threaten`, `reassure`, or `forgive` needs these three. + AdvancePressure { + by: PressureMagnitude, + }, + ReducePressure { + by: PressureMagnitude, + }, + ResolvePressure, } /// The referent shape of one operation: the single source of both the @@ -538,6 +750,14 @@ impl ComponentOpKind { Self::AcquireKnowledge { .. } | Self::Forget => { vec![subject(), RoleKindRule::Exact(FACT)] } + // Promisor and counterparty. A `Goal` slot is refused at admission + // with `GoalWithCounterparty`: a promise to oneself has no second + // referent to bind, so the action lane authors `Routine` and + // `Obligation` and the patch lane authors goals. + Self::CreateCommitment { .. } => vec![subject(), subject()], + Self::AdvancePressure { .. } | Self::ReducePressure { .. } | Self::ResolvePressure => { + vec![subject()] + } } } @@ -858,12 +1078,55 @@ pub(crate) enum ComponentOp { channel: Ref, controller: Option>, }, + /// Two identical creations are two commitments, not `NoOperationEffect`: + /// the key is command-derived so they cannot collide, and two promises of + /// the same thing to the same counterparty are two promises. This is where + /// a commitment differs from a grant, a holding, and a dependency, all of + /// which are set-shaped. + CreateCommitment { + subject: Ref, + counterparty: Option>, + kind: CommitmentKind, + due: FictionalMinutes, + period: Option, + checks: Vec, + }, + /// Removes the commitment and every pressure row sourced by it. Fulfilment, + /// default, and release are one write: the kernel never learns who invoked + /// an operation, so three names would be three spellings of one removal + /// with a distinction only a consumer can read. + DischargeCommitment { + subject: Ref, + key: CommitmentKey, + }, + /// Insert-or-add, saturating. With absence meaning zero, creation and + /// advance are the same write. + AdvancePressure { + source: PressureSourceRef, + target: Ref, + by: PressureMagnitude, + }, + /// Saturating subtract; removal at zero. + ReducePressure { + source: PressureSourceRef, + target: Ref, + by: PressureMagnitude, + }, + ResolvePressure { + source: PressureSourceRef, + target: Ref, + }, } -/// Empty on purpose: an `Option` can only be `None`, so the -/// answers-are-None rule is compile-enforced. +/// What an Active `AdmitPatch` answers. Draft answers nothing; Active must +/// answer a boundary the kernel currently derives or a jurisdiction whose +/// deficit is nonzero, and the commit must satisfy what it answered. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -pub(crate) enum PatchAnswer {} +#[serde(tag = "answer", rename_all = "snake_case")] +pub(crate) enum PatchAnswer { + Boundary(super::CausalBoundary), + Deficit(JurisdictionKey), +} #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(deny_unknown_fields)] @@ -1105,6 +1368,39 @@ pub(crate) enum Mismatch { AmbiguousSpeechAudience { handle: DraftHandle, }, + /// A `Routine` with no period, or a non-`Routine` with one. + CommitmentPeriodMismatch { + operation: usize, + }, + /// A non-`Routine` carrying checks. Nothing would ever evaluate them. + ChecksOnNonRoutine { + operation: usize, + }, + /// `due <= now` at creation. A promise cannot be born past due; it would + /// press on its subject on the very next tick with no chance to act. + CommitmentDueInThePast { + operation: usize, + }, + /// `counterparty == subject`. + SelfCommitment { + operation: usize, + }, + /// A goal is a promise to oneself, and a promise to another is an + /// obligation. This keeps the scale count's `Goal` clause meaning one thing. + GoalWithCounterparty { + operation: usize, + }, + /// `DischargeCommitment` naming a key the subject does not hold. + UnknownCommitment { + operation: usize, + }, + /// A scale-intent jurisdiction root that is not a declared place. + UnknownJurisdictionRoot { + handle: DraftHandle, + }, + /// The permille weights sum over 1000: weights distribute the target and + /// never raise it. + ScaleWeightsExceedWhole, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] @@ -1347,6 +1643,29 @@ pub(crate) enum ResolvedOp { statement: Statement, by: SubjectId, }, + CreateCommitment { + subject: SubjectId, + key: CommitmentKey, + commitment: Commitment, + }, + DischargeCommitment { + subject: SubjectId, + key: CommitmentKey, + }, + AdvancePressure { + source: PressureSource, + target: SubjectId, + by: PressureMagnitude, + }, + ReducePressure { + source: PressureSource, + target: SubjectId, + by: PressureMagnitude, + }, + ResolvePressure { + source: PressureSource, + target: SubjectId, + }, } /// One resource's movement across a whole patch. Accumulators are `u128` so an @@ -1398,6 +1717,10 @@ pub(super) struct ResolvedPatch { pub(super) channels: Vec, pub(super) operations: Vec, pub(super) evidence: Vec, + /// `Some` on the genesis lane and nowhere else: `CommandBody::AdmitPatch` + /// carries no intent, so the write-once rule is the command shape rather + /// than a check. + pub(super) scale_intent: Option, } impl ResolvedPatch { @@ -1449,6 +1772,17 @@ enum TargetKey { Subject(Key), } +/// [`PressureSource`] over candidate keys. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum PressureSourceKey { + Commitment { + subject: Key, + key: CommitmentKey, + }, + Dependency(TargetKey), + Subject(Key), +} + /// [`AuthorityTarget`] over candidate keys, so a grant over a place this patch /// declares is checked before any ID is minted. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] @@ -1953,6 +2287,7 @@ fn validate_affordance( require_subject(subject, mismatches); require_audience(via, mismatches); } + Precondition::Committed { to, .. } => require_subject(to, mismatches), } } // A speech-carrying entry must name exactly one audience: the lowering reads @@ -2423,6 +2758,7 @@ pub(super) fn resolve_patch( state: &super::WorldState, command_id: CommandId, patch: &WorldPatch, + scale_intent: Option<&WorldScaleIntentRef>, ) -> Result> { let world_id = state.world_id; let admits_human = super::admits_human(state.revision, &state.subjects); @@ -2714,6 +3050,56 @@ pub(super) fn resolve_patch( }) }) .collect(); + // Presence is all a discharge asks, and a create cannot collide: the key is + // command-derived and the index is unique within one patch. + let mut commitments: BTreeSet<(Key, CommitmentKey)> = state + .commitments + .iter() + .flat_map(|(subject_id, held)| { + held.keys() + .map(move |key| (Key::Existing(*subject_id), *key)) + }) + .collect(); + let mut pressures: BTreeMap<(Key, PressureSourceKey), u32> = state + .pressures + .iter() + .flat_map(|(target, held)| { + held.iter().map(move |(source, magnitude)| { + ( + ( + Key::Existing(*target), + match source { + PressureSource::Commitment { subject, key } => { + PressureSourceKey::Commitment { + subject: Key::Existing(*subject), + key: *key, + } + } + PressureSource::Dependency(DependencyTarget::Resource(entity_id)) => { + PressureSourceKey::Dependency(TargetKey::Resource(Key::Existing( + *entity_id, + ))) + } + PressureSource::Dependency(DependencyTarget::Route(edge_id)) => { + PressureSourceKey::Dependency(TargetKey::Route(Key::Existing( + *edge_id, + ))) + } + PressureSource::Dependency(DependencyTarget::Subject(subject_id)) => { + PressureSourceKey::Dependency(TargetKey::Subject(Key::Existing( + *subject_id, + ))) + } + PressureSource::Subject(subject_id) => { + PressureSourceKey::Subject(Key::Existing(*subject_id)) + } + }, + ), + magnitude.0, + ) + }) + }) + .collect(); let mut deltas: BTreeMap, LedgerDelta> = BTreeMap::new(); let mut declared_places: Vec<(DraftHandle, Key)> = Vec::new(); @@ -2861,7 +3247,159 @@ pub(super) fn resolve_patch( } for (position, operation) in patch.operations.iter().enumerate() { + let site = Site::Operation(position); match operation { + ComponentOp::CreateCommitment { + subject, + counterparty, + kind, + due, + period, + checks, + } => { + let subject_key = resolve_subject( + site.clone(), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let counterparty_key = counterparty.as_ref().map(|reference| { + resolve_subject( + site.clone(), + reference, + &index, + &state.subjects, + &mut mismatches, + ) + }); + let mut checks_resolve = true; + for check in checks { + checks_resolve &= + resolve_check(site.clone(), check, &index, state, &mut mismatches); + } + if (*kind == CommitmentKind::Routine) != period.is_some() { + mismatches.push(Mismatch::CommitmentPeriodMismatch { + operation: position, + }); + } + if let Some(period) = period + && !is_valid_cost(Cost(period.minutes())) + { + mismatches.push(Mismatch::InvalidCost { site: site.clone() }); + } + if *kind != CommitmentKind::Routine && !checks.is_empty() { + mismatches.push(Mismatch::ChecksOnNonRoutine { + operation: position, + }); + } + // A promise cannot be born past due: it would press on its + // subject on the very next tick with no chance to act. + if *due <= state.now { + mismatches.push(Mismatch::CommitmentDueInThePast { + operation: position, + }); + } + if counterparty.is_some() && *kind == CommitmentKind::Goal { + mismatches.push(Mismatch::GoalWithCounterparty { + operation: position, + }); + } + let Some(subject_key) = subject_key else { + continue; + }; + if let Some(counterparty_key) = &counterparty_key { + match counterparty_key { + None => continue, + Some(counterparty_key) if *counterparty_key == subject_key => { + mismatches.push(Mismatch::SelfCommitment { + operation: position, + }); + continue; + } + Some(_) => {} + } + } + if !checks_resolve { + continue; + } + commitments.insert(( + subject_key, + CommitmentKey { + command: command_id, + index: position as u32, + }, + )); + } + ComponentOp::DischargeCommitment { subject, key } => { + let Some(subject_key) = resolve_subject( + site.clone(), + subject, + &index, + &state.subjects, + &mut mismatches, + ) else { + continue; + }; + if !commitments.remove(&(subject_key, *key)) { + mismatches.push(Mismatch::UnknownCommitment { + operation: position, + }); + } + } + ComponentOp::AdvancePressure { source, target, by } + | ComponentOp::ReducePressure { source, target, by } => { + let advancing = matches!(operation, ComponentOp::AdvancePressure { .. }); + let target_key = resolve_subject( + site.clone(), + target, + &index, + &state.subjects, + &mut mismatches, + ); + let source_key = + resolve_pressure_source(site.clone(), source, &index, state, &mut mismatches); + let (Some(target_key), Some(source_key)) = (target_key, source_key) else { + continue; + }; + let slot = (target_key, source_key); + let current = pressures.get(&slot).copied().unwrap_or_default(); + let next = if advancing { + current.saturating_add(by.0) + } else { + current.saturating_sub(by.0) + }; + // A zero step and a subtraction that hits a floor both change + // nothing, which is one name and not three. + if next == current { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else if next == 0 { + pressures.remove(&slot); + } else { + pressures.insert(slot, next); + } + } + ComponentOp::ResolvePressure { source, target } => { + let target_key = resolve_subject( + site.clone(), + target, + &index, + &state.subjects, + &mut mismatches, + ); + let source_key = + resolve_pressure_source(site.clone(), source, &index, state, &mut mismatches); + let (Some(target_key), Some(source_key)) = (target_key, source_key) else { + continue; + }; + if pressures.remove(&(target_key, source_key)).is_none() { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } + } ComponentOp::Relocate { subject, via } => { let subject_key = resolve_subject( Site::Operation(position), @@ -3739,6 +4277,26 @@ pub(super) fn resolve_patch( }); } + if let Some(intent) = scale_intent { + for handle in intent.jurisdictions.keys() { + if index.get(handle) != Some(&PLACE) { + mismatches.push(Mismatch::UnknownJurisdictionRoot { + handle: handle.clone(), + }); + } + } + // Weights distribute the target and never raise it. + if intent + .jurisdictions + .values() + .map(|weight| u64::from(*weight)) + .sum::() + > 1000 + { + mismatches.push(Mismatch::ScaleWeightsExceedWhole); + } + } + if patch.declarations.is_empty() && patch.operations.is_empty() { mismatches.push(Mismatch::NoCanonicalChange); } @@ -4099,10 +4657,101 @@ pub(super) fn resolve_patch( over: authority_target_of(&grant.over), } }; + let precondition_of = |check: &PreconditionRef| -> BoundPrecondition { + match check { + PreconditionRef::Present { at } => BoundPrecondition::Present { + at: entity_id_of(&key_of(at)), + }, + PreconditionRef::Reachable { to, within } => BoundPrecondition::Reachable { + to: entity_id_of(&key_of(to)), + within: *within, + }, + PreconditionRef::Holds { resource, at_least } => BoundPrecondition::Holds { + resource: entity_id_of(&key_of(resource)), + at_least: *at_least, + }, + PreconditionRef::Authorized { over, kind } => BoundPrecondition::Authorized { + over: authority_target_of(over).as_referent(), + kind: kind.clone(), + }, + PreconditionRef::HasStanding { grievance } => BoundPrecondition::HasStanding { + grievance: grievance.clone(), + }, + PreconditionRef::Knows { fact, at_least } => BoundPrecondition::Knows { + fact: entity_id_of(&key_of(fact)), + at_least: *at_least, + }, + PreconditionRef::CanBroadcast { via } => BoundPrecondition::CanBroadcast { + via: audience_of(via), + }, + PreconditionRef::CanReach { subject, via } => BoundPrecondition::CanReach { + subject: subject_id_of(&key_of(subject)), + via: audience_of(via), + }, + PreconditionRef::Committed { to, kind } => BoundPrecondition::Committed { + to: subject_id_of(&key_of(to)), + kind: *kind, + }, + } + }; + let pressure_source_of = |source: &PressureSourceRef| -> PressureSource { + match source { + PressureSourceRef::Commitment { subject, key } => PressureSource::Commitment { + subject: subject_id_of(&key_of(subject)), + key: *key, + }, + PressureSourceRef::Dependency(target) => PressureSource::Dependency(target_of(target)), + PressureSourceRef::Subject(reference) => { + PressureSource::Subject(subject_id_of(&key_of(reference))) + } + } + }; let operations = patch .operations .iter() - .map(|operation| match operation { + .enumerate() + .map(|(position, operation)| match operation { + ComponentOp::CreateCommitment { + subject, + counterparty, + kind, + due, + period, + checks, + } => ResolvedOp::CreateCommitment { + subject: subject_id_of(&key_of(subject)), + key: CommitmentKey { + command: command_id, + index: position as u32, + }, + commitment: Commitment { + kind: *kind, + counterparty: counterparty + .as_ref() + .map(|reference| subject_id_of(&key_of(reference))), + due: *due, + period: *period, + checks: checks.iter().map(precondition_of).collect(), + }, + }, + ComponentOp::DischargeCommitment { subject, key } => ResolvedOp::DischargeCommitment { + subject: subject_id_of(&key_of(subject)), + key: *key, + }, + ComponentOp::AdvancePressure { source, target, by } => ResolvedOp::AdvancePressure { + source: pressure_source_of(source), + target: subject_id_of(&key_of(target)), + by: *by, + }, + ComponentOp::ReducePressure { source, target, by } => ResolvedOp::ReducePressure { + source: pressure_source_of(source), + target: subject_id_of(&key_of(target)), + by: *by, + }, + ComponentOp::ResolvePressure { source, target } => ResolvedOp::ResolvePressure { + source: pressure_source_of(source), + target: subject_id_of(&key_of(target)), + }, ComponentOp::Relocate { subject, via } => ResolvedOp::Relocate { subject_id: subject_id_of(&key_of(subject)), edge_id: edge_id_of(&key_of(via)), @@ -4267,9 +4916,114 @@ pub(super) fn resolve_patch( channels: declared_channels, operations, evidence: patch.evidence.clone(), + scale_intent: scale_intent.map(|intent| WorldScaleIntent { + targets: intent.targets.clone(), + jurisdictions: intent + .jurisdictions + .iter() + .map(|(handle, weight)| { + ( + *allocated_entities + .get(handle) + .expect("a jurisdiction root resolved above"), + *weight, + ) + }) + .collect(), + }), }) } +/// Whether every referent one stored check names resolves. The canonical +/// lowering runs after allocation, so a check that does not resolve here would +/// have nothing to lower to. +fn resolve_check( + site: Site, + check: &PreconditionRef, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> bool { + let entity = |kind: EntityKind, reference: &Ref, mismatches: &mut Vec| { + resolve_entity( + site.clone(), + kind, + reference, + index, + &state.entities, + mismatches, + ) + .is_some() + }; + let audience = |via: &AudienceRef, mismatches: &mut Vec| { + resolve_audience(site.clone(), via, index, state, mismatches).is_some() + }; + let subject = |reference: &Ref, mismatches: &mut Vec| { + resolve_subject(site.clone(), reference, index, &state.subjects, mismatches).is_some() + }; + match check { + PreconditionRef::Present { at } => entity(EntityKind::Place, at, mismatches), + PreconditionRef::Reachable { to, within } => { + let resolved = entity(EntityKind::Place, to, mismatches); + if !is_valid_cost(*within) { + mismatches.push(Mismatch::InvalidCost { site: site.clone() }); + return false; + } + resolved + } + PreconditionRef::Holds { resource, .. } => { + entity(EntityKind::Resource, resource, mismatches) + } + PreconditionRef::Authorized { over, kind } => { + let resolved = + resolve_authority_target(site.clone(), over, index, state, mismatches).is_some(); + if !is_civic_name(&kind.0) { + mismatches.push(Mismatch::InvalidCivicName { site: site.clone() }); + return false; + } + resolved + } + PreconditionRef::HasStanding { grievance } => { + if is_civic_name(&grievance.0) { + true + } else { + mismatches.push(Mismatch::InvalidCivicName { site: site.clone() }); + false + } + } + PreconditionRef::Knows { fact, .. } => entity(EntityKind::Fact, fact, mismatches), + PreconditionRef::CanBroadcast { via } => audience(via, mismatches), + PreconditionRef::CanReach { + subject: named, + via, + } => subject(named, mismatches) & audience(via, mismatches), + PreconditionRef::Committed { to, .. } => subject(to, mismatches), + } +} + +fn resolve_pressure_source( + site: Site, + source: &PressureSourceRef, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> Option { + match source { + PressureSourceRef::Commitment { subject, key } => { + resolve_subject(site, subject, index, &state.subjects, mismatches) + .map(|subject| PressureSourceKey::Commitment { subject, key: *key }) + } + PressureSourceRef::Dependency(target) => { + resolve_dependency_target(site, target, index, state, mismatches) + .map(PressureSourceKey::Dependency) + } + PressureSourceRef::Subject(reference) => { + resolve_subject(site, reference, index, &state.subjects, mismatches) + .map(PressureSourceKey::Subject) + } + } +} + /// Whether `place` is `root`, or reaches it through the candidate container /// chain. The walk is bounded by the graph size, so a cycle that does not /// include either end still terminates. @@ -5116,13 +5870,9 @@ mod tests { &auth_principal(owner()), ) .unwrap_err(); - assert!(matches!( - error, - KernelError::WrongPhase { - expected: WorldPhase::Draft, - actual: WorldPhase::Active, - } - )); + // Declaring in Active is elaboration, and elaboration answers a + // boundary. An unanswered one is refused before resolution. + assert!(matches!(error, KernelError::AnswerRequired)); } assert_eq!(kernel.journal.commit_count(), commits_before); assert_eq!(kernel.snapshot().unwrap(), active); @@ -5532,8 +6282,8 @@ mod tests { assert_ne!(admitted, genesis_player); let command_id = CommandId::new(); - let first = resolve_patch(&kernel.state, command_id, &patch).unwrap(); - let second = resolve_patch(&kernel.state, command_id, &patch).unwrap(); + let first = resolve_patch(&kernel.state, command_id, &patch, None).unwrap(); + let second = resolve_patch(&kernel.state, command_id, &patch, None).unwrap(); assert_eq!(first, second); } @@ -5676,9 +6426,10 @@ mod tests { Some(Ref::Draft(DraftHandle::new("rhythm-road"))), ), ]); - let resolved = resolve_patch(&kernel.state, CommandId::new(), &patch).unwrap(); + let resolved = resolve_patch(&kernel.state, CommandId::new(), &patch, None).unwrap(); let honest = super::super::WorldEffect::PatchAdmitted { resolved: resolved.clone(), + answers: None, }; // Forged: the position names a place no partition holds, and the effect @@ -5693,7 +6444,10 @@ mod tests { &mut candidate, CommandId::issue(), &CallerId::Principal(owner()), - &super::super::WorldEffect::PatchAdmitted { resolved: forged }, + &super::super::WorldEffect::PatchAdmitted { + answers: None, + resolved: forged, + }, ) .unwrap_err(); assert!(matches!(forged_error, KernelError::Invariant(_))); @@ -5728,18 +6482,19 @@ mod tests { assert!(matches!(unauthorized, KernelError::Invariant(_))); assert_eq!(candidate, kernel.state); - // And the Active phase is refused before any partition is touched. + // And an unanswered declaring effect is refused in Active before any + // partition is touched. let active = activate(&mut kernel); assert_eq!(active.revision, before.revision + 3); let mut candidate = kernel.state.clone(); - let wrong_phase = super::super::apply_effect( + let unanswered = super::super::apply_effect( &mut candidate, CommandId::issue(), &CallerId::Principal(owner()), &honest, ) .unwrap_err(); - assert!(matches!(wrong_phase, KernelError::Invariant(_))); + assert!(matches!(unanswered, KernelError::AnswerRequired)); assert_eq!(candidate, kernel.state); } @@ -5885,7 +6640,9 @@ mod tests { edge_id, }], evidence: Vec::new(), + scale_intent: None, }, + answers: None, }; let mut candidate = kernel.state.clone(); let error = super::super::apply_effect(