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 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-04 23:53:58 +02:00
commit d7fba90c71
9 changed files with 2305 additions and 173 deletions

View file

@ -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}),
&[],

View file

@ -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<PathBuf>) -> 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<AppState>) -> impl IntoResponse {
let mut revisions = state.revisions.subscribe();
let stream = async_stream::stream! {

View file

@ -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<RefKind> {
}
/// 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<ActionMismatch>,
) {
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<Role, Target>,
) -> Option<BoundPrecondition> {
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<ActionMismatch> {
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<AuthorityGrant>,
index: usize,
check: &BoundPrecondition,
) -> Option<ActionMismatch> {
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<Role, Target>,
) -> Result<Vec<patch::ComponentOp>, 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)?,

View file

@ -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> {
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<Self> {
(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<RoutineFulfilled>,
/// Pressure rows written, in `(target, source)` order, with the resulting
/// magnitude — not the delta.
pub(crate) pressed: Vec<PressureWritten>,
}
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<FictionalMinutes> {
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),
}
}

View file

@ -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<Value> {
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<Value> {
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,
)

View file

@ -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<super::SubjectId, BTreeMap<super::CommitmentKey, super::Commitment>>,
) -> 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::<u64>()
> 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();

View file

@ -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<SubmitReceipt, MailboxError> {
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,
)

File diff suppressed because it is too large Load diff

View file

@ -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<SubjectId>,
/// 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<TickMinutes>,
/// What must hold for a `Routine` to auto-fulfil. Role-free canonical
/// checks. Empty for `Obligation` and `Goal`.
pub(crate) checks: Vec<BoundPrecondition>,
}
/// 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<SubjectId>,
key: CommitmentKey,
},
Dependency(DependencyRef),
Subject(Ref<SubjectId>),
}
/// 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<EntityId>,
},
Reachable {
to: Ref<EntityId>,
within: Cost,
},
Holds {
resource: Ref<EntityId>,
at_least: Quantity,
},
Authorized {
over: AuthorityTargetRef,
kind: AuthorityKindName,
},
HasStanding {
grievance: GrievanceKindName,
},
Knows {
fact: Ref<EntityId>,
at_least: Confidence,
},
CanBroadcast {
via: AudienceRef,
},
CanReach {
subject: Ref<SubjectId>,
via: AudienceRef,
},
Committed {
to: Ref<SubjectId>,
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<SubjectKind, u32>,
/// Jurisdiction roots and their share, in permille. Weights distribute the
/// target and never raise it: the sum is checked `<= 1000`.
pub(crate) jurisdictions: BTreeMap<EntityId, u32>,
}
/// 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<SubjectKind, u32>,
pub(crate) jurisdictions: BTreeMap<DraftHandle, u32>,
}
/// 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<TickMinutes>,
},
/// 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<EntityId>,
controller: Option<Ref<SubjectId>>,
},
/// 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<SubjectId>,
counterparty: Option<Ref<SubjectId>>,
kind: CommitmentKind,
due: FictionalMinutes,
period: Option<TickMinutes>,
checks: Vec<PreconditionRef>,
},
/// 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<SubjectId>,
key: CommitmentKey,
},
/// Insert-or-add, saturating. With absence meaning zero, creation and
/// advance are the same write.
AdvancePressure {
source: PressureSourceRef,
target: Ref<SubjectId>,
by: PressureMagnitude,
},
/// Saturating subtract; removal at zero.
ReducePressure {
source: PressureSourceRef,
target: Ref<SubjectId>,
by: PressureMagnitude,
},
ResolvePressure {
source: PressureSourceRef,
target: Ref<SubjectId>,
},
}
/// Empty on purpose: an `Option<PatchAnswer>` 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<ResolvedChannel>,
pub(super) operations: Vec<ResolvedOp>,
pub(super) evidence: Vec<EvidenceRef>,
/// `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<WorldScaleIntent>,
}
impl ResolvedPatch {
@ -1449,6 +1772,17 @@ enum TargetKey {
Subject(Key<SubjectId>),
}
/// [`PressureSource`] over candidate keys.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum PressureSourceKey {
Commitment {
subject: Key<SubjectId>,
key: CommitmentKey,
},
Dependency(TargetKey),
Subject(Key<SubjectId>),
}
/// [`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<ResolvedPatch, Vec<Mismatch>> {
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<SubjectId>, 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<SubjectId>, 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<Key<EntityId>, LedgerDelta> = BTreeMap::new();
let mut declared_places: Vec<(DraftHandle, Key<EntityId>)> = 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::<u64>()
> 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<DraftHandle, RefKind>,
state: &super::WorldState,
mismatches: &mut Vec<Mismatch>,
) -> bool {
let entity = |kind: EntityKind, reference: &Ref<EntityId>, mismatches: &mut Vec<Mismatch>| {
resolve_entity(
site.clone(),
kind,
reference,
index,
&state.entities,
mismatches,
)
.is_some()
};
let audience = |via: &AudienceRef, mismatches: &mut Vec<Mismatch>| {
resolve_audience(site.clone(), via, index, state, mismatches).is_some()
};
let subject = |reference: &Ref<SubjectId>, mismatches: &mut Vec<Mismatch>| {
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<DraftHandle, RefKind>,
state: &super::WorldState,
mismatches: &mut Vec<Mismatch>,
) -> Option<PressureSourceKey> {
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(