diff --git a/crates/ghostlight-dungeon/src/playtest.rs b/crates/ghostlight-dungeon/src/playtest.rs index 418d357..a7d0897 100644 --- a/crates/ghostlight-dungeon/src/playtest.rs +++ b/crates/ghostlight-dungeon/src/playtest.rs @@ -42,6 +42,10 @@ use std::{ use tokio::sync::{Mutex, mpsc}; use tower::ServiceExt; +// A sibling file, not a subdirectory: two api tests read every entry of src/ as a file. +#[path = "playtest_atlas.rs"] +mod atlas; + const PLAN_JSON: &str = include_str!("../playtest/plan.json"); const HISTORY_IN_PROMPT: usize = 12; const CRITIC_CHUNK: usize = 10; @@ -1152,6 +1156,56 @@ fn render_index(plan: &Plan, outcomes: &[WorldOutcome], total: &BTreeMap, + pub(super) state: AppState, + pub(super) router: Router, + pub(super) cookies: Vec, + /// What each vault import reported, one line per profile. + pub(super) imports: Vec, +} + +/// Opens a run's state under `root/state`: imports `vaults`, counts every +/// inference the lanes make, and signs in one session per account. `wrap` +/// decorates the counted port before the lanes see it. +pub(super) fn open_harness( + root: &Path, + vaults: &[&str], + scale: Scale, + accounts: &[String], + wrap: impl FnOnce(Arc) -> Arc, +) -> anyhow::Result { + let state_root = root.join("state"); + std::fs::create_dir_all(&state_root)?; + prepare_admitted_state_layout(&state_root)?; + let mut imports = Vec::new(); + for vault in vaults { + let line = crate::vaults::import(&state_root, vault)?; + println!("import {line}"); + imports.push(line); + } + let shared = open_shared()?; + let global = CountingPort::new(shared.inference.clone()); + let shared = Shared { inference: wrap(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 account_refs: Vec<&str> = accounts.iter().map(String::as_str).collect(); + let (state, cookies, _assembled_fatal) = assemble( + &state_root, + catalog, + timelines, + Arc::new(scale), + Arc::new(SnapshotVaults::new(&state_root)), + Arc::new(HeimdallClient::fixture()), + &account_refs, + ); + let router = service_router(state.clone()); + Ok(Harness { global, state, router, cookies, imports }) +} + 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")?, @@ -1170,33 +1224,12 @@ pub(crate) async fn run(options: Options) -> anyhow::Result { let wall = Duration::from_secs(options.wall_minutes.unwrap_or(plan.wall_minutes) * 60); let stamp = options.stamp.clone().unwrap_or_else(|| Utc::now().format("%Y-%m-%dT%H%MZ").to_string()); let root = options.out.join(stamp); - std::fs::create_dir_all(root.join("state"))?; + std::fs::create_dir_all(&root)?; 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 vaults: BTreeSet<&str> = plan.worlds.iter().map(|world| world.vault.as_str()).collect(); + let vaults: Vec<&str> = vaults.into_iter().collect(); + let Harness { global, state, router, cookies, .. } = open_harness(&root, &vaults, Scale::from_env(), &accounts, |port| port)?; let run = Arc::new(Run { plan: plan.clone(), turns, diff --git a/crates/ghostlight-dungeon/src/playtest_atlas.rs b/crates/ghostlight-dungeon/src/playtest_atlas.rs new file mode 100644 index 0000000..d1f8272 --- /dev/null +++ b/crates/ghostlight-dungeon/src/playtest_atlas.rs @@ -0,0 +1,1432 @@ +//! The atlas run: one world, no player, elaboration sweeps across the whole of +//! it, then a Markdown atlas rendered from the final kernel state. +//! +//! Ruling multiresolution-gestalt names the true fractal (Gestalt turns from +//! the world down to the player's room) as unbuilt; this is the closest +//! approximation the existing machinery allows: the Active elaborator, swept +//! over every open boundary and scale deficit rather than the player's +//! vicinity. Nothing here decides a world change. Every change is the +//! elaborator's, admitted by the kernel; this module only seeds through Begin, +//! sweeps, watches, and reads. +//! +//! The atlas reads the public omniscient surface, `table_view`, because the +//! snapshot's routes, facts, commitments and offices are crate-private to the +//! kernel. The parser here is a reader of that text and renders what it cannot +//! parse verbatim rather than dropping it. Run it with +//! `scripts/playtest-yggdrasil.sh --atlas`. + +use super::{Client, Harness, Plan, dollars, open_harness, poll_seed}; +use crate::{begin::Scale, run_ahead::evidence_of}; +use anyhow::{Context, bail}; +use axum::http::Method; +use chrono::Utc; +use ghostlight::{ + EvidenceError, EvidenceQuery, EvidenceReceipt, EvidenceSource, InferenceFault, InferenceOutput, InferencePort, + InferenceRequest, Lens, PreparedInference, SubjectKind, WorldSnapshot, table_view, +}; +use serde_json::json; +use std::{ + collections::{BTreeMap, BTreeSet}, + io::Write, + path::PathBuf, + sync::{ + Arc, Mutex as StdMutex, + atomic::{AtomicUsize, Ordering}, + }, + time::{Duration, Instant}, +}; +use tokio::sync::Semaphore; + +/// The snapshot id the live server's re-import of the Zyphos vault at Zyphos +/// main 49207ef produced. A run that imports another reports it. +const EXPECTED_ZYPHOS_SNAPSHOT: &str = "62b087811a62a1cbeb641743f4cf0a13254dbda1244399273db9ae9cd5f58094"; +/// An entry counts as the work of the lenses whose requests ended within this +/// long before the last read: sessions commit as their last round returns. +const LENS_WINDOW: Duration = Duration::from_millis(2500); +const POLL_EVERY: Duration = Duration::from_secs(1); +/// Sweeps in a row that commit nothing before the run stops: what is left is +/// refused or unanswerable, not undone. +const STALL_SWEEPS: u32 = 3; +/// Times the run asks Begin to seed the one key before it gives up. +const SEED_ATTEMPTS: u32 = 4; + +// ------------------------------------------------------------- the options + +/// What a launch asks of the atlas run. Every number is a parameter. +#[derive(Clone, Debug)] +pub(super) struct AtlasOptions { + out: PathBuf, + stamp: Option, + vault: String, + era: String, + persons: u32, + institutions: u32, + populations: u32, + /// Sweeps at most; each sweep starts up to `sweep_sessions` sessions. + sweeps: u32, + sweep_sessions: usize, + seed_sessions: usize, + cost_cap: f64, + /// Concurrent connector calls, for Begin's seed and every sweep. + concurrency: usize, +} + +impl AtlasOptions { + fn from_reader(read: impl Fn(&str) -> Option) -> anyhow::Result { + fn number(read: &impl Fn(&str) -> Option, name: &str, default: T) -> anyhow::Result { + match read(name).filter(|text| !text.trim().is_empty()) { + Some(text) => text.trim().parse().map_err(|_| anyhow::anyhow!("{name} is not a number")), + None => Ok(default), + } + } + let text = |name: &str, default: &str| read(name).filter(|text| !text.trim().is_empty()).unwrap_or_else(|| default.to_owned()); + Ok(Self { + out: PathBuf::from(read("GHOSTLIGHT_ATLAS_OUT").or_else(|| read("GHOSTLIGHT_PLAYTEST_OUT")).context("GHOSTLIGHT_ATLAS_OUT is required")?), + stamp: read("GHOSTLIGHT_ATLAS_STAMP").filter(|text| !text.trim().is_empty()), + vault: text("GHOSTLIGHT_ATLAS_VAULT", "zyphos"), + era: text("GHOSTLIGHT_ATLAS_ERA", "imperial-present"), + persons: number(&read, "GHOSTLIGHT_ATLAS_PERSONS", 40)?, + institutions: number(&read, "GHOSTLIGHT_ATLAS_INSTITUTIONS", 12)?, + populations: number(&read, "GHOSTLIGHT_ATLAS_POPULATIONS", 6)?, + sweeps: number(&read, "GHOSTLIGHT_ATLAS_SWEEPS", 40)?, + sweep_sessions: number(&read, "GHOSTLIGHT_ATLAS_SWEEP_SESSIONS", 8)?, + seed_sessions: number(&read, "GHOSTLIGHT_ATLAS_SEED_SESSIONS", 2)?, + cost_cap: number(&read, "GHOSTLIGHT_ATLAS_COST_CAP", 40.0)?, + concurrency: number(&read, "GHOSTLIGHT_ATLAS_CONCURRENCY", 2)?, + }) + } + + fn scale(&self) -> Scale { + Scale { + targets: BTreeMap::from([ + (SubjectKind::Person, self.persons), + (SubjectKind::Institution, self.institutions), + (SubjectKind::Population, self.populations), + ]), + seed_sessions: self.seed_sessions, + sweep_sessions: self.sweep_sessions, + sweep_permits: self.concurrency.max(1), + } + } +} + +// ------------------------------------------------------------ the two taps + +/// When each lens's inferences ended. A session commits as its last request +/// returns, so what appears in the world was written by a lens whose request +/// ended just before it. +#[derive(Default)] +struct Activity(StdMutex>); + +impl Activity { + fn end(&self, lens: Lens) { + self.0.lock().unwrap().push((lens, Instant::now())); + } + + /// The lenses whose requests ended after `since`, in the order they first ended. + fn ended_since(&self, since: Instant) -> Vec { + let mut lenses = Vec::new(); + for (lens, at) in self.0.lock().unwrap().iter() { + if *at >= since && !lenses.contains(lens) { + lenses.push(*lens); + } + } + lenses + } +} + +/// The port the lanes infer through: it reads which lens an elaboration +/// request carries (the lens clause is in the request's instructions) and +/// changes nothing. +struct LensTap { + inner: Arc, + activity: Arc, +} + +fn lens_of(request: &PreparedInference) -> Option { + let text = serde_json::to_string(request).ok()?; + Lens::ALL.into_iter().find(|lens| text.contains(&format!("Lens: {}.", lens.name()))) +} + +#[async_trait::async_trait] +impl InferencePort for LensTap { + fn prepare(&self, request: InferenceRequest) -> Result { + self.inner.prepare(request) + } + + async fn infer(&self, request: PreparedInference) -> Result { + let lens = lens_of(&request); + let output = self.inner.infer(request).await; + if let Some(lens) = lens { + self.activity.end(lens); + } + output + } +} + +/// One retrieval the elaborator made: the referents it asked about and the +/// notes it was handed. +#[derive(Clone, Debug)] +struct Drawn { + sweep: usize, + referents: Vec, + notes: Vec, +} + +/// The evidence the sweeps read, recording each retrieval. The receipts' fields +/// are the kernel's; their `Debug` text is the public view of them. +struct Recorder { + inner: Arc, + sweep: AtomicUsize, + log: StdMutex>, +} + +fn debug_field<'a>(text: &'a str, start: &str, end: &str) -> Option<&'a str> { + let from = text.find(start)? + start.len(); + let to = text[from..].find(end)? + from; + Some(&text[from..to]) +} + +/// A receipt's note, as `title (reference)`. +fn receipt_note(receipt: &EvidenceReceipt) -> String { + let text = format!("{receipt:?}"); + let reference = debug_field(&text, "EvidenceRef(\"", "\")").unwrap_or("?"); + let title = debug_field(&text, "source: \"", "\" }").unwrap_or("?"); + format!("{title} ({reference})") +} + +#[async_trait::async_trait] +impl EvidenceSource for Recorder { + async fn retrieve(&self, query: &EvidenceQuery) -> Result, EvidenceError> { + let receipts = self.inner.retrieve(query).await?; + self.log.lock().unwrap().push(Drawn { + sweep: self.sweep.load(Ordering::SeqCst), + referents: query.referents.clone(), + notes: receipts.iter().map(receipt_note).collect(), + }); + Ok(receipts) + } +} + +impl Recorder { + /// The notes retrieved in `sweep` for a query that named any of `labels`. + fn notes_for(&self, sweep: usize, labels: &[&str]) -> Vec { + let wanted: Vec = labels.iter().filter(|label| label.len() > 2).map(|label| label.to_lowercase()).collect(); + let mut found = BTreeSet::new(); + for drawn in self.log.lock().unwrap().iter().filter(|drawn| drawn.sweep == sweep) { + let named = drawn.referents.iter().any(|referent| { + let referent = referent.to_lowercase(); + wanted.iter().any(|label| referent.contains(label.as_str())) + }); + if named { + found.extend(drawn.notes.iter().cloned()); + } + } + found.into_iter().collect() + } + + fn consulted(&self, sweep: usize) -> usize { + let log = self.log.lock().unwrap(); + log.iter().filter(|drawn| drawn.sweep == sweep).flat_map(|drawn| drawn.notes.iter()).collect::>().len() + } +} + +// ------------------------------------------------- reading the omniscient view + +#[derive(Clone, Debug, Default)] +struct Office { + name: String, + institution: String, + incumbent: String, + lends: String, +} + +#[derive(Clone, Debug, Default)] +struct Place { + id: String, + label: String, + container: Option, + occupants: Vec, +} + +#[derive(Clone, Debug, Default)] +struct Route { + id: String, + text: String, +} + +#[derive(Clone, Debug, Default)] +struct Subject { + id: String, + label: String, + kind: String, + mode: String, + place: String, + retired: bool, + granted: String, + holdings: String, + depends: String, + authority: String, + offices_held: Vec, + offices_granted: Vec, + forums: String, +} + +#[derive(Clone, Debug, Default)] +struct Fact { + id: String, + statement: String, + standing: String, + known_by: Vec, +} + +#[derive(Clone, Debug, Default)] +struct Commitment { + key: String, + holder_id: String, + holder: String, + kind: String, + with: Option, + due: String, + past_due: bool, + statement: String, +} + +#[derive(Clone, Debug, Default)] +struct Regard { + holder_id: String, + holder: String, + toward: String, + word: String, + total: String, + causes: String, +} + +#[derive(Clone, Debug, Default)] +struct Material { + id: String, + voice: String, + values: String, + memories: String, + reads: String, +} + +/// The world as the omniscient view prints it. Anything the reader could not +/// place stays in `unread`, verbatim, and the atlas prints it. +#[derive(Clone, Debug, Default)] +struct World { + places: Vec, + routes: Vec, + subjects: Vec, + facts: Vec, + commitments: Vec, + regards: Vec, + materials: Vec, + pressures: Vec, + unread: Vec, +} + +const SECTIONS: [&str; 13] = [ + "Places", "Routes", "Subjects", "Affordances", "Resources", "Channels", "Facts", "Commitments", "Pressures", "Regard", "Persona", "Clock", + "Guidance", +]; + +/// The view's sections: header word to body text. +fn sections(view: &str) -> BTreeMap<&'static str, String> { + let mut found: BTreeMap<&'static str, String> = BTreeMap::new(); + let mut current: Option<&'static str> = None; + for line in view.lines() { + let header = line.strip_prefix(" ").filter(|rest| !rest.starts_with(' ')).and_then(|rest| { + let word = rest.split([':', ' ']).next()?; + SECTIONS.iter().find(|section| **section == word).map(|section| (*section, rest)) + }); + match header { + Some((section, rest)) => { + current = Some(section); + let body = rest.split_once(':').map_or("", |(_, body)| body); + // `Regard (how ..., with what it rests on):` has a second colon-free tail. + let body = if section == "Regard" { rest.split_once("):").map_or(body, |(_, tail)| tail) } else { body }; + found.entry(section).or_default().push_str(body); + } + None => { + if let Some(section) = current { + let body = found.entry(section).or_default(); + body.push('\n'); + body.push_str(line); + } + } + } + } + found +} + +/// Items of a section body: split on `;` outside double quotes. +fn items(body: &str) -> Vec { + let mut out = Vec::new(); + let mut current = String::new(); + let mut quoted = false; + for character in body.chars() { + match character { + '"' => { + quoted = !quoted; + current.push(character); + } + ';' if !quoted => { + out.push(std::mem::take(&mut current)); + } + _ => current.push(character), + } + } + out.push(current); + out.into_iter().map(|item| item.trim().to_owned()).filter(|item| !item.is_empty() && item != "none").collect() +} + +/// `label [id] rest` as `(label, id, rest)`. +fn bracketed(text: &str) -> Option<(String, String, String)> { + let open = text.find(" [")?; + let close = text[open..].find(']')? + open; + Some((text[..open].to_owned(), text[open + 2..close].to_owned(), text[close + 1..].to_owned())) +} + +/// A `a [id], b [id]` list as labels. +fn labels_of(list: &str) -> Vec { + let list = list.trim(); + if list == "none" || list.is_empty() { + return Vec::new(); + } + list.split("], ").map(|part| part.split(" [").next().unwrap_or(part).trim().to_owned()).collect() +} + +fn offices(text: &str) -> Vec { + if text.trim() == "none" || text.trim().is_empty() { + return Vec::new(); + } + let mut merged: Vec = Vec::new(); + for part in text.split(", `") { + let part = part.trim_start_matches('`'); + match merged.last_mut() { + Some(last) if !part.contains("` of ") => { + last.push_str(", `"); + last.push_str(part); + } + _ => merged.push(part.to_owned()), + } + } + merged + .iter() + .map(|part| { + let (name, rest) = part.split_once("` of ").unwrap_or((part.as_str(), "")); + let (institution, rest) = rest.split_once(" (incumbent: ").unwrap_or((rest, "")); + let (incumbent, lends) = rest.split_once(", lends: ").unwrap_or((rest, "")); + Office { + name: name.to_owned(), + institution: institution.to_owned(), + incumbent: incumbent.to_owned(), + lends: lends.trim_end_matches(')').to_owned(), + } + }) + .collect() +} + +fn subject_of(item: &str) -> Option { + let (label, id, rest) = bracketed(item)?; + let inner = rest.trim().strip_prefix('(')?.strip_suffix(')')?; + let markers = [", in ", ", retired: ", ", granted: ", ", holdings: ", ", depends on: ", ", authority: ", ", offices held: ", ", offices granted: ", ", forums: "]; + let mut cuts = Vec::new(); + let mut from = 0; + for marker in markers { + let at = inner[from..].find(marker)? + from; + cuts.push((at, marker)); + from = at + marker.len(); + } + let field = |index: usize| -> String { + let start = cuts[index].0 + cuts[index].1.len(); + let end = cuts.get(index + 1).map_or(inner.len(), |next| next.0); + inner[start..end].trim().to_owned() + }; + let head = &inner[..cuts[0].0]; + let (kind, mode) = head.split_once(", ").unwrap_or((head, "")); + Some(Subject { + id, + label, + kind: kind.to_owned(), + mode: mode.to_owned(), + place: field(0), + retired: field(1) == "true", + granted: field(2), + holdings: field(3), + depends: field(4), + authority: field(5), + offices_held: offices(&field(6)), + offices_granted: offices(&field(7)), + forums: field(8), + }) +} + +fn commitment_of(item: &str) -> Option { + let (key, rest) = item.split_once(" held by ")?; + let (holder, holder_id, rest) = bracketed(rest)?; + let rest = rest.strip_prefix(": ")?; + let comma = rest.find(',')?; + let (kind, rest) = (&rest[..comma], &rest[comma..]); + let with = rest.split_once(", with ").map(|(_, after)| after.split(", due ").next().unwrap_or(after).split(" [").next().unwrap_or(after).to_owned()); + let due = rest.split_once(", due ").map(|(_, after)| after.split(" minutes").next().unwrap_or(after).to_owned()).unwrap_or_default(); + let (flags, statement) = rest.split_once("past due: ")?.1.split_once(": \"")?; + Some(Commitment { + key: key.to_owned(), + holder_id, + holder, + kind: kind.to_owned(), + with, + due, + past_due: flags == "true", + statement: statement.trim_end_matches('"').to_owned(), + }) +} + +fn regard_of(item: &str) -> Option { + let (holder, holder_id, rest) = bracketed(item)?; + let rest = rest.strip_prefix(" regards ")?; + let (toward, rest) = rest.split_once(" with ")?; + let (word, rest) = rest.split_once(" (")?; + let (total, causes) = rest.split_once("): ")?; + let toward = toward.split(" [").next().unwrap_or(toward); + Some(Regard { holder_id, holder, toward: toward.to_owned(), word: word.to_owned(), total: total.to_owned(), causes: causes.to_owned() }) +} + +fn parse_world(view: &str) -> World { + let found = sections(view); + let mut world = World::default(); + let body = |name: &str| found.get(name).map(String::as_str).unwrap_or(""); + + for piece in items(body("Places")) { + if let Some(list) = piece.strip_prefix("occupants:") { + if let Some(last) = world.places.last_mut() { + last.occupants = labels_of(list); + } + } else if let Some((label, id, rest)) = bracketed(&piece) { + let container = rest.trim().strip_prefix("(in ").and_then(|tail| tail.strip_suffix(')')).map(str::to_owned); + world.places.push(Place { id, label, container, occupants: Vec::new() }); + } else { + world.unread.push(format!("place: {piece}")); + } + } + for piece in items(body("Routes")) { + match bracketed(&piece) { + Some((label, id, rest)) => world.routes.push(Route { id, text: format!("{label}{rest}") }), + None => world.unread.push(format!("route: {piece}")), + } + } + for piece in items(body("Subjects")) { + match subject_of(&piece) { + Some(subject) => world.subjects.push(subject), + None => world.unread.push(format!("subject: {piece}")), + } + } + for piece in items(body("Facts")) { + if let Some(list) = piece.strip_prefix("known by:") { + if let Some(last) = world.facts.last_mut() { + last.known_by = labels_of(list); + } + } else if let Some(open) = piece.strip_prefix('"') + && let Some(split) = open.rfind("\" [") + && let Some((_, id, rest)) = bracketed(&format!("x{}", &open[split + 1..])) + { + world.facts.push(Fact { id, statement: open[..split].to_owned(), standing: rest.trim_start_matches(": ").to_owned(), known_by: Vec::new() }); + } else { + world.unread.push(format!("fact: {piece}")); + } + } + world.pressures = items(body("Pressures")); + for piece in items(body("Commitments")) { + match commitment_of(&piece) { + Some(commitment) => world.commitments.push(commitment), + None => world.unread.push(format!("commitment: {piece}")), + } + } + for piece in items(body("Regard")) { + match regard_of(&piece) { + Some(regard) => world.regards.push(regard), + None => match world.regards.last_mut() { + Some(last) if !piece.contains(" regards ") => { + last.causes.push_str("; "); + last.causes.push_str(&piece); + } + _ => world.unread.push(format!("regard: {piece}")), + }, + } + } + for piece in items(body("Persona")) { + if let Some(rest) = piece.strip_prefix("values:") { + if let Some(last) = world.materials.last_mut() { + last.values = rest.trim().to_owned(); + } + } else if let Some(rest) = piece.strip_prefix("memories:") { + if let Some(last) = world.materials.last_mut() { + last.memories = rest.trim().to_owned(); + } + } else if let Some(rest) = piece.strip_prefix("reads:") { + if let Some(last) = world.materials.last_mut() { + last.reads = rest.trim().to_owned(); + } + } else if let Some((_, id, rest)) = bracketed(&piece) { + let voice = rest.trim_start_matches(": voice ").trim().trim_matches('"').to_owned(); + world.materials.push(Material { id, voice, ..Material::default() }); + } else if let Some(last) = world.materials.last_mut() { + // A `;` inside a memory or read splits it; the piece continues the + // last field the material carries. + let field = [&mut last.reads, &mut last.memories, &mut last.values, &mut last.voice].into_iter().find(|field| !field.is_empty()); + if let Some(field) = field { + field.push_str("; "); + field.push_str(&piece); + } + } else { + world.unread.push(format!("persona material: {piece}")); + } + } + world +} + +impl World { + /// The entities the timeline follows: key to (section, label). + fn keyed(&self) -> BTreeMap { + let mut keyed = BTreeMap::new(); + for place in &self.places { + keyed.insert(format!("place:{}", place.id), ("place", place.label.clone())); + } + for route in &self.routes { + keyed.insert(format!("route:{}", route.id), ("route", route.text.clone())); + } + for subject in &self.subjects { + keyed.insert(format!("subject:{}", subject.id), (subject_section(&subject.kind), subject.label.clone())); + for office in &subject.offices_granted { + keyed.insert(format!("office:{}:{}", subject.id, office.name), ("office", format!("{} of {}", office.name, subject.label))); + } + } + // What a sweep changes without adding a thing: a subject's holdings, + // dependencies, authority or offices, a regard, a persona's material, a + // pressure. Each new state is a key of its own, first seen when it appears. + for subject in &self.subjects { + let state = format!("holdings: {}; depends on: {}; authority: {}; offices held: {}; forums: {}", subject.holdings, subject.depends, subject.authority, subject.offices_held.len(), subject.forums); + keyed.insert(format!("state:{}:{state}", subject.id), ("state", format!("{} ({state})", subject.label))); + } + for regard in &self.regards { + keyed.insert( + format!("regard:{}:{}:{}", regard.holder_id, regard.toward, regard.total), + ("regard", format!("{} regards {}: {} ({})", regard.holder, regard.toward, regard.word, regard.total)), + ); + } + for material in &self.materials { + let name = self.subjects.iter().find(|subject| subject.id == material.id).map_or(material.id.as_str(), |subject| subject.label.as_str()); + keyed.insert(format!("material:{}:{}|{}|{}", material.id, material.voice, material.values, material.memories), ("persona", format!("{name}: voice {}; values {}", material.voice, material.values))); + } + for pressure in &self.pressures { + keyed.insert(format!("pressure:{pressure}"), ("pressure", pressure.clone())); + } + for fact in &self.facts { + keyed.insert(format!("fact:{}", fact.id), ("fact", fact.statement.clone())); + } + for commitment in &self.commitments { + keyed.insert(format!("commitment:{}", commitment.key), ("commitment", commitment.statement.clone())); + } + keyed + } + + fn subject(&self, label: &str) -> Option<&Subject> { + self.subjects.iter().find(|subject| subject.label == label) + } + + fn people(&self) -> impl Iterator { + self.subjects.iter().filter(|subject| subject.kind == "person" && !subject.retired) + } + + /// The group a person belongs to: the institution whose office they hold, + /// else an institution or population they depend on, else one they share a + /// commitment with. + fn home_group(&self, person: &Subject) -> Option { + if let Some(office) = person.offices_held.first() { + return Some(office.institution.clone()); + } + let is_group = |kind: &str| kind == "institution" || kind == "population"; + let depended = person + .depends + .split(", ") + .filter_map(|part| part.strip_prefix("subject ")) + .find(|label| self.subject(label).is_some_and(|subject| is_group(&subject.kind))) + .map(str::to_owned); + depended.or_else(|| { + self.commitments.iter().find_map(|commitment| { + if commitment.holder_id == person.id { + commitment.with.as_deref().filter(|with| self.subject(with).is_some_and(|subject| is_group(&subject.kind))).map(str::to_owned) + } else if commitment.with.as_deref() == Some(person.label.as_str()) { + self.subjects.iter().find(|subject| subject.id == commitment.holder_id && is_group(&subject.kind)).map(|subject| subject.label.clone()) + } else { + None + } + }) + }) + } +} + +fn subject_section(kind: &str) -> &'static str { + match kind { + "person" => "person", + "institution" => "institution", + "population" => "population", + _ => "subject", + } +} + +// ------------------------------------------------------------ the run record + +#[derive(Clone, Debug)] +struct Seen { + sweep: usize, + lenses: Vec, + section: &'static str, + label: String, +} + +struct SweepRow { + sweep: usize, + claimed: usize, + started: usize, + committed: usize, + rejected: usize, + no_patch: usize, + abandoned: usize, + failed: usize, + boundaries: usize, + deficits: String, + cost: f64, + wall_secs: f64, +} + +fn deficit_line(world: &WorldSnapshot) -> String { + let mut rows: BTreeMap = BTreeMap::new(); + for row in &world.scale_deficit { + let kind = match row.kind { + SubjectKind::Person => "person", + SubjectKind::Institution => "institution", + SubjectKind::Population => "population", + }; + let entry = rows.entry(kind.to_owned()).or_default(); + entry.0 += row.qualified; + entry.1 += row.target; + } + rows.iter().map(|(kind, (qualified, target))| format!("{kind} {qualified}/{target}")).collect::>().join(", ") +} + +struct Watch<'a> { + host: &'a crate::timelines::TimelineHost, + activity: &'a Activity, + seen: BTreeMap, + last_poll: Instant, +} + +impl Watch<'_> { + /// Reads the world and records what appeared since the last read, under + /// `sweep` and the lenses active now. + async fn poll(&mut self, sweep: usize) -> Option { + let snapshot = self.host.world.snapshot().await.ok()?; + let world = parse_world(&table_view(&snapshot)); + // Begin's seed and its run-ahead are not a sweep of this run; no lens is read for them. + let lenses = if sweep == 0 { Vec::new() } else { self.activity.ended_since(self.last_poll.checked_sub(LENS_WINDOW).unwrap_or(self.last_poll)) }; + self.last_poll = Instant::now(); + for (key, (section, label)) in world.keyed() { + self.seen.entry(key).or_insert_with(|| Seen { sweep, lenses: lenses.clone(), section, label }); + } + Some(world) + } +} + +// ------------------------------------------------------------------- the run + +pub(super) async fn run(options: AtlasOptions) -> anyhow::Result { + let pool: usize = std::env::var("GHOSTLIGHT_CONTROLLER_MAX_CONCURRENT").ok().and_then(|text| text.trim().parse().ok()).unwrap_or(4); + if options.concurrency == 0 || pool > options.concurrency { + bail!( + "the connector pool is {pool} but this run may use {}: set GHOSTLIGHT_CONTROLLER_MAX_CONCURRENT={} so Begin's seed leaves the caller its headroom", + options.concurrency, + options.concurrency + ); + } + let plan = Plan::checked_in(); + let stamp = options.stamp.clone().unwrap_or_else(|| Utc::now().format("%Y-%m-%dT%H%MZ").to_string()); + let root = options.out.join(stamp); + std::fs::create_dir_all(&root)?; + let root = std::fs::canonicalize(&root)?; + let mut progress = std::fs::File::create(root.join("progress.log"))?; + let mut log = |line: String| { + let _ = writeln!(progress, "{} {line}", Utc::now().format("%H:%M:%SZ")); + println!("{line}"); + }; + let started = Instant::now(); + + let activity = Arc::new(Activity::default()); + let tap = activity.clone(); + let Harness { global, state, router, cookies, imports, .. } = open_harness( + &root, + &[options.vault.as_str()], + options.scale(), + &["atlas-observer".to_owned()], + move |port| Arc::new(LensTap { inner: port, activity: tap }), + )?; + for line in &imports { + log(format!("vault import: {line}")); + } + let import = imports.first().cloned().unwrap_or_default(); + let snapshot_id = import.split("id=").nth(1).unwrap_or("").trim().to_owned(); + let snapshot_note = if options.vault == "zyphos" && snapshot_id != EXPECTED_ZYPHOS_SNAPSHOT { + format!("DIFFERS from the live server's {EXPECTED_ZYPHOS_SNAPSHOT}") + } else { + "matches the expected id".to_owned() + }; + log(format!("snapshot id {snapshot_id}: {snapshot_note}")); + + let client = Client { router: router.clone(), cookie: cookies[0].clone() }; + let weights: BTreeMap = Lens::ALL.into_iter().map(|lens| (lens, 1)).collect(); + let body = json!({ + "key": uuid::Uuid::new_v4().to_string(), + "title": format!("{} atlas", options.vault), + "name": "Observer", + "vault": options.vault, + "era": options.era, + "lenses": weights, + }); + // A seed that authored no one fails and leaves the world a Draft; the same + // key seeds it again. The model's first draft is not deterministic, so the + // run asks up to `SEED_ATTEMPTS` times before it gives up. + let (mut timeline, mut seed_secs) = (String::new(), 0.0); + for attempt in 1..=SEED_ATTEMPTS { + let (status, reply) = client.call(Method::POST, "/api/begin", Some(body.clone())).await; + if !status.is_success() { + bail!("/api/begin answered {status}: {reply}"); + } + timeline = reply["timeline"].as_str().context("begin named no timeline")?.to_owned(); + log(format!( + "begun as {timeline} (attempt {attempt}): targets person {} institution {} population {}, all eight lenses at 1, era {}; seeding", + options.persons, options.institutions, options.populations, options.era + )); + match poll_seed(&client, &timeline, Instant::now()).await { + Ok(secs) => { + seed_secs = secs; + break; + } + Err(fault) if attempt < SEED_ATTEMPTS => log(format!("seed attempt {attempt} failed: {fault}; ${:.2} spent", dollars(&plan, &global.by_model()))), + Err(fault) => bail!("the seed failed {SEED_ATTEMPTS} times: {fault}"), + } + } + log(format!("seeded in {seed_secs:.0}s; ${:.2}", dollars(&plan, &global.by_model()))); + + let host = state.timelines.host(&timeline).await?; + // Begin's own run-ahead sweep holds this lock; ours waits for it, and a + // run-ahead that arrives after finds the lock taken and returns. + let _sweeping = host.sweeping.lock().await; + let evidence = evidence_of(&state.catalog, state.vaults.as_ref(), &host, &timeline).await.context("the world's evidence could not be reopened")?; + let recorder = Arc::new(Recorder { inner: evidence, sweep: AtomicUsize::new(0), log: StdMutex::new(Vec::new()) }); + let runner = host.controllers.elaborator(recorder.clone()); + + let mut watch = Watch { host: &host, activity: &activity, seen: BTreeMap::new(), last_poll: Instant::now() }; + watch.poll(0).await.context("the seeded world could not be read")?; + let opening = host.world.snapshot().await?; + log(format!( + "sweep 0 (Begin's seed and run-ahead): {} places, boundaries {}, {}", + opening.places.len(), + opening.boundaries.len(), + deficit_line(&opening) + )); + + let mut rows: Vec = Vec::new(); + let mut stop = format!("the {} sweeps were used", options.sweeps); + let mut stalled = 0; + for sweep in 1..=options.sweeps as usize { + let cost = dollars(&plan, &global.by_model()); + if cost >= options.cost_cap { + stop = format!("cost cap ${:.2} reached at ${cost:.2}", options.cost_cap); + break; + } + let before = host.world.snapshot().await?; + if before.boundaries.is_empty() && before.scale_deficit.iter().all(|row| row.deficit == 0) { + stop = "no boundary or deficit remains".into(); + break; + } + recorder.sweep.store(sweep, Ordering::SeqCst); + let began = Instant::now(); + let permits = Arc::new(Semaphore::new(options.concurrency)); + let mut sweeping = Box::pin(runner.sweep(permits, options.sweep_sessions)); + let outcome = loop { + tokio::select! { + outcome = &mut sweeping => break outcome, + _ = tokio::time::sleep(POLL_EVERY) => { watch.poll(sweep).await; } + } + }; + drop(sweeping); + watch.poll(sweep).await; + let report = match outcome { + Ok(report) => report, + Err(error) => { + log(format!("sweep {sweep} stopped with an error: {error}")); + stop = format!("sweep {sweep} ended in an error: {error}"); + break; + } + }; + let after = host.world.snapshot().await?; + let row = SweepRow { + sweep, + claimed: report.claimed, + started: report.started, + committed: report.committed, + rejected: report.rejected, + no_patch: report.no_patch, + abandoned: report.abandoned, + failed: report.failed.len(), + boundaries: after.boundaries.len(), + deficits: deficit_line(&after), + cost: dollars(&plan, &global.by_model()), + wall_secs: began.elapsed().as_secs_f64(), + }; + let usage = global.totals(); + log(format!( + "sweep {sweep}: claimed {} started {} committed {} rejected {} no_patch {} abandoned {} failed {} | places {} subjects {} boundaries {} | {} | ${:.2} | {} calls {} in {} out | {:.0}s", + row.claimed, row.started, row.committed, row.rejected, row.no_patch, row.abandoned, row.failed, + after.places.len(), after.subjects.len(), row.boundaries, row.deficits, row.cost, usage.calls, usage.prompt, usage.completion, row.wall_secs + )); + for failure in report.failed.iter().take(3) { + log(format!(" failed: {failure}")); + } + let claimed = row.claimed; + stalled = if row.committed == 0 { stalled + 1 } else { 0 }; + rows.push(row); + if claimed == 0 { + stop = "no claim remains: every open boundary and deficit is answered or at a fixed point".into(); + break; + } + if stalled >= STALL_SWEEPS { + stop = format!("{STALL_SWEEPS} sweeps in a row committed nothing"); + break; + } + } + log(format!("elaboration stopped: {stop}")); + + let final_snapshot = host.world.snapshot().await?; + let view = table_view(&final_snapshot); + let world = parse_world(&view); + let cost = dollars(&plan, &global.by_model()); + let usage = global.totals(); + let header = Header { + title: final_snapshot.title.clone(), + era: final_snapshot.era.as_ref().map(|era| format!("{} ({}): {}", era.label, era.id, era.description)).unwrap_or_default(), + options: &options, + snapshot_id: &snapshot_id, + snapshot_note: &snapshot_note, + stop: &stop, + cost, + calls: usage.calls, + wall_minutes: started.elapsed().as_secs_f64() / 60.0, + boundaries_left: final_snapshot.boundaries.len(), + deficits: deficit_line(&final_snapshot), + lens_weights: final_snapshot.lens_weights.iter().map(|(lens, weight)| format!("{} {weight}", lens.name())).collect::>().join(", "), + }; + std::fs::write(root.join("atlas.md"), render_atlas(&header, &world, &watch.seen, &rows, &recorder))?; + std::fs::write(root.join("world-view.txt"), &view)?; + let people = world.people().count(); + let count = |kind: &str| world.subjects.iter().filter(|subject| subject.kind == kind && !subject.retired).count(); + std::fs::write( + root.join("summary.json"), + serde_json::to_string_pretty(&json!({ + "timeline": timeline, + "snapshot_id": snapshot_id, + "snapshot_note": snapshot_note, + "places": world.places.len(), + "routes": world.routes.len(), + "institutions": count("institution"), + "people": people, + "populations": count("population"), + "facts": world.facts.len(), + "commitments": world.commitments.len(), + "sweeps": rows.len(), + "stop": stop, + "cost_usd": cost, + "calls": usage.calls, + "prompt_tokens": usage.prompt, + "completion_tokens": usage.completion, + "unread_view_items": world.unread.len(), + "wall_minutes": started.elapsed().as_secs_f64() / 60.0, + }))?, + )?; + log(format!( + "atlas written: {} places, {} institutions, {people} people, {} populations, {} facts; ${cost:.2}", + world.places.len(), + count("institution"), + count("population"), + world.facts.len() + )); + Ok(root) +} + +// ----------------------------------------------------------------- rendering + +struct Header<'a> { + title: String, + era: String, + options: &'a AtlasOptions, + snapshot_id: &'a str, + snapshot_note: &'a str, + stop: &'a str, + cost: f64, + calls: u64, + wall_minutes: f64, + boundaries_left: usize, + deficits: String, + lens_weights: String, +} + +/// One line of prose-safe text: no newlines, no table pipes. +fn flat(text: &str) -> String { + text.replace(['\n', '\r'], " ").replace('|', "/").trim().to_owned() +} + +fn lens_names(lenses: &[Lens]) -> String { + if lenses.is_empty() { "no lens read".to_owned() } else { lenses.iter().map(|lens| lens.name()).collect::>().join("/") } +} + +/// Who added an entry, and which sweep's retrieval the entry can be tied to. +struct Provenance<'a> { + seen: &'a BTreeMap, + recorder: &'a Recorder, +} + +impl Provenance<'_> { + fn added(&self, key: &str) -> String { + match self.seen.get(key) { + Some(seen) if seen.sweep == 0 => "sweep 0, Begin's seed".to_owned(), + Some(seen) => format!("sweep {}, {}", seen.sweep, lens_names(&seen.lenses)), + None => "not followed".to_owned(), + } + } + + fn notes(&self, key: &str, also: &[&str]) -> String { + let Some(seen) = self.seen.get(key) else { return "none recorded".to_owned() }; + if seen.sweep == 0 { + return "none recorded (Begin's seed does not log its retrievals)".to_owned(); + } + let mut labels = vec![seen.label.as_str()]; + labels.extend_from_slice(also); + let notes = self.recorder.notes_for(seen.sweep, &labels); + if notes.is_empty() { + format!("no query in sweep {} named it ({} notes consulted that sweep)", seen.sweep, self.recorder.consulted(seen.sweep)) + } else { + notes.into_iter().take(6).collect::>().join("; ") + } + } +} + +fn render_atlas(header: &Header, world: &World, seen: &BTreeMap, rows: &[SweepRow], recorder: &Recorder) -> String { + let provenance = Provenance { seen, recorder }; + let institutions: Vec<&Subject> = world.subjects.iter().filter(|subject| subject.kind == "institution" && !subject.retired).collect(); + let populations: Vec<&Subject> = world.subjects.iter().filter(|subject| subject.kind == "population" && !subject.retired).collect(); + let mut out = format!("# Atlas of {}\n\n", flat(&header.title)); + out.push_str(&format!( + "Era: {}\n\nLens weights: {}.\n\nTargets asked: person {}, institution {}, population {}. Left unanswered at the end: {} boundaries; scale ({}).\n\n", + flat(&header.era), + header.lens_weights, + header.options.persons, + header.options.institutions, + header.options.populations, + header.boundaries_left, + header.deficits + )); + out.push_str(&format!( + "| Places | Routes | Institutions | People | Populations | Facts | Commitments |\n|---|---|---|---|---|---|---|\n| {} | {} | {} | {} | {} | {} | {} |\n\n", + world.places.len(), + world.routes.len(), + institutions.len(), + world.people().count(), + populations.len(), + world.facts.len(), + world.commitments.len() + )); + out.push_str(&format!( + "Run: {} sweeps, ${:.2} of a ${:.2} cap, {} model calls, {:.0} minutes, concurrency {}. Stopped because: {}.\n\nVault snapshot `{}`: {}.\n\n", + rows.len(), + header.cost, + header.options.cost_cap, + header.calls, + header.wall_minutes, + header.options.concurrency, + header.stop, + header.snapshot_id, + header.snapshot_note + )); + out.push_str( + "How to read this. Every entry below was admitted by the kernel from an elaborator's patch; nothing here was written by hand. \ +The kernel keeps no separate kinds for customs, laws, debts or traits: they appear as facts (with standing), routine and obligation \ +commitments, offices and authority grants, forums, and the causes behind each regard. \"Added in\" names the sweep and the lenses whose \ +inference ended in the seconds before the entry first appeared, so with two sessions running at once it can name the other \ +session's lens as well. \"Drew on\" lists vault notes retrieved in that sweep by a query that named the entry or its place; the journal's own \ +per-patch evidence references are not readable outside the kernel, so an entry no query named says so.\n\n", + ); + + // Timeline. + out.push_str("## Elaboration timeline\n\n| Sweep | Claimed | Started | Committed | Rejected | No patch | Abandoned | Failed | Boundaries left | Scale | Cumulative $ | Seconds |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n"); + for row in rows { + out.push_str(&format!( + "| {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {:.2} | {:.0} |\n", + row.sweep, row.claimed, row.started, row.committed, row.rejected, row.no_patch, row.abandoned, row.failed, row.boundaries, row.deficits, row.cost, row.wall_secs + )); + } + out.push('\n'); + let sweeps: BTreeSet = seen.values().map(|entry| entry.sweep).collect(); + for sweep in sweeps { + let mut by_lens: BTreeMap>> = BTreeMap::new(); + for entry in seen.values().filter(|entry| entry.sweep == sweep && !(sweep == 0 && entry.section == "state")) { + by_lens.entry(if sweep == 0 { "Begin's seed".to_owned() } else { lens_names(&entry.lenses) }).or_default().entry(entry.section).or_default().push(&entry.label); + } + out.push_str(&format!("### Sweep {sweep}{}\n\n", if sweep == 0 { " (Begin's seed and run-ahead)" } else { "" })); + for (lens, sections) in by_lens { + let line: Vec = sections + .iter() + .map(|(section, labels)| { + let shown: Vec = labels.iter().take(14).map(|label| flat(&label.chars().take(90).collect::())).collect(); + let more = if labels.len() > shown.len() { format!(" and {} more", labels.len() - shown.len()) } else { String::new() }; + format!("{} {section}{}: {}{more}", labels.len(), if labels.len() == 1 { "" } else { "s" }, shown.join("; ")) + }) + .collect(); + out.push_str(&format!("- **{lens}** added {}\n", line.join(" | "))); + } + out.push('\n'); + } + + // Institutions first, with members and offices. + out.push_str("## Institutions\n\n"); + if institutions.is_empty() { + out.push_str("None stand in the final state.\n\n"); + } + for institution in &institutions { + let key = format!("subject:{}", institution.id); + out.push_str(&format!("### {}\n\n- Seat: {}. Added in {}.\n", flat(&institution.label), flat(&institution.place), provenance.added(&key))); + let members: Vec<&Subject> = world.people().filter(|person| world.home_group(person).as_deref() == Some(institution.label.as_str())).collect(); + if institution.offices_granted.is_empty() { + out.push_str("- Offices: none declared.\n"); + } + for office in &institution.offices_granted { + out.push_str(&format!( + "- Office `{}`: incumbent {}; lends {}. Added in {}.\n", + flat(&office.name), + flat(&office.incumbent), + flat(&office.lends), + provenance.added(&format!("office:{}:{}", institution.id, office.name)) + )); + } + if members.is_empty() { + out.push_str("- Members: none recorded.\n"); + } else { + out.push_str("- Members:\n"); + for member in members { + let role = member.offices_held.iter().map(|office| office.name.as_str()).collect::>().join(", "); + out.push_str(&format!(" - {} ({}){}\n", flat(&member.label), flat(&member.place), if role.is_empty() { String::new() } else { format!(", holds {}", flat(&role)) })); + } + } + for (name, text) in [("Holdings", &institution.holdings), ("Depends on", &institution.depends), ("Authority", &institution.authority), ("Forums", &institution.forums)] { + if text != "none" && !text.is_empty() { + out.push_str(&format!("- {name}: {}\n", flat(text))); + } + } + let commitments: Vec<&Commitment> = world.commitments.iter().filter(|commitment| commitment.holder_id == institution.id).collect(); + for commitment in commitments { + out.push_str(&format!("- {}: {}{}\n", commitment.kind, flat(&commitment.statement), commitment.with.as_ref().map_or(String::new(), |with| format!(" (with {})", flat(with))))); + } + out.push_str(&format!("- Drew on: {}\n\n", provenance.notes(&key, &[institution.place.as_str()]))); + } + + // Populations. + out.push_str("## Populations\n\n"); + if populations.is_empty() { + out.push_str("None stand in the final state.\n\n"); + } + for population in &populations { + let key = format!("subject:{}", population.id); + out.push_str(&format!("### {}\n\n- Place: {}. Added in {}.\n", flat(&population.label), flat(&population.place), provenance.added(&key))); + for (name, text) in [("Holdings", &population.holdings), ("Depends on", &population.depends), ("Authority", &population.authority)] { + if text != "none" && !text.is_empty() { + out.push_str(&format!("- {name}: {}\n", flat(text))); + } + } + let members: Vec<&str> = world.people().filter(|person| world.home_group(person).as_deref() == Some(population.label.as_str())).map(|person| person.label.as_str()).collect(); + if !members.is_empty() { + out.push_str(&format!("- People who depend on it: {}\n", members.join(", "))); + } + for commitment in world.commitments.iter().filter(|commitment| commitment.holder_id == population.id) { + out.push_str(&format!("- {}: {}\n", commitment.kind, flat(&commitment.statement))); + } + out.push_str(&format!("- Drew on: {}\n\n", provenance.notes(&key, &[population.place.as_str()]))); + } + + // People, by group then place. + out.push_str("## People\n\nGrouped by home group (the institution whose office a person holds, else the institution or population they depend on or share a commitment with), then by the place they stand in.\n\n"); + let mut groups: BTreeMap>> = BTreeMap::new(); + for person in world.people() { + let group = world.home_group(person).unwrap_or_else(|| "No group recorded".to_owned()); + groups.entry(group).or_default().entry(person.place.clone()).or_default().push(person); + } + for (group, places) in &groups { + out.push_str(&format!("### {}\n\n", flat(group))); + for (place, people) in places { + out.push_str(&format!("#### {}\n\n", flat(place))); + for person in people { + let key = format!("subject:{}", person.id); + out.push_str(&format!("- **{}** ({}). Added in {}.\n", flat(&person.label), flat(&person.mode), provenance.added(&key))); + if let Some(material) = world.materials.iter().find(|material| material.id == person.id) { + out.push_str(&format!(" - Voice: {}\n", flat(&material.voice))); + for (name, text) in [("Values", &material.values), ("Memories", &material.memories), ("Reads", &material.reads)] { + if text != "none" && !text.is_empty() { + out.push_str(&format!(" - {name}: {}\n", flat(text))); + } + } + } + for (name, text) in [("Holdings", &person.holdings), ("Depends on", &person.depends), ("Authority", &person.authority)] { + if text != "none" && !text.is_empty() { + out.push_str(&format!(" - {name}: {}\n", flat(text))); + } + } + for office in &person.offices_held { + out.push_str(&format!(" - Holds `{}` of {}\n", flat(&office.name), flat(&office.institution))); + } + for commitment in world.commitments.iter().filter(|commitment| commitment.holder_id == person.id) { + out.push_str(&format!( + " - {}: {}{}{}\n", + commitment.kind, + flat(&commitment.statement), + commitment.with.as_ref().map_or(String::new(), |with| format!(" (with {})", flat(with))), + if commitment.past_due { ", past due" } else { "" } + )); + } + for regard in world.regards.iter().filter(|regard| regard.holder_id == person.id) { + out.push_str(&format!(" - Regards {} with {} ({}): {}\n", flat(®ard.toward), regard.word, regard.total, flat(®ard.causes))); + } + out.push_str(&format!(" - Drew on: {}\n", provenance.notes(&key, &[person.place.as_str()]))); + } + out.push('\n'); + } + } + + // Places and routes. + out.push_str("## Places and routes\n\n"); + let mut roots: Vec<&Place> = world.places.iter().filter(|place| place.container.is_none() || !world.places.iter().any(|other| Some(&other.label) == place.container.as_ref())).collect(); + roots.sort_by(|a, b| a.label.cmp(&b.label)); + fn render_place(out: &mut String, world: &World, place: &Place, depth: usize, provenance: &Provenance, visited: &mut BTreeSet) { + if !visited.insert(place.id.clone()) { + return; + } + let key = format!("place:{}", place.id); + out.push_str(&format!( + "{}- **{}** (added in {}); present: {}; drew on: {}\n", + " ".repeat(depth), + flat(&place.label), + provenance.added(&key), + if place.occupants.is_empty() { "no one".to_owned() } else { place.occupants.iter().map(|name| flat(name)).collect::>().join(", ") }, + provenance.notes(&key, &[]) + )); + let mut children: Vec<&Place> = world.places.iter().filter(|other| other.container.as_ref() == Some(&place.label)).collect(); + children.sort_by(|a, b| a.label.cmp(&b.label)); + for child in children { + render_place(out, world, child, depth + 1, provenance, visited); + } + } + let mut visited = BTreeSet::new(); + for place in roots { + render_place(&mut out, world, place, 0, &provenance, &mut visited); + } + out.push_str("\nRoutes:\n\n"); + if world.routes.is_empty() { + out.push_str("- none\n"); + } + for route in &world.routes { + out.push_str(&format!("- {} (added in {})\n", flat(&route.text), provenance.added(&format!("route:{}", route.id)))); + } + out.push('\n'); + + // Facts, grouped by the first knower's home group. + out.push_str("## Facts\n\nGrouped by the home group of the first subject who knows the fact; a fact nobody knows stands last.\n\n"); + let mut fact_groups: BTreeMap> = BTreeMap::new(); + for fact in &world.facts { + let group = fact + .known_by + .first() + .and_then(|name| world.subject(name)) + .map(|subject| { + if subject.kind == "person" { world.home_group(subject).unwrap_or_else(|| "No group recorded".to_owned()) } else { subject.label.clone() } + }) + .unwrap_or_else(|| "Known by no one yet".to_owned()); + fact_groups.entry(group).or_default().push(fact); + } + for (group, facts) in fact_groups { + out.push_str(&format!("### {}\n\n", flat(&group))); + for fact in facts { + let key = format!("fact:{}", fact.id); + out.push_str(&format!( + "- \"{}\" [{}]; known by {}. Added in {}. Drew on: {}\n", + flat(&fact.statement), + flat(&fact.standing), + if fact.known_by.is_empty() { "no one".to_owned() } else { fact.known_by.iter().map(|name| flat(name)).collect::>().join(", ") }, + provenance.added(&key), + provenance.notes(&key, &[]) + )); + } + out.push('\n'); + } + + // Customs, laws and debts. + out.push_str("## Customs, laws and debts\n\nRoutines are what holders do on a cycle; obligations owed to a counterparty are the debts; offices, authority and forums are the law the kernel holds.\n\n"); + for (heading, kind) in [("Routines", "routine"), ("Obligations and debts", "obligation"), ("Goals", "goal")] { + out.push_str(&format!("### {heading}\n\n")); + let mut any = false; + for commitment in world.commitments.iter().filter(|commitment| commitment.kind == kind) { + any = true; + out.push_str(&format!( + "- {}: {}{}; due {} min{} (added in {})\n", + flat(&commitment.holder), + flat(&commitment.statement), + commitment.with.as_ref().map_or(String::new(), |with| format!(", with {}", flat(with))), + commitment.due, + if commitment.past_due { ", past due" } else { "" }, + provenance.added(&format!("commitment:{}", commitment.key)) + )); + } + if !any { + out.push_str("- none\n"); + } + out.push('\n'); + } + out.push_str("### Offices, authority and forums\n\n"); + let mut any = false; + for subject in world.subjects.iter().filter(|subject| !subject.retired) { + for (name, text) in [("authority", &subject.authority), ("forums", &subject.forums)] { + if text != "none" && !text.is_empty() { + any = true; + out.push_str(&format!("- {} {name}: {}\n", flat(&subject.label), flat(text))); + } + } + } + if !any { + out.push_str("- none\n"); + } + out.push('\n'); + + if !world.unread.is_empty() { + out.push_str("## Unread view items\n\nThe reader could not place these lines of the omniscient view; they are given verbatim.\n\n"); + for line in &world.unread { + out.push_str(&format!("- {}\n", flat(line))); + } + } + out +} + +#[tokio::test] +#[ignore = "live: spends connector credit; run through scripts/playtest-yggdrasil.sh --atlas on Yggdrasil"] +async fn live_atlas() { + // Faults the lanes only log (a failed seed names its cause there) reach the run log. + let _ = tracing_subscriber::fmt().with_env_filter(tracing_subscriber::EnvFilter::from_default_env()).with_writer(std::io::stdout).try_init(); + let options = AtlasOptions::from_reader(|name| std::env::var(name).ok()).expect("the atlas environment"); + let root = run(options).await.expect("the atlas run"); + println!("ATLAS {}", root.display()); +} + +#[cfg(test)] +mod tests { + use super::*; + + const VIEW: &str = "Whole-world table (the play agent's own view; reference anything by the id in brackets): + Places: The Commons [place-0]; occupants: Ona [s-1]; Hive Hall [place-1] (in The Commons); occupants: Vel [s-2], Mira Q [s-3]; Spur [place-2] (in Hive Hall); occupants: none; + Routes: Hall road [r-1]: The Commons -> Hive Hall, public, open; Narrow stair [r-2]: Hive Hall -> Spur, restricted, requires `key`, closed; + Subjects: Ona [s-1] (person, human, in The Commons, retired: false, granted: speak, holdings: none, depends on: none, authority: none, offices held: none, offices granted: none, forums: none); Vel [s-2] (person, narrative persona, in Hive Hall, retired: false, granted: speak, holdings: 3 of Wax [res-1], depends on: subject The Queens' Council, authority: none, offices held: `speaker` of The Queens' Council (incumbent: Vel, lends: `law` over Hive Hall [place-1]), offices granted: none, forums: none); Mira Q [s-3] (person, narrative persona, in Hive Hall, retired: false, granted: speak, holdings: none, depends on: subject The Brood, authority: none, offices held: none, offices granted: none, forums: none); The Queens' Council [s-4] (institution, operational agent, in Hive Hall, retired: false, granted: none, holdings: none, depends on: none, authority: none, offices held: none, offices granted: `speaker` of The Queens' Council (incumbent: Vel, lends: none), forums: none); The Brood [s-5] (population, operational agent, in Spur, retired: false, granted: none, holdings: none, depends on: none, authority: none, offices held: none, offices granted: none, forums: none); + Affordances: none + Resources: Wax [res-1]; + Channels: none + Facts: \"The hive keeps no private names; it is rude to ask.\" [f-1]: canonical; known by: Vel [s-2], Mira Q [s-3]; \"Wax is owed to the Council\" [f-2]: claimed by Vel; known by: none; + Commitments: cmd-1/0 held by Vel [s-2]: obligation, with The Queens' Council [s-4], due 120 minutes, past due: false: \"Deliver wax at the turning\"; cmd-2/0 held by Mira Q [s-3]: routine, due 60 minutes, every 1440 minutes, past due: true: \"Sing the brood awake\"; + Pressures: none + Regard (how each subject holds another, with what it rests on): Mira Q [s-3] regards Vel [s-2] with wary respect (+2): a debt of wax; a shared brood; + Persona material: Vel [s-2]: voice \"measured, dry\"; values: duty, wax; memories: the cold winter; reads: none; + Clock: the world reads 0 fictional minutes. + Guidance: be good. +"; + + #[test] + fn the_omniscient_view_reads_into_places_people_groups_and_commitments() { + let world = parse_world(VIEW); + assert!(world.unread.is_empty(), "{:?}", world.unread); + assert_eq!(world.places.len(), 3); + assert_eq!(world.places[1].container.as_deref(), Some("The Commons")); + assert_eq!(world.places[1].occupants, ["Vel", "Mira Q"]); + assert_eq!(world.routes.len(), 2); + assert_eq!(world.subjects.len(), 5); + let vel = world.subject("Vel").unwrap(); + assert_eq!(vel.offices_held[0].institution, "The Queens' Council"); + assert_eq!(vel.holdings, "3 of Wax [res-1]"); + assert_eq!(world.home_group(vel).as_deref(), Some("The Queens' Council")); + assert_eq!(world.home_group(world.subject("Mira Q").unwrap()).as_deref(), Some("The Brood")); + assert_eq!(world.facts.len(), 2); + assert!(world.facts[0].statement.contains("; it is rude"), "a quoted statement keeps its semicolon"); + assert_eq!(world.facts[0].known_by, ["Vel", "Mira Q"]); + assert_eq!(world.facts[1].standing, "claimed by Vel"); + assert_eq!(world.commitments.len(), 2); + assert_eq!(world.commitments[0].with.as_deref(), Some("The Queens' Council")); + assert!(world.commitments[1].past_due); + assert_eq!(world.regards[0].causes, "a debt of wax; a shared brood"); + assert_eq!(world.materials[0].values, "duty, wax"); + } + + #[test] + fn the_atlas_groups_people_by_institution_then_place_and_names_what_it_drew_on() { + let world = parse_world(VIEW); + let recorder = Recorder { + inner: Arc::new(ghostlight::NullEvidenceSource), + sweep: AtomicUsize::new(2), + log: StdMutex::new(vec![Drawn { sweep: 2, referents: vec!["Hive Hall".into()], notes: vec!["Hive customs (Civilizations/Hive.md)".into()] }]), + }; + let seen: BTreeMap = world + .keyed() + .into_iter() + .map(|(key, (section, label))| (key, Seen { sweep: if label == "Vel" { 2 } else { 0 }, lenses: vec![Lens::Charter], section, label })) + .collect(); + let options = AtlasOptions::from_reader(|name| (name == "GHOSTLIGHT_ATLAS_OUT").then(|| "/tmp/x".to_owned())).unwrap(); + let header = Header { + title: "Test".into(), + era: "present".into(), + options: &options, + snapshot_id: "abc", + snapshot_note: "matches", + stop: "test", + cost: 1.5, + calls: 3, + wall_minutes: 2.0, + boundaries_left: 0, + deficits: "person 3/40".into(), + lens_weights: "Patina 1".into(), + }; + let rows = [SweepRow { sweep: 1, claimed: 2, started: 2, committed: 1, rejected: 0, no_patch: 0, abandoned: 0, failed: 0, boundaries: 3, deficits: "person 3/40".into(), cost: 1.5, wall_secs: 9.0 }]; + let atlas = render_atlas(&header, &world, &seen, &rows, &recorder); + let group = atlas.find("### The Queens' Council\n\n#### Hive Hall").expect("people sit under their institution, then place"); + assert!(atlas.find("## People").unwrap() < group); + assert!(atlas.contains("Vel"), "{atlas}"); + assert!(atlas.contains("added in sweep 0, Begin's seed") || atlas.contains("Added in sweep 0, Begin's seed")); + assert!(atlas.contains("sweep 2, Charter")); + assert!(atlas.contains("Hive customs (Civilizations/Hive.md)"), "a query that named the place gives its note to the entry"); + assert!(atlas.contains("Sing the brood awake")); + assert!(atlas.contains("| 3 | 2 | 1 | 3 | 1 | 2 | 2 |"), "the counts row: {atlas}"); + } + + #[test] + fn the_options_default_to_the_ruled_scale_and_a_two_call_ceiling() { + let options = AtlasOptions::from_reader(|name| (name == "GHOSTLIGHT_ATLAS_OUT").then(|| "/tmp/x".to_owned())).unwrap(); + assert_eq!((options.persons, options.institutions, options.populations), (40, 12, 6)); + assert_eq!((options.concurrency, options.cost_cap), (2, 40.0)); + assert_eq!((options.vault.as_str(), options.era.as_str()), ("zyphos", "imperial-present")); + let scale = options.scale(); + assert_eq!(scale.targets[&SubjectKind::Person], 40); + assert_eq!(scale.sweep_permits, 2); + assert!(AtlasOptions::from_reader(|_| None).is_err(), "no output directory is refused"); + } +} diff --git a/scripts/playtest-yggdrasil.sh b/scripts/playtest-yggdrasil.sh index e094c04..0fe1798 100644 --- a/scripts/playtest-yggdrasil.sh +++ b/scripts/playtest-yggdrasil.sh @@ -4,6 +4,13 @@ # # scripts/playtest-yggdrasil.sh [--turns N] [--worlds id,id] [--wall-minutes M] # [--out DIR] [--rev REV] +# scripts/playtest-yggdrasil.sh --atlas [--set NAME=VALUE ...] [--rev REV] +# +# --atlas runs the elaboration-only world atlas (playtest::atlas::live_atlas) instead of +# the play-through; each --set becomes an environment variable of the unit. The atlas knobs +# are GHOSTLIGHT_ATLAS_{VAULT,ERA,PERSONS,INSTITUTIONS,POPULATIONS,SWEEPS,SWEEP_SESSIONS, +# SEED_SESSIONS,COST_CAP,CONCURRENCY}; set GHOSTLIGHT_CONTROLLER_MAX_CONCURRENT (the pool Begin +# seeds under) to the same concurrency, or the run refuses to start. # # Defaults: every world in crates/ghostlight-dungeon/playtest/plan.json, 12 turns # per character, 240 minutes of wall time. Run it from a worktree with the @@ -17,7 +24,7 @@ set -euo pipefail IMAGE=${IMAGE:-eureka-verify-rust:b99d30ec441e} KEY=${KEY:-/etc/gamecult/claude-connector/connection-ghostlight.key} CONNECTOR_ADDR=${CONNECTOR_ADDR:-127.0.0.1:4110} -turns=""; worlds=""; wall=""; out=""; rev=""; on_host=0; stamp="" +turns=""; worlds=""; wall=""; out=""; rev=""; on_host=0; stamp=""; atlas=0; sets=() while [ $# -gt 0 ]; do case "$1" in --turns) turns=$2; shift 2 ;; @@ -27,6 +34,8 @@ while [ $# -gt 0 ]; do --rev) rev=$2; shift 2 ;; --on-host) on_host=1; shift ;; --stamp) stamp=$2; shift 2 ;; + --atlas) atlas=1; shift ;; + --set) sets+=("$2"); shift 2 ;; *) echo "unknown argument $1" >&2; exit 2 ;; esac done @@ -41,6 +50,8 @@ if [ "$on_host" = 0 ]; then [ -n "$worlds" ] && args="$args --worlds $worlds" [ -n "$wall" ] && args="$args --wall-minutes $wall" [ -n "$out" ] && args="$args --out $out" + [ "$atlas" = 1 ] && args="$args --atlas" + for kv in "${sets[@]}"; do args="$args --set $kv"; done RUN_ON_HOST=1 TIMEOUT=3000 bash "$verify" "$here" "$rev" "$IMAGE" "bash scripts/playtest-yggdrasil.sh $args" exit $? fi @@ -66,11 +77,13 @@ if [ ! -x "$bin" ]; then fi test -x "$bin" -unit=ghostlight-playtest-$stamp +if [ "$atlas" = 1 ]; then kind=atlas; test_name=playtest::atlas::live_atlas; else kind=playtest; test_name=playtest::live_playtest; fi +unit=ghostlight-$kind-$stamp env_args=(--setenv=GHOSTLIGHT_CONNECTOR_ADDR="$CONNECTOR_ADDR" --setenv=GHOSTLIGHT_CONNECTOR_KEY_FILE="/run/credentials/$unit.service/connector-key" --setenv=GHOSTLIGHT_VAULT_BASE="${VAULT_BASE:-$base/vaults}" - --setenv=GHOSTLIGHT_PLAYTEST_OUT="$out" --setenv=GHOSTLIGHT_PLAYTEST_STAMP="$stamp") + --setenv=GHOSTLIGHT_PLAYTEST_OUT="$out" --setenv=GHOSTLIGHT_PLAYTEST_STAMP="$stamp" --setenv=GHOSTLIGHT_ATLAS_STAMP="$stamp") +for kv in "${sets[@]}"; do env_args+=(--setenv="$kv"); done [ -n "$turns" ] && env_args+=(--setenv=GHOSTLIGHT_PLAYTEST_TURNS="$turns") [ -n "$worlds" ] && env_args+=(--setenv=GHOSTLIGHT_PLAYTEST_WORLDS="$worlds") [ -n "$wall" ] && env_args+=(--setenv=GHOSTLIGHT_PLAYTEST_WALL_MINUTES="$wall") @@ -80,7 +93,7 @@ sudo systemd-run --unit "$unit" --collect --quiet \ -p User="$(id -un)" -p LoadCredential=connector-key:"$KEY" \ -p StandardOutput=append:"$out/$stamp.run.log" -p StandardError=append:"$out/$stamp.run.log" \ "${env_args[@]}" \ - "$bin" --ignored --exact playtest::live_playtest --nocapture --test-threads=1 + "$bin" --ignored --exact "$test_name" --nocapture --test-threads=1 echo "unit: $unit" echo "output: $out/$stamp"