dungeon: the DM's knobs, persisted per timeline in gestalt-knobs.cc; tune and run_world; sweep_sessions and the window env vars are gone

The wave and the run-ahead sweep read bands, depth, node-turn bound, lane allowances and the DM's leased focus from the timeline's knob document; default_knobs, Scale.sweep_sessions, Scale.window and their env vars are deleted. A wave gives no turn to subjects in the player's room, which is react's. Waves are ghostlight.dungeon_wave.v2 and record the allowances, focus and forced nodes they planned under. The DM's view prints the gears and what a node turn has cost by band.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-03 13:27:40 +01:00
commit 9c8ff5efba
10 changed files with 1076 additions and 126 deletions

View file

@ -440,7 +440,7 @@ async fn play(
.await
.is_some_and(|view| view.state == PlayTurnState::Closed);
if closed {
run_waves(&spawned, &state.scale, spawned.play.last_logged().await).await;
run_waves(&spawned, spawned.play.last_logged().await).await;
if let Some(evidence) = evidence_of(&state.catalog, state.vaults.as_ref(), &spawned, &timeline).await {
run_ahead(&spawned, evidence, &state.scale).await;
}

View file

@ -20,7 +20,7 @@ use crate::{
use chrono::Utc;
use ghostlight::{
CommandBody, CommandId, ControllerError, CreateJurisdictionIntent, CreateWorldIntent,
EvidenceSource, LaneTokens, Lens, LensWeights, MailboxError, PrincipalCommandIntent, SeedPort, SubjectKind,
EvidenceSource, Lens, LensWeights, MailboxError, PrincipalCommandIntent, SeedPort, SubjectKind,
VerifiedPrincipalEvidence, WorldEra, WorldPhase, WorldSnapshot,
};
use sha2::{Digest, Sha256};
@ -44,21 +44,14 @@ pub(crate) struct Scale {
/// Seed sessions Begin may spend before approving: the credit bound of a
/// Begin, one model round trip each.
pub(crate) seed_sessions: usize,
/// Elaboration sessions one run-ahead trigger may start.
pub(crate) sweep_sessions: usize,
/// Permits one run-ahead sweep may hold at once.
pub(crate) sweep_permits: usize,
/// What each background lane may spend in one post-turn window, in tokens.
/// Unset is unbounded: the ruled credit burn spends without a cap, and the
/// ledger reports.
pub(crate) window: LaneTokens,
}
const DEFAULT_PERSON_TARGET: u32 = 8;
const DEFAULT_INSTITUTION_TARGET: u32 = 2;
const DEFAULT_POPULATION_TARGET: u32 = 1;
const DEFAULT_SEED_SESSIONS: usize = 2;
const DEFAULT_SWEEP_SESSIONS: usize = 4;
const DEFAULT_SWEEP_PERMITS: usize = 2;
impl Scale {
@ -83,12 +76,7 @@ impl Scale {
),
]),
seed_sessions: number(&read, "GHOSTLIGHT_BEGIN_SEED_SESSIONS", DEFAULT_SEED_SESSIONS),
sweep_sessions: number(&read, "GHOSTLIGHT_SWEEP_SESSIONS", DEFAULT_SWEEP_SESSIONS),
sweep_permits: number(&read, "GHOSTLIGHT_SWEEP_PERMITS", DEFAULT_SWEEP_PERMITS).max(1),
window: LaneTokens {
wave: number(&read, "GHOSTLIGHT_WINDOW_WAVE_TOKENS", u64::MAX),
elaboration: number(&read, "GHOSTLIGHT_WINDOW_ELABORATION_TOKENS", u64::MAX),
},
}
}
}
@ -923,10 +911,15 @@ pub(crate) mod tests {
/// and the lane's ledger stays empty.
#[tokio::test]
async fn an_exhausted_elaboration_allowance_refuses_the_sweep_before_the_provider() {
let mut rig = deferred_rig();
rig.scale = Arc::new(Scale { window: LaneTokens { wave: u64::MAX, elaboration: 0 }, ..(*rig.scale).clone() });
let rig = deferred_rig();
let begun = begin_vault(&rig, Uuid::new_v4()).await;
let host = rig.timelines.host(&begun.timeline).await.unwrap();
{
let mut knobs = host.knobs.lock().await;
let mut none = knobs.current();
none.allowances.elaboration = 0;
knobs.replace(none).unwrap();
}
let draft = host.world.snapshot().await.unwrap();
rig.port.push(Ok(author("seed-1", &draft, &["a", "b"])));
rig.port.push(Ok(author("seed-2", &draft, &["c", "d"])));
@ -938,7 +931,7 @@ pub(crate) mod tests {
eventually(async || rig.port.seen_requests().into_iter().skip(2).find(|request| prompt_text(request).contains(NOTE))).await;
let revision = host.world.snapshot().await.unwrap().revision;
let window = ghostlight::RunId::new(&format!("window-{revision}")).unwrap();
assert_eq!(host.background.lane_spent(&window).unwrap(), LaneTokens { wave: 0, elaboration: 0 });
assert_eq!(host.background.lane_spent(&window).unwrap(), ghostlight::LaneTokens { wave: 0, elaboration: 0 });
}
/// Genesis stands the player at the commons, which no seed populates: a
@ -1161,12 +1154,11 @@ pub(crate) mod tests {
assert_eq!(scale.targets[&SubjectKind::Person], 8);
assert_eq!(scale.targets[&SubjectKind::Institution], 2);
assert_eq!(scale.targets[&SubjectKind::Population], 1);
assert_eq!((scale.seed_sessions, scale.sweep_sessions, scale.sweep_permits), (2, 4, 2));
assert_eq!((scale.seed_sessions, scale.sweep_permits), (2, 2));
let moved = Scale::from_reader(|name| {
match name {
"GHOSTLIGHT_BEGIN_PERSON_TARGET" => Some("12"),
"GHOSTLIGHT_BEGIN_SEED_SESSIONS" => Some("3"),
"GHOSTLIGHT_SWEEP_SESSIONS" => Some("junk"),
"GHOSTLIGHT_SWEEP_PERMITS" => Some("0"),
_ => None,
}
@ -1174,7 +1166,6 @@ pub(crate) mod tests {
});
assert_eq!(moved.targets[&SubjectKind::Person], 12);
assert_eq!(moved.seed_sessions, 3);
assert_eq!(moved.sweep_sessions, 4, "an unreadable override is the default");
assert_eq!(moved.sweep_permits, 1, "a sweep always holds at least one permit");
}

View file

@ -0,0 +1,589 @@
//! The DM's gears: one timeline's standing knobs for the world beyond the room.
//!
//! The document is scheduling state, never world truth. It holds how often each
//! distance band takes a turn, how far the focus opens, how many node turns a
//! wave may spend, what each background lane may spend in one post-turn window,
//! the focus the DM added with a lease in fictional minutes, and the nodes the
//! DM asked to run now. The planner and the elaborator's sweep read it; nothing
//! else decides how much the world beyond the room moves. The DM changes it only
//! through the `tune` and `run_world` tools, and the player's own place is never
//! in it: that focus is derived from the world each time.
//!
//! Demotion is lazy. A lease names the fictional minute it ends at; past it the
//! entry is simply not focus, and the next `tune` drops it from the document.
//! Every wave records the knobs it planned under.
use anyhow::Context;
use chrono::Utc;
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
use ghostlight::{
CoverBudget, EntityId, GestaltKnobs, Hierarchy, LaneTokens, NodeAnchor, NodeId, RecordedKnobs, SubjectId,
SubjectKind, TickMinutes, WorldSnapshot, id_text, id_text_matches, node_label,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::{ops::RangeInclusive, path::Path, sync::Arc};
use tokio::sync::Mutex;
const TYPE: &str = "ghostlight.dungeon_gestalt_knobs.v1";
const KEY: &str = "knobs";
/// The longest a band period or a lease may be: the clock's own span.
const LONGEST_MINUTES: i64 = 525_600;
const MOST_BANDS: usize = 8;
const DEPTHS: RangeInclusive<i64> = 1..=8;
const NODE_TURNS: RangeInclusive<i64> = 1..=32;
const MOST_ALLOWANCE: i64 = 5_000_000;
/// Leases and forced nodes the document holds at once.
const MOST_ENTRIES: usize = 8;
/// What a focus entry or a forced run names: a place, or an institution whose
/// node it is. Both are ids `table_view` prints.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum Target {
Place(EntityId),
Institution(SubjectId),
}
impl Target {
fn text(&self) -> String {
match self {
Self::Place(id) => id_text(id),
Self::Institution(id) => id_text(id),
}
}
/// The node this target stands for in `hierarchy`: the node that governs a
/// place, an institution's own node. None for an institution the hierarchy
/// no longer holds.
pub(crate) fn node(&self, hierarchy: &Hierarchy) -> Option<NodeId> {
match self {
Self::Place(place) => hierarchy.focus_path(*place).first().copied(),
Self::Institution(subject) => hierarchy
.nodes
.values()
.find(|node| node.anchor == NodeAnchor::Institution(*subject))
.map(|node| node.id),
}
}
}
/// A focus entry the DM added: it holds until the world's clock reaches `until`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct Lease {
pub(crate) target: Target,
pub(crate) until: u64,
}
/// One timeline's knobs, document `ghostlight.dungeon_gestalt_knobs.v1`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct DmKnobs {
pub(crate) knobs: RecordedKnobs,
/// What each background lane may spend in one post-turn window.
pub(crate) allowances: LaneTokens,
pub(crate) focus: Vec<Lease>,
/// Nodes the DM asked to run in the next post-turn wave; that wave takes them.
pub(crate) forced: Vec<Target>,
}
impl Default for DmKnobs {
/// A Begin's knobs: bands of an hour, six hours, a day and a week by
/// distance from the focus, the focus opened two nodes up, four node turns
/// a wave, each node's cover at four cells of six, and the allowances sized
/// to what the retired four-session sweep and its wave were: no cost has
/// been measured yet, so the DM tunes from the averages its view prints.
fn default() -> Self {
Self {
knobs: RecordedKnobs {
bands: vec![60, 360, 1440, 10_080],
depth: 2,
max_node_turns: 4,
cells: 4,
constituent_cap: 6,
urgency_slots: 1,
},
allowances: LaneTokens { wave: 200_000, elaboration: 200_000 },
focus: Vec::new(),
forced: Vec::new(),
}
}
}
impl DmKnobs {
/// The planner's knobs. A document whose values the planner would refuse
/// never reaches it: `tune` admits only values this reads.
pub(crate) fn gestalt(&self) -> anyhow::Result<GestaltKnobs> {
let bands = self
.knobs
.bands
.iter()
.map(|minutes| TickMinutes::new(*minutes).with_context(|| format!("band {minutes} is outside the clock's span")))
.collect::<anyhow::Result<Vec<_>>>()?;
let knobs = GestaltKnobs {
bands,
depth: self.knobs.depth,
max_node_turns: self.knobs.max_node_turns,
cover: CoverBudget {
cells: self.knobs.cells,
constituent_cap: self.knobs.constituent_cap,
urgency_slots: self.knobs.urgency_slots,
},
};
knobs.validate()?;
Ok(knobs)
}
/// The DM's focus entries still holding at fictional minute `now`.
pub(crate) fn standing(&self, now: u64) -> impl Iterator<Item = &Lease> {
self.focus.iter().filter(move |lease| lease.until > now)
}
}
/// The timeline's knobs in one CultCache file.
pub(crate) struct KnobStore {
store: OwnedRedbMessagePackBackingStore,
knobs: DmKnobs,
}
pub(crate) type KnobLog = Arc<Mutex<KnobStore>>;
impl KnobStore {
/// Opens the file, writing a Begin's knobs into a timeline that has none.
pub(crate) fn open(path: impl AsRef<Path>) -> anyhow::Result<Self> {
let store = OwnedRedbMessagePackBackingStore::new(path.as_ref())?;
store.validate_path_identity().context("knob store path identity is invalid")?;
let mut rows = store.pull_all()?;
let knobs = match rows.pop() {
None => None,
Some(row) => {
anyhow::ensure!(rows.is_empty() && row.r#type == TYPE && row.key == KEY, "the knob store holds a foreign record");
Some(rmp_serde::from_slice::<DmKnobs>(&row.payload).context("the knobs did not decode")?)
}
};
let mut opened = Self { store, knobs: knobs.clone().unwrap_or_default() };
opened.knobs.gestalt().context("the stored knobs are not plannable")?;
if knobs.is_none() {
opened.replace(opened.knobs.clone())?;
}
Ok(opened)
}
pub(crate) fn current(&self) -> DmKnobs {
self.knobs.clone()
}
pub(crate) fn replace(&mut self, knobs: DmKnobs) -> anyhow::Result<()> {
let row = CultCacheEnvelope {
key: KEY.into(),
r#type: TYPE.into(),
payload: rmp_serde::to_vec_named(&knobs)?,
stored_at: Utc::now().to_rfc3339(),
schema_id: Some(TYPE.into()),
};
self.store.validate_path_identity().context("knob store ownership was lost")?;
self.store.push(&row)?;
self.knobs = knobs;
Ok(())
}
}
/// A whole number inside `range`, or the refusal quoting what was given.
fn whole(name: &str, value: &Value, range: RangeInclusive<i64>) -> Result<i64, String> {
let Some(number) = value.as_i64() else {
return Err(format!("{name} must be a whole number, got {value}"));
};
if range.contains(&number) {
Ok(number)
} else {
Err(format!("{name} {number} is refused: it must be {} to {}", range.start(), range.end()))
}
}
/// The place or institution `text` names, by the id `table_view` prints.
fn resolve(text: &str, world: &WorldSnapshot) -> Result<Target, String> {
if let Some(place) = world.places.iter().find(|place| id_text_matches(place.id, text)) {
return Ok(Target::Place(place.id));
}
match world.subjects.iter().find(|subject| id_text_matches(subject.id, text)) {
Some(subject) if subject.kind == SubjectKind::Institution && !subject.retired => {
Ok(Target::Institution(subject.id))
}
Some(subject) => Err(format!(
"`{text}` names {}, which is not an institution; name its place or its institution",
subject.label
)),
None => Err(format!("`{text}` names no place or institution in the world")),
}
}
fn arguments_object(arguments: &str, tool: &str) -> Result<serde_json::Map<String, Value>, String> {
match serde_json::from_str::<Value>(arguments) {
Ok(Value::Object(fields)) => Ok(fields),
_ => Err(format!("{tool}'s arguments are not a JSON object: `{arguments}`")),
}
}
fn texts(name: &str, value: &Value) -> Result<Vec<String>, String> {
let Some(items) = value.as_array() else {
return Err(format!("{name} must be a list, got {value}"));
};
items
.iter()
.map(|item| item.as_str().map(str::to_owned).ok_or_else(|| format!("{name} holds {item}, which is not an id")))
.collect()
}
/// `tune`'s arguments applied to `current` at fictional minute `now`: the new
/// knobs and what changed, or the refusal naming the first value outside its
/// bound. Nothing changes unless every value is admitted.
pub(crate) fn tune(
current: &DmKnobs,
arguments: &str,
world: &WorldSnapshot,
now: u64,
) -> Result<(DmKnobs, String), String> {
let fields = arguments_object(arguments, "tune")?;
let mut next = current.clone();
next.focus.retain(|lease| lease.until > now);
let mut changed = Vec::new();
for (name, value) in &fields {
match name.as_str() {
"bands" => {
let items = value.as_array().ok_or_else(|| format!("bands must be a list, got {value}"))?;
if items.is_empty() || items.len() > MOST_BANDS {
return Err(format!("bands holds {} periods, refused: it takes 1 to {MOST_BANDS}", items.len()));
}
next.knobs.bands = items
.iter()
.map(|item| whole("band", item, 1..=LONGEST_MINUTES).map(|minutes| minutes as u32))
.collect::<Result<_, _>>()?;
changed.push(format!("bands {:?} minutes", next.knobs.bands));
}
"depth" => {
next.knobs.depth = whole("depth", value, DEPTHS)? as u8;
changed.push(format!("depth {}", next.knobs.depth));
}
"max_node_turns" => {
next.knobs.max_node_turns = whole("max_node_turns", value, NODE_TURNS)? as u16;
changed.push(format!("max_node_turns {}", next.knobs.max_node_turns));
}
"wave_allowance" => {
next.allowances.wave = whole("wave_allowance", value, 0..=MOST_ALLOWANCE)? as u64;
changed.push(format!("wave allowance {} tokens", next.allowances.wave));
}
"elaboration_allowance" => {
next.allowances.elaboration = whole("elaboration_allowance", value, 0..=MOST_ALLOWANCE)? as u64;
changed.push(format!("elaboration allowance {} tokens", next.allowances.elaboration));
}
"focus_remove" => {
for text in texts("focus_remove", value)? {
let before = next.focus.len();
next.focus.retain(|lease| lease.target.text() != text);
if next.focus.len() == before {
return Err(format!("`{text}` is not one of your focus entries"));
}
changed.push(format!("focus on {text} removed"));
}
}
"focus_add" => {}
other => return Err(format!("tune takes no `{other}`")),
}
}
if let Some(value) = fields.get("focus_add") {
let items = value.as_array().ok_or_else(|| format!("focus_add must be a list, got {value}"))?;
for item in items {
let entry = item.as_object().ok_or_else(|| format!("focus_add holds {item}, which is not an entry"))?;
let text = entry
.get("target")
.and_then(Value::as_str)
.ok_or_else(|| format!("focus_add entry {item} names no target"))?;
let minutes = whole("lease_minutes", entry.get("lease_minutes").unwrap_or(&Value::Null), 1..=LONGEST_MINUTES)?;
let target = resolve(text, world)?;
next.focus.retain(|lease| lease.target != target);
next.focus.push(Lease { target, until: now.saturating_add(minutes as u64) });
changed.push(format!("focus on {text} for {minutes} minutes"));
}
}
if changed.is_empty() {
return Err("tune changed nothing: name bands, depth, max_node_turns, wave_allowance, elaboration_allowance, focus_add or focus_remove".into());
}
if next.focus.len() > MOST_ENTRIES {
return Err(format!("{} focus entries is refused: {MOST_ENTRIES} at most", next.focus.len()));
}
next.gestalt().map_err(|error| error.to_string())?;
Ok((next, format!("tuned: {}. Allowances apply to the next window; a window already open keeps its own.", changed.join("; "))))
}
/// `run_world`'s arguments: the targets it names, resolved against the world.
pub(crate) fn run_world(arguments: &str, world: &WorldSnapshot) -> Result<Vec<Target>, String> {
let fields = arguments_object(arguments, "run_world")?;
let value = fields.get("targets").ok_or_else(|| format!("run_world needs `targets`: `{arguments}`"))?;
let mut targets = Vec::new();
for text in texts("targets", value)? {
let target = resolve(&text, world)?;
if !targets.contains(&target) {
targets.push(target);
}
}
if targets.is_empty() || targets.len() > MOST_ENTRIES {
return Err(format!("run_world takes 1 to {MOST_ENTRIES} targets, got {}", targets.len()));
}
Ok(targets)
}
/// Average tokens a node turn cost, by band, from the waves the timeline has
/// closed: `(average, node turns)` for each band, the last band taking every
/// distance beyond it.
pub(crate) fn band_costs(nodes: impl Iterator<Item = (u8, u64)>, bands: usize) -> Vec<(u64, u64)> {
let mut totals = vec![(0u64, 0u64); bands];
for (distance, tokens) in nodes {
let band = usize::from(distance).min(bands - 1);
totals[band].0 += tokens;
totals[band].1 += 1;
}
totals
.into_iter()
.map(|(tokens, turns)| (tokens.checked_div(turns).unwrap_or(0), turns))
.collect()
}
/// The section of the DM's opening view that shows its gears: the knobs, where
/// attention is, what is queued and what each band has cost.
pub(crate) fn gears_view(
knobs: &DmKnobs,
world: &WorldSnapshot,
hierarchy: &Hierarchy,
player_places: &[EntityId],
costs: &[(u64, u64)],
) -> String {
let mut out = String::from(
"The world beyond the room, and the gears you may turn (`tune`, `run_world`; time stays yours, and nothing here runs a node that is not due unless you ask):\n",
);
let bands: Vec<String> = knobs.knobs.bands.iter().map(u32::to_string).collect();
out.push_str(&format!(
"- Bands, minutes between a node's turns by distance from the focus, nearest first: {}. Depth {} (nodes open along each focus path), at most {} node turns a wave.\n",
bands.join(", "),
knobs.knobs.depth,
knobs.knobs.max_node_turns
));
out.push_str(&format!(
"- Allowances in one post-turn window: wave {} tokens, elaboration {} tokens.\n",
knobs.allowances.wave, knobs.allowances.elaboration
));
for place in player_places {
let path: Vec<String> = hierarchy.focus_path(*place).into_iter().map(|node| node_label(node, world, hierarchy)).collect();
out.push_str(&format!("- The player's focus runs {}.\n", path.join(" > ")));
}
for lease in knobs.standing(world.now.0) {
out.push_str(&format!(
"- Your focus: {} [{}], {} more minutes.\n",
target_label(&lease.target, world),
lease.target.text(),
lease.until - world.now.0
));
}
if !knobs.forced.is_empty() {
let named: Vec<String> = knobs.forced.iter().map(|target| target_label(target, world)).collect();
out.push_str(&format!("- Asked to run in this turn's wave: {}.\n", named.join(", ")));
}
let spent: Vec<String> = costs
.iter()
.enumerate()
.map(|(band, (average, turns))| {
if *turns == 0 {
format!("band {band}: no node turn yet")
} else {
format!("band {band}: {average} tokens over {turns} node turns")
}
})
.collect();
out.push_str(&format!("- What a node turn has cost on average: {}.\n\n", spent.join("; ")));
out
}
fn target_label(target: &Target, world: &WorldSnapshot) -> String {
match target {
Target::Place(id) => world.places.iter().find(|place| place.id == *id).map(|place| place.label.clone()),
Target::Institution(id) => world.subjects.iter().find(|subject| subject.id == *id).map(|subject| subject.label.clone()),
}
.unwrap_or_else(|| "-".to_owned())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{play::tests::ScriptedPort, waves::tests::Fixture};
use serde_json::json;
fn opaque<T: serde::de::DeserializeOwned>() -> T {
serde_json::from_value(json!(uuid::Uuid::new_v4().to_string())).unwrap()
}
/// A world with a player, a Warden and two places, and the id of each place.
async fn world() -> (WorldSnapshot, Hierarchy, EntityId, EntityId) {
let fixture = Fixture::new().await;
let (timelines, _stopped) = fixture.open(ScriptedPort::new(vec![]));
let host = timelines.host(&fixture.id).await.unwrap();
let world = host.world.snapshot().await.unwrap();
let hierarchy = host.world.hierarchy().await.unwrap();
let place = |label: &str| world.places.iter().find(|place| place.label == label).unwrap().id;
let (commons, gate) = (place("The Commons"), place("Gatehouse"));
(world, hierarchy, commons, gate)
}
fn refusal(current: &DmKnobs, world: &WorldSnapshot, arguments: serde_json::Value) -> String {
tune(current, &arguments.to_string(), world, 0).expect_err("the call is refused")
}
/// Spec test `bad values refused`: a value outside its bound is refused
/// whole, quoting the value, and a refused call leaves the document as it was.
#[tokio::test]
async fn a_value_outside_its_bound_is_refused_quoting_it() {
let (world, _, commons, _) = world().await;
let current = DmKnobs::default();
assert!(refusal(&current, &world, json!({"bands": [60, -5]})).contains("band -5"));
assert!(refusal(&current, &world, json!({"bands": [0]})).contains("band 0"));
assert!(refusal(&current, &world, json!({"bands": [525_601]})).contains("band 525601"));
assert!(refusal(&current, &world, json!({"bands": []})).contains("0 periods"));
assert!(refusal(&current, &world, json!({"bands": [1, 2, 3, 4, 5, 6, 7, 8, 9]})).contains("9 periods"));
assert!(refusal(&current, &world, json!({"depth": 0})).contains("depth 0"));
assert!(refusal(&current, &world, json!({"depth": 9})).contains("depth 9"));
assert!(refusal(&current, &world, json!({"depth": "deep"})).contains("\"deep\""));
assert!(refusal(&current, &world, json!({"depth": 2.5})).contains("2.5"));
assert!(refusal(&current, &world, json!({"max_node_turns": 0})).contains("max_node_turns 0"));
assert!(refusal(&current, &world, json!({"max_node_turns": 33})).contains("max_node_turns 33"));
assert!(refusal(&current, &world, json!({"wave_allowance": -1})).contains("wave_allowance -1"));
assert!(refusal(&current, &world, json!({"elaboration_allowance": 5_000_001})).contains("5000001"));
assert!(refusal(&current, &world, json!({"focus_remove": [id_text(commons)]})).contains("not one of your focus entries"));
let lease = |minutes: i64| json!({"focus_add": [{"target": id_text(commons), "lease_minutes": minutes}]});
assert!(refusal(&current, &world, lease(0)).contains("lease_minutes 0"));
assert!(refusal(&current, &world, lease(525_601)).contains("lease_minutes 525601"));
assert!(refusal(&current, &world, json!({"focus_add": [{"target": id_text(commons)}]})).contains("lease_minutes"));
assert!(refusal(&current, &world, json!({"focus_add": [{"target": "nowhere", "lease_minutes": 5}]})).contains("`nowhere`"));
assert!(refusal(&current, &world, json!({"depth": 3, "colour": "red"})).contains("`colour`"), "an unknown field is refused");
assert!(refusal(&current, &world, json!({})).contains("changed nothing"));
assert!(tune(&current, "[1]", &world, 0).unwrap_err().contains("not a JSON object"));
let person = id_text(world.subjects.iter().find(|subject| subject.label == "Warden").unwrap().id);
assert!(refusal(&current, &world, json!({"focus_add": [{"target": person, "lease_minutes": 5}]})).contains("not an institution"));
// One good field beside a bad one changes nothing: the call is refused whole.
assert!(tune(&current, r#"{"depth": 4, "bands": [-1]}"#, &world, 0).is_err());
assert_eq!(current, DmKnobs::default());
}
/// The values inside their bounds are applied, a lease is anchored at the
/// clock the call was made at, and a lease the DM re-adds replaces its own.
#[tokio::test]
async fn a_tune_inside_its_bounds_applies_every_field() {
let (world, _, commons, gate) = world().await;
let current = DmKnobs::default();
let asked = json!({
"bands": [5, 525_600],
"depth": 8,
"max_node_turns": 32,
"wave_allowance": 0,
"elaboration_allowance": 5_000_000,
"focus_add": [{"target": id_text(gate), "lease_minutes": 30}],
});
let (next, said) = tune(&current, &asked.to_string(), &world, 100).unwrap();
assert_eq!(next.knobs.bands, vec![5, 525_600]);
assert_eq!((next.knobs.depth, next.knobs.max_node_turns), (8, 32));
assert_eq!(next.allowances, LaneTokens { wave: 0, elaboration: 5_000_000 });
assert_eq!(next.focus, vec![Lease { target: Target::Place(gate), until: 130 }]);
assert_eq!(next.knobs.cells, current.knobs.cells, "the cover is not the DM\'s to tune");
assert!(said.contains("depth 8") && said.contains("next window"), "{said}");
let again = json!({"focus_add": [{"target": id_text(gate), "lease_minutes": 10}]});
let (renewed, _) = tune(&next, &again.to_string(), &world, 110).unwrap();
assert_eq!(renewed.focus, vec![Lease { target: Target::Place(gate), until: 120 }]);
let (swapped, _) = tune(&renewed, &json!({"focus_remove": [id_text(gate)]}).to_string(), &world, 111).unwrap();
assert!(swapped.focus.is_empty());
let (dropped, _) = tune(&next, &json!({"depth": 1}).to_string(), &world, 130).unwrap();
assert!(dropped.focus.is_empty(), "a lapsed lease is dropped by the next tune");
let two = json!({"focus_add": [{"target": id_text(commons), "lease_minutes": 5}, {"target": id_text(gate), "lease_minutes": 5}]});
assert_eq!(tune(&current, &two.to_string(), &world, 0).unwrap().0.focus.len(), 2);
}
#[tokio::test]
async fn run_world_names_places_and_institutions_the_view_prints() {
let (world, _, commons, gate) = world().await;
let named = |ids: Vec<String>| run_world(&json!({"targets": ids}).to_string(), &world);
assert_eq!(
named(vec![id_text(gate), id_text(commons), id_text(gate)]).unwrap(),
vec![Target::Place(gate), Target::Place(commons)],
"each target once, in the order named"
);
assert!(named(vec![]).unwrap_err().contains("1 to 8 targets"));
assert!(named(vec!["nowhere".into()]).unwrap_err().contains("`nowhere`"));
assert!(run_world("{}", &world).unwrap_err().contains("needs `targets`"));
assert!(run_world(r#"{"targets":"all"}"#, &world).unwrap_err().contains("must be a list"));
assert!(run_world(r#"{"targets":[3]}"#, &world).unwrap_err().contains("not an id"));
}
/// A target is the node that governs it: a place's governing node, an
/// institution's own, none for an institution the world no longer holds.
#[tokio::test]
async fn a_target_is_the_node_that_governs_it() {
let (_, hierarchy, commons, gate) = world().await;
assert_eq!(Target::Place(commons).node(&hierarchy), Some(hierarchy.root()));
assert_eq!(Target::Place(gate).node(&hierarchy), Some(hierarchy.root()));
assert_eq!(Target::Institution(opaque::<SubjectId>()).node(&hierarchy), None);
}
#[test]
fn a_stored_document_is_the_one_a_reopen_reads() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("gestalt-knobs.cc");
let mut kept = DmKnobs::default();
{
let mut store = KnobStore::open(&path).unwrap();
assert_eq!(store.current(), DmKnobs::default(), "a Begin\'s knobs, written at first open");
kept.knobs.depth = 5;
kept.focus.push(Lease { target: Target::Place(opaque::<EntityId>()), until: 9 });
kept.forced.push(Target::Institution(opaque::<SubjectId>()));
store.replace(kept.clone()).unwrap();
}
assert_eq!(KnobStore::open(&path).unwrap().current(), kept);
}
#[test]
fn a_document_the_planner_would_refuse_is_not_opened() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("gestalt-knobs.cc");
{
let mut store = KnobStore::open(&path).unwrap();
let mut broken = DmKnobs::default();
broken.knobs.bands.clear();
store.replace(broken).unwrap();
}
assert!(KnobStore::open(&path).is_err());
}
/// What a band costs on average is read from the node turns the closed waves
/// report: a distance past the last band is the last band.
#[test]
fn a_bands_cost_is_the_average_of_its_node_turns() {
let turns = [(0u8, 100u64), (0, 300), (1, 50), (9, 10), (3, 30)];
assert_eq!(band_costs(turns.into_iter(), 3), vec![(200, 2), (50, 1), (20, 2)]);
assert_eq!(band_costs(std::iter::empty(), 2), vec![(0, 0), (0, 0)]);
}
#[tokio::test]
async fn the_view_prints_the_gears_where_attention_is_and_what_is_asked() {
let (mut world, hierarchy, commons, gate) = world().await;
world.now = ghostlight::FictionalMinutes(10);
let mut knobs = DmKnobs::default();
knobs.focus = vec![
Lease { target: Target::Place(gate), until: 70 },
Lease { target: Target::Place(commons), until: 10 },
];
knobs.forced = vec![Target::Place(gate)];
let view = gears_view(&knobs, &world, &hierarchy, &[commons], &[(200, 2), (0, 0), (0, 0), (0, 0)]);
assert!(view.contains("60, 360, 1440, 10080. Depth 2"), "{view}");
assert!(view.contains("wave 200000 tokens, elaboration 200000 tokens"));
assert!(view.contains("The player\'s focus runs world."));
assert!(view.contains(&format!("Your focus: Gatehouse [{}], 60 more minutes.", id_text(gate))));
assert!(!view.contains("Your focus: The Commons"), "a lapsed lease is not shown");
assert!(view.contains("Asked to run in this turn\'s wave: Gatehouse."));
assert!(view.contains("band 0: 200 tokens over 2 node turns; band 1: no node turn yet"));
}
}

View file

@ -6,6 +6,7 @@ mod catalog;
mod heimdall;
mod idunn_health;
mod invite;
mod knobs;
mod page;
#[cfg(test)]
mod playtest;

View file

@ -60,7 +60,11 @@ use sha2::{Digest, Sha256};
use tokio::sync::{Mutex, Semaphore};
use crate::turn_log::{NewEntry, Page as TurnPage, TurnLog, TurnStatus};
use crate::waves::{WaveLog, offscreen_view};
use crate::{
knobs::{self, KnobLog},
run_ahead::player_places,
waves::{WaveLog, offscreen_view},
};
const STORE_TYPE: &str = "ghostlight.play_turn_store.v1";
/// PA.f172 bumped this from v1 to v2 when `question_surface_version` was
@ -150,6 +154,8 @@ const PLAY_TOOLS: &[&str] = &[
const DISPATCH_TOOL: &str = "dispatch";
const REACT_TOOL: &str = "react";
const ADVANCE_TIME_TOOL: &str = "advance_time";
pub(crate) const TUNE_TOOL: &str = "tune";
pub(crate) const RUN_WORLD_TOOL: &str = "run_world";
pub(crate) const ASK_PLAYER_TOOL: &str = "ask_player";
pub(crate) const END_TURN_TOOL: &str = "end_turn";
@ -195,6 +201,7 @@ view lists the open grievances the world has not answered. An office, a victim's
through their own people: give them their turns, and rule pressure (`advance_pressure`, from whoever would lean) or \
a sworn reckoning (`create_commitment`, the victim's kin with the doer as counterparty) where you judge the world would.\n\
- The world beyond the room moves between turns: the view opens with what moved off-screen since your last turn and which nodes were due but deferred. That is yours to know; the player learns of it only as it reaches them.
- The world beyond the room has gears you may turn when a scene calls for it: `tune` sets how often each distance band takes a turn, how deep the focus opens, how many node turns a wave may spend, what the background lanes may spend, and where you want attention for a lease of minutes; `run_world` asks for a node to take its turn in this turn's wave. The view shows the gears as they stand and what a node turn has cost. Neither is required; use them when the story needs the world nearer or further away.
- Call `end_turn` when the round's consequences are settled.";
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
@ -1322,6 +1329,8 @@ pub(crate) struct PlayTable {
/// The timeline's world waves, whose unseen reports open the next turn's
/// view. Absent on a table with no timeline around it.
waves: Option<WaveLog>,
/// The timeline's standing knobs, which `tune` and `run_world` write.
knobs: Option<KnobLog>,
/// What the player was shown, turn by turn (`turn_log`): written from the
/// row in `persist`, right after the row commits, and never edited.
log: Mutex<TurnLog>,
@ -1398,6 +1407,7 @@ impl PlayTable {
permits,
store: Mutex::new(store),
waves: None,
knobs: None,
log: Mutex::new(log),
pending_retry: std::sync::Mutex::new(None),
store_path,
@ -1411,9 +1421,11 @@ impl PlayTable {
})
}
/// The table with the timeline's wave store behind its opening views.
pub(crate) fn with_waves(mut self, waves: WaveLog) -> Self {
/// The table with the timeline's wave store behind its opening views and
/// its knobs behind `tune` and `run_world`.
pub(crate) fn with_gears(mut self, waves: WaveLog, knobs: KnobLog) -> Self {
self.waves = Some(waves);
self.knobs = Some(knobs);
self
}
@ -1773,8 +1785,9 @@ impl PlayTable {
Some(waves) => offscreen_view(&waves.lock().await.take_unseen(&turn_id)?),
None => String::new(),
};
let gears = self.gears_view(&snapshot).await?;
let opening_prompt = format!(
"{}\n\n{moved}The player writes:\n{}\n",
"{}\n\n{moved}{gears}The player writes:\n{}\n",
table_view(&snapshot),
text
);
@ -2248,6 +2261,13 @@ impl PlayTable {
continue;
}
if name == TUNE_TOOL || name == RUN_WORLD_TOOL {
let result = self.execute_gear(name, arguments).await;
record_call(turn, call_id, round, this_slot, None, Some(result));
self.persist(turn).await?;
continue;
}
// `<handle>__<kind>` actor call: `handle` alone picks the actor
// (Dungeon's own vocabulary — the library owns no notion of
// which subject was dispatched this turn); the full `name` is
@ -2465,6 +2485,58 @@ impl PlayTable {
}
}
/// The section of the opening view that shows the DM its gears: the knobs
/// as they stand, where attention is, what is queued, and what a node turn
/// has cost by band. Empty on a table with no timeline around it.
async fn gears_view(&self, snapshot: &WorldSnapshot) -> Result<String, PlayError> {
let Some(knobs) = &self.knobs else {
return Ok(String::new());
};
let current = knobs.lock().await.current();
let hierarchy = self.world.hierarchy().await?;
let turns = match &self.waves {
Some(waves) => waves.lock().await.node_turns(),
None => Vec::new(),
};
let costs = knobs::band_costs(turns.into_iter(), current.knobs.bands.len());
Ok(knobs::gears_view(&current, snapshot, &hierarchy, &player_places(snapshot), &costs))
}
/// `tune` and `run_world`: the DM's gears. Both are idempotent against the
/// knob document, so a call resumed after a crash that lost its result
/// answers again without a second effect worth recording.
async fn execute_gear(&self, name: &str, arguments: &str) -> String {
let Some(knobs) = &self.knobs else {
return format!("refused: this table has no world beyond the room to `{name}`");
};
let world = match self.round_snapshot().await {
Ok(world) => world,
Err(detail) => return format!("refused: {detail}"),
};
let mut store = knobs.lock().await;
let current = store.current();
let applied = if name == TUNE_TOOL {
knobs::tune(&current, arguments, &world, world.now.0)
} else {
knobs::run_world(arguments, &world).map(|targets| {
let mut next = current.clone();
for target in targets {
if !next.forced.contains(&target) {
next.forced.push(target);
}
}
(next, "queued for this turn's wave: they run at its head, within the wave allowance".to_owned())
})
};
match applied {
Ok((next, said)) => match store.replace(next) {
Ok(()) => said,
Err(error) => format!("refused: the knobs could not be kept: {error}"),
},
Err(refusal) => format!("refused: {refusal}"),
}
}
async fn execute_advance_time(
&self,
turn: &mut PlayTurn,
@ -3065,6 +3137,29 @@ for you to commit through each person's own `<handle>__speak` tool."
description: "Advance the world clock by a whole number of fictional minutes.".into(),
parameters_json: r#"{"type":"object","properties":{"minutes":{"type":"integer","minimum":1}},"required":["minutes"]}"#.into(),
},
ToolDefinition {
name: TUNE_TOOL.into(),
description: "Turn the gears of the world beyond the room; every field is optional and the call is \
refused whole if any value is outside its bound, quoting it. `bands` is the minutes between a node's turns by \
distance from the focus, nearest first (1 to 8 periods of 1 to 525600). `depth` is how many nodes along each \
focus path are open (1 to 8). `max_node_turns` bounds the node turns of one wave (1 to 32). `wave_allowance` and \
`elaboration_allowance` are what each background lane may spend in one post-turn window, in tokens (0 to 5000000); \
they apply from the next window. `focus_add` puts attention on a place or an institution, named by the id \
table_view prints in brackets, for `lease_minutes` of fictional time, after which it lapses by itself; \
`focus_remove` names ids to drop. The player's own place is always in focus and needs no entry. The view shows the \
gears as they stand."
.into(),
parameters_json: r#"{"type":"object","properties":{"bands":{"type":"array","items":{"type":"integer"}},"depth":{"type":"integer"},"max_node_turns":{"type":"integer"},"wave_allowance":{"type":"integer"},"elaboration_allowance":{"type":"integer"},"focus_add":{"type":"array","items":{"type":"object","properties":{"target":{"type":"string"},"lease_minutes":{"type":"integer"}},"required":["target","lease_minutes"]}},"focus_remove":{"type":"array","items":{"type":"string"}}},"required":[]}"#.into(),
},
ToolDefinition {
name: RUN_WORLD_TOOL.into(),
description: "Ask the world beyond the room to take its turn now: each named place or institution \
(the id table_view prints in brackets) is opened and its people act at the head of this turn's wave, which runs \
after the turn closes, whether or not their band is due, within the wave allowance. What the wave did is in your \
next view. Use it when a scene should set the world moving; the room itself is `react`."
.into(),
parameters_json: r#"{"type":"object","properties":{"targets":{"type":"array","items":{"type":"string"}}},"required":["targets"]}"#.into(),
},
ToolDefinition {
name: ASK_PLAYER_TOOL.into(),
description: "Stop the turn and ask the player a question.".into(),

View file

@ -22,7 +22,7 @@ use axum::http::Method;
use chrono::Utc;
use ghostlight::{
EvidenceError, EvidenceQuery, EvidenceReceipt, EvidenceSource, InferenceFault, InferenceOutput, InferencePort,
InferenceRequest, LaneTokens, Lens, PreparedInference, SubjectKind, WorldSnapshot, table_view,
InferenceRequest, Lens, PreparedInference, SubjectKind, WorldSnapshot, table_view,
};
use serde_json::json;
use std::{
@ -62,9 +62,9 @@ pub(super) struct AtlasOptions {
persons: u32,
institutions: u32,
populations: u32,
/// Sweeps at most; each sweep starts up to `sweep_sessions` sessions.
/// Sweeps at most; each sweep starts up to `sessions_per_sweep` sessions.
sweeps: u32,
sweep_sessions: usize,
sessions_per_sweep: usize,
seed_sessions: usize,
cost_cap: f64,
/// Concurrent connector calls, for Begin's seed and every sweep.
@ -89,7 +89,7 @@ impl AtlasOptions {
institutions: number(&read, "GHOSTLIGHT_ATLAS_INSTITUTIONS", 12)?,
populations: number(&read, "GHOSTLIGHT_ATLAS_POPULATIONS", 6)?,
sweeps: number(&read, "GHOSTLIGHT_ATLAS_SWEEPS", 40)?,
sweep_sessions: number(&read, "GHOSTLIGHT_ATLAS_SWEEP_SESSIONS", 8)?,
sessions_per_sweep: number(&read, "GHOSTLIGHT_ATLAS_SWEEP_SESSIONS", 8)?,
seed_sessions: number(&read, "GHOSTLIGHT_ATLAS_SEED_SESSIONS", 2)?,
cost_cap: number(&read, "GHOSTLIGHT_ATLAS_COST_CAP", 40.0)?,
concurrency: number(&read, "GHOSTLIGHT_ATLAS_CONCURRENCY", 2)?,
@ -104,9 +104,7 @@ impl AtlasOptions {
(SubjectKind::Population, self.populations),
]),
seed_sessions: self.seed_sessions,
sweep_sessions: self.sweep_sessions,
sweep_permits: self.concurrency.max(1),
window: LaneTokens { wave: u64::MAX, elaboration: u64::MAX },
}
}
}
@ -857,7 +855,7 @@ pub(super) async fn run(options: AtlasOptions) -> anyhow::Result<PathBuf> {
let began = Instant::now();
let permits = Arc::new(Semaphore::new(options.concurrency));
let focus = ghostlight::Focus::default();
let mut sweeping = Box::pin(runner.sweep(permits, options.sweep_sessions, &focus));
let mut sweeping = Box::pin(runner.sweep(permits, options.sessions_per_sweep, &focus));
let outcome = loop {
tokio::select! {
outcome = &mut sweeping => break outcome,

View file

@ -2,20 +2,24 @@
//!
//! A world's scale deficit is answered after play starts, not before: one sweep
//! once Begin activates a seeded world, and one after each closed turn. Each
//! sweep claims what the player is looking at first (`focus_of`), starts at
//! most `Scale::sweep_sessions` elaboration sessions and holds at most
//! `Scale::sweep_permits` permits, and spends in its own post-turn window: the
//! elaborator calls a provider only through the window's recording port, which
//! refuses a call that could pass the lane's allowance. The elaborator reads
//! the evidence of the snapshot its timeline is bound to, the same evidence the
//! seed read; an unseeded world reads none.
//! sweep claims what attention holds first (`focus_of`: the player's place and
//! the DM's standing focus), holds at most `Scale::sweep_permits` permits, and
//! spends in its own post-turn window: the elaborator calls a provider only
//! through the window's recording port, which refuses a call that could pass the
//! timeline's elaboration allowance, so how much a sweep does is the DM's knob
//! and not a session count. The elaborator reads the evidence of the snapshot
//! its timeline is bound to, the same evidence the seed read; an unseeded world
//! reads none.
use crate::{
begin::{Scale, Vaults},
catalog::Catalog,
knobs::{DmKnobs, Target},
timelines::TimelineHost,
};
use ghostlight::{ControllerMode, EvidenceSource, Focus, NullEvidenceSource, WorldSnapshot};
use ghostlight::{
ControllerMode, EntityId, EvidenceSource, Focus, Hierarchy, NullEvidenceSource, WorldSnapshot,
};
use std::sync::Arc;
use tokio::sync::{Mutex, Semaphore};
@ -33,7 +37,15 @@ pub(crate) async fn run_ahead(host: &TimelineHost, evidence: Arc<dyn EvidenceSou
return;
}
};
let window = match host.window(world.revision, &world, scale.window) {
let hierarchy = match host.world.hierarchy().await {
Ok(hierarchy) => hierarchy,
Err(error) => {
tracing::warn!(%error, "run-ahead could not read the hierarchy");
return;
}
};
let knobs = host.knobs.lock().await.current();
let window = match host.window(world.revision, &world, knobs.allowances) {
Ok(window) => Arc::new(window),
Err(error) => {
tracing::warn!(%error, "run-ahead could not open its window");
@ -42,17 +54,15 @@ pub(crate) async fn run_ahead(host: &TimelineHost, evidence: Arc<dyn EvidenceSou
};
let runner = host.controllers.elaborator(window, evidence);
let permits = Arc::new(Semaphore::new(scale.sweep_permits));
if let Err(error) = runner.sweep(permits, scale.sweep_sessions, &focus_of(&world)).await {
if let Err(error) = runner.sweep(permits, usize::MAX, &focus_of(&world, &hierarchy, &knobs)).await {
tracing::warn!(%error, "run-ahead elaboration stopped");
}
}
/// Where the player is looking: the place the world's owner's own human subject
/// stands in. A world with no placed player has no focus, and its sweep keeps
/// the kernel's order. The timeline's standing focus joins this when the DM
/// can set one (`dm-gestalt-knobs`).
pub(crate) fn focus_of(world: &WorldSnapshot) -> Focus {
let places = world
/// The places the world's owner's own human subjects stand in: the room the
/// player is in, which the DM's `react` owns and a world wave never turns.
pub(crate) fn player_places(world: &WorldSnapshot) -> Vec<EntityId> {
world
.subjects
.iter()
.filter(|subject| {
@ -60,8 +70,22 @@ pub(crate) fn focus_of(world: &WorldSnapshot) -> Focus {
&& subject.human_controller.as_ref() == Some(&world.owner)
})
.filter_map(|subject| world.place_of(subject.id))
.collect();
Focus { places, nodes: Vec::new() }
.collect()
}
/// Where attention is: the player's place, then the DM's focus entries whose
/// lease still holds. A world with no placed player and no entries has no
/// focus, and its sweep keeps the kernel's order.
pub(crate) fn focus_of(world: &WorldSnapshot, hierarchy: &Hierarchy, knobs: &DmKnobs) -> Focus {
let mut focus = Focus { places: player_places(world), nodes: Vec::new() };
for lease in knobs.standing(world.now.0) {
match lease.target {
Target::Place(place) if !focus.places.contains(&place) => focus.places.push(place),
Target::Place(_) => {}
Target::Institution(_) => focus.nodes.extend(lease.target.node(hierarchy)),
}
}
focus
}
/// The evidence a timeline's elaborator reads: its bound snapshot's, for the
@ -119,16 +143,18 @@ mod tests {
.find(|subject| subject.human_controller.as_ref() == Some(&world.owner))
.expect("the owner's player");
let stands = world.place_of(player.id).expect("the player stands somewhere");
assert_eq!(focus_of(&world).places, vec![stands]);
let hierarchy = host.world.hierarchy().await.unwrap();
let none = DmKnobs::default();
assert_eq!(focus_of(&world, &hierarchy, &none).places, vec![stands]);
let mut stranger = world.clone();
stranger.owner = ghostlight::PrincipalId::new("someone else");
assert!(focus_of(&stranger).places.is_empty(), "another principal's subject is not the owner's player");
assert!(focus_of(&stranger, &hierarchy, &none).places.is_empty(), "another principal's subject is not the owner's player");
let mut automaton = world;
for subject in &mut automaton.subjects {
subject.controller_mode = Some(ControllerMode::NarrativePersona);
}
assert!(focus_of(&automaton).places.is_empty(), "a persona is not looking");
assert!(focus_of(&automaton, &hierarchy, &none).places.is_empty(), "a persona is not looking");
}
/// A timeline's elaborator reads what its world was bound to: nothing

View file

@ -8,8 +8,14 @@ use std::{
};
/// The stores one timeline owns, each proved direct before it is opened.
pub(crate) const TIMELINE_STORES: [&str; 5] =
["world.cc", "controller-work.cc", "play-turn-v1.cc", "calls.cc", "waves.cc"];
pub(crate) const TIMELINE_STORES: [&str; 6] = [
"world.cc",
"controller-work.cc",
"play-turn-v1.cc",
"calls.cc",
"waves.cc",
"gestalt-knobs.cc",
];
fn default_runtime_root() -> PathBuf {
#[cfg(windows)]

View file

@ -6,6 +6,7 @@
use crate::{
catalog::timeline_directory_name,
knobs::{KnobLog, KnobStore},
play::PlayTable,
state_layout::prepare_timeline_directory,
waves::{WaveLog, WaveStore},
@ -44,6 +45,8 @@ pub(crate) struct TimelineHost {
/// The world waves this timeline's closed turns planned, and what the DM
/// has been shown of them.
pub(crate) waves: WaveLog,
/// The DM's standing knobs for this timeline's world beyond the room.
pub(crate) knobs: KnobLog,
inference: Arc<dyn InferencePort>,
}
@ -118,6 +121,9 @@ impl Timelines {
let waves: WaveLog = Arc::new(Mutex::new(
WaveStore::open(directory.join("waves.cc")).context("the wave store could not be opened")?,
));
let knobs: KnobLog = Arc::new(Mutex::new(
KnobStore::open(directory.join("gestalt-knobs.cc")).context("the knob store could not be opened")?,
));
let controllers = ControllerRunner::open(
world.clone(),
self.shared.inference.clone(),
@ -138,7 +144,7 @@ impl Timelines {
self.shared.permits.clone(),
directory.join("play-turn-v1.cc"),
)?
.with_waves(waves.clone());
.with_gears(waves.clone(), knobs.clone());
let (changes, _) = broadcast::channel(16);
let host = Arc::new(TimelineHost {
world,
@ -148,6 +154,7 @@ impl Timelines {
sweeping: Mutex::new(()),
background,
waves,
knobs,
inference: self.shared.inference.clone(),
});
hosts.insert(id.to_owned(), host.clone());

View file

@ -4,9 +4,10 @@
//!
//! The planner and the wave runner are the library's (`plan_wave`,
//! `run_frozen_cells`), the same ones the verse tick drives. What is the
//! Dungeon's is who sets the knobs (constants here until the DM can), when a
//! wave runs (after a closed turn, in the background window, under the sweep
//! lock) and who owns time: never a wave. A wave plans over the clock as the DM
//! Dungeon's is whose knobs they are (the DM's, persisted per timeline in
//! `knobs`), when a wave runs (after a closed turn, in the background window,
//! under the sweep lock) and who owns time: never a wave. The player's own room
//! is the DM's `react`, so a wave gives its people no turn. A wave plans over the clock as the DM
//! left it, so with no time passed nothing is due and no call is made.
//!
//! A wave is frozen under its closed turn's log `seq` before its first
@ -15,44 +16,30 @@
//! wave is planned, under the window ledger it opened in, so its cells
//! re-submit the command ids they first held.
use crate::{begin::Scale, run_ahead::focus_of, timelines::TimelineHost};
use crate::{
knobs::Target,
run_ahead::{focus_of, player_places},
timelines::TimelineHost,
};
use anyhow::{Context, ensure};
use chrono::Utc;
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
use ghostlight::{
CoverBudget, Deferral, FictionalMinutes, FrozenCell, GestaltKnobs, InferencePort, NodeId,
RecordedKnobs, TickIndex, TickMinutes, WaveClock, WaveSpend, WaveStop, act_line, acts_since,
deferred_nodes, node_reports, plan_wave, run_frozen_cells,
Deferral, FictionalMinutes, FrozenCell, InferencePort, LaneTokens, NodeId, RecordedKnobs, TickIndex,
WaveClock, WaveSpend, WaveStop, act_line, acts_since, deferred_nodes, node_reports, plan_wave,
run_frozen_cells,
};
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, path::Path, sync::Arc};
use tokio::sync::Mutex;
const TYPE: &str = "ghostlight.dungeon_wave.v1";
const TYPE: &str = "ghostlight.dungeon_wave.v2";
/// The acts one opening view lists, and the characters one act line keeps: the
/// view is a digest, and the kernel holds the rest.
const VIEW_ACTS: usize = 24;
const VIEW_LINE_CHARS: usize = 280;
/// The standing knobs of a Dungeon wave: bands of an hour, six hours, a day and
/// a week by distance from the player's place, the focus opened two nodes up,
/// four node turns a wave, and each node's cover at four cells of six. The
/// allowances are `Scale::window`'s. The DM sets these from `dm-gestalt-knobs`.
pub(crate) fn default_knobs() -> GestaltKnobs {
let band = |minutes| TickMinutes::new(minutes).expect("a band is inside the clock's span");
GestaltKnobs {
bands: vec![band(60), band(360), band(1440), band(10_080)],
depth: 2,
max_node_turns: 4,
cover: CoverBudget {
cells: 4,
constituent_cap: 6,
urgency_slots: 1,
},
}
}
/// What a node's turn moved, as the DM reads it: frozen when the wave closed,
/// so the labels and lines are what the world said then.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
@ -80,7 +67,7 @@ pub(crate) struct WaveReport {
pub(crate) out_of_allowance: bool,
}
/// One wave, document `ghostlight.dungeon_wave.v1`, keyed by the `seq` of the
/// One wave, document `ghostlight.dungeon_wave.v2`, keyed by the `seq` of the
/// closed turn it followed. Opened once with its cells and closed once with its
/// report; never reopened or deleted.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
@ -91,6 +78,13 @@ pub(crate) struct WaveRecord {
pub(crate) revision: u64,
pub(crate) opened_now: u64,
pub(crate) knobs: RecordedKnobs,
/// The window allowances the wave opened under: the ledger it finishes in
/// is reopened with these, whatever the DM has tuned since.
pub(crate) allowances: LaneTokens,
/// The DM's focus entries holding when the wave planned, and the nodes the
/// DM asked to run in it.
pub(crate) focus: Vec<Target>,
pub(crate) forced: Vec<Target>,
pub(crate) cells: Vec<FrozenCell>,
/// What the plan left out, frozen with the cells.
pub(crate) deferred: Vec<(NodeId, Deferral)>,
@ -144,6 +138,16 @@ impl WaveStore {
self.waves.get(&turn_seq).cloned()
}
/// Every node turn the closed waves report, as its distance from the focus
/// and the tokens it was charged.
pub(crate) fn node_turns(&self) -> Vec<(u8, u64)> {
self.waves
.values()
.filter_map(|wave| wave.report.as_ref())
.flat_map(|report| report.nodes.iter().map(|node| (node.distance, node.tokens)))
.collect()
}
pub(crate) fn contains(&self, turn_seq: u64) -> bool {
self.waves.contains_key(&turn_seq)
}
@ -253,28 +257,39 @@ pub(crate) fn offscreen_view(waves: &[WaveRecord]) -> String {
/// entry: finishes any wave left open, then plans and runs the wave the clock
/// makes due. Holds the sweep lock, so it never overlaps a run-ahead sweep, and
/// waits for it rather than dropping the wave a sweep would have blocked.
pub(crate) async fn run_waves(host: &TimelineHost, scale: &Scale, turn_seq: u64) {
pub(crate) async fn run_waves(host: &TimelineHost, turn_seq: u64) {
let _running = host.sweeping.lock().await;
if let Err(error) = move_world(host, scale, turn_seq).await {
if let Err(error) = move_world(host, turn_seq).await {
tracing::warn!(%error, turn_seq, "a world wave could not run");
}
}
async fn move_world(host: &TimelineHost, scale: &Scale, turn_seq: u64) -> anyhow::Result<()> {
async fn move_world(host: &TimelineHost, turn_seq: u64) -> anyhow::Result<()> {
let open = host.waves.lock().await.open_waves();
for record in open {
if !finish(host, scale, record).await? {
if !finish(host, record).await? {
return Ok(());
}
}
if host.waves.lock().await.contains(turn_seq) {
return Ok(());
}
let Some(record) = plan(host, turn_seq).await? else {
return Ok(());
};
host.waves.lock().await.open_wave(record.clone())?;
finish(host, scale, record).await?;
let planned = plan(host, turn_seq).await?;
if let Some(record) = &planned {
host.waves.lock().await.open_wave(record.clone())?;
}
// The asked-for nodes belong to the wave that planned them, run or not.
{
let mut knobs = host.knobs.lock().await;
let mut next = knobs.current();
if !next.forced.is_empty() {
next.forced.clear();
knobs.replace(next)?;
}
}
if let Some(record) = planned {
finish(host, record).await?;
}
Ok(())
}
@ -284,16 +299,24 @@ async fn move_world(host: &TimelineHost, scale: &Scale, turn_seq: u64) -> anyhow
/// has passed, and a wave never turns a world whose clock has not moved.
async fn plan(host: &TimelineHost, turn_seq: u64) -> anyhow::Result<Option<WaveRecord>> {
let world = host.world.snapshot().await?;
let opportunities = host.world.opportunities().await?;
let mut opportunities = host.world.opportunities().await?;
let graph = host.world.agency_graph().await?;
let mut hierarchy = host.world.hierarchy().await?;
// The player's room is the DM's `react`: a wave turning its people too would
// give them a second voice in the same moment.
let room = player_places(&world);
opportunities.retain(|opportunity| {
!world.place_of(opportunity.scope.subject_id).is_some_and(|place| room.contains(&place))
});
for opportunity in &opportunities {
hierarchy
.last_attended
.entry(opportunity.scope.subject_id)
.or_insert(FictionalMinutes(0));
}
let knobs = default_knobs();
let dm = host.knobs.lock().await.current();
let knobs = dm.gestalt()?;
let forced: Vec<NodeId> = dm.forced.iter().filter_map(|target| target.node(&hierarchy)).collect();
let wave = plan_wave(
WaveClock {
world: world.world_id,
@ -303,7 +326,8 @@ async fn plan(host: &TimelineHost, turn_seq: u64) -> anyhow::Result<Option<WaveR
&hierarchy,
&opportunities,
&graph,
&focus_of(&world),
&focus_of(&world, &hierarchy, &dm),
&forced,
&knobs,
)?;
let cells = wave.frozen();
@ -315,6 +339,9 @@ async fn plan(host: &TimelineHost, turn_seq: u64) -> anyhow::Result<Option<WaveR
revision: world.revision,
opened_now: world.now.0,
knobs: RecordedKnobs::of(&knobs),
allowances: dm.allowances,
focus: dm.standing(world.now.0).map(|lease| lease.target).collect(),
forced: dm.forced.clone(),
cells,
deferred: wave.deferred,
report: None,
@ -325,9 +352,9 @@ async fn plan(host: &TimelineHost, turn_seq: u64) -> anyhow::Result<Option<WaveR
/// Runs an open wave's frozen cells under the window ledger it opened in and
/// closes it with its report. False when a cell did not finish and the wave
/// stays open: its unreached members resume at the next trigger.
async fn finish(host: &TimelineHost, scale: &Scale, record: WaveRecord) -> anyhow::Result<bool> {
async fn finish(host: &TimelineHost, record: WaveRecord) -> anyhow::Result<bool> {
let world = host.world.snapshot().await?;
let window = Arc::new(host.window(record.revision, &world, scale.window)?);
let window = Arc::new(host.window(record.revision, &world, record.allowances)?);
let port: Arc<dyn InferencePort> = window.clone();
let runner = host.controllers.through(port);
let ordinal = TickIndex(record.turn_seq);
@ -367,18 +394,19 @@ async fn finish(host: &TimelineHost, scale: &Scale, record: WaveRecord) -> anyho
}
#[cfg(test)]
mod tests {
pub(crate) mod tests {
use super::*;
use crate::{
catalog::timeline_id,
knobs::{self, DmKnobs},
play::tests::{ScriptedPort, call_event, output, text_event},
state_layout::{prepare_admitted_state_layout, prepare_timeline_directory},
timelines::{Shared, Timelines},
};
use ghostlight::{
CommandBody, CommandId, ControllerModels, CreateWorldIntent, InferenceFault, InferenceOutput,
InferencePurpose, Lens, LensWeights, PreparedInference, PrincipalCommandIntent,
VerifiedPrincipalEvidence, WorldMailbox,
InferenceEvent, InferencePurpose, Lens, LensWeights, PlayPort, PreparedInference, PrincipalCommandIntent,
TickMinutes, VerifiedPrincipalEvidence, WorldMailbox, decode_authoring_calls, id_text,
};
use std::path::PathBuf;
use tokio::sync::{Notify, Semaphore, mpsc};
@ -400,15 +428,25 @@ mod tests {
/// One timeline whose world holds a player and a `Warden` an operational
/// agent decides for, on a state root the test can reopen.
struct Fixture {
pub(crate) struct Fixture {
_directory: tempfile::TempDir,
root: PathBuf,
id: String,
scale: Scale,
pub(crate) id: String,
}
impl Fixture {
async fn new() -> Self {
/// The Warden stands in a gatehouse down the road from the player: out
/// of the player's room, so a wave may turn him.
pub(crate) async fn new() -> Self {
Self::build(true).await
}
/// The Warden stands in the player's own room.
async fn in_the_room() -> Self {
Self::build(false).await
}
async fn build(warden_away: bool) -> Self {
let directory = tempfile::tempdir().unwrap();
let root = std::fs::canonicalize(directory.path()).unwrap();
prepare_admitted_state_layout(&root).unwrap();
@ -450,19 +488,47 @@ mod tests {
.await
.unwrap();
}
if warden_away {
let snapshot = world.snapshot().await.unwrap();
let warden = snapshot.subjects.iter().find(|subject| subject.label == "Warden").unwrap().id;
let commons = snapshot.place_of(warden).unwrap();
let commons = id_text(commons);
let warden = id_text(warden);
let declare_place = serde_json::json!({"handle": "gate", "label": "Gatehouse", "container": null}).to_string();
let declare_route = serde_json::json!({
"handle": "road",
"label": "The Road",
"from": {"ref": "existing", "value": commons},
"to": {"ref": "draft", "value": "gate"},
"access": {"access": "public"},
"cost": 1,
})
.to_string();
let relocate = serde_json::json!({
"subject": {"ref": "existing", "value": warden},
"via": {"ref": "draft", "value": "road"},
})
.to_string();
let decoded = decode_authoring_calls(&[
("declare_place", declare_place.as_str()),
("declare_route", declare_route.as_str()),
("relocate", relocate.as_str()),
])
.unwrap();
PlayPort::new(world.clone()).submit_patch(CommandId::new(), decoded.patch).await.unwrap();
}
drop(world);
task.await.unwrap();
Self {
_directory: directory,
root,
id,
scale: Scale::from_reader(|_| None),
}
}
/// The timelines of one process life over `inference`, and the signal
/// that a world owner stopped.
fn open(&self, inference: Arc<dyn InferencePort>) -> (Timelines, mpsc::UnboundedReceiver<String>) {
pub(crate) fn open(&self, inference: Arc<dyn InferencePort>) -> (Timelines, mpsc::UnboundedReceiver<String>) {
let (fatal, stopped) = mpsc::unbounded_channel();
let timelines = Timelines::new(
self.root.clone(),
@ -482,13 +548,21 @@ mod tests {
output(receipt, vec![call_event("act", "speak", serde_json::json!({"text": text}))])
}
async fn advance(host: &TimelineHost, minutes: u32) {
pub(crate) async fn advance(host: &TimelineHost, minutes: u32) {
host.world
.submit_clock(CommandId::new(), TickMinutes::new(minutes).unwrap())
.await
.unwrap();
}
/// Sets what the timeline's lanes may spend in a window.
async fn allow(host: &TimelineHost, set: impl FnOnce(&mut LaneTokens)) {
let mut store = host.knobs.lock().await;
let mut doc = store.current();
set(&mut doc.allowances);
store.replace(doc).unwrap();
}
async fn wave_of(host: &TimelineHost, turn_seq: u64) -> Option<WaveRecord> {
host.waves.lock().await.waves.get(&turn_seq).cloned()
}
@ -506,7 +580,7 @@ mod tests {
advance(&host, 400).await;
let before = host.world.snapshot().await.unwrap();
run_waves(&host, &fixture.scale, 1).await;
run_waves(&host, 1).await;
let wave = wave_of(&host, 1).await.expect("the wave was frozen under its turn");
let report = wave.report.expect("and closed");
@ -536,15 +610,15 @@ mod tests {
let port = ScriptedPort::new(vec![speaks("w0", "The gate holds.")]);
let (timelines, _stopped) = fixture.open(port.clone());
let host = timelines.host(&fixture.id).await.unwrap();
run_waves(&host, &fixture.scale, 1).await;
run_waves(&host, &fixture.scale, 2).await;
run_waves(&host, 1).await;
run_waves(&host, 2).await;
assert!(port.seen_requests().is_empty(), "no time passed, so nothing was due");
advance(&host, 59).await;
run_waves(&host, &fixture.scale, 3).await;
run_waves(&host, 3).await;
assert!(port.seen_requests().is_empty(), "one minute short of the band");
assert!(wave_of(&host, 3).await.is_none(), "an empty wave is not frozen");
advance(&host, 1).await;
run_waves(&host, &fixture.scale, 4).await;
run_waves(&host, 4).await;
assert_eq!(port.seen_requests().len(), 1, "the band's period has passed");
}
@ -556,11 +630,11 @@ mod tests {
let (timelines, _stopped) = fixture.open(port.clone());
let host = timelines.host(&fixture.id).await.unwrap();
advance(&host, 400).await;
run_waves(&host, &fixture.scale, 1).await;
run_waves(&host, &fixture.scale, 2).await;
run_waves(&host, 1).await;
run_waves(&host, 2).await;
assert_eq!(port.seen_requests().len(), 1, "the Warden took its turn at 400 and is not due at 400");
advance(&host, 60).await;
run_waves(&host, &fixture.scale, 3).await;
run_waves(&host, 3).await;
assert_eq!(port.seen_requests().len(), 2);
}
@ -573,9 +647,9 @@ mod tests {
let (timelines, _stopped) = fixture.open(port.clone());
let host = timelines.host(&fixture.id).await.unwrap();
advance(&host, 400).await;
run_waves(&host, &fixture.scale, 1).await;
run_waves(&host, 1).await;
advance(&host, 400).await;
run_waves(&host, &fixture.scale, 1).await;
run_waves(&host, 1).await;
assert_eq!(port.seen_requests().len(), 1);
let mut waves = host.waves.lock().await;
assert!(waves.contains(1) && !waves.contains(7));
@ -595,14 +669,14 @@ mod tests {
let (timelines, mut stopped) = fixture.open(down.clone());
let host = timelines.host(&fixture.id).await.unwrap();
advance(&host, 400).await;
run_waves(&host, &fixture.scale, 1).await;
run_waves(&host, 1).await;
let open = wave_of(&host, 1).await.unwrap();
assert!(open.report.is_none(), "a cell that did not finish leaves the wave open");
assert_eq!(host.waves.lock().await.open_waves().len(), 1);
// A wave left open holds the world's next one back: the open wave is
// finished first, and a trigger that cannot finish it plans nothing.
down.push_answer(Err(InferenceFault::retryable("the connector is still down")));
run_waves(&host, &fixture.scale, 2).await;
run_waves(&host, 2).await;
assert!(wave_of(&host, 2).await.is_none(), "no second wave while one is open");
assert_eq!(host.waves.lock().await.open_waves().len(), 1);
drop(host);
@ -612,7 +686,7 @@ mod tests {
let up = ScriptedPort::new(vec![speaks("w0", "The gate holds.")]);
let (timelines, _stopped) = fixture.open(up.clone());
let host = timelines.host(&fixture.id).await.unwrap();
run_waves(&host, &fixture.scale, 2).await;
run_waves(&host, 2).await;
let finished = wave_of(&host, 1).await.unwrap();
assert!(finished.report.is_some(), "the open wave was finished");
assert_eq!(finished.cells, open.cells, "as frozen");
@ -628,13 +702,13 @@ mod tests {
/// reported as waiting, never dropped, and the provider is not called.
#[tokio::test]
async fn an_exhausted_wave_allowance_defers_the_node_and_reports_it() {
let mut fixture = Fixture::new().await;
fixture.scale.window = ghostlight::LaneTokens { wave: 0, elaboration: u64::MAX };
let fixture = Fixture::new().await;
let port = ScriptedPort::new(vec![speaks("w0", "Unheard.")]);
let (timelines, _stopped) = fixture.open(port.clone());
let host = timelines.host(&fixture.id).await.unwrap();
allow(&host, |allowances| allowances.wave = 0).await;
advance(&host, 400).await;
run_waves(&host, &fixture.scale, 1).await;
run_waves(&host, 1).await;
assert!(port.seen_requests().len() <= 1);
let report = wave_of(&host, 1).await.unwrap().report.expect("a budget stop closes the wave");
assert!(report.out_of_allowance);
@ -660,7 +734,10 @@ mod tests {
turn_seq,
revision: 1,
opened_now: 0,
knobs: RecordedKnobs::of(&default_knobs()),
knobs: DmKnobs::default().knobs,
allowances: DmKnobs::default().allowances,
focus: Vec::new(),
forced: Vec::new(),
cells: Vec::new(),
deferred: Vec::new(),
report,
@ -758,7 +835,7 @@ mod tests {
let (timelines, _stopped) = fixture.open(port.clone());
let host = timelines.host(&fixture.id).await.unwrap();
advance(&host, 400).await;
run_waves(&host, &fixture.scale, 1).await;
run_waves(&host, 1).await;
{
let mut waves = host.waves.lock().await;
waves.open_wave(record(2, None)).unwrap();
@ -779,11 +856,172 @@ mod tests {
first.find("Off-screen since").unwrap() < first.find("The player writes:").unwrap(),
"the view opens before the player's words"
);
assert!(first.contains("The world beyond the room, and the gears you may turn"), "{first}");
assert!(first.contains("60, 360, 1440, 10080") && first.contains("Depth 2"), "the knobs as they stand");
assert!(first.contains("wave 200000 tokens, elaboration 200000 tokens"));
assert!(first.contains("The player's focus runs world."), "the focus path by label");
assert!(first.contains("band 0: ") && first.contains("over 1 node turns"), "what the wave's node turn cost");
host.play.run(&who, Uuid::new_v4().to_string(), "I wait again.".into()).await.unwrap();
let second = serde_json::to_string(&port.seen_requests()[3]).unwrap();
assert!(!second.contains("Off-screen since your last turn") && !second.contains("Crown"), "{second}");
}
/// A DM round that makes `calls` and ends the turn, and the narration after.
fn dm_turn_script(calls: Vec<(&str, serde_json::Value)>) -> Vec<InferenceOutput> {
let mut events: Vec<InferenceEvent> = calls
.into_iter()
.enumerate()
.map(|(number, (name, arguments))| call_event(&format!("c{number}"), name, arguments))
.collect();
events.push(call_event("end", crate::play::END_TURN_TOOL, serde_json::json!({})));
vec![output("r0", events), output("proj-0", vec![text_event("You wait.")])]
}
/// Spec test `tune persists`: a depth the DM tuned survives a process
/// restart, and the next wave records the knobs it planned under.
#[tokio::test]
async fn a_tuned_depth_survives_a_restart_and_is_recorded_in_the_next_wave() {
let fixture = Fixture::new().await;
let port = ScriptedPort::new(dm_turn_script(vec![(
crate::play::TUNE_TOOL,
serde_json::json!({"depth": 3, "bands": [10, 60], "wave_allowance": 90000}),
)]));
let (timelines, mut stopped) = fixture.open(port.clone());
let host = timelines.host(&fixture.id).await.unwrap();
assert_eq!(host.knobs.lock().await.current(), DmKnobs::default(), "a Begin's knobs until the DM tunes");
host.play.run(&principal(), Uuid::new_v4().to_string(), "I wait.".into()).await.unwrap();
assert_eq!(host.knobs.lock().await.current().knobs.depth, 3);
drop(host);
drop(timelines);
stopped.recv().await.expect("the world owner stopped with the process");
let up = ScriptedPort::new(vec![speaks("w0", "The gate holds.")]);
let (timelines, _stopped) = fixture.open(up.clone());
let host = timelines.host(&fixture.id).await.unwrap();
let kept = host.knobs.lock().await.current();
assert_eq!((kept.knobs.depth, kept.knobs.bands.clone(), kept.allowances.wave), (3, vec![10, 60], 90_000));
advance(&host, 20).await;
run_waves(&host, 1).await;
let wave = wave_of(&host, 1).await.expect("the Warden was due past the tuned band");
assert_eq!((wave.knobs.depth, wave.knobs.bands.clone()), (3, vec![10, 60]));
assert_eq!(wave.allowances.wave, 90_000, "the wave records the allowances its ledger opened with");
}
/// Spec test `lease closes lazily`: a DM focus entry holds for the waves
/// inside its lease and is gone from the first wave after it; the document
/// keeps the entry until the DM next tunes.
#[tokio::test]
async fn a_dm_focus_entry_closes_in_the_first_wave_after_its_lease() {
let fixture = Fixture::new().await;
let port = ScriptedPort::new(vec![speaks("w0", "One."), speaks("w1", "Two."), speaks("w2", "Three.")]);
let (timelines, _stopped) = fixture.open(port.clone());
let host = timelines.host(&fixture.id).await.unwrap();
let world = host.world.snapshot().await.unwrap();
let gate = world.places.iter().find(|place| place.label == "Gatehouse").unwrap().id;
{
let mut store = host.knobs.lock().await;
let asked = serde_json::json!({
"bands": [10],
"focus_add": [{"target": id_text(gate), "lease_minutes": 60}],
});
let (next, _) = knobs::tune(&store.current(), &asked.to_string(), &world, world.now.0).unwrap();
store.replace(next).unwrap();
}
for (minutes, turn) in [(20, 1), (20, 2), (30, 3)] {
advance(&host, minutes).await;
run_waves(&host, turn).await;
}
let held = vec![Target::Place(gate)];
assert_eq!(wave_of(&host, 1).await.unwrap().focus, held, "inside the lease, at minute 20");
assert_eq!(wave_of(&host, 2).await.unwrap().focus, held, "inside the lease, at minute 40");
assert!(wave_of(&host, 3).await.unwrap().focus.is_empty(), "at minute 70 the lease has ended");
let hierarchy = host.world.hierarchy().await.unwrap();
let dm = host.knobs.lock().await.current();
assert_eq!(dm.focus.len(), 1, "demotion is lazy: the entry stays until the next tune");
let looks_at_gate = |now: u64| {
let mut then = world.clone();
then.now = FictionalMinutes(now);
focus_of(&then, &hierarchy, &dm).places.contains(&gate)
};
assert!(looks_at_gate(59), "a lease of 60 holds at minute 59");
assert!(!looks_at_gate(60), "and has ended at minute 60");
}
/// What `run_world` of the player's own place does to a timeline whose clock
/// has not moved, with the wave lane allowing `wave` tokens: the wave it
/// froze, whether the Warden acted, and the knobs after.
async fn forced_wave(wave: u64) -> (WaveRecord, bool, DmKnobs, usize) {
let fixture = Fixture::new().await;
let port = ScriptedPort::new(vec![]);
let (timelines, _stopped) = fixture.open(port.clone());
let host = timelines.host(&fixture.id).await.unwrap();
allow(&host, |allowances| allowances.wave = wave).await;
let world = host.world.snapshot().await.unwrap();
let commons = id_text(player_places(&world)[0]);
for answer in dm_turn_script(vec![(crate::play::RUN_WORLD_TOOL, serde_json::json!({"targets": [commons]}))]) {
port.push_answer(Ok(answer));
}
port.push_answer(Ok(speaks("w0", "The gate holds.")));
host.play.run(&principal(), Uuid::new_v4().to_string(), "I wait.".into()).await.unwrap();
assert_eq!(host.knobs.lock().await.current().forced.len(), 1, "queued until a wave takes it");
let seq = host.play.last_logged().await;
run_waves(&host, seq).await;
let log = host.world.operator_log().await.unwrap();
let wave = wave_of(&host, seq).await.expect("the asked-for node froze a wave though nothing was due");
let acted = log.iter().any(|act| act.speaker_label == "Warden");
(wave, acted, host.knobs.lock().await.current(), port.seen_requests().len())
}
/// Spec test `run_world forces within allowance`: a node the DM named runs
/// in the post-turn wave though its band has not passed, and the wave takes
/// the request with it.
#[tokio::test]
async fn run_world_runs_a_node_that_is_not_due() {
let (wave, acted, after, requests) = forced_wave(200_000).await;
let report = wave.report.expect("closed");
assert_eq!(report.nodes.len(), 1);
assert_eq!(report.nodes[0].label, "world");
assert!(acted, "the Warden took the turn the DM asked for");
assert_eq!(wave.opened_now, 0, "no time had passed: only the DM's ask made it due");
assert_eq!(wave.forced.len(), 1);
assert!(after.forced.is_empty(), "the wave took the request");
assert_eq!(requests, 3, "the DM's round, its narration and the Warden's turn");
}
/// The same ask with the wave allowance spent: the node is reported
/// deferred for the allowance, no provider is called for it and the request
/// is still the wave's, not carried to the next.
#[tokio::test]
async fn a_run_world_past_the_allowance_is_reported_deferred() {
let (wave, acted, after, requests) = forced_wave(0).await;
let report = wave.report.expect("a budget stop closes the wave");
assert!(report.out_of_allowance);
assert!(report.waiting.iter().any(|node| node.reason == Deferral::Allowance), "{report:?}");
assert!(!acted && requests == 2, "the Warden never reached the provider");
assert!(after.forced.is_empty());
}
/// The player's room is the DM's `react`: a wave gives its people no turn,
/// forced or due.
#[tokio::test]
async fn a_wave_gives_no_turn_to_the_players_room() {
let fixture = Fixture::in_the_room().await;
let port = ScriptedPort::new(vec![speaks("w0", "Doubled.")]);
let (timelines, _stopped) = fixture.open(port.clone());
let host = timelines.host(&fixture.id).await.unwrap();
let world = host.world.snapshot().await.unwrap();
let mut doc = host.knobs.lock().await.current();
doc.knobs.bands = vec![1];
let room = serde_json::json!({"targets": [id_text(player_places(&world)[0])]}).to_string();
doc.forced = knobs::run_world(&room, &world).unwrap();
host.knobs.lock().await.replace(doc).unwrap();
advance(&host, 400).await;
run_waves(&host, 1).await;
assert!(port.seen_requests().is_empty(), "the Warden stands in the player's room");
assert!(wave_of(&host, 1).await.is_none());
}
/// A port that holds the operational agent's call until the test lets it
/// go, and answers every other call from its script.
struct HeldPort {
@ -826,8 +1064,7 @@ mod tests {
advance(&host, 400).await;
let waving = {
let host = host.clone();
let scale = fixture.scale.clone();
tokio::spawn(async move { run_waves(&host, &scale, 1).await })
tokio::spawn(async move { run_waves(&host, 1).await })
};
tokio::time::timeout(std::time::Duration::from_secs(20), held.entered.notified())
.await