Aetherlight AL2a.1: delete the lens lane and the Ghostlight golden fixture
Remove lens.rs, LensWeights in genesis input, WorldState, snapshot and creation, SetLensWeights, LensWeightsReplaced, LensWeightsNeverDraw and the draw-rule shape check. The journal's lens replay tests are rewritten over an owner AdvanceTime history (replays exactly; a forged caller fails replay). The state shape changed, so Ghostlight's base_world fixture no longer decodes: the golden replay test and its three fixtures go (AL4 adds Aetherlight's own). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
6ef5f51a42
commit
10f487dc16
10 changed files with 50 additions and 939 deletions
|
|
@ -172,7 +172,6 @@ pub(super) fn exercise(
|
|||
evidence: Vec::new(),
|
||||
},
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.map_err(KernelError::PatchRejected)?
|
||||
.operations
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ use crate::patch::{
|
|||
use crate::tests::{auth_principal, command, creation, owner};
|
||||
use crate::{
|
||||
CallerId, CommandBody, CommandId, CreateWorld, KernelError, SubjectKind, SubmitReceipt,
|
||||
WorldId, WorldKernel, WorldPatch,
|
||||
WorldKernel, WorldPatch,
|
||||
};
|
||||
|
||||
fn verb(path: RenderPath, roles: &[(&str, GrammarReferentKind)]) -> GrammarVerb {
|
||||
|
|
@ -484,34 +484,6 @@ fn a_grammar_names_each_verb_once_and_has_a_schema() {
|
|||
);
|
||||
}
|
||||
|
||||
/// The fixture world was written by the code at base 367e2eb, which has no
|
||||
/// grammar field anywhere. Reopening it must reproduce the digests that code
|
||||
/// recorded.
|
||||
#[test]
|
||||
fn existing_world_reopens_with_unchanged_digests() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("world.cc");
|
||||
std::fs::write(&path, include_bytes!("../../tests/fixtures/base_world.cc")).unwrap();
|
||||
let world_id: WorldId =
|
||||
serde_json::from_str(include_str!("../../tests/fixtures/base_world.id").trim()).unwrap();
|
||||
let kernel = WorldKernel::open(&path, world_id).expect("a base-written world reopens");
|
||||
let snapshot = kernel.snapshot().unwrap();
|
||||
let recorded = include_str!("../../tests/fixtures/base_world.digests");
|
||||
let mut lines = recorded.lines();
|
||||
assert_eq!(snapshot.revision.to_string(), lines.next().unwrap());
|
||||
assert_eq!(snapshot.state_digest, lines.next().unwrap());
|
||||
assert_eq!(
|
||||
snapshot.last_commit_digest.as_deref(),
|
||||
Some(lines.next().unwrap())
|
||||
);
|
||||
assert!(snapshot.grammar.is_none());
|
||||
// Its state still derives the recorded digest from its bytes.
|
||||
assert_eq!(
|
||||
crate::state_digest(&kernel.state).unwrap(),
|
||||
snapshot.state_digest
|
||||
);
|
||||
}
|
||||
|
||||
fn submit_as(
|
||||
kernel: &mut WorldKernel,
|
||||
caller: CallerId,
|
||||
|
|
@ -711,7 +683,6 @@ fn an_effect_resolved_elsewhere_cannot_install_an_entry_outside_the_grammar() {
|
|||
CommandId::new(),
|
||||
&patch_of(vec![declare("probe", kind, roles)]),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.expect("the unbound twin admits any canonical kind")
|
||||
};
|
||||
|
|
|
|||
|
|
@ -463,7 +463,6 @@ fn the_subjects_map_refuses_a_second_subject_for_one_key_even_when_resolved_else
|
|||
place,
|
||||
)]),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.expect("the key is unheld at the revision both were resolved against")
|
||||
};
|
||||
|
|
@ -680,7 +679,6 @@ fn admitting_a_resolved_effect_refuses_two_subjects_with_one_key() {
|
|||
mirror("second", Some(key("aetheria.ship", "Gamma")), place),
|
||||
]),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.expect("two distinct keys resolve")
|
||||
};
|
||||
|
|
|
|||
|
|
@ -759,11 +759,6 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError>
|
|||
"the scale intent names a non-place root or distributes more than the whole".into(),
|
||||
));
|
||||
}
|
||||
// The third statement of the draw rule, beside genesis and
|
||||
// `SetLensWeights`: no stored world holds weights that never draw.
|
||||
if !state.lens_weights.draws() {
|
||||
return Err(JournalError::Corrupt("the lens weights never draw".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
|
||||
|
|
@ -1109,7 +1104,6 @@ mod tests {
|
|||
let owner = PrincipalId::new("owner@example.test");
|
||||
let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone()));
|
||||
let creation = CreateWorld {
|
||||
lens_weights: crate::tests::stock_weights(),
|
||||
id: CommandId::new(),
|
||||
owner: owner.clone(),
|
||||
title: "Before".into(),
|
||||
|
|
@ -1194,7 +1188,6 @@ mod tests {
|
|||
let owner = PrincipalId::new("owner@example.test");
|
||||
let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone()));
|
||||
let creation = CreateWorld {
|
||||
lens_weights: crate::tests::stock_weights(),
|
||||
id: CommandId::new(),
|
||||
owner: owner.clone(),
|
||||
title: "Kharad".into(),
|
||||
|
|
@ -1319,11 +1312,10 @@ mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
/// Lens weights entered both rows — the state row holds them and a commit
|
||||
/// row carries `LensWeightsReplaced` — so both schemas bumped and both
|
||||
/// `consumer.v4` strings are refused at open. No migration, no dual read.
|
||||
/// A store written under an older schema is refused at open: both
|
||||
/// `consumer.v4` strings. No migration, no dual read.
|
||||
#[test]
|
||||
fn a_store_written_before_the_lens_schema_is_refused() {
|
||||
fn a_store_written_under_an_older_schema_is_refused() {
|
||||
for (row_type, schema) in [
|
||||
(STATE_ROW, "ghostlight.world_state.consumer.v4"),
|
||||
(COMMIT_ROW, "ghostlight.world_commit.consumer.v4"),
|
||||
|
|
@ -1346,34 +1338,28 @@ mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
/// A world whose history includes an owner's `SetLensWeights`, reopened
|
||||
/// from its own store rows.
|
||||
fn lens_history() -> (tempfile::TempDir, WorldKernel, crate::LensWeights) {
|
||||
use crate::tests::{auth_principal, creation, owner, submit_owner};
|
||||
use crate::{Lens, LensWeights};
|
||||
/// A world whose history includes an owner's clock advance, reopened from
|
||||
/// its own store rows.
|
||||
fn clock_history() -> (tempfile::TempDir, WorldKernel) {
|
||||
use crate::tests::{activate, auth_principal, creation, owner, submit_owner};
|
||||
use crate::TickMinutes;
|
||||
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (mut kernel, _) = WorldKernel::create(
|
||||
directory.path().join("world.cc"),
|
||||
creation(CommandId::new(), "Lens History"),
|
||||
creation(CommandId::new(), "Clock History"),
|
||||
&auth_principal(owner()),
|
||||
)
|
||||
.unwrap();
|
||||
let replaced = LensWeights::new(BTreeMap::from([
|
||||
(Lens::Patina, 0),
|
||||
(Lens::Charter, 4),
|
||||
(Lens::Ledger, 1),
|
||||
(Lens::Numen, 2),
|
||||
]));
|
||||
let snapshot = kernel.snapshot().unwrap();
|
||||
let snapshot = activate(&mut kernel);
|
||||
submit_owner(
|
||||
&mut kernel,
|
||||
&snapshot,
|
||||
CommandBody::SetLensWeights {
|
||||
weights: replaced.clone(),
|
||||
CommandBody::AdvanceTime {
|
||||
minutes: TickMinutes::new(30).unwrap(),
|
||||
},
|
||||
);
|
||||
(directory, kernel, replaced)
|
||||
(directory, kernel)
|
||||
}
|
||||
|
||||
fn rows_of(state: &WorldState, commits: &[WorldCommit]) -> Vec<CultCacheEnvelope> {
|
||||
|
|
@ -1387,151 +1373,69 @@ mod tests {
|
|||
rows
|
||||
}
|
||||
|
||||
/// Replay re-derives the owner's weight change: the honest history reopens
|
||||
/// to the same state digest and weights, and the store on disk does too.
|
||||
/// Replay re-derives the owner's clock advance: the honest history reopens
|
||||
/// to the same state digest and reading, and the store on disk does too.
|
||||
#[test]
|
||||
fn a_history_with_a_lens_weight_change_replays_exactly() {
|
||||
let (directory, kernel, replaced) = lens_history();
|
||||
fn a_history_with_an_owner_clock_advance_replays_exactly() {
|
||||
let (directory, kernel) = clock_history();
|
||||
let honest: Vec<WorldCommit> = kernel.journal.commits.values().cloned().collect();
|
||||
let (_, replayed, commits) =
|
||||
recover(rows_of(&kernel.state, &honest), None).expect("the honest history replays");
|
||||
assert_eq!(commits.len(), honest.len());
|
||||
assert_eq!(replayed.state_digest, kernel.state.state_digest);
|
||||
assert_eq!(replayed.lens_weights, replaced);
|
||||
assert_eq!(replayed.now, kernel.state.now);
|
||||
|
||||
let (world_id, digest) = (kernel.state.world_id, kernel.state.state_digest.clone());
|
||||
let (world_id, digest, now) =
|
||||
(kernel.state.world_id, kernel.state.state_digest.clone(), kernel.state.now);
|
||||
drop(kernel);
|
||||
let reopened = WorldKernel::open(directory.path().join("world.cc"), world_id).unwrap();
|
||||
assert_eq!(reopened.state.state_digest, digest);
|
||||
assert_eq!(reopened.state.lens_weights, replaced);
|
||||
assert_eq!(reopened.state.now, now);
|
||||
}
|
||||
|
||||
/// A stored weight change is not believed about who made it or what it
|
||||
/// wrote. Each forgery re-seals the whole store around its rewrite: the
|
||||
/// head state takes the effect's weights, its state digest is recomputed,
|
||||
/// the commit's resulting state digest and its own digest follow, and the
|
||||
/// head's last commit digest names the re-sealed commit. No digest can
|
||||
/// answer for the check, which the drawing control proves: the same
|
||||
/// re-sealing around a set that draws replays.
|
||||
/// A stored command is not believed about who made it. The forgery re-seals
|
||||
/// the commit around its rewrite and the head's last commit digest names the
|
||||
/// re-sealed commit, so no digest can answer for the check; the control, the
|
||||
/// same re-sealing around the honest caller, replays.
|
||||
#[test]
|
||||
fn a_forged_lens_weights_row_fails_replay() {
|
||||
fn a_clock_advance_forged_to_another_caller_fails_replay() {
|
||||
use crate::tests::human_principal;
|
||||
use crate::{Lens, LensWeights};
|
||||
|
||||
let (_directory, kernel, _) = lens_history();
|
||||
let (_directory, kernel) = clock_history();
|
||||
let honest: Vec<WorldCommit> = kernel.journal.commits.values().cloned().collect();
|
||||
let forge = |rewrite: &dyn Fn(&mut WorldCommit)| -> (WorldState, Vec<WorldCommit>) {
|
||||
let mut head = kernel.state.clone();
|
||||
let mut forged: Vec<WorldCommit> = honest.clone();
|
||||
let lens_row = forged
|
||||
let clock_row = forged
|
||||
.iter_mut()
|
||||
.filter(|commit| matches!(commit.effect, WorldEffect::LensWeightsReplaced { .. }))
|
||||
.filter(|commit| matches!(commit.effect, WorldEffect::TimeAdvanced { .. }))
|
||||
.collect::<Vec<_>>();
|
||||
let [commit] = <[&mut WorldCommit; 1]>::try_from(lens_row)
|
||||
.expect("the history holds exactly one lens weights row");
|
||||
let [commit] = <[&mut WorldCommit; 1]>::try_from(clock_row)
|
||||
.expect("the history holds exactly one clock row");
|
||||
assert_eq!(
|
||||
commit.resulting_revision, head.revision,
|
||||
"the lens weights row is the head commit"
|
||||
"the clock row is the head commit"
|
||||
);
|
||||
rewrite(commit);
|
||||
let WorldEffect::LensWeightsReplaced { weights } = &commit.effect else {
|
||||
unreachable!("a lens weights row stays one");
|
||||
};
|
||||
head.lens_weights = weights.clone();
|
||||
head.state_digest = crate::state_digest(&head).unwrap();
|
||||
commit.resulting_state_digest = head.state_digest.clone();
|
||||
commit.digest = commit_digest(commit).unwrap();
|
||||
head.last_commit_digest = Some(commit.digest.clone());
|
||||
|
||||
// Every seal agrees with what it seals.
|
||||
assert_eq!(crate::state_digest(&head).unwrap(), head.state_digest);
|
||||
assert_eq!(commit_digest(commit).unwrap(), commit.digest);
|
||||
assert_eq!(commit.resulting_state_digest, head.state_digest);
|
||||
assert_eq!(head.last_commit_digest.as_deref(), Some(commit.digest.as_str()));
|
||||
(head, forged)
|
||||
};
|
||||
let set = |weights: LensWeights| {
|
||||
move |commit: &mut WorldCommit| {
|
||||
if let CommittedCommand::WorldCommand(command) = &mut commit.command {
|
||||
command.body = CommandBody::SetLensWeights {
|
||||
weights: weights.clone(),
|
||||
};
|
||||
}
|
||||
commit.effect = WorldEffect::LensWeightsReplaced {
|
||||
weights: weights.clone(),
|
||||
};
|
||||
}
|
||||
};
|
||||
let refused = |(head, forged): (WorldState, Vec<WorldCommit>)| -> String {
|
||||
let error =
|
||||
recover(rows_of(&head, &forged), None).expect_err("a forged lens weights row replayed");
|
||||
let JournalError::Corrupt(detail) = error else {
|
||||
panic!("unexpected refusal: {error:?}");
|
||||
};
|
||||
detail
|
||||
};
|
||||
|
||||
// The control: a re-sealed store around a different set that draws
|
||||
// replays, so the re-sealing leaves nothing for a digest to catch.
|
||||
let drawing = LensWeights::new(BTreeMap::from([(Lens::Veil, 2), (Lens::Ember, 1)]));
|
||||
let (head, forged) = forge(&set(drawing.clone()));
|
||||
let (_, replayed, _) =
|
||||
recover(rows_of(&head, &forged), None).expect("a consistent re-sealed store replays");
|
||||
assert_eq!(replayed.lens_weights, drawing);
|
||||
let (head, control) = forge(&|_| {});
|
||||
recover(rows_of(&head, &control), None).expect("a consistent re-sealed store replays");
|
||||
|
||||
// A non-owner principal with a live approver role in this world.
|
||||
let detail = refused(forge(&|commit| {
|
||||
let (head, forged) = forge(&|commit| {
|
||||
if let CommittedCommand::WorldCommand(command) = &mut commit.command {
|
||||
command.caller = CallerId::Principal(human_principal());
|
||||
}
|
||||
}));
|
||||
assert!(detail.contains("Unauthorized") || detail.contains("does not own"), "{detail}");
|
||||
// The clock capability.
|
||||
let detail = refused(forge(&|commit| {
|
||||
if let CommittedCommand::WorldCommand(command) = &mut commit.command {
|
||||
command.caller = CallerId::System(crate::SystemCapability::Clock);
|
||||
}
|
||||
}));
|
||||
assert!(detail.contains("Unauthorized") || detail.contains("does not own"), "{detail}");
|
||||
// Every lens named, all at zero, in the command, its effect and the
|
||||
// head: only the draw rule is left to refuse it.
|
||||
let never = LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 0)).collect());
|
||||
let detail = refused(forge(&set(never)));
|
||||
assert!(
|
||||
detail.contains("never draw") || detail.contains("LensWeightsNeverDraw"),
|
||||
"something other than the draw rule refused the all-zero row: {detail}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The third statement of the draw rule: a state row whose weights never
|
||||
/// draw is refused by the shape check itself, not only by replay.
|
||||
#[test]
|
||||
fn a_state_row_whose_lens_weights_never_draw_is_refused() {
|
||||
use crate::{Lens, LensWeights};
|
||||
|
||||
let (_directory, kernel, _) = lens_history();
|
||||
let mut forged = kernel.state.clone();
|
||||
forged.lens_weights =
|
||||
LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 0)).collect());
|
||||
let JournalError::Corrupt(detail) =
|
||||
verify_state_shape(&forged).expect_err("an all-zero weight set passed the shape check")
|
||||
else {
|
||||
unreachable!("the shape check only reports corruption")
|
||||
});
|
||||
let error = recover(rows_of(&head, &forged), None)
|
||||
.expect_err("a clock advance forged to a non-owner replayed");
|
||||
let JournalError::Corrupt(detail) = error else {
|
||||
panic!("unexpected refusal: {error:?}");
|
||||
};
|
||||
assert!(detail.contains("lens weights"), "unexpected refusal: {detail}");
|
||||
|
||||
forged.lens_weights = LensWeights::default();
|
||||
assert!(verify_state_shape(&forged).is_err());
|
||||
assert!(verify_state_shape(&kernel.state).is_ok());
|
||||
|
||||
let commits: Vec<WorldCommit> = kernel.journal.commits.values().cloned().collect();
|
||||
let mut zeroed = kernel.state.clone();
|
||||
zeroed.lens_weights =
|
||||
LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 0)).collect());
|
||||
assert!(matches!(
|
||||
recover(rows_of(&zeroed, &commits), None),
|
||||
Err(JournalError::Corrupt(_))
|
||||
));
|
||||
assert!(detail.contains("Unauthorized") || detail.contains("does not own"), "{detail}");
|
||||
}
|
||||
|
||||
/// The tick is re-derived at replay by the same function that produced it,
|
||||
|
|
@ -1764,7 +1668,6 @@ mod tests {
|
|||
let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone()));
|
||||
let creation_id = CommandId::new();
|
||||
let creation = CreateWorld {
|
||||
lens_weights: crate::tests::stock_weights(),
|
||||
id: creation_id,
|
||||
owner: owner.clone(),
|
||||
title: "Admitted".into(),
|
||||
|
|
|
|||
|
|
@ -1,361 +0,0 @@
|
|||
//! The stock lenses. A lens is the flavor an elaborator session reaches for:
|
||||
//! prompt emphasis over the one fixed tool catalog, never admission, authority,
|
||||
//! or quota. This module owns the stock table, each lens's instruction text,
|
||||
//! and the draw recipe; it reads no world state and writes nothing.
|
||||
|
||||
use super::{CommandId, KernelError, WorldId, digest};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// The sentence every lens's instructions begin with.
|
||||
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.";
|
||||
|
||||
/// The library's stock lens set. Serialized by snake_case name, so a name the
|
||||
/// library does not know cannot be represented at any deserialization boundary.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Lens {
|
||||
Patina,
|
||||
Charter,
|
||||
Ledger,
|
||||
Hearth,
|
||||
Tangle,
|
||||
Veil,
|
||||
Ember,
|
||||
Numen,
|
||||
}
|
||||
|
||||
impl Lens {
|
||||
/// Every lens, in declaration order. The draw walks this order.
|
||||
pub const ALL: [Lens; 8] = [
|
||||
Lens::Patina,
|
||||
Lens::Charter,
|
||||
Lens::Ledger,
|
||||
Lens::Hearth,
|
||||
Lens::Tangle,
|
||||
Lens::Veil,
|
||||
Lens::Ember,
|
||||
Lens::Numen,
|
||||
];
|
||||
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Lens::Patina => "Patina",
|
||||
Lens::Charter => "Charter",
|
||||
Lens::Ledger => "Ledger",
|
||||
Lens::Hearth => "Hearth",
|
||||
Lens::Tangle => "Tangle",
|
||||
Lens::Veil => "Veil",
|
||||
Lens::Ember => "Ember",
|
||||
Lens::Numen => "Numen",
|
||||
}
|
||||
}
|
||||
|
||||
/// What kind of structure the lens reaches for.
|
||||
pub(crate) fn reaches_for(self) -> &'static str {
|
||||
match self {
|
||||
Lens::Patina => "ordinary objects, customs, nicknames, local jokes",
|
||||
Lens::Charter => "government, law, offices, selection, succession, redress",
|
||||
Lens::Ledger => "resources, labor, trade, infrastructure, scarcity, class pressure",
|
||||
Lens::Hearth => "kinship, daily life, care, obligation, belonging",
|
||||
Lens::Tangle => "factions, alliances, rivalries, leverage",
|
||||
Lens::Veil => "secrets, rumors, misinformation, taboos, unevenly held knowledge",
|
||||
Lens::Ember => "disputes, hazards, instability, escalation, urgent pressure",
|
||||
Lens::Numen => "religion, magic, ritual, awe, cosmology, the genuinely strange",
|
||||
}
|
||||
}
|
||||
|
||||
/// Existing patch tool names in emphasis order. Emphasis is prompt text
|
||||
/// only: the catalog, its order, and its schemas are the same for every lens.
|
||||
pub(crate) fn leads_with(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
Lens::Patina => &[
|
||||
"set_persona_material",
|
||||
"declare_affordance",
|
||||
"declare_resource",
|
||||
"declare_place",
|
||||
],
|
||||
Lens::Charter => &[
|
||||
"grant_authority",
|
||||
"open_office",
|
||||
"install_incumbent",
|
||||
"open_forum",
|
||||
"declare_subject",
|
||||
],
|
||||
Lens::Ledger => &[
|
||||
"transfer",
|
||||
"bind",
|
||||
"declare_resource",
|
||||
"alter_cost",
|
||||
"declare_route",
|
||||
],
|
||||
Lens::Hearth => &[
|
||||
"create_commitment",
|
||||
"set_persona_material",
|
||||
"declare_subject",
|
||||
],
|
||||
Lens::Tangle => &[
|
||||
"advance_pressure",
|
||||
"create_commitment",
|
||||
"grant_authority",
|
||||
"declare_subject",
|
||||
"bind",
|
||||
],
|
||||
Lens::Veil => &[
|
||||
"acquire_knowledge",
|
||||
"communicate",
|
||||
"declare_channel",
|
||||
"set_reach",
|
||||
"declare_fact",
|
||||
"forget",
|
||||
],
|
||||
Lens::Ember => &[
|
||||
"advance_pressure",
|
||||
"create_commitment",
|
||||
"close_route",
|
||||
"consume",
|
||||
],
|
||||
Lens::Numen => &[
|
||||
"declare_fact",
|
||||
"declare_affordance",
|
||||
"set_persona_material",
|
||||
"witness",
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/// The elaborator's instructions under this lens: the shared sentence, then
|
||||
/// the lens clause. Read once, when a session is first built; the session
|
||||
/// then carries the text, and nothing rebuilds it from here.
|
||||
pub(crate) fn instructions(self) -> String {
|
||||
format!(
|
||||
"{ELABORATION_INSTRUCTIONS} Lens: {}. Reach for {}. Lead with {}; every supplied tool remains available.",
|
||||
self.name(),
|
||||
self.reaches_for(),
|
||||
self.leads_with().join(", "),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// A world's lens weights. Validity is decided where weights are admitted;
|
||||
/// `Default` is the empty map a world holds before genesis writes its weights,
|
||||
/// and it never draws.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct LensWeights(BTreeMap<Lens, u32>);
|
||||
|
||||
impl LensWeights {
|
||||
pub fn new(weights: BTreeMap<Lens, u32>) -> Self {
|
||||
Self(weights)
|
||||
}
|
||||
|
||||
/// A lens the map does not name weighs zero.
|
||||
pub fn get(&self, lens: Lens) -> u32 {
|
||||
self.0.get(&lens).copied().unwrap_or(0)
|
||||
}
|
||||
|
||||
pub fn iter(&self) -> impl Iterator<Item = (Lens, u32)> + '_ {
|
||||
self.0.iter().map(|(lens, weight)| (*lens, *weight))
|
||||
}
|
||||
|
||||
/// Some weight is nonzero, so a draw has somewhere to land.
|
||||
pub(crate) fn draws(&self) -> bool {
|
||||
self.0.values().any(|weight| *weight > 0)
|
||||
}
|
||||
|
||||
/// Every stock lens weighs the same in both sets. A lens a map does not
|
||||
/// name weighs zero, so `{charter: 3}` and `{patina: 0, charter: 3}` are
|
||||
/// one set spelled two ways: they draw identically and neither replaces
|
||||
/// the other.
|
||||
pub(crate) fn weighs_the_same_as(&self, other: &LensWeights) -> bool {
|
||||
Lens::ALL
|
||||
.into_iter()
|
||||
.all(|lens| self.get(lens) == other.get(lens))
|
||||
}
|
||||
}
|
||||
|
||||
/// The draw's whole input: the world and the session's fixed identity. The
|
||||
/// weights select over it; they are not part of it.
|
||||
#[derive(Serialize)]
|
||||
struct LensPreimage {
|
||||
world_id: WorldId,
|
||||
command_id: CommandId,
|
||||
}
|
||||
|
||||
/// One digest, one modulo, one cumulative walk over `Lens::ALL` — the recipe
|
||||
/// `select_band` uses, not a second entropy shape. The same world, session
|
||||
/// identity, and weights draw the same lens. Modulo rather than rejection
|
||||
/// sampling: the bias is bounded by `total_weight / 2^64`.
|
||||
pub(crate) fn draw(
|
||||
weights: &LensWeights,
|
||||
world_id: WorldId,
|
||||
command_id: CommandId,
|
||||
) -> Result<Lens, KernelError> {
|
||||
// The guard is on the divisor itself, as `select_band`'s is: no other
|
||||
// statement of "these weights draw" can let the modulo below divide by zero.
|
||||
let total: u128 = Lens::ALL
|
||||
.iter()
|
||||
.map(|lens| u128::from(weights.get(*lens)))
|
||||
.sum();
|
||||
if total == 0 {
|
||||
return Err(KernelError::Invariant("lens weights never draw".into()));
|
||||
}
|
||||
let preimage = digest(&LensPreimage {
|
||||
world_id,
|
||||
command_id,
|
||||
})?;
|
||||
let head = preimage
|
||||
.strip_prefix("sha256:")
|
||||
.and_then(|hex| hex.get(..16))
|
||||
.and_then(|head| u64::from_str_radix(head, 16).ok())
|
||||
.ok_or_else(|| KernelError::Invariant("lens draw digest is not hex".into()))?;
|
||||
let mut position = u128::from(head) % total;
|
||||
for lens in Lens::ALL {
|
||||
let weight = u128::from(weights.get(lens));
|
||||
if position < weight {
|
||||
return Ok(lens);
|
||||
}
|
||||
position -= weight;
|
||||
}
|
||||
Err(KernelError::Invariant(
|
||||
"lens weights did not cover the draw".into(),
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::tests::stock_weights;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
fn ids() -> Vec<CommandId> {
|
||||
(0..200)
|
||||
.map(|i| CommandId::derived("l1-probe", &[&i.to_string()]))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn tally(weights: &LensWeights) -> BTreeMap<Lens, usize> {
|
||||
let mut counts = BTreeMap::new();
|
||||
for id in ids() {
|
||||
let lens = draw(weights, WorldId::nil_for_test(), id).unwrap();
|
||||
*counts.entry(lens).or_insert(0) += 1;
|
||||
}
|
||||
counts
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_draw_is_a_function_of_world_and_session() {
|
||||
let weights = stock_weights();
|
||||
let world = WorldId::nil_for_test();
|
||||
for id in ids() {
|
||||
assert_eq!(
|
||||
draw(&weights, world, id).unwrap(),
|
||||
draw(&weights, world, id).unwrap()
|
||||
);
|
||||
}
|
||||
let expected: BTreeMap<Lens, usize> = BTREE_STOCK_TALLY.into_iter().collect();
|
||||
assert_eq!(tally(&weights), expected);
|
||||
}
|
||||
|
||||
/// Computed at Cut 1 and pinned: the replay proof for 200 derived ids under
|
||||
/// stock weights.
|
||||
const BTREE_STOCK_TALLY: [(Lens, usize); 8] = [
|
||||
(Lens::Patina, 22),
|
||||
(Lens::Charter, 37),
|
||||
(Lens::Ledger, 26),
|
||||
(Lens::Hearth, 19),
|
||||
(Lens::Tangle, 23),
|
||||
(Lens::Veil, 29),
|
||||
(Lens::Ember, 18),
|
||||
(Lens::Numen, 26),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn a_zero_weight_never_draws() {
|
||||
let weights = LensWeights::new(BTreeMap::from([
|
||||
(Lens::Patina, 0),
|
||||
(Lens::Charter, 3),
|
||||
(Lens::Ledger, 1),
|
||||
]));
|
||||
let counts = tally(&weights);
|
||||
assert_eq!(counts.get(&Lens::Patina), None, "a zero weight drew");
|
||||
let expected: BTreeMap<Lens, usize> = ZERO_WEIGHT_TALLY.into_iter().collect();
|
||||
assert_eq!(counts, expected);
|
||||
}
|
||||
|
||||
/// Computed at Cut 1 and pinned; near 3:1 over the same 200 ids.
|
||||
const ZERO_WEIGHT_TALLY: [(Lens, usize); 2] = [(Lens::Charter, 155), (Lens::Ledger, 45)];
|
||||
|
||||
#[test]
|
||||
fn all_zero_weights_are_an_error() {
|
||||
let world = WorldId::nil_for_test();
|
||||
let id = CommandId::derived("l1-probe", &["0"]);
|
||||
let all_zero = LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 0)).collect());
|
||||
assert_eq!(all_zero.iter().count(), 8);
|
||||
for weights in [LensWeights::default(), all_zero] {
|
||||
assert!(matches!(
|
||||
draw(&weights, world, id),
|
||||
Err(KernelError::Invariant(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_lens_name_does_not_deserialize() {
|
||||
for refused in [
|
||||
r#"{"Patina":1}"#,
|
||||
r#"{"patina ":1}"#,
|
||||
r#"{"patinaa":1}"#,
|
||||
r#"{"patina":1,"tribunal":1}"#,
|
||||
] {
|
||||
assert!(
|
||||
serde_json::from_str::<LensWeights>(refused).is_err(),
|
||||
"{refused} deserialized"
|
||||
);
|
||||
}
|
||||
let accepted = serde_json::from_str::<LensWeights>(r#"{"patina":1}"#).unwrap();
|
||||
assert_eq!(accepted.get(Lens::Patina), 1);
|
||||
assert_eq!(accepted.iter().count(), 1);
|
||||
|
||||
let stock = stock_weights();
|
||||
let bytes = rmp_serde::to_vec_named(&stock).unwrap();
|
||||
let back: LensWeights = rmp_serde::from_slice(&bytes).unwrap();
|
||||
assert_eq!(back, stock);
|
||||
assert_eq!(rmp_serde::to_vec_named(&back).unwrap(), bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_lens_text_names_its_own_leads() {
|
||||
let mut texts = BTreeSet::new();
|
||||
for lens in Lens::ALL {
|
||||
let text = lens.instructions();
|
||||
assert!(text.contains(lens.name()), "{lens:?} text omits its name");
|
||||
for name in lens.leads_with() {
|
||||
assert!(text.contains(name), "{lens:?} text omits {name}");
|
||||
}
|
||||
texts.insert(text);
|
||||
}
|
||||
assert_eq!(texts.len(), 8, "two lenses share a text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lenses_serialize_as_snake_case_names() {
|
||||
let names: Vec<String> = Lens::ALL
|
||||
.iter()
|
||||
.map(|lens| serde_json::to_string(lens).unwrap())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
r#""patina""#,
|
||||
r#""charter""#,
|
||||
r#""ledger""#,
|
||||
r#""hearth""#,
|
||||
r#""tangle""#,
|
||||
r#""veil""#,
|
||||
r#""ember""#,
|
||||
r#""numen""#,
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -61,7 +61,6 @@ mod grammar;
|
|||
#[cfg(test)]
|
||||
mod import_key_tests;
|
||||
mod journal;
|
||||
mod lens;
|
||||
mod patch;
|
||||
|
||||
pub(crate) use action::ActionMismatch;
|
||||
|
|
@ -72,7 +71,6 @@ pub use grammar::{
|
|||
GrammarBinding, GrammarError, GrammarIdentity, GrammarReferentKind, GrammarRole, GrammarVerb,
|
||||
RenderPath,
|
||||
};
|
||||
pub use lens::{Lens, LensWeights};
|
||||
pub use patch::{
|
||||
CommitmentKey, DraftHandle, JurisdictionKey, Mismatch, PatchAnswer, Ref, RefKind, RefName, Role,
|
||||
Site, Statement, WorldPatch,
|
||||
|
|
@ -390,9 +388,6 @@ struct CreateWorld {
|
|||
/// Authored once, here, and never mutated: `CommandBody::AdmitPatch` carries
|
||||
/// no intent, so write-once is the command shape rather than a check.
|
||||
scale_intent: WorldScaleIntentRef,
|
||||
/// The world's flavor as genesis writes it. `SetLensWeights` may replace
|
||||
/// it later; this command carries what the world began with.
|
||||
lens_weights: LensWeights,
|
||||
/// The grammar the world is bound to for its whole life, or none for an
|
||||
/// open-catalog world. Authored here and nowhere else: genesis installs it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
|
|
@ -418,9 +413,6 @@ pub struct CreateWorldIntent {
|
|||
/// The jurisdiction roots genesis declares beside the commons, because
|
||||
/// `resolve_patch` only resolves roots the same patch declares.
|
||||
pub jurisdictions: Vec<CreateJurisdictionIntent>,
|
||||
/// Required. The library holds no default weights; a consumer states the
|
||||
/// world's flavor or is refused.
|
||||
pub lens_weights: LensWeights,
|
||||
}
|
||||
|
||||
/// One jurisdiction root as ingress states it. The handle is a string here and
|
||||
|
|
@ -666,15 +658,6 @@ pub enum CommandBody {
|
|||
AdvanceTime {
|
||||
minutes: TickMinutes,
|
||||
},
|
||||
/// Replaces the world's whole lens weight set. Owner only, in any phase,
|
||||
/// under genesis admission: a set that never draws is refused, and a zero
|
||||
/// weight is admitted and never draws. A set that weighs every lens as
|
||||
/// the current one does, however its map is spelled, changes nothing
|
||||
/// canonical and is refused with `NoCanonicalChange` after admission, so
|
||||
/// nothing commits. A session that already drew keeps its recorded lens.
|
||||
SetLensWeights {
|
||||
weights: LensWeights,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
|
|
@ -865,10 +848,6 @@ struct WorldState {
|
|||
now: FictionalMinutes,
|
||||
/// The authored scale target, written once by genesis and never mutated.
|
||||
scale_intent: WorldScaleIntent,
|
||||
/// Written by genesis and replaced only by `SetLensWeights`; read by the
|
||||
/// elaborator's draw and by nothing that admits. It enters `state_digest`
|
||||
/// and no `ScopePreimage`.
|
||||
lens_weights: LensWeights,
|
||||
controller_assignments: BTreeMap<DecisionScope, ControllerAssignment>,
|
||||
/// What an affordance *is*. World-authored, Draft-only, written by
|
||||
/// `admit_resolved` alone.
|
||||
|
|
@ -920,11 +899,6 @@ enum WorldEffect {
|
|||
to: FictionalMinutes,
|
||||
motion: Motion,
|
||||
},
|
||||
/// The owner replaced the world's lens weights. `apply_effect` re-decides
|
||||
/// the owner and the draw rule.
|
||||
LensWeightsReplaced {
|
||||
weights: LensWeights,
|
||||
},
|
||||
}
|
||||
|
||||
/// The exact raw command admitted by the world owner. This is the sole
|
||||
|
|
@ -1211,7 +1185,6 @@ pub struct WorldSnapshot {
|
|||
/// commitment gazetteer.
|
||||
pub boundaries: Vec<CausalBoundary>,
|
||||
pub scale_deficit: Vec<ScaleDeficitRow>,
|
||||
pub lens_weights: LensWeights,
|
||||
pub state_digest: String,
|
||||
pub last_commit_digest: Option<String>,
|
||||
}
|
||||
|
|
@ -1437,7 +1410,6 @@ fn prepare_creation(
|
|||
input.id,
|
||||
&input.patch,
|
||||
Some(&input.scale_intent),
|
||||
Some(&input.lens_weights),
|
||||
)
|
||||
.map_err(KernelError::PatchRejected)?;
|
||||
require_ruler(&CallerId::Principal(input.owner.clone()), &resolved)
|
||||
|
|
@ -1799,7 +1771,7 @@ fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result<WorldEffect,
|
|||
!(patch.declarations.is_empty() && patch.evidence.is_empty()),
|
||||
)?;
|
||||
let confinement = require_patch_author(state, &command.caller, answers.as_ref())?;
|
||||
let resolved = patch::resolve_patch(state, command.id, patch, None, None)
|
||||
let resolved = patch::resolve_patch(state, command.id, patch, None)
|
||||
.map_err(KernelError::PatchRejected)?;
|
||||
require_ruler(&command.caller, &resolved).map_err(KernelError::PatchRejected)?;
|
||||
if let Some(ground) = confinement {
|
||||
|
|
@ -1810,25 +1782,6 @@ fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result<WorldEffect,
|
|||
resolved,
|
||||
})
|
||||
}
|
||||
CommandBody::SetLensWeights { weights } => {
|
||||
require_owner(state, &command.caller)?;
|
||||
if !weights.draws() {
|
||||
return Err(KernelError::PatchRejected(vec![
|
||||
Mismatch::LensWeightsNeverDraw,
|
||||
]));
|
||||
}
|
||||
// Admission first, then effect: a caller who may not set weights,
|
||||
// or a set that never draws, is refused as such even when it
|
||||
// equals the current set. Only an admitted set can be a no-op.
|
||||
if weights.weighs_the_same_as(&state.lens_weights) {
|
||||
return Err(KernelError::PatchRejected(vec![
|
||||
Mismatch::NoCanonicalChange,
|
||||
]));
|
||||
}
|
||||
Ok(WorldEffect::LensWeightsReplaced {
|
||||
weights: weights.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1974,9 +1927,6 @@ impl WorldState {
|
|||
last_opportunity_at: BTreeMap::new(),
|
||||
now: FictionalMinutes::default(),
|
||||
scale_intent: WorldScaleIntent::default(),
|
||||
// Never persisted: genesis overwrites it, and `verify_state_shape`
|
||||
// refuses a stored set that never draws.
|
||||
lens_weights: LensWeights::default(),
|
||||
controller_assignments: BTreeMap::new(),
|
||||
affordance_catalog: BTreeMap::new(),
|
||||
affordance_grants: BTreeMap::new(),
|
||||
|
|
@ -2019,7 +1969,6 @@ impl WorldState {
|
|||
command.id,
|
||||
&command.patch,
|
||||
Some(&command.scale_intent),
|
||||
Some(&command.lens_weights),
|
||||
)
|
||||
.map_err(KernelError::PatchRejected)?;
|
||||
if &expected != resolved {
|
||||
|
|
@ -2296,9 +2245,6 @@ fn admit_resolved(
|
|||
if let Some(intent) = &resolved.scale_intent {
|
||||
state.scale_intent = intent.clone();
|
||||
}
|
||||
if let Some(weights) = &resolved.lens_weights {
|
||||
state.lens_weights = weights.clone();
|
||||
}
|
||||
apply_operations(state, &resolved.operations, &resolved.evidence, resolves_to)
|
||||
}
|
||||
|
||||
|
|
@ -4217,7 +4163,6 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> {
|
|||
now: state.now,
|
||||
boundaries: derive_boundaries(state)?,
|
||||
scale_deficit: derive_scale_deficit(state)?,
|
||||
lens_weights: state.lens_weights.clone(),
|
||||
state_digest: state.state_digest.clone(),
|
||||
last_commit_digest: state.last_commit_digest.clone(),
|
||||
})
|
||||
|
|
@ -5482,14 +5427,6 @@ fn apply_effect(
|
|||
.insert(written.source, written.magnitude);
|
||||
}
|
||||
}
|
||||
WorldEffect::LensWeightsReplaced { weights } => {
|
||||
if caller != &CallerId::Principal(state.owner.clone()) || !weights.draws() {
|
||||
return Err(KernelError::Invariant(
|
||||
"lens weights effect does not satisfy owner admission".into(),
|
||||
));
|
||||
}
|
||||
state.lens_weights = weights.clone();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -5595,11 +5532,6 @@ mod tests {
|
|||
.expect("the fixture world declares this affordance")
|
||||
}
|
||||
|
||||
/// Every stock lens at weight one.
|
||||
pub(crate) fn stock_weights() -> LensWeights {
|
||||
LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 1)).collect())
|
||||
}
|
||||
|
||||
pub(crate) fn creation(id: CommandId, title: &str) -> CreateWorld {
|
||||
CreateWorld {
|
||||
id,
|
||||
|
|
@ -5664,7 +5596,6 @@ mod tests {
|
|||
],
|
||||
},
|
||||
scale_intent: WorldScaleIntentRef::default(),
|
||||
lens_weights: stock_weights(),
|
||||
grammar: None,
|
||||
}
|
||||
}
|
||||
|
|
@ -8899,7 +8830,6 @@ mod custody_tests {
|
|||
let mut candidate = kernel.state.clone();
|
||||
let forged = WorldEffect::PatchAdmitted {
|
||||
resolved: ResolvedPatch {
|
||||
lens_weights: None,
|
||||
subjects: Vec::new(),
|
||||
entities: Vec::new(),
|
||||
routes: Vec::new(),
|
||||
|
|
@ -9495,7 +9425,6 @@ mod custody_tests {
|
|||
|
||||
let forge = |operations: Vec<ResolvedOp>| WorldEffect::PatchAdmitted {
|
||||
resolved: ResolvedPatch {
|
||||
lens_weights: None,
|
||||
subjects: Vec::new(),
|
||||
entities: Vec::new(),
|
||||
routes: Vec::new(),
|
||||
|
|
@ -12210,7 +12139,6 @@ mod witness_tests {
|
|||
evidence: Vec::new(),
|
||||
},
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.expect("the witness resolves over committed state");
|
||||
for ground in [
|
||||
|
|
@ -15271,7 +15199,7 @@ mod clock_tests {
|
|||
panic!("the operations helper builds an admitted patch");
|
||||
};
|
||||
let resolved =
|
||||
patch::resolve_patch(&kernel.state, CommandId::new(), patch, None, None).expect("resolves");
|
||||
patch::resolve_patch(&kernel.state, CommandId::new(), patch, None).expect("resolves");
|
||||
assert!(
|
||||
resolved.scale_intent.is_none(),
|
||||
"an Active patch resolved a scale intent"
|
||||
|
|
@ -15281,54 +15209,6 @@ mod clock_tests {
|
|||
assert_eq!(kernel.state.scale_intent, authored);
|
||||
}
|
||||
|
||||
// ---- lens weights: world data, genesis, and the owner command --------
|
||||
|
||||
fn every_lens_at_zero() -> LensWeights {
|
||||
LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 0)).collect())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn genesis_writes_the_lens_weights_it_was_given() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("world.cc");
|
||||
let given = LensWeights::new(BTreeMap::from([(Lens::Patina, 2), (Lens::Numen, 1)]));
|
||||
let mut input = creation(CommandId::new(), "Flavored");
|
||||
input.lens_weights = given.clone();
|
||||
let (kernel, _) = WorldKernel::create(&path, input, &auth_principal(owner())).unwrap();
|
||||
let created = kernel.snapshot().unwrap();
|
||||
assert_eq!(created.lens_weights, given);
|
||||
assert_eq!(kernel.state.lens_weights, given);
|
||||
|
||||
let world_id = created.world_id;
|
||||
drop(kernel);
|
||||
let replayed = WorldKernel::open(&path, world_id).unwrap();
|
||||
assert_eq!(replayed.snapshot().unwrap(), created);
|
||||
assert_eq!(replayed.state.state_digest, created.state_digest);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_genesis_lens_set_that_never_draws_is_refused() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("world.cc");
|
||||
let mut input = creation(CommandId::new(), "Flavorless");
|
||||
input.lens_weights = every_lens_at_zero();
|
||||
let Err(error) = WorldKernel::create(&path, input, &auth_principal(owner())) else {
|
||||
panic!("a genesis lens set that never draws was admitted");
|
||||
};
|
||||
let KernelError::PatchRejected(mismatches) = error else {
|
||||
panic!("expected a rejected genesis patch, got {error:?}");
|
||||
};
|
||||
assert_eq!(mismatches, vec![Mismatch::LensWeightsNeverDraw]);
|
||||
assert!(!path.exists(), "a refused genesis wrote a world file");
|
||||
|
||||
// The same creation with one real weight among the zeros is admitted.
|
||||
let mut input = creation(CommandId::new(), "Flavorless");
|
||||
let mut weights = BTreeMap::from_iter(every_lens_at_zero().iter());
|
||||
weights.insert(Lens::Veil, 1);
|
||||
input.lens_weights = LensWeights::new(weights);
|
||||
WorldKernel::create(&path, input, &auth_principal(owner())).expect("one nonzero weight");
|
||||
}
|
||||
|
||||
// ---- PA.f26: the genesis lane obeys `require_ruler` too ------------
|
||||
|
||||
/// PA.f26: `prepare_creation` and `WorldState::genesis` both call
|
||||
|
|
@ -15415,7 +15295,6 @@ mod clock_tests {
|
|||
input.id,
|
||||
&input.patch,
|
||||
Some(&input.scale_intent),
|
||||
Some(&input.lens_weights),
|
||||
)
|
||||
.expect("the resolver is actor-blind and accepts a Ruled fact");
|
||||
let effect = WorldEffect::WorldCreated {
|
||||
|
|
@ -15444,7 +15323,6 @@ mod clock_tests {
|
|||
input.id,
|
||||
&input.patch,
|
||||
Some(&input.scale_intent),
|
||||
Some(&input.lens_weights),
|
||||
)
|
||||
.expect("the resolver is actor-blind and accepts a Mint");
|
||||
let effect = WorldEffect::WorldCreated {
|
||||
|
|
@ -15457,223 +15335,6 @@ mod clock_tests {
|
|||
assert!(matches!(error, KernelError::Invariant(_)), "{error:?}");
|
||||
}
|
||||
|
||||
/// Soul falsification, the lens twin of the scale intent's write-once
|
||||
/// test: an Active patch resolves no weights; only the owner's
|
||||
/// `SetLensWeights` replaces them, in Draft and in Active; every other
|
||||
/// caller is `Unauthorized`; a set that never draws is refused; and
|
||||
/// `apply_effect` re-decides the owner against a hand-built effect.
|
||||
#[test]
|
||||
fn soul_the_lens_weights_are_replaced_only_by_the_owner_command() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (mut kernel, _) = WorldKernel::create(
|
||||
directory.path().join("world.cc"),
|
||||
creation(CommandId::new(), "Owner Flavor"),
|
||||
&auth_principal(owner()),
|
||||
)
|
||||
.unwrap();
|
||||
let draft_weights = LensWeights::new(BTreeMap::from([
|
||||
(Lens::Patina, 0),
|
||||
(Lens::Charter, 3),
|
||||
(Lens::Ledger, 1),
|
||||
]));
|
||||
let draft = kernel.snapshot().unwrap();
|
||||
submit_owner(
|
||||
&mut kernel,
|
||||
&draft,
|
||||
CommandBody::SetLensWeights {
|
||||
weights: draft_weights.clone(),
|
||||
},
|
||||
);
|
||||
assert_eq!(kernel.state.revision, draft.revision + 1);
|
||||
assert_eq!(kernel.state.lens_weights, draft_weights);
|
||||
|
||||
let active = activate(&mut kernel);
|
||||
let active_weights = LensWeights::new(BTreeMap::from([
|
||||
(Lens::Hearth, 5),
|
||||
(Lens::Tangle, 0),
|
||||
(Lens::Ember, 2),
|
||||
]));
|
||||
submit_owner(
|
||||
&mut kernel,
|
||||
&active,
|
||||
CommandBody::SetLensWeights {
|
||||
weights: active_weights.clone(),
|
||||
},
|
||||
);
|
||||
assert_eq!(kernel.state.revision, active.revision + 1);
|
||||
assert_eq!(kernel.state.lens_weights, active_weights);
|
||||
|
||||
// An Active patch is handed no weights, so it cannot resolve any.
|
||||
let resolved = patch::resolve_patch(
|
||||
&kernel.state,
|
||||
CommandId::new(),
|
||||
&operations_patch(&kernel),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.expect("resolves");
|
||||
assert!(resolved.lens_weights.is_none(), "an Active patch resolved lens weights");
|
||||
let after_patch = kernel.snapshot().unwrap();
|
||||
let patch = operations_patch(&kernel);
|
||||
submit_owner(
|
||||
&mut kernel,
|
||||
&after_patch,
|
||||
CommandBody::AdmitPatch {
|
||||
answers: None,
|
||||
patch,
|
||||
},
|
||||
);
|
||||
assert_eq!(kernel.state.lens_weights, active_weights);
|
||||
|
||||
// Every caller but the owner, with real weights.
|
||||
let proposed = super::tests::stock_weights();
|
||||
let before = kernel.state.clone();
|
||||
for caller in [
|
||||
CallerId::Principal(human_principal()),
|
||||
CallerId::Principal(PrincipalId::new("stranger@example.test")),
|
||||
elaborator(JurisdictionKey::Uncovered),
|
||||
CallerId::System(SystemCapability::Clock),
|
||||
CallerId::System(SystemCapability::Consumer {
|
||||
consumer: ConsumerId::of_name("lens-consumer"),
|
||||
}),
|
||||
] {
|
||||
let result = submit_as(
|
||||
&mut kernel,
|
||||
caller.clone(),
|
||||
CommandBody::SetLensWeights {
|
||||
weights: proposed.clone(),
|
||||
},
|
||||
);
|
||||
assert!(
|
||||
matches!(result, Err(KernelError::Unauthorized)),
|
||||
"{caller:?} replaced the lens weights: {result:?}"
|
||||
);
|
||||
}
|
||||
assert_eq!(kernel.state, before);
|
||||
|
||||
// The owner, with every lens named at zero.
|
||||
let result = submit_as(
|
||||
&mut kernel,
|
||||
CallerId::Principal(owner()),
|
||||
CommandBody::SetLensWeights {
|
||||
weights: every_lens_at_zero(),
|
||||
},
|
||||
);
|
||||
let Err(KernelError::PatchRejected(mismatches)) = result else {
|
||||
panic!("a lens set that never draws was admitted: {result:?}");
|
||||
};
|
||||
assert_eq!(mismatches, vec![Mismatch::LensWeightsNeverDraw]);
|
||||
assert_eq!(kernel.state, before);
|
||||
|
||||
// The owner, with valid weights, against the revision before the
|
||||
// last commit.
|
||||
let stale = command(
|
||||
&draft,
|
||||
CommandId::new(),
|
||||
CallerId::Principal(owner()),
|
||||
CommandBody::SetLensWeights {
|
||||
weights: proposed.clone(),
|
||||
},
|
||||
);
|
||||
assert!(matches!(
|
||||
kernel.submit(stale, &auth_principal(owner())),
|
||||
Err(KernelError::RevisionMismatch { .. })
|
||||
));
|
||||
assert_eq!(kernel.state, before);
|
||||
|
||||
// `apply_effect` re-decides: a hand-built effect under a non-owner or
|
||||
// a system caller never applies, and neither does one that never draws.
|
||||
for (caller, weights) in [
|
||||
(CallerId::Principal(human_principal()), proposed.clone()),
|
||||
(CallerId::System(SystemCapability::Clock), proposed.clone()),
|
||||
(CallerId::Principal(owner()), every_lens_at_zero()),
|
||||
] {
|
||||
let mut candidate = kernel.state.clone();
|
||||
let error = apply_effect(
|
||||
&mut candidate,
|
||||
CommandId::new(),
|
||||
&caller,
|
||||
&WorldEffect::LensWeightsReplaced { weights },
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(
|
||||
error,
|
||||
KernelError::Invariant(_) | KernelError::Unauthorized
|
||||
),
|
||||
"{caller:?}: {error:?}"
|
||||
);
|
||||
assert_eq!(candidate, kernel.state);
|
||||
}
|
||||
// The honest effect applies through the same arm.
|
||||
let mut candidate = kernel.state.clone();
|
||||
apply_effect(
|
||||
&mut candidate,
|
||||
CommandId::new(),
|
||||
&CallerId::Principal(owner()),
|
||||
&WorldEffect::LensWeightsReplaced {
|
||||
weights: proposed.clone(),
|
||||
},
|
||||
)
|
||||
.expect("the owner's effect applies");
|
||||
assert_eq!(candidate.lens_weights, proposed);
|
||||
|
||||
// Identical weights from the owner change nothing canonical: refused
|
||||
// as `NoCanonicalChange`, and nothing commits.
|
||||
let result = submit_as(
|
||||
&mut kernel,
|
||||
CallerId::Principal(owner()),
|
||||
CommandBody::SetLensWeights {
|
||||
weights: active_weights.clone(),
|
||||
},
|
||||
);
|
||||
let Err(KernelError::PatchRejected(mismatches)) = result else {
|
||||
panic!("identical lens weights were admitted: {result:?}");
|
||||
};
|
||||
assert_eq!(mismatches, vec![Mismatch::NoCanonicalChange]);
|
||||
assert_eq!(kernel.state, before);
|
||||
|
||||
// The order is admission, then effect. Identical weights from a
|
||||
// non-owner are `Unauthorized`; and against a state whose own set
|
||||
// never draws (no store holds one, so the state is built by hand), an
|
||||
// identical all-zero set is `LensWeightsNeverDraw`, not a no-op.
|
||||
let result = submit_as(
|
||||
&mut kernel,
|
||||
CallerId::Principal(human_principal()),
|
||||
CommandBody::SetLensWeights {
|
||||
weights: active_weights.clone(),
|
||||
},
|
||||
);
|
||||
assert!(
|
||||
matches!(result, Err(KernelError::Unauthorized)),
|
||||
"a non-owner's identical set: {result:?}"
|
||||
);
|
||||
assert_eq!(kernel.state, before);
|
||||
let mut never = kernel.state.clone();
|
||||
never.lens_weights = every_lens_at_zero();
|
||||
let current = kernel.snapshot().unwrap();
|
||||
let identical_zero = command(
|
||||
¤t,
|
||||
CommandId::new(),
|
||||
CallerId::Principal(owner()),
|
||||
CommandBody::SetLensWeights {
|
||||
weights: every_lens_at_zero(),
|
||||
},
|
||||
);
|
||||
let result = reduce(&never, &identical_zero);
|
||||
let Err(KernelError::PatchRejected(mismatches)) = result else {
|
||||
panic!("an identical set that never draws: {result:?}");
|
||||
};
|
||||
assert_eq!(mismatches, vec![Mismatch::LensWeightsNeverDraw]);
|
||||
|
||||
// Replay across that history is unchanged: the refused attempts wrote
|
||||
// nothing, and the store reopens to the same head.
|
||||
let (path, world_id) = (directory.path().join("world.cc"), kernel.state.world_id);
|
||||
drop(kernel);
|
||||
let reopened = WorldKernel::open(path, world_id).expect("the history reopens");
|
||||
assert_eq!(reopened.state, before);
|
||||
}
|
||||
|
||||
/// An owner commit that adds a commitment to the first person: a real
|
||||
/// Active patch with no answer, and nothing to do with lenses.
|
||||
fn operations_patch(kernel: &WorldKernel) -> WorldPatch {
|
||||
|
|
@ -15698,46 +15359,6 @@ mod clock_tests {
|
|||
patch
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lens_weights_enter_the_state_digest_and_no_scope_digest() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (mut kernel, _) = WorldKernel::create(
|
||||
directory.path().join("world.cc"),
|
||||
creation(CommandId::new(), "Digest Flavor"),
|
||||
&auth_principal(owner()),
|
||||
)
|
||||
.unwrap();
|
||||
let active = activate(&mut kernel);
|
||||
|
||||
let mut other = kernel.state.clone();
|
||||
other.lens_weights =
|
||||
LensWeights::new(BTreeMap::from([(Lens::Patina, 1), (Lens::Veil, 7)]));
|
||||
assert_ne!(
|
||||
state_digest(&other).unwrap(),
|
||||
state_digest(&kernel.state).unwrap(),
|
||||
"lens weights did not enter the state digest"
|
||||
);
|
||||
|
||||
let digests = |kernel: &WorldKernel| -> BTreeMap<SubjectId, ScopeDigest> {
|
||||
derive_opportunities(&kernel.state)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|opportunity| (opportunity.scope.subject_id, opportunity.scope_digest))
|
||||
.collect()
|
||||
};
|
||||
let before = digests(&kernel);
|
||||
assert!(!before.is_empty(), "the active fixture derives opportunities");
|
||||
submit_owner(
|
||||
&mut kernel,
|
||||
&active,
|
||||
CommandBody::SetLensWeights {
|
||||
weights: other.lens_weights.clone(),
|
||||
},
|
||||
);
|
||||
assert_ne!(kernel.state.state_digest, active.state_digest);
|
||||
assert_eq!(digests(&kernel), before, "lens weights entered a scope digest");
|
||||
}
|
||||
|
||||
/// Soul falsification: a discharge names one subject's own live key.
|
||||
#[test]
|
||||
fn soul_discharging_a_foreign_or_already_discharged_commitment_is_refused() {
|
||||
|
|
@ -16385,7 +16006,6 @@ mod clock_tests {
|
|||
command_id,
|
||||
&shed_under(clockwork.dead_end, "shed"),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.expect("the patch resolves");
|
||||
let effect = WorldEffect::PatchAdmitted {
|
||||
|
|
@ -17532,7 +17152,7 @@ mod clock_tests {
|
|||
}],
|
||||
evidence: Vec::new(),
|
||||
};
|
||||
let resolved = patch::resolve_patch(&kernel.state, command_id, &patch, None, None)
|
||||
let resolved = patch::resolve_patch(&kernel.state, command_id, &patch, None)
|
||||
.expect("the patch resolves; the resolver is actor-blind");
|
||||
let effect = WorldEffect::PatchAdmitted {
|
||||
answers: Some(PatchAnswer::Boundary(answered)),
|
||||
|
|
@ -17569,7 +17189,7 @@ mod clock_tests {
|
|||
let answered = dead_end_boundary(&kernel);
|
||||
let command_id = CommandId::issue();
|
||||
let patch = ruled_fact_patch("rule");
|
||||
let resolved = patch::resolve_patch(&kernel.state, command_id, &patch, None, None)
|
||||
let resolved = patch::resolve_patch(&kernel.state, command_id, &patch, None)
|
||||
.expect("the patch resolves; the resolver is actor-blind");
|
||||
let effect = WorldEffect::PatchAdmitted {
|
||||
answers: Some(PatchAnswer::Boundary(answered)),
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@
|
|||
use super::clock::{FictionalMinutes, TickMinutes};
|
||||
use super::grammar::GrammarRefusal;
|
||||
use super::{
|
||||
AffordanceId, CommandId, ControllerAssignment, ControllerId, EdgeId, EntityId, LensWeights,
|
||||
AffordanceId, CommandId, ControllerAssignment, ControllerId, EdgeId, EntityId,
|
||||
NewController, SubjectId, SubjectKind, SubjectState, WorldId,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
|
@ -1737,9 +1737,6 @@ pub enum Mismatch {
|
|||
/// The permille weights sum over 1000: weights distribute the target and
|
||||
/// never raise it.
|
||||
ScaleWeightsExceedWhole,
|
||||
/// A lens weight set with no nonzero weight, at genesis or in
|
||||
/// `SetLensWeights`. A single zero weight is admitted and never draws.
|
||||
LensWeightsNeverDraw,
|
||||
/// A jurisdictional author wrote outside its jurisdiction. The owner is
|
||||
/// unconfined and never sees this.
|
||||
OutsideJurisdiction {
|
||||
|
|
@ -2141,9 +2138,6 @@ pub(super) struct ResolvedPatch {
|
|||
/// carries no intent, so the write-once rule is the command shape rather
|
||||
/// than a check.
|
||||
pub(super) scale_intent: Option<WorldScaleIntent>,
|
||||
/// `Some` on the genesis lane and nowhere else, as `scale_intent` is. After
|
||||
/// genesis the weights change only through `SetLensWeights`.
|
||||
pub(super) lens_weights: Option<LensWeights>,
|
||||
}
|
||||
|
||||
impl ResolvedPatch {
|
||||
|
|
@ -3219,7 +3213,6 @@ pub(super) fn resolve_patch(
|
|||
command_id: CommandId,
|
||||
patch: &WorldPatch,
|
||||
scale_intent: Option<&WorldScaleIntentRef>,
|
||||
lens_weights: Option<&LensWeights>,
|
||||
) -> Result<ResolvedPatch, Vec<Mismatch>> {
|
||||
let world_id = state.world_id;
|
||||
let admits_human = super::admits_human(state.revision, &state.subjects);
|
||||
|
|
@ -5151,12 +5144,6 @@ pub(super) fn resolve_patch(
|
|||
}
|
||||
}
|
||||
|
||||
if let Some(weights) = lens_weights
|
||||
&& !weights.draws()
|
||||
{
|
||||
mismatches.push(Mismatch::LensWeightsNeverDraw);
|
||||
}
|
||||
|
||||
if patch.declarations.is_empty() && patch.operations.is_empty() {
|
||||
mismatches.push(Mismatch::NoCanonicalChange);
|
||||
}
|
||||
|
|
@ -5854,7 +5841,6 @@ pub(super) fn resolve_patch(
|
|||
})
|
||||
.collect(),
|
||||
}),
|
||||
lens_weights: lens_weights.cloned(),
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -7378,8 +7364,8 @@ mod tests {
|
|||
assert_ne!(admitted, genesis_human);
|
||||
|
||||
let command_id = CommandId::new();
|
||||
let first = resolve_patch(&kernel.state, command_id, &patch, None, None).unwrap();
|
||||
let second = resolve_patch(&kernel.state, command_id, &patch, None, None).unwrap();
|
||||
let first = resolve_patch(&kernel.state, command_id, &patch, None).unwrap();
|
||||
let second = resolve_patch(&kernel.state, command_id, &patch, None).unwrap();
|
||||
assert_eq!(first, second);
|
||||
}
|
||||
|
||||
|
|
@ -7522,7 +7508,7 @@ mod tests {
|
|||
Some(Ref::Draft(DraftHandle::new("rhythm-road"))),
|
||||
),
|
||||
]);
|
||||
let resolved = resolve_patch(&kernel.state, CommandId::new(), &patch, None, None).unwrap();
|
||||
let resolved = resolve_patch(&kernel.state, CommandId::new(), &patch, None).unwrap();
|
||||
let honest = super::super::WorldEffect::PatchAdmitted {
|
||||
resolved: resolved.clone(),
|
||||
answers: None,
|
||||
|
|
@ -7726,7 +7712,6 @@ mod tests {
|
|||
for edge_id in [topology.span, topology.shutter, topology.toll] {
|
||||
let forged = super::super::WorldEffect::PatchAdmitted {
|
||||
resolved: ResolvedPatch {
|
||||
lens_weights: None,
|
||||
subjects: Vec::new(),
|
||||
entities: Vec::new(),
|
||||
routes: Vec::new(),
|
||||
|
|
|
|||
BIN
native/aetherlight/tests/fixtures/base_world.cc
vendored
BIN
native/aetherlight/tests/fixtures/base_world.cc
vendored
Binary file not shown.
|
|
@ -1,3 +0,0 @@
|
|||
3
|
||||
sha256:b706f57cb417603366a1f47a5dd099fbf68bfecc5b2e8d61d281630791d1d76d
|
||||
sha256:2039956a26c3d5b073d101e5898ac5a60a9eb63a3b93f447b2d8f78ef4caf979
|
||||
|
|
@ -1 +0,0 @@
|
|||
"a534b32a-4d00-429c-bf6c-ce1d55385380"
|
||||
Loading…
Reference in a new issue