diff --git a/crates/ghostlight/src/cover.rs b/crates/ghostlight/src/cover.rs index 5d1ce42..8f5a906 100644 --- a/crates/ghostlight/src/cover.rs +++ b/crates/ghostlight/src/cover.rs @@ -62,9 +62,12 @@ impl std::fmt::Display for CellId { } } -fn derive_uuid(name: &str) -> Uuid { +/// sha256 over a fixed namespace and a name, first sixteen bytes: the one id +/// recipe the scheduler's derived ids share (cells here, hierarchy nodes in +/// `hierarchy.rs`), so the two cannot drift apart. +pub(crate) fn derive_uuid(namespace: &str, name: &str) -> Uuid { let mut hasher = Sha256::new(); - hasher.update(COVER_NAMESPACE.as_bytes()); + hasher.update(namespace.as_bytes()); hasher.update([0u8]); hasher.update(name.as_bytes()); let bytes: [u8; 16] = hasher.finalize()[..16] @@ -81,7 +84,7 @@ fn cell_id(world: WorldId, tick: TickIndex, members: &[SubjectId]) -> CellId { .first() .copied() .expect("a cell always has at least one member"); - CellId(derive_uuid(&format!( + CellId(derive_uuid(COVER_NAMESPACE, &format!( "cell|{world:?}|{}|{}|{lowest:?}", tick.0, members.len() @@ -90,7 +93,7 @@ fn cell_id(world: WorldId, tick: TickIndex, members: &[SubjectId]) -> CellId { /// The stable, derived identity a cell's controller-work row is keyed by. pub(crate) fn cell_work_uuid(world: WorldId, cell: CellId, tick: TickIndex) -> Uuid { - derive_uuid(&format!("cell-work|{world:?}|{cell}|{}", tick.0)) + derive_uuid(COVER_NAMESPACE, &format!("cell-work|{world:?}|{cell}|{}", tick.0)) } /// One constituent's submission id. Deterministic, so a resumed cell re-submits @@ -101,7 +104,7 @@ pub(crate) fn cell_constituent_uuid( subject: SubjectId, tick: TickIndex, ) -> Uuid { - derive_uuid(&format!("cell-act|{world:?}|{cell}|{subject:?}|{}", tick.0)) + derive_uuid(COVER_NAMESPACE, &format!("cell-act|{world:?}|{cell}|{subject:?}|{}", tick.0)) } #[derive(Clone, Debug, PartialEq, Eq)] diff --git a/crates/ghostlight/src/hierarchy.rs b/crates/ghostlight/src/hierarchy.rs new file mode 100644 index 0000000..48002bb --- /dev/null +++ b/crates/ghostlight/src/hierarchy.rs @@ -0,0 +1,750 @@ +//! The gestalt hierarchy: who hangs from whom, derived from world state on +//! every read. +//! +//! This organ owns the tree and nothing else. [`derive_hierarchy`] is pure over +//! a `&WorldState`: no clock, no entropy, no mailbox, no filesystem. Nothing it +//! returns is stored, cached or admitted; a node, a [`NodeId`] and a home +//! parent change only because the world changed through an ordinary command +//! (an office granted, an authority granted, a subject moved). +//! +//! Like the agency graph it is wider than any subject view, so it is reachable +//! from `WorldMailbox` and from neither `ControllerPort` nor `ElaborationPort`. +//! The agency graph stays the adjacency inside one node. +//! +//! Home-parent rule, the first that exists: the institution in which the +//! subject holds an office (several: fewest live members, then lowest id); the +//! institution holding an authority grant over the subject (several: lowest +//! id); the innermost institution holding a grant over a place subtree that +//! contains its position (several over one place: lowest id); the place node +//! of its own position; the root. A subject never hangs from itself. Two +//! institutions that would hang from each other are a cycle, broken at its +//! lowest id, which hangs from the root. Other ties stay context, not a second +//! parent: one home per subject. + +use super::{ + ControllerMode, EntityId, EntityKind, FictionalMinutes, SubjectId, SubjectKind, WorldId, + WorldState, cover::derive_uuid, patch::AuthorityTarget, +}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet}; +use uuid::Uuid; + +/// Fixed, never regenerated: two worlds in one process are separated by the +/// world id inside the name, as cover ids are. +const NODE_NAMESPACE: &str = "ghostlight.gestalt.node.v1"; + +/// Derived from `(world, anchor)`, so the same anchor in the same world is the +/// same node on every read and across every unrelated commit. +#[derive( + Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, +)] +#[serde(transparent)] +pub struct NodeId(Uuid); + +impl NodeId { + pub(crate) fn of(world: WorldId, anchor: &NodeAnchor) -> Self { + Self(derive_uuid( + NODE_NAMESPACE, + &format!("node|{world:?}|{anchor:?}"), + )) + } +} + +/// What a node stands on. `Subject` names a leaf: a derived hierarchy lists +/// leaves as a node's `loose` subjects and mints no node for them, so the +/// variant exists to give a leaf one stable id when a planner needs it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(tag = "anchor", content = "id", rename_all = "snake_case")] +pub enum NodeAnchor { + World, + Institution(SubjectId), + Place(EntityId), + Subject(SubjectId), +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Node { + pub id: NodeId, + pub anchor: NodeAnchor, + /// `None` for the root alone. + pub parent: Option, + /// Ascending by id. + pub children: Vec, + /// The institution subject that speaks for its own node, when it has a + /// non-Human controller. `None` for the root and for place nodes. + pub voice: Option, + /// Subjects that hang directly from this node and are not nodes + /// themselves. Ascending. Never the Human subject. + pub loose: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Hierarchy { + root: NodeId, + pub nodes: BTreeMap, + /// Every placed subject's one parent node, the Human subject included: + /// the player is placed, never a voice. + pub home: BTreeMap, + /// When each voice last consumed a decision opportunity; absent means + /// never. Read from the kernel's `last_opportunity_at`. + pub last_attended: BTreeMap, + /// For every place, the node that governs it: its own place node if one + /// exists, else its innermost governing institution, else the nearest + /// enclosing place node, else the root. + governing: BTreeMap, +} + +impl Hierarchy { + pub fn root(&self) -> NodeId { + self.root + } + + /// The chain of nodes that govern `place`, innermost first and ending at + /// the root. A place the world does not hold is governed by the root + /// alone. + pub fn focus_path(&self, place: EntityId) -> Vec { + let mut path = Vec::new(); + let mut current = Some(self.governing.get(&place).copied().unwrap_or(self.root)); + while let Some(id) = current { + path.push(id); + current = self.nodes.get(&id).and_then(|node| node.parent); + } + path + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Home { + Institution(SubjectId), + Place(EntityId), + Root, +} + +/// The place and its containers, innermost first. Bounded by the entity count, +/// so a corrupt containment loop cannot spin. +fn place_chain(state: &WorldState, place: EntityId) -> Vec { + let mut chain = Vec::new(); + let mut current = Some(place); + for _ in 0..=state.entities.len() { + let Some(node) = current else { break }; + chain.push(node); + current = state + .entities + .get(&node) + .and_then(|record| record.container); + } + chain +} + +pub(super) fn derive_hierarchy(state: &WorldState) -> Hierarchy { + // Who exists to the hierarchy: every subject with a controller. Voices are + // the ones that are not Human. + let mut placed: BTreeSet = BTreeSet::new(); + let mut voices: BTreeSet = BTreeSet::new(); + for (scope, controller) in &state.controller_assignments { + match controller.mode() { + Some(ControllerMode::Human) => { + placed.insert(scope.subject_id); + } + Some(_) => { + placed.insert(scope.subject_id); + voices.insert(scope.subject_id); + } + None => {} + } + } + let institutions: BTreeSet = voices + .iter() + .copied() + .filter(|subject| { + state + .subjects + .get(subject) + .is_some_and(|record| record.kind == SubjectKind::Institution) + }) + .collect(); + + // Office incumbency: subject -> (institution, its live member count). + let members = |institution: SubjectId| -> usize { + state + .selection + .get(&institution) + .map(|offices| { + offices + .values() + .filter_map(|office| office.incumbent) + .filter(|incumbent| placed.contains(incumbent)) + .collect::>() + .len() + }) + .unwrap_or(0) + }; + let mut offices_held: BTreeMap> = BTreeMap::new(); + for institution in &institutions { + for office in state.selection.get(institution).into_iter().flat_map(|o| o.values()) { + if let Some(incumbent) = office.incumbent + && placed.contains(&incumbent) + { + let held = offices_held.entry(incumbent).or_default(); + if !held.contains(institution) { + held.push(*institution); + } + } + } + } + + // Authority grants held by an institution, by what they cover. + let mut over_subject: BTreeMap> = BTreeMap::new(); + let mut over_place: BTreeMap> = BTreeMap::new(); + for (holder, grants) in &state.authority { + if !institutions.contains(holder) { + continue; + } + for grant in grants { + match grant.over { + AuthorityTarget::Subject(subject) => { + over_subject.entry(subject).or_default().insert(*holder); + } + AuthorityTarget::PlaceSubtree(place) => { + over_place.entry(place).or_default().insert(*holder); + } + } + } + } + + let mut home_of: BTreeMap = BTreeMap::new(); + for subject in &placed { + let own = *subject; + let by_office = offices_held.get(&own).and_then(|held| { + held.iter() + .copied() + .filter(|institution| *institution != own) + .min_by_key(|institution| (members(*institution), *institution)) + }); + let by_grant = || { + over_subject + .get(&own) + .and_then(|holders| holders.iter().copied().find(|holder| *holder != own)) + }; + let by_place = || { + let position = state.positions.get(&own)?; + place_chain(state, position.place).into_iter().find_map(|place| { + over_place + .get(&place) + .and_then(|holders| holders.iter().copied().find(|holder| *holder != own)) + }) + }; + let home = by_office + .or_else(by_grant) + .or_else(by_place) + .map(Home::Institution) + .or_else(|| state.positions.get(&own).map(|position| Home::Place(position.place))) + .unwrap_or(Home::Root); + home_of.insert(own, home); + } + + // A cycle can only run through institutions. Break each at its lowest id. + let mut settled: BTreeSet = BTreeSet::new(); + for start in &institutions { + let mut path: Vec = Vec::new(); + let mut current = *start; + loop { + if settled.contains(¤t) { + break; + } + if let Some(at) = path.iter().position(|seen| *seen == current) { + let lowest = path[at..].iter().copied().min().expect("a cycle is non-empty"); + home_of.insert(lowest, Home::Root); + break; + } + path.push(current); + match home_of.get(¤t) { + Some(Home::Institution(parent)) => current = *parent, + _ => break, + } + } + settled.extend(path); + } + + // Place nodes exist only where some subject hangs from one. + let place_nodes: BTreeSet = home_of + .values() + .filter_map(|home| match home { + Home::Place(place) => Some(*place), + _ => None, + }) + .collect(); + let world = state.world_id; + let root = NodeId::of(world, &NodeAnchor::World); + let institution_node = |institution: SubjectId| NodeId::of(world, &NodeAnchor::Institution(institution)); + let place_node = |place: EntityId| NodeId::of(world, &NodeAnchor::Place(place)); + let node_of_home = |home: &Home| match home { + Home::Institution(institution) => institution_node(*institution), + Home::Place(place) => place_node(*place), + Home::Root => root, + }; + + let mut nodes: BTreeMap = BTreeMap::new(); + nodes.insert( + root, + Node { + id: root, + anchor: NodeAnchor::World, + parent: None, + children: Vec::new(), + voice: None, + loose: Vec::new(), + }, + ); + for institution in &institutions { + let id = institution_node(*institution); + nodes.insert( + id, + Node { + id, + anchor: NodeAnchor::Institution(*institution), + parent: Some(node_of_home(&home_of[institution])), + children: Vec::new(), + voice: Some(*institution), + loose: Vec::new(), + }, + ); + } + for place in &place_nodes { + let id = place_node(*place); + let parent = place_chain(state, *place) + .into_iter() + .skip(1) + .find(|ancestor| place_nodes.contains(ancestor)) + .map(place_node) + .unwrap_or(root); + nodes.insert( + id, + Node { + id, + anchor: NodeAnchor::Place(*place), + parent: Some(parent), + children: Vec::new(), + voice: None, + loose: Vec::new(), + }, + ); + } + + let mut home: BTreeMap = BTreeMap::new(); + for (subject, subject_home) in &home_of { + let parent = node_of_home(subject_home); + home.insert(*subject, parent); + if voices.contains(subject) && !institutions.contains(subject) { + nodes + .get_mut(&parent) + .expect("a home names a node that was just minted") + .loose + .push(*subject); + } + } + let links: Vec<(NodeId, NodeId)> = nodes + .values() + .filter_map(|node| node.parent.map(|parent| (parent, node.id))) + .collect(); + for (parent, child) in links { + nodes + .get_mut(&parent) + .expect("a parent is a minted node") + .children + .push(child); + } + // `home_of` iterates ascending, so `loose` is already ascending; children + // arrive in node-id order from `nodes`. + + let mut governing: BTreeMap = BTreeMap::new(); + for (place, record) in &state.entities { + if record.kind != EntityKind::Place { + continue; + } + let chain = place_chain(state, *place); + let node = if place_nodes.contains(place) { + place_node(*place) + } else if let Some(holder) = chain + .iter() + .find_map(|link| over_place.get(link).and_then(|holders| holders.first())) + { + institution_node(*holder) + } else { + chain + .iter() + .find(|link| place_nodes.contains(link)) + .map(|link| place_node(*link)) + .unwrap_or(root) + }; + governing.insert(*place, node); + } + + let last_attended = voices + .iter() + .filter_map(|voice| { + state + .last_opportunity_at + .get(voice) + .map(|at| (*voice, *at)) + }) + .collect(); + + Hierarchy { + root, + nodes, + home, + last_attended, + governing, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::patch::{ + AuthorityGrant, AuthorityKindName, EntityRecord, Office, OfficeName, Position, + }; + use crate::{ + ControllerAssignment, ControllerId, DecisionScope, PrincipalId, SubjectState, + }; + + struct Fixture { + state: WorldState, + next: u128, + } + + impl Fixture { + fn new() -> Self { + Self { + state: WorldState::empty( + WorldId(Uuid::from_u128(0xfeed)), + PrincipalId::new("owner"), + "Hierarchy".into(), + None, + ), + next: 1, + } + } + + fn uuid(&mut self) -> Uuid { + self.next += 1; + Uuid::from_u128(self.next) + } + + fn place(&mut self, label: &str, container: Option) -> EntityId { + let id = EntityId(self.uuid()); + self.state.entities.insert( + id, + EntityRecord { + label: label.into(), + kind: EntityKind::Place, + container, + }, + ); + id + } + + fn subject(&mut self, label: &str, kind: SubjectKind, at: Option) -> SubjectId { + let id = SubjectId(self.uuid()); + let controller_id = ControllerId(self.uuid()); + self.state.subjects.insert( + id, + SubjectState { + label: label.into(), + kind, + import_key: None, + }, + ); + self.state.controller_assignments.insert( + DecisionScope { subject_id: id }, + ControllerAssignment::NarrativePersona { controller_id }, + ); + if let Some(place) = at { + self.state.positions.insert(id, Position { place }); + } + id + } + + fn player(&mut self, at: EntityId) -> SubjectId { + let id = self.subject("Player", SubjectKind::Person, Some(at)); + let controller_id = ControllerId(self.uuid()); + self.state.controller_assignments.insert( + DecisionScope { subject_id: id }, + ControllerAssignment::Human { + controller_id, + principal: PrincipalId::new("player"), + }, + ); + id + } + + fn office(&mut self, institution: SubjectId, name: &str, incumbent: SubjectId) { + self.state.selection.entry(institution).or_default().insert( + OfficeName(name.into()), + Office { + incumbent: Some(incumbent), + delegated: [AuthorityKindName("rule".into())].into(), + }, + ); + } + + fn grant(&mut self, holder: SubjectId, over: AuthorityTarget) { + self.state.authority.entry(holder).or_default().insert(AuthorityGrant { + kind: AuthorityKindName("rule".into()), + over, + }); + } + } + + fn parent_of(hierarchy: &Hierarchy, node: NodeId) -> Option { + hierarchy.nodes[&node].parent + } + + fn inst(hierarchy: &Hierarchy, world: &WorldState, subject: SubjectId) -> NodeId { + let id = NodeId::of(world.world_id, &NodeAnchor::Institution(subject)); + assert!(hierarchy.nodes.contains_key(&id), "no institution node"); + id + } + + #[test] + fn hierarchy_is_deterministic_and_ids_survive_an_unrelated_commit() { + let mut f = Fixture::new(); + let town = f.place("Town", None); + let council = f.subject("Council", SubjectKind::Institution, None); + let alice = f.subject("Alice", SubjectKind::Person, Some(town)); + f.grant(council, AuthorityTarget::PlaceSubtree(town)); + f.office(council, "mayor", alice); + let first = derive_hierarchy(&f.state); + assert_eq!(first, derive_hierarchy(&f.state)); + assert_eq!( + serde_json::to_vec(&first).unwrap(), + serde_json::to_vec(&derive_hierarchy(&f.state)).unwrap() + ); + // Time passes and an unrelated subject acts: no node changes identity. + f.state.now = FictionalMinutes(500); + f.state.revision += 7; + f.state.last_opportunity_at.insert(alice, FictionalMinutes(40)); + let later = derive_hierarchy(&f.state); + assert_eq!( + first.nodes.keys().collect::>(), + later.nodes.keys().collect::>() + ); + assert_eq!(first.home, later.home); + assert_eq!(later.last_attended.get(&alice), Some(&FictionalMinutes(40))); + assert!(first.last_attended.is_empty()); + // The same anchor in another world is another node. + let other = NodeId::of(WorldId(Uuid::from_u128(0xbeef)), &NodeAnchor::World); + assert_ne!(other, first.root()); + } + + #[test] + fn every_voice_has_exactly_one_home_and_a_chain_to_the_root() { + let mut f = Fixture::new(); + let region = f.place("Region", None); + let town = f.place("Town", Some(region)); + let tavern = f.place("Tavern", Some(town)); + let empire = f.subject("Empire", SubjectKind::Institution, None); + let council = f.subject("Council", SubjectKind::Institution, Some(town)); + let guild = f.subject("Guild", SubjectKind::Institution, Some(tavern)); + let folk = f.subject("Townsfolk", SubjectKind::Population, Some(town)); + let alice = f.subject("Alice", SubjectKind::Person, Some(tavern)); + let bob = f.subject("Bob", SubjectKind::Person, Some(region)); + let nowhere = f.subject("Drifter", SubjectKind::Person, None); + let player = f.player(tavern); + f.grant(empire, AuthorityTarget::Subject(council)); + f.grant(council, AuthorityTarget::PlaceSubtree(town)); + f.office(guild, "master", alice); + let hierarchy = derive_hierarchy(&f.state); + + let voices = [empire, council, guild, folk, alice, bob, nowhere]; + for voice in voices { + let mut at = hierarchy.home[&voice]; + let mut seen = BTreeSet::new(); + loop { + assert!(seen.insert(at), "a chain revisited a node"); + match parent_of(&hierarchy, at) { + Some(up) => at = up, + None => break, + } + } + assert_eq!(at, hierarchy.root(), "a chain ended off the root"); + // Exactly one place holds it: as a child node or as a loose subject. + let holders = hierarchy + .nodes + .values() + .filter(|node| node.loose.contains(&voice) || { + node.anchor == NodeAnchor::Institution(voice) + }) + .count(); + assert_eq!(holders, 1, "a voice is held by {holders} nodes"); + } + assert_eq!(hierarchy.home.len(), voices.len() + 1, "the player is placed too"); + assert!(hierarchy.home.contains_key(&player)); + // A population is a single loose voice, hung by the same rule. + assert_eq!(hierarchy.home[&folk], inst(&hierarchy, &f.state, council)); + assert_eq!(hierarchy.home[&nowhere], hierarchy.root()); + // Children and parents agree. + for node in hierarchy.nodes.values() { + for child in &node.children { + assert_eq!(hierarchy.nodes[child].parent, Some(node.id)); + } + } + } + + #[test] + fn institutions_come_before_places() { + let mut f = Fixture::new(); + let town = f.place("Town", None); + let tap_room = f.place("Tap-room", Some(town)); + let field = f.place("Field", None); + let council = f.subject("Council", SubjectKind::Institution, None); + let guild = f.subject("Guild", SubjectKind::Institution, None); + let in_guild = f.subject("Guildsman", SubjectKind::Person, Some(tap_room)); + let plain = f.subject("Drinker", SubjectKind::Person, Some(tap_room)); + let farmer = f.subject("Farmer", SubjectKind::Person, Some(field)); + f.grant(council, AuthorityTarget::PlaceSubtree(town)); + f.office(guild, "member", in_guild); + let hierarchy = derive_hierarchy(&f.state); + assert_eq!(hierarchy.home[&in_guild], inst(&hierarchy, &f.state, guild)); + assert_eq!(hierarchy.home[&plain], inst(&hierarchy, &f.state, council)); + let field_node = NodeId::of(f.state.world_id, &NodeAnchor::Place(field)); + assert_eq!(hierarchy.home[&farmer], field_node); + assert_eq!(parent_of(&hierarchy, field_node), Some(hierarchy.root())); + // A place node exists only where somebody hangs from it. + assert_eq!( + hierarchy + .nodes + .values() + .filter(|node| matches!(node.anchor, NodeAnchor::Place(_))) + .count(), + 1 + ); + } + + #[test] + fn an_authority_grant_over_the_subject_beats_a_place_grant() { + let mut f = Fixture::new(); + let town = f.place("Town", None); + let council = f.subject("Council", SubjectKind::Institution, None); + let temple = f.subject("Temple", SubjectKind::Institution, None); + let priest = f.subject("Priest", SubjectKind::Person, Some(town)); + f.grant(council, AuthorityTarget::PlaceSubtree(town)); + f.grant(temple, AuthorityTarget::Subject(priest)); + let hierarchy = derive_hierarchy(&f.state); + assert_eq!(hierarchy.home[&priest], inst(&hierarchy, &f.state, temple)); + } + + #[test] + fn the_innermost_place_grant_governs_and_several_offices_pick_the_smaller_body() { + let mut f = Fixture::new(); + let region = f.place("Region", None); + let town = f.place("Town", Some(region)); + let crown = f.subject("Crown", SubjectKind::Institution, None); + let council = f.subject("Council", SubjectKind::Institution, None); + let big = f.subject("Big", SubjectKind::Institution, None); + let small = f.subject("Small", SubjectKind::Institution, None); + let walker = f.subject("Walker", SubjectKind::Person, Some(town)); + let other_a = f.subject("A", SubjectKind::Person, None); + let other_b = f.subject("B", SubjectKind::Person, None); + let sitter = f.subject("Sitter", SubjectKind::Person, Some(town)); + f.grant(crown, AuthorityTarget::PlaceSubtree(region)); + f.grant(council, AuthorityTarget::PlaceSubtree(town)); + f.office(big, "a", other_a); + f.office(big, "b", other_b); + f.office(big, "c", sitter); + f.office(small, "a", sitter); + let hierarchy = derive_hierarchy(&f.state); + assert_eq!(hierarchy.home[&walker], inst(&hierarchy, &f.state, council)); + assert_eq!(hierarchy.home[&sitter], inst(&hierarchy, &f.state, small)); + } + + #[test] + fn a_cycle_is_broken_at_its_lowest_id() { + let mut f = Fixture::new(); + let one = f.subject("One", SubjectKind::Institution, None); + let two = f.subject("Two", SubjectKind::Institution, None); + f.grant(one, AuthorityTarget::Subject(two)); + f.grant(two, AuthorityTarget::Subject(one)); + let (low, high) = if one < two { (one, two) } else { (two, one) }; + let hierarchy = derive_hierarchy(&f.state); + assert_eq!(hierarchy.home[&low], hierarchy.root()); + assert_eq!(hierarchy.home[&high], inst(&hierarchy, &f.state, low)); + } + + #[test] + fn a_tail_leading_into_a_cycle_keeps_its_parent_when_the_cycle_breaks() { + let mut f = Fixture::new(); + let tail = f.subject("Tail", SubjectKind::Institution, None); + let one = f.subject("One", SubjectKind::Institution, None); + let two = f.subject("Two", SubjectKind::Institution, None); + f.grant(one, AuthorityTarget::Subject(tail)); + f.grant(one, AuthorityTarget::Subject(two)); + f.grant(two, AuthorityTarget::Subject(one)); + let hierarchy = derive_hierarchy(&f.state); + assert_eq!(hierarchy.home[&tail], inst(&hierarchy, &f.state, one)); + assert_eq!(hierarchy.home[&one], hierarchy.root()); + assert_eq!(hierarchy.home[&two], inst(&hierarchy, &f.state, one)); + } + + #[test] + fn the_player_is_placed_and_never_a_voice() { + let mut f = Fixture::new(); + let town = f.place("Town", None); + let council = f.subject("Council", SubjectKind::Institution, None); + let player = f.player(town); + f.grant(council, AuthorityTarget::PlaceSubtree(town)); + f.office(council, "seat", player); + let hierarchy = derive_hierarchy(&f.state); + assert_eq!(hierarchy.home[&player], inst(&hierarchy, &f.state, council)); + assert!( + hierarchy + .nodes + .values() + .all(|node| node.voice != Some(player) && !node.loose.contains(&player)) + ); + assert!(!hierarchy.last_attended.contains_key(&player)); + } + + #[test] + fn the_focus_path_follows_governance() { + let mut f = Fixture::new(); + let town = f.place("Town", None); + let tap_room = f.place("Tap-room", Some(town)); + let heath = f.place("Heath", None); + let empire = f.subject("Empire", SubjectKind::Institution, None); + let council = f.subject("Council", SubjectKind::Institution, None); + f.subject("Drinker", SubjectKind::Person, Some(tap_room)); + f.grant(council, AuthorityTarget::PlaceSubtree(town)); + f.grant(empire, AuthorityTarget::Subject(council)); + let hierarchy = derive_hierarchy(&f.state); + assert_eq!( + hierarchy.focus_path(tap_room), + vec![ + inst(&hierarchy, &f.state, council), + inst(&hierarchy, &f.state, empire), + hierarchy.root(), + ] + ); + // An ungoverned place is governed by the root alone. + assert_eq!(hierarchy.focus_path(heath), vec![hierarchy.root()]); + } + + #[test] + fn a_place_node_hangs_from_the_nearest_enclosing_place_node() { + let mut f = Fixture::new(); + let region = f.place("Region", None); + let hamlet = f.place("Hamlet", Some(region)); + let barn = f.place("Barn", Some(hamlet)); + f.subject("Reeve", SubjectKind::Person, Some(region)); + f.subject("Hand", SubjectKind::Person, Some(barn)); + let hierarchy = derive_hierarchy(&f.state); + let region_node = NodeId::of(f.state.world_id, &NodeAnchor::Place(region)); + let barn_node = NodeId::of(f.state.world_id, &NodeAnchor::Place(barn)); + assert_eq!(parent_of(&hierarchy, barn_node), Some(region_node)); + assert_eq!( + hierarchy.focus_path(hamlet), + vec![region_node, hierarchy.root()] + ); + } +} diff --git a/crates/ghostlight/src/lib.rs b/crates/ghostlight/src/lib.rs index 7e03fd4..fe5cffd 100644 --- a/crates/ghostlight/src/lib.rs +++ b/crates/ghostlight/src/lib.rs @@ -54,6 +54,12 @@ //! ```compile_fail,E0425 //! let _ = ghostlight::fixture_inference_output("prose", "receipt"); //! ``` +//! +//! ```compile_fail,E0599 +//! fn no_lane_reads_it(port: &ghostlight::ControllerPort) { +//! let _ = port.hierarchy(); +//! } +//! ``` mod action; mod aetheria; @@ -64,6 +70,7 @@ mod controllers; mod cover; mod elaboration; mod grammar; +mod hierarchy; #[cfg(test)] mod import_key_tests; mod journal; @@ -104,6 +111,7 @@ pub use aetheria::{ AetheriaCatalog, AetheriaFaction, CatalogReadError, VerbRule, read_aetheria_catalog, }; pub use cover::{AgencyGraph, Cell, Cover, CoverBudget, CoverBudgetError, TickIndex, derive_cover}; +pub use hierarchy::{Hierarchy, Node, NodeAnchor, NodeId}; pub use elaboration::{ ElaborationCheckpoint, ElaborationRunner, ElaboratorSession, SweepReport, EvidenceError, EvidenceQuery, EvidenceReceipt, EvidenceSource, NullEvidenceSource, SeedCheckpoint, SeedOutcome, SeedRunner, select_row, @@ -1749,6 +1757,14 @@ impl WorldKernel { Ok(agency_graph(&self.state)) } + /// The gestalt hierarchy. Separate from `snapshot` for the reason + /// `agency_graph` is: it is wider than any subject view, so a field on + /// `WorldSnapshot` would be reachable from every prompt builder. + fn hierarchy(&self) -> Result { + self.journal.ensure_healthy()?; + Ok(hierarchy::derive_hierarchy(&self.state)) + } + fn submit( &mut self, command: CommandEnvelope, diff --git a/crates/ghostlight/src/mailbox.rs b/crates/ghostlight/src/mailbox.rs index aca0b9a..27a03a8 100644 --- a/crates/ghostlight/src/mailbox.rs +++ b/crates/ghostlight/src/mailbox.rs @@ -1,5 +1,5 @@ use super::{ - AgencyGraph, AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, CommandId, + AgencyGraph, AuthenticatedCaller, Hierarchy, CallerId, CommandBody, CommandEnvelope, CommandId, ConsumerId, CreateWorld, CreateWorldIntent, CreationReceipt, DecisionInvocation, DecisionOpportunity, Declaration, DraftHandle, EntityDeclaration, EntityKind, JurisdictionKey, KernelError, NewController, OperatorEvent, PatchAnswer, PrincipalCommandIntent, PrincipalId, @@ -83,6 +83,11 @@ enum Request { AgencyGraph { reply: oneshot::Sender>, }, + /// The gestalt hierarchy, derived from world state. Separate from + /// `Snapshot` as `AgencyGraph` is: only the tick driver may hold it. + Hierarchy { + reply: oneshot::Sender>, + }, /// The tick driver's opportunity list. Separate from `Snapshot` so the /// list a cover is derived from has one door, held by the driver. Opportunities { @@ -498,6 +503,23 @@ impl WorldMailbox { .map_err(MailboxError::Kernel) } + /// The tick driver's projection of the gestalt hierarchy, derived afresh + /// from the world on every call. It is on `WorldMailbox` and on neither + /// `ControllerPort` nor `ElaborationPort`, as `agency_graph` is: the tree + /// is wider than any subject view. + pub async fn hierarchy(&self) -> Result { + let (reply, response) = oneshot::channel(); + self.sender + .send(Request::Hierarchy { reply }) + .await + .map_err(|_| MailboxError::Unavailable)?; + + response + .await + .map_err(|_| MailboxError::Unavailable)? + .map_err(MailboxError::Kernel) + } + /// The tick driver's opportunity list, in snapshot order. It is on /// `WorldMailbox` and on no controller port, as `agency_graph` is. pub async fn opportunities(&self) -> Result, MailboxError> { @@ -1090,6 +1112,19 @@ async fn run_owner(mut owned: OwnedWorld, mut receiver: mpsc::Receiver) return; } } + Request::Hierarchy { reply } => { + let result = match &owned { + OwnedWorld::Empty(_) => Err(KernelError::WorldNotCreated), + OwnedWorld::Live(kernel) => kernel.hierarchy(), + }; + let owner_must_stop = result + .as_ref() + .is_err_and(KernelError::requires_owner_restart); + let _ = reply.send(result); + if owner_must_stop { + return; + } + } Request::Opportunities { reply } => { let result = match &owned { OwnedWorld::Empty(_) => Err(KernelError::WorldNotCreated), @@ -1248,6 +1283,22 @@ mod tests { } } + #[tokio::test] + async fn hierarchy_is_derived_from_the_world_through_the_mailbox() { + let (_directory, _path, mailbox, task, _authenticated, _input, _receipt) = fixture().await; + let hierarchy = mailbox.hierarchy().await.unwrap(); + let snapshot = mailbox.snapshot().await.unwrap(); + // The fixture world holds one Human operator in one room: placed under + // that room's node, no voice anywhere. + assert_eq!(hierarchy.home.len(), 1); + assert!(hierarchy.nodes.values().all(|node| node.voice.is_none() && node.loose.is_empty())); + assert_eq!(hierarchy.nodes.len(), 2); + assert_eq!(hierarchy, mailbox.hierarchy().await.unwrap()); + assert_eq!(snapshot.subjects.len(), 1); + drop(mailbox); + task.await.unwrap(); + } + #[tokio::test] async fn empty_owner_rejects_world_operations_then_accepts_creation() { let directory = tempfile::tempdir().unwrap();