From 2732d38c960f8ecec5f3133c5d64b31bef0facb5 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 11:36:54 +0100 Subject: [PATCH 1/5] wave: reporting helpers (node_reports, deferred_nodes, node_label, acts_since, act_line) move from the verse driver to the wave organ; ControllerRunner::through runs the decision lanes over a window port Co-Authored-By: Claude Opus 5.5 --- crates/ghostlight/src/controllers.rs | 14 ++ crates/ghostlight/src/lib.rs | 8 +- crates/ghostlight/src/verse/mod.rs | 2 +- crates/ghostlight/src/verse/run.rs | 188 +------------------------- crates/ghostlight/src/wave.rs | 189 +++++++++++++++++++++++++++ 5 files changed, 214 insertions(+), 187 deletions(-) diff --git a/crates/ghostlight/src/controllers.rs b/crates/ghostlight/src/controllers.rs index 32149c7..efc4139 100644 --- a/crates/ghostlight/src/controllers.rs +++ b/crates/ghostlight/src/controllers.rs @@ -3283,6 +3283,20 @@ impl ControllerRunner { }) } + /// This runner's decision lanes over another inference port: the port of a + /// window whose ledger the calls reserve in. The mailbox, the work store and + /// the models are this runner's own, so a wave run through it resumes the + /// same controller-work rows. + pub fn through(&self, inference: Arc) -> Self { + Self { + mailbox: self.mailbox.clone(), + elaboration: self.elaboration.clone(), + inference, + work: Arc::clone(&self.work), + models: self.models.clone(), + } + } + /// The authoring lane, over the mailbox the decision lanes use, reading the /// evidence the caller's timeline is bound to and calling the provider only /// through `inference`: the port of the window the sweep spends in. A world diff --git a/crates/ghostlight/src/lib.rs b/crates/ghostlight/src/lib.rs index fa878cd..a30a01a 100644 --- a/crates/ghostlight/src/lib.rs +++ b/crates/ghostlight/src/lib.rs @@ -114,9 +114,9 @@ pub use aetheria::{ pub use cover::{AgencyGraph, Cell, Cover, CoverBudget, CoverBudgetError, TickIndex, derive_cover}; pub use hierarchy::{Hierarchy, Node, NodeAnchor, NodeId}; pub use wave::{ - Deferral, Focus, FrozenCell, GestaltKnobs, GestaltKnobsError, NodeOutcome, NodeTurn, Refusal, - RefusalReason, UnattributedCall, Wave, WaveClock, WaveOutcome, WaveStop, plan_wave, - run_frozen_cells, + Deferral, DeferredNode, Focus, FrozenCell, GestaltKnobs, GestaltKnobsError, NodeOutcome, NodeReport, + NodeTurn, Refusal, RefusalReason, UnattributedCall, Wave, WaveClock, WaveOutcome, WaveStop, + act_line, acts_since, deferred_nodes, node_label, node_reports, plan_wave, run_frozen_cells, }; pub use elaboration::{ ElaborationCheckpoint, ElaborationRunner, ElaboratorSession, SweepReport, EvidenceError, EvidenceQuery, @@ -168,7 +168,7 @@ pub use vault::{ pub use verse::{ CALL_RECORD_SCHEMA, CallRecordError, CallRecordStore, CreateVerseWorldIntent, Lane, LaneTokens, NodeSpend, ProviderCallRecord, WaveSpend, - RUN_RECORD_SCHEMA, DeferredNode, NodeReport, RecordedKnobs, RecordingInferencePort, RunClaim, + RUN_RECORD_SCHEMA, RecordedKnobs, RecordingInferencePort, RunClaim, ReplayInferencePort, RunField, RunId, RunOutcome, RunStart, RunStatus, TickCheckpoint, TickReport, VerseGenesisError, VerseRunConfig, VerseRunError, VerseRunRecord, VerseRunStore, call_run_id, run_manual, diff --git a/crates/ghostlight/src/verse/mod.rs b/crates/ghostlight/src/verse/mod.rs index 9b21250..efc3adf 100644 --- a/crates/ghostlight/src/verse/mod.rs +++ b/crates/ghostlight/src/verse/mod.rs @@ -14,7 +14,7 @@ pub use calls::{ WaveSpend, }; pub use run::{ - RUN_RECORD_SCHEMA, DeferredNode, NodeReport, RecordedKnobs, RunClaim, RunOutcome, RunStatus, + RUN_RECORD_SCHEMA, RecordedKnobs, RunClaim, RunOutcome, RunStatus, TickCheckpoint, TickReport, VerseRunConfig, VerseRunError, VerseRunRecord, VerseRunStore, call_run_id, run_manual, }; diff --git a/crates/ghostlight/src/verse/run.rs b/crates/ghostlight/src/verse/run.rs index e5a589a..d458a0c 100644 --- a/crates/ghostlight/src/verse/run.rs +++ b/crates/ghostlight/src/verse/run.rs @@ -25,12 +25,13 @@ use super::calls::{RecordingInferencePort, WaveSpend, canonical}; use crate::cover::TickIndex; use crate::wave::{ - Deferral, FrozenCell, Focus, GestaltKnobs, GestaltKnobsError, Refusal, RefusalReason, UnattributedCall, - WaveClock, WaveOutcome, WaveStop, plan_wave, run_frozen_cells, + 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, }; use crate::{ AgencyGraph, CommandId, ControllerRunner, DecisionOpportunity, FictionalMinutes, Hierarchy, MailboxError, - NodeAnchor, NodeId, OperatorEvent, RenderPath, SubjectId, TickMinutes, WorldId, WorldMailbox, + NodeAnchor, NodeId, OperatorEvent, SubjectId, TickMinutes, WorldId, WorldMailbox, WorldSnapshot, }; use chrono::Utc; @@ -206,29 +207,6 @@ pub struct VerseRunConfig { pub knobs: GestaltKnobs, } -/// What one node's turn did in a tick, as the operator reads it. -#[derive(Clone, Debug)] -pub struct NodeReport { - /// The node's anchor's label; `-` when the world no longer names the - /// anchor, and for acts no frozen cell claims. - pub label: String, - /// Hierarchy distance from the focus when the wave was planned; none for - /// acts no frozen cell claims. - pub distance: Option, - /// The acts the node's members committed, from the operator log. - pub acts: Vec, - pub refusals: Vec, - /// Tokens charged while the node's cells ran in this invocation. - pub spent: u64, -} - -/// A node that took no turn, or not all of it, as the operator reads it. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct DeferredNode { - pub label: String, - pub reason: Deferral, -} - /// A tick as the operator reads it, including the one a run ended inside. #[derive(Clone, Debug)] pub struct TickReport { @@ -290,22 +268,7 @@ impl std::fmt::Display for TickReport { None => writeln!(f, " node {}: {} tokens", node.label, node.spent)?, } for act in &node.acts { - let path = match act.render_path { - Some(RenderPath::ShipAction) => "ship_action", - Some(RenderPath::Conversation) => "conversation", - None => "-", - }; - write!(f, " {} {} [{path}]", act.speaker_label, act.verb)?; - for role in &act.roles { - write!(f, " {}={}", role.role, role.target)?; - } - if let Some(speech) = &act.speech { - write!(f, " says {:?}", speech.as_str())?; - } - if let Some(display) = &act.display { - write!(f, " shows {:?}", display.as_str())?; - } - writeln!(f)?; + writeln!(f, " {}", act_line(act))?; } for refusal in &node.refusals { let reason = match refusal.reason { @@ -890,7 +853,7 @@ where .collect(); let report = TickReport { nodes: node_reports(&tick.cells, &outcome, acts, &spend, &snapshot, &hierarchy), - deferred: deferred_nodes(&tick, &outcome, &snapshot, &hierarchy), + deferred: deferred_nodes(&tick.deferred, &tick.cells, &outcome, &snapshot, &hierarchy), spend, checkpoint, labels, @@ -900,145 +863,6 @@ where (open.map_or(TickEnd::Closed, TickEnd::Open), Some(report)) } -/// The tick's nodes in the order its frozen cells first name them, each with -/// the acts its members committed and the refusals its cells ended in. A node -/// the run never reached and that committed nothing is not listed. An act no -/// frozen cell claims is kept under a node labelled `-`, never dropped. -fn node_reports( - frozen: &[FrozenCell], - outcome: &WaveOutcome, - acts: Vec, - spend: &WaveSpend, - snapshot: &WorldSnapshot, - hierarchy: &Hierarchy, -) -> Vec { - let mut order: Vec<(NodeId, u8)> = Vec::new(); - let mut home: BTreeMap = BTreeMap::new(); - for cell in frozen { - let at = order - .iter() - .position(|(node, _)| *node == cell.node) - .unwrap_or_else(|| { - order.push((cell.node, cell.distance)); - order.len() - 1 - }); - home.extend(cell.members.iter().map(|member| (*member, at))); - } - let mut reports: Vec = order - .iter() - .map(|(node, distance)| { - let ran = outcome.nodes.iter().find(|ran| ran.node == *node); - NodeReport { - label: node_label(*node, snapshot, hierarchy), - distance: Some(*distance), - acts: Vec::new(), - refusals: ran.map(|ran| ran.refusals.clone()).unwrap_or_default(), - spent: spend - .nodes - .iter() - .find(|spent| spent.node == *node) - .map_or(0, |spent| spent.charged), - } - }) - .collect(); - let ran: Vec = order - .iter() - .map(|(node, _)| outcome.nodes.iter().any(|ran| ran.node == *node)) - .collect(); - let mut unclaimed = Vec::new(); - for act in acts { - match home.get(&act.speaker) { - Some(&at) => reports[at].acts.push(act), - None => unclaimed.push(act), - } - } - let mut kept: Vec = reports - .into_iter() - .zip(ran) - .filter(|(report, ran)| *ran || !report.acts.is_empty()) - .map(|(report, _)| report) - .collect(); - if !unclaimed.is_empty() { - kept.push(NodeReport { - label: "-".into(), - distance: None, - acts: unclaimed, - refusals: Vec::new(), - spent: 0, - }); - } - kept -} - -/// The nodes of the tick that took no turn: the plan's deferrals, frozen with -/// the tick, and, when the run stopped on its allowance, the nodes it never -/// reached and the one it stopped inside. A fault stop defers nothing. -fn deferred_nodes( - tick: &VerseTick, - outcome: &WaveOutcome, - snapshot: &WorldSnapshot, - hierarchy: &Hierarchy, -) -> Vec { - let mut deferred: Vec<(NodeId, Deferral)> = tick.deferred.clone(); - if outcome.stop == Some(WaveStop::Budget) { - let entered: Vec = outcome.nodes.iter().map(|node| node.node).collect(); - let stopped_in = entered.last().copied(); - let mut seen: Vec = Vec::new(); - for cell in &tick.cells { - if seen.contains(&cell.node) { - continue; - } - seen.push(cell.node); - if !entered.contains(&cell.node) || Some(cell.node) == stopped_in { - deferred.push((cell.node, Deferral::Allowance)); - } - } - } - deferred - .into_iter() - .map(|(node, reason)| DeferredNode { - label: node_label(node, snapshot, hierarchy), - reason, - }) - .collect() -} - -/// What the operator calls a node: its anchor's label in the snapshot, `world` -/// for the root, `-` for an anchor the world no longer holds. -fn node_label(node: NodeId, snapshot: &WorldSnapshot, hierarchy: &Hierarchy) -> String { - let subject = |id: SubjectId| { - snapshot - .subjects - .iter() - .find(|subject| subject.id == id) - .map(|subject| subject.label.clone()) - }; - match hierarchy.nodes.get(&node).map(|node| node.anchor) { - Some(NodeAnchor::World) => Some("world".to_owned()), - Some(NodeAnchor::Institution(id) | NodeAnchor::Subject(id)) => subject(id), - Some(NodeAnchor::Place(entity)) => snapshot - .places - .iter() - .find(|place| place.id == entity) - .map(|place| place.label.clone()), - None => None, - } - .unwrap_or_else(|| "-".to_owned()) -} - -/// The acts a tick committed: the operator log's events past the tick's -/// opening revision. A log that cannot be read is `None`, never an empty tick. -fn acts_since( - log: Result, MailboxError>, - since: u64, -) -> Option> { - log.ok().map(|log| { - log.into_iter() - .filter(|event| event.revision > since) - .collect() - }) -} - /// The tick document for `ordinal`: the open one a run left, or a new one /// frozen from a wave planned now over the derived hierarchy with no focus. An /// open tick the world has moved past is closed as the world's first. A diff --git a/crates/ghostlight/src/wave.rs b/crates/ghostlight/src/wave.rs index b83acb2..982efb5 100644 --- a/crates/ghostlight/src/wave.rs +++ b/crates/ghostlight/src/wave.rs @@ -42,6 +42,8 @@ use super::{ SubmissionDisposition, }, hierarchy::{Hierarchy, Node, NodeAnchor, NodeId}, + verse::WaveSpend, + MailboxError, OperatorEvent, RenderPath, WorldSnapshot, }; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet, VecDeque}; @@ -762,6 +764,193 @@ pub async fn run_frozen_cells( WaveOutcome { nodes, stop } } +// What a wave did, as a reader sees it. + +/// What one node's turn did in a wave, as the operator or the table reads it. +#[derive(Clone, Debug)] +pub struct NodeReport { + /// The node's anchor's label; `-` when the world no longer names the + /// anchor, and for acts no frozen cell claims. + pub label: String, + /// Hierarchy distance from the focus when the wave was planned; none for + /// acts no frozen cell claims. + pub distance: Option, + /// The acts the node's members committed, from the operator log. + pub acts: Vec, + pub refusals: Vec, + /// Tokens charged while the node's cells ran in this invocation. + pub spent: u64, +} + +/// A node that took no turn, or not all of it, as the operator reads it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DeferredNode { + pub label: String, + pub reason: Deferral, +} + +/// The tick's nodes in the order its frozen cells first name them, each with +/// the acts its members committed and the refusals its cells ended in. A node +/// the run never reached and that committed nothing is not listed. An act no +/// frozen cell claims is kept under a node labelled `-`, never dropped. +pub fn node_reports( + frozen: &[FrozenCell], + outcome: &WaveOutcome, + acts: Vec, + spend: &WaveSpend, + snapshot: &WorldSnapshot, + hierarchy: &Hierarchy, +) -> Vec { + let mut order: Vec<(NodeId, u8)> = Vec::new(); + let mut home: BTreeMap = BTreeMap::new(); + for cell in frozen { + let at = order + .iter() + .position(|(node, _)| *node == cell.node) + .unwrap_or_else(|| { + order.push((cell.node, cell.distance)); + order.len() - 1 + }); + home.extend(cell.members.iter().map(|member| (*member, at))); + } + let mut reports: Vec = order + .iter() + .map(|(node, distance)| { + let ran = outcome.nodes.iter().find(|ran| ran.node == *node); + NodeReport { + label: node_label(*node, snapshot, hierarchy), + distance: Some(*distance), + acts: Vec::new(), + refusals: ran.map(|ran| ran.refusals.clone()).unwrap_or_default(), + spent: spend + .nodes + .iter() + .find(|spent| spent.node == *node) + .map_or(0, |spent| spent.charged), + } + }) + .collect(); + let ran: Vec = order + .iter() + .map(|(node, _)| outcome.nodes.iter().any(|ran| ran.node == *node)) + .collect(); + let mut unclaimed = Vec::new(); + for act in acts { + match home.get(&act.speaker) { + Some(&at) => reports[at].acts.push(act), + None => unclaimed.push(act), + } + } + let mut kept: Vec = reports + .into_iter() + .zip(ran) + .filter(|(report, ran)| *ran || !report.acts.is_empty()) + .map(|(report, _)| report) + .collect(); + if !unclaimed.is_empty() { + kept.push(NodeReport { + label: "-".into(), + distance: None, + acts: unclaimed, + refusals: Vec::new(), + spent: 0, + }); + } + kept +} + +/// The nodes of a wave that took no turn, or not all of it: the plan's +/// deferrals, frozen with the wave, and, when the run stopped on its allowance, +/// the nodes it never reached and the one it stopped inside. A fault stop +/// defers nothing. +pub fn deferred_nodes( + planned: &[(NodeId, Deferral)], + frozen: &[FrozenCell], + outcome: &WaveOutcome, + snapshot: &WorldSnapshot, + hierarchy: &Hierarchy, +) -> Vec { + let mut deferred: Vec<(NodeId, Deferral)> = planned.to_vec(); + if outcome.stop == Some(WaveStop::Budget) { + let entered: Vec = outcome.nodes.iter().map(|node| node.node).collect(); + let stopped_in = entered.last().copied(); + let mut seen: Vec = Vec::new(); + for cell in frozen { + if seen.contains(&cell.node) { + continue; + } + seen.push(cell.node); + if !entered.contains(&cell.node) || Some(cell.node) == stopped_in { + deferred.push((cell.node, Deferral::Allowance)); + } + } + } + deferred + .into_iter() + .map(|(node, reason)| DeferredNode { + label: node_label(node, snapshot, hierarchy), + reason, + }) + .collect() +} + +/// What the operator calls a node: its anchor's label in the snapshot, `world` +/// for the root, `-` for an anchor the world no longer holds. +pub fn node_label(node: NodeId, snapshot: &WorldSnapshot, hierarchy: &Hierarchy) -> String { + let subject = |id: SubjectId| { + snapshot + .subjects + .iter() + .find(|subject| subject.id == id) + .map(|subject| subject.label.clone()) + }; + match hierarchy.nodes.get(&node).map(|node| node.anchor) { + Some(NodeAnchor::World) => Some("world".to_owned()), + Some(NodeAnchor::Institution(id) | NodeAnchor::Subject(id)) => subject(id), + Some(NodeAnchor::Place(entity)) => snapshot + .places + .iter() + .find(|place| place.id == entity) + .map(|place| place.label.clone()), + None => None, + } + .unwrap_or_else(|| "-".to_owned()) +} + +/// The acts a tick committed: the operator log's events past the tick's +/// opening revision. A log that cannot be read is `None`, never an empty tick. +pub fn acts_since( + log: Result, MailboxError>, + since: u64, +) -> Option> { + log.ok().map(|log| { + log.into_iter() + .filter(|event| event.revision > since) + .collect() + }) +} + +/// One committed act as a line of prose for a reader: who, which verb, how it +/// renders, what its roles are bound to, what was said or shown. +pub fn act_line(act: &OperatorEvent) -> String { + let path = match act.render_path { + Some(RenderPath::ShipAction) => "ship_action", + Some(RenderPath::Conversation) => "conversation", + None => "-", + }; + let mut line = format!("{} {} [{path}]", act.speaker_label, act.verb); + for role in &act.roles { + line.push_str(&format!(" {}={}", role.role, role.target)); + } + if let Some(speech) = &act.speech { + line.push_str(&format!(" says {:?}", speech.as_str())); + } + if let Some(display) = &act.display { + line.push_str(&format!(" shows {:?}", display.as_str())); + } + line +} + #[cfg(test)] mod tests { use super::*; From de80f8a84adffea201a88adb8bf848b969f9fb12 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 11:44:06 +0100 Subject: [PATCH 2/5] 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::{ From 85365d2aece2fe28d527d4364d8eed3054bb6411 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 11:47:34 +0100 Subject: [PATCH 3/5] dungeon waves: the view-before-words check names the opening's own line Co-Authored-By: Claude Opus 5.5 --- crates/ghostlight-dungeon/src/waves.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ghostlight-dungeon/src/waves.rs b/crates/ghostlight-dungeon/src/waves.rs index 34cdc03..755fe0a 100644 --- a/crates/ghostlight-dungeon/src/waves.rs +++ b/crates/ghostlight-dungeon/src/waves.rs @@ -730,7 +730,7 @@ mod tests { 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(), + 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(); From fac31f126b1e45c23e9331a9b699f7e591512b3c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 11:47:42 +0100 Subject: [PATCH 4/5] docs: the Dungeon's world waves have landed Co-Authored-By: Claude Opus 5.5 --- docs/targets/multiresolution-gestalt.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/docs/targets/multiresolution-gestalt.md b/docs/targets/multiresolution-gestalt.md index 7388e61..057e344 100644 --- a/docs/targets/multiresolution-gestalt.md +++ b/docs/targets/multiresolution-gestalt.md @@ -337,6 +337,24 @@ is depth 1 and one band at the tick span, which plans the flat cover's shape. `run_frozen_cells` in `wave.rs` runs the frozen cells for any driver; the clock advance stays in the verse driver. +Landed (cut `dungeon-world-waves`, branch `ghostlight-verse/dungeon-world-waves` +from Ghostlight `main` `ab290dc`): after each closed play turn the Dungeon runs +`run_waves` (`waves.rs`) under the sweep lock, before run-ahead. It finishes any +wave left open, then plans one wave with `plan_wave` over the derived hierarchy +with the player's place as focus and constant knobs (bands 60, 360, 1440 and +10080 minutes, depth 2, four node turns, cover 4/6/1). The wave is frozen under +the closed turn's log `seq` in the timeline's `waves.cc` +(`ghostlight.dungeon_wave.v1`) before its first call, runs through +`run_frozen_cells` on a runner over the window port, and closes once with a +report. It spends in `window-`, so a resumed wave +reopens its own ledger and re-submits its own command ids. A voice the world +has never given an opportunity counts as attended at the clock's origin, so +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. + ## Cut sequence Each cut is one `cut_spec` in the mind, `ghostlight-verse:cut_spec:cut-.r1`, From 738b57bada1af361e73a0e9aea98d5c738e0d860 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 12:50:15 +0100 Subject: [PATCH 5/5] dungeon waves: tests pin the turn key, the one-view hand-off, the open wave holding the next back, and a wave that never reaches the model Co-Authored-By: Claude Opus 5.5 --- crates/ghostlight-dungeon/src/api.rs | 11 ++++- crates/ghostlight-dungeon/src/turn_log.rs | 2 + crates/ghostlight-dungeon/src/waves.rs | 50 ++++++++++++++++++++++- 3 files changed, 61 insertions(+), 2 deletions(-) diff --git a/crates/ghostlight-dungeon/src/api.rs b/crates/ghostlight-dungeon/src/api.rs index 7d32d08..c849061 100644 --- a/crates/ghostlight-dungeon/src/api.rs +++ b/crates/ghostlight-dungeon/src/api.rs @@ -1379,8 +1379,12 @@ mod tests { 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( + "r1", + vec![call_event("c3", "advance_time", json!({"minutes": 100})), call_event("c4", END_TURN_TOOL, json!({}))], + ))); app.rig.port.push(Ok(output("proj-1", vec![text_event("Nothing stirs.")]))); + app.rig.port.push(Ok(output("w1", vec![call_event("act", "speak", json!({"text": "The gate still holds."}))]))); 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; @@ -1393,6 +1397,11 @@ mod tests { .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}"); + // A wave is named by the closed turn that followed it: the second + // turn's wave is the second entry of the log, not the first. + let second = eventually(async || host.waves.lock().await.wave(2).filter(|wave| wave.report.is_some())).await; + assert_eq!(second.opened_now, 500); + assert!(second.report.unwrap().nodes[0].acts[0].contains("The gate still holds.")); } #[tokio::test] diff --git a/crates/ghostlight-dungeon/src/turn_log.rs b/crates/ghostlight-dungeon/src/turn_log.rs index 90e5dae..65b5df4 100644 --- a/crates/ghostlight-dungeon/src/turn_log.rs +++ b/crates/ghostlight-dungeon/src/turn_log.rs @@ -204,8 +204,10 @@ mod tests { let path = directory.path().join("turn-log-v1.cc"); { let mut log = TurnLog::open(&path).unwrap(); + assert_eq!(log.last_seq(), 0); for n in 1..=5 { assert_eq!(log.record(new(&format!("t{n}"), 1, &format!("say {n}"))).unwrap(), Some(n)); + assert_eq!(log.last_seq(), n); } assert_eq!(log.record(new("t3", 1, "say 3 again")).unwrap(), None, "a recorded submission is never rewritten"); let newest = log.page(None, 2); diff --git a/crates/ghostlight-dungeon/src/waves.rs b/crates/ghostlight-dungeon/src/waves.rs index 755fe0a..d448604 100644 --- a/crates/ghostlight-dungeon/src/waves.rs +++ b/crates/ghostlight-dungeon/src/waves.rs @@ -578,6 +578,7 @@ mod tests { run_waves(&host, &fixture.scale, 1).await; assert_eq!(port.seen_requests().len(), 1); let mut waves = host.waves.lock().await; + assert!(waves.contains(1) && !waves.contains(7)); 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"); @@ -598,6 +599,12 @@ mod tests { 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; + 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); drop(timelines); stopped.recv().await.expect("the world owner stopped with the process"); @@ -678,10 +685,49 @@ mod tests { 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!(!view.contains("more acts"), "nothing was cut, so nothing is counted: {view}"); assert_eq!(offscreen_view(&[]), ""); assert_eq!(offscreen_view(&[record(2, None)]), "", "an open wave has nothing to say yet"); } + /// A wave is carried by one turn's opening view: the first to ask takes it, + /// asking again answers the same, and every other turn finds it taken. + #[test] + fn a_wave_belongs_to_the_one_view_that_took_it() { + let directory = tempfile::tempdir().unwrap(); + let mut store = WaveStore::open(directory.path().join("waves.cc")).unwrap(); + 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(); + 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(); + assert!(store.take_unseen("second").unwrap().iter().map(|wave| wave.turn_seq).eq([2])); + } + + /// Waves are keyed by their turn and survive the process: two waves reopen + /// as two, each as it was closed, each marked as its viewer left it. + #[test] + fn waves_survive_a_reopen_each_under_its_own_turn() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("waves.cc"); + { + 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.take_unseen("viewer").unwrap(); + } + let store = WaveStore::open(&path).unwrap(); + assert_eq!(store.open_waves().iter().map(|wave| wave.turn_seq).collect::>(), [3]); + let closed = store.wave(4).unwrap(); + assert_eq!(closed.report.unwrap().nodes[0].label, "Guild"); + assert_eq!(closed.seen_by.as_deref(), Some("viewer")); + assert!(store.wave(3).unwrap().seen_by.is_none()); + } + #[test] fn the_view_is_a_digest_not_the_ledger() { let long = "x".repeat(VIEW_LINE_CHARS + 50); @@ -783,7 +829,9 @@ mod tests { let scale = fixture.scale.clone(); tokio::spawn(async move { run_waves(&host, &scale, 1).await }) }; - held.entered.notified().await; + tokio::time::timeout(std::time::Duration::from_secs(20), held.entered.notified()) + .await + .expect("the wave reached the model"); assert!(host.sweeping.try_lock().is_err(), "the wave holds the sweep lock"); let who = principal();