diff --git a/crates/ghostlight-dungeon/src/api.rs b/crates/ghostlight-dungeon/src/api.rs index 15ef1ba..3851581 100644 --- a/crates/ghostlight-dungeon/src/api.rs +++ b/crates/ghostlight-dungeon/src/api.rs @@ -7,7 +7,8 @@ use crate::{ auth_guard::{BEGIN_COOKIE, BEGIN_TTL_SECONDS}, heimdall::AuthBeginReceipt, - begin::{BeginRequest, begin}, + begin::{BeginRequest, SeedStatus, begin}, + run_ahead::{evidence_of, run_ahead}, play::{Admission, OpenQuestion, PlayError, PlayRequest, PlayTurnState, PlayTurnView}, runtime::AppState, }; @@ -178,8 +179,15 @@ async fn timelines(headers: HeaderMap, State(state): State) -> Respons .timelines_of(account) .into_iter() .map(|(timeline, world)| { + let (status, reason) = match state.seeding.status(&timeline.id) { + None => ("ready", None), + Some(SeedStatus::Seeding) => ("seeding", None), + Some(SeedStatus::Failed(reason)) => ("failed", Some(reason)), + }; json!({ "timeline": timeline.id, + "status": status, + "reason": reason, "worldId": world.world_id, "title": world.title, "parent": timeline.parent, @@ -223,6 +231,7 @@ async fn begin_world( &state.catalog, &state.timelines, state.vaults.as_ref(), + &state.seeding, &principal, BeginRequest { key: body.key, @@ -284,6 +293,7 @@ async fn play( tracing::warn!(%error, "the player's pointer could not move"); } } + let timeline = body.timeline.clone(); let host = match state.timelines.host(&body.timeline).await { Ok(host) => host, Err(error) => { @@ -343,12 +353,26 @@ async fn play( }; let _ = host.changes.send(()); let spawned = host.clone(); + let state = state.clone(); tokio::spawn(async move { - if let Err(error) = spawned.play.execute(admitted, &principal).await { + let ran = spawned.play.execute(admitted, &principal).await; + if let Err(error) = &ran { let turn_id = spawned.play.current_turn_view().await.map(|view| view.turn_id); tracing::warn!(%error, ?turn_id, "a play turn ended in error"); } let _ = spawned.changes.send(()); + // The turn is closed: answer some of the world's deficit ahead of play. + let closed = ran.is_ok() + && spawned + .play + .current_turn_view() + .await + .is_some_and(|view| view.state == PlayTurnState::Closed); + if closed + && let Some(evidence) = evidence_of(&state.catalog, state.vaults.as_ref(), &timeline).await + { + run_ahead(&spawned, evidence, &state.seeding.scale).await; + } }); reply(StatusCode::ACCEPTED, json!({"outcome": "accepted"})) } @@ -669,7 +693,7 @@ mod tests { use super::*; use crate::{ app_session::AppSessionOwner, - begin::tests::{Rig, one_vault, principal, rig}, + begin::tests::{Rig, author, deferred_rig, eventually, one_vault, principal, rig}, heimdall::{ AccountSummary, AuthBeginReceipt, AuthCompletionReceipt, AuthNavigation, AuthProvider, HeimdallPort, SessionRefresher, VerifiedSessionAdmission, VerifiedSessionRefresh, @@ -802,7 +826,10 @@ mod tests { /// An app over a scripted model with one signed-in session per entry of /// `accounts` (the same account twice is the same player on two devices). async fn app(script: Vec, accounts: &[&str]) -> App { - let rig = rig(script); + app_over(rig(script), accounts).await + } + + async fn app_over(rig: Rig, accounts: &[&str]) -> App { let key = rig.directory.path().join("session.key"); std::fs::write(&key, [17_u8; 32]).unwrap(); let mut sessions = @@ -830,6 +857,7 @@ mod tests { catalog: rig.catalog.clone(), timelines: rig.timelines.clone(), vaults: one_vault(), + seeding: rig.seeding.clone(), sessions: Arc::new(Mutex::new(sessions)), heimdall: heimdall.clone(), auth: Arc::default(), @@ -952,6 +980,50 @@ mod tests { assert_eq!(status, StatusCode::UNAUTHORIZED); } + /// Spec test: POST /api/begin on a vault returns the timeline before the + /// seed has finished; the timeline list reads Seeding, then Ready; and a + /// failed seed reads Failed with a reason that names no endpoint. + #[tokio::test] + async fn a_vault_begin_returns_at_once_and_the_timeline_reads_seeding_then_ready_or_failed() { + let app = app_over(deferred_rig(), &["alice"]).await; + let cookie = app.cookies[0].clone(); + let begin = |key: Uuid| json!({"key": key, "title": "Ashfall", "name": "Deru", "vault": "delvehold"}); + let status_of = async |timeline: &str| { + let (status, _, body) = call(&app, Method::GET, "/api/timelines", Some(&cookie), None).await; + assert_eq!(status, StatusCode::OK); + body["timelines"] + .as_array() + .unwrap() + .iter() + .find(|row| row["timeline"] == timeline) + .map(|row| (row["status"].as_str().unwrap().to_owned(), row["reason"].clone())) + }; + + let (code, _, body) = call(&app, Method::POST, "/api/begin", Some(&cookie), Some(begin(Uuid::new_v4()))).await; + assert_eq!(code, StatusCode::OK, "{body}"); + assert_eq!(body["reached"], "seeding"); + let timeline = body["timeline"].as_str().unwrap().to_owned(); + assert_eq!(status_of(&timeline).await.unwrap().0, "seeding"); + + let host = app.state.timelines.host(&timeline).await.unwrap(); + let draft = host.world.snapshot().await.unwrap(); + app.rig.port.push(Ok(author("seed-1", &draft, &["a", "b"]))); + app.rig.port.push(Ok(author("seed-2", &draft, &["c", "d"]))); + eventually(async || (status_of(&timeline).await.unwrap().0 == "ready").then_some(())).await; + + let (code, _, body) = call(&app, Method::POST, "/api/begin", Some(&cookie), Some(begin(Uuid::new_v4()))).await; + assert_eq!(code, StatusCode::OK, "{body}"); + let failing = body["timeline"].as_str().unwrap().to_owned(); + app.rig.port.push(Err("http://10.0.0.7:9/secret endpoint down")); + let (state, reason) = eventually(async || { + status_of(&failing).await.filter(|(state, _)| state == "failed") + }) + .await; + assert_eq!(state, "failed"); + let reason = reason.as_str().unwrap(); + assert!(reason.contains("seed") && !reason.contains("10.0.0.7"), "{reason}"); + } + #[tokio::test] async fn logout_revokes_the_cookie_even_when_heimdall_is_unreachable() { let app = app(vec![], &["alice"]).await; diff --git a/crates/ghostlight-dungeon/src/begin.rs b/crates/ghostlight-dungeon/src/begin.rs index b3e0df9..0ef0fae 100644 --- a/crates/ghostlight-dungeon/src/begin.rs +++ b/crates/ghostlight-dungeon/src/begin.rs @@ -2,57 +2,154 @@ //! //! The player gives a title, a name, an optional brief and an optional vault //! profile. Begin creates the world through the kernel, records the world and -//! its root timeline in the catalog, seeds from the vault snapshot when a -//! profile was chosen, then approves and activates. With no profile the world -//! activates unseeded. Every kernel command is a separate command with a -//! derived id, so replaying the same key resumes where the last attempt -//! stopped and never repeats what the kernel already committed. +//! its root timeline in the catalog, then approves and activates. With no +//! profile the world activates unseeded and empty. With one it states a scale +//! intent (one `start` jurisdiction and per-kind targets) so the kernel derives +//! a deficit, and the seed lane answers a first piece of it in the background +//! before the world activates: Begin returns the timeline at once and the +//! timeline's status reads Seeding, Ready or Failed. Every kernel command is a +//! separate command with a derived id, so replaying the same key resumes where +//! the last attempt stopped and never repeats what the kernel already +//! committed. use crate::{ catalog::{Catalog, Timeline, WorldRecord, timeline_id}, + run_ahead::run_ahead, timelines::{TimelineHost, Timelines}, }; use chrono::Utc; use ghostlight::{ - CommandBody, CommandId, ControllerError, CreateWorldIntent, EvidenceSource, Lens, LensWeights, - MailboxError, PrincipalCommandIntent, SeedPort, VerifiedPrincipalEvidence, WorldPhase, - WorldSnapshot, + CommandBody, CommandId, ControllerError, CreateJurisdictionIntent, CreateWorldIntent, + EvidenceSource, Lens, LensWeights, MailboxError, PrincipalCommandIntent, SeedPort, SubjectKind, + VerifiedPrincipalEvidence, WorldPhase, WorldSnapshot, }; use sha2::{Digest, Sha256}; use std::{collections::BTreeMap, sync::Arc}; use tokio::sync::Mutex; use uuid::Uuid; -/// Seeding sessions Begin may spend before approving. Each session is one -/// model round trip, so this is the credit bound of a Begin. -const BEGIN_SEED_SESSIONS: usize = 8; +/// The handle of the one jurisdiction root a vault-seeded world declares. Every +/// derived boundary the world later grows sits under it. +const START_HANDLE: &str = "start"; -/// A vault snapshot ready to seed from: its content id and the evidence -/// source that reads only that snapshot. +/// What a vault-seeded Begin asks of the world, and how much it spends before +/// returning. Two seed sessions author the first place cluster and its first +/// people so Begin is back in about a minute; the rest of the deficit, and +/// every boundary derived from it, is answered by Active elaboration after +/// play starts. An unseeded Begin states no targets at all. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Scale { + /// World-wide target of goal-bearing subjects per kind. + pub(crate) targets: BTreeMap, + /// Seed sessions Begin may spend before approving: the credit bound of a + /// Begin, one model round trip each. + pub(crate) seed_sessions: usize, + /// Elaboration sessions one run-ahead trigger may start. + pub(crate) sweep_sessions: usize, + /// Permits one run-ahead sweep may hold at once. + pub(crate) sweep_permits: usize, +} + +const DEFAULT_PERSON_TARGET: u32 = 8; +const DEFAULT_INSTITUTION_TARGET: u32 = 2; +const DEFAULT_POPULATION_TARGET: u32 = 1; +const DEFAULT_SEED_SESSIONS: usize = 2; +const DEFAULT_SWEEP_SESSIONS: usize = 4; +const DEFAULT_SWEEP_PERMITS: usize = 2; + +impl Scale { + pub(crate) fn from_env() -> Self { + Self::from_reader(|name| std::env::var(name).ok()) + } + + pub(crate) fn from_reader(read: impl Fn(&str) -> Option) -> Self { + fn number(read: &impl Fn(&str) -> Option, name: &str, default: T) -> T { + read(name).and_then(|value| value.trim().parse().ok()).unwrap_or(default) + } + Self { + targets: BTreeMap::from([ + (SubjectKind::Person, number(&read, "GHOSTLIGHT_BEGIN_PERSON_TARGET", DEFAULT_PERSON_TARGET)), + ( + SubjectKind::Institution, + number(&read, "GHOSTLIGHT_BEGIN_INSTITUTION_TARGET", DEFAULT_INSTITUTION_TARGET), + ), + ( + SubjectKind::Population, + number(&read, "GHOSTLIGHT_BEGIN_POPULATION_TARGET", DEFAULT_POPULATION_TARGET), + ), + ]), + seed_sessions: number(&read, "GHOSTLIGHT_BEGIN_SEED_SESSIONS", DEFAULT_SEED_SESSIONS), + sweep_sessions: number(&read, "GHOSTLIGHT_SWEEP_SESSIONS", DEFAULT_SWEEP_SESSIONS), + sweep_permits: number(&read, "GHOSTLIGHT_SWEEP_PERMITS", DEFAULT_SWEEP_PERMITS).max(1), + } + } +} + +/// Where a timeline stands, as the page shows it. Display-only: nothing reads +/// it back to decide anything, and a timeline with no entry reads as Ready. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum SeedStatus { + Seeding, + Failed(String), +} + +/// The scale a Begin states and the status of the seeds in flight. +pub(crate) struct Seeding { + pub(crate) scale: Scale, + status: std::sync::Mutex>, +} + +impl Seeding { + pub(crate) fn new(scale: Scale) -> Self { + Self { + scale, + status: std::sync::Mutex::new(BTreeMap::new()), + } + } + + pub(crate) fn status(&self, timeline: &str) -> Option { + self.status.lock().unwrap().get(timeline).cloned() + } + + /// Claims the seed of `timeline`; false when one is already running. + fn claim(&self, timeline: &str) -> bool { + let mut status = self.status.lock().unwrap(); + if status.get(timeline) == Some(&SeedStatus::Seeding) { + return false; + } + status.insert(timeline.to_owned(), SeedStatus::Seeding); + true + } + + fn settle(&self, timeline: &str, outcome: Result<(), &BeginError>) { + let mut status = self.status.lock().unwrap(); + match outcome { + Ok(()) => { + status.remove(timeline); + } + Err(error) => { + status.insert(timeline.to_owned(), SeedStatus::Failed(error.to_string())); + } + } + } +} + +/// A vault snapshot ready to seed from: its content id, the evidence source +/// that reads only that snapshot, and the deterministic premise a seed falls +/// back on when the player gave no brief. pub(crate) struct VaultSeed { pub(crate) snapshot_id: String, pub(crate) evidence: Arc, + pub(crate) premise: Option, } /// The vault profiles a player may choose at Begin. Opening one yields the -/// snapshot to seed from. +/// snapshot to seed from; `evidence` reopens a snapshot a world was already +/// bound to. pub(crate) trait Vaults: Send + Sync { fn names(&self) -> Vec; fn open(&self, profile: &str) -> anyhow::Result; -} - -/// No profile is configured: every Begin activates unseeded. Cut 1c replaces -/// this with the snapshot-backed profile catalog once vault import lands. -pub(crate) struct NoVaults; - -impl Vaults for NoVaults { - fn names(&self) -> Vec { - Vec::new() - } - - fn open(&self, profile: &str) -> anyhow::Result { - anyhow::bail!("vault profile `{profile}` is not configured") - } + fn evidence(&self, snapshot_id: &str) -> anyhow::Result>; } pub(crate) struct BeginRequest { @@ -138,6 +235,7 @@ pub(crate) async fn begin( catalog: &Mutex, timelines: &Timelines, vaults: &dyn Vaults, + seeding: &Arc, principal: &VerifiedPrincipalEvidence, request: BeginRequest, ) -> Result { @@ -167,6 +265,17 @@ pub(crate) async fn begin( .map_err(|error| stopped("open", error))?; let brief = request.brief.unwrap_or_default(); + let (targets, jurisdictions) = match &vault { + Some(_) => ( + seeding.scale.targets.clone(), + vec![CreateJurisdictionIntent { + handle: START_HANDLE.into(), + label: request.title.clone(), + permille: 1000, + }], + ), + None => (BTreeMap::new(), Vec::new()), + }; let world_id = match current(&host).await.map_err(|error| from_mailbox("create", error))? { Some(world) => world.world_id, None => { @@ -179,8 +288,8 @@ pub(crate) async fn begin( human_subject_label: request.name, narrative_persona_label: None, operational_agent_label: None, - targets: BTreeMap::new(), - jurisdictions: Vec::new(), + targets, + jurisdictions, lens_weights: uniform_lens_weights(), }, principal, @@ -216,48 +325,119 @@ pub(crate) async fn begin( } } - let mut reached = "created"; - if let Some(world) = current(&host).await.map_err(|error| from_mailbox("seed", error))? - && world.phase == WorldPhase::Draft - { - if let Some(vault) = vault { - let runner = host.controllers.seeder( - SeedPort::new(host.world.clone(), principal.clone()), - vault.evidence, - (!brief.is_empty()).then_some(brief), - ); - runner.sweep(BEGIN_SEED_SESSIONS).await.map_err(|error| { + let draft = current(&host) + .await + .map_err(|error| from_mailbox("seed", error))? + .is_some_and(|world| world.phase == WorldPhase::Draft); + let reached = match (draft, vault) { + (false, _) => "activated", + (true, None) => { + finish(&host, principal, key, world_id).await?; + "activated" + } + (true, Some(vault)) => { + if seeding.claim(&timeline) { + let seed_brief = (!brief.is_empty()) + .then_some(brief) + .or_else(|| vault.premise.clone()); + let seed = Seed { + timeline: timeline.clone(), + host, + principal: principal.clone(), + key, + world_id, + evidence: vault.evidence, + brief: seed_brief, + seeding: seeding.clone(), + }; + tokio::spawn(seed.run()); + } + "seeding" + } + }; + Ok(Begun { timeline, reached }) +} + +/// Approves and activates a Draft world, each a separate derived command. +async fn finish( + host: &TimelineHost, + principal: &VerifiedPrincipalEvidence, + key: Uuid, + world_id: ghostlight::WorldId, +) -> Result<(), BeginError> { + for (name, body) in [ + ("approve", CommandBody::ApproveDraft), + ("activate", CommandBody::ActivateWorld), + ] { + let world = current(host) + .await + .map_err(|error| from_mailbox(name, error))? + .ok_or_else(|| stopped(name, "the world could not be read"))?; + host.world + .submit_principal( + PrincipalCommandIntent { + id: derived_step_id(key, name)?, + world_id, + expected_revision: world.revision, + body, + }, + principal, + ) + .await + .map_err(|error| from_mailbox(name, error))?; + } + Ok(()) +} + +/// A vault Begin's background half: the seed sessions, then approval and +/// activation, then the first run-ahead sweep. Its outcome is the timeline's +/// status. +struct Seed { + timeline: String, + host: Arc, + principal: VerifiedPrincipalEvidence, + key: Uuid, + world_id: ghostlight::WorldId, + evidence: Arc, + brief: Option, + seeding: Arc, +} + +impl Seed { + async fn run(self) { + let outcome = self.seed_and_activate().await; + self.seeding.settle(&self.timeline, outcome.as_ref().map(|_| ())); + if let Err(error) = &outcome { + tracing::warn!(%error, timeline = %self.timeline, "a seeded begin stopped"); + return; + } + run_ahead(&self.host, self.evidence.clone(), &self.seeding.scale).await; + } + + async fn seed_and_activate(&self) -> Result<(), BeginError> { + let runner = self.host.controllers.seeder( + SeedPort::new(self.host.world.clone(), self.principal.clone()), + self.evidence.clone(), + self.brief.clone(), + ); + runner + .sweep(self.seeding.scale.seed_sessions) + .await + .map_err(|error| { tracing::warn!(%error, "seeding a world could not complete"); stopped("seed", describe_seed_failure(&error)) })?; - reached = "seeded"; + // A seed that answered nothing leaves the Draft as it was: the world + // is not activated empty, and the same key seeds it again. + let world = current(&self.host) + .await + .map_err(|error| from_mailbox("seed", error))? + .ok_or_else(|| stopped("seed", "the world could not be read"))?; + if !world.scale_deficit.is_empty() && world.scale_deficit.iter().all(|row| row.qualified == 0) { + return Err(stopped("seed", "seeding authored no one")); } - for (name, body, done) in [ - ("approve", CommandBody::ApproveDraft, "approved"), - ("activate", CommandBody::ActivateWorld, "activated"), - ] { - let world = current(&host) - .await - .map_err(|error| from_mailbox(name, error))? - .ok_or_else(|| stopped(name, "the world could not be read"))?; - host.world - .submit_principal( - PrincipalCommandIntent { - id: derived_step_id(key, name)?, - world_id, - expected_revision: world.revision, - body, - }, - principal, - ) - .await - .map_err(|error| from_mailbox(name, error))?; - reached = done; - } - } else { - reached = "activated"; + finish(&self.host, &self.principal, self.key, self.world_id).await } - Ok(Begun { timeline, reached }) } /// A seed failure reaches the player as a category, never as the error's own @@ -291,15 +471,24 @@ pub(crate) mod tests { pub(crate) catalog: Arc>, pub(crate) timelines: Arc, pub(crate) port: Arc, + pub(crate) seeding: Arc, _fatal: mpsc::UnboundedReceiver, } /// One catalog and one timeline registry over a scripted inference port. pub(crate) fn rig(script: Vec) -> Rig { + rig_over(ScriptedPort::new(script)) + } + + /// The same over a port that waits for the test to answer. + pub(crate) fn deferred_rig() -> Rig { + rig_over(ScriptedPort::deferred()) + } + + fn rig_over(port: Arc) -> Rig { let directory = tempfile::tempdir().unwrap(); let root = std::fs::canonicalize(directory.path()).unwrap(); crate::state_layout::prepare_admitted_state_layout(&root).unwrap(); - let port = ScriptedPort::new(script); let (fatal, receiver) = mpsc::unbounded_channel(); let timelines = Timelines::new( root.clone(), @@ -321,6 +510,7 @@ pub(crate) mod tests { catalog: Arc::new(Mutex::new(Catalog::open(root.join("catalog.cc")).unwrap())), timelines: Arc::new(timelines), port, + seeding: Arc::new(Seeding::new(Scale::from_reader(|_| None))), directory, _fatal: receiver, } @@ -340,17 +530,30 @@ pub(crate) mod tests { } } - struct OneVault; + /// A vault of one note, imported the way production imports one, so the + /// seed and the elaborator read real snapshot receipts. + pub(crate) struct OneVault { + evidence: Arc, + _vault: tempfile::TempDir, + } - struct EmptyEvidence; + pub(crate) const NOTE: &str = "The breakwater of Ashfall is haunted by gulls that remember every wreck."; - #[async_trait::async_trait] - impl EvidenceSource for EmptyEvidence { - async fn retrieve( - &self, - _query: &ghostlight::EvidenceQuery, - ) -> Result, ghostlight::EvidenceError> { - Ok(Vec::new()) + impl OneVault { + pub(crate) fn new() -> Self { + let vault = tempfile::tempdir().unwrap(); + std::fs::write(vault.path().join("Ashfall.md"), format!("{NOTE}\n")).unwrap(); + let snapshot = ghostlight::VaultSnapshot::build(&ghostlight::VaultProfile { + name: "delvehold".into(), + root: vault.path().to_path_buf(), + ..ghostlight::VaultProfile::default() + }) + .unwrap(); + let evidence = ghostlight::VaultEvidenceSource::from_snapshot(&snapshot, "").unwrap(); + Self { + evidence: Arc::new(evidence), + _vault: vault, + } } } @@ -362,45 +565,218 @@ pub(crate) mod tests { fn open(&self, profile: &str) -> anyhow::Result { anyhow::ensure!(profile == "delvehold", "unknown profile"); Ok(VaultSeed { - snapshot_id: "vault-snapshot:feedface".into(), - evidence: Arc::new(EmptyEvidence), + snapshot_id: "feedface".into(), + evidence: self.evidence.clone(), + premise: Some("A cold harbor, from the vault.".into()), }) } + + fn evidence(&self, snapshot_id: &str) -> anyhow::Result> { + anyhow::ensure!(snapshot_id == "feedface", "unknown snapshot"); + Ok(self.evidence.clone()) + } + } + + /// An empty catalog: every Begin in a test that wants no vault. + pub(crate) struct NoVaults; + + impl Vaults for NoVaults { + fn names(&self) -> Vec { + Vec::new() + } + + fn open(&self, profile: &str) -> anyhow::Result { + anyhow::bail!("vault profile `{profile}` is not configured") + } + + fn evidence(&self, _: &str) -> anyhow::Result> { + anyhow::bail!("no snapshots") + } } pub(crate) fn one_vault() -> Arc { - Arc::new(OneVault) + Arc::new(OneVault::new()) } - #[tokio::test] - async fn begin_with_a_profile_binds_the_snapshot_and_activates() { - let rig = rig(vec![output("seed-1", vec![])]); - let alice = principal("alice"); - let begun = begin(&rig.catalog, &rig.timelines, &OneVault, &alice, request(Uuid::new_v4(), Some("delvehold"))) + /// Calls the seed session answers with: a patch declaring `handles` as + /// people under the `start` root, each with a controller, the Speak entry, + /// a position and a goal. + pub(crate) fn author(receipt: &str, world: &WorldSnapshot, handles: &[&str]) -> ghostlight::InferenceOutput { + let root = world.places.iter().find(|place| place.label == "Ashfall").unwrap().id; + let speak = world.affordances.iter().find(|entry| entry.entry.kind.0 == "speak").unwrap().id; + let (root, speak) = (serde_json::to_value(root).unwrap(), serde_json::to_value(speak).unwrap()); + let mut calls = Vec::new(); + for handle in handles { + calls.push(( + "declare_subject", + serde_json::json!({ + "handle": handle, + "label": format!("Gull-keeper {handle}"), + "kind": "person", + "controller": {"type": "narrative_persona"}, + "affordances": [{"ref": "existing", "value": speak}], + "position": {"ref": "existing", "value": root}, + }), + )); + calls.push(( + "create_commitment", + serde_json::json!({ + "subject": {"ref": "draft", "value": handle}, + "counterparty": null, + "kind": "goal", + "due": 600, + "period": null, + "checks": [], + "statement": "Keep the harbor lamps lit through the winter.", + }), + )); + } + calls.push(("submit", serde_json::json!({}))); + output( + receipt, + calls + .into_iter() + .enumerate() + .map(|(index, (name, arguments))| ghostlight::InferenceEvent::ToolCall { + call_id: format!("call-{index}"), + name: name.to_owned(), + arguments: arguments.to_string(), + }) + .collect(), + ) + } + + /// Everything the model was shown in one request. + fn prompt_text(request: &ghostlight::InferenceRequest) -> String { + let mut text = request.provider.instructions.clone(); + for item in &request.provider.input { + if let model_connector::InputItem::UserText { text: more } = item { + text.push_str(more); + } + } + text + } + + pub(crate) async fn eventually(mut probe: impl AsyncFnMut() -> Option) -> T { + for _ in 0..400 { + if let Some(found) = probe().await { + return found; + } + tokio::time::sleep(std::time::Duration::from_millis(25)).await; + } + panic!("the awaited state never came"); + } + + async fn begin_vault(rig: &Rig, key: Uuid) -> Begun { + begin(&rig.catalog, &rig.timelines, &OneVault::new(), &rig.seeding, &principal("alice"), request(key, Some("delvehold"))) .await - .unwrap(); - assert_eq!(begun.reached, "activated"); - let catalog = rig.catalog.lock().await; - let (timeline, world) = catalog.owned_timeline("alice", &begun.timeline).unwrap(); - assert_eq!(world.snapshot_id.as_deref(), Some("vault-snapshot:feedface")); - assert!(timeline.parent.is_none()); - assert_eq!(catalog.player("alice").unwrap().timeline.as_deref(), Some(begun.timeline.as_str())); - drop(catalog); - // A world with no scale targets has no deficit, so the seed lane finds - // it clean and asks no model; the snapshot binding still stands. - assert!(rig.port.seen_requests().is_empty()); + .unwrap() + } + + /// Spec test: with the defaults a vault Begin has a deficit before it + /// seeds, a Person row under `start` of target 8, and returns before the + /// seed has asked the model anything. + #[tokio::test] + async fn a_vault_begin_returns_at_once_with_a_deficit_to_seed() { + let rig = deferred_rig(); + let begun = begin_vault(&rig, Uuid::new_v4()).await; + assert_eq!(begun.reached, "seeding"); + assert_eq!(rig.seeding.status(&begun.timeline), Some(SeedStatus::Seeding)); let host = rig.timelines.host(&begun.timeline).await.unwrap(); - assert_eq!(host.world.snapshot().await.unwrap().phase, WorldPhase::Active); + let world = host.world.snapshot().await.unwrap(); + assert_eq!(world.phase, WorldPhase::Draft); + let person = world + .scale_deficit + .iter() + .find(|row| row.kind == SubjectKind::Person) + .expect("a Person row exists only under a declared jurisdiction"); + assert_eq!((person.target, person.deficit), (8, 8)); + assert!(world.scale_deficit.iter().any(|row| row.kind == SubjectKind::Institution && row.target == 2)); + assert!(world.scale_deficit.iter().any(|row| row.kind == SubjectKind::Population && row.target == 1)); + assert!(world.places.iter().any(|place| place.label == "Ashfall"), "the root is the title"); + assert_eq!( + rig.catalog.lock().await.owned_timeline("alice", &begun.timeline).unwrap().1.snapshot_id.as_deref(), + Some("feedface") + ); + } + + /// Spec test: seeding calls the model with the vault's evidence behind it, + /// commits qualifying people, activates, and the status reads Ready; the + /// remaining deficit is then answered in Active under the run-ahead bound, + /// the elaborator reading the same snapshot. + #[tokio::test] + async fn a_seeded_begin_commits_people_activates_and_runs_ahead_on_the_snapshot() { + let rig = deferred_rig(); + let begun = begin_vault(&rig, Uuid::new_v4()).await; + let host = rig.timelines.host(&begun.timeline).await.unwrap(); + let draft = host.world.snapshot().await.unwrap(); + rig.port.push(Ok(author("seed-1", &draft, &["a", "b"]))); + rig.port.push(Ok(author("seed-2", &draft, &["c", "d"]))); + + let world = eventually(async || { + let world = host.world.snapshot().await.unwrap(); + (world.phase == WorldPhase::Active && rig.seeding.status(&begun.timeline).is_none()).then_some(world) + }) + .await; + let person = world.scale_deficit.iter().find(|row| row.kind == SubjectKind::Person).unwrap(); + assert_eq!((person.target, person.qualified, person.deficit), (8, 4, 4)); + let seed = rig.port.seen_requests(); + assert!( + seed.iter().take(2).all(|request| request.purpose == ghostlight::InferencePurpose::Elaboration), + "two seed sessions asked the model" + ); + assert!( + prompt_text(&seed[0]).contains("A cold harbor, from the vault."), + "the vault's premise stood in for the missing brief" + ); + + // Run-ahead: the Active world's elaborator sits on the nonzero `start` + // row, and what it is shown is the snapshot's own receipt. + eventually(async || { + rig.port + .seen_requests() + .into_iter() + .skip(2) + .find(|request| prompt_text(request).contains(NOTE)) + }) + .await; + } + + /// Spec test: a seed fault reads Failed with a category and no endpoint + /// text, leaves the world a Draft, and the same key seeds it again. + #[tokio::test] + async fn a_seed_fault_reads_failed_and_the_same_key_seeds_again() { + let rig = deferred_rig(); + let key = Uuid::new_v4(); + let begun = begin_vault(&rig, key).await; + rig.port.push(Err("http://10.0.0.7:9/secret endpoint down")); + let status = eventually(async || match rig.seeding.status(&begun.timeline) { + Some(SeedStatus::Failed(reason)) => Some(reason), + _ => None, + }) + .await; + assert!(!status.contains("10.0.0.7") && !status.contains("http"), "{status}"); + let host = rig.timelines.host(&begun.timeline).await.unwrap(); + assert_eq!(host.world.snapshot().await.unwrap().phase, WorldPhase::Draft); + + let again = begin_vault(&rig, key).await; + assert_eq!((again.timeline.as_str(), again.reached), (begun.timeline.as_str(), "seeding")); + assert_eq!(rig.seeding.status(&begun.timeline), Some(SeedStatus::Seeding)); } #[tokio::test] async fn begin_without_a_profile_activates_unseeded_and_asks_no_model() { let rig = rig(vec![]); - let begun = begin(&rig.catalog, &rig.timelines, &NoVaults, &principal("alice"), request(Uuid::new_v4(), None)) + let begun = begin(&rig.catalog, &rig.timelines, &NoVaults, &rig.seeding, &principal("alice"), request(Uuid::new_v4(), None)) .await .unwrap(); assert_eq!(begun.reached, "activated"); assert!(rig.port.seen_requests().is_empty()); + let host = rig.timelines.host(&begun.timeline).await.unwrap(); + let world = host.world.snapshot().await.unwrap(); + assert_eq!(world.phase, WorldPhase::Active); + assert!(world.scale_deficit.is_empty(), "an unseeded Begin states no targets"); + assert_eq!(rig.seeding.status(&begun.timeline), None); let catalog = rig.catalog.lock().await; assert_eq!(catalog.owned_timeline("alice", &begun.timeline).unwrap().1.snapshot_id, None); } @@ -408,7 +784,7 @@ pub(crate) mod tests { #[tokio::test] async fn an_unknown_profile_refuses_the_begin_before_anything_is_made() { let rig = rig(vec![]); - let error = begin(&rig.catalog, &rig.timelines, &OneVault, &principal("alice"), request(Uuid::new_v4(), Some("nowhere"))) + let error = begin(&rig.catalog, &rig.timelines, &OneVault::new(), &rig.seeding, &principal("alice"), request(Uuid::new_v4(), Some("nowhere"))) .await .err() .unwrap(); @@ -422,8 +798,8 @@ pub(crate) mod tests { let rig = rig(vec![]); let alice = principal("alice"); let key = Uuid::new_v4(); - let first = begin(&rig.catalog, &rig.timelines, &NoVaults, &alice, request(key, None)).await.unwrap(); - let again = begin(&rig.catalog, &rig.timelines, &NoVaults, &alice, request(key, None)).await.unwrap(); + let first = begin(&rig.catalog, &rig.timelines, &NoVaults, &rig.seeding, &alice, request(key, None)).await.unwrap(); + let again = begin(&rig.catalog, &rig.timelines, &NoVaults, &rig.seeding, &alice, request(key, None)).await.unwrap(); assert_eq!(first.timeline, again.timeline); assert_eq!(rig.catalog.lock().await.timelines_of("alice").len(), 1); } @@ -432,8 +808,8 @@ pub(crate) mod tests { async fn another_players_replay_of_a_begin_key_is_refused() { let rig = rig(vec![]); let key = Uuid::new_v4(); - begin(&rig.catalog, &rig.timelines, &NoVaults, &principal("alice"), request(key, None)).await.unwrap(); - let error = begin(&rig.catalog, &rig.timelines, &NoVaults, &principal("mallory"), request(key, None)) + begin(&rig.catalog, &rig.timelines, &NoVaults, &rig.seeding, &principal("alice"), request(key, None)).await.unwrap(); + let error = begin(&rig.catalog, &rig.timelines, &NoVaults, &rig.seeding, &principal("mallory"), request(key, None)) .await .err() .unwrap(); @@ -441,4 +817,28 @@ pub(crate) mod tests { assert!(rig.catalog.lock().await.timelines_of("mallory").is_empty()); } + /// The scale a Begin states and the bound a trigger spends under, with the + /// env override that moves each. + #[test] + fn the_scale_defaults_and_overrides() { + let scale = Scale::from_reader(|_| None); + assert_eq!(scale.targets[&SubjectKind::Person], 8); + assert_eq!(scale.targets[&SubjectKind::Institution], 2); + assert_eq!(scale.targets[&SubjectKind::Population], 1); + assert_eq!((scale.seed_sessions, scale.sweep_sessions, scale.sweep_permits), (2, 4, 2)); + let moved = Scale::from_reader(|name| { + match name { + "GHOSTLIGHT_BEGIN_PERSON_TARGET" => Some("12"), + "GHOSTLIGHT_BEGIN_SEED_SESSIONS" => Some("3"), + "GHOSTLIGHT_SWEEP_SESSIONS" => Some("junk"), + "GHOSTLIGHT_SWEEP_PERMITS" => Some("0"), + _ => None, + } + .map(str::to_owned) + }); + assert_eq!(moved.targets[&SubjectKind::Person], 12); + assert_eq!(moved.seed_sessions, 3); + assert_eq!(moved.sweep_sessions, 4, "an unreadable override is the default"); + assert_eq!(moved.sweep_permits, 1, "a sweep always holds at least one permit"); + } } diff --git a/crates/ghostlight-dungeon/src/main.rs b/crates/ghostlight-dungeon/src/main.rs index 1797b62..30b1729 100644 --- a/crates/ghostlight-dungeon/src/main.rs +++ b/crates/ghostlight-dungeon/src/main.rs @@ -7,10 +7,12 @@ mod heimdall; mod idunn_health; mod invite; mod play; +mod run_ahead; mod runtime; mod session_refresh; mod state_layout; mod timelines; +mod vaults; use anyhow::bail; use std::path::PathBuf; @@ -24,9 +26,13 @@ async fn main() -> anyhow::Result<()> { println!("{}", invite::request(&PathBuf::from(path), hours)?); return Ok(()); } + [command, flag, path, profile] if command == "import-vault" && flag == "--state-root" => { + println!("{}", vaults::import(&PathBuf::from(path), &profile.to_string_lossy())?); + return Ok(()); + } [flag, path] if flag == "--state-root" => Some(PathBuf::from(path)), [] => None, - _ => bail!("usage: ghostlight-dungeon [--state-root PATH] | ghostlight-dungeon invite --state-root PATH HOURS"), + _ => bail!("usage: ghostlight-dungeon [--state-root PATH] | ghostlight-dungeon invite --state-root PATH HOURS | ghostlight-dungeon import-vault --state-root PATH PROFILE"), }; runtime::run(state_root).await } diff --git a/crates/ghostlight-dungeon/src/play.rs b/crates/ghostlight-dungeon/src/play.rs index a47e805..918a3b6 100644 --- a/crates/ghostlight-dungeon/src/play.rs +++ b/crates/ghostlight-dungeon/src/play.rs @@ -3329,6 +3329,11 @@ pub(crate) mod tests { pub(crate) struct ScriptedPort { queue: StdMutex>>, seen: StdMutex>, + /// A deferred port waits for its next scripted answer instead of + /// refusing: a test writes the answer once it has read the world the + /// request is about. + deferred: bool, + pushed: tokio::sync::Notify, } impl ScriptedPort { @@ -3336,9 +3341,26 @@ pub(crate) mod tests { Arc::new(Self { queue: StdMutex::new(outputs.into_iter().map(Ok).collect()), seen: StdMutex::new(Vec::new()), + deferred: false, + pushed: tokio::sync::Notify::new(), }) } + pub(crate) fn deferred() -> Arc { + Arc::new(Self { + queue: StdMutex::new(VecDeque::new()), + seen: StdMutex::new(Vec::new()), + deferred: true, + pushed: tokio::sync::Notify::new(), + }) + } + + pub(crate) fn push(&self, answer: Result) { + self.queue.lock().unwrap().push_back(answer); + self.pushed.notify_waiters(); + self.pushed.notify_one(); + } + pub(crate) fn seen_requests(&self) -> Vec { self.seen.lock().unwrap().clone() } @@ -3352,10 +3374,17 @@ pub(crate) mod tests { } async fn infer(&self, _request: PreparedInference) -> Result { - match self.queue.lock().unwrap().pop_front() { - Some(Ok(output)) => Ok(output), - Some(Err(detail)) => Err(InferenceFault::recovery_required(detail)), - None => Err(InferenceFault::recovery_required("scripted port exhausted")), + loop { + let waiting = self.pushed.notified(); + match self.queue.lock().unwrap().pop_front() { + Some(Ok(output)) => return Ok(output), + Some(Err(detail)) => return Err(InferenceFault::recovery_required(detail)), + None if !self.deferred => { + return Err(InferenceFault::recovery_required("scripted port exhausted")); + } + None => {} + } + waiting.await; } } } diff --git a/crates/ghostlight-dungeon/src/run_ahead.rs b/crates/ghostlight-dungeon/src/run_ahead.rs new file mode 100644 index 0000000..979e8a6 --- /dev/null +++ b/crates/ghostlight-dungeon/src/run_ahead.rs @@ -0,0 +1,56 @@ +//! Run-ahead: the bounded Active elaboration sweep. +//! +//! A world's scale deficit is answered after play starts, not before: one sweep +//! once Begin activates a seeded world, and one after each closed turn. Each +//! sweep starts at most `Scale::sweep_sessions` elaboration sessions and holds +//! at most `Scale::sweep_permits` permits, so a trigger cannot spend without +//! bound. The elaborator reads the evidence of the snapshot its timeline is +//! bound to, the same evidence the seed read; an unseeded world reads none. + +use crate::{ + begin::{Scale, Vaults}, + catalog::Catalog, + timelines::TimelineHost, +}; +use ghostlight::{EvidenceSource, NullEvidenceSource}; +use std::sync::Arc; +use tokio::sync::{Mutex, Semaphore}; + +/// One bounded sweep of `host` over `evidence`. A sweep already running on this +/// timeline is the trigger's answer: the sweep that follows picks up what this +/// one would have. +pub(crate) async fn run_ahead(host: &TimelineHost, evidence: Arc, scale: &Scale) { + let Ok(_running) = host.sweeping.try_lock() else { + return; + }; + let runner = host.controllers.elaborator(evidence); + let permits = Arc::new(Semaphore::new(scale.sweep_permits)); + if let Err(error) = runner.sweep(permits, scale.sweep_sessions).await { + tracing::warn!(%error, "run-ahead elaboration stopped"); + } +} + +/// The evidence a timeline's elaborator reads: its bound snapshot's, or none +/// for a world that began unseeded. A bound snapshot that cannot be reopened +/// yields no evidence at all and no sweep, never a blind one. +pub(crate) async fn evidence_of( + catalog: &Mutex, + vaults: &dyn Vaults, + timeline: &str, +) -> Option> { + let snapshot_id = { + let catalog = catalog.lock().await; + let world = catalog.world(&catalog.timeline(timeline)?.world_id)?; + world.snapshot_id.clone() + }; + match snapshot_id { + None => Some(Arc::new(NullEvidenceSource)), + Some(id) => match vaults.evidence(&id) { + Ok(evidence) => Some(evidence), + Err(error) => { + tracing::warn!(%error, timeline, "a seeded timeline's snapshot could not be reopened"); + None + } + }, + } +} diff --git a/crates/ghostlight-dungeon/src/runtime.rs b/crates/ghostlight-dungeon/src/runtime.rs index 28a4d14..d6724fa 100644 --- a/crates/ghostlight-dungeon/src/runtime.rs +++ b/crates/ghostlight-dungeon/src/runtime.rs @@ -5,7 +5,7 @@ use crate::{ api, app_session::AppSessionOwner, auth_guard::AuthGuard, - begin::{NoVaults, Vaults}, + begin::{Scale, Seeding, Vaults}, catalog::Catalog, heimdall::{HeimdallClient, HeimdallPort}, idunn_health::{ @@ -60,6 +60,7 @@ pub(crate) struct AppState { pub(crate) catalog: Arc>, pub(crate) timelines: Arc, pub(crate) vaults: Arc, + pub(crate) seeding: Arc, pub(crate) sessions: Arc>, pub(crate) heimdall: Arc, pub(crate) auth: Arc, @@ -214,7 +215,8 @@ pub(crate) async fn run(state_root_binding: Option) -> anyhow::Result<( let mut state = AppState { catalog: Arc::new(Mutex::new(catalog)), timelines: Arc::new(Timelines::new(runtime_root.clone(), shared, fatal.clone())), - vaults: Arc::new(NoVaults), + vaults: Arc::new(crate::vaults::SnapshotVaults::new(&runtime_root)), + seeding: Arc::new(Seeding::new(Scale::from_env())), sessions: Arc::new(Mutex::new(sessions)), heimdall, auth: Arc::default(), diff --git a/crates/ghostlight-dungeon/src/state_layout.rs b/crates/ghostlight-dungeon/src/state_layout.rs index 1a8f8dc..68f47c7 100644 --- a/crates/ghostlight-dungeon/src/state_layout.rs +++ b/crates/ghostlight-dungeon/src/state_layout.rs @@ -71,6 +71,10 @@ pub(crate) fn prepare_admitted_state_layout(runtime_root: &Path) -> anyhow::Resu let service_root = runtime_root.join("service"); ensure_direct_directory(&service_root, "service state directory")?; ensure_direct_directory(&runtime_root.join("timelines"), "timelines directory")?; + ensure_direct_directory( + &runtime_root.join(crate::vaults::SNAPSHOT_DIRECTORY), + "vault snapshot directory", + )?; for path in [ runtime_root.join("catalog.cc"), service_root.join("app-sessions-v2.cc"), diff --git a/crates/ghostlight-dungeon/src/timelines.rs b/crates/ghostlight-dungeon/src/timelines.rs index 3d8b7f8..ca42564 100644 --- a/crates/ghostlight-dungeon/src/timelines.rs +++ b/crates/ghostlight-dungeon/src/timelines.rs @@ -34,6 +34,8 @@ pub(crate) struct TimelineHost { pub(crate) play: Arc, /// Pulsed whenever this timeline's turn changes; the stream wakes on it. pub(crate) changes: broadcast::Sender<()>, + /// Held while a run-ahead sweep runs: one at a time per timeline. + pub(crate) sweeping: Mutex<()>, } pub(crate) struct Timelines { @@ -100,6 +102,7 @@ impl Timelines { controllers, play: Arc::new(play), changes, + sweeping: Mutex::new(()), }); hosts.insert(id.to_owned(), host.clone()); Ok(host) diff --git a/crates/ghostlight-dungeon/src/vaults.rs b/crates/ghostlight-dungeon/src/vaults.rs new file mode 100644 index 0000000..da7a99d --- /dev/null +++ b/crates/ghostlight-dungeon/src/vaults.rs @@ -0,0 +1,171 @@ +//! The production vault catalog: the profiles production serves, over the +//! snapshots an operator import left in the store. +//! +//! The daemon never reads a vault directory. `VaultSnapshot::build` is the +//! only reader of one, and it runs in the `import-vault` command; what lives +//! here is a read of the store the import wrote: which snapshot a profile last +//! produced, and that snapshot's evidence. + +use crate::begin::{VaultSeed, Vaults}; +use anyhow::{Context, bail}; +use ghostlight::{ + EvidenceSource, SnapshotId, VaultEvidenceSource, VaultError, VaultSnapshot, + production_profile, production_vault_names, +}; +use std::{ + collections::HashMap, + path::{Path, PathBuf}, + sync::{Arc, Mutex}, +}; + +/// The snapshot store, under the state root. +pub(crate) const SNAPSHOT_DIRECTORY: &str = "snapshots"; + +/// The directory the host keeps its vault copies in; the importer roots every +/// production profile under it. +pub(crate) const VAULT_BASE_ENVIRONMENT: &str = "GHOSTLIGHT_VAULT_BASE"; + +pub(crate) struct SnapshotVaults { + store: PathBuf, + /// A snapshot's evidence, loaded once: every turn's run-ahead sweep asks + /// for it again. + evidence: Mutex>>, +} + +impl SnapshotVaults { + pub(crate) fn new(state_root: &Path) -> Self { + Self { + store: state_root.join(SNAPSHOT_DIRECTORY), + evidence: Mutex::new(HashMap::new()), + } + } + + fn imported(&self, profile: &str) -> Result { + VaultSnapshot::current_id(&self.store, profile) + } +} + +impl Vaults for SnapshotVaults { + fn names(&self) -> Vec { + production_vault_names() + .filter(|name| self.imported(name).is_ok()) + .map(str::to_owned) + .collect() + } + + fn open(&self, profile: &str) -> anyhow::Result { + if !production_vault_names().any(|name| name == profile) { + bail!("vault profile `{profile}` is not one this server serves"); + } + let id = self + .imported(profile) + .map_err(|_| anyhow::anyhow!("vault profile `{profile}` has not been imported"))?; + let snapshot = VaultSnapshot::load(&self.store, &id) + .map_err(|error| anyhow::anyhow!("vault profile `{profile}`: {error}"))?; + let evidence: Arc = + Arc::new(VaultEvidenceSource::from_snapshot(&snapshot, "").context("the snapshot holds no evidence")?); + self.evidence + .lock() + .unwrap() + .insert(id.to_string(), evidence.clone()); + Ok(VaultSeed { + snapshot_id: id.to_string(), + evidence, + premise: snapshot.premise(), + }) + } + + fn evidence(&self, snapshot_id: &str) -> anyhow::Result> { + if let Some(held) = self.evidence.lock().unwrap().get(snapshot_id) { + return Ok(held.clone()); + } + let id = SnapshotId::parse(snapshot_id).context("the snapshot id is not an id")?; + let snapshot = VaultSnapshot::load(&self.store, &id) + .map_err(|error| anyhow::anyhow!("snapshot {snapshot_id}: {error}"))?; + let evidence: Arc = + Arc::new(VaultEvidenceSource::from_snapshot(&snapshot, "").context("the snapshot holds no evidence")?); + self.evidence + .lock() + .unwrap() + .insert(snapshot_id.to_owned(), evidence.clone()); + Ok(evidence) + } +} + +/// `ghostlight-dungeon import-vault --state-root PATH PROFILE`: the one reader +/// of a vault directory. Builds the production profile of `profile` rooted +/// under `$GHOSTLIGHT_VAULT_BASE`, stores the snapshot and records it as the +/// profile's current import. Prints the snapshot id. +pub(crate) fn import(state_root: &Path, profile: &str) -> anyhow::Result { + let base = std::env::var_os(VAULT_BASE_ENVIRONMENT) + .map(PathBuf::from) + .with_context(|| format!("{VAULT_BASE_ENVIRONMENT} is required"))?; + let Some(profile) = production_profile(profile, &base) else { + bail!("vault profile `{profile}` is not one this server serves"); + }; + let store = state_root.join(SNAPSHOT_DIRECTORY); + let snapshot = VaultSnapshot::build(&profile).map_err(|error| anyhow::anyhow!("{error}"))?; + snapshot + .import_into(&store) + .map_err(|error| anyhow::anyhow!("{error}"))?; + snapshot + .record_current(&store) + .map_err(|error| anyhow::anyhow!("{error}"))?; + Ok(format!("{} notes={} id={}", profile.name, snapshot.note_count(), snapshot.id())) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn write(root: &Path, relative: &str, text: &str) { + let path = root.join(relative); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } + + /// An imported snapshot of a tiny Avatar vault under a state root. + fn imported_avatar() -> (tempfile::TempDir, SnapshotVaults, String) { + let state = tempfile::tempdir().unwrap(); + let vault = tempfile::tempdir().unwrap(); + write(vault.path(), "Avatar/index.md", "A river city under a spirit sky.\n"); + write(vault.path(), "Avatar/Places/Harbor.md", "The harbor of the river city.\n"); + let profile = production_profile("avatar", vault.path()).unwrap(); + let snapshot = VaultSnapshot::build(&profile).unwrap(); + let store = state.path().join(SNAPSHOT_DIRECTORY); + snapshot.import_into(&store).unwrap(); + snapshot.record_current(&store).unwrap(); + let id = snapshot.id().to_string(); + let vaults = SnapshotVaults::new(state.path()); + (state, vaults, id) + } + + #[test] + fn it_lists_the_imported_profiles_and_opens_the_recorded_snapshot() { + let (_state, vaults, id) = imported_avatar(); + assert_eq!(vaults.names(), ["avatar"]); + let seed = vaults.open("avatar").unwrap(); + assert_eq!(seed.snapshot_id, id); + assert_eq!(seed.premise.as_deref(), Some("A river city under a spirit sky.")); + assert!(vaults.evidence(&id).is_ok()); + } + + #[test] + fn a_profile_never_imported_is_refused_by_name_and_so_is_a_stranger() { + let (_state, vaults, _) = imported_avatar(); + let never = vaults.open("zyphos").err().unwrap().to_string(); + assert!(never.contains("`zyphos` has not been imported"), "{never}"); + let stranger = vaults.open("../avatar").err().unwrap().to_string(); + assert!(stranger.contains("is not one this server serves"), "{stranger}"); + assert!(vaults.evidence("not-an-id").is_err()); + } + + /// The daemon side is a read of the store alone: with the vault directory + /// gone the profile still opens. + #[test] + fn opening_a_profile_reads_the_store_and_never_the_vault() { + let (_state, vaults, _) = imported_avatar(); + // `imported_avatar` dropped its vault directory already. + assert!(vaults.open("avatar").is_ok()); + } +}