From de80f8a84adffea201a88adb8bf848b969f9fb12 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 11:44:06 +0100 Subject: [PATCH] dungeon waves: a planned wave after each closed turn, frozen under its turn in waves.cc and finished on restart; the DM's opening view names what moved off-screen and what is due Co-Authored-By: Claude Opus 5.5 --- crates/ghostlight-dungeon/src/api.rs | 72 +- crates/ghostlight-dungeon/src/main.rs | 1 + crates/ghostlight-dungeon/src/play.rs | 29 +- crates/ghostlight-dungeon/src/run_ahead.rs | 4 +- crates/ghostlight-dungeon/src/state_layout.rs | 3 +- crates/ghostlight-dungeon/src/timelines.rs | 20 +- crates/ghostlight-dungeon/src/turn_log.rs | 5 + crates/ghostlight-dungeon/src/waves.rs | 803 ++++++++++++++++++ crates/ghostlight/src/verse/run.rs | 8 +- crates/ghostlight/src/verse/run/tests.rs | 3 +- 10 files changed, 929 insertions(+), 19 deletions(-) create mode 100644 crates/ghostlight-dungeon/src/waves.rs diff --git a/crates/ghostlight-dungeon/src/api.rs b/crates/ghostlight-dungeon/src/api.rs index ecdcd28..7d32d08 100644 --- a/crates/ghostlight-dungeon/src/api.rs +++ b/crates/ghostlight-dungeon/src/api.rs @@ -10,6 +10,7 @@ use crate::{ begin::{BeginRequest, begin}, catalog::SeedStatus, run_ahead::{evidence_of, run_ahead}, + waves::run_waves, play::{Admission, OpenQuestion, PlayError, PlayRequest, PlayTurnState, PlayTurnView}, runtime::AppState, }; @@ -430,17 +431,19 @@ async fn play( tracing::warn!(%error, ?turn_id, "a play turn ended in error"); } let _ = spawned.changes.send(()); - // The turn is closed: answer some of the world's deficit ahead of play. + // The turn is closed: the world moves on what the clock made due, and + // then answers some of its deficit ahead of play. let closed = ran.is_ok() && spawned .play .current_turn_view() .await .is_some_and(|view| view.state == PlayTurnState::Closed); - if closed - && let Some(evidence) = evidence_of(&state.catalog, state.vaults.as_ref(), &spawned, &timeline).await - { - run_ahead(&spawned, evidence, &state.scale).await; + if closed { + run_waves(&spawned, &state.scale, 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; + } } }); reply(StatusCode::ACCEPTED, json!({"outcome": "accepted"})) @@ -1333,6 +1336,65 @@ 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 + /// turn's opening view says what moved. + #[tokio::test] + async fn a_closed_turn_moves_the_world_and_the_next_view_says_so() { + let ids = |world: &ghostlight::WorldSnapshot| { + let speak = world.affordances.iter().find(|entry| entry.entry.kind.0 == "speak").unwrap().id; + let player = world.subjects.iter().find(|subject| subject.human_controller.as_ref() == Some(&world.owner)).unwrap(); + (serde_json::to_value(speak).unwrap(), serde_json::to_value(world.place_of(player.id).unwrap()).unwrap()) + }; + let app = app(vec![], &["alice"]).await; + 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()); + app.rig.port.push(Ok(output( + "r0", + vec![ + call_event( + "c0", + "declare_subject", + json!({ + "handle": "warden", + "label": "Warden", + "kind": "institution", + "controller": {"type": "operational_agent"}, + "affordances": [{"ref": "existing", "value": speak}], + "position": {"ref": "existing", "value": place}, + }), + ), + call_event("c1", "advance_time", json!({"minutes": 400})), + call_event("c2", END_TURN_TOOL, json!({})), + ], + ))); + app.rig.port.push(Ok(output("proj-0", vec![text_event("A day passes.")]))); + app.rig.port.push(Ok(output("w0", vec![call_event("act", "speak", json!({"text": "The gate holds."}))]))); + let (status, body) = play_text(&app, &cookie, &timeline, "I wait out the day.", None).await; + assert_eq!(status, StatusCode::ACCEPTED, "{body}"); + settled_turn(&app, &cookie, &timeline).await; + let wave = eventually(async || host.waves.lock().await.wave(1).filter(|wave| wave.report.is_some())).await; + assert_eq!(wave.opened_now, 400, "the wave planned over the clock the DM left"); + assert_eq!(host.world.snapshot().await.unwrap().now.0, 400, "and left it where it was"); + + app.rig.port.push(Ok(output("r1", vec![call_event("c3", END_TURN_TOOL, json!({}))]))); + app.rig.port.push(Ok(output("proj-1", vec![text_event("Nothing stirs.")]))); + let (status, body) = play_text(&app, &cookie, &timeline, "I wait again.", None).await; + assert_eq!(status, StatusCode::ACCEPTED, "{body}"); + settled_turn(&app, &cookie, &timeline).await; + let opening = app + .rig + .port + .seen_requests() + .iter() + .map(|request| serde_json::to_string(request).unwrap()) + .find(|text| text.contains("I wait again.")) + .expect("the second turn asked the model"); + assert!(opening.contains("Off-screen since your last turn") && opening.contains("The gate holds."), "{opening}"); + } + #[tokio::test] async fn only_a_closed_turn_runs_the_world_ahead() { let app = app_over(deferred_rig(), &["alice"]).await; diff --git a/crates/ghostlight-dungeon/src/main.rs b/crates/ghostlight-dungeon/src/main.rs index 691eb55..c38e1b9 100644 --- a/crates/ghostlight-dungeon/src/main.rs +++ b/crates/ghostlight-dungeon/src/main.rs @@ -20,6 +20,7 @@ mod timelines; mod turn_log; mod vaults; mod verbs; +mod waves; use anyhow::bail; use std::path::PathBuf; diff --git a/crates/ghostlight-dungeon/src/play.rs b/crates/ghostlight-dungeon/src/play.rs index 995ba55..2d21b6c 100644 --- a/crates/ghostlight-dungeon/src/play.rs +++ b/crates/ghostlight-dungeon/src/play.rs @@ -60,6 +60,7 @@ 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}; const STORE_TYPE: &str = "ghostlight.play_turn_store.v1"; /// PA.f172 bumped this from v1 to v2 when `question_surface_version` was @@ -193,6 +194,7 @@ on is `declare_trait`.\n\ view lists the open grievances the world has not answered. An office, a victim's kin and the witnesses answer \ 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. - Call `end_turn` when the round's consequences are settled."; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -1317,6 +1319,9 @@ pub(crate) struct PlayTable { /// itself. permits: Arc, store: Mutex, + /// 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, /// 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, @@ -1392,6 +1397,7 @@ impl PlayTable { model, permits, store: Mutex::new(store), + waves: None, log: Mutex::new(log), pending_retry: std::sync::Mutex::new(None), store_path, @@ -1405,6 +1411,18 @@ impl PlayTable { }) } + /// The table with the timeline's wave store behind its opening views. + pub(crate) fn with_waves(mut self, waves: WaveLog) -> Self { + self.waves = Some(waves); + self + } + + /// The `seq` of the newest turn log entry, 0 when nothing was shown yet: the + /// name a closed turn's world wave is keyed by. + pub(crate) async fn last_logged(&self) -> u64 { + self.log.lock().await.last_seq() + } + /// PA.f186/PA.f193-E: the most recent sidecar this store's directory /// carries, if any — not only one this process's own `open` wrote. /// Scanned fresh from disk on every call (`retired_row_sidecars_on_disk`, @@ -1748,13 +1766,20 @@ impl PlayTable { /// live snapshot, not from the caller's own evidence. async fn begin_turn(&self, key: String, text: String) -> Result { let snapshot = self.play.snapshot().await?; + let turn_id = uuid::Uuid::new_v4().to_string(); + // What moved off-screen since the table last looked, from the waves + // this turn is the first to see. + let moved = match &self.waves { + Some(waves) => offscreen_view(&waves.lock().await.take_unseen(&turn_id)?), + None => String::new(), + }; let opening_prompt = format!( - "{}\n\nThe player writes:\n{}\n", + "{}\n\n{moved}The player writes:\n{}\n", table_view(&snapshot), text ); Ok(PlayTurn { - turn_id: uuid::Uuid::new_v4().to_string(), + turn_id, applied_keys: vec![key], opening_prompt, player_prose: vec![text], diff --git a/crates/ghostlight-dungeon/src/run_ahead.rs b/crates/ghostlight-dungeon/src/run_ahead.rs index 138077a..8b3d224 100644 --- a/crates/ghostlight-dungeon/src/run_ahead.rs +++ b/crates/ghostlight-dungeon/src/run_ahead.rs @@ -33,7 +33,7 @@ pub(crate) async fn run_ahead(host: &TimelineHost, evidence: Arc Arc::new(window), Err(error) => { tracing::warn!(%error, "run-ahead could not open its window"); @@ -51,7 +51,7 @@ pub(crate) async fn run_ahead(host: &TimelineHost, evidence: Arc Focus { +pub(crate) fn focus_of(world: &WorldSnapshot) -> Focus { let places = world .subjects .iter() diff --git a/crates/ghostlight-dungeon/src/state_layout.rs b/crates/ghostlight-dungeon/src/state_layout.rs index f8e06ab..a181d3a 100644 --- a/crates/ghostlight-dungeon/src/state_layout.rs +++ b/crates/ghostlight-dungeon/src/state_layout.rs @@ -8,7 +8,8 @@ use std::{ }; /// The stores one timeline owns, each proved direct before it is opened. -pub(crate) const TIMELINE_STORES: [&str; 4] = ["world.cc", "controller-work.cc", "play-turn-v1.cc", "calls.cc"]; +pub(crate) const TIMELINE_STORES: [&str; 5] = + ["world.cc", "controller-work.cc", "play-turn-v1.cc", "calls.cc", "waves.cc"]; fn default_runtime_root() -> PathBuf { #[cfg(windows)] diff --git a/crates/ghostlight-dungeon/src/timelines.rs b/crates/ghostlight-dungeon/src/timelines.rs index 627fa28..6fc91a2 100644 --- a/crates/ghostlight-dungeon/src/timelines.rs +++ b/crates/ghostlight-dungeon/src/timelines.rs @@ -8,6 +8,7 @@ use crate::{ catalog::timeline_directory_name, play::PlayTable, state_layout::prepare_timeline_directory, + waves::{WaveLog, WaveStore}, }; use ghostlight::{ CallRecordError, CallRecordStore, ControllerModels, ControllerPort, ControllerRunner, @@ -40,21 +41,27 @@ pub(crate) struct TimelineHost { /// The spend ledgers of this timeline's background windows, one run each. /// The play turn's own calls never reach it. pub(crate) background: Arc, + /// The world waves this timeline's closed turns planned, and what the DM + /// has been shown of them. + pub(crate) waves: WaveLog, inference: Arc, } impl TimelineHost { /// The port of the post-turn window that follows world revision - /// `world.revision`: the one port the background lanes call a provider + /// `revision`: the one port the background lanes call a provider /// 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. + /// 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. + /// `world` is the world the window is opened over now. pub(crate) fn window( &self, + revision: u64, world: &WorldSnapshot, allowances: LaneTokens, ) -> Result { - let run = RunId::new(&format!("window-{}", world.revision))?; + let run = RunId::new(&format!("window-{revision}"))?; RecordingInferencePort::open( self.inference.clone(), self.background.clone(), @@ -108,6 +115,9 @@ impl Timelines { CallRecordStore::open(directory.join("calls.cc")) .context("the background call ledger could not be opened")?, ); + let waves: WaveLog = Arc::new(Mutex::new( + WaveStore::open(directory.join("waves.cc")).context("the wave store could not be opened")?, + )); let controllers = ControllerRunner::open( world.clone(), self.shared.inference.clone(), @@ -127,7 +137,8 @@ impl Timelines { self.shared.play_model.clone(), self.shared.permits.clone(), directory.join("play-turn-v1.cc"), - )?; + )? + .with_waves(waves.clone()); let (changes, _) = broadcast::channel(16); let host = Arc::new(TimelineHost { world, @@ -136,6 +147,7 @@ impl Timelines { changes, sweeping: Mutex::new(()), background, + waves, inference: self.shared.inference.clone(), }); hosts.insert(id.to_owned(), host.clone()); diff --git a/crates/ghostlight-dungeon/src/turn_log.rs b/crates/ghostlight-dungeon/src/turn_log.rs index 2ed31a0..90e5dae 100644 --- a/crates/ghostlight-dungeon/src/turn_log.rs +++ b/crates/ghostlight-dungeon/src/turn_log.rs @@ -105,6 +105,11 @@ impl TurnLog { Ok(Self { store, entries }) } + /// The `seq` of the newest entry; 0 for an empty log. + pub(crate) fn last_seq(&self) -> u64 { + self.entries.len() as u64 + } + pub(crate) fn contains(&self, seq: u64) -> bool { seq >= 1 && seq <= self.entries.len() as u64 } diff --git a/crates/ghostlight-dungeon/src/waves.rs b/crates/ghostlight-dungeon/src/waves.rs new file mode 100644 index 0000000..34cdc03 --- /dev/null +++ b/crates/ghostlight-dungeon/src/waves.rs @@ -0,0 +1,803 @@ +//! The Dungeon's world waves: after a closed turn the timeline plans one wave +//! of the gestalt hierarchy, freezes it, runs it through the controller organ, +//! and keeps what moved so the DM's next opening view can say so. +//! +//! 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 +//! 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 +//! inference and closed once with its report; a wave left open (a process that +//! died, a fault that left a cell pending) is finished as frozen before any new +//! 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 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, +}; +use serde::{Deserialize, Serialize}; +use std::{collections::BTreeMap, path::Path, sync::Arc}; +use tokio::sync::Mutex; + +const TYPE: &str = "ghostlight.dungeon_wave.v1"; + +/// 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)] +pub(crate) struct NodeMoved { + pub(crate) label: String, + pub(crate) distance: u8, + pub(crate) acts: Vec, + /// Tokens the node's calls were charged. + pub(crate) tokens: u64, +} + +/// A node due that took no turn, or not all of it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct NodeWaiting { + pub(crate) label: String, + pub(crate) reason: Deferral, +} + +/// A wave as it ended. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct WaveReport { + pub(crate) nodes: Vec, + pub(crate) waiting: Vec, + /// True when the window's wave allowance ran out before the last cell. + pub(crate) out_of_allowance: bool, +} + +/// One wave, document `ghostlight.dungeon_wave.v1`, 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)] +pub(crate) struct WaveRecord { + pub(crate) turn_seq: u64, + /// The world revision the wave opened at: also the window ledger it spends + /// in and the revision its acts are read past. + pub(crate) revision: u64, + pub(crate) opened_now: u64, + pub(crate) knobs: RecordedKnobs, + pub(crate) cells: Vec, + /// What the plan left out, frozen with the cells. + pub(crate) deferred: Vec<(NodeId, Deferral)>, + pub(crate) report: Option, + /// The turn whose opening view carried the report. + pub(crate) seen_by: Option, +} + +fn key_of(seq: u64) -> String { + format!("{seq:012}") +} + +/// The timeline's waves in one CultCache file. +pub(crate) struct WaveStore { + store: OwnedRedbMessagePackBackingStore, + waves: BTreeMap, +} + +pub(crate) type WaveLog = Arc>; + +impl WaveStore { + pub(crate) fn open(path: impl AsRef) -> anyhow::Result { + let store = OwnedRedbMessagePackBackingStore::new(path.as_ref())?; + store.validate_path_identity().context("wave store path identity is invalid")?; + let mut waves = BTreeMap::new(); + for row in store.pull_all()? { + ensure!(row.r#type == TYPE, "the wave store holds a foreign record"); + let record: WaveRecord = rmp_serde::from_slice(&row.payload).context("a wave did not decode")?; + ensure!(row.key == key_of(record.turn_seq), "a wave sits under the wrong key"); + waves.insert(record.turn_seq, record); + } + Ok(Self { store, waves }) + } + + fn put(&mut self, record: WaveRecord) -> anyhow::Result<()> { + let row = CultCacheEnvelope { + key: key_of(record.turn_seq), + r#type: TYPE.into(), + payload: rmp_serde::to_vec_named(&record)?, + stored_at: Utc::now().to_rfc3339(), + schema_id: Some(TYPE.into()), + }; + self.store.validate_path_identity().context("wave store ownership was lost")?; + self.store.push(&row)?; + self.waves.insert(record.turn_seq, record); + Ok(()) + } + + #[cfg(test)] + pub(crate) fn wave(&self, turn_seq: u64) -> Option { + self.waves.get(&turn_seq).cloned() + } + + pub(crate) fn contains(&self, turn_seq: u64) -> bool { + self.waves.contains_key(&turn_seq) + } + + /// Freezes a wave. A turn's wave is frozen once. + pub(crate) fn open_wave(&mut self, record: WaveRecord) -> anyhow::Result<()> { + ensure!(!self.contains(record.turn_seq), "that turn's wave is already frozen"); + ensure!(record.report.is_none() && record.seen_by.is_none(), "a wave opens unreported"); + self.put(record) + } + + /// Closes a wave with its report. A wave closes once. + pub(crate) fn close_wave(&mut self, turn_seq: u64, report: WaveReport) -> anyhow::Result<()> { + let mut record = self.waves.get(&turn_seq).cloned().context("no such wave")?; + ensure!(record.report.is_none(), "that wave is already closed"); + record.report = Some(report); + self.put(record) + } + + /// The waves still open, oldest first. + pub(crate) fn open_waves(&self) -> Vec { + self.waves.values().filter(|record| record.report.is_none()).cloned().collect() + } + + /// The closed waves `viewer`'s opening view carries, oldest first: those no + /// turn has carried yet, marked as this turn's, and those already marked as + /// this turn's, so asking again answers the same. + pub(crate) fn take_unseen(&mut self, viewer: &str) -> anyhow::Result> { + let mut taken = Vec::new(); + let keys: Vec = self.waves.keys().copied().collect(); + for key in keys { + let mut record = self.waves[&key].clone(); + if record.report.is_none() { + continue; + } + match record.seen_by.as_deref() { + Some(seen) if seen == viewer => {} + Some(_) => continue, + None => { + record.seen_by = Some(viewer.to_owned()); + self.put(record.clone())?; + } + } + taken.push(record); + } + Ok(taken) + } +} + +/// The section of the DM's opening view for waves it has not seen: what moved +/// off-screen, by node, and which due nodes did not run. Empty when there is +/// nothing to say, so a table with no waves opens as it always did. +pub(crate) fn offscreen_view(waves: &[WaveRecord]) -> String { + let reports: Vec<&WaveReport> = waves.iter().filter_map(|wave| wave.report.as_ref()).collect(); + let mut lines: Vec = Vec::new(); + let mut shown = 0usize; + let mut more = 0usize; + for report in &reports { + for node in &report.nodes { + let mut acts = Vec::new(); + for act in &node.acts { + if shown >= VIEW_ACTS { + more += 1; + } else { + shown += 1; + acts.push(act.chars().take(VIEW_LINE_CHARS).collect::()); + } + } + if !acts.is_empty() { + lines.push(format!("- {} (distance {}): {}", node.label, node.distance, acts.join("; "))); + } + } + } + let mut out = String::new(); + 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 { + out.push_str(line); + out.push('\n'); + } + if more > 0 { + out.push_str(&format!("- and {more} more acts the world holds\n")); + } + out.push('\n'); + } + let mut waiting: Vec = Vec::new(); + for report in &reports { + for node in &report.waiting { + let why = match node.reason { + Deferral::OverBound => "over the node-turn bound", + Deferral::Allowance => "past the allowance", + Deferral::NotDue => continue, + }; + let entry = format!("{} ({why})", node.label); + if !waiting.contains(&entry) { + waiting.push(entry); + } + } + } + if !waiting.is_empty() { + out.push_str(&format!("Due but not run, and still due next time: {}\n\n", waiting.join(", "))); + } + out +} + +/// Runs the timeline's world after a closed turn, `turn_seq` being its log +/// 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) { + let _running = host.sweeping.lock().await; + if let Err(error) = move_world(host, scale, 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<()> { + let open = host.waves.lock().await.open_waves(); + for record in open { + if !finish(host, scale, 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?; + Ok(()) +} + +/// The wave the clock makes due, frozen but not yet opened; none when nothing +/// is due. A voice the world has never given an opportunity is attended at the +/// clock's origin, so a world's people are first due when their band's period +/// has passed, and a wave never turns a world whose clock has not moved. +async fn plan(host: &TimelineHost, turn_seq: u64) -> anyhow::Result> { + let world = host.world.snapshot().await?; + let opportunities = host.world.opportunities().await?; + let graph = host.world.agency_graph().await?; + let mut hierarchy = host.world.hierarchy().await?; + for opportunity in &opportunities { + hierarchy + .last_attended + .entry(opportunity.scope.subject_id) + .or_insert(FictionalMinutes(0)); + } + let knobs = default_knobs(); + let wave = plan_wave( + WaveClock { + world: world.world_id, + ordinal: TickIndex(turn_seq), + now: FictionalMinutes(world.now.0), + }, + &hierarchy, + &opportunities, + &graph, + &focus_of(&world), + &knobs, + )?; + let cells = wave.frozen(); + if cells.is_empty() { + return Ok(None); + } + Ok(Some(WaveRecord { + turn_seq, + revision: world.revision, + opened_now: world.now.0, + knobs: RecordedKnobs::of(&knobs), + cells, + deferred: wave.deferred, + report: None, + seen_by: None, + })) +} + +/// 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 { + let world = host.world.snapshot().await?; + let window = Arc::new(host.window(record.revision, &world, scale.window)?); + let port: Arc = window.clone(); + let runner = host.controllers.through(port); + let ordinal = TickIndex(record.turn_seq); + let outcome = run_frozen_cells(&host.world, &runner, ordinal, &record.cells).await; + if let Some(WaveStop::Fault(code)) = outcome.stop { + tracing::warn!(code, turn_seq = record.turn_seq, "a world wave stopped with cells unfinished"); + return Ok(false); + } + let Some(acts) = acts_since(host.world.operator_log().await, record.revision) else { + return Ok(false); + }; + let after = host.world.snapshot().await?; + let hierarchy = host.world.hierarchy().await?; + let spend = WaveSpend::of(&window.records()?, world.world_id, ordinal, &record.cells)?; + let nodes = node_reports(&record.cells, &outcome, acts, &spend, &after, &hierarchy) + .into_iter() + .filter_map(|node| { + Some(NodeMoved { + label: node.label, + distance: node.distance?, + acts: node.acts.iter().map(act_line).collect(), + tokens: node.spent, + }) + }) + .collect(); + let waiting = deferred_nodes(&record.deferred, &record.cells, &outcome, &after, &hierarchy) + .into_iter() + .map(|node| NodeWaiting { label: node.label, reason: node.reason }) + .collect(); + let report = WaveReport { + nodes, + waiting, + out_of_allowance: outcome.stop == Some(WaveStop::Budget), + }; + host.waves.lock().await.close_wave(record.turn_seq, report)?; + Ok(true) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + catalog::timeline_id, + 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, + }; + use std::path::PathBuf; + use tokio::sync::{Notify, Semaphore, mpsc}; + use uuid::Uuid; + + fn models() -> ControllerModels { + ControllerModels { + projector: "claude-sonnet-5-5".into(), + persona: "claude-sonnet-5-5".into(), + interpreter: "claude-haiku-5-5".into(), + operational_agent: "claude-haiku-5-5".into(), + elaborator: "claude-sonnet-5-5".into(), + } + } + + fn principal() -> VerifiedPrincipalEvidence { + VerifiedPrincipalEvidence::new("waves-account", Utc::now() + chrono::Duration::hours(4)) + } + + /// 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 { + _directory: tempfile::TempDir, + root: PathBuf, + id: String, + scale: Scale, + } + + impl Fixture { + async fn new() -> Self { + let directory = tempfile::tempdir().unwrap(); + let root = std::fs::canonicalize(directory.path()).unwrap(); + prepare_admitted_state_layout(&root).unwrap(); + let uuid = Uuid::new_v4(); + let id = timeline_id(uuid); + let timeline = prepare_timeline_directory(&root, &uuid.hyphenated().to_string()).unwrap(); + let (world, task) = WorldMailbox::open(timeline.join("world.cc")).unwrap(); + let who = principal(); + let receipt = world + .create( + CreateWorldIntent { + id: CommandId::new(), + title: "Waves".into(), + brief: "A table for world waves.".into(), + human_subject_label: "Player".into(), + narrative_persona_label: None, + operational_agent_label: Some("Warden".into()), + targets: BTreeMap::new(), + jurisdictions: Vec::new(), + lens_weights: LensWeights::new(BTreeMap::from([(Lens::Hearth, 1)])), + era: None, + }, + &who, + ) + .await + .unwrap(); + for body in [CommandBody::ApproveDraft, CommandBody::ActivateWorld] { + let revision = world.snapshot().await.unwrap().revision; + world + .submit_principal( + PrincipalCommandIntent { + id: CommandId::new(), + world_id: receipt.world_id, + expected_revision: revision, + body, + }, + &who, + ) + .await + .unwrap(); + } + drop(world); + task.await.unwrap(); + Self { + _directory: directory, + root, + id, + scale: Scale::from_reader(|_| None), + } + } + + /// The timelines of one process life over `inference`, and the signal + /// that a world owner stopped. + fn open(&self, inference: Arc) -> (Timelines, mpsc::UnboundedReceiver) { + let (fatal, stopped) = mpsc::unbounded_channel(); + let timelines = Timelines::new( + self.root.clone(), + Shared { + inference, + models: models(), + play_model: "claude-sonnet-5-5".into(), + permits: Arc::new(Semaphore::new(2)), + }, + fatal, + ); + (timelines, stopped) + } + } + + fn speaks(receipt: &str, text: &str) -> InferenceOutput { + output(receipt, vec![call_event("act", "speak", serde_json::json!({"text": text}))]) + } + + async fn advance(host: &TimelineHost, minutes: u32) { + host.world + .submit_clock(CommandId::new(), TickMinutes::new(minutes).unwrap()) + .await + .unwrap(); + } + + async fn wave_of(host: &TimelineHost, turn_seq: u64) -> Option { + host.waves.lock().await.waves.get(&turn_seq).cloned() + } + + /// Spec test `a closed turn runs what is due`: once the clock has carried + /// the Warden past its band, a closed turn runs one wave whose cell commits + /// through the kernel, in the window's wave lane alone, and the wave never + /// moves the clock. + #[tokio::test] + async fn a_closed_turn_runs_what_is_due() { + 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(); + advance(&host, 400).await; + let before = host.world.snapshot().await.unwrap(); + + run_waves(&host, &fixture.scale, 1).await; + + let wave = wave_of(&host, 1).await.expect("the wave was frozen under its turn"); + let report = wave.report.expect("and closed"); + assert_eq!(report.nodes.len(), 1); + assert_eq!(report.nodes[0].distance, 0); + assert_eq!(report.nodes[0].acts.len(), 1); + assert!(report.nodes[0].acts[0].contains("Warden") && report.nodes[0].acts[0].contains("The gate holds.")); + assert!(report.nodes[0].tokens > 0, "the node's spend is reported"); + assert!(!report.out_of_allowance); + assert_eq!(wave.opened_now, 400); + assert_eq!(port.seen_requests().len(), 1); + let log = host.world.operator_log().await.unwrap(); + assert!(log.iter().any(|act| act.speaker_label == "Warden")); + let after = host.world.snapshot().await.unwrap(); + assert_eq!(after.now, before.now, "a wave never advances the clock"); + let window = ghostlight::RunId::new(&format!("window-{}", wave.revision)).unwrap(); + let spent = host.background.lane_spent(&window).unwrap(); + assert!(spent.wave > 0 && spent.elaboration == 0, "the wave spent in its own lane: {spent:?}"); + } + + /// Spec test `no time, no calls`, and its edge: the world's people are + /// attended at the clock's origin, so nothing is due before the nearest + /// band's period has passed and a closed turn calls no model. + #[tokio::test] + async fn no_time_no_calls() { + 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(); + run_waves(&host, &fixture.scale, 1).await; + run_waves(&host, &fixture.scale, 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; + 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; + assert_eq!(port.seen_requests().len(), 1, "the band's period has passed"); + } + + /// A voice attended since is not due again until its band has passed again. + #[tokio::test] + async fn an_attended_voice_waits_out_its_band_again() { + let fixture = Fixture::new().await; + let port = ScriptedPort::new(vec![speaks("w0", "First."), speaks("w1", "Second.")]); + 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; + 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; + assert_eq!(port.seen_requests().len(), 2); + } + + /// A turn's wave is frozen once: asking again for the same turn plans + /// nothing new and calls nothing. + #[tokio::test] + async fn a_turns_wave_is_frozen_once() { + let fixture = Fixture::new().await; + let port = ScriptedPort::new(vec![speaks("w0", "First."), speaks("w1", "Again.")]); + 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; + advance(&host, 400).await; + run_waves(&host, &fixture.scale, 1).await; + assert_eq!(port.seen_requests().len(), 1); + let mut waves = host.waves.lock().await; + let record = waves.waves[&1].clone(); + assert!(waves.open_wave(record.clone()).is_err(), "a frozen wave is not frozen again"); + assert!(waves.close_wave(1, record.report.clone().unwrap()).is_err(), "a closed wave is not closed again"); + } + + /// Spec test `restart finishes the open wave`: a wave whose cell did not + /// finish stays open, a new process life finishes it as frozen under the + /// ledger it opened in, and the resumed call is the cell's own command. + #[tokio::test] + async fn restart_finishes_the_open_wave_under_its_own_command_ids() { + let fixture = Fixture::new().await; + let down = ScriptedPort::new(vec![]); + down.push_answer(Err(InferenceFault::retryable("the connector is down"))); + 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; + 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); + 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(); + run_waves(&host, &fixture.scale, 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"); + assert_eq!(finished.revision, open.revision); + assert!(wave_of(&host, 2).await.is_none(), "the Warden was just attended: nothing new is due"); + let world = host.world.snapshot().await.unwrap().world_id; + let window = ghostlight::RunId::new(&format!("window-{}", open.revision)).unwrap(); + let spend = WaveSpend::of(&host.background.records(&window).unwrap(), world, TickIndex(1), &open.cells).unwrap(); + assert_eq!(spend.nodes[0].calls, 1, "the resumed call carries the frozen cell's command id"); + } + + /// An allowance that cannot cover a call closes the wave with its nodes + /// 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 port = ScriptedPort::new(vec![speaks("w0", "Unheard.")]); + 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; + 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); + assert!( + report.waiting.iter().any(|node| node.reason == Deferral::Allowance), + "the node past the allowance is reported: {report:?}" + ); + let log = host.world.operator_log().await.unwrap(); + assert!(log.iter().all(|act| act.speaker_label != "Warden"), "nothing was committed"); + } + + fn moved(label: &str, acts: &[&str]) -> NodeMoved { + NodeMoved { + label: label.into(), + distance: 1, + acts: acts.iter().map(|act| (*act).to_owned()).collect(), + tokens: 7, + } + } + + fn record(turn_seq: u64, report: Option) -> WaveRecord { + WaveRecord { + turn_seq, + revision: 1, + opened_now: 0, + knobs: RecordedKnobs::of(&default_knobs()), + cells: Vec::new(), + deferred: Vec::new(), + report, + seen_by: None, + } + } + + #[test] + fn the_view_names_what_moved_by_node_and_what_waits() { + let report = WaveReport { + nodes: vec![moved("Ironmarket Guild", &["Brask speak says \"Hold the gate.\""]), moved("Quiet Hall", &[])], + waiting: vec![ + NodeWaiting { label: "Crown".into(), reason: Deferral::OverBound }, + NodeWaiting { label: "Council".into(), reason: Deferral::Allowance }, + NodeWaiting { label: "Hamlet".into(), reason: Deferral::NotDue }, + ], + out_of_allowance: false, + }; + let view = offscreen_view(&[record(1, Some(report))]); + assert!(view.contains("Off-screen since your last turn")); + assert!(view.contains("- Ironmarket Guild (distance 1): Brask speak says \"Hold the gate.\"\n")); + assert!(!view.contains("Quiet Hall"), "a node that did nothing is not news"); + assert!(view.contains("Due but not run, and still due next time: Crown (over the node-turn bound), Council (past the allowance)\n")); + assert!(!view.contains("Hamlet"), "a node not yet due is not waiting"); + assert_eq!(offscreen_view(&[]), ""); + assert_eq!(offscreen_view(&[record(2, None)]), "", "an open wave has nothing to say yet"); + } + + #[test] + fn the_view_is_a_digest_not_the_ledger() { + let long = "x".repeat(VIEW_LINE_CHARS + 50); + let many: Vec = (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 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"); + assert!(view.contains(&format!("act 0 {}", "x".repeat(VIEW_LINE_CHARS - "act 0 ".len())))); + assert!(view.contains(&format!("act {} ", VIEW_ACTS - 1))); + assert!(!view.contains(&format!("act {VIEW_ACTS} "))); + } + + /// Spec test `the DM sees what moved`: the next turn's opening prompt names + /// the off-screen acts and the deferred nodes, once, and the turn after it + /// opens without them. + #[tokio::test] + async fn the_dm_sees_what_moved_once() { + let fixture = Fixture::new().await; + let port = ScriptedPort::new(vec![ + speaks("w0", "The gate holds."), + output("r0", vec![call_event("c0", crate::play::END_TURN_TOOL, serde_json::json!({}))]), + output("proj-0", vec![text_event("You wait.")]), + output("r1", vec![call_event("c1", crate::play::END_TURN_TOOL, serde_json::json!({}))]), + output("proj-1", vec![text_event("You wait again.")]), + ]); + 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; + { + let mut waves = host.waves.lock().await; + waves.open_wave(record(2, None)).unwrap(); + let report = WaveReport { + nodes: Vec::new(), + waiting: vec![NodeWaiting { label: "Crown".into(), reason: Deferral::OverBound }], + out_of_allowance: false, + }; + waves.close_wave(2, report).unwrap(); + } + let who = principal(); + host.play.run(&who, Uuid::new_v4().to_string(), "I wait.".into()).await.unwrap(); + let first = serde_json::to_string(&port.seen_requests()[1]).unwrap(); + assert!(first.contains("Off-screen since your last turn"), "{first}"); + assert!(first.contains("Warden") && first.contains("The gate holds.")); + assert!(first.contains("Crown (over the node-turn bound)")); + assert!( + first.find("Off-screen since").unwrap() < first.find("The player writes").unwrap(), + "the view opens before the player's words" + ); + 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 port that holds the operational agent's call until the test lets it + /// go, and answers every other call from its script. + struct HeldPort { + inner: Arc, + entered: Notify, + release: Notify, + } + + #[async_trait::async_trait] + impl InferencePort for HeldPort { + fn prepare(&self, request: ghostlight::InferenceRequest) -> Result { + self.inner.prepare(request) + } + + async fn infer(&self, request: PreparedInference) -> Result { + if request.purpose == InferencePurpose::OperationalAgent { + self.entered.notify_one(); + self.release.notified().await; + } + self.inner.infer(request).await + } + } + + /// Spec test `background never blocks play`: a play turn is accepted, runs + /// and closes while a wave sits inside a model call. + #[tokio::test] + async fn background_never_blocks_play() { + let fixture = Fixture::new().await; + let held = Arc::new(HeldPort { + inner: ScriptedPort::new(vec![ + output("r0", vec![call_event("c0", crate::play::END_TURN_TOOL, serde_json::json!({}))]), + output("proj-0", vec![text_event("You wait.")]), + speaks("w0", "The gate holds."), + ]), + entered: Notify::new(), + release: Notify::new(), + }); + let (timelines, _stopped) = fixture.open(held.clone()); + let host = timelines.host(&fixture.id).await.unwrap(); + 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 }) + }; + held.entered.notified().await; + assert!(host.sweeping.try_lock().is_err(), "the wave holds the sweep lock"); + + let who = principal(); + let ran = tokio::time::timeout( + std::time::Duration::from_secs(20), + host.play.run(&who, Uuid::new_v4().to_string(), "I wait.".into()), + ) + .await + .expect("the play turn did not wait for the wave"); + ran.unwrap(); + assert!(!waving.is_finished(), "the wave is still inside its call"); + + held.release.notify_one(); + waving.await.unwrap(); + assert!(wave_of(&host, 1).await.unwrap().report.is_some()); + } +} diff --git a/crates/ghostlight/src/verse/run.rs b/crates/ghostlight/src/verse/run.rs index d458a0c..1532d1f 100644 --- a/crates/ghostlight/src/verse/run.rs +++ b/crates/ghostlight/src/verse/run.rs @@ -26,12 +26,12 @@ use super::calls::{RecordingInferencePort, WaveSpend, canonical}; use crate::cover::TickIndex; use crate::wave::{ Deferral, DeferredNode, FrozenCell, Focus, GestaltKnobs, GestaltKnobsError, NodeReport, Refusal, - RefusalReason, UnattributedCall, WaveClock, WaveOutcome, WaveStop, act_line, acts_since, - deferred_nodes, node_label, node_reports, plan_wave, run_frozen_cells, + RefusalReason, UnattributedCall, WaveClock, WaveStop, act_line, acts_since, + deferred_nodes, node_reports, plan_wave, run_frozen_cells, }; use crate::{ AgencyGraph, CommandId, ControllerRunner, DecisionOpportunity, FictionalMinutes, Hierarchy, MailboxError, - NodeAnchor, NodeId, OperatorEvent, SubjectId, TickMinutes, WorldId, WorldMailbox, + NodeId, OperatorEvent, SubjectId, TickMinutes, WorldId, WorldMailbox, WorldSnapshot, }; use chrono::Utc; @@ -131,7 +131,7 @@ pub struct RecordedKnobs { } impl RecordedKnobs { - fn of(knobs: &GestaltKnobs) -> Self { + pub fn of(knobs: &GestaltKnobs) -> Self { Self { bands: knobs.bands.iter().map(|band| band.minutes()).collect(), depth: knobs.depth, diff --git a/crates/ghostlight/src/verse/run/tests.rs b/crates/ghostlight/src/verse/run/tests.rs index 08ed4eb..8a7e2b8 100644 --- a/crates/ghostlight/src/verse/run/tests.rs +++ b/crates/ghostlight/src/verse/run/tests.rs @@ -8,7 +8,8 @@ use crate::controllers::{ use crate::cover::derive_cover; use crate::controllers::{CellRun, ConstituentRefusalReason, ControllerError}; use crate::cover::{CellId, TickIndex}; -use crate::wave::{CellEnd, absorb, classify, pending_code, refreshed}; +use crate::wave::{CellEnd, WaveOutcome, absorb, classify, node_label, pending_code, refreshed}; +use crate::NodeAnchor; use crate::{Cell, CoverBudget, CoverBudgetError, EntityId, SubmitReceipt}; use crate::tests::stock_weights; use crate::verse::{