Merge ghostlight-verse/dm-gestalt-knobs: the DM's persisted per-timeline knobs (tune, run_world); tuned allowances bind the open window; room left to react; focus outer key in fair_claims (cut-dm-gestalt-knobs r1, reports h1 h2)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-03 15:31:08 +01:00
commit 077bc54c0e
17 changed files with 1526 additions and 177 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;
}
@ -1336,8 +1336,9 @@ mod tests {
/// A turn that closes runs the world ahead; a turn that stops to ask the
/// player does not.
/// The route's own wiring of the world wave: the DM declares a Warden and
/// lets a day pass, the closed turn runs a wave over it, and the next
/// The route's own wiring of the world wave: the DM declares a Warden in a
/// gatehouse beyond the room, tunes the bands so the gatehouse is soon due,
/// and lets a day pass; the closed turn runs a wave over it, and the next
/// turn's opening view says what moved.
#[tokio::test]
async fn a_closed_turn_moves_the_world_and_the_next_view_says_so() {
@ -1350,10 +1351,11 @@ mod tests {
let cookie = app.cookies[0].clone();
let timeline = begin_one(&app, &cookie).await;
let host = app.state.timelines.host(&timeline).await.unwrap();
let (speak, place) = ids(&host.world.snapshot().await.unwrap());
let (speak, _) = ids(&host.world.snapshot().await.unwrap());
app.rig.port.push(Ok(output(
"r0",
vec![
call_event("c5", "declare_place", json!({"handle": "gate", "label": "Gatehouse", "container": null})),
call_event(
"c0",
"declare_subject",
@ -1363,9 +1365,10 @@ mod tests {
"kind": "institution",
"controller": {"type": "operational_agent"},
"affordances": [{"ref": "existing", "value": speak}],
"position": {"ref": "existing", "value": place},
"position": {"ref": "draft", "value": "gate"},
}),
),
call_event("c6", "tune", json!({"bands": [60, 60, 60]})),
call_event("c1", "advance_time", json!({"minutes": 400})),
call_event("c2", END_TURN_TOOL, json!({})),
],

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,658 @@
//! 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 {
/// What the world calls the target, `-` when it no longer holds it.
pub(crate) fn label(&self, world: &WorldSnapshot) -> String {
target_label(self, world)
}
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 bind the window already open too: a lane held above its new allowance is exhausted.", 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
}
pub(crate) 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)
}
/// The same world with `count` more places declared, and every place's id.
async fn crowded_world(count: usize) -> (WorldSnapshot, Vec<EntityId>) {
let fixture = Fixture::new().await;
let (timelines, _stopped) = fixture.open(ScriptedPort::new(vec![]));
let host = timelines.host(&fixture.id).await.unwrap();
let declared: Vec<String> = (0..count)
.map(|number| json!({"handle": format!("p{number}"), "label": format!("Place {number}"), "container": null}).to_string())
.collect();
let calls: Vec<(&str, &str)> = declared.iter().map(|call| ("declare_place", call.as_str())).collect();
let decoded = ghostlight::decode_authoring_calls(&calls).unwrap();
ghostlight::PlayPort::new(host.world.clone())
.submit_patch(ghostlight::CommandId::new(), decoded.patch)
.await
.unwrap();
let world = host.world.snapshot().await.unwrap();
let places = world.places.iter().map(|place| place.id).collect();
(world, places)
}
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 == "Player").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 eight = json!({"bands": [1, 2, 3, 4, 5, 6, 7, 8]});
assert_eq!(tune(&current, &eight.to_string(), &world, 0).unwrap().0.knobs.bands.len(), 8, "eight periods is the most");
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("open too"), "{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);
}
/// Eight focus entries are the most: the ninth is refused whole, and an
/// entry the DM already holds is renewed, not added.
#[tokio::test]
async fn the_document_holds_eight_focus_entries_and_no_more() {
let (world, places) = crowded_world(8).await;
let asked = |place: EntityId| json!({"focus_add": [{"target": id_text(place), "lease_minutes": 30}]}).to_string();
let mut doc = DmKnobs::default();
for place in &places[..8] {
doc = tune(&doc, &asked(*place), &world, 0).unwrap().0;
}
assert_eq!(doc.focus.len(), 8, "eight entries are admitted");
assert!(tune(&doc, &asked(places[8]), &world, 0).unwrap_err().contains("9 focus entries"));
assert_eq!(tune(&doc, &asked(places[0]), &world, 5).unwrap().0.focus.len(), 8, "renewing is not adding");
assert_eq!(tune(&doc, &asked(places[8]), &world, 30).unwrap().0.focus.len(), 1, "lapsed entries make room");
let named = |count: usize| {
let ids: Vec<String> = places[..count].iter().map(|place| id_text(*place)).collect();
run_world(&json!({"targets": ids}).to_string(), &world)
};
assert_eq!(named(8).unwrap().len(), 8);
assert!(named(9).unwrap_err().contains("got 9"));
}
/// An institution is named like a place and is the DM's focus or ask; a
/// person is not.
#[tokio::test]
async fn an_institution_is_named_by_its_id_and_labelled_by_its_name() {
let (mut world, hierarchy, _, _) = world().await;
let warden = world.subjects.iter().find(|subject| subject.label == "Warden").unwrap().id;
let asked = json!({"focus_add": [{"target": id_text(warden), "lease_minutes": 30}]}).to_string();
let (doc, _) = tune(&DmKnobs::default(), &asked, &world, 0).unwrap();
assert_eq!(doc.focus, vec![Lease { target: Target::Institution(warden), until: 30 }]);
assert_eq!(run_world(&json!({"targets": [id_text(warden)]}).to_string(), &world).unwrap(), vec![Target::Institution(warden)]);
let mut retired = world.clone();
retired.subjects.iter_mut().find(|subject| subject.id == warden).unwrap().retired = true;
assert!(tune(&DmKnobs::default(), &asked, &retired, 0).unwrap_err().contains("not an institution"), "a retired institution is not named");
world.now = ghostlight::FictionalMinutes(0);
let view = gears_view(&doc, &world, &hierarchy, &[], &[(0, 0)]);
assert!(view.contains(&format!("Your focus: Warden [{}], 30 more minutes.", id_text(warden))), "{view}");
}
#[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 (world, hierarchy, commons, gate) = world().await;
let anchor = |target: Target| hierarchy.nodes[&target.node(&hierarchy).unwrap()].anchor;
assert_eq!(anchor(Target::Place(commons)), NodeAnchor::Place(commons));
assert_eq!(anchor(Target::Place(gate)), NodeAnchor::Place(gate));
let warden = world.subjects.iter().find(|subject| subject.label == "Warden").unwrap().id;
assert_eq!(anchor(Target::Institution(warden)), NodeAnchor::Institution(warden));
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 The Commons > 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>,
}
@ -53,7 +56,9 @@ impl TimelineHost {
/// through, reserving each call in the window's ledger first. The window's
/// cap is its allowances together. A window at the same revision is the same
/// ledger, so a trigger that finds nothing changed spends no new allowance,
/// and a wave resumed after a restart reopens the ledger it opened in.
/// and a wave resumed after a restart reopens the ledger it opened in. The
/// caller passes the knobs' allowances every time and the ledger follows them,
/// keeping its spend: a tune binds the window already open.
/// `world` is the world the window is opened over now.
pub(crate) fn window(
&self,
@ -62,7 +67,7 @@ impl TimelineHost {
allowances: LaneTokens,
) -> Result<RecordingInferencePort, CallRecordError> {
let run = RunId::new(&format!("window-{revision}"))?;
RecordingInferencePort::open(
RecordingInferencePort::open_following(
self.inference.clone(),
self.background.clone(),
run,
@ -118,6 +123,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 +146,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 +156,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)]
@ -78,9 +65,11 @@ pub(crate) struct WaveReport {
pub(crate) waiting: Vec<NodeWaiting>,
/// True when the window's wave allowance ran out before the last cell.
pub(crate) out_of_allowance: bool,
/// Asked-for targets that had no turn to take.
pub(crate) nothing_stirred: Vec<String>,
}
/// 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 +80,16 @@ pub(crate) struct WaveRecord {
pub(crate) revision: u64,
pub(crate) opened_now: u64,
pub(crate) knobs: RecordedKnobs,
/// The window allowances in force when the wave planned, kept as the
/// record; the window the wave runs in follows the knobs as they stand.
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>,
/// Labels of the asked-for targets no one had a turn to take for, frozen
/// with the plan: the DM's next view says nothing stirred there.
pub(crate) quiet: Vec<String>,
pub(crate) cells: Vec<FrozenCell>,
/// What the plan left out, frozen with the cells.
pub(crate) deferred: Vec<(NodeId, Deferral)>,
@ -144,6 +143,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)
}
@ -218,6 +227,18 @@ pub(crate) fn offscreen_view(waves: &[WaveRecord]) -> String {
}
}
let mut out = String::new();
let mut quiet: Vec<&str> = Vec::new();
for label in reports.iter().flat_map(|report| report.nothing_stirred.iter()) {
if !quiet.contains(&label.as_str()) {
quiet.push(label);
}
}
for label in quiet {
out.push_str(&format!("Nothing stirred at {label}: you asked for its turn and no one there had one to take.\n"));
}
if !out.is_empty() {
out.push('\n');
}
if !lines.is_empty() {
out.push_str("Off-screen since your last turn (the world beyond the room moved; the player knows none of it unless it reaches them):\n");
for line in &lines {
@ -253,28 +274,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 +316,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,11 +343,24 @@ 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();
if cells.is_empty() {
// An asked-for target whose node neither takes a turn nor waits has no one
// there to act.
let quiet: Vec<String> = dm
.forced
.iter()
.filter(|target| {
target.node(&hierarchy).is_none_or(|node| {
!wave.turns.iter().any(|turn| turn.node == node) && !wave.deferred.iter().any(|(id, _)| *id == node)
})
})
.map(|target| target.label(&world))
.collect();
if cells.is_empty() && quiet.is_empty() {
return Ok(None);
}
Ok(Some(WaveRecord {
@ -315,6 +368,10 @@ 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(),
quiet,
cells,
deferred: wave.deferred,
report: None,
@ -325,9 +382,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, host.knobs.lock().await.current().allowances)?);
let port: Arc<dyn InferencePort> = window.clone();
let runner = host.controllers.through(port);
let ordinal = TickIndex(record.turn_seq);
@ -361,24 +418,26 @@ async fn finish(host: &TimelineHost, scale: &Scale, record: WaveRecord) -> anyho
nodes,
waiting,
out_of_allowance: outcome.stop == Some(WaveStop::Budget),
nothing_stirred: record.quiet.clone(),
};
host.waves.lock().await.close_wave(record.turn_seq, report)?;
Ok(true)
}
#[cfg(test)]
mod tests {
pub(crate) mod tests {
use super::*;
use crate::{
catalog::timeline_id,
knobs::{self, DmKnobs, KnobStore, Lease},
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};
@ -398,17 +457,40 @@ mod tests {
VerifiedPrincipalEvidence::new("waves-account", Utc::now() + chrono::Duration::hours(4))
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Warden {
InTheRoom,
AtTheGate,
AtTheWatchedGate,
}
/// 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, and the DM is watching the gatehouse: a lease that
/// never ends, so his node is open and one band from nothing.
pub(crate) async fn new() -> Self {
Self::build(Warden::AtTheWatchedGate).await
}
/// The same, with nobody watching the gatehouse.
async fn unwatched() -> Self {
Self::build(Warden::AtTheGate).await
}
/// The Warden stands in the player's own room.
async fn in_the_room() -> Self {
Self::build(Warden::InTheRoom).await
}
async fn build(warden: Warden) -> Self {
let directory = tempfile::tempdir().unwrap();
let root = std::fs::canonicalize(directory.path()).unwrap();
prepare_admitted_state_layout(&root).unwrap();
@ -450,19 +532,55 @@ mod tests {
.await
.unwrap();
}
let mut watched = None;
if warden != Warden::InTheRoom {
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();
watched = world.snapshot().await.unwrap().places.iter().find(|place| place.label == "Gatehouse").map(|place| place.id);
}
drop(world);
task.await.unwrap();
if let (Warden::AtTheWatchedGate, Some(gate)) = (warden, watched) {
let mut store = KnobStore::open(timeline.join("gestalt-knobs.cc")).unwrap();
let mut doc = store.current();
doc.focus.push(Lease { target: Target::Place(gate), until: u64::MAX });
store.replace(doc).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 +600,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 +632,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 +662,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 +682,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 +699,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 +721,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 +738,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 +754,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 +786,11 @@ 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(),
quiet: Vec::new(),
cells: Vec::new(),
deferred: Vec::new(),
report,
@ -678,6 +808,7 @@ mod tests {
NodeWaiting { label: "Hamlet".into(), reason: Deferral::NotDue },
],
out_of_allowance: false,
nothing_stirred: Vec::new(),
};
let view = offscreen_view(&[record(1, Some(report))]);
assert!(view.contains("Off-screen since your last turn"));
@ -699,11 +830,11 @@ mod tests {
for seq in [1, 2] {
store.open_wave(record(seq, None)).unwrap();
}
store.close_wave(1, WaveReport { nodes: Vec::new(), waiting: Vec::new(), out_of_allowance: false }).unwrap();
store.close_wave(1, WaveReport { nodes: Vec::new(), waiting: Vec::new(), out_of_allowance: false, nothing_stirred: Vec::new() }).unwrap();
assert!(store.take_unseen("first").unwrap().iter().map(|wave| wave.turn_seq).eq([1]), "an open wave is not carried");
assert!(store.take_unseen("first").unwrap().iter().map(|wave| wave.turn_seq).eq([1]), "asking again answers the same");
assert!(store.take_unseen("second").unwrap().is_empty(), "a taken wave is not carried twice");
store.close_wave(2, WaveReport { nodes: Vec::new(), waiting: Vec::new(), out_of_allowance: false }).unwrap();
store.close_wave(2, WaveReport { nodes: Vec::new(), waiting: Vec::new(), out_of_allowance: false, nothing_stirred: Vec::new() }).unwrap();
assert!(store.take_unseen("second").unwrap().iter().map(|wave| wave.turn_seq).eq([2]));
}
@ -717,7 +848,7 @@ mod tests {
let mut store = WaveStore::open(&path).unwrap();
store.open_wave(record(3, None)).unwrap();
store.open_wave(record(4, None)).unwrap();
store.close_wave(4, WaveReport { nodes: vec![moved("Guild", &["acts"])], waiting: Vec::new(), out_of_allowance: false }).unwrap();
store.close_wave(4, WaveReport { nodes: vec![moved("Guild", &["acts"])], waiting: Vec::new(), out_of_allowance: false, nothing_stirred: Vec::new() }).unwrap();
store.take_unseen("viewer").unwrap();
}
let store = WaveStore::open(&path).unwrap();
@ -733,7 +864,7 @@ mod tests {
let long = "x".repeat(VIEW_LINE_CHARS + 50);
let many: Vec<String> = (0..VIEW_ACTS + 3).map(|n| format!("act {n} {long}")).collect();
let acts: Vec<&str> = many.iter().map(String::as_str).collect();
let report = WaveReport { nodes: vec![moved("Guild", &acts)], waiting: Vec::new(), out_of_allowance: false };
let report = WaveReport { nodes: vec![moved("Guild", &acts)], waiting: Vec::new(), out_of_allowance: false, nothing_stirred: Vec::new() };
let view = offscreen_view(&[record(1, Some(report))]);
assert!(view.contains("- and 3 more acts the world holds"), "{view}");
assert!(!view.contains(&long), "each act keeps its first {VIEW_LINE_CHARS} characters");
@ -758,7 +889,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();
@ -766,6 +897,7 @@ mod tests {
nodes: Vec::new(),
waiting: vec![NodeWaiting { label: "Crown".into(), reason: Deferral::OverBound }],
out_of_allowance: false,
nothing_stirred: Vec::new(),
};
waves.close_wave(2, report).unwrap();
}
@ -779,11 +911,239 @@ 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 The Commons > world."), "the focus path by label");
let charged = wave_of(&host, 1).await.unwrap().report.unwrap().nodes[0].tokens;
assert!(charged > 1);
assert!(
first.contains(&format!("band 0: {charged} tokens over 1 node turns")),
"what the wave's node turn cost, on average, in its band"
);
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().knobs, DmKnobs::default().knobs, "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)
};
let commons = player_places(&world)[0];
let mut also = dm.clone();
also.focus = vec![Lease { target: Target::Place(commons), until: u64::MAX }];
assert_eq!(focus_of(&world, &hierarchy, &also).places, vec![commons], "the player's own place is not listed twice");
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 gatehouse 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, u64) {
let fixture = Fixture::unwatched().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 gate = id_text(world.places.iter().find(|place| place.label == "Gatehouse").unwrap().id);
for answer in dm_turn_script(vec![(crate::play::RUN_WORLD_TOOL, serde_json::json!({"targets": [gate]}))]) {
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");
let window = ghostlight::RunId::new(&format!("window-{}", wave.revision)).unwrap();
let spent = host.background.lane_spent(&window).unwrap().wave;
(wave, acted, host.knobs.lock().await.current(), spent)
}
/// 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, spent) = forced_wave(200_000).await;
let report = wave.report.expect("closed");
assert_eq!(report.nodes.len(), 1);
assert_eq!(report.nodes[0].label, "Gatehouse");
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!(spent > 0, "the turn was charged to the wave lane");
}
/// 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, spent) = 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 && spent == 0, "the call was refused before the provider: nothing committed, nothing spent");
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");
let wave = wave_of(&host, 1).await.expect("an asked-for target nobody could act for is still told");
let report = wave.report.expect("closed");
assert!(report.nodes.is_empty() && wave.cells.is_empty());
assert_eq!(report.nothing_stirred, vec!["The Commons".to_owned()]);
assert!(host.knobs.lock().await.current().forced.is_empty(), "the wave took the request");
let view = offscreen_view(&[wave_of(&host, 1).await.unwrap()]);
assert!(view.contains("Nothing stirred at The Commons"), "{view}");
assert!(!view.contains("Off-screen since"), "{view}");
}
/// Only the target no one could act for is told: the gatehouse took its
/// turn, the player's room had no one to give one.
#[tokio::test]
async fn only_the_target_nobody_could_act_for_is_told() {
let fixture = Fixture::unwatched().await;
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();
let world = host.world.snapshot().await.unwrap();
let ids: Vec<String> = world.places.iter().map(|place| id_text(place.id)).collect();
let mut doc = host.knobs.lock().await.current();
doc.forced = knobs::run_world(&serde_json::json!({"targets": ids}).to_string(), &world).unwrap();
host.knobs.lock().await.replace(doc).unwrap();
run_waves(&host, 1).await;
let wave = wave_of(&host, 1).await.unwrap();
assert_eq!(wave.quiet, vec!["The Commons".to_owned()], "the gatehouse had a Warden");
assert_eq!(wave.report.unwrap().nodes.len(), 1);
}
/// A tune made while the window at the current revision is open binds it:
/// the allowance that refused a wave is raised and the next wave at the
/// same revision runs, spending what the ledger already held on top.
#[tokio::test]
async fn an_allowance_tuned_mid_window_binds_the_open_window() {
let fixture = Fixture::new().await;
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();
allow(&host, |allowances| allowances.wave = 0).await;
advance(&host, 400).await;
run_waves(&host, 1).await;
let refused = wave_of(&host, 1).await.unwrap().report.unwrap();
assert!(refused.out_of_allowance && refused.nodes.iter().all(|node| node.acts.is_empty()), "{refused:?}");
let revision = wave_of(&host, 1).await.unwrap().revision;
allow(&host, |allowances| allowances.wave = 200_000).await;
run_waves(&host, 2).await;
let wave = wave_of(&host, 2).await.expect("the Warden was still due");
assert_eq!(wave.revision, revision, "the same world revision, so the same open window");
let report = wave.report.unwrap();
assert!(!report.out_of_allowance && report.nodes.len() == 1, "{report:?}");
let window = ghostlight::RunId::new(&format!("window-{revision}")).unwrap();
assert!(host.background.lane_spent(&window).unwrap().wave > 0);
// Lowered under what the window holds, the lane is exhausted, not broken.
allow(&host, |allowances| allowances.wave = 1).await;
let world = host.world.snapshot().await.unwrap();
let window = host.window(revision, &world, host.knobs.lock().await.current().allowances);
assert!(window.is_ok(), "a lowered allowance opens the window");
}
/// 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 +1186,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

View file

@ -15075,6 +15075,46 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur
task.await.unwrap();
}
/// Focus is the outer key of the claim order: the entry the kernel refused
/// at the place the player is looking at is retried ahead of untried demand
/// elsewhere, where without a focus the untried entry goes first.
#[tokio::test]
async fn a_refused_entry_in_focus_goes_ahead_of_untried_demand_out_of_focus() {
let (_directory, mailbox, task, _commons, roads) = dead_end_world(
crate::tests::stock_weights(),
&["The Unwalked Road", "The Far Road"],
Roots::Commons,
0,
)
.await;
let good = shed_on_the_named_road(vec![
("The Unwalked Road", roads[0]),
("The Far Road", roads[1]),
]);
let port = Arc::new(SweepPort::new(move |call, request| {
if call == 0 || wire_of(request).contains(REFUSAL_TURN) {
refused_round(call)
} else {
good(call, request)
}
}));
let runner = sweep_runner(&mailbox, port.clone(), fresh_store());
let first = runner.sweep(pool(2), 1, &Focus::default()).await.unwrap();
assert_eq!((first.started, first.rejected), (1, 1));
let order = crate::elaboration::claim_order(&mailbox.snapshot().await.unwrap(), &Focus::default());
let tried = if boundary_at(roads[0])(&order[0]) { roads[0] } else { roads[1] };
let focus = Focus { places: vec![tried], nodes: Vec::new() };
let second = runner.sweep(pool(2), 1, &focus).await.unwrap();
assert_eq!(
(second.started, second.rejected, second.committed),
(1, 1, 0),
"the tried entry at the focus was retried, not the untried one elsewhere: {second:?}"
);
drop(runner);
drop(mailbox);
task.await.unwrap();
}
/// A patch the resolver admits but that leaves its boundary standing is
/// refused with no site. The session is repaired like any refusal, and the
/// repair turn says what the answer needs; it does not fail the session.

View file

@ -793,7 +793,7 @@ impl ElaborationRunner {
&in_flight,
focus,
)?;
let entries = self.fair_claims(entries, &in_flight).await?;
let entries = self.fair_claims(entries, &in_flight, &snapshot, focus).await?;
report.claimed = entries.len();
let snapshot = Arc::new(snapshot);
// Raised by a session before it releases its permit, so the sweep sees
@ -861,20 +861,28 @@ impl ElaborationRunner {
quarantine.map_or(Ok(report), Err)
}
/// The claim set in the order a bounded sweep should spend on it. An entry
/// no session has touched goes before one a session already tried, so an
/// entry the kernel refused is not retried ahead of untried demand; the
/// tried ones follow least recently stored first, so they rotate. An entry
/// whose stored session ended without a patch is a fixed point that runs no
/// inference, and it takes no slot.
/// The claim set in the order a bounded sweep should spend on it. Focus is
/// the outer key: demand at a focus place goes before the rest, so a tried
/// entry the player is looking at is not parked behind untried demand
/// elsewhere. Inside each band an entry no session has touched goes before
/// one a session already tried, so an entry the kernel refused is not
/// retried ahead of untried demand; the tried ones follow least recently
/// stored first, so they rotate. An entry whose stored session ended
/// without a patch is a fixed point that runs no inference, and it takes no
/// slot.
async fn fair_claims(
&self,
entries: Vec<(CommandId, ElaboratorSession)>,
in_flight: &[(CommandId, ElaboratorSession)],
snapshot: &WorldSnapshot,
focus: &Focus,
) -> Result<Vec<(CommandId, ElaboratorSession)>, ControllerError> {
let mut untried = Vec::new();
let mut tried: Vec<((CommandId, ElaboratorSession), usize)> = Vec::new();
// Band 0 is the focus; each band holds its untried and its tried.
type Tried = Vec<((CommandId, ElaboratorSession), usize)>;
let mut bands: [(Vec<(CommandId, ElaboratorSession)>, Tried); 2] = Default::default();
for entry in entries {
let band = usize::from(!entry_in_focus(snapshot, focus, &entry.1));
let (untried, tried) = &mut bands[band];
if let Some(position) = in_flight.iter().position(|(id, _)| *id == entry.0) {
tried.push((entry, position));
continue;
@ -890,9 +898,13 @@ impl ElaborationRunner {
_ => tried.push((entry, usize::MAX)),
}
}
tried.sort_by_key(|(_, position)| *position);
untried.extend(tried.into_iter().map(|(entry, _)| entry));
Ok(untried)
let mut ordered = Vec::new();
for (mut untried, mut tried) in bands {
tried.sort_by_key(|(_, position)| *position);
untried.extend(tried.into_iter().map(|(entry, _)| entry));
ordered.append(&mut untried);
}
Ok(ordered)
}
/// The first entry of one jurisdiction's claim set, stepped: what a sweep
@ -998,9 +1010,8 @@ fn demand_entries(
}
}
}
let (focused, rest): (Vec<_>, Vec<_>) = entries.into_iter().partition(|(_, session)| {
answer_place(snapshot, &session.answer).is_some_and(|place| in_focus(snapshot, focus, place))
});
let (focused, rest): (Vec<_>, Vec<_>) =
entries.into_iter().partition(|(_, session)| entry_in_focus(snapshot, focus, session));
Ok(focused.into_iter().chain(rest).collect())
}
@ -1033,6 +1044,11 @@ fn answer_place(snapshot: &WorldSnapshot, answer: &PatchAnswer) -> Option<Entity
}
}
/// Whether the demand an entry answers sits at a focus place.
fn entry_in_focus(snapshot: &WorldSnapshot, focus: &Focus, session: &ElaboratorSession) -> bool {
answer_place(snapshot, &session.answer).is_some_and(|place| in_focus(snapshot, focus, place))
}
/// A place is in focus when it is a focus place, inside one, or one open route
/// from one, the route read either way: the player's exits and the way back.
pub(super) fn in_focus(snapshot: &WorldSnapshot, focus: &Focus, place: EntityId) -> bool {

View file

@ -469,18 +469,26 @@ impl CallRecordStore {
/// The first claim of a run writes its ledger: the cap it is opened under
/// the lane allowances, and the world it starts from. A later claim must name
/// the same cap and allowances; the start is not compared, because a resumed world has moved on.
/// With `follow`, a ledger already begun takes the cap and allowances named
/// here in place of its own, its spend kept: a caller whose limits change
/// while a run is open (the Dungeon's tuned allowances) owns them, and a
/// limit below what is already held only exhausts the lane.
fn claim(
&self,
run: &RunId,
cap: u64,
allowances: LaneTokens,
start: &RunStart,
follow: bool,
) -> Result<(), CallRecordError> {
let mut state = self.lock()?;
if !state.owned.insert(run.as_str().to_owned()) {
return Err(CallRecordError::RunInUse);
}
let begun = match state.runs.get(run.as_str()).and_then(|t| t.ledger.as_ref()) {
let begun = match state.runs.get(run.as_str()).and_then(|t| t.ledger.clone()) {
Some(ledger) if follow && (ledger.cap != cap || ledger.allowances != allowances) => {
Self::write_ledger(&mut state, RunLedger { cap, allowances, ..ledger })
}
Some(ledger) if ledger.cap != cap => Err(CallRecordError::RunMismatch(RunField::Cap)),
Some(ledger) if ledger.allowances != allowances => {
Err(CallRecordError::RunMismatch(RunField::Allowances))
@ -680,14 +688,24 @@ impl RecordingInferencePort {
allowances: LaneTokens,
start: &RunStart,
) -> Result<Self, CallRecordError> {
store.claim(&run, cap_tokens, allowances, start)?;
Ok(Self {
inner,
store,
run,
cap: cap_tokens,
allowances,
})
store.claim(&run, cap_tokens, allowances, start, false)?;
Ok(Self { inner, store, run, cap: cap_tokens, allowances })
}
/// `open`, except that a run already begun follows the cap and allowances
/// given here instead of refusing them: its ledger takes them, the spend
/// already held stays, and a lane whose allowance now sits below its spend
/// refuses further calls as exhausted.
pub fn open_following(
inner: Arc<dyn InferencePort>,
store: Arc<CallRecordStore>,
run: RunId,
cap_tokens: u64,
allowances: LaneTokens,
start: &RunStart,
) -> Result<Self, CallRecordError> {
store.claim(&run, cap_tokens, allowances, start, true)?;
Ok(Self { inner, store, run, cap: cap_tokens, allowances })
}
/// The run this port records.

View file

@ -527,6 +527,46 @@ async fn one_run_has_one_ledger_and_one_owner() {
assert_eq!(inner.calls(), 1);
}
#[tokio::test]
async fn a_following_open_takes_new_limits_and_keeps_the_spend() {
let directory = tempfile::tempdir().unwrap();
let (store, _) = store_in(&directory);
let prepared = prepared_for("follow", 1_200);
let bound = bound_of(&prepared);
let inner = ScriptedPort::new(vec![Ok(reply("a", "r1")), Ok(reply("b", "r2")), Ok(reply("c", "r3"))]);
let run = RunId::new("run-follow").unwrap();
let open = |cap: u64, follow: bool| {
let open = if follow { RecordingInferencePort::open_following } else { RecordingInferencePort::open };
open(inner.clone(), store.clone(), run.clone(), cap, lanes(cap), &start())
};
let first = open(bound, false).unwrap();
first.infer(prepared.clone()).await.unwrap();
first.infer(prepared.clone()).await.expect_err("the one call the limits allowed was made");
drop(first);
assert_eq!(open(bound * 2, false).err(), Some(CallRecordError::RunMismatch(RunField::Cap)), "a plain reopen still refuses other limits");
// Raised: the open ledger takes the new limits and the call that was refused runs.
let raised = open(bound * 2, true).unwrap();
assert_eq!(raised.spent(), bound, "the spend is kept");
raised.infer(prepared.clone()).await.unwrap();
drop(raised);
// Lowered below what is already held: the open succeeds and the lane is exhausted.
let lowered = open(bound / 2, true).unwrap();
assert_eq!(lowered.spent(), bound * 2);
lowered.infer(prepared.clone()).await.expect_err("the lane is exhausted");
assert_eq!(inner.calls(), 2);
drop(lowered);
// Either limit alone changing is followed too: the cap with the same lanes, the lanes with the same cap.
let other = |cap: u64, lanes: LaneTokens| {
RecordingInferencePort::open_following(inner.clone(), store.clone(), run.clone(), cap, lanes, &start())
};
drop(other(bound * 3, lanes(bound / 2)).unwrap());
drop(other(bound * 3, lanes(bound)).unwrap());
assert_eq!(other(bound * 3, lanes(bound)).unwrap().cap(), bound * 3);
drop(other(bound / 2, lanes(bound / 2)).unwrap());
// The limits the ledger now holds are the followed ones: a plain open of them is accepted.
drop(open(bound / 2, false).unwrap());
}
#[tokio::test]
async fn usage_over_the_bound_is_charged_in_full_and_faults_the_call() {
let directory = tempfile::tempdir().unwrap();

View file

@ -898,6 +898,7 @@ fn open_or_find(
opportunities,
graph,
&Focus::default(),
&[],
&config.knobs,
)?;
let tick = VerseTick {

View file

@ -226,17 +226,22 @@ fn folded(hierarchy: &Hierarchy, open: &BTreeSet<NodeId>, node: &Node) -> bool {
/// 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.
/// restricted here to each node's voices. `forced` names nodes a driver wants
/// turned now: each is opened like a focus node, is due whatever its band, and
/// runs before every node that is not forced.
pub fn plan_wave(
clock: WaveClock,
hierarchy: &Hierarchy,
opportunities: &[DecisionOpportunity],
graph: &AgencyGraph,
focus: &Focus,
forced: &[NodeId],
knobs: &GestaltKnobs,
) -> Result<Wave, GestaltKnobsError> {
knobs.validate()?;
let (open, distance) = open_and_distance(hierarchy, focus, knobs);
let mut attended = focus.clone();
attended.nodes.extend(forced.iter().copied());
let (open, distance) = open_and_distance(hierarchy, &attended, knobs);
let active: BTreeSet<SubjectId> = opportunities
.iter()
.filter(|opportunity| opportunity.controller_mode != super::ControllerMode::Human)
@ -291,7 +296,7 @@ pub fn plan_wave(
// 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 due: Vec<(bool, 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)) {
@ -302,24 +307,26 @@ pub fn plan_wave(
} else {
None
};
let is_due = match oldest {
None => true,
Some(stamp) => clock.now.since(stamp) >= u64::from(knobs.period(*at)),
};
let forced_now = forced.contains(id);
let is_due = forced_now
|| match oldest {
None => true,
Some(stamp) => clock.now.since(stamp) >= u64::from(knobs.period(*at)),
};
if is_due {
due.push((*at, oldest, *id));
due.push((!forced_now, *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) {
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) {
for (_, at, _, id) in due.into_iter().take(bound) {
let voices = &units
.iter()
.find(|(unit, _, _)| *unit == id)
@ -1018,6 +1025,7 @@ mod tests {
&opportunities(&f.state),
&AgencyGraph::default(),
focus,
&[],
knobs,
)
.unwrap()
@ -1087,6 +1095,46 @@ mod tests {
}
}
/// A forced node is open at the head of the wave and due whatever its
/// band, ahead of a node that is due by itself and inside the node-turn
/// bound; planned without it, nothing about it runs.
#[test]
fn a_forced_node_runs_first_though_its_band_has_not_passed() {
let r = realm();
let knobs = knobs(&[10, 360, 5000], 1, 1);
let empire_node = node(&r.f, NodeAnchor::Institution(r.empire));
let mut hierarchy = derive_hierarchy(&r.f.state);
let root = hierarchy.root();
for voice in [r.empire, r.herald, r.council, r.drinker, r.wanderers] {
hierarchy.last_attended.insert(voice, FictionalMinutes(999));
}
let world = r.f.state.world_id;
let opportunities = opportunities(&r.f.state);
let run = |forced: &[NodeId]| {
plan_wave(
WaveClock { world, ordinal: TickIndex(7), now: FictionalMinutes(1000) },
&hierarchy,
&opportunities,
&AgencyGraph::default(),
&Focus::default(),
forced,
&knobs,
)
.unwrap()
};
let plain = run(&[]);
assert!(plain.turns.iter().all(|turn| turn.node != empire_node), "the empire attended a minute ago is not due");
let forced = run(&[empire_node]);
assert_eq!(forced.turns.len(), 1, "the node-turn bound still holds");
assert_eq!(forced.turns[0].node, empire_node);
assert!(forced.turns[0].open && forced.turns[0].distance == 0);
assert!(
forced.deferred.contains(&(root, Deferral::OverBound)),
"the never-attended world waits behind the forced node: {:?}",
forced.deferred
);
}
#[test]
fn a_node_is_due_by_its_band_and_not_a_minute_sooner() {
let r = realm();
@ -1219,6 +1267,7 @@ mod tests {
&opportunities(&r.f.state),
&AgencyGraph::default(),
&at_tap_room(&r),
&[],
&knobs,
)
.unwrap();

View file

@ -267,8 +267,9 @@ Research notes of pass `gestalt-map` (`ghostlight-verse:research:gestalt-map.*`)
one open route from one (read either way); a boundary's place is its
destination's, or the position of the subject it names; a deficit's is its
jurisdiction root; the uncovered residual is nowhere. The partition is stable,
so an empty focus is today's order. Fair claims still puts an untried entry
before a tried one. It answers "what is the player looking at" with
so an empty focus is today's order. Focus is also the outer key of fair
claims: in-focus demand before the rest, and inside each band an untried
entry before a tried one. It answers "what is the player looking at" with
structure, where waves answer it with action.
- **Demotions.** `Scale::sweep_sessions` and `sweep_permits` stop deciding
how much elaboration happens; the elaboration allowance does, and permits
@ -285,9 +286,8 @@ the command id a request id begins with, so node spend is a join and
`NodeOutcome.spent` is gone. The verse tick is `ghostlight.verse_tick.v3` and
records what the plan deferred; the tick report lists deferred nodes with why
(not due, over the node-turn bound, past the allowance). The Dungeon's run-ahead
spends in `window-<world revision>` of the timeline's `calls.cc`, with
`GHOSTLIGHT_WINDOW_WAVE_TOKENS` and `GHOSTLIGHT_WINDOW_ELABORATION_TOKENS`
(unset is unbounded) until `dm-gestalt-knobs` sets them from the knobs.
spends in `window-<world revision>` of the timeline's `calls.cc`, under the
allowances of the timeline's knobs (below).
### Deletion line
@ -353,7 +353,46 @@ nothing is due until a band's period has passed and a wave never turns a world
whose clock has not moved. The clock stays the DM's. The DM's next opening view
carries the closed waves it has not seen: acts by node, then nodes due but not
run. A wave that stops with a cell unfinished stays open and is finished at the
timeline's next closed turn.
timeline's next closed turn. (That is the wave as `dungeon-world-waves`
landed it; the knobs, the document version and the room rule changed with
`dm-gestalt-knobs`, below.)
Landed (cut `dm-gestalt-knobs`, branch `ghostlight-verse/dm-gestalt-knobs` from
Ghostlight `main` `d3b0e20`): the knobs are one document per timeline,
`ghostlight.dungeon_gestalt_knobs.v1` in `gestalt-knobs.cc` (`knobs.rs`),
written with a Begin's defaults when a timeline opens without one: bands 60,
360, 1440 and 10080 minutes, depth 2, four node turns, cover 4/6/1, and a wave
and an elaboration allowance of 200000 tokens a window (sized to the retired
four-session sweep; no cost is measured yet). `default_knobs`,
`Scale::sweep_sessions`, `Scale::window` and their environment variables are
deleted; `Scale::sweep_permits` stays as the concurrency bound. The wave, the
run-ahead sweep and the opening view read the document, and each wave
(`ghostlight.dungeon_wave.v2`) records the knobs, allowances, DM focus and
forced nodes it planned under; the window it runs in follows the knobs as they
stand.
The DM turns them with two tools. `tune` sets bands (1 to 8 periods of 1 to
525600 minutes), depth (1 to 8), `max_node_turns` (1 to 32), the two lane
allowances (0 to 5000000 tokens), and adds or removes focus entries, each a
place or an institution by the id `table_view` prints, with a lease in
fictional minutes. A value outside its bound refuses the whole call, quoting
the value. A lease is an end minute: past it the entry is not focus, and the
next `tune` drops it. The player's own place is derived, never stored.
`run_world` names places or institutions; the next post-turn wave opens them
like focus nodes, treats them as due whatever their band and runs them ahead of
every other node, within the wave allowance (a node past it is reported
waiting); that wave takes the request whether or not it ran. The opening view
prints the knobs, the focus path by label, the DM's leases and queued nodes,
and the average tokens a node turn has cost in each band from the closed waves.
The knobs are the authority over a window's limits: a window already open at
the current revision follows a tuned allowance (`open_following`), keeps its
spend, and a lane held above a lowered allowance is exhausted, not an error.
A `run_world` target with no one to take a turn is frozen into its wave and the
next view says "nothing stirred" at it.
A wave gives no turn to a subject standing in the player's place: the room is
the DM's `react`. The DM's focus on an institution opens its node for waves;
the elaborator's claim order reads only the places.
## Cut sequence