wave: plan_wave, GestaltKnobs, Focus, AgencyGraph::restricted; grouped silent members stamp attended (cut-gestalt-planner r1)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
40a28c0b69
commit
31c36a37b7
5 changed files with 785 additions and 9 deletions
|
|
@ -16598,6 +16598,55 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur
|
|||
}
|
||||
}
|
||||
|
||||
/// A grouped member that proposes nothing still has its turn recorded: it
|
||||
/// declines, and the kernel stamps `last_opportunity_at`, which is what
|
||||
/// takes its node off the wave planner's due list.
|
||||
#[tokio::test]
|
||||
async fn a_grouped_member_that_proposes_nothing_is_stamped_attended() {
|
||||
let (_directory, mailbox, task) = active_cell_mailbox(vec![
|
||||
NewController::OperationalAgent,
|
||||
NewController::OperationalAgent,
|
||||
NewController::OperationalAgent,
|
||||
])
|
||||
.await;
|
||||
let cell = one_group(&mailbox).await;
|
||||
assert!(mailbox.hierarchy().await.unwrap().last_attended.is_empty());
|
||||
let (runner, _store) = grouped_runner(
|
||||
&mailbox,
|
||||
vec![
|
||||
output(
|
||||
vec![
|
||||
speak_call("c0", "c0__speak", "Hold the bridge."),
|
||||
InferenceEvent::ToolCall {
|
||||
call_id: "c1".into(),
|
||||
name: "c1__finish_without_proposal".into(),
|
||||
arguments: "{}".into(),
|
||||
},
|
||||
InferenceEvent::ToolCall {
|
||||
call_id: "c2".into(),
|
||||
name: "c2__finish_without_proposal".into(),
|
||||
arguments: "{}".into(),
|
||||
},
|
||||
],
|
||||
"silent-one",
|
||||
),
|
||||
output(vec![InferenceEvent::Text("Nothing further.".into())], "silent-two"),
|
||||
],
|
||||
);
|
||||
let CellRun::Grouped(run) = runner.run_cell(&cell).await.unwrap() else {
|
||||
panic!("a coarse cell did not run the grouped lane")
|
||||
};
|
||||
assert!(run.refused.is_empty(), "{:?}", run.refused);
|
||||
assert_eq!(run.submissions.len(), 3);
|
||||
let attended = mailbox.hierarchy().await.unwrap().last_attended;
|
||||
for member in cell.members() {
|
||||
assert!(attended.contains_key(&member.subject), "a member was left due");
|
||||
}
|
||||
drop(runner);
|
||||
drop(mailbox);
|
||||
task.await.unwrap();
|
||||
}
|
||||
|
||||
/// The call's arguments are not kept at all: only the name is.
|
||||
#[test]
|
||||
fn the_name_of_a_call_naming_no_handle_is_kept_and_its_arguments_are_not() {
|
||||
|
|
|
|||
|
|
@ -236,6 +236,27 @@ impl AgencyGraph {
|
|||
}
|
||||
}
|
||||
|
||||
/// The adjacency among `members` alone: one node's voices partition over
|
||||
/// the edges that run between them. A star's centre outside `members`
|
||||
/// leaves its rays unlinked, which is honest: they were adjacent through
|
||||
/// somebody who is not at this table.
|
||||
pub(crate) fn restricted(&self, members: &BTreeSet<SubjectId>) -> Self {
|
||||
Self {
|
||||
subjects: self
|
||||
.subjects
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|subject| members.contains(subject))
|
||||
.collect(),
|
||||
edges: self
|
||||
.edges
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|(one, other)| members.contains(one) && members.contains(other))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn link(&mut self, one: SubjectId, other: SubjectId) {
|
||||
if one == other {
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -88,6 +88,9 @@ pub struct Hierarchy {
|
|||
/// When each voice last consumed a decision opportunity; absent means
|
||||
/// never. Read from the kernel's `last_opportunity_at`.
|
||||
pub last_attended: BTreeMap<SubjectId, FictionalMinutes>,
|
||||
/// The voices that are populations. A closed place node still speaks for
|
||||
/// its populations; its persons are silent.
|
||||
pub populations: BTreeSet<SubjectId>,
|
||||
/// 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.
|
||||
|
|
@ -390,17 +393,29 @@ pub(super) fn derive_hierarchy(state: &WorldState) -> Hierarchy {
|
|||
})
|
||||
.collect();
|
||||
|
||||
let populations = voices
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|voice| {
|
||||
state
|
||||
.subjects
|
||||
.get(voice)
|
||||
.is_some_and(|record| record.kind == SubjectKind::Population)
|
||||
})
|
||||
.collect();
|
||||
|
||||
Hierarchy {
|
||||
root,
|
||||
nodes,
|
||||
home,
|
||||
last_attended,
|
||||
populations,
|
||||
governing,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
use crate::patch::{
|
||||
AuthorityGrant, AuthorityKindName, EntityRecord, Office, OfficeName, Position,
|
||||
|
|
@ -409,13 +424,13 @@ mod tests {
|
|||
ControllerAssignment, ControllerId, DecisionScope, PrincipalId, SubjectState,
|
||||
};
|
||||
|
||||
struct Fixture {
|
||||
state: WorldState,
|
||||
pub(crate) struct Fixture {
|
||||
pub(crate) state: WorldState,
|
||||
next: u128,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
state: WorldState::empty(
|
||||
WorldId(Uuid::from_u128(0xfeed)),
|
||||
|
|
@ -432,7 +447,7 @@ mod tests {
|
|||
Uuid::from_u128(self.next)
|
||||
}
|
||||
|
||||
fn place(&mut self, label: &str, container: Option<EntityId>) -> EntityId {
|
||||
pub(crate) fn place(&mut self, label: &str, container: Option<EntityId>) -> EntityId {
|
||||
let id = EntityId(self.uuid());
|
||||
self.state.entities.insert(
|
||||
id,
|
||||
|
|
@ -445,7 +460,7 @@ mod tests {
|
|||
id
|
||||
}
|
||||
|
||||
fn subject(&mut self, label: &str, kind: SubjectKind, at: Option<EntityId>) -> SubjectId {
|
||||
pub(crate) fn subject(&mut self, label: &str, kind: SubjectKind, at: Option<EntityId>) -> SubjectId {
|
||||
let id = SubjectId(self.uuid());
|
||||
let controller_id = ControllerId(self.uuid());
|
||||
self.state.subjects.insert(
|
||||
|
|
@ -466,7 +481,7 @@ mod tests {
|
|||
id
|
||||
}
|
||||
|
||||
fn player(&mut self, at: EntityId) -> SubjectId {
|
||||
pub(crate) 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(
|
||||
|
|
@ -479,7 +494,7 @@ mod tests {
|
|||
id
|
||||
}
|
||||
|
||||
fn office(&mut self, institution: SubjectId, name: &str, incumbent: SubjectId) {
|
||||
pub(crate) fn office(&mut self, institution: SubjectId, name: &str, incumbent: SubjectId) {
|
||||
self.state.selection.entry(institution).or_default().insert(
|
||||
OfficeName(name.into()),
|
||||
Office {
|
||||
|
|
@ -489,7 +504,7 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
fn grant(&mut self, holder: SubjectId, over: AuthorityTarget) {
|
||||
pub(crate) fn grant(&mut self, holder: SubjectId, over: AuthorityTarget) {
|
||||
self.state.authority.entry(holder).or_default().insert(AuthorityGrant {
|
||||
kind: AuthorityKindName("rule".into()),
|
||||
over,
|
||||
|
|
|
|||
|
|
@ -83,6 +83,7 @@ mod table;
|
|||
mod tool_schema;
|
||||
mod vault;
|
||||
mod verse;
|
||||
mod wave;
|
||||
|
||||
pub(crate) use action::ActionMismatch;
|
||||
pub(crate) use attitude::{
|
||||
|
|
@ -112,6 +113,9 @@ pub use aetheria::{
|
|||
};
|
||||
pub use cover::{AgencyGraph, Cell, Cover, CoverBudget, CoverBudgetError, TickIndex, derive_cover};
|
||||
pub use hierarchy::{Hierarchy, Node, NodeAnchor, NodeId};
|
||||
pub use wave::{
|
||||
Deferral, Focus, GestaltKnobs, GestaltKnobsError, NodeTurn, Wave, WaveClock, plan_wave,
|
||||
};
|
||||
pub use elaboration::{
|
||||
ElaborationCheckpoint, ElaborationRunner, ElaboratorSession, SweepReport, EvidenceError, EvidenceQuery,
|
||||
EvidenceReceipt, EvidenceSource, NullEvidenceSource, SeedCheckpoint, SeedOutcome, SeedRunner, select_row,
|
||||
|
|
|
|||
687
crates/ghostlight/src/wave.rs
Normal file
687
crates/ghostlight/src/wave.rs
Normal file
|
|
@ -0,0 +1,687 @@
|
|||
//! The wave planner: one pure function that says which nodes of the hierarchy
|
||||
//! take a turn now, and how each node's voices partition into cells.
|
||||
//!
|
||||
//! This organ owns the plan and nothing else. [`plan_wave`] is pure over its
|
||||
//! arguments: no clock read, no entropy, no mailbox, no filesystem, no store.
|
||||
//! Due-ness is derived from the kernel's `last_opportunity_at` (carried in the
|
||||
//! hierarchy as `last_attended`), so there is no schedule to keep in step with
|
||||
//! the world. A [`Wave`] is derived and disposable like a cover, and it never
|
||||
//! enters world state: the kernel learns a wave happened only through ordinary
|
||||
//! one-opportunity submissions.
|
||||
//!
|
||||
//! The focus opens the hierarchy: from each focused place's governing node up
|
||||
//! `depth` nodes. An open node speaks in detail for its own anchor, its loose
|
||||
//! subjects and the anchors of its closed institution children. A closed
|
||||
//! institution speaks only through its anchor; a closed place or the root
|
||||
//! speaks for its populations and for its closed institution children, and the
|
||||
//! persons under it are silent and accrue attention debt in the kernel.
|
||||
//!
|
||||
//! A node is due when its band's period has passed since its most neglected
|
||||
//! voice was last attended; a voice never attended makes it due. Periods are
|
||||
//! fictional minutes by distance from the focus, the last band covering the
|
||||
//! rest. `max_node_turns` bounds how many due nodes run, nearest first; the
|
||||
//! rest are reported, never dropped. Inside a node [`derive_cover`] partitions
|
||||
//! the voices with the wave ordinal as its tick, so its rotation guarantee and
|
||||
//! its oversubscription signal hold per node.
|
||||
|
||||
use super::{
|
||||
AgencyGraph, Cell, CoverBudget, CoverBudgetError, DecisionOpportunity, EntityId,
|
||||
FictionalMinutes, SubjectId, TickIndex, TickMinutes, WorldId, derive_cover,
|
||||
hierarchy::{Hierarchy, Node, NodeAnchor, NodeId},
|
||||
};
|
||||
use std::collections::{BTreeMap, BTreeSet, VecDeque};
|
||||
|
||||
/// The standing knobs: how often each distance band runs, how far the focus
|
||||
/// opens, how many node turns one wave may spend, and the per-node cover.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct GestaltKnobs {
|
||||
/// Period in fictional minutes. Index is hierarchy distance from the
|
||||
/// focus; the last band is the rest.
|
||||
pub bands: Vec<TickMinutes>,
|
||||
/// How many nodes along each focus path are open.
|
||||
pub depth: u8,
|
||||
/// N: node turns per wave.
|
||||
pub max_node_turns: u16,
|
||||
/// The cover budget each node's voices partition under.
|
||||
pub cover: CoverBudget,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
|
||||
pub enum GestaltKnobsError {
|
||||
#[error("a wave needs at least one rate band")]
|
||||
NoBands,
|
||||
#[error("a wave must allow at least one node turn")]
|
||||
NoNodeTurns,
|
||||
#[error(transparent)]
|
||||
Cover(#[from] CoverBudgetError),
|
||||
}
|
||||
|
||||
impl GestaltKnobs {
|
||||
pub fn validate(&self) -> Result<(), GestaltKnobsError> {
|
||||
if self.bands.is_empty() {
|
||||
return Err(GestaltKnobsError::NoBands);
|
||||
}
|
||||
if self.max_node_turns < 1 {
|
||||
return Err(GestaltKnobsError::NoNodeTurns);
|
||||
}
|
||||
self.cover.validated()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn period(&self, distance: u8) -> u32 {
|
||||
let band = usize::from(distance).min(self.bands.len() - 1);
|
||||
self.bands[band].minutes()
|
||||
}
|
||||
}
|
||||
|
||||
/// Where attention is. Both empty is the verse shape: no focus, the whole
|
||||
/// tree planned from its root at the rest rate.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Focus {
|
||||
pub places: Vec<EntityId>,
|
||||
pub nodes: Vec<NodeId>,
|
||||
}
|
||||
|
||||
/// The wave's identity inputs: the world, the ordinal that rotates each node's
|
||||
/// cover, and the fictional time due-ness is measured at.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct WaveClock {
|
||||
pub world: WorldId,
|
||||
pub ordinal: TickIndex,
|
||||
pub now: FictionalMinutes,
|
||||
}
|
||||
|
||||
/// One node's turn: its voices partitioned into cells.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct NodeTurn {
|
||||
pub node: NodeId,
|
||||
/// Hierarchy distance from the focus; with no focus, the rest band's index.
|
||||
pub distance: u8,
|
||||
pub open: bool,
|
||||
pub cells: Vec<Cell>,
|
||||
/// The cover's signal that the cap yielded inside this node.
|
||||
pub oversubscribed: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Deferral {
|
||||
/// Its band's period has not passed since its most neglected voice.
|
||||
NotDue,
|
||||
/// Due, but the wave's node-turn bound ran out first.
|
||||
OverBound,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Wave {
|
||||
pub world: WorldId,
|
||||
pub ordinal: TickIndex,
|
||||
pub knobs: GestaltKnobs,
|
||||
/// Nearest to the focus first.
|
||||
pub turns: Vec<NodeTurn>,
|
||||
pub deferred: Vec<(NodeId, Deferral)>,
|
||||
/// Active voices that take no turn because their node is closed, by node.
|
||||
pub silent: Vec<(NodeId, Vec<SubjectId>)>,
|
||||
}
|
||||
|
||||
/// Every node an open path or the verse shape opens, and every node's distance
|
||||
/// from the focus.
|
||||
fn open_and_distance(
|
||||
hierarchy: &Hierarchy,
|
||||
focus: &Focus,
|
||||
knobs: &GestaltKnobs,
|
||||
) -> (BTreeSet<NodeId>, BTreeMap<NodeId, u8>) {
|
||||
let depth = usize::from(knobs.depth);
|
||||
let rest = u8::try_from(knobs.bands.len() - 1).unwrap_or(u8::MAX);
|
||||
let mut paths: Vec<Vec<NodeId>> = focus
|
||||
.places
|
||||
.iter()
|
||||
.map(|place| hierarchy.focus_path(*place))
|
||||
.collect();
|
||||
for node in &focus.nodes {
|
||||
let mut path = Vec::new();
|
||||
let mut current = hierarchy.nodes.contains_key(node).then_some(*node);
|
||||
while let Some(id) = current {
|
||||
path.push(id);
|
||||
current = hierarchy.nodes.get(&id).and_then(|record| record.parent);
|
||||
}
|
||||
paths.push(path);
|
||||
}
|
||||
paths.retain(|path| !path.is_empty());
|
||||
|
||||
if paths.is_empty() {
|
||||
// The verse shape: from the root down `depth` levels, all at the rest
|
||||
// rate.
|
||||
let mut open = BTreeSet::new();
|
||||
let mut queue = VecDeque::from([(hierarchy.root(), 0usize)]);
|
||||
while let Some((id, level)) = queue.pop_front() {
|
||||
if level >= depth {
|
||||
continue;
|
||||
}
|
||||
open.insert(id);
|
||||
if let Some(node) = hierarchy.nodes.get(&id) {
|
||||
queue.extend(node.children.iter().map(|child| (*child, level + 1)));
|
||||
}
|
||||
}
|
||||
return (open, hierarchy.nodes.keys().map(|id| (*id, rest)).collect());
|
||||
}
|
||||
|
||||
let open = paths
|
||||
.iter()
|
||||
.flat_map(|path| path.iter().take(depth).copied())
|
||||
.collect();
|
||||
let mut distance: BTreeMap<NodeId, u8> = BTreeMap::new();
|
||||
let mut queue = VecDeque::new();
|
||||
for path in &paths {
|
||||
if distance.insert(path[0], 0).is_none() {
|
||||
queue.push_back(path[0]);
|
||||
}
|
||||
}
|
||||
while let Some(id) = queue.pop_front() {
|
||||
let here = distance[&id];
|
||||
let node = &hierarchy.nodes[&id];
|
||||
for next in node.parent.iter().chain(node.children.iter()) {
|
||||
if !distance.contains_key(next) {
|
||||
distance.insert(*next, here.saturating_add(1));
|
||||
queue.push_back(*next);
|
||||
}
|
||||
}
|
||||
}
|
||||
(open, distance)
|
||||
}
|
||||
|
||||
/// A closed institution child whose parent speaks for it: its anchor is one of
|
||||
/// the parent's voices and it takes no turn of its own.
|
||||
fn folded(hierarchy: &Hierarchy, open: &BTreeSet<NodeId>, node: &Node) -> bool {
|
||||
matches!(node.anchor, NodeAnchor::Institution(_))
|
||||
&& !open.contains(&node.id)
|
||||
&& node
|
||||
.parent
|
||||
.and_then(|parent| hierarchy.nodes.get(&parent))
|
||||
.is_some_and(|parent| {
|
||||
open.contains(&parent.id)
|
||||
|| !matches!(parent.anchor, NodeAnchor::Institution(_))
|
||||
})
|
||||
}
|
||||
|
||||
/// The wave: pure over its arguments. `opportunities` arrives in the kernel's
|
||||
/// attention order and is never re-sorted; `graph` is the whole agency graph,
|
||||
/// restricted here to each node's voices.
|
||||
pub fn plan_wave(
|
||||
clock: WaveClock,
|
||||
hierarchy: &Hierarchy,
|
||||
opportunities: &[DecisionOpportunity],
|
||||
graph: &AgencyGraph,
|
||||
focus: &Focus,
|
||||
knobs: &GestaltKnobs,
|
||||
) -> Result<Wave, GestaltKnobsError> {
|
||||
knobs.validate()?;
|
||||
let (open, distance) = open_and_distance(hierarchy, focus, knobs);
|
||||
let active: BTreeSet<SubjectId> = opportunities
|
||||
.iter()
|
||||
.filter(|opportunity| opportunity.controller_mode != super::ControllerMode::Human)
|
||||
.map(|opportunity| opportunity.scope.subject_id)
|
||||
.collect();
|
||||
|
||||
// Each node that takes a turn, with the voices it speaks for.
|
||||
let mut silent: Vec<(NodeId, Vec<SubjectId>)> = Vec::new();
|
||||
let mut units: Vec<(NodeId, u8, BTreeSet<SubjectId>)> = Vec::new();
|
||||
for node in hierarchy.nodes.values() {
|
||||
if folded(hierarchy, &open, node) {
|
||||
let quiet: Vec<SubjectId> = node
|
||||
.loose
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|voice| active.contains(voice))
|
||||
.collect();
|
||||
if !quiet.is_empty() {
|
||||
silent.push((node.id, quiet));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let is_open = open.contains(&node.id);
|
||||
let closed_institution = !is_open && matches!(node.anchor, NodeAnchor::Institution(_));
|
||||
let mut voices: BTreeSet<SubjectId> = node.voice.into_iter().collect();
|
||||
let mut quiet: Vec<SubjectId> = Vec::new();
|
||||
for loose in &node.loose {
|
||||
if !closed_institution && (is_open || hierarchy.populations.contains(loose)) {
|
||||
voices.insert(*loose);
|
||||
} else {
|
||||
quiet.push(*loose);
|
||||
}
|
||||
}
|
||||
if !closed_institution {
|
||||
for child in &node.children {
|
||||
let child = &hierarchy.nodes[child];
|
||||
if folded(hierarchy, &open, child) {
|
||||
voices.extend(child.voice);
|
||||
}
|
||||
}
|
||||
}
|
||||
voices.retain(|voice| active.contains(voice));
|
||||
quiet.retain(|voice| active.contains(voice));
|
||||
if !quiet.is_empty() {
|
||||
silent.push((node.id, quiet));
|
||||
}
|
||||
if !voices.is_empty() {
|
||||
let at = distance.get(&node.id).copied().unwrap_or(u8::MAX);
|
||||
units.push((node.id, at, voices));
|
||||
}
|
||||
}
|
||||
|
||||
// Due-ness: the most neglected voice against the band's period. `None`
|
||||
// sorts first, so a never-attended voice is both due and most neglected.
|
||||
let mut due: Vec<(u8, Option<FictionalMinutes>, NodeId)> = Vec::new();
|
||||
let mut deferred: Vec<(NodeId, Deferral)> = Vec::new();
|
||||
for (id, at, voices) in &units {
|
||||
let oldest = if voices.iter().all(|voice| hierarchy.last_attended.contains_key(voice)) {
|
||||
voices
|
||||
.iter()
|
||||
.filter_map(|voice| hierarchy.last_attended.get(voice).copied())
|
||||
.min()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let is_due = match oldest {
|
||||
None => true,
|
||||
Some(stamp) => clock.now.since(stamp) >= u64::from(knobs.period(*at)),
|
||||
};
|
||||
if is_due {
|
||||
due.push((*at, oldest, *id));
|
||||
} else {
|
||||
deferred.push((*id, Deferral::NotDue));
|
||||
}
|
||||
}
|
||||
due.sort();
|
||||
let bound = usize::from(knobs.max_node_turns);
|
||||
for (_, _, id) in due.iter().skip(bound) {
|
||||
deferred.push((*id, Deferral::OverBound));
|
||||
}
|
||||
|
||||
let mut turns = Vec::new();
|
||||
for (at, _, id) in due.into_iter().take(bound) {
|
||||
let voices = &units
|
||||
.iter()
|
||||
.find(|(unit, _, _)| *unit == id)
|
||||
.expect("a due node came from the units")
|
||||
.2;
|
||||
let own: Vec<DecisionOpportunity> = opportunities
|
||||
.iter()
|
||||
.filter(|opportunity| voices.contains(&opportunity.scope.subject_id))
|
||||
.cloned()
|
||||
.collect();
|
||||
let cover = derive_cover(
|
||||
clock.world,
|
||||
clock.ordinal,
|
||||
&own,
|
||||
&graph.restricted(voices),
|
||||
knobs.cover,
|
||||
);
|
||||
turns.push(NodeTurn {
|
||||
node: id,
|
||||
distance: at,
|
||||
open: open.contains(&id),
|
||||
cells: cover.cells,
|
||||
oversubscribed: cover.oversubscribed,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(Wave {
|
||||
world: clock.world,
|
||||
ordinal: clock.ordinal,
|
||||
knobs: knobs.clone(),
|
||||
turns,
|
||||
deferred,
|
||||
silent,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::hierarchy::{derive_hierarchy, tests::Fixture};
|
||||
use crate::patch::AuthorityTarget;
|
||||
use crate::{ControllerMode, DecisionScope, ScopeDigest, SubjectKind, WorldState};
|
||||
use uuid::Uuid;
|
||||
|
||||
fn opportunities(state: &WorldState) -> Vec<DecisionOpportunity> {
|
||||
state
|
||||
.controller_assignments
|
||||
.iter()
|
||||
.filter_map(|(scope, controller)| {
|
||||
let mode = controller.mode().filter(|mode| *mode != ControllerMode::Human)?;
|
||||
Some(DecisionOpportunity {
|
||||
world_id: state.world_id,
|
||||
revision: 1,
|
||||
scope_digest: ScopeDigest::fixture(&format!("{:?}", scope.subject_id)),
|
||||
scope: DecisionScope {
|
||||
subject_id: scope.subject_id,
|
||||
},
|
||||
controller_id: serde_json::from_value(serde_json::json!(
|
||||
Uuid::from_u128(1).to_string()
|
||||
))
|
||||
.expect("a controller id parses from its canonical uuid"),
|
||||
controller_mode: mode,
|
||||
affordance_ids: Vec::new(),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn minutes(values: &[u32]) -> Vec<TickMinutes> {
|
||||
values.iter().map(|v| TickMinutes::new(*v).unwrap()).collect()
|
||||
}
|
||||
|
||||
fn knobs(bands: &[u32], depth: u8, max_node_turns: u16) -> GestaltKnobs {
|
||||
GestaltKnobs {
|
||||
bands: minutes(bands),
|
||||
depth,
|
||||
max_node_turns,
|
||||
cover: CoverBudget {
|
||||
cells: 8,
|
||||
constituent_cap: 8,
|
||||
urgency_slots: 2,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn plan(
|
||||
f: &Fixture,
|
||||
hierarchy: &Hierarchy,
|
||||
focus: &Focus,
|
||||
knobs: &GestaltKnobs,
|
||||
now: u64,
|
||||
) -> Wave {
|
||||
let world = f.state.world_id;
|
||||
plan_wave(
|
||||
WaveClock {
|
||||
world,
|
||||
ordinal: TickIndex(7),
|
||||
now: FictionalMinutes(now),
|
||||
},
|
||||
hierarchy,
|
||||
&opportunities(&f.state),
|
||||
&AgencyGraph::default(),
|
||||
focus,
|
||||
knobs,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn voices_of(wave: &Wave, node: NodeId) -> BTreeSet<SubjectId> {
|
||||
wave.turns
|
||||
.iter()
|
||||
.filter(|turn| turn.node == node)
|
||||
.flat_map(|turn| turn.cells.iter())
|
||||
.flat_map(|cell| cell.members().iter().map(|member| member.subject))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn node(f: &Fixture, anchor: NodeAnchor) -> NodeId {
|
||||
NodeId::of(f.state.world_id, &anchor)
|
||||
}
|
||||
|
||||
struct Realm {
|
||||
f: Fixture,
|
||||
tap_room: EntityId,
|
||||
crown: SubjectId,
|
||||
empire: SubjectId,
|
||||
council: SubjectId,
|
||||
drinker: SubjectId,
|
||||
herald: SubjectId,
|
||||
courtier: SubjectId,
|
||||
wanderers: SubjectId,
|
||||
}
|
||||
|
||||
/// tap-room under council under empire under crown under the root; a
|
||||
/// herald hangs from the empire, a courtier from the crown, a population
|
||||
/// from the root.
|
||||
fn realm() -> Realm {
|
||||
let mut f = Fixture::new();
|
||||
let town = f.place("Town", None);
|
||||
let tap_room = f.place("Tap-room", Some(town));
|
||||
let crown = f.subject("Crown", SubjectKind::Institution, None);
|
||||
let empire = f.subject("Empire", SubjectKind::Institution, None);
|
||||
let council = f.subject("Council", SubjectKind::Institution, None);
|
||||
let drinker = f.subject("Drinker", SubjectKind::Person, Some(tap_room));
|
||||
let herald = f.subject("Herald", SubjectKind::Person, None);
|
||||
let courtier = f.subject("Courtier", SubjectKind::Person, None);
|
||||
let wanderers = f.subject("Wanderers", SubjectKind::Population, None);
|
||||
f.grant(council, AuthorityTarget::PlaceSubtree(town));
|
||||
f.grant(empire, AuthorityTarget::Subject(council));
|
||||
f.grant(crown, AuthorityTarget::Subject(empire));
|
||||
f.grant(empire, AuthorityTarget::Subject(herald));
|
||||
f.grant(crown, AuthorityTarget::Subject(courtier));
|
||||
Realm {
|
||||
f,
|
||||
tap_room,
|
||||
crown,
|
||||
empire,
|
||||
council,
|
||||
drinker,
|
||||
herald,
|
||||
courtier,
|
||||
wanderers,
|
||||
}
|
||||
}
|
||||
|
||||
fn at_tap_room(realm: &Realm) -> Focus {
|
||||
Focus {
|
||||
places: vec![realm.tap_room],
|
||||
nodes: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_node_is_due_by_its_band_and_not_a_minute_sooner() {
|
||||
let r = realm();
|
||||
let focus = at_tap_room(&r);
|
||||
let knobs = knobs(&[10, 360, 5000], 3, 16);
|
||||
let empire_node = node(&r.f, NodeAnchor::Institution(r.empire));
|
||||
for (gap, due) in [(360u64, true), (359, false)] {
|
||||
let mut hierarchy = derive_hierarchy(&r.f.state);
|
||||
for voice in [r.empire, r.herald] {
|
||||
hierarchy.last_attended.insert(voice, FictionalMinutes(1000 - gap));
|
||||
}
|
||||
let wave = plan(&r.f, &hierarchy, &focus, &knobs, 1000);
|
||||
let ran = wave.turns.iter().any(|turn| turn.node == empire_node);
|
||||
assert_eq!(ran, due, "gap {gap}");
|
||||
assert_eq!(
|
||||
wave.deferred.contains(&(empire_node, Deferral::NotDue)),
|
||||
!due
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_most_neglected_voice_sets_due_and_a_never_attended_voice_is_due() {
|
||||
let r = realm();
|
||||
let focus = at_tap_room(&r);
|
||||
let knobs = knobs(&[10, 360, 5000], 3, 16);
|
||||
let empire_node = node(&r.f, NodeAnchor::Institution(r.empire));
|
||||
let mut hierarchy = derive_hierarchy(&r.f.state);
|
||||
// The empire was attended a minute ago; the herald never was.
|
||||
hierarchy.last_attended.insert(r.empire, FictionalMinutes(999));
|
||||
let wave = plan(&r.f, &hierarchy, &focus, &knobs, 1000);
|
||||
assert!(wave.turns.iter().any(|turn| turn.node == empire_node));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_focus_opens_to_depth_and_a_closed_institution_speaks_only_through_its_anchor() {
|
||||
let r = realm();
|
||||
let hierarchy = derive_hierarchy(&r.f.state);
|
||||
let wave = plan(&r.f, &hierarchy, &at_tap_room(&r), &knobs(&[1, 1, 1, 1], 2, 16), 10);
|
||||
let council = node(&r.f, NodeAnchor::Institution(r.council));
|
||||
let empire = node(&r.f, NodeAnchor::Institution(r.empire));
|
||||
let crown = node(&r.f, NodeAnchor::Institution(r.crown));
|
||||
let open = |id| wave.turns.iter().find(|turn| turn.node == id).map(|turn| turn.open);
|
||||
assert_eq!(open(council), Some(true));
|
||||
assert_eq!(open(empire), Some(true));
|
||||
assert_eq!(open(crown), None, "the crown is folded under the closed root");
|
||||
// The empire speaks for itself and its herald; the council for itself
|
||||
// and the drinker; the closed crown through the root, courtier silent.
|
||||
assert_eq!(
|
||||
voices_of(&wave, empire),
|
||||
BTreeSet::from([r.empire, r.herald])
|
||||
);
|
||||
assert_eq!(voices_of(&wave, council), BTreeSet::from([r.council, r.drinker]));
|
||||
assert_eq!(
|
||||
voices_of(&wave, hierarchy.root()),
|
||||
BTreeSet::from([r.crown, r.wanderers])
|
||||
);
|
||||
assert!(wave.silent.contains(&(crown, vec![r.courtier])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_voice_takes_two_cells_in_one_wave() {
|
||||
let r = realm();
|
||||
let hierarchy = derive_hierarchy(&r.f.state);
|
||||
let mut small = knobs(&[1, 1, 1, 1], 4, 16);
|
||||
small.cover = CoverBudget {
|
||||
cells: 1,
|
||||
constituent_cap: 8,
|
||||
urgency_slots: 0,
|
||||
};
|
||||
for depth in 0..5 {
|
||||
small.depth = depth;
|
||||
let wave = plan(&r.f, &hierarchy, &at_tap_room(&r), &small, 10);
|
||||
let mut seen = BTreeSet::new();
|
||||
for turn in &wave.turns {
|
||||
for cell in &turn.cells {
|
||||
for member in cell.members() {
|
||||
assert!(seen.insert(member.subject), "twice at depth {depth}");
|
||||
}
|
||||
}
|
||||
}
|
||||
let cells: Vec<_> = wave.turns.iter().flat_map(|turn| turn.cells.iter()).collect();
|
||||
let ids: BTreeSet<_> = cells
|
||||
.iter()
|
||||
.map(|cell| match cell {
|
||||
Cell::Singleton { id, .. } | Cell::Group { id, .. } => *id,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(ids.len(), cells.len(), "a cell id repeated");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bound_defers_the_farthest_due_nodes_and_drops_none() {
|
||||
let r = realm();
|
||||
let hierarchy = derive_hierarchy(&r.f.state);
|
||||
let wave = plan(&r.f, &hierarchy, &at_tap_room(&r), &knobs(&[1, 1, 1, 1], 3, 2), 10);
|
||||
let council = node(&r.f, NodeAnchor::Institution(r.council));
|
||||
let empire = node(&r.f, NodeAnchor::Institution(r.empire));
|
||||
let crown = node(&r.f, NodeAnchor::Institution(r.crown));
|
||||
assert_eq!(
|
||||
wave.turns.iter().map(|turn| turn.node).collect::<Vec<_>>(),
|
||||
vec![council, empire]
|
||||
);
|
||||
assert_eq!(
|
||||
wave.deferred,
|
||||
vec![
|
||||
(crown, Deferral::OverBound),
|
||||
(hierarchy.root(), Deferral::OverBound)
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_inputs_give_the_same_wave() {
|
||||
let r = realm();
|
||||
let hierarchy = derive_hierarchy(&r.f.state);
|
||||
let knobs = knobs(&[1, 1, 1, 1], 3, 16);
|
||||
let one = plan(&r.f, &hierarchy, &at_tap_room(&r), &knobs, 10);
|
||||
let two = plan(&r.f, &hierarchy, &at_tap_room(&r), &knobs, 10);
|
||||
assert_eq!(one, two);
|
||||
assert_eq!(format!("{one:?}"), format!("{two:?}"));
|
||||
let later = plan_wave(
|
||||
WaveClock {
|
||||
world: r.f.state.world_id,
|
||||
ordinal: TickIndex(8),
|
||||
now: FictionalMinutes(10),
|
||||
},
|
||||
&hierarchy,
|
||||
&opportunities(&r.f.state),
|
||||
&AgencyGraph::default(),
|
||||
&at_tap_room(&r),
|
||||
&knobs,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(one.turns.len(), later.turns.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_focus_plans_from_the_root_at_the_rest_rate() {
|
||||
let r = realm();
|
||||
let mut hierarchy = derive_hierarchy(&r.f.state);
|
||||
let knobs = knobs(&[10, 500], 2, 16);
|
||||
let root = hierarchy.root();
|
||||
let crown = node(&r.f, NodeAnchor::Institution(r.crown));
|
||||
// The root and the crown, its one child, are open.
|
||||
for voice in [r.wanderers, r.crown] {
|
||||
hierarchy.last_attended.insert(voice, FictionalMinutes(1000 - 499));
|
||||
}
|
||||
let wave = plan(&r.f, &hierarchy, &Focus::default(), &knobs, 1000);
|
||||
assert!(!wave.turns.iter().any(|turn| turn.node == root));
|
||||
assert!(wave.deferred.contains(&(root, Deferral::NotDue)));
|
||||
assert!(wave.turns.iter().all(|turn| turn.distance == 1));
|
||||
for voice in [r.wanderers, r.crown] {
|
||||
hierarchy.last_attended.insert(voice, FictionalMinutes(1000 - 500));
|
||||
}
|
||||
let wave = plan(&r.f, &hierarchy, &Focus::default(), &knobs, 1000);
|
||||
let root_turn = wave.turns.iter().find(|turn| turn.node == root).unwrap();
|
||||
assert!(root_turn.open);
|
||||
assert!(wave.turns.iter().any(|turn| turn.node == crown && turn.open));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persons_under_a_closed_place_take_no_turn_and_the_wave_names_their_node() {
|
||||
let mut r = realm();
|
||||
let field = r.f.place("Field", None);
|
||||
let farmer = r.f.subject("Farmer", SubjectKind::Person, Some(field));
|
||||
let herd = r.f.subject("Herd", SubjectKind::Population, Some(field));
|
||||
let hierarchy = derive_hierarchy(&r.f.state);
|
||||
let wave = plan(&r.f, &hierarchy, &at_tap_room(&r), &knobs(&[1, 1, 1, 1, 1], 1, 16), 10);
|
||||
let field_node = node(&r.f, NodeAnchor::Place(field));
|
||||
assert_eq!(voices_of(&wave, field_node), BTreeSet::from([herd]));
|
||||
assert!(wave.silent.contains(&(field_node, vec![farmer])));
|
||||
let all: BTreeSet<_> = wave
|
||||
.turns
|
||||
.iter()
|
||||
.flat_map(|turn| turn.cells.iter())
|
||||
.flat_map(|cell| cell.members().iter().map(|m| m.subject))
|
||||
.collect();
|
||||
assert!(!all.contains(&farmer));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_node_leaves_the_due_list_once_its_voices_are_attended() {
|
||||
// A decline stamps last_opportunity_at, so the hierarchy reads the
|
||||
// voice as attended and the node is not due again before its period.
|
||||
let mut r = realm();
|
||||
let focus = at_tap_room(&r);
|
||||
let knobs = knobs(&[100, 100, 100, 100], 4, 16);
|
||||
let council = node(&r.f, NodeAnchor::Institution(r.council));
|
||||
r.f.state.now = FictionalMinutes(500);
|
||||
for voice in [r.council, r.drinker] {
|
||||
r.f.state.last_opportunity_at.insert(voice, r.f.state.now);
|
||||
}
|
||||
let hierarchy = derive_hierarchy(&r.f.state);
|
||||
let wave = plan(&r.f, &hierarchy, &focus, &knobs, 500);
|
||||
assert!(wave.deferred.contains(&(council, Deferral::NotDue)));
|
||||
let wave = plan(&r.f, &hierarchy, &focus, &knobs, 600);
|
||||
assert!(wave.turns.iter().any(|turn| turn.node == council));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn knobs_without_bands_or_turns_are_refused() {
|
||||
let mut bad = knobs(&[1], 1, 1);
|
||||
bad.bands.clear();
|
||||
assert_eq!(bad.validate(), Err(GestaltKnobsError::NoBands));
|
||||
let mut bad = knobs(&[1], 1, 1);
|
||||
bad.max_node_turns = 0;
|
||||
assert_eq!(bad.validate(), Err(GestaltKnobsError::NoNodeTurns));
|
||||
let mut bad = knobs(&[1], 1, 1);
|
||||
bad.cover.constituent_cap = 1;
|
||||
assert!(matches!(bad.validate(), Err(GestaltKnobsError::Cover(_))));
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue