Dungeon: Begin takes era and lens weights, evidence follows the world's era, /api/vaults lists eras and lenses, the page asks for both

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-02 23:38:09 +01:00
commit d646d59c46
8 changed files with 416 additions and 102 deletions

View file

@ -67,3 +67,7 @@ textarea { resize: vertical; line-height: 1.5; }
label.choice { text-transform: none; letter-spacing: 0; font: inherit; color: var(--text); margin: .4rem 0; }
.older { text-align: center; }
.older .btn { margin: .4rem 0; }
.lens { display: flex; gap: .5rem; align-items: center; padding: .35rem 0; border-bottom: 1px solid var(--line); }
.lens .what { flex: 1 1 auto; min-width: 0; }
.lens .n { min-width: 1.5rem; text-align: center; font: 600 1.05rem var(--head); }
.step { background: none; border: 1px solid var(--line); color: var(--text); border-radius: .5rem; min-width: 44px; min-height: 44px; font: 600 1.2rem var(--head); cursor: pointer; flex: none; }

View file

@ -178,9 +178,32 @@ async function beginView() {
const vaults = status === 200 ? body.vaults || [] : [];
const msg = el("div", {});
if (status !== 200) msg.append(errorLine(body.error || "The lore list could not be read."));
let vault = vaults.length ? vaults[0] : "";
const choices = vaults.map((name, i) => el("label", { class: "choice" },
el("input", { type: "radio", name: "vault", value: name, checked: i === 0, onchange: () => { vault = name; } }), name));
const lenses = status === 200 ? body.lenses || [] : [];
let vault = vaults.length ? vaults[0].name : "";
let era = null;
// The era picker follows the vault choice; a vault with one era offers none.
const eraBox = el("div", {});
const drawEras = () => {
const chosen = vaults.find((v) => v.name === vault);
era = chosen ? chosen.default_era : null;
eraBox.replaceChildren(...(chosen && chosen.eras.length > 1 ? [el("label", {}, "Era"),
...chosen.eras.map((e) => el("label", { class: "choice" },
el("input", { type: "radio", name: "era", value: e.id, checked: e.id === era, onchange: () => { era = e.id; } }),
el("span", {}, e.label, el("span", { class: "small blk" }, e.description))))] : []));
};
const choices = vaults.map((v, i) => el("label", { class: "choice" },
el("input", { type: "radio", name: "vault", value: v.name, checked: i === 0, onchange: () => { vault = v.name; drawEras(); } }), v.name));
drawEras();
// Each lens weighs what the world reaches for: 0 never, 5 most.
const weights = Object.fromEntries(lenses.map((l) => [l.id, 1]));
const lensRows = lenses.map((l) => {
const shown = el("span", { class: "n", "aria-live": "polite" }, "1");
const step = (by) => { weights[l.id] = Math.max(0, Math.min(5, weights[l.id] + by)); shown.textContent = String(weights[l.id]); };
return el("div", { class: "lens" },
el("span", { class: "what" }, el("b", {}, l.name), el("span", { class: "small blk" }, l.reaches_for)),
el("button", { class: "step", type: "button", "aria-label": "Less " + l.name, onclick: () => step(-1) }, "−"), shown,
el("button", { class: "step", type: "button", "aria-label": "More " + l.name, onclick: () => step(1) }, "+"));
});
const title = el("input", { type: "text", id: "title", autocomplete: "off", value: LS.get("begin-title") || "" });
const name = el("input", { type: "text", id: "name", autocomplete: "off", value: LS.get("begin-name") || "" });
const brief = el("textarea", { id: "brief", rows: "3" });
@ -188,7 +211,7 @@ async function beginView() {
go.onclick = async () => {
if (!title.value.trim() || !name.value.trim()) return msg.replaceChildren(errorLine("A world needs a title and your name in it."));
go.disabled = true; msg.replaceChildren(el("p", { class: "note pulse" }, "Starting the world"));
const { status: s, body: b } = await post("begin", { key: beginKey, title: title.value.trim(), name: name.value.trim(), brief: brief.value.trim() || null, vault: vault || null });
const { status: s, body: b } = await post("begin", { key: beginKey, title: title.value.trim(), name: name.value.trim(), brief: brief.value.trim() || null, vault: vault || null, era: vault ? era : null, lenses: lenses.length ? weights : null });
go.disabled = false;
if (s === 200) { beginKey = null; LS.set("begin-title", title.value.trim()); LS.set("begin-name", name.value.trim()); return openTimeline(b.timeline); }
const unknown = b.outcome === "unknown" || s === 0;
@ -198,9 +221,11 @@ async function beginView() {
show(el("h1", {}, "Begin a world"),
el("label", {}, "1. Lore"),
vaults.length ? choices : el("p", { class: "line info" }, "No vault has been imported on this server, so a world would start with no lore. Ask the host to import one."),
eraBox,
el("label", { for: "title" }, "2. Name the world"), title,
el("label", { for: "name" }, "3. What you are called in it"), name,
el("label", { for: "brief" }, "4. Anything the storyteller should know (optional)"), brief,
lenses.length ? [el("label", {}, "5. What the world reaches for"), lensRows] : "",
go, msg,
el("p", { class: "small" }, "A world seeded from lore takes a few minutes. You can leave this page; it carries on."));
}

View file

@ -24,7 +24,7 @@ use axum::{
routing::{get, post},
};
use chrono::{DateTime, Utc};
use ghostlight::{CommandId, VerifiedPrincipalEvidence, WorldPhase};
use ghostlight::{CommandId, Lens, VerifiedPrincipalEvidence, WorldPhase};
use serde::Deserialize;
use serde_json::{Value, json};
use std::{convert::Infallible, time::Duration};
@ -228,7 +228,17 @@ async fn vaults(headers: HeaderMap, State(state): State<AppState>) -> Response {
if authenticated_principal(&headers, &state).await.is_none() {
return unauthorized();
}
reply(StatusCode::OK, json!({"vaults": state.vaults.names()}))
let vaults: Vec<_> = state
.vaults
.offers()
.into_iter()
.map(|offer| json!({"name": offer.name, "default_era": offer.default_era, "eras": offer.eras.iter().map(|era| json!({"id": era.id, "label": era.label, "description": era.description})).collect::<Vec<_>>()}))
.collect();
let lenses: Vec<_> = Lens::ALL
.into_iter()
.map(|lens| json!({"id": lens, "name": lens.name(), "reaches_for": lens.reaches_for()}))
.collect();
reply(StatusCode::OK, json!({"vaults": vaults, "lenses": lenses}))
}
#[derive(Debug, Deserialize)]
@ -241,6 +251,11 @@ struct BeginBody {
brief: Option<String>,
#[serde(default)]
vault: Option<String>,
#[serde(default)]
era: Option<String>,
/// Lens id (snake_case) to weight; omitted is every lens at one.
#[serde(default)]
lenses: Option<std::collections::BTreeMap<Lens, u32>>,
}
async fn begin_world(
@ -263,6 +278,8 @@ async fn begin_world(
name: body.name,
brief: body.brief,
vault: body.vault,
era: body.era,
lenses: body.lenses,
},
)
.await;
@ -421,7 +438,7 @@ async fn play(
.await
.is_some_and(|view| view.state == PlayTurnState::Closed);
if closed
&& let Some(evidence) = evidence_of(&state.catalog, state.vaults.as_ref(), &timeline).await
&& let Some(evidence) = evidence_of(&state.catalog, state.vaults.as_ref(), &spawned, &timeline).await
{
run_ahead(&spawned, evidence, &state.scale).await;
}
@ -1241,6 +1258,40 @@ mod tests {
body["timeline"].as_str().unwrap().to_owned()
}
/// Spec test: GET /api/vaults lists each vault with its eras and default
/// and all eight lenses with their reach; POST /api/begin with an era and
/// lenses pins both in the world, and a field the body does not know is
/// refused.
#[tokio::test]
async fn the_vault_list_and_a_begin_with_era_and_lenses_over_http() {
let app = app_over(deferred_rig(), &["alice"]).await;
let cookie = app.cookies[0].clone();
let (code, _, listed) = call(&app, Method::GET, "/api/vaults", Some(&cookie), None).await;
assert_eq!(code, StatusCode::OK, "{listed}");
let vault = &listed["vaults"][0];
assert_eq!((vault["name"].as_str(), vault["default_era"].as_str()), (Some("delvehold"), Some("a")));
assert_eq!(vault["eras"].as_array().unwrap().len(), 2);
assert_eq!(vault["eras"][1]["id"], "b");
assert!(vault["eras"][1]["description"].as_str().is_some_and(|text| !text.is_empty()));
let lenses = listed["lenses"].as_array().unwrap();
assert_eq!(lenses.len(), 8);
assert!(lenses.iter().all(|lens| lens["reaches_for"].as_str().is_some_and(|text| !text.is_empty())));
assert!(lenses.iter().any(|lens| lens["id"] == "charter"));
let body = json!({"key": Uuid::new_v4(), "title": "Ashfall", "name": "Deru", "vault": "delvehold",
"era": "b", "lenses": {"charter": 3, "veil": 3, "hearth": 3}});
let (code, _, begun) = call(&app, Method::POST, "/api/begin", Some(&cookie), Some(body)).await;
assert_eq!(code, StatusCode::OK, "{begun}");
let host = app.rig.timelines.host(begun["timeline"].as_str().unwrap()).await.unwrap();
let world = host.world.snapshot().await.unwrap();
assert_eq!(world.era.unwrap().id, "b");
assert_eq!((world.lens_weights.get(Lens::Charter), world.lens_weights.get(Lens::Ember)), (3, 0));
let unknown = json!({"key": Uuid::new_v4(), "title": "Ashfall", "name": "Deru", "tier": "x"});
let (code, _, _) = call(&app, Method::POST, "/api/begin", Some(&cookie), Some(unknown)).await;
assert!(code.is_client_error());
}
/// Spec test: POST /api/begin on a vault returns the timeline before the
/// seed has finished, and the timeline list reads Seeding, then Ready.
#[tokio::test]
@ -2084,13 +2135,13 @@ mod tests {
async fn serve_the_page_for_a_browser_probe() {
struct NoVaults;
impl crate::begin::Vaults for NoVaults {
fn names(&self) -> Vec<String> {
fn offers(&self) -> Vec<crate::begin::VaultOffer> {
vec![]
}
fn open(&self, _: &str) -> anyhow::Result<crate::begin::VaultSeed> {
fn open(&self, _: &str, _: Option<&str>) -> anyhow::Result<crate::begin::VaultSeed> {
anyhow::bail!("no vault")
}
fn evidence(&self, _: &str) -> anyhow::Result<Arc<dyn ghostlight::EvidenceSource>> {
fn evidence(&self, _: &str, _: Option<&str>) -> anyhow::Result<Arc<dyn ghostlight::EvidenceSource>> {
anyhow::bail!("no vault")
}
}

View file

@ -21,7 +21,7 @@ use chrono::Utc;
use ghostlight::{
CommandBody, CommandId, ControllerError, CreateJurisdictionIntent, CreateWorldIntent,
EvidenceSource, Lens, LensWeights, MailboxError, PrincipalCommandIntent, SeedPort, SubjectKind,
VerifiedPrincipalEvidence, WorldPhase, WorldSnapshot,
VerifiedPrincipalEvidence, WorldEra, WorldPhase, WorldSnapshot,
};
use sha2::{Digest, Sha256};
use std::{collections::BTreeMap, sync::Arc};
@ -92,15 +92,25 @@ pub(crate) struct VaultSeed {
pub(crate) snapshot_id: String,
pub(crate) evidence: Arc<dyn EvidenceSource>,
pub(crate) premise: Option<String>,
/// The era the evidence was read for, and the world will be pinned to.
pub(crate) era: WorldEra,
}
/// The vault profiles a player may choose at Begin. Opening one yields the
/// snapshot to seed from; `evidence` reopens a snapshot a world was already
/// bound to.
/// A vault profile a player may choose at Begin, with the eras it offers.
pub(crate) struct VaultOffer {
pub(crate) name: String,
pub(crate) default_era: String,
pub(crate) eras: Vec<WorldEra>,
}
/// The vault profiles a player may choose at Begin. Opening one for an era
/// (the profile's default when none is named) yields the snapshot to seed
/// from; `evidence` reopens a snapshot a world was already bound to, for the
/// era the world was pinned to (a world with none withholds nothing).
pub(crate) trait Vaults: Send + Sync {
fn names(&self) -> Vec<String>;
fn open(&self, profile: &str) -> anyhow::Result<VaultSeed>;
fn evidence(&self, snapshot_id: &str) -> anyhow::Result<Arc<dyn EvidenceSource>>;
fn offers(&self) -> Vec<VaultOffer>;
fn open(&self, profile: &str, era: Option<&str>) -> anyhow::Result<VaultSeed>;
fn evidence(&self, snapshot_id: &str, era: Option<&str>) -> anyhow::Result<Arc<dyn EvidenceSource>>;
}
pub(crate) struct BeginRequest {
@ -111,6 +121,10 @@ pub(crate) struct BeginRequest {
pub(crate) name: String,
pub(crate) brief: Option<String>,
pub(crate) vault: Option<String>,
/// The era id the world is set in; the profile's default when absent.
pub(crate) era: Option<String>,
/// What the player weighs the world's lenses at; uniform when absent.
pub(crate) lenses: Option<BTreeMap<Lens, u32>>,
}
pub(crate) struct Begun {
@ -206,9 +220,10 @@ pub(crate) async fn begin(
}
// The vault is resolved before anything is created: an unknown profile
// refuses the Begin whole.
let vault = match request.vault.as_deref() {
Some(profile) => Some(vaults.open(profile).map_err(|error| stopped("vault", error))?),
None => None,
let vault = match (request.vault.as_deref(), request.era.as_deref()) {
(Some(profile), era) => Some(vaults.open(profile, era).map_err(|error| stopped("vault", error))?),
(None, Some(_)) => return Err(stopped("request", "an era needs a vault")),
(None, None) => None,
};
let host = timelines
.host(&timeline)
@ -227,7 +242,16 @@ pub(crate) async fn begin(
),
None => (BTreeMap::new(), Vec::new()),
};
let world_id = match current(&host).await.map_err(|error| from_mailbox("create", error))? {
let existing = current(&host).await.map_err(|error| from_mailbox("create", error))?;
// A replayed Begin resumes the world it made: the evidence it seeds from
// is the world's era, whatever era the replay named.
let vault = match (vault, request.vault.as_deref(), existing.as_ref().and_then(|world| world.era.as_ref())) {
(Some(seed), Some(profile), Some(era)) if era.id != seed.era.id => {
Some(vaults.open(profile, Some(&era.id)).map_err(|error| stopped("vault", error))?)
}
(vault, _, _) => vault,
};
let world_id = match existing {
Some(world) => world.world_id,
None => {
host.world
@ -241,7 +265,8 @@ pub(crate) async fn begin(
operational_agent_label: None,
targets,
jurisdictions,
lens_weights: uniform_lens_weights(),
lens_weights: request.lenses.map_or_else(uniform_lens_weights, LensWeights::new),
era: vault.as_ref().map(|seed| seed.era.clone()),
},
principal,
)
@ -446,7 +471,7 @@ fn describe_seed_failure(error: &ControllerError) -> &'static str {
}
}
/// Dungeon policy for a world created before Session Zero's sliders exist.
/// The weights of a request that states none: every lens at one.
fn uniform_lens_weights() -> LensWeights {
LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 1)).collect())
}
@ -529,6 +554,8 @@ pub(crate) mod tests {
name: "Deru".into(),
brief: Some("A cold harbor town.".into()),
vault: vault.map(str::to_owned),
era: None,
lenses: None,
}
}
@ -551,7 +578,7 @@ pub(crate) mod tests {
..ghostlight::VaultProfile::default()
})
.unwrap();
let evidence = ghostlight::VaultEvidenceSource::from_snapshot(&snapshot, "").unwrap();
let evidence = ghostlight::VaultEvidenceSource::from_snapshot(&snapshot, "", &[]).unwrap();
Self {
evidence: Arc::new(evidence),
_vault: vault,
@ -559,21 +586,41 @@ pub(crate) mod tests {
}
}
/// The two eras the scripted vault offers; `a` is its default.
pub(crate) fn scripted_eras() -> Vec<WorldEra> {
[
("a", "The Thaw", "Ice still holds the harbor mouth shut."),
("b", "The Drowning", "The sea has taken the lower town."),
]
.map(|(id, label, description)| WorldEra {
id: id.into(),
label: label.into(),
description: description.into(),
})
.into()
}
impl Vaults for OneVault {
fn names(&self) -> Vec<String> {
vec!["delvehold".into()]
fn offers(&self) -> Vec<VaultOffer> {
vec![VaultOffer { name: "delvehold".into(), default_era: "a".into(), eras: scripted_eras() }]
}
fn open(&self, profile: &str) -> anyhow::Result<VaultSeed> {
fn open(&self, profile: &str, era: Option<&str>) -> anyhow::Result<VaultSeed> {
anyhow::ensure!(profile == "delvehold", "unknown profile");
let era = era.unwrap_or("a");
let era = scripted_eras()
.into_iter()
.find(|candidate| candidate.id == era)
.ok_or_else(|| anyhow::anyhow!("no such era"))?;
Ok(VaultSeed {
snapshot_id: "feedface".into(),
evidence: self.evidence.clone(),
premise: Some("A cold harbor, from the vault.".into()),
era,
})
}
fn evidence(&self, snapshot_id: &str) -> anyhow::Result<Arc<dyn EvidenceSource>> {
fn evidence(&self, snapshot_id: &str, _: Option<&str>) -> anyhow::Result<Arc<dyn EvidenceSource>> {
anyhow::ensure!(snapshot_id == "feedface", "unknown snapshot");
Ok(self.evidence.clone())
}
@ -583,15 +630,15 @@ pub(crate) mod tests {
pub(crate) struct NoVaults;
impl Vaults for NoVaults {
fn names(&self) -> Vec<String> {
fn offers(&self) -> Vec<VaultOffer> {
Vec::new()
}
fn open(&self, profile: &str) -> anyhow::Result<VaultSeed> {
fn open(&self, profile: &str, _: Option<&str>) -> anyhow::Result<VaultSeed> {
anyhow::bail!("vault profile `{profile}` is not configured")
}
fn evidence(&self, _: &str) -> anyhow::Result<Arc<dyn EvidenceSource>> {
fn evidence(&self, _: &str, _: Option<&str>) -> anyhow::Result<Arc<dyn EvidenceSource>> {
anyhow::bail!("no snapshots")
}
}
@ -929,4 +976,111 @@ pub(crate) mod tests {
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");
}
async fn begin_with(rig: &Rig, request: BeginRequest) -> Result<Begun, BeginError> {
begin(&rig.catalog, &rig.timelines, &OneVault::new(), &rig.scale, &principal("alice"), request).await
}
async fn world_of(rig: &Rig, timeline: &str) -> WorldSnapshot {
rig.timelines.host(timeline).await.unwrap().world.snapshot().await.unwrap()
}
/// Spec test: Begin on era `b` pins it in the world, and both the seed
/// request and a later Active elaboration request carry era b's label and
/// description and never era a's.
#[tokio::test]
async fn a_begin_pins_its_era_and_every_elaboration_lane_reads_it() {
let rig = deferred_rig();
let begun = begin_with(&rig, BeginRequest { era: Some("b".into()), ..request(Uuid::new_v4(), Some("delvehold")) })
.await
.unwrap();
let host = rig.timelines.host(&begun.timeline).await.unwrap();
let draft = host.world.snapshot().await.unwrap();
assert_eq!(draft.era.as_ref().map(|era| era.id.as_str()), Some("b"));
rig.port.push(Ok(author("seed-1", &draft, &["a", "b"])));
rig.port.push(Ok(author("seed-2", &draft, &["c", "d"])));
eventually(async || {
let world = host.world.snapshot().await.unwrap();
(world.phase == WorldPhase::Active && rig.status(&begun.timeline).await.is_none()).then_some(())
})
.await;
let active = eventually(async || {
rig.port.seen_requests().into_iter().skip(2).find(|request| prompt_text(request).contains(NOTE))
})
.await;
let seed = rig.port.seen_requests().into_iter().next().unwrap();
for request in [seed, active] {
let text = prompt_text(&request);
assert!(text.contains("The Drowning") && text.contains("The sea has taken the lower town"), "{text}");
assert!(!text.contains("Ice still holds"), "era a's description reached a lane pinned to b");
}
assert_eq!(world_of(&rig, &begun.timeline).await.era.unwrap().id, "b");
}
/// Spec test: no era is the profile's default, and replaying the key with
/// another era resumes the same timeline with the era unchanged.
#[tokio::test]
async fn the_default_era_is_pinned_and_a_replay_cannot_change_it() {
let rig = deferred_rig();
let key = Uuid::new_v4();
let first = begin_vault(&rig, key).await;
assert_eq!(world_of(&rig, &first.timeline).await.era.unwrap().id, "a");
let again = begin_with(&rig, BeginRequest { era: Some("b".into()), ..request(key, Some("delvehold")) })
.await
.unwrap();
assert_eq!(again.timeline, first.timeline);
assert_eq!(world_of(&rig, &again.timeline).await.era.unwrap().id, "a", "write-once");
}
/// Spec test: an era the vault does not list refuses the whole Begin, and
/// so does an era with no vault.
#[tokio::test]
async fn an_unknown_era_refuses_whole() {
let rig = deferred_rig();
let unknown = begin_with(&rig, BeginRequest { era: Some("zz".into()), ..request(Uuid::new_v4(), Some("delvehold")) })
.await
.err()
.unwrap();
assert_eq!(unknown.step, "vault");
let eraless = begin(
&rig.catalog,
&rig.timelines,
&NoVaults,
&rig.scale,
&principal("alice"),
BeginRequest { era: Some("a".into()), ..request(Uuid::new_v4(), None) },
)
.await
.err()
.unwrap();
assert_eq!(eraless.step, "request");
assert!(rig.catalog.lock().await.timelines_of("alice").is_empty(), "nothing was made");
assert!(rig.port.seen_requests().is_empty(), "no model call");
}
/// Spec test: the lens weights a Begin states are the world's, omitted
/// lenses are one each, and weights that never draw refuse and make no
/// world.
#[tokio::test]
async fn the_lens_weights_a_begin_states_reach_the_world() {
let rig = deferred_rig();
let stated = BTreeMap::from([(Lens::Charter, 3), (Lens::Veil, 3), (Lens::Hearth, 3)]);
let begun = begin_with(&rig, BeginRequest { lenses: Some(stated), ..request(Uuid::new_v4(), Some("delvehold")) })
.await
.unwrap();
let weights = world_of(&rig, &begun.timeline).await.lens_weights;
for lens in Lens::ALL {
let expected = if matches!(lens, Lens::Charter | Lens::Veil | Lens::Hearth) { 3 } else { 0 };
assert_eq!(weights.get(lens), expected, "{lens:?}");
}
let omitted = begin_vault(&rig, Uuid::new_v4()).await;
let weights = world_of(&rig, &omitted.timeline).await.lens_weights;
assert!(Lens::ALL.into_iter().all(|lens| weights.get(lens) == 1));
let before = rig.catalog.lock().await.timelines_of("alice").len();
let never = BTreeMap::from(Lens::ALL.map(|lens| (lens, 0)));
let refused = begin_with(&rig, BeginRequest { lenses: Some(never), ..request(Uuid::new_v4(), Some("delvehold")) }).await;
assert!(refused.is_err());
assert_eq!(rig.catalog.lock().await.timelines_of("alice").len(), before, "no world was recorded");
}
}

View file

@ -3588,6 +3588,7 @@ pub(crate) mod tests {
targets: BTreeMap::new(),
jurisdictions: Vec::new(),
lens_weights: LensWeights::new(BTreeMap::from([(Lens::Hearth, 1)])),
era: None,
},
&principal,
)
@ -5715,6 +5716,7 @@ pub(crate) mod tests {
targets: BTreeMap::new(),
jurisdictions: Vec::new(),
lens_weights: LensWeights::new(BTreeMap::from([(Lens::Hearth, 1)])),
era: None,
},
&principal,
)
@ -7202,6 +7204,7 @@ pub(crate) mod tests {
targets: BTreeMap::new(),
jurisdictions: Vec::new(),
lens_weights: LensWeights::new(BTreeMap::from([(Lens::Hearth, 1)])),
era: None,
},
&principal,
)

View file

@ -30,12 +30,14 @@ pub(crate) async fn run_ahead(host: &TimelineHost, evidence: Arc<dyn EvidenceSou
}
}
/// 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.
/// The evidence a timeline's elaborator reads: its bound snapshot's, for the
/// era its world was pinned to, or none for a world that began unseeded. A
/// bound snapshot that cannot be reopened, or a world that cannot be read,
/// yields no evidence at all and no sweep, never a blind or era-blind one.
pub(crate) async fn evidence_of(
catalog: &Mutex<Catalog>,
vaults: &dyn Vaults,
host: &TimelineHost,
timeline: &str,
) -> Option<Arc<dyn EvidenceSource>> {
let snapshot_id = {
@ -43,15 +45,16 @@ pub(crate) async fn evidence_of(
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
}
},
let Some(id) = snapshot_id else {
return Some(Arc::new(NullEvidenceSource));
};
let era = host.world.snapshot().await.ok()?.era;
match vaults.evidence(&id, era.as_ref().map(|era| era.id.as_str())) {
Ok(evidence) => Some(evidence),
Err(error) => {
tracing::warn!(%error, timeline, "a seeded timeline's snapshot could not be reopened");
None
}
}
}
@ -59,31 +62,13 @@ pub(crate) async fn evidence_of(
mod tests {
use super::*;
use crate::{
begin::tests::{NoVaults, one_vault},
catalog::{Timeline, WorldRecord, timeline_id},
begin::{
BeginRequest, begin,
tests::{NoVaults, deferred_rig, one_vault, principal, request},
},
};
use chrono::Utc;
use uuid::Uuid;
async fn catalog_with(snapshot_id: Option<&str>) -> (tempfile::TempDir, Mutex<Catalog>, String) {
let directory = tempfile::tempdir().unwrap();
let mut catalog = Catalog::open(directory.path().join("catalog.cc")).unwrap();
let timeline = timeline_id(Uuid::new_v4());
catalog
.mint_timeline(
Some(WorldRecord {
world_id: "w1".into(),
title: "Ashfall".into(),
owner: "alice".into(),
snapshot_id: snapshot_id.map(str::to_owned),
created_at: Utc::now(),
}),
Timeline { id: timeline.clone(), world_id: "w1".into(), parent: None },
)
.unwrap();
(directory, Mutex::new(catalog), timeline)
}
/// A timeline's elaborator reads what its world was bound to: nothing
/// for an unseeded world, the snapshot for a seeded one, and no evidence
/// (so no sweep) for a snapshot that cannot be reopened or a timeline the
@ -91,11 +76,33 @@ mod tests {
#[tokio::test]
async fn the_evidence_of_a_timeline_is_its_bound_snapshots() {
let vaults = one_vault();
let (_a, unseeded, timeline) = catalog_with(None).await;
assert!(evidence_of(&unseeded, &NoVaults, &timeline).await.is_some(), "an unseeded world reads none, and still sweeps");
let (_b, seeded, timeline) = catalog_with(Some("feedface")).await;
assert!(evidence_of(&seeded, vaults.as_ref(), &timeline).await.is_some());
assert!(evidence_of(&seeded, &NoVaults, &timeline).await.is_none(), "an unreadable snapshot is never swept blind");
assert!(evidence_of(&seeded, vaults.as_ref(), "timeline:00000000-0000-4000-8000-000000000000").await.is_none());
let rig = deferred_rig();
let alice = principal("alice");
let unseeded = begin(&rig.catalog, &rig.timelines, &NoVaults, &rig.scale, &alice, request(Uuid::new_v4(), None))
.await
.unwrap();
let host = rig.timelines.host(&unseeded.timeline).await.unwrap();
assert!(
evidence_of(&rig.catalog, &NoVaults, &host, &unseeded.timeline).await.is_some(),
"an unseeded world reads none, and still sweeps"
);
let seeded = begin(
&rig.catalog,
&rig.timelines,
vaults.as_ref(),
&rig.scale,
&alice,
BeginRequest { era: Some("b".into()), ..request(Uuid::new_v4(), Some("delvehold")) },
)
.await
.unwrap();
let host = rig.timelines.host(&seeded.timeline).await.unwrap();
assert!(evidence_of(&rig.catalog, vaults.as_ref(), &host, &seeded.timeline).await.is_some());
assert!(
evidence_of(&rig.catalog, &NoVaults, &host, &seeded.timeline).await.is_none(),
"an unreadable snapshot is never swept blind"
);
let stranger = "timeline:00000000-0000-4000-8000-000000000000";
assert!(evidence_of(&rig.catalog, vaults.as_ref(), &host, stranger).await.is_none());
}
}

View file

@ -673,6 +673,8 @@ mod tests {
name: "Deru".into(),
brief: None,
vault: Some(profile.clone()),
era: None,
lenses: None,
},
)
.await

View file

@ -6,11 +6,11 @@
//! 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 crate::begin::{VaultOffer, VaultSeed, Vaults};
use anyhow::{Context, bail};
use ghostlight::{
EvidenceSource, SnapshotId, VaultEvidenceSource, VaultError, VaultSnapshot,
production_profile, production_vault_names,
EvidenceSource, SnapshotId, VaultEra, VaultEvidenceSource, VaultError, VaultSnapshot, WorldEra,
production_eras, production_profile, production_vault_names,
};
use std::{
collections::HashMap,
@ -27,9 +27,9 @@ 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<HashMap<String, Arc<dyn EvidenceSource>>>,
/// A snapshot's evidence for one era, loaded once: every turn's run-ahead
/// sweep asks for it again. Cache only; the era is the world's.
evidence: Mutex<HashMap<(String, String), Arc<dyn EvidenceSource>>>,
}
impl SnapshotVaults {
@ -45,53 +45,87 @@ impl SnapshotVaults {
}
}
/// The evidence of `snapshot` for `era`, which withholds the era's paths; a
/// world with no era withholds nothing.
fn evidence_for(snapshot: &VaultSnapshot, era: Option<&VaultEra>) -> anyhow::Result<Arc<dyn EvidenceSource>> {
let evidence = VaultEvidenceSource::from_snapshot(snapshot, "", era.map_or(&[], |era| era.withhold))
.context("the snapshot holds no evidence")?;
Ok(Arc::new(evidence))
}
impl Vaults for SnapshotVaults {
fn names(&self) -> Vec<String> {
fn offers(&self) -> Vec<VaultOffer> {
production_vault_names()
.filter(|name| self.imported(name).is_ok())
.map(str::to_owned)
.filter_map(|name| {
let (eras, default) = production_eras(name)?;
Some(VaultOffer {
name: name.to_owned(),
default_era: default.to_owned(),
eras: eras.iter().map(world_era).collect(),
})
})
.collect()
}
fn open(&self, profile: &str) -> anyhow::Result<VaultSeed> {
if !production_vault_names().any(|name| name == profile) {
fn open(&self, profile: &str, era: Option<&str>) -> anyhow::Result<VaultSeed> {
let Some((eras, default)) = production_eras(profile) else {
bail!("vault profile `{profile}` is not one this server serves");
}
};
let wanted = era.unwrap_or(default);
let chosen = eras
.iter()
.find(|candidate| candidate.id == wanted)
.with_context(|| format!("vault profile `{profile}` has no era `{wanted}`"))?;
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<dyn EvidenceSource> =
Arc::new(VaultEvidenceSource::from_snapshot(&snapshot, "").context("the snapshot holds no evidence")?);
let evidence = evidence_for(&snapshot, Some(chosen))?;
self.evidence
.lock()
.unwrap()
.insert(id.to_string(), evidence.clone());
.insert((id.to_string(), chosen.id.to_owned()), evidence.clone());
Ok(VaultSeed {
snapshot_id: id.to_string(),
evidence,
premise: snapshot.premise(),
era: world_era(chosen),
})
}
fn evidence(&self, snapshot_id: &str) -> anyhow::Result<Arc<dyn EvidenceSource>> {
if let Some(held) = self.evidence.lock().unwrap().get(snapshot_id) {
fn evidence(&self, snapshot_id: &str, era: Option<&str>) -> anyhow::Result<Arc<dyn EvidenceSource>> {
let key = (snapshot_id.to_owned(), era.unwrap_or_default().to_owned());
if let Some(held) = self.evidence.lock().unwrap().get(&key) {
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<dyn EvidenceSource> =
Arc::new(VaultEvidenceSource::from_snapshot(&snapshot, "").context("the snapshot holds no evidence")?);
self.evidence
.lock()
.unwrap()
.insert(snapshot_id.to_owned(), evidence.clone());
let name = &snapshot.profile().name;
let chosen = match era {
None => None,
Some(era) => Some(
production_eras(name)
.and_then(|(eras, _)| eras.iter().find(|candidate| candidate.id == era))
.with_context(|| format!("vault profile `{name}` has no era `{era}`"))?,
),
};
let evidence = evidence_for(&snapshot, chosen)?;
self.evidence.lock().unwrap().insert(key, evidence.clone());
Ok(evidence)
}
}
fn world_era(era: &VaultEra) -> WorldEra {
WorldEra {
id: era.id.to_owned(),
label: era.label.to_owned(),
description: era.description.to_owned(),
}
}
/// `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
@ -146,30 +180,32 @@ mod tests {
fn a_stored_snapshot_id_that_is_not_an_id_is_refused_before_a_path_is_built() {
let (_state, vaults, id) = imported_avatar();
for bad in ["abc".to_owned(), format!("../{}", &id[3..]), id.to_uppercase()] {
let error = vaults.evidence(&bad).err().expect("refused").to_string();
let error = vaults.evidence(&bad, Some("rda-return")).err().expect("refused").to_string();
assert!(error.contains("not an id"), "{bad}: {error}");
}
assert!(vaults.evidence(&id).is_ok());
assert!(vaults.evidence(&id, Some("rda-return")).is_ok());
}
#[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!(vaults.offers().iter().map(|offer| offer.name.as_str()).collect::<Vec<_>>(), ["avatar"]);
let seed = vaults.open("avatar", None).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());
assert_eq!(seed.era.id, "rda-return", "an omitted era is the profile's default");
assert!(vaults.evidence(&id, Some("rda-return")).is_ok());
assert!(vaults.evidence(&id, Some("no-such-era")).is_err());
}
#[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();
let never = vaults.open("zyphos", None).err().unwrap().to_string();
assert!(never.contains("`zyphos` has not been imported"), "{never}");
let stranger = vaults.open("../avatar").err().unwrap().to_string();
let stranger = vaults.open("../avatar", None).err().unwrap().to_string();
assert!(stranger.contains("is not one this server serves"), "{stranger}");
assert!(vaults.evidence("not-an-id").is_err());
assert!(vaults.evidence("not-an-id", Some("rda-return")).is_err());
}
/// The daemon side is a read of the store alone: with the vault directory
@ -178,6 +214,38 @@ mod tests {
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());
assert!(vaults.open("avatar", None).is_ok());
}
/// A pre-Elysium Aetheria world never sees the Post-Elysium folder, in the
/// seed's evidence or in the evidence reopened for run-ahead; a
/// post-Elysium world does.
#[tokio::test]
async fn a_pre_elysium_world_never_sees_the_post_elysium_folder() {
use ghostlight::EvidenceQuery;
let state = tempfile::tempdir().unwrap();
let vault = tempfile::tempdir().unwrap();
write(vault.path(), "AetheriaLore/Aetheria/Worldbuilding/Post-Elysium/Aether.md", "The aether answers espers.
");
write(vault.path(), "AetheriaLore/Aetheria/Worldbuilding/Pre-Elysium/Collapse.md", "The grid fails.
");
let snapshot = VaultSnapshot::build(&production_profile("aetheria", vault.path()).unwrap()).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());
let aether = EvidenceQuery { referents: vec!["Aether".into()] };
let seed = vaults.open("aetheria", None).unwrap();
assert_eq!(seed.era.id, "pre-elysium", "late Sol is the default");
assert!(seed.evidence.retrieve(&aether).await.unwrap().is_empty(), "the seed's evidence");
let reopened = vaults.evidence(&id, Some("pre-elysium")).unwrap();
assert!(reopened.retrieve(&aether).await.unwrap().is_empty(), "run-ahead's evidence");
let after = vaults.open("aetheria", Some("post-elysium")).unwrap();
assert!(!after.evidence.retrieve(&aether).await.unwrap().is_empty());
assert!(vaults.open("aetheria", Some("nowhen")).is_err());
}
}