Widen the patch author to a confined external consumer

Cut first: the elaboration lane's two draft caps and its own sha256-to-uuid
command-id spelling, `jurisdiction_covers` and `confine_to_jurisdiction` as
jurisdiction-only names and signatures, the flat empty-affordance invariant,
and the two total controller accessors that were keeping a fictional
controller so a reader could stay infallible.

Then widen. `PatchGround` names what a confined author may write: a place
subtree, or every subject bound to one consumer, derived from
`controller_assignments` at decision time and never carried on the wire.
`SystemCapability::Consumer` is admitted for `AdmitPatch` and nothing else, in
the same closed pairing `reduce` decides and `apply_effect` re-decides.
`ControllerAssignment::ExternallyControlled` is a subject the world can see,
relate to, and reason about but never puppet: no controller id, no mode, no
affordance, no opportunity, no adjacency, and a forged history in which it
acted fails replay.

`patch::decode_patch` is the one decode owner for a `WorldPatch` from a byte
source, with one byte cap applied to the frame before `rmp_serde` sees it and
three item caps checked before `resolve_patch`; the elaboration lane reads the
same two item constants it used to own privately.

`world/consumer.rs` owns the ingress and no world truth: one typed document
over one loopback route, canonical MessagePack in and out, a registry that
holds only SHA-256 digests, one derived command key, one port method, one
atomic verdict. The state and commit schemas bump with the caller tag; prior
stores are refused.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-05 03:19:00 +02:00
commit e0c6f9cb22
10 changed files with 962 additions and 126 deletions

View file

