diff --git a/crates/ghostlight-dungeon/playtest/plan.json b/crates/ghostlight-dungeon/playtest/plan.json new file mode 100644 index 0000000..a8bf733 --- /dev/null +++ b/crates/ghostlight-dungeon/playtest/plan.json @@ -0,0 +1,79 @@ +{ + "turns_per_character": 12, + "wall_minutes": 240, + "turn_timeout_minutes": 15, + "character_model": "claude-sonnet-5-5", + "critic_model": "claude-opus-5-5", + "prices": { + "opus": { "input": 4.0, "output": 20.0, "cache_read": 0.2 }, + "sonnet": { "input": 2.0, "output": 10.0, "cache_read": 0.1 }, + "haiku": { "input": 0.1, "output": 0.5 } + }, + "temperaments": { + "diplomat": { + "goal": "Make allies and brokered deals; leave every room better disposed toward you than you found it.", + "manner": "Talks first and listens closely. Offers trades, introductions and face-saving ways out. Never draws a weapon unless cornered.", + "pushes_on": "Whether NPCs have their own interests and bargain back, or simply agree." + }, + "murderhobo": { + "goal": "Take what you want and answer slights with steel.", + "manner": "Quick to anger, blunt, armed. Escalates to violence at the first insult or obstacle, then looks for loot.", + "pushes_on": "Whether the world pushes back: guards, kin, law, reputation, wounds." + }, + "wanderer": { + "goal": "See as much of the world as you can: go places, ask what lies beyond them, follow every road and rumour.", + "manner": "Curious and restless. Moves on whenever somewhere is explored. Asks locals about the next place and about their own history.", + "pushes_on": "Whether the world has depth ahead of the player, or invents it thin." + }, + "schemer": { + "goal": "Gain power by playing factions against one another.", + "manner": "Lies fluently, carries tales between parties, makes promises you intend to break, and keeps track of who owes whom.", + "pushes_on": "Whether factions have memory and consequences, and whether lies can be caught." + }, + "devout": { + "goal": "Live by the local faith or creed and seek its rites, shrines, teachers and doctrine.", + "manner": "Earnest and respectful. Asks what is believed, what is forbidden, what is owed to the powers. Takes part in observances.", + "pushes_on": "Depth of lore about belief, cosmology and the powers a setting holds sacred." + }, + "grifter": { + "goal": "Come out ahead through theft, cheating and unpaid debts.", + "manner": "Charming and shifty. Picks pockets, short-changes, forges, runs cons, skips out on what is owed.", + "pushes_on": "Whether ledgers, debts, law and watchfulness exist and bite." + }, + "provocateur": { + "goal": "Stir trouble: insult the powerful, defy rules, take the unpopular side of every dispute.", + "manner": "Loud, contrarian, theatrical. Says what nobody wants said and refuses to back down.", + "pushes_on": "Whether NPCs make enemies of you and stay hostile, or forgive at once." + }, + "charmer": { + "goal": "Win hearts: flirt, seduce, court and be courted.", + "manner": "Warm, flattering, bold about desire. Pursues romance with whoever seems interested and watches how the story handles it.", + "pushes_on": "Romance handling, and whether content limits are stated honestly rather than evaded." + } + }, + "worlds": [ + { "id": "delvehold-diplomat", "vault": "delvehold", "era": "present", "name": "Ilsa Brandt", "temperament": "diplomat" }, + { "id": "delvehold-murderhobo", "vault": "delvehold", "era": "present", "name": "Korr Skullsplitter", "temperament": "murderhobo" }, + { "id": "delvehold-grifter", "vault": "delvehold", "era": "present", "name": "Pip Tallowcandle", "temperament": "grifter" }, + { + "id": "aetheria-pre-schemer", "vault": "aetheria", "era": "pre-elysium", "name": "Vesper Quill", "temperament": "schemer", + "lenses": { "weighted": { "charter": 3, "veil": 3, "hearth": 3 }, "rest": 1 } + }, + { + "id": "aetheria-pre-devout", "vault": "aetheria", "era": "pre-elysium", "name": "Sister Anwen Roe", "temperament": "devout", + "lenses": { "weighted": { "charter": 3, "veil": 3, "hearth": 3 }, "rest": 1 } + }, + { + "id": "aetheria-pre-provocateur", "vault": "aetheria", "era": "pre-elysium", "name": "Dax Marlowe", "temperament": "provocateur", + "lenses": { "weighted": { "charter": 3, "veil": 3, "hearth": 3 }, "rest": 1 } + }, + { + "id": "aetheria-post-wanderer", "vault": "aetheria", "era": "post-elysium", "name": "Tamsin Ode", "temperament": "wanderer", + "lenses": { "weighted": { "numen": 3, "veil": 3, "tangle": 3 }, "rest": 1 } + }, + { + "id": "aetheria-post-charmer", "vault": "aetheria", "era": "post-elysium", "name": "Lucan Vey", "temperament": "charmer", + "lenses": { "weighted": { "numen": 3, "veil": 3, "tangle": 3 }, "rest": 1 } + } + ] +} diff --git a/crates/ghostlight-dungeon/src/main.rs b/crates/ghostlight-dungeon/src/main.rs index f9539f1..aba17cd 100644 --- a/crates/ghostlight-dungeon/src/main.rs +++ b/crates/ghostlight-dungeon/src/main.rs @@ -7,6 +7,8 @@ mod heimdall; mod idunn_health; mod invite; mod page; +#[cfg(test)] +mod playtest; mod play; mod run_ahead; mod runtime; diff --git a/crates/ghostlight-dungeon/src/playtest.rs b/crates/ghostlight-dungeon/src/playtest.rs new file mode 100644 index 0000000..ed7cb32 --- /dev/null +++ b/crates/ghostlight-dungeon/src/playtest.rs @@ -0,0 +1,1141 @@ +//! Playtest harness: AI characters of set temperaments play the Dungeon's own +//! HTTP API in parallel worlds, and a model critic reads the result. +//! +//! The harness owns the plan, the characters' words and the reports. Every +//! world change goes through `service_router` exactly as the page's calls do: +//! `/api/begin`, `/api/turn`, `/api/play`, `/api/history`. Transcripts come from +//! `/api/history`; elaboration entries are diffs of the world snapshot; the +//! critic reports and gates nothing. Run it with `scripts/playtest-yggdrasil.sh`. + +use crate::{ + api::COOKIE_NAME, + begin::Scale, + catalog::Catalog, + heimdall::HeimdallClient, + runtime::{AppState, open_shared, service_router}, + state_layout::prepare_admitted_state_layout, + test_support::{CountingPort, ModelUsage, assemble}, + timelines::{Shared, Timelines}, + vaults::{SNAPSHOT_DIRECTORY, SnapshotVaults}, +}; +use anyhow::{Context, bail}; +use axum::{ + Router, + body::{Body, to_bytes}, + http::{Method, Request, StatusCode, header}, +}; +use chrono::Utc; +use ghostlight::{ + CommandId, InferenceEvent, InferencePort, InferenceRequest, Lens, VaultSnapshot, + production_eras, +}; +use model_connector::{InputItem, ToolDefinition}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use std::{ + collections::{BTreeMap, BTreeSet}, + io::Write, + path::{Path, PathBuf}, + sync::{Arc, Mutex as StdMutex}, + time::{Duration, Instant}, +}; +use tokio::sync::{Mutex, mpsc}; +use tower::ServiceExt; + +const PLAN_JSON: &str = include_str!("../playtest/plan.json"); +const HISTORY_IN_PROMPT: usize = 12; +const CRITIC_CHUNK: usize = 10; +const CRITIC_READS: usize = 10; +const NOTE_CHARS: usize = 6000; + +// ---------------------------------------------------------------- the plan + +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct Plan { + turns_per_character: u32, + wall_minutes: u64, + turn_timeout_minutes: u64, + character_model: String, + critic_model: String, + prices: BTreeMap, + temperaments: BTreeMap, + worlds: Vec, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct Price { + input: f64, + output: f64, + #[serde(default)] + cache_read: Option, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct Temperament { + goal: String, + manner: String, + pushes_on: String, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct WorldPlan { + id: String, + vault: String, + era: String, + name: String, + temperament: String, + /// Absent is the world's uniform lenses. + #[serde(default)] + lenses: Option, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct LensPlan { + weighted: BTreeMap, + rest: u32, +} + +impl WorldPlan { + /// The Begin body's lens map: the weighted lenses and every other lens at + /// `rest`. + fn lens_weights(&self) -> Option> { + let plan = self.lenses.as_ref()?; + Some(Lens::ALL.into_iter().map(|lens| (lens, plan.weighted.get(&lens).copied().unwrap_or(plan.rest))).collect()) + } + + fn lens_line(&self) -> String { + match &self.lenses { + None => "uniform".into(), + Some(plan) => { + let weighted: Vec = plan.weighted.iter().map(|(lens, weight)| format!("{} {weight}", lens.name())).collect(); + format!("{}, rest {}", weighted.join(" "), plan.rest) + } + } + } +} + +impl Plan { + pub(crate) fn checked_in() -> Plan { + serde_json::from_str(PLAN_JSON).expect("the checked-in plan parses") + } + + fn validate(&self) -> anyhow::Result<()> { + for world in &self.worlds { + if !self.temperaments.contains_key(&world.temperament) { + bail!("world {} names no temperament `{}`", world.id, world.temperament); + } + } + Ok(()) + } +} + +/// What a launch asks of the plan: the three knobs the operator sets. +#[derive(Clone, Debug)] +pub(crate) struct Options { + out: PathBuf, + turns: Option, + worlds: Option>, + wall_minutes: Option, + plan: Option, +} + +impl Options { + fn from_env() -> anyhow::Result { + let number = |name: &str| -> anyhow::Result> { + match std::env::var(name) { + Ok(text) if !text.trim().is_empty() => Ok(Some(text.trim().parse().with_context(|| format!("{name} is not a number"))?)), + _ => Ok(None), + } + }; + Ok(Self { + out: PathBuf::from(std::env::var("GHOSTLIGHT_PLAYTEST_OUT").context("GHOSTLIGHT_PLAYTEST_OUT is required")?), + turns: number("GHOSTLIGHT_PLAYTEST_TURNS")?.map(|value| value as u32), + worlds: std::env::var("GHOSTLIGHT_PLAYTEST_WORLDS") + .ok() + .filter(|text| !text.trim().is_empty()) + .map(|text| text.split(',').map(|id| id.trim().to_owned()).collect()), + wall_minutes: number("GHOSTLIGHT_PLAYTEST_WALL_MINUTES")?, + plan: std::env::var_os("GHOSTLIGHT_PLAYTEST_PLAN").map(PathBuf::from), + }) + } +} + +// -------------------------------------------------------- records and cost + +/// One history entry as `/api/history` gives it. +#[derive(Clone, Debug, Default, Deserialize, Serialize)] +struct Entry { + seq: u64, + #[serde(default)] + text: String, + #[serde(default)] + narration: Option, + #[serde(default)] + question: Option, + #[serde(default)] + refusal: Option, + #[serde(default)] + fault: Option, + #[serde(default)] + status: String, +} + +/// What a snapshot diff found, tagged with the history length it followed and +/// the player's place. +#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)] +struct Elaboration { + after_seq: u64, + place: Option, + added: Vec, + removed: Vec, +} + +#[derive(Clone, Debug, Default, Deserialize, Serialize)] +struct Slide { + #[serde(default)] + turn: u64, + #[serde(default)] + quote: String, + #[serde(default)] + kind: String, + #[serde(default)] + lore_says: String, + #[serde(default)] + note: String, + #[serde(default)] + severity: String, +} + +#[derive(Clone, Debug, Default, Deserialize, Serialize)] +struct Mechanic { + #[serde(default)] + turn: u64, + #[serde(default)] + kind: String, + #[serde(default)] + quote: String, + #[serde(default)] + note: String, +} + +#[derive(Clone, Debug, Default, Deserialize, Serialize)] +struct Verdict { + #[serde(default)] + slides: Vec, + #[serde(default)] + mechanics: Vec, +} + +fn dollars(plan: &Plan, usage: &BTreeMap) -> f64 { + usage + .iter() + .map(|(model, used)| { + let Some(price) = plan.prices.iter().find(|(family, _)| model.contains(family.as_str())).map(|(_, price)| price) else { + return 0.0; + }; + let fresh = used.prompt.saturating_sub(used.cached_prompt) as f64; + let cached = used.cached_prompt as f64; + (fresh * price.input + cached * price.cache_read.unwrap_or(price.input) + used.completion as f64 * price.output) / 1_000_000.0 + }) + .sum() +} + +fn tokens_line(usage: &BTreeMap) -> String { + usage + .iter() + .map(|(model, used)| format!("{model}: {} calls, {} in ({} cached), {} out", used.calls, used.prompt, used.cached_prompt, used.completion)) + .collect::>() + .join("; ") +} + +// ------------------------------------------------------------- the driver + +struct Client { + router: Router, + cookie: String, +} + +impl Client { + async fn call(&self, method: Method, uri: &str, body: Option) -> (StatusCode, Value) { + let request = Request::builder().method(method).uri(uri).header(header::COOKIE, format!("{COOKIE_NAME}={}", self.cookie)); + let request = match body { + Some(body) => request.header(header::CONTENT_TYPE, "application/json").body(Body::from(body.to_string())), + None => request.body(Body::empty()), + } + .expect("a request builds"); + let response = self.router.clone().oneshot(request).await.expect("the router is infallible"); + let status = response.status(); + let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap_or_default(); + (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null)) + } +} + +/// Everything one run shares. +struct Run { + plan: Plan, + turns: u32, + deadline: Instant, + root: PathBuf, + state: AppState, + router: Router, + global: Arc, + progress: StdMutex, + started: Instant, +} + +impl Run { + fn log(&self, line: &str) { + let stamp = Utc::now().format("%H:%M:%SZ"); + let _ = writeln!(self.progress.lock().unwrap(), "{stamp} {line}"); + } + + fn running_cost(&self) -> f64 { + dollars(&self.plan, &self.global.by_model()) + } +} + +struct WorldOutcome { + plan: WorldPlan, + turns_reached: u32, + faults: Vec, + seed_secs: Option, + slides: usize, + mechanics: usize, + own_cost: f64, +} + +#[derive(Default)] +struct WorldRecord { + faults: Vec, + seed_secs: Option, + turns_reached: u32, + elaboration: Vec, + sweeps_running_at_turn: Vec, + turn_secs: Vec<(u32, f64)>, +} + +async fn poll_seed(client: &Client, timeline: &str, started: Instant) -> Result { + loop { + let (status, body) = client.call(Method::GET, "/api/timelines", None).await; + if status != StatusCode::OK { + return Err(format!("timelines listing answered {status}")); + } + let row = body["timelines"].as_array().and_then(|rows| rows.iter().find(|row| row["timeline"] == timeline)); + match row.and_then(|row| row["status"].as_str()) { + Some("seeding") => {} + Some("failed") => return Err(format!("seed failed: {}", row.map(|row| row["reason"].to_string()).unwrap_or_default())), + Some(_) => return Ok(started.elapsed().as_secs_f64()), + None => return Err("the timeline is not in the listing".into()), + } + if started.elapsed() > Duration::from_secs(1800) { + return Err("seed still running after 30 minutes".into()); + } + tokio::time::sleep(Duration::from_secs(3)).await; + } +} + +async fn read_history(client: &Client, timeline: &str) -> Vec { + let mut all: Vec = Vec::new(); + let mut before: Option = None; + loop { + let uri = match before { + Some(before) => format!("/api/history/{timeline}?limit=100&before={before}"), + None => format!("/api/history/{timeline}?limit=100"), + }; + let (status, body) = client.call(Method::GET, &uri, None).await; + if status != StatusCode::OK { + break; + } + let page: Vec = serde_json::from_value(body["entries"].clone()).unwrap_or_default(); + let mut older = page; + older.append(&mut all); + all = older; + match body["older"].as_u64() { + Some(next) => before = Some(next), + None => break, + } + } + all +} + +/// A world's labels, as the diff reads them. +fn world_labels(world: &ghostlight::WorldSnapshot) -> BTreeSet { + let subjects = world.subjects.iter().map(|subject| format!("{:?}: {}", subject.kind, subject.label)); + let places = world.places.iter().map(|place| format!("place: {}", place.label)); + subjects.chain(places).collect() +} + +fn diff(before: &BTreeSet, now: &BTreeSet, after_seq: u64, place: Option) -> Elaboration { + Elaboration { + after_seq, + place, + added: now.difference(before).cloned().collect(), + removed: before.difference(now).cloned().collect(), + } +} + +/// The player's place, by the same position the live check reads: a position +/// is not public on the snapshot, so the subject's Debug text names it by the +/// place's entity id. +fn player_place(world: &ghostlight::WorldSnapshot) -> Option { + let player = world.subjects.iter().find(|subject| subject.human_controller.is_some())?; + let text = format!("{player:?}"); + world.places.iter().find(|place| text.contains(&format!("position: Some({:?})", place.id))).map(|place| place.label.clone()) +} + +/// One inference through the port, retried a few times on a fault. +async fn infer(port: &Arc, request: InferenceRequest) -> anyhow::Result { + let mut last = String::new(); + for attempt in 0..3u64 { + let prepared = match port.prepare(request.clone()) { + Ok(prepared) => prepared, + Err(fault) => bail!("the request could not be prepared: {fault}"), + }; + match port.infer(prepared).await { + Ok(output) => return Ok(output), + Err(fault) => { + last = fault.to_string(); + tokio::time::sleep(Duration::from_secs(5 * (attempt + 1))).await; + } + } + } + bail!("the connector faulted three times: {last}") +} + +fn tool(name: &str, description: &str, parameters: &str) -> ToolDefinition { + ToolDefinition { name: name.into(), description: description.into(), parameters_json: parameters.into() } +} + +fn transcript_for_prompt(entries: &[Entry]) -> String { + entries + .iter() + .map(|entry| { + let mut block = format!("You: {}", entry.text); + for (label, line) in [("Storyteller", &entry.narration), ("Storyteller asks", &entry.question), ("The world refused", &entry.refusal), ("Fault", &entry.fault)] { + if let Some(line) = line.as_deref().filter(|line| !line.is_empty()) { + block.push_str(&format!("\n{label}: {line}")); + } + } + block + }) + .collect::>() + .join("\n\n") +} + +const CHARACTER_INSTRUCTIONS: &str = "You are a person playing a text role-playing game, in character. \ +You see only what a player sees: the world's title, its era, and the story so far. Each turn you write \ +what your character says or does, in first person or as a short command, one to four sentences, then \ +call `act`. Play to your temperament: it is how you choose, not something to announce. Do not narrate \ +outcomes; the storyteller does that. When the storyteller asks you a question, answer it."; + +async fn character_action( + port: &Arc, + plan: &Plan, + world: &WorldPlan, + title: &str, + era_label: &str, + history: &[Entry], + question: Option<&str>, +) -> anyhow::Result<(String, String)> { + let card = &plan.temperaments[&world.temperament]; + let mut prompt = format!( + "You are {name}, a {temperament}.\nGoal: {goal}\nManner: {manner}\n\nWorld: {title}\nEra: {era_label}\n\n", + name = world.name, + temperament = world.temperament, + goal = card.goal, + manner = card.manner, + ); + if history.is_empty() { + prompt.push_str("The story has not begun. Write your first action."); + } else { + prompt.push_str(&format!("The story so far (last {} entries):\n\n{}", history.len(), transcript_for_prompt(history))); + } + if let Some(question) = question { + prompt.push_str(&format!("\n\nThe storyteller is waiting on an answer to: {question}\nYour text must answer it.")); + } + let act = tool( + "act", + "Say or do something as your character.", + r#"{"type":"object","properties":{"text":{"type":"string"},"intent":{"type":"string"}},"required":["text","intent"],"additionalProperties":false}"#, + ); + let request = InferenceRequest::play(CommandId::new(), 0, &plan.character_model, CHARACTER_INSTRUCTIONS, vec![InputItem::UserText { text: prompt }], vec![act], 1_200) + .map_err(|error| anyhow::anyhow!("{error}"))?; + let output = infer(port, request).await?; + let mut spoken = String::new(); + for event in output.events() { + match event { + InferenceEvent::ToolCall { name, arguments, .. } if name == "act" => { + let args: Value = serde_json::from_str(arguments).unwrap_or(Value::Null); + if let Some(text) = args["text"].as_str().filter(|text| !text.trim().is_empty()) { + return Ok((text.to_owned(), args["intent"].as_str().unwrap_or_default().to_owned())); + } + } + InferenceEvent::Text(text) => spoken.push_str(text), + _ => {} + } + } + if spoken.trim().is_empty() { + bail!("the character model returned no action"); + } + Ok((spoken.trim().to_owned(), String::new())) +} + +/// One character action through `/api/play`, then the wait for the turn to +/// close. `Ok(false)` is a turn that timed out: the world cannot go on. +async fn take_turn(run: &Run, client: &Client, timeline: &str, text: &str, token: Option<&str>, record: &mut WorldRecord, k: u32) -> bool { + let mut body = json!({"timeline": timeline, "key": uuid::Uuid::new_v4().to_string(), "text": text}); + if let Some(token) = token { + body["answers"] = json!(token); + } + let (status, reply) = client.call(Method::POST, "/api/play", Some(body)).await; + if !status.is_success() { + record.faults.push(format!("turn {k}: /api/play answered {status}: {reply}")); + return true; + } + let started = Instant::now(); + let limit = Duration::from_secs(run.plan.turn_timeout_minutes * 60); + loop { + tokio::time::sleep(Duration::from_secs(2)).await; + let (status, view) = client.call(Method::GET, &format!("/api/turn/{timeline}"), None).await; + if !status.is_success() { + record.faults.push(format!("turn {k}: /api/turn answered {status}")); + return true; + } + let turn = &view["turn"]; + match turn["state"].as_str() { + Some("closed") | Some("awaiting_player") => { + if let Some(fault) = turn["fault"].as_str() { + record.faults.push(format!("turn {k}: faulted: {fault}")); + } + return true; + } + _ => {} + } + if started.elapsed() > limit { + record.faults.push(format!("turn {k}: timed out after {} minutes", run.plan.turn_timeout_minutes)); + return false; + } + } +} + +async fn play_world(run: Arc, world: WorldPlan, cookie: String) -> WorldOutcome { + let dir = run.root.join(&world.id); + let _ = std::fs::create_dir_all(&dir); + let client = Client { router: run.router.clone(), cookie }; + let own = CountingPort::new(run.global.clone()); + let port: Arc = own.clone(); + let mut record = WorldRecord::default(); + let title = format!("{} playtest: {}", world.vault, world.temperament); + let mut timeline = String::new(); + let mut era_label = world.era.clone(); + let mut history: Vec = Vec::new(); + + let stage: anyhow::Result<()> = async { + let began = Instant::now(); + let mut body = json!({"key": uuid::Uuid::new_v4().to_string(), "title": title, "name": world.name, "vault": world.vault, "era": world.era}); + if let Some(weights) = world.lens_weights() { + body["lenses"] = serde_json::to_value(weights)?; + } + let (status, reply) = client.call(Method::POST, "/api/begin", Some(body)).await; + if !status.is_success() { + bail!("/api/begin answered {status}: {reply}"); + } + timeline = reply["timeline"].as_str().context("begin named no timeline")?.to_owned(); + run.log(&format!("{} begun as {timeline}; seeding", world.id)); + match poll_seed(&client, &timeline, began).await { + Ok(secs) => record.seed_secs = Some(secs), + Err(fault) => bail!("{fault}"), + } + let host = run.state.timelines.host(&timeline).await?; + let mut seen = world_labels(&host.world.snapshot().await.context("the world could not be read")?); + if let Ok(world_now) = host.world.snapshot().await { + if let Some(era) = &world_now.era { + era_label = era.label.clone(); + } + record.elaboration.push(diff(&BTreeSet::new(), &seen, 0, player_place(&world_now))); + } + + for k in 1..=run.turns { + if Instant::now() >= run.deadline { + record.faults.push(format!("wall time reached before turn {k}")); + break; + } + let turn_started = Instant::now(); + if host.sweeping.try_lock().is_err() { + record.sweeps_running_at_turn.push(k); + } + let (_, view) = client.call(Method::GET, &format!("/api/turn/{timeline}"), None).await; + let open = (view["turn"]["state"] == "awaiting_player").then(|| (view["turn"]["question"]["text"].as_str().unwrap_or_default().to_owned(), view["turn"]["question"]["token"].as_str().map(str::to_owned))); + let (_, hist) = client.call(Method::GET, &format!("/api/history/{timeline}?limit={HISTORY_IN_PROMPT}"), None).await; + history = serde_json::from_value(hist["entries"].clone()).unwrap_or_default(); + let (text, _intent) = match character_action(&port, &run.plan, &world, &title, &era_label, &history, open.as_ref().map(|(text, _)| text.as_str())).await { + Ok(action) => action, + Err(error) => { + record.faults.push(format!("turn {k}: the character could not act: {error}")); + break; + } + }; + let token = open.as_ref().and_then(|(_, token)| token.clone()); + let alive = take_turn(&run, &client, &timeline, &text, token.as_deref(), &mut record, k).await; + record.turns_reached = k; + record.turn_secs.push((k, turn_started.elapsed().as_secs_f64())); + let after_seq = read_history(&client, &timeline).await.last().map_or(0, |entry| entry.seq); + if let Ok(now) = host.world.snapshot().await { + let labels = world_labels(&now); + record.elaboration.push(diff(&seen, &labels, after_seq, player_place(&now))); + seen = labels; + } + let usage = run.global.totals(); + run.log(&format!( + "{} turn {k}/{} {:.0}s tokens {} in {} out running ${:.2}", + world.id, + run.turns, + turn_started.elapsed().as_secs_f64(), + usage.prompt, + usage.completion, + run.running_cost() + )); + if !alive { + break; + } + } + // Let the last run-ahead sweep land, so its additions are in the log. + let waiting = Instant::now(); + while host.sweeping.try_lock().is_err() && waiting.elapsed() < Duration::from_secs(180) { + tokio::time::sleep(Duration::from_secs(3)).await; + } + let after_seq = read_history(&client, &timeline).await.last().map_or(0, |entry| entry.seq); + if let Ok(now) = host.world.snapshot().await { + let labels = world_labels(&now); + let tail = diff(&seen, &labels, after_seq, player_place(&now)); + if !tail.added.is_empty() || !tail.removed.is_empty() { + record.elaboration.push(tail); + } + } + Ok(()) + } + .await; + if let Err(error) = stage { + record.faults.push(format!("{error:#}")); + } + run.log(&format!("{} played {} turns, {} faults; critic next", world.id, record.turns_reached, record.faults.len())); + + let entries = if timeline.is_empty() { Vec::new() } else { read_history(&client, &timeline).await }; + let elaboration_jsonl: String = record.elaboration.iter().map(|entry| serde_json::to_string(entry).unwrap() + "\n").collect(); + let _ = std::fs::write(dir.join("elaboration.jsonl"), elaboration_jsonl); + let _ = std::fs::write(dir.join("transcript.md"), render_transcript(&entries)); + + let notebook = NoteBook::open(&run.root.join("state").join(SNAPSHOT_DIRECTORY), &world); + let mut verdict = Verdict::default(); + let mut critic_errors: Vec = Vec::new(); + match ¬ebook { + Err(error) => critic_errors.push(format!("the critic has no lore: {error:#}")), + Ok(book) => { + for chunk in entries.chunks(CRITIC_CHUNK) { + let (lo, hi) = (chunk[0].seq, chunk[chunk.len() - 1].seq); + let elab: Vec<&Elaboration> = record.elaboration.iter().filter(|each| each.after_seq + 1 >= lo && each.after_seq <= hi).collect(); + match critique(&port, &run.plan, book, &era_label, chunk, &elab).await { + Ok(found) => { + verdict.slides.extend(found.slides); + verdict.mechanics.extend(found.mechanics); + } + Err(error) => critic_errors.push(format!("turns {lo}-{hi}: {error:#}")), + } + } + } + } + let _ = std::fs::write(dir.join("critic.json"), serde_json::to_string_pretty(&json!({"slides": verdict.slides, "mechanics": verdict.mechanics, "errors": critic_errors})).unwrap()); + let own_cost = dollars(&run.plan, &own.by_model()); + let report = render_report(&ReportInput { + plan: &run.plan, + world: &world, + timeline: &timeline, + era_label: &era_label, + entries: &entries, + verdict: &verdict, + critic_errors: &critic_errors, + record: &record, + own_usage: own.by_model(), + own_cost, + }); + let _ = std::fs::write(dir.join("report.md"), report); + WorldOutcome { + plan: world, + turns_reached: record.turns_reached, + faults: record.faults, + seed_secs: record.seed_secs, + slides: verdict.slides.len(), + mechanics: verdict.mechanics.len(), + own_cost, + } +} + +// --------------------------------------------------------------- the critic + +#[derive(Deserialize)] +struct SnapDoc { + notes: Vec, +} + +#[derive(Deserialize)] +struct SnapNote { + reference: String, + title: String, + #[serde(default)] + aliases: Vec, + body: String, +} + +/// The world's own evidence for its era, read by title: the imported snapshot +/// with the era's withheld paths removed. Lookup only; it judges nothing. +struct NoteBook { + notes: Vec, + premise: String, +} + +impl NoteBook { + fn open(store: &Path, world: &WorldPlan) -> anyhow::Result { + let id = VaultSnapshot::current_id(store, &world.vault).map_err(|error| anyhow::anyhow!("{error}"))?; + let snapshot = VaultSnapshot::load(store, &id).map_err(|error| anyhow::anyhow!("{error}"))?; + let premise = snapshot.premise().unwrap_or_default(); + let doc: SnapDoc = rmp_serde::from_slice(&snapshot.to_bytes()).context("the snapshot did not decode")?; + let withheld: Vec<&str> = production_eras(&world.vault) + .and_then(|(eras, _)| eras.iter().find(|era| era.id == world.era)) + .map(|era| era.withhold.to_vec()) + .unwrap_or_default(); + let notes = doc + .notes + .into_iter() + .filter(|note| !withheld.iter().any(|path| note.reference == *path || note.reference.starts_with(&format!("{path}/")))) + .collect(); + Ok(Self { notes, premise }) + } + + fn read(&self, referent: &str) -> String { + let key = referent.trim().to_lowercase(); + let stem = |note: &SnapNote| Path::new(¬e.reference).file_stem().map(|stem| stem.to_string_lossy().to_lowercase()).unwrap_or_default(); + let exact = self + .notes + .iter() + .filter(|note| stem(note) == key || note.title.trim().to_lowercase() == key || note.aliases.iter().any(|alias| alias.trim().to_lowercase() == key)) + .min_by_key(|note| note.reference.len()); + let found = exact.or_else(|| { + let tokens: Vec<&str> = key.split_whitespace().filter(|token| token.len() > 2).collect(); + self.notes + .iter() + .map(|note| { + let (title, body) = (note.title.to_lowercase(), note.body.to_lowercase()); + let score: usize = tokens.iter().map(|token| usize::from(title.contains(token)) * 4 + body.matches(token).count().min(8)).sum(); + (score, note) + }) + .filter(|(score, _)| *score > 0) + .max_by_key(|(score, note)| (*score, std::cmp::Reverse(note.reference.len()))) + .map(|(_, note)| note) + }); + match found { + Some(note) => format!("{}\n\n{}", note.reference, note.body.chars().take(NOTE_CHARS).collect::()), + None => format!("No note in this world's lore answers `{referent}`."), + } + } +} + +const CRITIC_INSTRUCTIONS: &str = "You are a lore critic reading a stretch of a play-through of a text role-playing \ +game whose world was built from a lore vault. You report; you never decide anything. Find the places where the \ +storyteller's narration or the world's additions slide off the lore: era_mix (something from a different era of the \ +setting), contradicts_lore (the vault says otherwise), genre_drift (the tone or genre leaves the setting's), \ +unsupported_invention (a specific fact or name the lore gives no ground for, presented as established). Check suspicions \ +against the lore with `read_note` before you flag them; the notes you can read are the only lore this world has, so an \ +absent note is itself evidence. Also report mechanics: npc_softness (an NPC who should push back or hold a grudge folds), \ +no_pushback (the player's act met no resistance or consequence it should have), narrator_refusal (the storyteller \ +declines the player's act, in fiction or on content grounds). Quote the exact words, and cite the turn number. Report \ +nothing you cannot quote. Call `report` once, with empty lists if nothing is wrong."; + +async fn critique(port: &Arc, plan: &Plan, book: &NoteBook, era_label: &str, chunk: &[Entry], elaboration: &[&Elaboration]) -> anyhow::Result { + let mut prompt = format!("Era: {era_label}\n\nVault premise:\n{}\n\nTranscript (turn numbers are the bracketed seq):\n\n", book.premise); + for entry in chunk { + prompt.push_str(&format!("[{}] Player: {}\n", entry.seq, entry.text)); + for (label, line) in [("Storyteller", &entry.narration), ("Question", &entry.question), ("Refused", &entry.refusal), ("Fault", &entry.fault)] { + if let Some(line) = line.as_deref().filter(|line| !line.is_empty()) { + prompt.push_str(&format!("[{}] {label}: {line}\n", entry.seq)); + } + } + prompt.push('\n'); + } + if !elaboration.is_empty() { + prompt.push_str("What the world gained (elaborators), by the turn it followed:\n"); + for each in elaboration { + let added: Vec<&String> = each.added.iter().take(60).collect(); + prompt.push_str(&format!("after [{}] at {}: {}\n", each.after_seq, each.place.as_deref().unwrap_or("?"), added.iter().map(|label| label.as_str()).collect::>().join("; "))); + } + } + let read_note = tool("read_note", "Read one note of this world's lore by title, alias or filename.", r#"{"type":"object","properties":{"referent":{"type":"string"}},"required":["referent"],"additionalProperties":false}"#); + let report = tool( + "report", + "Report your findings for this stretch.", + r#"{"type":"object","properties":{ +"slides":{"type":"array","items":{"type":"object","properties":{"turn":{"type":"integer"},"quote":{"type":"string"},"kind":{"type":"string","enum":["era_mix","contradicts_lore","genre_drift","unsupported_invention"]},"lore_says":{"type":"string"},"note":{"type":"string"},"severity":{"type":"string","enum":["low","medium","high"]}},"required":["turn","quote","kind","lore_says","note","severity"],"additionalProperties":false}}, +"mechanics":{"type":"array","items":{"type":"object","properties":{"turn":{"type":"integer"},"kind":{"type":"string","enum":["npc_softness","no_pushback","narrator_refusal"]},"quote":{"type":"string"},"note":{"type":"string"}},"required":["turn","kind","quote","note"],"additionalProperties":false}} +},"required":["slides","mechanics"],"additionalProperties":false}"#, + ); + let mut conversation = vec![InputItem::UserText { text: prompt }]; + let mut reads = 0usize; + for round in 0..(CRITIC_READS + 3) { + let tools = if reads < CRITIC_READS { vec![read_note.clone(), report.clone()] } else { vec![report.clone()] }; + let request = InferenceRequest::play(CommandId::new(), round, &plan.critic_model, CRITIC_INSTRUCTIONS, conversation.clone(), tools, 6_000).map_err(|error| anyhow::anyhow!("{error}"))?; + let output = infer(port, request).await?; + let mut asked = false; + for event in output.events() { + match event { + InferenceEvent::Text(text) if !text.is_empty() => conversation.push(InputItem::AssistantText { text: text.clone() }), + InferenceEvent::ToolCall { call_id, name, arguments } if name == "report" => { + let _ = call_id; + return serde_json::from_str(arguments).context("the critic's report did not parse"); + } + InferenceEvent::ToolCall { call_id, name, arguments } => { + asked = true; + reads += 1; + let referent = serde_json::from_str::(arguments).ok().and_then(|args| args["referent"].as_str().map(str::to_owned)).unwrap_or_default(); + let result = if name == "read_note" { book.read(&referent) } else { format!("no tool named {name}") }; + conversation.push(InputItem::ToolCall { call_id: call_id.clone(), name: name.clone(), arguments: arguments.clone() }); + conversation.push(InputItem::ToolResult { call_id: call_id.clone(), output: result }); + } + _ => {} + } + } + if !asked { + bail!("the critic ended without a report"); + } + } + bail!("the critic never reported") +} + +// ------------------------------------------------------------ the renderers + +fn render_transcript(entries: &[Entry]) -> String { + let mut text = String::new(); + for entry in entries { + text.push_str(&format!("### [{}] {}\n\n**Player:** {}\n\n", entry.seq, entry.status, entry.text)); + for (label, line) in [("Storyteller", &entry.narration), ("Storyteller asks", &entry.question), ("Refused", &entry.refusal), ("Fault", &entry.fault)] { + if let Some(line) = line.as_deref().filter(|line| !line.is_empty()) { + text.push_str(&format!("**{label}:** {line}\n\n")); + } + } + } + text +} + +struct ReportInput<'a> { + plan: &'a Plan, + world: &'a WorldPlan, + timeline: &'a str, + era_label: &'a str, + entries: &'a [Entry], + verdict: &'a Verdict, + critic_errors: &'a [String], + record: &'a WorldRecord, + own_usage: BTreeMap, + own_cost: f64, +} + +fn quote_block(text: &str) -> String { + text.lines().map(|line| format!("> {line}")).collect::>().join("\n") +} + +fn render_report(input: &ReportInput) -> String { + let (plan, world) = (input.plan, input.world); + let card = &plan.temperaments[&world.temperament]; + let mut out = format!( + "# {} ({})\n\n- Vault: {}\n- Era: {} ({})\n- Lenses: {}\n- Temperament: {}, played as {}. Goal: {} Pushes on: {}\n- Timeline: {}\n- Turns reached: {}\n- Seed: {}\n- Character and critic cost: ${:.2} ({})\n", + world.id, + world.temperament, + world.vault, + input.era_label, + world.era, + world.lens_line(), + world.temperament, + world.name, + card.goal, + card.pushes_on, + input.timeline, + input.record.turns_reached, + input.record.seed_secs.map_or("did not finish".into(), |secs| format!("{secs:.0}s")), + input.own_cost, + tokens_line(&input.own_usage), + ); + if !input.record.sweeps_running_at_turn.is_empty() { + out.push_str(&format!("- Run-ahead sweep still running at the start of turns: {:?}\n", input.record.sweeps_running_at_turn)); + } + if !input.record.turn_secs.is_empty() { + out.push_str(&format!("- Seconds per turn: {}\n", input.record.turn_secs.iter().map(|(k, secs)| format!("{k}: {secs:.0}")).collect::>().join(", "))); + } + if !input.record.faults.is_empty() { + out.push_str("\n## Faults\n\n"); + for fault in &input.record.faults { + out.push_str(&format!("- {fault}\n")); + } + } + if !input.critic_errors.is_empty() { + out.push_str("\n## Critic errors\n\n"); + for error in input.critic_errors { + out.push_str(&format!("- {error}\n")); + } + } + out.push_str("\n## Transcript\n\nFlags are the critic's reading, for the operator to rule on; none of them gated anything.\n\n"); + for entry in input.entries { + out.push_str(&format!("### [{}] {}\n\n**Player:** {}\n\n", entry.seq, entry.status, entry.text)); + for (label, line) in [("Storyteller", &entry.narration), ("Storyteller asks", &entry.question), ("Refused", &entry.refusal), ("Fault", &entry.fault)] { + if let Some(line) = line.as_deref().filter(|line| !line.is_empty()) { + out.push_str(&format!("**{label}:** {line}\n\n")); + } + } + for slide in input.verdict.slides.iter().filter(|slide| slide.turn == entry.seq) { + out.push_str(&format!( + "> **Off-lore ({}, {}).** Quote: \"{}\"\n> Lore says: {}\n> {}\n\n", + slide.kind, slide.severity, slide.quote, slide.lore_says, slide.note + )); + } + for mechanic in input.verdict.mechanics.iter().filter(|mechanic| mechanic.turn == entry.seq) { + out.push_str(&format!("> **Mechanics ({}).** Quote: \"{}\"\n> {}\n\n", mechanic.kind, mechanic.quote, mechanic.note)); + } + } + let stray: Vec<&Slide> = input.verdict.slides.iter().filter(|slide| !input.entries.iter().any(|entry| entry.seq == slide.turn)).collect(); + if !stray.is_empty() { + out.push_str("### Flags naming no turn in this transcript\n\n"); + for slide in stray { + out.push_str(&format!("> **Off-lore ({}, turn {}).** \"{}\" {}\n\n", slide.kind, slide.turn, slide.quote, slide.note)); + } + } + out.push_str("## Elaboration timeline\n\nWhat the world gained, grouped by the turn it followed and the player's place then.\n\n"); + let mut by_turn: BTreeMap> = BTreeMap::new(); + for each in &input.record.elaboration { + by_turn.entry(each.after_seq).or_default().push(each); + } + for (turn, group) in by_turn { + out.push_str(&format!("### After turn {}\n\n", if turn == 0 { "0 (the seed)".to_owned() } else { turn.to_string() })); + let mut by_place: BTreeMap> = BTreeMap::new(); + for each in group { + by_place.entry(each.place.clone().unwrap_or_else(|| "unplaced".into())).or_default().push(each); + } + for (place, group) in by_place { + out.push_str(&format!("At {place}:\n")); + for each in group { + for added in &each.added { + out.push_str(&format!("- added {added}\n")); + } + for removed in &each.removed { + out.push_str(&format!("- removed {removed}\n")); + } + } + out.push('\n'); + } + } + out +} + +fn render_index(plan: &Plan, outcomes: &[WorldOutcome], total: &BTreeMap, wall: Duration) -> String { + let mut out = format!("# Playtest index\n\nWall time: {:.0} minutes. Total cost: ${:.2}. Usage: {}\n\n| World | Character | Turns | Faults | Seed s | Slides | Mechanics | Char+critic $ |\n|---|---|---|---|---|---|---|---|\n", wall.as_secs_f64() / 60.0, dollars(plan, total), tokens_line(total)); + for each in outcomes { + out.push_str(&format!( + "| [{id}]({id}/report.md) | {name} ({temperament}) | {turns} | {faults} | {seed} | {slides} | {mechanics} | {cost:.2} |\n", + id = each.plan.id, + name = each.plan.name, + temperament = each.plan.temperament, + turns = each.turns_reached, + faults = each.faults.len(), + seed = each.seed_secs.map_or("-".into(), |secs| format!("{secs:.0}")), + slides = each.slides, + mechanics = each.mechanics, + cost = each.own_cost, + )); + } + out +} + +// -------------------------------------------------------------- the launch + +/// Plays the selected worlds in parallel, writes every report and the index, +/// and returns the dated output directory. +pub(crate) async fn run(options: Options) -> anyhow::Result { + let mut plan = match &options.plan { + Some(path) => serde_json::from_slice(&std::fs::read(path)?).context("the plan file did not parse")?, + None => Plan::checked_in(), + }; + plan.validate()?; + if let Some(ids) = &options.worlds { + for id in ids { + if !plan.worlds.iter().any(|world| &world.id == id) { + bail!("the plan has no world `{id}`"); + } + } + plan.worlds.retain(|world| ids.contains(&world.id)); + } + let turns = options.turns.unwrap_or(plan.turns_per_character); + let wall = Duration::from_secs(options.wall_minutes.unwrap_or(plan.wall_minutes) * 60); + let root = options.out.join(Utc::now().format("%Y-%m-%dT%H%MZ").to_string()); + std::fs::create_dir_all(root.join("state"))?; + let root = std::fs::canonicalize(&root)?; + let state_root = root.join("state"); + prepare_admitted_state_layout(&state_root)?; + let vaults: BTreeSet<&str> = plan.worlds.iter().map(|world| world.vault.as_str()).collect(); + for vault in vaults { + println!("import {}", crate::vaults::import(&state_root, vault)?); + } + + let shared = open_shared()?; + let global = CountingPort::new(shared.inference.clone()); + let shared = Shared { inference: global.clone(), ..shared }; + let (fatal, _fatal_events) = mpsc::unbounded_channel(); + let timelines = Arc::new(Timelines::new(state_root.clone(), shared, fatal)); + let catalog = Arc::new(Mutex::new(Catalog::open(state_root.join("catalog.cc"))?)); + let accounts: Vec = plan.worlds.iter().map(|world| format!("playtest-{}", world.id)).collect(); + let account_refs: Vec<&str> = accounts.iter().map(String::as_str).collect(); + let (state, cookies, _assembled_fatal) = assemble( + &state_root, + catalog, + timelines, + Arc::new(Scale::from_env()), + Arc::new(SnapshotVaults::new(&state_root)), + Arc::new(HeimdallClient::fixture()), + &account_refs, + ); + let router = service_router(state.clone()); + let run = Arc::new(Run { + plan: plan.clone(), + turns, + deadline: Instant::now() + wall, + root: root.clone(), + state, + router, + global, + progress: StdMutex::new(std::fs::File::create(root.join("progress.log"))?), + started: Instant::now(), + }); + run.log(&format!("playtest starts: {} worlds, {turns} turns each, {} minutes", plan.worlds.len(), wall.as_secs() / 60)); + println!("playtest output: {}", root.display()); + let mut handles = Vec::new(); + for (world, cookie) in plan.worlds.iter().cloned().zip(cookies) { + handles.push(tokio::spawn(play_world(run.clone(), world, cookie))); + } + let mut outcomes = Vec::new(); + for handle in handles { + match handle.await { + Ok(outcome) => outcomes.push(outcome), + Err(error) => run.log(&format!("a world task died: {error}")), + } + } + std::fs::write(root.join("index.md"), render_index(&plan, &outcomes, &run.global.by_model(), run.started.elapsed()))?; + run.log(&format!("playtest done: ${:.2}", run.running_cost())); + Ok(root) +} + +/// Live: spends connector credit. Run through `scripts/playtest-yggdrasil.sh`, +/// which loads the connector key and sets the environment this reads. The +/// test fails only when the harness cannot run: no connector, no snapshot. +#[tokio::test(flavor = "multi_thread", worker_threads = 8)] +#[ignore = "live: spends connector credit; run through scripts/playtest-yggdrasil.sh on Yggdrasil"] +async fn live_playtest() { + let options = Options::from_env().expect("the playtest environment"); + let root = run(options).await.expect("the harness runs"); + println!("PLAYTEST REPORTS {}", root.display()); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_checked_in_plan_is_the_rulings_matrix() { + let plan = Plan::checked_in(); + plan.validate().unwrap(); + assert_eq!(plan.worlds.len(), 8); + assert_eq!(plan.turns_per_character, 12); + let of = |vault: &str, era: &str| -> Vec<&str> { + plan.worlds.iter().filter(|world| world.vault == vault && world.era == era).map(|world| world.temperament.as_str()).collect() + }; + assert_eq!(of("delvehold", "present"), ["diplomat", "murderhobo", "grifter"]); + assert_eq!(of("aetheria", "pre-elysium"), ["schemer", "devout", "provocateur"]); + assert_eq!(of("aetheria", "post-elysium"), ["wanderer", "charmer"]); + let pre = plan.worlds.iter().find(|world| world.id == "aetheria-pre-schemer").unwrap().lens_weights().unwrap(); + assert_eq!(pre[&Lens::Charter], 3); + assert_eq!(pre[&Lens::Ledger], 1, "the rest stay alive at one"); + let post = plan.worlds.iter().find(|world| world.id == "aetheria-post-charmer").unwrap().lens_weights().unwrap(); + assert_eq!((post[&Lens::Numen], post[&Lens::Veil], post[&Lens::Tangle], post[&Lens::Charter]), (3, 3, 3, 1)); + assert!(plan.worlds.iter().find(|world| world.vault == "delvehold").unwrap().lens_weights().is_none(), "Delvehold runs the uniform default"); + for (vault, era) in plan.worlds.iter().map(|world| (world.vault.as_str(), world.era.as_str())) { + assert!(production_eras(vault).unwrap().0.iter().any(|candidate| candidate.id == era), "{vault} has era {era}"); + } + } + + #[test] + fn an_unknown_plan_field_is_refused() { + let mut plan: Value = serde_json::from_str(PLAN_JSON).unwrap(); + plan["surprise"] = json!(1); + assert!(serde_json::from_value::(plan).is_err()); + } + + #[test] + fn a_critic_slide_lands_under_its_turn_and_gates_nothing() { + let plan = Plan::checked_in(); + let world = plan.worlds[0].clone(); + let entries: Vec = (1..=3) + .map(|seq| Entry { seq, text: format!("act {seq}"), narration: Some(format!("narration {seq}")), status: "committed".into(), ..Entry::default() }) + .collect(); + let verdict = Verdict { + slides: vec![Slide { turn: 2, quote: "a laser rifle".into(), kind: "era_mix".into(), lore_says: "no lasers".into(), note: "wrong era".into(), severity: "high".into() }], + mechanics: vec![Mechanic { turn: 3, kind: "no_pushback".into(), quote: "the guard shrugs".into(), note: "none".into() }], + }; + let record = WorldRecord { + elaboration: vec![Elaboration { after_seq: 2, place: Some("The Gate".into()), added: vec!["Person: Brann".into()], removed: vec![] }], + ..WorldRecord::default() + }; + let text = render_report(&ReportInput { + plan: &plan, + world: &world, + timeline: "timeline:x", + era_label: "The Greathold now", + entries: &entries, + verdict: &verdict, + critic_errors: &[], + record: &record, + own_usage: BTreeMap::new(), + own_cost: 0.0, + }); + let (two, three) = (text.find("### [2]").unwrap(), text.find("### [3]").unwrap()); + let flag = text.find("Off-lore (era_mix, high)").unwrap(); + assert!(two < flag && flag < three, "the slide sits under turn 2"); + assert!(text.find("Mechanics (no_pushback)").unwrap() > three); + assert!(text.contains("### After turn 2") && text.contains("At The Gate:") && text.contains("- added Person: Brann")); + } + + #[test] + fn a_diff_names_what_the_world_gained_and_lost() { + let before: BTreeSet = ["place: Gate", "Person: Old"].map(String::from).into(); + let now: BTreeSet = ["place: Gate", "Person: New"].map(String::from).into(); + let found = diff(&before, &now, 4, Some("Gate".into())); + assert_eq!((found.added, found.removed), (vec!["Person: New".to_owned()], vec!["Person: Old".to_owned()])); + } + + #[test] + fn cost_reads_reported_usage_at_the_plan_prices() { + let plan = Plan::checked_in(); + let mut usage = BTreeMap::new(); + usage.insert("claude-opus-5-5".to_owned(), ModelUsage { calls: 1, prompt: 1_000_000, cached_prompt: 500_000, completion: 100_000 }); + // 0.5M fresh at 4 + 0.5M cached at 0.2 + 0.1M out at 20. + assert!((dollars(&plan, &usage) - (2.0 + 0.1 + 2.0)).abs() < 1e-9); + } + + #[test] + fn a_note_is_read_by_title_and_a_missing_one_says_so() { + let book = NoteBook { + premise: String::new(), + notes: vec![SnapNote { reference: "Places/Low Sere.md".into(), title: "Low Sere".into(), aliases: vec!["the Sere".into()], body: "A drowned market.".into() }], + }; + assert!(book.read("the sere").contains("A drowned market.")); + assert!(book.read("zzzz").starts_with("No note")); + } +}