Give the world Knowledge, Channels, and Fact standing
Speech stops being a broadcast event everyone can read and becomes a typed claim that some subjects hold. Three partitions carry it: `facts` (one row per `EntityKind::Fact`, write-once), `channels` (one row per `EntityKind::Channel`), and `knowledge`, which is the sole owner of who-heard-what. `state.events` is demoted from perception surface to causal record. The events log records what was done; the knowledge partition decides what a subject may act on and what its projection may contain. `WorldSnapshot.events` is deleted outright, so `controllers.rs` structurally cannot read an unscoped log; the human operator's story feed moves to `WorldKernel::operator_log`, reached through its own mailbox request and passed to `eve::authenticated_surface` beside the snapshot. Two pure functions state reach and nothing else does: `audience` (who is in earshot) and `fan_out` (who gains knowledge from one telling). Co-location is the actor's exact place; a channel's `Reach::Place` is the subtree, through the same `covers_place` walk a jurisdiction uses. A telling never overwrites a holder and `Believed` is fixed by the kernel, so no speaker owns another subject's credence. The kernel Speak entry gains its real shape: one `CanBroadcast` precondition, so an unplaced subject fails with `NoAudience` rather than being heard by everyone. A `carries_speech` entry must name exactly one audience, and `exercise` prepends two kernel-owned operations no slot or band can influence: `AssertClaim` mints the fact, `Communicate` fans it out. That makes `action::exercise` the second `derive_id` call site; the "only `admit_resolved` allocates" rule is rewritten rather than amended. The kernel does not compare two statements. There is no dedup, no interning, no contradiction check, and no similarity. Deception is a `Claimed` fact standing beside its asserter's own knowledge of a different one, and the meaning of that gap belongs to a reader. `STATE_SCHEMA`/`COMMIT_SCHEMA` become `.knowledge.v1` and the controller work schema moves to v5; a pre-pass store is refused with no migration path. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
parent
43e8042d8c
commit
b8ff18282e
8 changed files with 3422 additions and 271 deletions
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
use crate::{
|
||||
mesh::{COMMAND_BOUNDARY, COMMAND_RESULT_SCHEMA, PROVIDER_ID, SURFACE_ID},
|
||||
world::{ControllerMode, WorldPhase, WorldSnapshot},
|
||||
world::{ControllerMode, OperatorEvent, WorldPhase, WorldSnapshot},
|
||||
};
|
||||
use anyhow::{Context, bail};
|
||||
use chrono::{DateTime, Utc};
|
||||
|
|
@ -100,9 +100,13 @@ fn anonymous_surface_at(version: u64) -> Value {
|
|||
)
|
||||
}
|
||||
|
||||
/// `operator_log` arrives beside the snapshot rather than inside it: the story
|
||||
/// feed is the human operator's surface, and no subject-facing lane may reach an
|
||||
/// unscoped event log.
|
||||
pub(crate) fn authenticated_surface(
|
||||
account: &str,
|
||||
snapshot: Option<&WorldSnapshot>,
|
||||
operator_log: &[OperatorEvent],
|
||||
) -> anyhow::Result<Value> {
|
||||
let version = surface_version(snapshot);
|
||||
let mut children = vec![json!({
|
||||
|
|
@ -182,7 +186,7 @@ pub(crate) fn authenticated_surface(
|
|||
"children":[{
|
||||
"id":"world.summary.body",
|
||||
"kind":"text",
|
||||
"props":{"value":format!("{} subject(s), {} committed event(s)", world.subjects.len(), world.events.len())},
|
||||
"props":{"value":format!("{} subject(s), {} committed event(s)", world.subjects.len(), operator_log.len())},
|
||||
"children":[]
|
||||
}]
|
||||
}));
|
||||
|
|
@ -228,11 +232,10 @@ pub(crate) fn authenticated_surface(
|
|||
}
|
||||
}
|
||||
WorldPhase::Active => {
|
||||
let story = world
|
||||
.events
|
||||
let story = operator_log
|
||||
.iter()
|
||||
.filter_map(|event| {
|
||||
event.invocation.speech.as_ref().map(|text| {
|
||||
event.speech.as_ref().map(|text| {
|
||||
json!({
|
||||
"id":format!("world.event.{}", event.revision),
|
||||
"kind":"text",
|
||||
|
|
@ -533,7 +536,7 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn empty_authenticated_surface_has_create_without_session_zero() {
|
||||
let surface = authenticated_surface("sha256:owner", None).unwrap();
|
||||
let surface = authenticated_surface("sha256:owner", None, &[]).unwrap();
|
||||
let encoded = serde_json::to_string(&surface).unwrap();
|
||||
assert!(encoded.contains("world.create"));
|
||||
assert!(encoded.contains("narrative_persona_label"));
|
||||
|
|
|
|||
|
|
@ -13,8 +13,8 @@ use crate::{
|
|||
AffordanceId, CommandBody, CommandId, ControllerError, ControllerModels,
|
||||
ControllerPendingReason, ControllerRunner, ControllerWorkCustody, CreateWorldIntent,
|
||||
DecisionInvocation, DecisionOpportunity, KernelError, MailboxError, NarrativeRun,
|
||||
OperationalRun, PrincipalCommandIntent, PrincipalId, SubmissionDisposition, SubmitReceipt,
|
||||
Utterance, WorldMailbox, WorldSnapshot,
|
||||
OperationalRun, PrincipalCommandIntent, PrincipalId, Statement, SubmissionDisposition,
|
||||
SubmitReceipt, WorldMailbox, WorldSnapshot,
|
||||
},
|
||||
};
|
||||
use anyhow::{Context, bail, ensure};
|
||||
|
|
@ -442,9 +442,11 @@ async fn eve_surface(
|
|||
let Some(principal) = authenticated_principal(&headers, &state).await else {
|
||||
return Json(eve::anonymous_surface()).into_response();
|
||||
};
|
||||
match current_world(&state).await.and_then(|snapshot| {
|
||||
eve::authenticated_surface(principal.account_subject_hash(), snapshot.as_ref())
|
||||
}) {
|
||||
match current_operator_view(&state)
|
||||
.await
|
||||
.and_then(|(snapshot, log)| {
|
||||
eve::authenticated_surface(principal.account_subject_hash(), snapshot.as_ref(), &log)
|
||||
}) {
|
||||
Ok(surface) => Json(surface).into_response(),
|
||||
Err(error) => (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
|
|
@ -1241,7 +1243,7 @@ async fn execute_world(
|
|||
affordance: payload.affordance_id,
|
||||
bindings: Vec::new(),
|
||||
proposed: Vec::new(),
|
||||
speech: Some(Utterance::new(payload.text).ok_or_else(|| {
|
||||
speech: Some(Statement::new(payload.text).ok_or_else(|| {
|
||||
RuntimeCommandError::Payload("spoken text is not canonical".into())
|
||||
})?),
|
||||
},
|
||||
|
|
@ -1305,6 +1307,21 @@ async fn current_world(state: &AppState) -> anyhow::Result<Option<WorldSnapshot>
|
|||
}
|
||||
}
|
||||
|
||||
/// The two halves of the operator surface, fetched together: the projection of
|
||||
/// world state, and the story feed the human reads. The feed is deliberately not
|
||||
/// a snapshot field, so no controller lane can reach it.
|
||||
async fn current_operator_view(
|
||||
state: &AppState,
|
||||
) -> anyhow::Result<(Option<WorldSnapshot>, Vec<crate::world::OperatorEvent>)> {
|
||||
let snapshot = current_world(state).await?;
|
||||
let log = match state.world.operator_log().await {
|
||||
Ok(log) => log,
|
||||
Err(MailboxError::Kernel(KernelError::WorldNotCreated)) => Vec::new(),
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
Ok((snapshot, log))
|
||||
}
|
||||
|
||||
async fn publish_projection(state: &AppState) -> anyhow::Result<u64> {
|
||||
let snapshot = current_world(state).await?;
|
||||
let version = eve::surface_version(snapshot.as_ref());
|
||||
|
|
@ -2181,8 +2198,9 @@ mod tests {
|
|||
)
|
||||
.await;
|
||||
assert_eq!(spoken["sourceVersion"], 4);
|
||||
let world = current_world(&fixture.state).await.unwrap().unwrap();
|
||||
assert_eq!(world.events.len(), 1);
|
||||
let (world, log) = current_operator_view(&fixture.state).await.unwrap();
|
||||
assert!(world.is_some());
|
||||
assert_eq!(log.len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
|
|
|||
|
|
@ -7,8 +7,8 @@
|
|||
//! draws a band, and the draw goes through the one `digest()` owner.
|
||||
|
||||
use super::patch::{
|
||||
self, Affordance, Bounds, ComponentOpKind, Cost, Precondition, Quantity, RefKind, Role,
|
||||
WorldPatch,
|
||||
self, Affordance, Audience, AudienceSpec, Bounds, ComponentOpKind, Cost, Precondition,
|
||||
Quantity, RefKind, Role, WorldPatch,
|
||||
};
|
||||
use super::{
|
||||
AffordanceId, AuthorityGrant, AuthorityTarget, CommandId, DecisionEvent, DecisionInvocation,
|
||||
|
|
@ -89,6 +89,23 @@ pub(crate) enum ActionMismatch {
|
|||
DelegationNotMonotone {
|
||||
slot: usize,
|
||||
},
|
||||
/// The actor does not hold the bound fact at the required confidence. A
|
||||
/// re-appraisal that lowered its own confidence while the proposal was in
|
||||
/// flight arrives here rather than as a rebind: confidence is admission-only.
|
||||
FactUnknown {
|
||||
precondition: usize,
|
||||
},
|
||||
/// The actor has no audience at all: unplaced for co-location, or outside a
|
||||
/// channel it does not control.
|
||||
NoAudience {
|
||||
precondition: usize,
|
||||
},
|
||||
/// The addressed subject is not inside that audience. A target that walked
|
||||
/// out of the room while the proposal was in flight arrives here: the
|
||||
/// preimage holds what the actor *is*, not the world it reaches.
|
||||
CannotReach {
|
||||
precondition: usize,
|
||||
},
|
||||
}
|
||||
|
||||
/// The band draw's whole preimage. Five fields, none of them from the
|
||||
|
|
@ -136,7 +153,7 @@ pub(super) fn exercise(
|
|||
|
||||
let band = select_band(state, command_id, granted.id, entry)?;
|
||||
let operations = lower(entry, band, invocation, &bindings)?;
|
||||
let effects = if operations.is_empty() {
|
||||
let mut effects = if operations.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
// The same resolver, the same per-operation preconditions, the same
|
||||
|
|
@ -154,6 +171,41 @@ pub(super) fn exercise(
|
|||
.operations
|
||||
};
|
||||
|
||||
// The speech lowering: kernel-owned, not a slot, and unreachable by any
|
||||
// proposer, band, or effect ceiling. The audience comes from the entry's one
|
||||
// speech precondition, so a world's `whisper` and `proclaim` lower through
|
||||
// the same two operations with a different audience and the kernel learns no
|
||||
// genre. Addressing does not narrow the fan-out: a voice fills its audience.
|
||||
let speech = match (&invocation.speech, entry.carries_speech) {
|
||||
(Some(statement), true) => {
|
||||
let fact = EntityId(patch::derive_id(
|
||||
patch::ENTITY_NAMESPACE,
|
||||
state.world_id,
|
||||
command_id,
|
||||
&patch::DraftHandle::new(SPEECH_HANDLE),
|
||||
Some(SPEECH_INDEX),
|
||||
));
|
||||
let to = speech_audience(entry, &bindings)?;
|
||||
effects.splice(
|
||||
0..0,
|
||||
[
|
||||
patch::ResolvedOp::AssertClaim {
|
||||
fact,
|
||||
statement: statement.clone(),
|
||||
by: actor,
|
||||
},
|
||||
patch::ResolvedOp::Communicate {
|
||||
speaker: actor,
|
||||
fact,
|
||||
to,
|
||||
},
|
||||
],
|
||||
);
|
||||
Some(fact)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let revision = state
|
||||
.revision
|
||||
.checked_add(1)
|
||||
|
|
@ -163,12 +215,42 @@ pub(super) fn exercise(
|
|||
revision,
|
||||
scope: current.scope,
|
||||
controller_id: current.controller_id,
|
||||
invocation: invocation.clone(),
|
||||
affordance: granted.id,
|
||||
speech,
|
||||
band,
|
||||
effects,
|
||||
})
|
||||
}
|
||||
|
||||
/// The synthetic handle every minted claim allocates under. It is synthesized
|
||||
/// only in Active and declarations are Draft-only, so no world-declared handle
|
||||
/// can collide with it.
|
||||
const SPEECH_HANDLE: &str = "ghostlight.speech";
|
||||
|
||||
/// The speech index, passed as `derive_id`'s discriminator. It is `0` for every
|
||||
/// invocation because one invocation carries one utterance; it exists so a later
|
||||
/// multi-utterance turn needs no second allocation idiom.
|
||||
const SPEECH_INDEX: &str = "0";
|
||||
|
||||
/// The audience a speech-carrying entry names. The declaration validator already
|
||||
/// refused an entry with none (`SpeechWithoutAudience`) or two
|
||||
/// (`AmbiguousSpeechAudience`), so anything else here is a corrupt catalog.
|
||||
fn speech_audience(
|
||||
entry: &Affordance,
|
||||
bindings: &BTreeMap<Role, Target>,
|
||||
) -> Result<Audience, KernelError> {
|
||||
entry
|
||||
.preconditions
|
||||
.iter()
|
||||
.find_map(|precondition| match precondition {
|
||||
Precondition::CanBroadcast { via } | Precondition::CanReach { via, .. } => {
|
||||
bound_audience(via, bindings)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.ok_or_else(|| KernelError::Invariant("a speech-carrying entry names no audience".into()))
|
||||
}
|
||||
|
||||
/// Stage 2. The acting subject is never a declared role: the kernel binds the
|
||||
/// reserved name `actor` to it and refuses an invocation that tries to. A
|
||||
/// binding that happens to name the actor through a declared role is legal and
|
||||
|
|
@ -328,10 +410,61 @@ fn check_preconditions(
|
|||
});
|
||||
}
|
||||
}
|
||||
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::audience(state, actor, &audience).contains(&actor) {
|
||||
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,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
fn bound_audience(via: &AudienceSpec, bindings: &BTreeMap<Role, Target>) -> Option<Audience> {
|
||||
match via {
|
||||
AudienceSpec::Colocated => Some(Audience::Colocated),
|
||||
AudienceSpec::Channel(role) => match bindings.get(role).copied() {
|
||||
Some(Target::Entity(entity_id)) => Some(Audience::Channel(entity_id)),
|
||||
_ => None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Stage 4, beside the ceilings: an authority a slot would grant or revoke
|
||||
/// must not exceed the actor's own. For a grant this is the monotonicity
|
||||
/// envelope — no holder mints authority it does not itself hold. For a
|
||||
|
|
@ -506,7 +639,7 @@ fn check_proposals(
|
|||
rejections.push(ActionMismatch::SlotNotProposed { slot });
|
||||
}
|
||||
}
|
||||
// `Utterance` is serde-transparent, so a value that arrived through
|
||||
// `Statement` is serde-transparent, so a value that arrived through
|
||||
// deserialization rather than through the constructor is re-checked here
|
||||
// rather than trusted.
|
||||
match (&invocation.speech, entry.carries_speech) {
|
||||
|
|
@ -703,6 +836,18 @@ fn lower(
|
|||
institution: subject(0)?,
|
||||
office: office.clone(),
|
||||
},
|
||||
ComponentOpKind::AcquireKnowledge { confidence } => {
|
||||
patch::ComponentOp::AcquireKnowledge {
|
||||
subject: subject(0)?,
|
||||
fact: entity(1)?,
|
||||
source: patch::AuthoredSource::Witnessed,
|
||||
confidence: *confidence,
|
||||
}
|
||||
}
|
||||
ComponentOpKind::Forget => patch::ComponentOp::Forget {
|
||||
subject: subject(0)?,
|
||||
fact: entity(1)?,
|
||||
},
|
||||
});
|
||||
}
|
||||
Ok(operations)
|
||||
|
|
@ -724,7 +869,7 @@ mod tests {
|
|||
};
|
||||
use crate::world::{
|
||||
AffordanceKindName, AuthenticatedCaller, CallerId, CommandBody, Declaration, EntityKind,
|
||||
ProposedEffect, RoleBinding, SubmitReceipt, Utterance, WorldEffect, WorldKernel,
|
||||
ProposedEffect, RoleBinding, Statement, SubmitReceipt, WorldEffect, WorldKernel,
|
||||
WorldPatch, WorldSnapshot, apply_effect,
|
||||
};
|
||||
use std::collections::BTreeSet;
|
||||
|
|
@ -1083,7 +1228,7 @@ mod tests {
|
|||
let directory = tempfile::tempdir().unwrap();
|
||||
let bench = bench(directory.path(), "Speech");
|
||||
let mut spoken_carry = bench.carry(1, bench.yard);
|
||||
spoken_carry.speech = Some(Utterance::new("Take it.").unwrap());
|
||||
spoken_carry.speech = Some(Statement::new("Take it.").unwrap());
|
||||
assert_eq!(
|
||||
bench.rejections(&spoken_carry),
|
||||
vec![ActionMismatch::SpeechNotCarried]
|
||||
|
|
@ -1101,9 +1246,9 @@ mod tests {
|
|||
vec![ActionMismatch::SpeechRequired]
|
||||
);
|
||||
|
||||
// `Utterance` is serde-transparent, so a value that arrived without the
|
||||
// `Statement` is serde-transparent, so a value that arrived without the
|
||||
// constructor is re-checked here rather than trusted.
|
||||
silent_speak.speech = Some(serde_json::from_str::<Utterance>("\" \"").unwrap());
|
||||
silent_speak.speech = Some(serde_json::from_str::<Statement>("\" \"").unwrap());
|
||||
assert_eq!(
|
||||
bench.rejections(&silent_speak),
|
||||
vec![ActionMismatch::EmptySpeech]
|
||||
|
|
@ -1354,13 +1499,8 @@ mod tests {
|
|||
let bench = bench(directory.path(), "ForgedAction");
|
||||
let opportunity = bench.clerk_opportunity();
|
||||
let command_id = CommandId::issue();
|
||||
let honest = draw_once(
|
||||
&bench.kernel.state,
|
||||
command_id,
|
||||
&opportunity,
|
||||
&bench.carry(2, bench.yard),
|
||||
)
|
||||
.unwrap();
|
||||
let invocation = bench.carry(2, bench.yard);
|
||||
let honest = draw_once(&bench.kernel.state, command_id, &opportunity, &invocation).unwrap();
|
||||
let caller = CallerId::Controller(opportunity.controller_id);
|
||||
|
||||
for forged in [
|
||||
|
|
@ -1385,6 +1525,7 @@ mod tests {
|
|||
&caller,
|
||||
&WorldEffect::DecisionExercised {
|
||||
opportunity: opportunity.clone(),
|
||||
invocation: invocation.clone(),
|
||||
event: forged,
|
||||
},
|
||||
)
|
||||
|
|
@ -1401,6 +1542,7 @@ mod tests {
|
|||
&caller,
|
||||
&WorldEffect::DecisionExercised {
|
||||
opportunity,
|
||||
invocation: invocation.clone(),
|
||||
event: honest,
|
||||
},
|
||||
)
|
||||
|
|
@ -1434,7 +1576,7 @@ mod tests {
|
|||
affordance: speak,
|
||||
bindings: Vec::new(),
|
||||
proposed: Vec::new(),
|
||||
speech: Some(Utterance::new("I open the door.").unwrap()),
|
||||
speech: Some(Statement::new("I open the door.").unwrap()),
|
||||
},
|
||||
},
|
||||
),
|
||||
|
|
@ -1444,9 +1586,10 @@ mod tests {
|
|||
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
|
||||
let event = kernel.state.events.last().unwrap();
|
||||
assert_eq!(event.band, 0);
|
||||
assert!(event.effects.is_empty());
|
||||
// The two the speech lowering prepends, and nothing from a slot.
|
||||
assert_eq!(event.effects.len(), 2);
|
||||
assert_eq!(
|
||||
event.invocation.speech.as_ref().map(Utterance::as_str),
|
||||
crate::world::tests::spoken(&kernel.state, event),
|
||||
Some("I open the door.")
|
||||
);
|
||||
assert_eq!(kernel.state.holdings, holdings);
|
||||
|
|
@ -1483,7 +1626,7 @@ mod tests {
|
|||
kind: &str,
|
||||
bindings: Vec<RoleBinding>,
|
||||
proposed: Vec<ProposedEffect>,
|
||||
speech: Option<Utterance>,
|
||||
speech: Option<Statement>,
|
||||
) -> DecisionInvocation {
|
||||
DecisionInvocation {
|
||||
affordance: affordance_named(&self.active, kind),
|
||||
|
|
@ -1773,7 +1916,9 @@ mod tests {
|
|||
role: Role("actor".into()),
|
||||
kind: RefKind::Subject(None),
|
||||
}],
|
||||
preconditions: Vec::new(),
|
||||
preconditions: vec![Precondition::CanBroadcast {
|
||||
via: AudienceSpec::Colocated,
|
||||
}],
|
||||
effect_slots: Vec::new(),
|
||||
outcome_bands: vec![OutcomeBand {
|
||||
weight: 1,
|
||||
|
|
@ -1962,7 +2107,7 @@ mod tests {
|
|||
"petition",
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
Some(Utterance::new("The tithe was taken twice.").unwrap()),
|
||||
Some(Statement::new("The tithe was taken twice.").unwrap()),
|
||||
);
|
||||
assert_eq!(
|
||||
bench.rejected_as(bench.civic.outsider, &petition),
|
||||
|
|
@ -1980,9 +2125,9 @@ mod tests {
|
|||
.events
|
||||
.last()
|
||||
.expect("the committed event");
|
||||
assert!(event.effects.is_empty());
|
||||
assert_eq!(event.effects.len(), 2);
|
||||
assert_eq!(
|
||||
event.invocation.speech.as_ref().map(Utterance::as_str),
|
||||
crate::world::tests::spoken(&bench.kernel.state, event),
|
||||
Some("The tithe was taken twice.")
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -7,11 +7,11 @@
|
|||
//! affordance fields.
|
||||
|
||||
use crate::world::{
|
||||
AffordanceId, AffordanceSnapshot, AuthorityGrant, Bounds, CommandId, CommitReceipt,
|
||||
AffordanceId, AffordanceSnapshot, AuthorityGrant, Bounds, CommandId, CommitReceipt, Confidence,
|
||||
ControllerMode, Cost, DecisionInvocation, DecisionOpportunity, DependencyTarget, EdgeId,
|
||||
EntityId, EntityKind, KernelError, Magnitude, MailboxError, OfficeSnapshot, ProposedEffect,
|
||||
Quantity, RefKind, RoleBinding, SubjectId, SubjectSnapshot, SubmitReceipt, Target, Utterance,
|
||||
WorldMailbox, WorldSnapshot,
|
||||
EntityId, EntityKind, FactStandingView, KernelError, KnowledgeSnapshot, KnowledgeSource,
|
||||
Magnitude, MailboxError, OfficeSnapshot, ProposedEffect, Quantity, RefKind, RoleBinding,
|
||||
Statement, SubjectId, SubjectSnapshot, SubmitReceipt, Target, WorldMailbox, WorldSnapshot,
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
use chrono::Utc;
|
||||
|
|
@ -46,8 +46,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.v4";
|
||||
const CONTROLLER_WORK_SCHEMA: &str = "ghostlight.controller_work.v4";
|
||||
const CONTROLLER_WORK_ROW: &str = "controller_work.v5";
|
||||
const CONTROLLER_WORK_SCHEMA: &str = "ghostlight.controller_work.v5";
|
||||
|
||||
/// 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
|
||||
|
|
@ -2607,7 +2607,8 @@ impl SelectedDecision {
|
|||
"offices_held": Self::typed_offices(&self.subject.offices_held),
|
||||
"offices_granted": Self::typed_offices(&self.subject.offices_granted),
|
||||
"redress": self.typed_redress(),
|
||||
"visible_events": self.typed_visible_events(),
|
||||
"knowledge": self.typed_knowledge(),
|
||||
"channels": self.typed_channels(),
|
||||
}))
|
||||
.map_err(|error| ControllerError::Serialization(error.to_string()))
|
||||
}
|
||||
|
|
@ -2740,53 +2741,77 @@ impl SelectedDecision {
|
|||
}
|
||||
|
||||
fn visible_stimulus(&self) -> Result<String, ControllerError> {
|
||||
serde_json::to_string_pretty(&self.projector_visible_events()?)
|
||||
serde_json::to_string_pretty(&self.projector_knowledge())
|
||||
.map_err(|error| ControllerError::Serialization(error.to_string()))
|
||||
}
|
||||
|
||||
/// Only spoken events. What one subject perceives of another's action is a
|
||||
/// `Knowledge` question and has no component yet; rendering every action
|
||||
/// here would decide that every subject perceives everything.
|
||||
fn typed_visible_events(&self) -> Vec<Value> {
|
||||
self.snapshot
|
||||
.events
|
||||
/// The acting subject's own knowledge, and nothing else. A subject perceives
|
||||
/// a speech act if and only if it holds `Knowledge` of that act's fact, so
|
||||
/// this is a renderer over one kernel-derived field rather than a walk that
|
||||
/// decides reach a second time. Confidence reaches the Projector as prose
|
||||
/// uncertainty, which makes the prompt's instruction a description of the
|
||||
/// surface instead of its enforcement.
|
||||
fn projector_knowledge(&self) -> Vec<Value> {
|
||||
self.subject
|
||||
.knowledge
|
||||
.iter()
|
||||
.filter_map(|event| {
|
||||
event.invocation.speech.as_ref().map(|text| {
|
||||
json!({
|
||||
"revision": event.revision,
|
||||
"speaker_subject_id": event.scope.subject_id,
|
||||
"text": text.as_str(),
|
||||
})
|
||||
.map(|entry| {
|
||||
json!({
|
||||
"speaker": self.speaker_label(entry),
|
||||
"certainty": entry.confidence,
|
||||
"text": entry.statement.as_str(),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn projector_visible_events(&self) -> Result<Vec<Value>, ControllerError> {
|
||||
self.snapshot
|
||||
.events
|
||||
/// Attribution comes from the listener's own knowledge, never from an event
|
||||
/// scope: a subject that holds a fact it was never told sees the statement
|
||||
/// with no speaker, because it knows the thing and not the telling. A label
|
||||
/// is resolved only for a subject that spoke to this one.
|
||||
fn speaker_label(&self, entry: &KnowledgeSnapshot) -> Value {
|
||||
match entry.source {
|
||||
KnowledgeSource::Told { by, .. } => self
|
||||
.snapshot
|
||||
.subjects
|
||||
.iter()
|
||||
.find(|subject| subject.id == by)
|
||||
.map_or(Value::Null, |subject| Value::String(subject.label.clone())),
|
||||
KnowledgeSource::Witnessed | KnowledgeSource::Evidenced => Value::Null,
|
||||
}
|
||||
}
|
||||
|
||||
fn typed_knowledge(&self) -> Vec<Value> {
|
||||
self.subject
|
||||
.knowledge
|
||||
.iter()
|
||||
.filter_map(|event| event.invocation.speech.as_ref().map(|text| (event, text)))
|
||||
.map(|(event, text)| {
|
||||
let speaker = self
|
||||
.snapshot
|
||||
.subjects
|
||||
.iter()
|
||||
.find(|subject| subject.id == event.scope.subject_id)
|
||||
.map(|subject| subject.label.as_str())
|
||||
.ok_or_else(|| {
|
||||
ControllerError::Serialization(
|
||||
"visible event speaker is absent from the canonical snapshot".into(),
|
||||
)
|
||||
})?;
|
||||
Ok(json!({
|
||||
"speaker": speaker,
|
||||
"text": text.as_str(),
|
||||
}))
|
||||
.map(|entry| {
|
||||
json!({
|
||||
"fact": entry.fact,
|
||||
"statement": entry.statement.as_str(),
|
||||
"standing": match entry.standing {
|
||||
FactStandingView::Canonical => json!({"standing": "canonical"}),
|
||||
FactStandingView::Claimed { by } => {
|
||||
json!({"standing": "claimed", "by": by})
|
||||
}
|
||||
},
|
||||
"confidence": entry.confidence,
|
||||
"source": entry.source,
|
||||
"spoken_at": entry.spoken_at,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Only the channels this subject controls, by id. Who else is in reach is a
|
||||
/// question about other subjects, so no reach set is carried.
|
||||
fn typed_channels(&self) -> Vec<Value> {
|
||||
self.subject
|
||||
.controls
|
||||
.iter()
|
||||
.map(|channel| json!({"id": channel}))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The narrative lane speaks and does nothing else, so it finds its entry by
|
||||
|
|
@ -2799,7 +2824,7 @@ fn speak_invocation(
|
|||
.iter()
|
||||
.find(|entry| entry.entry.kind.0 == SPEAK_KIND)
|
||||
.ok_or(ControllerError::SpeakUnavailable)?;
|
||||
let speech = Utterance::new(text).ok_or_else(|| {
|
||||
let speech = Statement::new(text).ok_or_else(|| {
|
||||
ControllerError::Serialization("Persona proposal is not canonical utterance text".into())
|
||||
})?;
|
||||
Ok(DecisionInvocation {
|
||||
|
|
@ -3672,7 +3697,7 @@ fn decode_catalog_call(
|
|||
.get("text")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| "`text` is missing or not a string".to_owned())?;
|
||||
Some(Utterance::new(text).ok_or_else(|| "`text` is not canonical".to_owned())?)
|
||||
Some(Statement::new(text).ok_or_else(|| "`text` is not canonical".to_owned())?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
|
@ -3745,7 +3770,7 @@ mod tests {
|
|||
}
|
||||
use crate::world::{
|
||||
AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, ControllerId, CreateWorld,
|
||||
DecisionScope, Declaration, DraftHandle, EventId, NewController, PrincipalId, ScopeDigest,
|
||||
DecisionScope, Declaration, DraftHandle, NewController, PrincipalId, ScopeDigest,
|
||||
SubjectDeclaration, SubjectKind, WorldId, WorldPatch, WorldPhase,
|
||||
};
|
||||
use std::{
|
||||
|
|
@ -3910,6 +3935,10 @@ mod tests {
|
|||
controller_mode: ControllerMode::NarrativePersona,
|
||||
affordance_ids: vec![speak_affordance],
|
||||
};
|
||||
// Mara was told. Iris also holds a fact of her own that Mara was never
|
||||
// told, and no surface of Mara's may carry it.
|
||||
let heard = EntityId::issue();
|
||||
let unheard = EntityId::issue();
|
||||
let actor = SubjectSnapshot {
|
||||
id: actor_id,
|
||||
label: "Mara at the rain gate".into(),
|
||||
|
|
@ -3926,6 +3955,18 @@ mod tests {
|
|||
offices_held: Vec::new(),
|
||||
offices_granted: Vec::new(),
|
||||
redress: Vec::new(),
|
||||
knowledge: vec![KnowledgeSnapshot {
|
||||
fact: heard,
|
||||
statement: Statement::new("The lower hinge is flooding.").unwrap(),
|
||||
standing: FactStandingView::Claimed { by: speaker_id },
|
||||
confidence: Confidence::Believed,
|
||||
source: KnowledgeSource::Told {
|
||||
by: speaker_id,
|
||||
via: None,
|
||||
},
|
||||
spoken_at: Some(40),
|
||||
}],
|
||||
controls: BTreeSet::new(),
|
||||
};
|
||||
let speaker = SubjectSnapshot {
|
||||
id: speaker_id,
|
||||
|
|
@ -3943,6 +3984,15 @@ mod tests {
|
|||
offices_held: Vec::new(),
|
||||
offices_granted: Vec::new(),
|
||||
redress: Vec::new(),
|
||||
knowledge: vec![KnowledgeSnapshot {
|
||||
fact: unheard,
|
||||
statement: Statement::new("The tollhouse ledger is short.").unwrap(),
|
||||
standing: FactStandingView::Canonical,
|
||||
confidence: Confidence::Certain,
|
||||
source: KnowledgeSource::Witnessed,
|
||||
spoken_at: None,
|
||||
}],
|
||||
controls: BTreeSet::new(),
|
||||
};
|
||||
let snapshot = WorldSnapshot {
|
||||
world_id: opportunity.world_id,
|
||||
|
|
@ -3957,22 +4007,6 @@ mod tests {
|
|||
places: Vec::new(),
|
||||
resources: Vec::new(),
|
||||
routes: Vec::new(),
|
||||
events: vec![crate::world::DecisionEvent {
|
||||
id: EventId::for_command(CommandId::new()),
|
||||
revision: 40,
|
||||
scope: DecisionScope {
|
||||
subject_id: speaker_id,
|
||||
},
|
||||
controller_id: speaker_controller,
|
||||
invocation: DecisionInvocation {
|
||||
affordance: AffordanceId::issue(),
|
||||
bindings: Vec::new(),
|
||||
proposed: Vec::new(),
|
||||
speech: Some(Utterance::new("The lower hinge is flooding.").unwrap()),
|
||||
},
|
||||
band: 0,
|
||||
effects: Vec::new(),
|
||||
}],
|
||||
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()),
|
||||
|
|
@ -4003,14 +4037,112 @@ mod tests {
|
|||
);
|
||||
}
|
||||
assert!(projector_surface.contains("Mara at the rain gate"));
|
||||
// The speaker's label is resolved because Mara was told by her, and the
|
||||
// statement appears because Mara holds it. Iris's own unheard fact does
|
||||
// not: a subject's view carries its own knowledge and no one else's.
|
||||
assert!(projector_surface.contains("Iris in the tollhouse"));
|
||||
assert!(projector_surface.contains("The lower hinge is flooding."));
|
||||
assert!(!projector_surface.contains("The tollhouse ledger is short."));
|
||||
|
||||
let operational_surface = selected.typed_view().unwrap();
|
||||
assert!(operational_surface.contains("state_digest"));
|
||||
assert!(operational_surface.contains("speaker_subject_id"));
|
||||
assert!(operational_surface.contains("The lower hinge is flooding."));
|
||||
assert!(!operational_surface.contains("The tollhouse ledger is short."));
|
||||
}
|
||||
|
||||
/// Verification 5, second half, over real committed state: a subject
|
||||
/// perceives a speech act if and only if it holds `Knowledge` of that act's
|
||||
/// fact. The speaker speaks in the hall; the listener perceives it, the
|
||||
/// bystander one containment level down does not, the placeless stranger
|
||||
/// does not, and no surface of any of the three carries the utterance bytes
|
||||
/// except the listener's.
|
||||
#[test]
|
||||
fn a_subject_does_not_perceive_speech_it_was_not_in_reach_of() {
|
||||
use crate::world::tests::{auth_principal, command, opportunity_for, owner, speech_world};
|
||||
use crate::world::{
|
||||
AuthenticatedCaller, DecisionInvocation, Role, RoleBinding, Statement, SubmitReceipt,
|
||||
Target, WorldKernel,
|
||||
};
|
||||
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let mut kernel = WorldKernel::create(
|
||||
directory.path().join("world.cc"),
|
||||
crate::world::tests::creation(CommandId::new(), "Leakage"),
|
||||
&auth_principal(owner()),
|
||||
)
|
||||
.expect("a created world")
|
||||
.0;
|
||||
let (speech, active) = speech_world(&mut kernel);
|
||||
let utterance = "The lower hinge is flooding tonight.";
|
||||
let opportunity = opportunity_for(&active, speech.speaker);
|
||||
let caller = CallerId::Controller(opportunity.controller_id);
|
||||
let receipt = kernel
|
||||
.submit(
|
||||
command(
|
||||
&active,
|
||||
CommandId::new(),
|
||||
caller.clone(),
|
||||
CommandBody::ExerciseDecision {
|
||||
opportunity,
|
||||
invocation: DecisionInvocation {
|
||||
affordance: speech.whisper,
|
||||
bindings: vec![RoleBinding {
|
||||
role: Role("target".into()),
|
||||
target: Target::Subject(speech.listener),
|
||||
}],
|
||||
proposed: Vec::new(),
|
||||
speech: Some(Statement::new(utterance).unwrap()),
|
||||
},
|
||||
},
|
||||
),
|
||||
&AuthenticatedCaller::fixture(caller),
|
||||
)
|
||||
.expect("the whisper commits");
|
||||
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
|
||||
|
||||
let snapshot = kernel.snapshot().unwrap();
|
||||
let surfaces = |subject_id| {
|
||||
let subject = snapshot
|
||||
.subjects
|
||||
.iter()
|
||||
.find(|subject| subject.id == subject_id)
|
||||
.expect("the subject")
|
||||
.clone();
|
||||
let opportunity = opportunity_for(&snapshot, subject_id);
|
||||
let granted: Vec<AffordanceSnapshot> = snapshot
|
||||
.affordances
|
||||
.iter()
|
||||
.filter(|entry| subject.affordances.contains(&entry.id))
|
||||
.cloned()
|
||||
.collect();
|
||||
let selected = SelectedDecision {
|
||||
snapshot: snapshot.clone(),
|
||||
subject,
|
||||
opportunity,
|
||||
granted,
|
||||
};
|
||||
format!(
|
||||
"{}\n{}\n{}",
|
||||
selected.projector_context().unwrap(),
|
||||
selected.visible_stimulus().unwrap(),
|
||||
selected.typed_view().unwrap(),
|
||||
)
|
||||
};
|
||||
|
||||
assert!(surfaces(speech.listener).contains(utterance));
|
||||
for deaf in [speech.bystander, speech.stranger, speech.speaker] {
|
||||
assert!(
|
||||
!surfaces(deaf).contains(utterance),
|
||||
"a subject perceived speech it holds no knowledge of"
|
||||
);
|
||||
}
|
||||
// The listener sees who told it, and nothing about anyone else's
|
||||
// knowledge, holdings, or position.
|
||||
let heard = surfaces(speech.listener);
|
||||
assert!(heard.contains("The Hall Speaker"));
|
||||
assert!(!heard.contains("The Yard Bystander"));
|
||||
assert!(!heard.contains("The Placeless Stranger"));
|
||||
}
|
||||
/// Soul falsification: the typed view carries the acting subject's own place
|
||||
/// and the routes incident to it, and no more. Another subject's position
|
||||
/// and a route that touches neither endpoint stay out of the surface.
|
||||
|
|
@ -4066,6 +4198,8 @@ mod tests {
|
|||
offices_held: Vec::new(),
|
||||
offices_granted: Vec::new(),
|
||||
redress: Vec::new(),
|
||||
knowledge: Vec::new(),
|
||||
controls: BTreeSet::new(),
|
||||
};
|
||||
let other = SubjectSnapshot {
|
||||
id: other_id,
|
||||
|
|
@ -4083,6 +4217,8 @@ mod tests {
|
|||
offices_held: Vec::new(),
|
||||
offices_granted: Vec::new(),
|
||||
redress: Vec::new(),
|
||||
knowledge: Vec::new(),
|
||||
controls: BTreeSet::new(),
|
||||
};
|
||||
let named_place = |id, label: &str| PlaceSnapshot {
|
||||
id,
|
||||
|
|
@ -4118,7 +4254,6 @@ mod tests {
|
|||
named_route(first_edge, "The Yard Ramp", yard, road),
|
||||
named_route(second_edge, "The Vault Stair", road, vault),
|
||||
],
|
||||
events: Vec::new(),
|
||||
opportunities: vec![opportunity.clone()],
|
||||
state_digest: "sha256:state".into(),
|
||||
last_commit_digest: None,
|
||||
|
|
@ -4660,14 +4795,25 @@ mod tests {
|
|||
owner: owner.clone(),
|
||||
title: "Controller Fixture".into(),
|
||||
patch: WorldPatch {
|
||||
declarations: vec![Declaration::Subject(SubjectDeclaration {
|
||||
handle: DraftHandle::new("subject"),
|
||||
label: "Subject".into(),
|
||||
kind: SubjectKind::Person,
|
||||
controller,
|
||||
affordances: kernel_speak_grant(),
|
||||
position: None,
|
||||
})],
|
||||
declarations: vec![
|
||||
Declaration::Entity(crate::world::EntityDeclaration {
|
||||
handle: DraftHandle::new("commons"),
|
||||
label: "The Commons".into(),
|
||||
kind: EntityKind::Place,
|
||||
container: None,
|
||||
}),
|
||||
Declaration::Subject(SubjectDeclaration {
|
||||
handle: DraftHandle::new("subject"),
|
||||
label: "Subject".into(),
|
||||
kind: SubjectKind::Person,
|
||||
controller,
|
||||
affordances: kernel_speak_grant(),
|
||||
// Speech needs a room to fill.
|
||||
position: Some(crate::world::Ref::Draft(DraftHandle::new(
|
||||
"commons",
|
||||
))),
|
||||
}),
|
||||
],
|
||||
operations: Vec::new(),
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
|
|
@ -4816,7 +4962,7 @@ mod tests {
|
|||
replayed.submission,
|
||||
SubmissionDisposition::PreviouslyConfirmed(_)
|
||||
));
|
||||
assert_eq!(mailbox.snapshot().await.unwrap().events.len(), 1);
|
||||
assert_eq!(mailbox.operator_log().await.unwrap().len(), 1);
|
||||
drop(runner);
|
||||
drop(mailbox);
|
||||
task.await.unwrap();
|
||||
|
|
@ -4875,7 +5021,7 @@ mod tests {
|
|||
replayed.submission,
|
||||
SubmissionDisposition::PreviouslyConfirmed(_)
|
||||
));
|
||||
assert_eq!(mailbox.snapshot().await.unwrap().events.len(), 1);
|
||||
assert_eq!(mailbox.operator_log().await.unwrap().len(), 1);
|
||||
drop(runner);
|
||||
drop(mailbox);
|
||||
task.await.unwrap();
|
||||
|
|
@ -4943,7 +5089,7 @@ mod tests {
|
|||
assert_eq!(applied.resulting_revision, opportunity.revision + 1);
|
||||
let after = mailbox.snapshot().await.unwrap();
|
||||
assert_eq!(after.revision, opportunity.revision + 1);
|
||||
assert!(after.events.is_empty());
|
||||
assert!(mailbox.operator_log().await.unwrap().is_empty());
|
||||
let refreshed = after.opportunities[0].clone();
|
||||
assert_ne!(refreshed, opportunity);
|
||||
assert_eq!(refreshed.scope_digest, opportunity.scope_digest);
|
||||
|
|
@ -5032,7 +5178,7 @@ mod tests {
|
|||
assert_eq!(applied.resulting_revision, opportunity.revision + 1);
|
||||
let after = mailbox.snapshot().await.unwrap();
|
||||
assert_eq!(after.revision, opportunity.revision + 1);
|
||||
assert!(after.events.is_empty());
|
||||
assert!(mailbox.operator_log().await.unwrap().is_empty());
|
||||
|
||||
let OperationalRun::Completed(replayed) = runner
|
||||
.run_operational(command_id, &opportunity)
|
||||
|
|
@ -5204,16 +5350,9 @@ mod tests {
|
|||
derive_narrative_capture(turn, interpreter_prompt, completed).unwrap(),
|
||||
captured
|
||||
);
|
||||
let snapshot = mailbox.snapshot().await.unwrap();
|
||||
assert_eq!(snapshot.events.len(), 1);
|
||||
assert_eq!(
|
||||
snapshot.events[0]
|
||||
.invocation
|
||||
.speech
|
||||
.as_ref()
|
||||
.map(Utterance::as_str),
|
||||
Some(speech)
|
||||
);
|
||||
let log = mailbox.operator_log().await.unwrap();
|
||||
assert_eq!(log.len(), 1);
|
||||
assert_eq!(log[0].speech.as_ref().map(Statement::as_str), Some(speech));
|
||||
|
||||
drop(reopened_terminal);
|
||||
drop(mailbox);
|
||||
|
|
@ -5374,7 +5513,7 @@ mod tests {
|
|||
affordance: human_speak,
|
||||
bindings: Vec::new(),
|
||||
proposed: Vec::new(),
|
||||
speech: Some(Utterance::new(seed).unwrap()),
|
||||
speech: Some(Statement::new(seed).unwrap()),
|
||||
},
|
||||
},
|
||||
},
|
||||
|
|
@ -5395,8 +5534,9 @@ mod tests {
|
|||
.unwrap();
|
||||
|
||||
snapshot = mailbox.snapshot().await.unwrap();
|
||||
assert!(snapshot.events.len() == 1);
|
||||
let seeded_text = snapshot.events[0].invocation.speech.as_ref().unwrap();
|
||||
let log = mailbox.operator_log().await.unwrap();
|
||||
assert!(log.len() == 1);
|
||||
let seeded_text = log[0].speech.as_ref().unwrap();
|
||||
assert!(seeded_text.as_str().as_bytes() == seed.as_bytes());
|
||||
let narrative_subject = snapshot
|
||||
.subjects
|
||||
|
|
@ -5495,14 +5635,14 @@ mod tests {
|
|||
assert!(interpreter_speak.source_end_byte == narrative_span.end_byte);
|
||||
|
||||
snapshot = mailbox.snapshot().await.unwrap();
|
||||
assert!(snapshot.events.len() == 2);
|
||||
let log = mailbox.operator_log().await.unwrap();
|
||||
assert!(log.len() == 2);
|
||||
assert!(snapshot.revision == narrative_opportunity.revision + 1);
|
||||
let narrative_event = snapshot
|
||||
.events
|
||||
let narrative_event = log
|
||||
.iter()
|
||||
.find(|event| event.controller_id == narrative_subject.controller_id)
|
||||
.find(|event| event.speaker == narrative_subject.id)
|
||||
.unwrap();
|
||||
let committed_narrative_speech = narrative_event.invocation.speech.as_ref().unwrap();
|
||||
let committed_narrative_speech = narrative_event.speech.as_ref().unwrap();
|
||||
assert!(committed_narrative_speech.as_str().as_bytes() == narrative_speech.as_bytes());
|
||||
|
||||
let operational_subject = snapshot
|
||||
|
|
@ -5567,14 +5707,14 @@ mod tests {
|
|||
assert!(operational_speak.text.as_bytes() == operational_speech.as_bytes());
|
||||
|
||||
snapshot = mailbox.snapshot().await.unwrap();
|
||||
assert!(snapshot.events.len() == 3);
|
||||
let log = mailbox.operator_log().await.unwrap();
|
||||
assert!(log.len() == 3);
|
||||
assert!(snapshot.revision == operational_opportunity.revision + 1);
|
||||
let operational_event = snapshot
|
||||
.events
|
||||
let operational_event = log
|
||||
.iter()
|
||||
.find(|event| event.controller_id == operational_subject.controller_id)
|
||||
.find(|event| event.speaker == operational_subject.id)
|
||||
.unwrap();
|
||||
let committed_operational_speech = operational_event.invocation.speech.as_ref().unwrap();
|
||||
let committed_operational_speech = operational_event.speech.as_ref().unwrap();
|
||||
assert!(committed_operational_speech.as_str().as_bytes() == operational_speech.as_bytes());
|
||||
|
||||
drop(runner);
|
||||
|
|
|
|||
|
|
@ -12,8 +12,8 @@ use std::{
|
|||
};
|
||||
use thiserror::Error;
|
||||
|
||||
const STATE_ROW: &str = "world_state.authority.v1";
|
||||
const COMMIT_ROW: &str = "world_commit.authority.v1";
|
||||
const STATE_ROW: &str = "world_state.knowledge.v1";
|
||||
const COMMIT_ROW: &str = "world_commit.knowledge.v1";
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub(super) enum JournalError {
|
||||
|
|
@ -527,6 +527,80 @@ fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> {
|
|||
));
|
||||
}
|
||||
}
|
||||
// Facts, channels, and knowledge. The `facts`/`channels` bijections run both
|
||||
// ways: a payload row without its entity, or an entity of that kind without
|
||||
// its payload, is a referenceable half-thing.
|
||||
for (entity_id, record) in &state.facts {
|
||||
let standing_is_live = match &record.standing {
|
||||
super::FactStanding::Canonical { evidence } => {
|
||||
super::patch::is_canonical_text(evidence.text())
|
||||
}
|
||||
super::FactStanding::Claimed { by } => state.subjects.contains_key(by),
|
||||
};
|
||||
if !state
|
||||
.entities
|
||||
.get(entity_id)
|
||||
.is_some_and(|entity| entity.kind == super::EntityKind::Fact)
|
||||
|| !super::patch::is_canonical_text(record.statement.as_str())
|
||||
|| !standing_is_live
|
||||
{
|
||||
return Err(JournalError::Corrupt(
|
||||
"a fact names no canonical entity, statement, or standing".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
for (entity_id, record) in &state.channels {
|
||||
let reach_is_live = match &record.reach {
|
||||
super::Reach::Subjects(members) => members
|
||||
.iter()
|
||||
.all(|subject_id| state.subjects.contains_key(subject_id)),
|
||||
super::Reach::Place(place) => is_place(place),
|
||||
};
|
||||
if !state
|
||||
.entities
|
||||
.get(entity_id)
|
||||
.is_some_and(|entity| entity.kind == super::EntityKind::Channel)
|
||||
|| !reach_is_live
|
||||
|| !record
|
||||
.controller
|
||||
.is_none_or(|subject_id| state.subjects.contains_key(&subject_id))
|
||||
{
|
||||
return Err(JournalError::Corrupt(
|
||||
"a channel names no canonical entity, reach, or controller".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
for (entity_id, entity) in &state.entities {
|
||||
let paired = match entity.kind {
|
||||
super::EntityKind::Fact => state.facts.contains_key(entity_id),
|
||||
super::EntityKind::Channel => state.channels.contains_key(entity_id),
|
||||
super::EntityKind::Place | super::EntityKind::Resource => true,
|
||||
};
|
||||
if !paired {
|
||||
return Err(JournalError::Corrupt(
|
||||
"a fact or channel entity carries no payload row".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
for (subject_id, held) in &state.knowledge {
|
||||
let entry_is_live = |entry: &super::Knowledge| match entry.source {
|
||||
super::KnowledgeSource::Told { by, via } => {
|
||||
state.subjects.contains_key(&by)
|
||||
&& via.is_none_or(|channel| state.channels.contains_key(&channel))
|
||||
}
|
||||
super::KnowledgeSource::Witnessed | super::KnowledgeSource::Evidenced => true,
|
||||
};
|
||||
if !state.subjects.contains_key(subject_id)
|
||||
|| held.is_empty()
|
||||
|| held
|
||||
.iter()
|
||||
.any(|(fact, entry)| !state.facts.contains_key(fact) || !entry_is_live(entry))
|
||||
{
|
||||
return Err(JournalError::Corrupt(
|
||||
"knowledge does not name a canonical subject, fact, and source".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
|
||||
|
|
@ -663,6 +737,7 @@ fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> {
|
|||
));
|
||||
}
|
||||
let mut event_ids = BTreeSet::new();
|
||||
let mut claimed = BTreeSet::new();
|
||||
let mut previous_event_revision = 0;
|
||||
for event in &state.events {
|
||||
let assignment = state
|
||||
|
|
@ -671,8 +746,19 @@ fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> {
|
|||
.ok_or_else(|| JournalError::Corrupt("event references an unknown scope".into()))?;
|
||||
let entry = state
|
||||
.affordance_catalog
|
||||
.get(&event.invocation.affordance)
|
||||
.get(&event.affordance)
|
||||
.ok_or_else(|| JournalError::Corrupt("event uses an unknown affordance".into()))?;
|
||||
// A speech event names the claim it minted, and that claim is asserted
|
||||
// by the acting subject and by no other event.
|
||||
let speech_is_canonical = event.speech.is_none_or(|fact| {
|
||||
claimed.insert(fact)
|
||||
&& state.facts.get(&fact).is_some_and(|record| {
|
||||
record.standing
|
||||
== super::FactStanding::Claimed {
|
||||
by: event.scope.subject_id,
|
||||
}
|
||||
})
|
||||
});
|
||||
if !event_ids.insert(event.id)
|
||||
|| event.revision == 0
|
||||
|| event.revision > state.revision
|
||||
|
|
@ -681,9 +767,15 @@ fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> {
|
|||
|| !state
|
||||
.affordance_grants
|
||||
.get(&event.scope)
|
||||
.is_some_and(|granted| granted.contains(&event.invocation.affordance))
|
||||
.is_some_and(|granted| granted.contains(&event.affordance))
|
||||
|| event.band >= entry.outcome_bands.len()
|
||||
|| (entry.outcome_bands[event.band].effects.is_empty() && !event.effects.is_empty())
|
||||
|| event.speech.is_some() != entry.carries_speech
|
||||
// One lowered operation per band effect, plus the two the speech
|
||||
// lowering prepends.
|
||||
|| entry.outcome_bands[event.band].effects.len()
|
||||
+ if event.speech.is_some() { 2 } else { 0 }
|
||||
!= event.effects.len()
|
||||
|| !speech_is_canonical
|
||||
{
|
||||
return Err(JournalError::Corrupt(
|
||||
"decision event is noncanonical or violates controller scope".into(),
|
||||
|
|
@ -1758,7 +1850,12 @@ mod custody_tests {
|
|||
panic!("expected an applied invocation");
|
||||
};
|
||||
let accepted = kernel.snapshot().unwrap();
|
||||
let committed = accepted.events.last().expect("the committed event").clone();
|
||||
let committed = kernel
|
||||
.state
|
||||
.events
|
||||
.last()
|
||||
.expect("the committed event")
|
||||
.clone();
|
||||
assert!(!committed.effects.is_empty());
|
||||
let world_id = accepted.world_id;
|
||||
drop(kernel);
|
||||
|
|
@ -1766,12 +1863,7 @@ mod custody_tests {
|
|||
let mut reopened = WorldKernel::open(&path, world_id).unwrap();
|
||||
assert_eq!(reopened.snapshot().unwrap(), accepted);
|
||||
assert_eq!(
|
||||
reopened
|
||||
.snapshot()
|
||||
.unwrap()
|
||||
.events
|
||||
.last()
|
||||
.expect("the replayed event"),
|
||||
reopened.state.events.last().expect("the replayed event"),
|
||||
&committed
|
||||
);
|
||||
assert_eq!(
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
use super::{
|
||||
AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, CommandId, CreateWorld,
|
||||
CreateWorldIntent, CreationReceipt, DecisionInvocation, DecisionOpportunity, Declaration,
|
||||
DraftHandle, KernelError, NewController, PrincipalCommandIntent, PrincipalId,
|
||||
SubjectDeclaration, SubjectKind, SubmitReceipt, WorldKernel, WorldPatch, WorldSnapshot,
|
||||
journal, patch::kernel_speak_grant, prepare_creation,
|
||||
DraftHandle, EntityDeclaration, EntityKind, KernelError, NewController, OperatorEvent,
|
||||
PrincipalCommandIntent, PrincipalId, Ref, SubjectDeclaration, SubjectKind, SubmitReceipt,
|
||||
WorldKernel, WorldPatch, WorldSnapshot, journal, patch::kernel_speak_grant, prepare_creation,
|
||||
};
|
||||
use crate::app_session::VerifiedPrincipalEvidence;
|
||||
use std::path::Path;
|
||||
|
|
@ -11,6 +11,10 @@ use thiserror::Error;
|
|||
use tokio::sync::{mpsc, oneshot};
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
/// The one place a world starts with, so its first subjects can hear each
|
||||
/// other. A world that wants more declares them through the patch lane.
|
||||
const GENESIS_PLACE: &str = "commons";
|
||||
|
||||
const REQUEST_CAPACITY: usize = 32;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
|
|
@ -48,6 +52,11 @@ enum Request {
|
|||
Snapshot {
|
||||
reply: oneshot::Sender<Result<WorldSnapshot, KernelError>>,
|
||||
},
|
||||
/// The human operator's story feed. Separate from `Snapshot` so no
|
||||
/// controller lane can reach an unscoped event log.
|
||||
OperatorLog {
|
||||
reply: oneshot::Sender<Result<Vec<OperatorEvent>, KernelError>>,
|
||||
},
|
||||
ControllerReceipt {
|
||||
command_id: CommandId,
|
||||
opportunity: super::DecisionOpportunity,
|
||||
|
|
@ -92,6 +101,9 @@ impl WorldMailbox {
|
|||
let principal_id = PrincipalId::new(principal.account_subject_hash());
|
||||
// Ingress owns label normalization; the reducer only admits canonical
|
||||
// labels.
|
||||
// A world needs a room. Co-located speech fills the place its speaker
|
||||
// stands in, so ingress declares one and stands every genesis subject
|
||||
// there rather than creating a world where nobody can be heard.
|
||||
let declare = |handle: &str, label: String, kind, controller| {
|
||||
Declaration::Subject(SubjectDeclaration {
|
||||
handle: DraftHandle::new(handle),
|
||||
|
|
@ -99,17 +111,25 @@ impl WorldMailbox {
|
|||
kind,
|
||||
controller,
|
||||
affordances: kernel_speak_grant(),
|
||||
position: None,
|
||||
position: Some(Ref::Draft(DraftHandle::new(GENESIS_PLACE))),
|
||||
})
|
||||
};
|
||||
let mut declarations = vec![declare(
|
||||
"first-person",
|
||||
input.human_subject_label,
|
||||
SubjectKind::Person,
|
||||
NewController::Human {
|
||||
principal: principal_id.clone(),
|
||||
},
|
||||
)];
|
||||
let mut declarations = vec![
|
||||
Declaration::Entity(EntityDeclaration {
|
||||
handle: DraftHandle::new(GENESIS_PLACE),
|
||||
label: "The Commons".into(),
|
||||
kind: EntityKind::Place,
|
||||
container: None,
|
||||
}),
|
||||
declare(
|
||||
"first-person",
|
||||
input.human_subject_label,
|
||||
SubjectKind::Person,
|
||||
NewController::Human {
|
||||
principal: principal_id.clone(),
|
||||
},
|
||||
),
|
||||
];
|
||||
if let Some(label) = input.narrative_persona_label {
|
||||
declarations.push(declare(
|
||||
"narrative-persona",
|
||||
|
|
@ -306,6 +326,21 @@ impl WorldMailbox {
|
|||
.await
|
||||
}
|
||||
|
||||
/// The human operator's story feed. It is not a perception surface, and no
|
||||
/// controller lane calls it.
|
||||
pub(crate) async fn operator_log(&self) -> Result<Vec<OperatorEvent>, MailboxError> {
|
||||
let (reply, response) = oneshot::channel();
|
||||
self.sender
|
||||
.send(Request::OperatorLog { reply })
|
||||
.await
|
||||
.map_err(|_| MailboxError::Unavailable)?;
|
||||
|
||||
response
|
||||
.await
|
||||
.map_err(|_| MailboxError::Unavailable)?
|
||||
.map_err(MailboxError::Kernel)
|
||||
}
|
||||
|
||||
pub(crate) async fn snapshot(&self) -> Result<WorldSnapshot, MailboxError> {
|
||||
let (reply, response) = oneshot::channel();
|
||||
self.sender
|
||||
|
|
@ -472,6 +507,19 @@ async fn run_owner(mut owned: OwnedWorld, mut receiver: mpsc::Receiver<Request>)
|
|||
return;
|
||||
}
|
||||
}
|
||||
Request::OperatorLog { reply } => {
|
||||
let result = match &owned {
|
||||
OwnedWorld::Empty(_) => Err(KernelError::WorldNotCreated),
|
||||
OwnedWorld::Live(kernel) => kernel.operator_log(),
|
||||
};
|
||||
let owner_must_stop = result
|
||||
.as_ref()
|
||||
.is_err_and(KernelError::requires_owner_restart);
|
||||
let _ = reply.send(result);
|
||||
if owner_must_stop {
|
||||
return;
|
||||
}
|
||||
}
|
||||
Request::ControllerReceipt {
|
||||
command_id,
|
||||
opportunity,
|
||||
|
|
@ -535,16 +583,24 @@ mod tests {
|
|||
owner: PrincipalId::new("owner"),
|
||||
title: title.into(),
|
||||
patch: WorldPatch {
|
||||
declarations: vec![Declaration::Subject(SubjectDeclaration {
|
||||
handle: DraftHandle::new("operator"),
|
||||
label: "Operator".into(),
|
||||
kind: SubjectKind::Person,
|
||||
controller: NewController::Human {
|
||||
principal: PrincipalId::new("owner"),
|
||||
},
|
||||
affordances: kernel_speak_grant(),
|
||||
position: None,
|
||||
})],
|
||||
declarations: vec![
|
||||
Declaration::Entity(EntityDeclaration {
|
||||
handle: DraftHandle::new(GENESIS_PLACE),
|
||||
label: "The Commons".into(),
|
||||
kind: EntityKind::Place,
|
||||
container: None,
|
||||
}),
|
||||
Declaration::Subject(SubjectDeclaration {
|
||||
handle: DraftHandle::new("operator"),
|
||||
label: "Operator".into(),
|
||||
kind: SubjectKind::Person,
|
||||
controller: NewController::Human {
|
||||
principal: PrincipalId::new("owner"),
|
||||
},
|
||||
affordances: kernel_speak_grant(),
|
||||
position: Some(Ref::Draft(DraftHandle::new(GENESIS_PLACE))),
|
||||
}),
|
||||
],
|
||||
operations: Vec::new(),
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
|
|
@ -627,7 +683,7 @@ mod tests {
|
|||
invalid
|
||||
.patch
|
||||
.declarations
|
||||
.push(invalid.patch.declarations[0].clone());
|
||||
.push(invalid.patch.declarations[1].clone());
|
||||
let Err(MailboxError::Kernel(KernelError::PatchRejected(rejected))) =
|
||||
mailbox.create_fixture(invalid, &authenticated).await
|
||||
else {
|
||||
|
|
@ -919,6 +975,8 @@ mod tests {
|
|||
let (mailbox, _task) = WorldMailbox::open(directory.path().join("world.cc")).unwrap();
|
||||
let owner = PrincipalId::new("owner");
|
||||
let authenticated = authenticated_owner();
|
||||
// Two rooms, not one: a telling reaches its own room, so the bound
|
||||
// subject must stand somewhere the unrelated speaker does not.
|
||||
let declare = |handle: &str, label: &str, controller: NewController| {
|
||||
Declaration::Subject(SubjectDeclaration {
|
||||
handle: DraftHandle::new(handle),
|
||||
|
|
@ -926,7 +984,15 @@ mod tests {
|
|||
kind: SubjectKind::Person,
|
||||
controller,
|
||||
affordances: kernel_speak_grant(),
|
||||
position: None,
|
||||
position: Some(Ref::Draft(DraftHandle::new(format!("room-{handle}")))),
|
||||
})
|
||||
};
|
||||
let room = |handle: &str| {
|
||||
Declaration::Entity(EntityDeclaration {
|
||||
handle: DraftHandle::new(format!("room-{handle}")),
|
||||
label: format!("The {handle} room"),
|
||||
kind: EntityKind::Place,
|
||||
container: None,
|
||||
})
|
||||
};
|
||||
let created = mailbox
|
||||
|
|
@ -937,6 +1003,8 @@ mod tests {
|
|||
title: "Soul Stamping".into(),
|
||||
patch: WorldPatch {
|
||||
declarations: vec![
|
||||
room("witness"),
|
||||
room("council"),
|
||||
declare("witness", "The Witness", NewController::NarrativePersona),
|
||||
declare("council", "The Council", NewController::OperationalAgent),
|
||||
],
|
||||
|
|
@ -980,7 +1048,7 @@ mod tests {
|
|||
affordance: opportunity.affordance_ids[0],
|
||||
bindings: Vec::new(),
|
||||
proposed: Vec::new(),
|
||||
speech: Some(crate::world::Utterance::new(text).unwrap()),
|
||||
speech: Some(crate::world::Statement::new(text).unwrap()),
|
||||
};
|
||||
mailbox
|
||||
.submit_controller(
|
||||
|
|
@ -1047,7 +1115,7 @@ mod tests {
|
|||
affordance: forged.affordance_ids[0],
|
||||
bindings: Vec::new(),
|
||||
proposed: Vec::new(),
|
||||
speech: Some(crate::world::Utterance::new("Let me in.").unwrap()),
|
||||
speech: Some(crate::world::Statement::new("Let me in.").unwrap()),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
Loading…
Reference in a new issue