@ -44,7 +44,7 @@ pub const IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT: &str = "GAMECULT_IDUNN_CANDI
pub const IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT: &str = "GAMECULT_IDUNN_PROCESS_WRITE_LEASE";
pub(crate) const TARGET: &str = "ghostlight";
const STATE_SCHEMA_GENERATION: &str = "world-v2";
const STATE_SCHEMA_GENERATION: &str = "world-v3";
const STATE_CONTRACT_SHA256: &str =
"sha256-bf6ec06d885a59ddb237c6224d0abb4ccceac8c7ba23761d1326d7f562a4c21e";
const CULTNET_RUDP_PROTOCOL_ID: &str = "cultnet.transport.rudp.v0";
@ -173,7 +173,7 @@ impl RuntimePresencePublisher {
expected.state_schema_generation.as_deref() == Some(STATE_SCHEMA_GENERATION)
&& expected.state_contract_sha256.as_deref() == Some(STATE_CONTRACT_SHA256)
&& expected.write_lease_required,
"Expected does not name Ghostlight's writable world-v2 state"
"Expected does not name Ghostlight's writable world-v3 state"
);
ensure!(
activation.expected_projection_sha256 == expected.canonical_sha256()?
@ -1390,7 +1390,7 @@ pub(crate) mod tests {
assert!(
error
.to_string()
.contains("does not name Ghostlight's writable world-v2 state")
.contains("does not name Ghostlight's writable world-v3 state")
);
}

View file

@ -5,7 +5,7 @@
use crate::{
eve,
world::{STATE_SCHEMA, WorldSnapshot},
world::{CONSUMER_PATCH_SCHEMA, CONSUMER_RECEIPT_SCHEMA, STATE_SCHEMA, WorldSnapshot},
};
use anyhow::Result;
use chrono::{DateTime, Utc};
@ -241,7 +241,9 @@ pub(crate) fn provider_advertisement(identity: &MeshRuntimeIdentity, updated_at:
"gamecult.eve.command_invocation.v1",
COMMAND_RESULT_SCHEMA,
"heimdall.access_gate_state.v1",
STATE_SCHEMA
STATE_SCHEMA,
CONSUMER_PATCH_SCHEMA,
CONSUMER_RECEIPT_SCHEMA
],
"witnesses":[{
"kind":"source-commit",

View file

@ -10,12 +10,12 @@ use crate::{
},
mesh::{self, MeshPublisher, MeshRuntimeIdentity},
world::{
AffordanceId, CellRun, CommandBody, CommandId, ControllerError, ControllerModels,
ControllerPendingReason, ControllerRunner, ControllerWorkCustody, Cover, CoverBudget,
CreateWorldIntent, DecisionInvocation, DecisionOpportunity, KernelError, MailboxError,
NarrativeRun, OperationalRun, PrincipalCommandIntent, PrincipalId, Statement,
SubmissionDisposition, SubmitReceipt, TickMinutes, WorldMailbox, WorldSnapshot,
derive_cover,
AffordanceId, CONSUMER_BODY_LIMIT, CellRun, CommandBody, CommandId, ConsumerPort,
ConsumerRegistry, ControllerError, ControllerModels, ControllerPendingReason,
ControllerRunner, ControllerWorkCustody, Cover, CoverBudget, CreateWorldIntent,
DecisionInvocation, DecisionOpportunity, KernelError, MailboxError, NarrativeRun,
OperationalRun, PrincipalCommandIntent, PrincipalId, Statement, SubmissionDisposition,
SubmitReceipt, TickMinutes, WorldMailbox, WorldSnapshot, derive_cover,
},
};
use anyhow::{Context, bail, ensure};
@ -64,6 +64,11 @@ struct RuntimeHealthOwner {
#[derive(Clone)]
struct AppState {
world: WorldMailbox,
/// The consumer ingress's narrow view of the same owner, and the configured
/// consumers it authenticates against. The registry is read once at startup
/// and holds only digests; a missing file means no consumers.
consumer: ConsumerPort,
consumers: Arc<ConsumerRegistry>,
/// The one cognition organ, shared. Concurrency is owned by
/// `controller_permits` and quarantine by `controller_quarantined`: an
/// exclusive lock here would be a second owner of both, and a tick spends a
@ -275,7 +280,10 @@ pub(crate) async fn run(state_root_binding: Option<PathBuf>) -> anyhow::Result<(
require_no_runtime_custody_failure(&mut fatal_events)?;
let (revisions, _) = broadcast::channel(32);
let cover_budget = configured_cover_budget()?;
let consumers = Arc::new(open_consumer_registry());
let mut state = AppState {
consumer: ConsumerPort::new(world.clone()),
consumers,
world,
controllers: controllers.map(Arc::new),
controller_permits: Arc::new(Semaphore::new(configured_controller_concurrency())),
@ -404,6 +412,10 @@ fn api_router(state: AppState) -> Router {
"/cultnet/snapshot",
post(cultnet_snapshot).layer(DefaultBodyLimit::max(CULTNET_SNAPSHOT_BODY_LIMIT)),
)
.route(
"/cultnet/world-patch",
post(cultnet_world_patch).layer(DefaultBodyLimit::max(CONSUMER_BODY_LIMIT)),
)
.route("/api/eve/provider", get(eve_provider))
.route("/api/eve/surfaces/{surface_id}", get(eve_surface))
.route("/api/eve/commands", post(eve_command))
@ -411,6 +423,51 @@ fn api_router(state: AppState) -> Router {
.with_state(state)
}
/// The consumer ingress's door. Loopback and content type are the two gates
/// `/cultnet/snapshot` already established; everything past them belongs to
/// `world::consumer`, which owns decode, bounds, authentication, and the one
/// receipt. This handler holds no opinion about a patch.
async fn cultnet_world_patch(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<AppState>,
headers: HeaderMap,
body: Bytes,
) -> Response {
if !peer.ip().is_loopback() {
return StatusCode::FORBIDDEN.into_response();
}
if headers.get(header::CONTENT_TYPE) != Some(&HeaderValue::from_static("application/msgpack")) {
return StatusCode::UNSUPPORTED_MEDIA_TYPE.into_response();
}
let receipt = crate::world::admit_document(&state.consumer, &state.consumers, &body).await;
match crate::world::encode_receipt(&receipt) {
Ok(bytes) => (
StatusCode::OK,
[(header::CONTENT_TYPE, "application/msgpack")],
bytes,
)
.into_response(),
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
}
}
/// Read once at startup. A missing or unset path means no configured
/// consumers, which is the fail-closed default; a malformed file is fatal to
/// the registry rather than silently empty, so a mistyped credential cannot
/// read as "no consumers configured".
fn open_consumer_registry() -> ConsumerRegistry {
let Ok(path) = std::env::var(crate::world::CONSUMER_CREDENTIALS_ENVIRONMENT) else {
return ConsumerRegistry::empty();
};
match ConsumerRegistry::from_secret_file(&path) {
Ok(registry) => registry,
Err(error) => {
tracing::warn!(%error, "consumer credentials are unreadable; no consumer is configured");
ConsumerRegistry::empty()
}
}
}
async fn cultnet_snapshot(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<AppState>,
@ -2247,6 +2304,8 @@ mod tests {
let (revisions, _) = broadcast::channel(8);
let (fatal, _fatal_events) = mpsc::unbounded_channel();
let state = AppState {
consumer: ConsumerPort::new(world.clone()),
consumers: Arc::new(ConsumerRegistry::empty()),
world,
controllers: Some(Arc::new(controllers)),
controller_permits: Arc::new(Semaphore::new(TEST_CONTROLLER_CONCURRENCY)),

View file

@ -0,0 +1,427 @@
//! The consumer ingress: the world's third patch author.
//!
//! This module owns exactly four things — decoding a document, bounding it,
//! authenticating the consumer that sent it, and projecting one receipt. It
//! owns no world truth, holds no opinion about a patch's content, and does not
//! pre-validate: a second reducer here could disagree with the kernel's, so
//! structure is decided once, by `resolve_patch`, behind the same
//! `require_patch_author`, `confine_to_ground`, and idempotency ledger every
//! other author passes through.
use super::mailbox::{ConsumerPort, MailboxError};
use super::patch::{self, PatchDecodeError};
use super::{
CommandId, ConsumerId, KernelError, Mismatch, PatchAnswer, SubmitReceipt, WorldId, WorldPatch,
};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use std::path::Path;
/// The inbound document and the outbound receipt. Ghostlight-owned typed
/// records in canonical MessagePack, not CultNet control messages.
pub(crate) const CONSUMER_PATCH_SCHEMA: &str = "ghostlight.consumer_patch.v0";
pub(crate) const CONSUMER_RECEIPT_SCHEMA: &str = "ghostlight.consumer_receipt.v0";
/// The one namespace a consumer's command key is derived under.
const CONSUMER_COMMAND_NAMESPACE: &str = "ghostlight.consumer.command.v0";
/// The envelope's own fields, generously bounded. The patch bound is
/// `patch::MAX_PATCH_BYTES` and stays there; this is derived from it so the
/// transport guard cannot become a second opinion about how big a patch may be.
const CONSUMER_ENVELOPE_SLACK: usize = 8 * 1024;
pub(crate) const CONSUMER_BODY_LIMIT: usize = patch::MAX_PATCH_BYTES + CONSUMER_ENVELOPE_SLACK;
/// The environment variable naming the credentials file.
pub(crate) const CONSUMER_CREDENTIALS_ENVIRONMENT: &str = "GHOSTLIGHT_CONSUMER_CREDENTIALS";
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub(crate) struct ConsumerPatchDocument {
/// Pinned to `CONSUMER_PATCH_SCHEMA`; any other value is refused before the
/// body is read.
pub(crate) schema: String,
pub(crate) world_id: WorldId,
/// The consumer's configured name. Lowered to a `ConsumerId` by the
/// registry and never carried further; the kernel never sees it.
pub(crate) consumer: String,
/// Presented secret. Compared against the registry's stored SHA-256 and
/// dropped. Never logged, never journaled, never echoed.
pub(crate) secret: String,
/// The consumer's own retry key. With the world and the consumer, this is
/// the whole command-id derivation.
pub(crate) idempotency_key: String,
/// The Ghostlight revision this document was built against.
pub(crate) expected_revision: u64,
/// Absent for the ordinary component-only batch; present only when the
/// document declares in Active.
pub(crate) answers: Option<PatchAnswer>,
/// Canonical-MessagePack `WorldPatch` frame, decoded by `decode_patch`.
/// A nested frame rather than an inline value, so `MAX_PATCH_BYTES` is
/// checked against the patch itself before any of its items deserializes.
#[serde(with = "serde_bytes")]
pub(crate) patch: Vec<u8>,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub(crate) struct ConsumerReceiptDocument {
pub(crate) schema: String,
pub(crate) world_id: Option<WorldId>,
/// Absent when the document did not decode far enough to derive one. The
/// derivation reads the world, the consumer, and the idempotency key, so a
/// frame that fails before authentication has no command key to name.
pub(crate) command_id: Option<CommandId>,
/// The live revision whenever the kernel was reached, applied or not.
pub(crate) revision: Option<u64>,
pub(crate) outcome: ConsumerOutcome,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "outcome", rename_all = "snake_case")]
pub(crate) enum ConsumerOutcome {
Applied {
state_digest: String,
commit_digest: String,
},
AlreadyApplied {
state_digest: String,
commit_digest: String,
},
/// One verdict for one document. `mismatches` is the resolver's complete
/// set when the refusal is structural, and empty otherwise. A consumer
/// wanting per-item results splits documents.
Refused {
gate: ConsumerRefusal,
mismatches: Vec<Mismatch>,
},
/// The owner task is restarting. The same bytes may be sent again.
Unavailable,
/// The reply channel dropped. Resubmit the same bytes: the derived command
/// id and the ledger make the resubmission the probe.
Unknown,
}
/// A wire projection of `KernelError` and `PatchDecodeError`. It decides
/// nothing, and its mapping is exhaustive so a new kernel error cannot silently
/// become `Internal`.
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub(crate) enum ConsumerRefusal {
Schema,
TooLarge,
NotCanonical,
Malformed,
Unauthenticated,
Unauthorized,
WorldMismatch,
StaleRevision,
CommandIdConflict,
Structural,
AnswerRequired,
AnswerNotDerived,
AnswerNotSatisfied,
Internal,
}
/// Configured consumers, keyed by name, valued by the SHA-256 of that
/// consumer's shared secret. The plaintext never enters the process image.
///
/// A missing file means no consumers and every document is `Unauthenticated`.
/// That is the fail-closed default, and it is why this door can exist before an
/// operator has configured anything.
#[derive(Clone, Debug, Default)]
pub(crate) struct ConsumerRegistry {
entries: BTreeMap<String, [u8; 32]>,
}
impl ConsumerRegistry {
pub(crate) fn empty() -> Self {
Self::default()
}
/// One `name = <64 hex digits>` line per consumer, blank lines and `#`
/// comments ignored. A file that does not exist yields no consumers; a file
/// that exists and is malformed is an error, because a mistyped credential
/// file must not read as an empty one.
pub(crate) fn from_secret_file(path: impl AsRef<Path>) -> Result<Self, String> {
let path = path.as_ref();
if !path.exists() {
return Ok(Self::empty());
}
let text = std::fs::read_to_string(path).map_err(|error| error.to_string())?;
let mut entries = BTreeMap::new();
for (number, line) in text.lines().enumerate() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let Some((name, digest)) = line.split_once('=') else {
return Err(format!(
"consumer credential line {} has no `=`",
number + 1
));
};
let name = name.trim();
let digest = decode_digest(digest.trim()).ok_or_else(|| {
format!(
"consumer credential line {} is not a sha256 hex digest",
number + 1
)
})?;
if name.is_empty() || entries.insert(name.to_owned(), digest).is_some() {
return Err(format!(
"consumer credential line {} names an empty or duplicate consumer",
number + 1
));
}
}
Ok(Self { entries })
}
#[cfg(test)]
pub(crate) fn with_secret(name: &str, secret: &str) -> Self {
Self {
entries: BTreeMap::from([(name.to_owned(), Sha256::digest(secret.as_bytes()).into())]),
}
}
/// The presented secret is hashed and compared in constant time, then
/// dropped. A name that is not configured takes the same comparison against
/// a zero digest, so a miss and a wrong secret are one answer.
fn authenticate(&self, name: &str, secret: &str) -> Option<ConsumerId> {
let presented: [u8; 32] = Sha256::digest(secret.as_bytes()).into();
let stored = self.entries.get(name).copied().unwrap_or([0u8; 32]);
let mut difference = 0u8;
for (left, right) in presented.iter().zip(stored.iter()) {
difference |= left ^ right;
}
if difference == 0 && self.entries.contains_key(name) {
Some(ConsumerId::of_name(name))
} else {
None
}
}
}
fn decode_digest(text: &str) -> Option<[u8; 32]> {
if text.len() != 64 {
return None;
}
let mut digest = [0u8; 32];
for (index, byte) in digest.iter_mut().enumerate() {
*byte = u8::from_str_radix(text.get(index * 2..index * 2 + 2)?, 16).ok()?;
}
Some(digest)
}
/// Decode, bound, authenticate, submit, project. One atomic verdict per
/// document: there is no partial acceptance, because there is one command.
pub(crate) async fn admit_document(
port: &ConsumerPort,
registry: &ConsumerRegistry,
bytes: &[u8],
) -> ConsumerReceiptDocument {
let document = match decode_document(bytes) {
Ok(document) => document,
Err(gate) => return refused(None, None, None, gate),
};
if document.schema != CONSUMER_PATCH_SCHEMA {
return refused(None, None, None, ConsumerRefusal::Schema);
}
let world_id = Some(document.world_id);
let Some(consumer) = registry.authenticate(&document.consumer, &document.secret) else {
return refused(world_id, None, None, ConsumerRefusal::Unauthenticated);
};
let command_id = CommandId::derived(
CONSUMER_COMMAND_NAMESPACE,
&[
&document.world_id.text(),
&consumer.text(),
&document.idempotency_key,
],
);
let patch = match patch::decode_patch(&document.patch) {
Ok(patch) => patch,
Err(error) => {
return refused(world_id, Some(command_id), None, decode_refusal(error));
}
};
let outcome = port
.submit_consumer(
document.world_id,
document.expected_revision,
command_id,
consumer,
document.answers.clone(),
patch,
)
.await;
project(world_id, command_id, outcome)
}
/// The outer frame's own decode: bounded, canonical, and tiny. It runs before
/// the nested patch frame is looked at, and the nested frame carries its own
/// bound.
fn decode_document(bytes: &[u8]) -> Result<ConsumerPatchDocument, ConsumerRefusal> {
if bytes.len() > CONSUMER_BODY_LIMIT {
return Err(ConsumerRefusal::TooLarge);
}
let document: ConsumerPatchDocument =
rmp_serde::from_slice(bytes).map_err(|_| ConsumerRefusal::Malformed)?;
if rmp_serde::to_vec_named(&document).map_err(|_| ConsumerRefusal::Malformed)? != bytes {
return Err(ConsumerRefusal::NotCanonical);
}
Ok(document)
}
fn decode_refusal(error: PatchDecodeError) -> ConsumerRefusal {
match error {
PatchDecodeError::TooLarge { .. }
| PatchDecodeError::TooManyDeclarations { .. }
| PatchDecodeError::TooManyOperations { .. }
| PatchDecodeError::TooManyEvidence { .. } => ConsumerRefusal::TooLarge,
PatchDecodeError::NotCanonical => ConsumerRefusal::NotCanonical,
PatchDecodeError::Malformed => ConsumerRefusal::Malformed,
}
}
fn project(
world_id: Option<WorldId>,
command_id: CommandId,
outcome: Result<SubmitReceipt, MailboxError>,
) -> ConsumerReceiptDocument {
let (revision, outcome) = match outcome {
Ok(SubmitReceipt::Applied(receipt)) => (
Some(receipt.resulting_revision),
ConsumerOutcome::Applied {
state_digest: receipt.resulting_state_digest,
commit_digest: receipt.commit_digest,
},
),
Ok(SubmitReceipt::AlreadyApplied(receipt)) => (
Some(receipt.resulting_revision),
ConsumerOutcome::AlreadyApplied {
state_digest: receipt.resulting_state_digest,
commit_digest: receipt.commit_digest,
},
),
Err(MailboxError::Unavailable) => (None, ConsumerOutcome::Unavailable),
Err(MailboxError::OutcomeUnknown { .. }) => (None, ConsumerOutcome::Unknown),
Err(MailboxError::Kernel(error)) => {
let revision = match &error {
KernelError::RevisionMismatch { actual, .. } => Some(*actual),
_ => None,
};
let mismatches = match &error {
KernelError::PatchRejected(set) => set.clone(),
_ => Vec::new(),
};
(
revision,
ConsumerOutcome::Refused {
gate: kernel_refusal(&error),
mismatches,
},
)
}
};
ConsumerReceiptDocument {
schema: CONSUMER_RECEIPT_SCHEMA.into(),
world_id,
command_id: Some(command_id),
revision,
outcome,
}
}
/// Exhaustive by construction: a new `KernelError` variant fails to compile
/// here rather than becoming `Internal` by default.
fn kernel_refusal(error: &KernelError) -> ConsumerRefusal {
match error {
KernelError::PatchRejected(_) => ConsumerRefusal::Structural,
KernelError::WorldMismatch | KernelError::OpenedWorldMismatch => {
ConsumerRefusal::WorldMismatch
}
KernelError::Unauthorized
| KernelError::AuthenticationMismatch
| KernelError::ControllerMismatch
| KernelError::NotDraftApprover => ConsumerRefusal::Unauthorized,
KernelError::RevisionMismatch { .. } => ConsumerRefusal::StaleRevision,
KernelError::CommandIdConflict | KernelError::CreationConflict => {
ConsumerRefusal::CommandIdConflict
}
KernelError::AnswerRequired => ConsumerRefusal::AnswerRequired,
KernelError::AnswerNotDerived => ConsumerRefusal::AnswerNotDerived,
KernelError::AnswerNotSatisfied => ConsumerRefusal::AnswerNotSatisfied,
KernelError::InvalidCommandId
| KernelError::EmptyTitle
| KernelError::EmptyPrincipal
| KernelError::ActionRejected(_)
| KernelError::WrongPhase { .. }
| KernelError::DraftAlreadyApproved
| KernelError::MissingApprovals(_)
| KernelError::OpportunityMismatch
| KernelError::ScopeChanged { .. }
| KernelError::AffordanceDenied
| KernelError::CreationTargetOccupied
| KernelError::WorldNotCreated
| KernelError::RecoveryRequired { .. }
| KernelError::OwnershipLost
| KernelError::Serialization(_)
| KernelError::Store(_)
| KernelError::CorruptJournal(_)
| KernelError::Invariant(_) => ConsumerRefusal::Internal,
}
}
fn refused(
world_id: Option<WorldId>,
command_id: Option<CommandId>,
revision: Option<u64>,
gate: ConsumerRefusal,
) -> ConsumerReceiptDocument {
ConsumerReceiptDocument {
schema: CONSUMER_RECEIPT_SCHEMA.into(),
world_id,
command_id,
revision,
outcome: ConsumerOutcome::Refused {
gate,
mismatches: Vec::new(),
},
}
}
/// The canonical encoding of one document, for the ingress's callers and for
/// the tests that build one.
#[cfg(test)]
pub(crate) fn encode_document(document: &ConsumerPatchDocument) -> Result<Vec<u8>, String> {
rmp_serde::to_vec_named(document).map_err(|error| error.to_string())
}
pub(crate) fn encode_receipt(receipt: &ConsumerReceiptDocument) -> Result<Vec<u8>, String> {
rmp_serde::to_vec_named(receipt).map_err(|error| error.to_string())
}
#[cfg(test)]
pub(crate) fn build_document(
world_id: WorldId,
consumer: &str,
secret: &str,
idempotency_key: &str,
expected_revision: u64,
answers: Option<PatchAnswer>,
patch: &WorldPatch,
) -> Result<ConsumerPatchDocument, String> {
Ok(ConsumerPatchDocument {
schema: CONSUMER_PATCH_SCHEMA.into(),
world_id,
consumer: consumer.into(),
secret: secret.into(),
idempotency_key: idempotency_key.into(),
expected_revision,
answers,
patch: rmp_serde::to_vec_named(patch).map_err(|error| error.to_string())?,
})
}

View file

@ -1001,10 +1001,12 @@ fn select_one(
else {
return Err(ControllerError::NoOpportunity { expected });
};
if subject.controller_mode != expected {
// Fail closed on a subject with no controller: a mirror has neither a mode
// nor a controller id, so neither comparison can accidentally hold.
if subject.controller_mode != Some(expected) {
return Err(ControllerError::NoOpportunity { expected });
}
if exact_opportunity.controller_id != subject.controller_id {
if Some(exact_opportunity.controller_id) != subject.controller_id {
return Err(ControllerError::OpportunityMismatch);
}
let matches = snapshot
@ -5111,8 +5113,8 @@ mod tests {
id: actor_id,
label: "Mara at the rain gate".into(),
kind: SubjectKind::Person,
controller_id: actor_controller,
controller_mode: ControllerMode::NarrativePersona,
controller_id: Some(actor_controller),
controller_mode: Some(ControllerMode::NarrativePersona),
human_controller: None,
affordances: BTreeSet::from([speak_affordance]),
position: None,
@ -5142,8 +5144,8 @@ mod tests {
id: speaker_id,
label: "Iris in the tollhouse".into(),
kind: SubjectKind::Person,
controller_id: speaker_controller,
controller_mode: ControllerMode::OperationalAgent,
controller_id: Some(speaker_controller),
controller_mode: Some(ControllerMode::OperationalAgent),
human_controller: None,
affordances: BTreeSet::new(),
position: None,
@ -5361,8 +5363,8 @@ mod tests {
id: actor_id,
label: "The Walker".into(),
kind: SubjectKind::Person,
controller_id: actor_controller,
controller_mode: ControllerMode::OperationalAgent,
controller_id: Some(actor_controller),
controller_mode: Some(ControllerMode::OperationalAgent),
human_controller: None,
affordances: BTreeSet::from([speak_affordance]),
position: Some(yard),
@ -5382,8 +5384,8 @@ mod tests {
id: other_id,
label: "The Vault Keeper".into(),
kind: SubjectKind::Person,
controller_id: other_controller,
controller_mode: ControllerMode::OperationalAgent,
controller_id: Some(other_controller),
controller_mode: Some(ControllerMode::OperationalAgent),
human_controller: None,
affordances: BTreeSet::new(),
position: Some(vault),
@ -6670,7 +6672,7 @@ mod tests {
let human_opportunity = snapshot
.opportunities
.iter()
.find(|opportunity| opportunity.controller_id == human_subject.controller_id)
.find(|opportunity| Some(opportunity.controller_id) == human_subject.controller_id)
.cloned()
.unwrap();
let human_speak = *snapshot
@ -6724,13 +6726,13 @@ mod tests {
let narrative_subject = snapshot
.subjects
.iter()
.find(|subject| subject.controller_mode == ControllerMode::NarrativePersona)
.find(|subject| subject.controller_mode == Some(ControllerMode::NarrativePersona))
.cloned()
.unwrap();
let narrative_opportunity = snapshot
.opportunities
.iter()
.find(|opportunity| opportunity.controller_id == narrative_subject.controller_id)
.find(|opportunity| Some(opportunity.controller_id) == narrative_subject.controller_id)
.cloned()
.unwrap();
let narrative_command = CommandId::new();
@ -6831,13 +6833,15 @@ mod tests {
let operational_subject = snapshot
.subjects
.iter()
.find(|subject| subject.controller_mode == ControllerMode::OperationalAgent)
.find(|subject| subject.controller_mode == Some(ControllerMode::OperationalAgent))
.cloned()
.unwrap();
let operational_opportunity = snapshot
.opportunities
.iter()
.find(|opportunity| opportunity.controller_id == operational_subject.controller_id)
.find(|opportunity| {
Some(opportunity.controller_id) == operational_subject.controller_id
})
.cloned()
.unwrap();
let operational_command = CommandId::new();

View file

@ -18,7 +18,7 @@ use super::controllers::{
};
#[cfg(test)]
use super::patch::RECORD_GAP_PATCH_TOOL;
use super::patch::{ComponentOp, FactStandingRef};
use super::patch::{self, ComponentOp, FactStandingRef};
use super::patch::{
PATCH_TOOLS, PatchToolShape, SUBMIT_PATCH_TOOL, patch_tool_signatures, patch_tools,
};
@ -35,6 +35,7 @@ use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use thiserror::Error;
#[cfg(test)]
use uuid::Uuid;
/// The elaborator wants many tool calls inside one round and several rounds for
@ -42,12 +43,6 @@ use uuid::Uuid;
/// `TOOL_STEP_BUDGET` is left alone for the lane it belongs to.
const ELABORATION_ROUND_BUDGET: usize = 6;
/// The author owns the size of what it authors. The kernel gets no cap:
/// `resolve_patch` is total, and a cap there would be a second authority over
/// what a patch may be.
const MAX_DRAFT_DECLARATIONS: usize = 64;
const MAX_DRAFT_OPERATIONS: usize = 128;
const ELABORATION_NAMESPACE: &str = "ghostlight.command.elaboration.v1";
const ELABORATION_INSTRUCTIONS: &str = "Use only the supplied tools to author structure inside your jurisdiction. Answer the boundary or deficit you were given, then submit. Recording a gap changes nothing.";
@ -924,7 +919,7 @@ fn apply_tool_call(
}
},
PatchToolShape::Declare { variant, fixed } => {
if draft.declarations.len() >= MAX_DRAFT_DECLARATIONS {
if draft.declarations.len() >= patch::MAX_PATCH_DECLARATIONS {
gaps.push(tool_decode_need(
name,
arguments,
@ -954,7 +949,7 @@ fn apply_tool_call(
}
}
PatchToolShape::Operate { variant } => {
if draft.operations.len() >= MAX_DRAFT_OPERATIONS {
if draft.operations.len() >= patch::MAX_PATCH_OPERATIONS {
gaps.push(tool_decode_need(
name,
arguments,
@ -1029,24 +1024,15 @@ pub(super) fn elaboration_request(
/// A session's identity is derived from the world, the jurisdiction, and the
/// answer's digest, so a crashed loop resumes the same store row and the
/// mailbox's idempotency probe sees the same command. No `uuid/v5`: the digest
/// is sha256 and its first sixteen bytes become the id.
/// mailbox's idempotency probe sees the same command. The derivation itself is
/// `CommandId::derived`, which is the one recipe every derived command key
/// uses.
fn session_command_id(session: &ElaboratorSession) -> Result<CommandId, ControllerError> {
let mut hasher = Sha256::new();
hasher.update(ELABORATION_NAMESPACE.as_bytes());
hasher.update(
rmp_serde::to_vec_named(&(
session.world_id,
session.jurisdiction,
&session.answer_digest,
))
.map_err(|error| ControllerError::Serialization(error.to_string()))?,
);
let bytes: [u8; 16] = hasher.finalize()[..16]
.try_into()
.expect("sha256 yields at least sixteen bytes");
CommandId::parse_uuid(&Uuid::from_bytes(bytes).to_string())
.map_err(|error| ControllerError::Serialization(error.to_string()))
let scope = digest_of(&(session.world_id, session.jurisdiction))?;
Ok(CommandId::derived(
ELABORATION_NAMESPACE,
&[&scope, session.answer_digest.text()],
))
}
fn digest_of<T: Serialize>(value: &T) -> Result<String, ControllerError> {
@ -1128,7 +1114,7 @@ mod tests {
/// The author owns the size of what it authors. The kernel gets no cap.
#[test]
fn a_draft_past_the_size_cap_becomes_a_gap() {
let mut calls: Vec<(&str, Value)> = (0..=MAX_DRAFT_DECLARATIONS)
let mut calls: Vec<(&str, Value)> = (0..=patch::MAX_PATCH_DECLARATIONS)
.map(|index| {
(
"declare_place",
@ -1142,7 +1128,10 @@ mod tests {
.collect();
calls.push((SUBMIT_PATCH_TOOL, serde_json::json!({})));
let capture = capture(&vec![output(calls)]);
assert_eq!(capture.draft.declarations.len(), MAX_DRAFT_DECLARATIONS);
assert_eq!(
capture.draft.declarations.len(),
patch::MAX_PATCH_DECLARATIONS
);
assert!(
capture.gaps.iter().any(|gap| gap.detail.contains("cap")),
"the call past the cap was not recorded as a gap"

View file

@ -811,7 +811,10 @@ fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> {
.get(&scope)
.ok_or_else(|| JournalError::Corrupt("decision subject has no controller".into()))?;
super::validate_assignment(assignment).map_err(kernel_error)?;
if !controller_ids.insert(assignment.id()) {
// A mirror has no controller id, so it joins no uniqueness set.
if let Some(controller_id) = assignment.id()
&& !controller_ids.insert(controller_id)
{
return Err(JournalError::Corrupt(
"controller ID owns more than one canonical scope".into(),
));
@ -838,13 +841,17 @@ fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> {
));
}
}
// Both ways, the pairing `admit_resolved` decided: a mirror holds no grant,
// and every controller-bearing scope holds one.
if state
.controller_assignments
.keys()
.any(|scope| !state.affordance_grants.contains_key(scope))
.iter()
.any(|(scope, assignment)| {
state.affordance_grants.contains_key(scope) != assignment.mode().is_some()
})
{
return Err(JournalError::Corrupt(
"decision scope has no affordance grant".into(),
"controller assignment and affordance grant do not pair".into(),
));
}
// Every stored entry still passes the declaration validator, so a forged
@ -891,7 +898,9 @@ fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> {
|| event.revision == 0
|| event.revision > state.revision
|| event.revision <= previous_event_revision
|| event.controller_id != assignment.id()
// A forged history in which a mirror acted fails here: its
// assignment has no controller id to match.
|| Some(event.controller_id) != assignment.id()
|| !state
.affordance_grants
.get(&event.scope)

View file

@ -1,11 +1,11 @@
use super::{
AgencyGraph, AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, CommandId,
CreateWorld, CreateWorldIntent, CreationReceipt, DecisionInvocation, DecisionOpportunity,
Declaration, DraftHandle, EntityDeclaration, EntityKind, JurisdictionKey, KernelError,
NewController, OperatorEvent, PatchAnswer, PrincipalCommandIntent, PrincipalId, Ref,
SubjectDeclaration, SubjectKind, SubmitReceipt, SystemCapability, TickMinutes, WorldKernel,
WorldPatch, WorldScaleIntentRef, WorldSnapshot, journal, patch::kernel_speak_grant,
prepare_creation,
ConsumerId, CreateWorld, CreateWorldIntent, CreationReceipt, DecisionInvocation,
DecisionOpportunity, Declaration, DraftHandle, EntityDeclaration, EntityKind, JurisdictionKey,
KernelError, NewController, OperatorEvent, PatchAnswer, PrincipalCommandIntent, PrincipalId,
Ref, SubjectDeclaration, SubjectKind, SubmitReceipt, SystemCapability, TickMinutes, WorldId,
WorldKernel, WorldPatch, WorldScaleIntentRef, WorldSnapshot, journal,
patch::kernel_speak_grant, prepare_creation,
};
use crate::app_session::VerifiedPrincipalEvidence;
use std::path::Path;
@ -362,6 +362,33 @@ impl WorldMailbox {
.await
}
/// The consumer lane's one door, and the only constructor of a `Consumer`
/// capability. It takes the revision the consumer built against rather than
/// stamping one: a caller that cannot name its revision cannot be told its
/// batch is stale, and telling it so is the whole point of the field.
pub(super) async fn submit_consumer(
&self,
world_id: WorldId,
expected_revision: u64,
command_id: CommandId,
consumer: ConsumerId,
answers: Option<PatchAnswer>,
patch: WorldPatch,
) -> Result<SubmitReceipt, MailboxError> {
let capability = SystemCapability::Consumer { consumer };
self.submit_authenticated(
CommandEnvelope {
id: command_id,
world_id,
expected_revision,
caller: CallerId::System(capability),
body: CommandBody::AdmitPatch { answers, patch },
},
AuthenticatedCaller::verified_system(capability),
)
.await
}
#[cfg(test)]
pub(super) async fn create_fixture(
&self,
@ -512,6 +539,42 @@ impl ElaborationPort {
}
}
/// The consumer ingress's narrowing of the mailbox: one method. The ingress
/// has no reason to read the world — it selects no answer, pre-validates
/// nothing, and returns a receipt rather than state — so a snapshot method here
/// would be authority granted before the pass that needs it.
#[derive(Clone)]
pub(crate) struct ConsumerPort {
mailbox: WorldMailbox,
}
impl ConsumerPort {
pub(crate) fn new(mailbox: WorldMailbox) -> Self {
Self { mailbox }
}
pub(super) async fn submit_consumer(
&self,
world_id: WorldId,
expected_revision: u64,
command_id: CommandId,
consumer: ConsumerId,
answers: Option<PatchAnswer>,
patch: WorldPatch,
) -> Result<SubmitReceipt, MailboxError> {
self.mailbox
.submit_consumer(
world_id,
expected_revision,
command_id,
consumer,
answers,
patch,
)
.await
}
}
#[derive(Clone)]
pub(crate) struct ControllerPort {
mailbox: WorldMailbox,

View file

@ -7,6 +7,7 @@
mod action;
mod clock;
mod consumer;
mod controllers;
mod cover;
mod elaboration;
@ -17,6 +18,10 @@ mod tool_schema;
pub(crate) use action::ActionMismatch;
pub(crate) use clock::{FictionalMinutes, Motion, TickMinutes};
pub(crate) use consumer::{
CONSUMER_BODY_LIMIT, CONSUMER_CREDENTIALS_ENVIRONMENT, CONSUMER_PATCH_SCHEMA,
CONSUMER_RECEIPT_SCHEMA, ConsumerRegistry, admit_document, encode_receipt,
};
pub(crate) use controllers::{
CellRun, ControllerError, ControllerModels, ControllerOpenError, ControllerPendingReason,
ControllerRunner, ControllerWorkCustody, NarrativeCapture, NarrativeDecision, NarrativePending,
@ -26,7 +31,9 @@ pub(crate) use controllers::{
pub(crate) use cover::{
AgencyGraph, Cell, CellId, Constituent, Cover, CoverBudget, Resolution, TickIndex, derive_cover,
};
pub(crate) use mailbox::{ControllerPort, ElaborationPort, MailboxError, WorldMailbox};
pub(crate) use mailbox::{
ConsumerPort, ControllerPort, ElaborationPort, MailboxError, WorldMailbox,
};
pub(crate) use patch::{
AccessKind, Affordance, AffordanceKindName, Audience, AuthoredSource, AuthorityGrant,
AuthorityKindName, AuthorityTarget, BoundPrecondition, Bounds, ChannelRecord, Commitment,
@ -66,8 +73,8 @@ use std::path::Path;
use thiserror::Error;
use uuid::Uuid;
pub(crate) const STATE_SCHEMA: &str = "ghostlight.world_state.elaboration.v1";
pub(crate) const COMMIT_SCHEMA: &str = "ghostlight.world_commit.elaboration.v1";
pub(crate) const STATE_SCHEMA: &str = "ghostlight.world_state.consumer.v1";
pub(crate) const COMMIT_SCHEMA: &str = "ghostlight.world_commit.consumer.v1";
/// Compatibility tag derived from [`STATE_SCHEMA`]: the trailing
/// `<family>-<version>` pair (e.g. `foundation-v1`). Callers that publish a
@ -134,12 +141,33 @@ impl CommandId {
Self(cover::cell_constituent_uuid(world, cell, subject, tick))
}
/// sha256 over a namespace and its ordered, length-prefixed parts, first
/// sixteen bytes. A command key, not a referent id: `patch::derive_id`
/// still has exactly two call sites. No `uuid/v5`.
pub(crate) fn derived(namespace: &str, parts: &[&str]) -> Self {
let mut hasher = Sha256::new();
hasher.update(namespace.as_bytes());
for part in parts {
hasher.update((part.len() as u64).to_be_bytes());
hasher.update(part.as_bytes());
}
let bytes: [u8; 16] = hasher.finalize()[..16]
.try_into()
.expect("sha256 yields at least sixteen bytes");
Self(Uuid::from_bytes(bytes))
}
fn key(self) -> String {
self.0.to_string()
}
}
impl WorldId {
/// Canonical text, for the key derivations that hash a world identity.
pub(crate) fn text(self) -> String {
self.0.to_string()
}
/// A named zero for tests that need a world identity and no world.
#[cfg(test)]
pub(super) fn nil_for_test() -> Self {
@ -228,12 +256,42 @@ pub(crate) enum ControllerMode {
OperationalAgent,
}
/// A configured external consumer. Opaque inside the kernel: derived from the
/// consumer's configured name at the ingress registry and never spelled back
/// out, so no consumer name can reach a match arm.
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(transparent)]
pub(crate) struct ConsumerId(Uuid);
/// The one namespace a configured consumer name lowers through.
const CONSUMER_ID_NAMESPACE: &str = "ghostlight.consumer.id.v0";
impl ConsumerId {
/// The one lowering from a configured name, through `CommandId::derived`'s
/// recipe over its own namespace. Called only by the ingress registry.
pub(crate) fn of_name(name: &str) -> Self {
Self(CommandId::derived(CONSUMER_ID_NAMESPACE, &[name]).0)
}
/// Canonical text, for the command-key derivation that hashes it.
pub(crate) fn text(self) -> String {
self.0.to_string()
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub(crate) enum NewController {
Human { principal: PrincipalId },
Human {
principal: PrincipalId,
},
NarrativePersona,
OperationalAgent,
/// Declared as a mirror of state this world does not own. Mints no
/// controller, no mode, and no opportunity.
External {
consumer: ConsumerId,
},
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
@ -280,6 +338,28 @@ enum SystemCapability {
Elaborator {
jurisdiction: JurisdictionKey,
},
/// One external consumer, authoring only the subjects this world has
/// admitted as its mirrors. Minted by exactly one mailbox method, after the
/// ingress has authenticated the document; never derived from session
/// evidence.
Consumer {
consumer: ConsumerId,
},
}
/// What a confined patch author may write. `None` from `require_patch_author`
/// still means unconfined: the owner.
///
/// Deliberately not `AuthorityTarget`. That is in-world grant vocabulary read
/// by `covers` and `targets_overlap`; this names a caller's write scope, and
/// its consumer arm names a caller rather than a subject — the subject set is
/// derived from `controller_assignments` at decision time.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum PatchGround {
/// A place subtree. The elaborator's shape, unchanged in meaning.
Jurisdiction(JurisdictionKey),
/// Every subject bound to this consumer.
Consumer(ConsumerId),
}
#[derive(Clone, Debug)]
@ -509,22 +589,30 @@ enum ControllerAssignment {
OperationalAgent {
controller_id: ControllerId,
},
/// A mirror of state this world does not own. It has no controller id and
/// no mode, because the kernel will not keep a fictional one so an accessor
/// can stay infallible.
ExternallyControlled {
consumer: ConsumerId,
},
}
impl ControllerAssignment {
fn id(&self) -> ControllerId {
fn id(&self) -> Option<ControllerId> {
match self {
Self::Human { controller_id, .. }
| Self::NarrativePersona { controller_id }
| Self::OperationalAgent { controller_id } => *controller_id,
| Self::OperationalAgent { controller_id } => Some(*controller_id),
Self::ExternallyControlled { .. } => None,
}
}
fn mode(&self) -> ControllerMode {
fn mode(&self) -> Option<ControllerMode> {
match self {
Self::Human { .. } => ControllerMode::Human,
Self::NarrativePersona { .. } => ControllerMode::NarrativePersona,
Self::OperationalAgent { .. } => ControllerMode::OperationalAgent,
Self::Human { .. } => Some(ControllerMode::Human),
Self::NarrativePersona { .. } => Some(ControllerMode::NarrativePersona),
Self::OperationalAgent { .. } => Some(ControllerMode::OperationalAgent),
Self::ExternallyControlled { .. } => None,
}
}
@ -534,13 +622,31 @@ impl ControllerAssignment {
Self::NarrativePersona { controller_id } | Self::OperationalAgent { controller_id } => {
CallerId::Controller(*controller_id)
}
// The only caller that could ever act for this scope, and the
// controller lane cannot mint it.
Self::ExternallyControlled { consumer } => {
CallerId::System(SystemCapability::Consumer {
consumer: *consumer,
})
}
}
}
fn consumer(&self) -> Option<ConsumerId> {
match self {
Self::ExternallyControlled { consumer } => Some(*consumer),
Self::Human { .. } | Self::NarrativePersona { .. } | Self::OperationalAgent { .. } => {
None
}
}
}
fn human_principal(&self) -> Option<&PrincipalId> {
match self {
Self::Human { principal, .. } => Some(principal),
Self::NarrativePersona { .. } | Self::OperationalAgent { .. } => None,
Self::NarrativePersona { .. }
| Self::OperationalAgent { .. }
| Self::ExternallyControlled { .. } => None,
}
}
}
@ -726,8 +832,10 @@ pub(crate) struct SubjectSnapshot {
pub(crate) id: SubjectId,
pub(crate) label: String,
pub(crate) kind: SubjectKind,
pub(crate) controller_id: ControllerId,
pub(crate) controller_mode: ControllerMode,
/// Absent for an externally controlled mirror, which has no controller and
/// no turn. Every reader fails closed on `None`; none gets a default.
pub(crate) controller_id: Option<ControllerId>,
pub(crate) controller_mode: Option<ControllerMode>,
pub(crate) human_controller: Option<PrincipalId>,
pub(crate) affordances: BTreeSet<AffordanceId>,
pub(crate) position: Option<EntityId>,
@ -1409,9 +1517,8 @@ fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result<WorldEffect,
let confinement = require_patch_author(state, &command.caller, answers.as_ref())?;
let resolved = patch::resolve_patch(state, command.id, patch, None)
.map_err(KernelError::PatchRejected)?;
if let Some(jurisdiction) = confinement {
confine_to_jurisdiction(state, &resolved, jurisdiction)
.map_err(KernelError::PatchRejected)?;
if let Some(ground) = confinement {
confine_to_ground(state, &resolved, ground).map_err(KernelError::PatchRejected)?;
}
Ok(WorldEffect::PatchAdmitted {
answers: answers.clone(),
@ -1431,7 +1538,7 @@ fn require_system_capability(caller: &CallerId, body: &CommandBody) -> Result<()
(capability, body),
(SystemCapability::Clock, CommandBody::AdvanceTime { .. })
| (
SystemCapability::Elaborator { .. },
SystemCapability::Elaborator { .. } | SystemCapability::Consumer { .. },
CommandBody::AdmitPatch { .. }
)
);
@ -1660,7 +1767,7 @@ fn admit_resolved(state: &mut WorldState, resolved: &ResolvedPatch) -> Result<()
let mut controller_ids: BTreeSet<ControllerId> = state
.controller_assignments
.values()
.map(ControllerAssignment::id)
.filter_map(ControllerAssignment::id)
.collect();
for entry in &resolved.affordances {
if state
@ -1688,9 +1795,17 @@ fn admit_resolved(state: &mut WorldState, resolved: &ResolvedPatch) -> Result<()
"only world genesis may bind a human controller".into(),
));
}
if subject.affordances.is_empty() {
// Controller-shaped, both ways: a mirror receives no affordance, and
// every other controller must receive one. That is what makes the
// mirror's exclusion from opportunity derivation consistent rather than
// merely enforced.
if matches!(
subject.controller,
ControllerAssignment::ExternallyControlled { .. }
) != subject.affordances.is_empty()
{
return Err(KernelError::Invariant(
"admitted subject has no affordance".into(),
"admitted subject's controller and affordance grant do not pair".into(),
));
}
if let Some(position) = subject.position
@ -1703,7 +1818,9 @@ fn admit_resolved(state: &mut WorldState, resolved: &ResolvedPatch) -> Result<()
"admitted position does not name a canonical place".into(),
));
}
if !controller_ids.insert(subject.controller.id()) {
if let Some(controller_id) = subject.controller.id()
&& !controller_ids.insert(controller_id)
{
return Err(KernelError::Invariant(
"admitted controller ID collision".into(),
));
@ -3020,7 +3137,9 @@ fn agency_graph(state: &WorldState) -> AgencyGraph {
let active: BTreeSet<SubjectId> = state
.controller_assignments
.iter()
.filter(|(_, controller)| controller.mode() != ControllerMode::Human)
.filter(|(_, controller)| {
matches!(controller.mode(), Some(mode) if mode != ControllerMode::Human)
})
.map(|(scope, _)| scope.subject_id)
.collect();
let mut graph = AgencyGraph {
@ -3396,6 +3515,11 @@ pub(crate) enum CausalBoundary {
pub(crate) struct BoundaryDigest(String);
impl BoundaryDigest {
/// The digest text, for the one command-key derivation that hashes it.
pub(super) fn text(&self) -> &str {
&self.0
}
/// The deficit lane's answer has no preimage of its own: its digest is the
/// session's, produced by the same `sha256:` spelling.
pub(super) fn from_digest(value: String) -> Self {
@ -3694,7 +3818,16 @@ fn derive_opportunities(state: &WorldState) -> Result<Vec<DecisionOpportunity>,
state
.controller_assignments
.iter()
// World truth, not a scheduling preference: a mirror has no turn, so it
// never mints an opportunity and never trips the empty-grant invariant.
.filter(|(_, controller)| controller.mode().is_some())
.map(|(scope, controller)| {
let (Some(controller_id), Some(controller_mode)) = (controller.id(), controller.mode())
else {
return Err(KernelError::Invariant(
"decision scope has no controller turn".into(),
));
};
let affordance_ids: Vec<_> = state
.affordance_grants
.get(scope)
@ -3712,8 +3845,8 @@ fn derive_opportunities(state: &WorldState) -> Result<Vec<DecisionOpportunity>,
revision: state.revision,
scope_digest: scope_digest(state, *scope)?,
scope: *scope,
controller_id: controller.id(),
controller_mode: controller.mode(),
controller_id,
controller_mode,
affordance_ids,
})
})
@ -3848,15 +3981,29 @@ fn require_patch_author(
state: &WorldState,
caller: &CallerId,
answers: Option<&PatchAnswer>,
) -> Result<Option<JurisdictionKey>, KernelError> {
) -> Result<Option<PatchGround>, KernelError> {
match caller {
CallerId::Principal(principal) if principal == &state.owner => Ok(None),
CallerId::System(SystemCapability::Elaborator { jurisdiction }) => {
let answer = answers.ok_or(KernelError::Unauthorized)?;
if !jurisdiction_covers(state, *jurisdiction, answer) {
let ground = PatchGround::Jurisdiction(*jurisdiction);
if !ground_covers(state, ground, answer) {
return Err(KernelError::Unauthorized);
}
Ok(Some(*jurisdiction))
Ok(Some(ground))
}
CallerId::System(SystemCapability::Consumer { consumer }) => {
// Authority over its own mirrors is not jurisdictional and does not
// depend on an answer. An answer, when present, must name a subject
// this consumer is bound to, so a consumer cannot claim credit for
// structure it is confined out of writing.
let ground = PatchGround::Consumer(*consumer);
if let Some(answer) = answers
&& !ground_covers(state, ground, answer)
{
return Err(KernelError::Unauthorized);
}
Ok(Some(ground))
}
_ => Err(KernelError::Unauthorized),
}
@ -3871,7 +4018,21 @@ fn require_patch_author(
/// roots' targets, so a parent answering a child's row would reduce two targets
/// with one subject and drain a child's queue while its own row stays red.
/// Boundaries name a thing; deficits name a row.
fn jurisdiction_covers(state: &WorldState, held: JurisdictionKey, answer: &PatchAnswer) -> bool {
/// A consumer's arm is narrower on purpose: it may answer only a
/// `MissingStructure` boundary on one of its own mirrors. A deficit is
/// jurisdictional and a consumer holds no jurisdiction; a boundary about a
/// foreign subject is not its business.
fn ground_covers(state: &WorldState, held: PatchGround, answer: &PatchAnswer) -> bool {
let held = match held {
PatchGround::Jurisdiction(jurisdiction) => jurisdiction,
PatchGround::Consumer(consumer) => {
let PatchAnswer::Boundary(CausalBoundary::MissingStructure { subject, .. }) = answer
else {
return false;
};
return bound_to_consumer(state, *subject, consumer);
}
};
match answer {
PatchAnswer::Boundary(CausalBoundary::UnelaboratedDestination { place, .. }) => {
place_in(state, held, *place)
@ -3893,6 +4054,20 @@ fn jurisdiction_covers(state: &WorldState, held: JurisdictionKey, answer: &Patch
}
}
/// Is this committed subject one of that consumer's mirrors? The consumer's
/// ground is derived here, at decision time, and never carried on the wire: a
/// binding a later commit revoked shrinks the consumer's authority with no
/// ingress change.
fn bound_to_consumer(state: &WorldState, subject: SubjectId, consumer: ConsumerId) -> bool {
state
.controller_assignments
.get(&DecisionScope {
subject_id: subject,
})
.and_then(ControllerAssignment::consumer)
== Some(consumer)
}
fn place_in(state: &WorldState, held: JurisdictionKey, place: EntityId) -> bool {
match held {
JurisdictionKey::PlaceSubtree(root) => patch::covers_place(&state.entities, root, place),
@ -3929,16 +4104,32 @@ fn candidate_places(
/// patch that satisfies its answer may also declare unrelated structure inside
/// its jurisdiction, because "the minimum the boundary needs" is a semantic
/// verdict the kernel must not hold.
fn confine_to_jurisdiction(
fn confine_to_ground(
state: &WorldState,
resolved: &ResolvedPatch,
held: JurisdictionKey,
held: PatchGround,
) -> Result<(), Vec<Mismatch>> {
let entities = candidate_places(state, resolved);
// A consumer names no ground, so every place, every route, and every
// place-shaped reach is refused with no extra rule: relocation, route
// opening and closing, cost changes, and place-subtree grants are
// unrepresentable for it because they carry a place or a route.
let inside = |place: EntityId| match held {
JurisdictionKey::PlaceSubtree(root) => patch::covers_place(&entities, root, place),
JurisdictionKey::Uncovered => false,
PatchGround::Jurisdiction(JurisdictionKey::PlaceSubtree(root)) => {
patch::covers_place(&entities, root, place)
}
PatchGround::Jurisdiction(JurisdictionKey::Uncovered) | PatchGround::Consumer(_) => false,
};
// Every subject's consumer binding over `state ∪ patch`, so a consumer's
// first document can declare its own mirror and write it in one patch.
let mut bindings: BTreeMap<SubjectId, Option<ConsumerId>> = state
.controller_assignments
.iter()
.map(|(scope, assignment)| (scope.subject_id, assignment.consumer()))
.collect();
for declared in &resolved.subjects {
bindings.insert(declared.subject_id, declared.controller.consumer());
}
let mut positions: BTreeMap<SubjectId, Option<EntityId>> = state
.positions
.iter()
@ -3961,9 +4152,18 @@ fn confine_to_jurisdiction(
let mut mismatches = Vec::new();
let mut confine_subject = |site: &Site, subject: SubjectId, mismatches: &mut Vec<Mismatch>| {
let admitted = match positions.get(&subject).copied().flatten() {
Some(place) => inside(place),
None => held == JurisdictionKey::Uncovered,
let admitted = match held {
PatchGround::Jurisdiction(jurisdiction) => {
match positions.get(&subject).copied().flatten() {
Some(place) => inside(place),
None => jurisdiction == JurisdictionKey::Uncovered,
}
}
// Position is unconfined for a consumer: what binds a mirror is who
// controls it, not where it stands.
PatchGround::Consumer(consumer) => {
bindings.get(&subject).copied().flatten() == Some(consumer)
}
};
if !admitted {
mismatches.push(Mismatch::OutsideJurisdiction { site: site.clone() });
@ -3997,9 +4197,17 @@ fn confine_to_jurisdiction(
confine_place(&site, to, &mut mismatches);
}
for declared in &resolved.facts {
if let FactStanding::Claimed { by } = declared.fact.standing {
let site = Site::Declaration(declared.handle.clone());
confine_subject(&site, by, &mut mismatches);
let site = Site::Declaration(declared.handle.clone());
match declared.fact.standing {
FactStanding::Claimed { by } => confine_subject(&site, by, &mut mismatches),
// A consumer's citation is its own provenance claim, and that claim
// buys an `Admit` into its own custody and a claimed fact. It
// cannot canonize.
FactStanding::Canonical { .. } => {
if matches!(held, PatchGround::Consumer(_)) {
mismatches.push(Mismatch::OutsideJurisdiction { site });
}
}
}
}
for declared in &resolved.channels {
@ -4245,7 +4453,7 @@ fn apply_effect(
(capability, effect),
(SystemCapability::Clock, WorldEffect::TimeAdvanced { .. })
| (
SystemCapability::Elaborator { .. },
SystemCapability::Elaborator { .. } | SystemCapability::Consumer { .. },
WorldEffect::PatchAdmitted { .. }
)
);
@ -4267,10 +4475,10 @@ fn apply_effect(
"admitted patch does not satisfy admission authority".into(),
)
})?;
if let Some(jurisdiction) = confinement {
confine_to_jurisdiction(state, resolved, jurisdiction).map_err(|_| {
if let Some(ground) = confinement {
confine_to_ground(state, resolved, ground).map_err(|_| {
KernelError::Invariant(
"admitted patch wrote outside its author's jurisdiction".into(),
"admitted patch wrote outside its author's ground".into(),
)
})?;
}
@ -5992,7 +6200,7 @@ mod tests {
.get_mut(&scope)
.unwrap();
*assignment = ControllerAssignment::NarrativePersona {
controller_id: assignment.id(),
controller_id: assignment.id().expect("the fixture scope has a controller"),
};
assert_ne!(scope_digest(&changed_controller, scope).unwrap(), base);

View file

@ -1142,6 +1142,68 @@ pub(crate) struct WorldPatch {
pub(crate) evidence: Vec<EvidenceRef>,
}
/// The one byte bound on a `WorldPatch` frame from any external source, and
/// the three item bounds on a `WorldPatch` as a value. One owner, two
/// consumers: the consumer ingress decodes against them, and the elaboration
/// lane checks its own draft against the same two item caps.
pub(crate) const MAX_PATCH_BYTES: usize = 256 * 1024;
pub(crate) const MAX_PATCH_DECLARATIONS: usize = 64;
pub(crate) const MAX_PATCH_OPERATIONS: usize = 128;
pub(crate) const MAX_PATCH_EVIDENCE: usize = 64;
/// Why a patch was refused before the resolver ever saw it. Not a second
/// structural vocabulary: nothing here reads world state.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PatchDecodeError {
TooLarge { bytes: usize },
NotCanonical,
Malformed,
TooManyDeclarations { count: usize },
TooManyOperations { count: usize },
TooManyEvidence { count: usize },
}
/// The one decode owner for a `WorldPatch` from a byte source. The byte cap is
/// applied to the frame before `rmp_serde` sees it, so no item is deserialized
/// out of a frame the world would not accept; the item caps are checked on the
/// decoded value before `resolve_patch`, which is the first thing that costs
/// `state ∪ patch`.
pub(crate) fn decode_patch(bytes: &[u8]) -> Result<WorldPatch, PatchDecodeError> {
if bytes.len() > MAX_PATCH_BYTES {
return Err(PatchDecodeError::TooLarge { bytes: bytes.len() });
}
let patch: WorldPatch =
rmp_serde::from_slice(bytes).map_err(|_| PatchDecodeError::Malformed)?;
// The canonical round-trip the journal and the presence route already
// require, so one frame has one encoding.
if rmp_serde::to_vec_named(&patch).map_err(|_| PatchDecodeError::Malformed)? != bytes {
return Err(PatchDecodeError::NotCanonical);
}
check_patch_caps(&patch)?;
Ok(patch)
}
/// The same three item caps against an in-memory draft, for the lane that
/// builds rather than decodes.
pub(crate) fn check_patch_caps(patch: &WorldPatch) -> Result<(), PatchDecodeError> {
if patch.declarations.len() > MAX_PATCH_DECLARATIONS {
return Err(PatchDecodeError::TooManyDeclarations {
count: patch.declarations.len(),
});
}
if patch.operations.len() > MAX_PATCH_OPERATIONS {
return Err(PatchDecodeError::TooManyOperations {
count: patch.operations.len(),
});
}
if patch.evidence.len() > MAX_PATCH_EVIDENCE {
return Err(PatchDecodeError::TooManyEvidence {
count: patch.evidence.len(),
});
}
Ok(())
}
/// One named structural check that a patch failed. A rejection carries the
/// complete set, never the first failure. It never enters `WorldState`,
/// `WorldEffect`, `CommandEnvelope`, or `WorldCommit`; the serde derives exist
@ -1177,8 +1239,11 @@ pub(crate) enum Mismatch {
UnadmittedController {
handle: DraftHandle,
},
NoAffordances {
handle: DraftHandle,
/// A declared subject's controller and affordance grant do not pair: a
/// mirror was granted an affordance, or an ordinary controller was granted
/// none. `admit_resolved` re-decides the same rule.
ControllerGrantMismatch {
site: Site,
},
EmptyEvidence {
position: usize,
@ -2876,9 +2941,13 @@ pub(super) fn resolve_patch(
}
}
if let Declaration::Subject(subject) = declaration {
if subject.affordances.is_empty() {
mismatches.push(Mismatch::NoAffordances {
handle: handle.clone(),
// Both ways. A mirror receives no opportunity, so it may hold no
// affordance; every other controller must hold one.
if matches!(subject.controller, NewController::External { .. })
!= subject.affordances.is_empty()
{
mismatches.push(Mismatch::ControllerGrantMismatch {
site: Site::Declaration(handle.clone()),
});
}
if let NewController::Human { principal } = &subject.controller
@ -4526,23 +4595,29 @@ pub(super) fn resolve_patch(
});
}
allocated_subjects.insert(input.handle.clone(), subject_id);
let controller_id = ControllerId(derive_id(
CONTROLLER_NAMESPACE,
world_id,
command_id,
&input.handle,
None,
));
let mut controller_id = || {
ControllerId(derive_id(
CONTROLLER_NAMESPACE,
world_id,
command_id,
&input.handle,
None,
))
};
let controller = match input.controller.clone() {
NewController::Human { principal } => ControllerAssignment::Human {
controller_id,
controller_id: controller_id(),
principal,
},
NewController::NarrativePersona => {
ControllerAssignment::NarrativePersona { controller_id }
}
NewController::OperationalAgent => {
ControllerAssignment::OperationalAgent { controller_id }
NewController::NarrativePersona => ControllerAssignment::NarrativePersona {
controller_id: controller_id(),
},
NewController::OperationalAgent => ControllerAssignment::OperationalAgent {
controller_id: controller_id(),
},
// No controller id is derived, because there is no controller.
NewController::External { consumer } => {
ControllerAssignment::ExternallyControlled { consumer }
}
};
let granted = input