diff --git a/.gitignore b/.gitignore index 3c71615..22759ba 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,6 @@ target/ # Claude Code agent worktrees (Hands/Soul isolation); never source .claude/worktrees/ + +# Captured probe screenshots (scripts and fixtures under probes/page/ stay tracked) +probes/page/*.png diff --git a/AGENTS.md b/AGENTS.md index f0e4406..1a74f58 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -5,15 +5,17 @@ Ghostlight is a Rust world kernel and the play daemon built on it. Models propose; the kernel admits or refuses. The same kernel is meant to run the simulation behind Aetheria's public story, a persistent cast and storylets, as -well as Ghostlight Dungeon, the single-player DM-led client (parked at -tag `parked/ghostlight-eve-surface`). `README.md` says -what exists today and what does not. +well as Ghostlight Dungeon (`crates/ghostlight-dungeon` and +`deployment/idunn/recipe.toml`, live on `main` for the Dungeon playtest; the +earlier Eve surface is at tag `parked/ghostlight-eve-surface`). `README.md` +says what exists today and what does not. ## Where State Lives - Campaign state (targets, rulings, cut specs, reports, verdicts, findings, follow-ups) lives in the Eureka mind, not in this repo. The current campaign - is `ghostlight-verse`; query it through the `eureka-state` tools. + is `ghostlight-verse`; query it through the `huginn` CLI + (`EUREKA_INSTANCE=weksa`, `HUGINN_ENDPOINT=rudp://10.77.0.1:17877`). - `notes/ghostlight-verse-target.md` and `notes/ghostlight-verse-map.md` are the campaign's prose target and map. Read the map for probed body facts. - This repo has no state directory, no state CLI, and no evidence ledger. Do not @@ -56,8 +58,9 @@ what exists today and what does not. - Kernel: `crates/ghostlight/src/`. Its vocabulary and current mechanism: `docs/architecture/ghostlight-world-ontology.md`. The consumer contract: `docs/architecture/ghostlight-world-consumer-api.md`. -- Parked Dungeon (daemon, play table, Eve surface, browser host, Idunn recipe): - tag `parked/ghostlight-eve-surface`; not on main. +- Dungeon daemon and Idunn recipe: `crates/ghostlight-dungeon/` and + `deployment/idunn/recipe.toml` (the earlier Eve surface is at tag + `parked/ghostlight-eve-surface`). - Persona membrane: `crates/ghostlight-persona-projection/src/lib.rs`. - Claude SDK sidecar: `sidecar/claude-sdk/`. - Architecture rationale (the parked Dungeon's): `docs/architecture/ghostlight-dungeon-mvp.md`. @@ -66,11 +69,12 @@ what exists today and what does not. ## Build, Verify, Deploy -Nothing deploys from this repo: the Idunn target `ghostlight` is braked and stopped (deployment and -lifecycle brakes engaged, unit stopped; retirement waits on -`ghostlight-verse:follow_up:idunn-v2-target-retirement`) and no recipe exists on main. Kernel and verse tests run on Linux on Yggdrasil (the -`ygg-verify` stopgap), not on the workstation; a Windows compile is not evidence -about Linux, so say which host you used. Do not run `idunn up ghostlight`. +`crates/ghostlight-dungeon` deploys to Yggdrasil from `deployment/idunn/recipe.toml` +for the Dungeon playtest (brake release admitted in +`ghostlight-verse:ruling:ghostlight-brake-release-granted`). Kernel, verse, and +Dungeon tests run on Linux on Yggdrasil (the `ygg-verify` stopgap), not on the +workstation; a Windows compile is not evidence about Linux, so say which host you +used. For infrastructure, SSH, Idunn, Odin, or Heimdall work, consult `F:\Projects\gamecult-ops` before acting. diff --git a/README.md b/README.md index ff4a893..8f36bb8 100644 --- a/README.md +++ b/README.md @@ -71,12 +71,12 @@ advances it a number of ticks under a token cap, reporting per tick what each faction did and what it cost. Nothing loads AetheriaLore prose, models storylets, or produces episodes yet. Targets: `notes/ghostlight-verse-target.md`. -## Ghostlight Dungeon (parked) +## Ghostlight Dungeon -The single-player, DM-led client and its daemon, Eve play surface and browser -host are parked at tag `parked/ghostlight-eve-surface`. Nothing is deployed and -nothing on main serves HTTP. The Dungeon returns when Thing 2 gives it a UI -(follow-up `dungeon-ui-on-thing2`); the rebuild starts from the tag. +`crates/ghostlight-dungeon` and `deployment/idunn/recipe.toml` are live on `main` +for the Dungeon playtest: one Rust binary serving the compiled browser page, +the Deru HTTPS API, and the Idunn/Odin CultNet runtime-presence endpoints. The +earlier Eve surface remains at tag `parked/ghostlight-eve-surface` as history. ## Repo map diff --git a/crates/ghostlight-dungeon/src/heimdall.rs b/crates/ghostlight-dungeon/src/heimdall.rs index 40d3c75..d2f9cea 100644 --- a/crates/ghostlight-dungeon/src/heimdall.rs +++ b/crates/ghostlight-dungeon/src/heimdall.rs @@ -261,25 +261,10 @@ pub struct HeimdallClient { jwks: Arc>, } -/// Idunn's projection of a managed Heimdall dependency, when Heimdall is a -/// v2-managed target (it is not, as of this cut: every v2 deploy of it has -/// failed and it still runs as the legacy `heimdall.service`, so -/// `runtime.rs` always passes `None` here). Not an Idunn dependency in -/// `deployment/idunn/recipe.toml` right now, but the type stays owned here -/// so `require_expected_heimdall_boundary` below can resume checking a -/// discovered boundary against it the moment Heimdall returns as a managed -/// dependency, without re-deriving this shape from scratch. -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) struct HeimdallDependencyBinding { - pub(crate) provider_id: String, - pub(crate) endpoint: SocketAddr, -} - #[derive(Clone)] enum HeimdallBoundaryLocator { Odin { endpoint: SocketAddr, - expected: Option, }, #[cfg(test)] Fixed(ResolvedHeimdallBoundary), @@ -562,11 +547,7 @@ impl VerifiedSessionRefresh { } impl HeimdallClient { - pub fn from_env( - runtime_id: &str, - odin_endpoint: SocketAddr, - expected: Option, - ) -> anyhow::Result { + pub fn from_env(runtime_id: &str, odin_endpoint: SocketAddr) -> anyhow::Result { if runtime_id.is_empty() || runtime_id.trim() != runtime_id { bail!("Ghostlight runtime identity is not canonical"); } @@ -594,7 +575,6 @@ impl HeimdallClient { providers, boundary_locator: HeimdallBoundaryLocator::Odin { endpoint: odin_endpoint, - expected, }, runtime_id: runtime_id.into(), shared_secret, @@ -1023,13 +1003,7 @@ impl HeimdallBoundaryLocator { operation: &str, ) -> anyhow::Result { let boundary = match self { - Self::Odin { endpoint, expected } => { - let boundary = discover_heimdall_boundary(*endpoint, runtime_id)?; - if let Some(expected) = expected { - require_expected_heimdall_boundary(&boundary, expected)?; - } - boundary - } + Self::Odin { endpoint } => discover_heimdall_boundary(*endpoint, runtime_id)?, #[cfg(test)] Self::Fixed(boundary) => boundary.clone(), }; @@ -1044,16 +1018,6 @@ impl HeimdallBoundaryLocator { } } -fn require_expected_heimdall_boundary( - boundary: &ResolvedHeimdallBoundary, - expected: &HeimdallDependencyBinding, -) -> anyhow::Result<()> { - if boundary.daemon_id != expected.provider_id || boundary.endpoint != expected.endpoint { - bail!("discovered Heimdall boundary differs from Expected"); - } - Ok(()) -} - fn discover_heimdall_boundary( odin_endpoint: SocketAddr, runtime_id: &str, @@ -1610,17 +1574,6 @@ mod tests { assert_eq!(resolved.endpoint, "127.0.0.1:4101".parse().unwrap()); assert_eq!(resolved.daemon_id, "yggdrasil-heimdall"); assert_eq!(resolved.operations, vec!["heimdall.auth.begin"]); - let expected = HeimdallDependencyBinding { - provider_id: "yggdrasil-heimdall".into(), - endpoint: "127.0.0.1:4101".parse().unwrap(), - }; - require_expected_heimdall_boundary(&resolved, &expected) - .expect("exact Expected Heimdall should match discovery"); - let substitute = HeimdallDependencyBinding { - provider_id: "another-heimdall".into(), - endpoint: expected.endpoint, - }; - assert!(require_expected_heimdall_boundary(&resolved, &substitute).is_err()); } #[test] diff --git a/crates/ghostlight-dungeon/src/play.rs b/crates/ghostlight-dungeon/src/play.rs index b69b308..6dbc90a 100644 --- a/crates/ghostlight-dungeon/src/play.rs +++ b/crates/ghostlight-dungeon/src/play.rs @@ -15,7 +15,7 @@ use std::{ collections::VecDeque, - path::{Path, PathBuf}, + path::Path, sync::{ Arc, atomic::{AtomicBool, Ordering}, @@ -23,8 +23,7 @@ use std::{ time::Duration, }; -use anyhow::{Context, anyhow, bail}; -use base64::Engine; +use anyhow::{Context, bail}; use chrono::Utc; use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore}; use ghostlight::{ @@ -67,32 +66,7 @@ use crate::{ }; const STORE_TYPE: &str = "ghostlight.play_turn_store.v1"; -/// PA.f172 bumped this from v1 to v2 when `question_surface_version` was -/// added to `PlayTurn` without `#[serde(default)]`. PA.f170 (Cut 13) bumps it -/// again, v2 to v3: `question_surface_version` is deleted outright (the -/// version-only staleness comparison it served is gone, replaced by the -/// opaque per-question `question_token`) and `question_token` carries -/// `#[serde(default)]` in its place, for exactly the same reason — a v1 or v2 -/// row's own bytes never had either field, so the same current struct decodes -/// either as `None`. `open` still gates strictly on the row's own declared -/// `schema_id` (a legacy branch recognizes `LEGACY_STORE_SCHEMA_V1` and -/// `LEGACY_STORE_SCHEMA_V2` by name, never silently), but once recognized, -/// upgrades the row to `STORE_SCHEMA` in place rather than discarding the -/// turn it names as unreadable. A row recovered this way whose question is -/// still open (`state == AwaitingPlayer`) mints a fresh token as part of the -/// upgrade — no earlier schema ever recorded one, and the card is re-rendered -/// with whatever the row holds, so a player returning to an upgraded session -/// can still answer. const STORE_SCHEMA: &str = "ghostlight.play_turn_store.v3"; -/// The schema id every row written before `question_surface_version` existed -/// carries. Recognized by `PlayTurnStore::open` as legacy, not corrupt, and -/// upgraded to `STORE_SCHEMA` in place (PA.f172, PA.f170). -const LEGACY_STORE_SCHEMA_V1: &str = "ghostlight.play_turn_store.v1"; -/// The schema id every row written between PA.f172 and PA.f170 carries: it -/// has `question_surface_version` (now deleted) but not `question_token`. -/// Recognized by `PlayTurnStore::open` as legacy, not corrupt, and upgraded -/// to `STORE_SCHEMA` in place the same way a v1 row is (PA.f170). -const LEGACY_STORE_SCHEMA_V2: &str = "ghostlight.play_turn_store.v2"; const STORE_KEY: &str = "primary"; /// The one round budget: exhausting it closes the turn and narrates, rather @@ -296,16 +270,7 @@ struct PlayTurn { /// stays the store's current one. Once the turn closes, this list is /// archived into the store's own `KeyLedger` (PA.f83), which is where a /// replay of one of these keys is recognized after a new turn has opened - /// in this one's place. `#[serde(default)]` (PA.f177): PA.f95's original - /// reasoning covered only the *current*-schema (v3) strict path, where it - /// still holds — `to_vec_named` always emits this field, so a v3 row that - /// omitted it re-encodes to different bytes and the canonical check still - /// bails. It did not cover the *legacy* v1/v2 branches: a row older than - /// this field's own introduction still carries `LEGACY_STORE_SCHEMA_V1`, - /// so without a default `upgrade_legacy_row`'s decode itself failed with - /// "missing field `applied_keys`", `PlayTurnStore::open` returned `Err`, - /// and `state.play` went `None` — silently, forever, on every restart. - #[serde(default)] + /// in this one's place. applied_keys: Vec, opening_prompt: String, player_prose: Vec, @@ -318,21 +283,8 @@ struct PlayTurn { /// cleared alongside `question`. It carries no turn id, round, slot, /// subject, or any other world handle — it is an answer's handle and /// nothing else (invariant 8: reading it in devtools teaches nothing - /// about the world). This replaces PA.f161's `question_surface_version` - /// and the version-only staleness comparison it served: two questions - /// opened in the same turn carry the same surface version (asking is - /// conversational and never moves it), so a version comparison alone - /// cannot tell them apart — the gap Soul proved for PA.f170. Runtime's - /// `world.play` arm refuses an answer whose own token does not name this - /// one. `#[serde(default)]`, matching the earlier `question_surface_version` - /// reasoning it replaces: a row written under `LEGACY_STORE_SCHEMA_V1` or - /// `LEGACY_STORE_SCHEMA_V2` never had this field, so the same current - /// struct decodes it to `None` for either — exactly what "no question - /// ever recorded a token" means for a turn that old. `PlayTurnStore::open` - /// mints a fresh one for a recovered row whose question is still open, so - /// an upgraded session stays answerable; the canonical re-encode check - /// below still holds current-schema (v3) rows to their exact bytes. - #[serde(default)] + /// about the world). Runtime's `world.play` arm refuses an answer whose + /// own token does not name this one. question_token: Option, refusal: Option, narration: Option, @@ -342,11 +294,6 @@ struct PlayTurn { /// snapshot, or narrate failure after the turn opened (PA.f85/PA.f93), or /// a kernel `Invariant` error poisoned the table (PA.f66b). `None` for a /// turn that closed through `end_turn` or the round budget. - /// `#[serde(default)]` (PA.f177): same reasoning as `applied_keys` above - /// — the current-schema canonical check still holds a v3 row to it, and a - /// legacy row older than this field's own introduction now decodes it as - /// `None` instead of failing `upgrade_legacy_row` outright. - #[serde(default)] fault: Option, state: PlayTurnState, } @@ -534,15 +481,7 @@ impl PlayTurnStore { .validate_path_identity() .context("play-turn store path identity is invalid")?; let rows = store.pull_all()?; - // PA.f193-E/PA.f194-E: the third element is the sidecar path a - // retirement wrote this call, `None` on every ordinary path (fresh - // init, a row that decoded/upgraded cleanly). Nothing on - // `PlayTurnStore` itself keeps it — `PlayTable::retired_row_sidecar` - // scans the store's own directory fresh on every `/health` read - // instead, so a retirement a *prior* process performed is still - // reported after a restart, not only by the process whose own `open` - // happened to perform it. - let (row, state, _retired_sidecar) = match rows.as_slice() { + let (row, state) = match rows.as_slice() { [] => { let state = PlayTurnStoreState { schema: STORE_SCHEMA.into(), @@ -554,167 +493,26 @@ impl PlayTurnStore { if !store.compare_and_swap_batch(&[], vec![row.clone()])? { bail!("play-turn store changed during initialization"); } - (row, state, None) + (row, state) } - // PA.f184: a row already at the current schema id can still fail - // to read — genuinely corrupt bytes, or (the realistic trigger) a - // future change to `PlayTurn`'s field set or order that lands - // without moving `STORE_SCHEMA`, which flips the canonical - // re-encode check below without touching `schema_id` at all. - // Before this fix every one of those three checks `bail!`ed - // unconditionally, so `open` failed the identical way on every - // future restart and the play card stayed gone until an operator - // deleted the store by hand — exactly the PA.f177 gap, but for a - // row this store itself is supposed to already understand. Now it - // retires through the same `retire_unreadable_row` path the - // legacy arms use, so a damaged or future-schema row loses its - // one turn instead of the whole play surface. [row] if row.r#type == STORE_TYPE && row.key == STORE_KEY && row.schema_id.as_deref() == Some(STORE_SCHEMA) => { - match read_current_schema_row(row) { - Ok(state) => (row.clone(), state, None), - Err(CurrentSchemaRowError::Decode(error)) => { - let (row, state, sidecar) = - retire_unreadable_row(&store, path.as_ref(), row, STORE_SCHEMA, &error)?; - (row, state, Some(sidecar)) - } - // PA.f193-A/B: not a decode failure — the row's bytes - // parsed into a `PlayTurnStoreState` perfectly fine, and - // either the canonical re-encode check or the inner - // `schema` tag disagreed. The row is left untouched and - // `open` fails loudly, the same shape `upgrade_legacy_row` - // already uses for its own `Other` arm (PA.f185), instead - // of destroying a turn that decoded just fine. - Err(CurrentSchemaRowError::Other(error)) => { - return Err(error).context("reading a current-schema play-turn row failed"); - } + let state: PlayTurnStoreState = + rmp_serde::from_slice(&row.payload).context("play-turn state is corrupt")?; + if rmp_serde::to_vec_named(&state)? != row.payload { + bail!("play-turn state is not canonical"); } - } - // PA.f172/PA.f170: a row written before `question_token` existed - // — named legacy, not corrupt, because it is neither: it is a - // real, previously-canonical shape this process itself wrote, - // under the schema id that was current when it did. - // `question_token` carries `#[serde(default)]`, so the very same - // `PlayTurnStoreState` decodes it correctly (the field reads back - // `None`, matching what "no question ever recorded a token" - // means for a turn this old). `upgrade_legacy_row` mints a fresh - // token when the recovered turn's own question is still open, - // upgrades the row to `STORE_SCHEMA` (v3) in place, and persists - // that upgrade immediately, so the legacy path is only ever taken - // once per row; the canonical re-encode check does not apply - // here — a legacy row's bytes were never canonical under v3 and - // were never meant to be — it resumes for every write this store - // makes from here on. - // PA.f177: `upgrade_legacy_row`'s own decode can still fail — a - // row older than `applied_keys`/`fault` themselves, or one that - // is genuinely damaged — even though the schema id names it - // recognizably legacy. That is no longer treated as "open must - // fail and every future open must fail on the exact same row"; - // the row is retired to a sidecar file and the store starts - // fresh instead (see `retire_unreadable_row`). - [row] - if row.r#type == STORE_TYPE - && row.key == STORE_KEY - && row.schema_id.as_deref() == Some(LEGACY_STORE_SCHEMA_V1) => - { - match upgrade_legacy_row(&store, row, LEGACY_STORE_SCHEMA_V1) { - Ok((row, state)) => (row, state, None), - Err(LegacyRowError::Decode(error)) => { - let (row, state, sidecar) = retire_unreadable_row( - &store, - path.as_ref(), - row, - LEGACY_STORE_SCHEMA_V1, - &error, - )?; - (row, state, Some(sidecar)) - } - // PA.f185: not a decode failure — an inner `schema` tag - // that disagrees with the envelope, or a lost - // compare-and-swap race — so the row is left untouched - // and `open` fails loudly instead of destroying a turn - // that decoded just fine. - Err(LegacyRowError::Other(error)) => { - return Err(error).context("upgrading a legacy play-turn row failed"); - } + if state.schema != STORE_SCHEMA { + bail!("play-turn state schema is invalid"); } + (row.clone(), state) } - // PA.f170: a row written between PA.f172 and PA.f170 — it has - // `question_surface_version` (deleted, silently ignored on - // decode since nothing here reads it) but no `question_token`. - // Upgraded exactly like a v1 row above; PA.f177's own retirement - // fallback applies here too. - [row] - if row.r#type == STORE_TYPE - && row.key == STORE_KEY - && row.schema_id.as_deref() == Some(LEGACY_STORE_SCHEMA_V2) => - { - match upgrade_legacy_row(&store, row, LEGACY_STORE_SCHEMA_V2) { - Ok((row, state)) => (row, state, None), - Err(LegacyRowError::Decode(error)) => { - let (row, state, sidecar) = retire_unreadable_row( - &store, - path.as_ref(), - row, - LEGACY_STORE_SCHEMA_V2, - &error, - )?; - (row, state, Some(sidecar)) - } - Err(LegacyRowError::Other(error)) => { - return Err(error).context("upgrading a legacy play-turn row failed"); - } - } - } - // PA.f184/PA.f194-A: our own key and type, but a schema id none - // of the arms above recognize — a future schema this build has - // never seen, not foreign data. That alone does not mean the row - // is unreadable: an Idunn rollback across a schema-id move can - // hand this build a row stamped with a schema id it has never - // seen whose bytes still decode cleanly under the current - // `PlayTurnStoreState` shape (nothing about the struct changed, - // only the id). Before this fix, every unrecognized schema id - // was retired on the id alone, with no decode attempted — a - // canonical, perfectly readable row lost its one open turn, and - // the sidecar's own `reason` claimed the row "could not be read" - // when nothing had tried. Attempt the decode first, exactly like - // the current- and legacy-schema arms above: retire only on a - // genuine decode failure; a row that decodes cleanly is left - // untouched and `open` fails loudly instead, so an operator sees - // the mismatch rather than losing the turn silently. Multiple - // rows, or a row under a different `type`/`key` entirely, still - // bail below: that is genuinely foreign content this store must - // not guess about destroying. - [row] if row.r#type == STORE_TYPE && row.key == STORE_KEY => { - match rmp_serde::from_slice::(&row.payload) { - Ok(_) => { - return Err(anyhow!( - "play-turn row declares unrecognized schema {:?} but its payload decodes \ - cleanly under the current PlayTurnStoreState shape; refusing to retire a \ - readable row (PA.f194-A) — open a build that recognizes this schema", - row.schema_id - )); - } - Err(decode_error) => { - let reason = anyhow::Error::new(decode_error).context(format!( - "play-turn row declares unrecognized schema {:?}", - row.schema_id - )); - let (row, state, sidecar) = retire_unreadable_row( - &store, - path.as_ref(), - row, - row.schema_id.as_deref().unwrap_or(""), - &reason, - )?; - (row, state, Some(sidecar)) - } - } - } - _ => bail!("play-turn store contains foreign or otherwise-unreadable records; start with a fresh store"), + _ => bail!( + "play-turn store contains foreign or mismatched-schema records; start with a fresh store" + ), }; Ok(Self { store, @@ -835,296 +633,11 @@ fn envelope(state: &PlayTurnStoreState) -> anyhow::Result { /// with no world meaning of its own — not a `QuestionId`, not a subject, /// turn, round, or slot, and forging one only answers the forger's own /// already-open question (invariant 8). `execute_round`'s `ASK_PLAYER_TOOL` -/// arm mints one every time a question opens; `upgrade_legacy_row` mints one -/// for a recovered legacy row whose question is still open, since no earlier -/// schema ever recorded one. +/// arm mints one every time a question opens. fn mint_question_token() -> String { uuid::Uuid::new_v4().to_string() } -/// `upgrade_legacy_row`'s own error, split by whether the row was actually -/// unreadable (PA.f185). Soul's probe: a row whose envelope declares -/// `LEGACY_STORE_SCHEMA_V1` and whose inner `schema` field says -/// `LEGACY_STORE_SCHEMA_V2` decodes its turn perfectly — `opening_prompt`, -/// `question`, every field reads back intact — but the inner-schema -/// consistency check below, and a lost `compare_and_swap_batch` race while -/// persisting the upgrade, both used to be indistinguishable from "the bytes -/// would not parse at all" once `PlayTurnStore::open` caught the `Err`: every -/// exit landed in `retire_unreadable_row`, destroying a readable turn under a -/// sidecar reason ("did not decode even leniently") that was false for -/// either case. Only `Decode` is that genuine case; `Other` propagates as an -/// ordinary `open` failure instead, so a schema-tag mismatch is diagnosable -/// and a transient CAS race can be retried, rather than both being treated as -/// permanent corruption and quietly erased. -enum LegacyRowError { - Decode(anyhow::Error), - Other(anyhow::Error), -} - -/// Shared by `PlayTurnStore::open`'s `LEGACY_STORE_SCHEMA_V1` and -/// `LEGACY_STORE_SCHEMA_V2` branches (PA.f170): decodes `row` under the -/// current `PlayTurnStoreState`/`PlayTurn` structs — both legacy schemas -/// decode through exactly the same `#[serde(default)]` fields a current- -/// schema row would — mints a fresh `question_token` when the recovered -/// turn's own question is still open (no earlier schema ever recorded one), -/// then upgrades the row to `STORE_SCHEMA` in place and persists that -/// upgrade immediately, so the legacy path is only ever taken once per row. -fn upgrade_legacy_row( - store: &OwnedRedbMessagePackBackingStore, - row: &CultCacheEnvelope, - legacy_schema: &str, -) -> Result<(CultCacheEnvelope, PlayTurnStoreState), LegacyRowError> { - let mut state: PlayTurnStoreState = rmp_serde::from_slice(&row.payload) - .with_context(|| format!("play-turn legacy {legacy_schema} state is corrupt")) - .map_err(LegacyRowError::Decode)?; - if state.schema != legacy_schema { - return Err(LegacyRowError::Other(anyhow!( - "play-turn legacy {legacy_schema} state schema is invalid: payload itself declares {:?}", - state.schema - ))); - } - if let Some(turn) = state.turn.as_mut() - && turn.state == PlayTurnState::AwaitingPlayer - && turn.question.is_some() - && turn.question_token.is_none() - { - turn.question_token = Some(mint_question_token()); - } - state.schema = STORE_SCHEMA.into(); - let upgraded_row = envelope(&state).map_err(LegacyRowError::Other)?; - match store.compare_and_swap_batch(std::slice::from_ref(row), vec![upgraded_row.clone()]) { - Ok(true) => Ok((upgraded_row, state)), - Ok(false) => Err(LegacyRowError::Other(anyhow!( - "play-turn store changed while upgrading a legacy {legacy_schema} row" - ))), - Err(error) => Err(LegacyRowError::Other(error)), - } -} - -/// `read_current_schema_row`'s own error, split the same way -/// `upgrade_legacy_row`'s is (PA.f185, here PA.f193-A/B): only a genuine -/// decode failure means the row is actually unreadable. A row whose bytes -/// parse into a `PlayTurnStoreState` but fail the canonical re-encode check, -/// or whose inner `schema` field disagrees with the envelope's own -/// `STORE_SCHEMA`, has a perfectly readable turn inside it — before this fix -/// both cases reached `PlayTurnStore::open` as a plain `anyhow::Error` and -/// were routed into `retire_unreadable_row` exactly like a genuine decode -/// failure, destroying a turn that decoded fine. Only `Decode` is that -/// genuine case; `Other` propagates as an ordinary `open` failure instead, -/// leaving the row untouched. -enum CurrentSchemaRowError { - Decode(anyhow::Error), - Other(anyhow::Error), -} - -/// `PlayTurnStore::open`'s current-schema arm (PA.f184): a row already -/// declaring `STORE_SCHEMA` can still fail to read — genuinely corrupt bytes, -/// or a future change to `PlayTurn`'s own field set or order that lands -/// without moving `STORE_SCHEMA`, which the canonical re-encode check below -/// exists to catch. Unlike `upgrade_legacy_row` (PA.f185), there is no -/// upward-migration path for a current-schema row that fails one of these — -/// nothing upgrades it in place — but that does not make every exit here -/// retirement-worthy: the canonical check and the inner-schema check both run -/// only after the decode has already succeeded, so a row that fails either -/// one is readable, not corrupt (PA.f193-A/B). -fn read_current_schema_row(row: &CultCacheEnvelope) -> Result { - let state: PlayTurnStoreState = rmp_serde::from_slice(&row.payload) - .context("play-turn state is corrupt") - .map_err(CurrentSchemaRowError::Decode)?; - let reencoded = rmp_serde::to_vec_named(&state) - .context("re-encoding play-turn state failed") - .map_err(CurrentSchemaRowError::Other)?; - if reencoded != row.payload { - return Err(CurrentSchemaRowError::Other(anyhow!("play-turn state is not canonical"))); - } - if state.schema != STORE_SCHEMA { - return Err(CurrentSchemaRowError::Other(anyhow!("play-turn state schema is invalid"))); - } - Ok(state) -} - -/// A legacy row's payload, `type`, `key` and `schema_id`, preserved for -/// whoever the operator hands `retire_unreadable_row`'s sidecar file to -/// (Soul's owed item 5). This is the one deliberate exception to the GameCult -/// substrate doctrine's "no load-bearing JSON": the doctrine's own carve-out -/// is content that exists to communicate with "the Non-CultNet xenos", and an -/// operator opening a forensic dump by hand with a text editor is exactly -/// that boundary, not a CultCache consumer. The msgpack form this replaced -/// was preservation in name only — nothing in this Body could read it back, -/// an operator included, without writing a one-off decoder first. JSON here -/// is readable directly; `payload_base64` carries the row's original bytes -/// verbatim (standard, padded alphabet) so nothing is lost, proven by the -/// round-trip test below. -#[derive(Serialize)] -struct RetiredPlayTurnRow<'a> { - retired_at: String, - reason: String, - r#type: &'a str, - key: &'a str, - schema_id: Option<&'a str>, - stored_at: &'a str, - payload_base64: String, -} - -/// `PlayTurnStore::open`'s fallback when a row this build recognizes by its -/// `schema_id` (legacy or current) still cannot be turned into a usable -/// `PlayTurnStoreState` — a row older than `applied_keys`/`fault` themselves -/// (PA.f177), one genuinely damaged past what a schema-shape upgrade can -/// recover, a current-schema row whose bytes no longer round-trip -/// canonically (PA.f184), or a schema id no arm above recognizes at all. Before -/// PA.f177 this row made `open` return `Err` unconditionally: `open_play` -/// caught that, logged it, and left `state.play` `None` — every future `open` -/// hit the identical row and failed the identical way, so the play card -/// stayed gone until an operator deleted the store by hand. The invariant is -/// that a daemon never answers an unreadable row by quietly having no play -/// surface, so this writes the row, byte for byte, to a sidecar file beside -/// the store (named for what it is, so it reads as forensic evidence and not -/// as another store — PA.f192: the extension is `.json`, not `.cc`, since -/// this sidecar is a one-shot forensic dump, never a CultCache store some -/// future process might mistake it for and try to open; Soul's owed item 5: -/// the content really is JSON, an operator-readable text file with the row's -/// original bytes preserved verbatim as base64 — see `RetiredPlayTurnRow`'s -/// own doc comment for why JSON here does not violate the GameCult substrate -/// doctrine), clears the row -/// through the store's own compare-and-swap (the same guard `swap_in` uses -/// for every other write — this is not a second, unguarded writer), and -/// returns a fresh, empty state so `open` succeeds and play starts fresh. -/// Logged at `warn`, so the fact reaches the operator through the same log -/// stream `runtime.rs`'s own `open_play` failure warning already uses, next -/// to the `playStatus` the operator already checks (PA.f193-E: -/// `PlayTable::retired_row_sidecar` reports it structurally too, by scanning -/// the store's own directory fresh on every read rather than trusting a flag -/// cached at `open` — see that method's own doc comment for why a cached -/// per-process flag is not enough for `/health` to survive a restart). -/// -/// PA.f189: two orderings matter here and are both deliberate. -/// - The sidecar write happens *before* the destructive compare-and-swap. -/// If the write fails, this returns `Err` without ever touching the row — -/// `open` fails loudly and the original row is exactly where it was, so a -/// disk-full or permission failure never destroys evidence it could not -/// also preserve. -/// - If the write succeeds but the compare-and-swap below then fails — the -/// store changed identity mid-retirement, another writer raced this one, -/// or custody was lost — this still returns `Err`. The sidecar file it -/// already wrote is *not* cleaned up: nothing here can tell whether the -/// race means the original row is still there (safe to retry retirement, -/// which would then write a second, differently-timestamped sidecar) or -/// already gone some other way. An orphaned sidecar from a failed -/// retirement is therefore an expected, if rare, shape — a forensic -/// leftover with no corresponding successful retirement — and an operator -/// clearing them out should confirm the row it names is actually resolved -/// (upgraded, retired again, or the store rebuilt) before deleting one. -/// -/// **Precondition (PA.f194-A):** the caller must have already attempted to -/// decode `row`'s payload and that attempt must have failed — `decode_error` -/// is trusted verbatim into the sidecar's own `reason` field ("could not be -/// read: ..."), so a caller that has not actually tried to read the row makes -/// that claim false. This function performs no decode of its own to verify -/// it. An unrecognized `schema_id` alone is not evidence of unreadability: a -/// row can declare a schema this build has never seen and still decode -/// cleanly under the current `PlayTurnStoreState` shape (a future schema -/// built from an identical struct, surfaced by an Idunn rollback across a -/// schema-id move). `PlayTurnStore::open`'s own unrecognized-schema arm -/// attempts a decode first and only calls this on genuine decode failure, -/// exactly like its current- and legacy-schema siblings. -fn retire_unreadable_row( - store: &OwnedRedbMessagePackBackingStore, - store_path: &Path, - row: &CultCacheEnvelope, - declared_schema: &str, - decode_error: &anyhow::Error, -) -> anyhow::Result<(CultCacheEnvelope, PlayTurnStoreState, PathBuf)> { - let reason = format!("row declared schema {declared_schema} but could not be read: {decode_error:#}"); - let sidecar = retired_row_sidecar_path(store_path); - let record = RetiredPlayTurnRow { - retired_at: Utc::now().to_rfc3339(), - reason: reason.clone(), - r#type: &row.r#type, - key: &row.key, - schema_id: row.schema_id.as_deref(), - stored_at: &row.stored_at, - payload_base64: base64::engine::general_purpose::STANDARD.encode(&row.payload), - }; - // Pretty-printed (Soul's owed item 5): this file exists for an operator - // to open and read, not for a machine to round-trip efficiently, so - // legibility wins over byte count. - let bytes = serde_json::to_vec_pretty(&record).context("encoding the retired play-turn row failed")?; - std::fs::write(&sidecar, &bytes) - .with_context(|| format!("writing the retired play-turn row to {} failed", sidecar.display()))?; - - let fresh = PlayTurnStoreState { - schema: STORE_SCHEMA.into(), - turn: None, - ledger: KeyLedger::default(), - revision: 0, - }; - let fresh_row = envelope(&fresh)?; - if !store.compare_and_swap_batch(std::slice::from_ref(row), vec![fresh_row.clone()])? { - bail!("play-turn store changed while retiring an unreadable row (the sidecar at {} was already written and is left in place)", sidecar.display()); - } - - tracing::warn!( - sidecar = %sidecar.display(), - reason = %reason, - "a play-turn row could not be read; it was retired to a sidecar file and play starts fresh" - ); - - Ok((fresh_row, fresh, sidecar)) -} - -/// Beside the store, named for what it is: -/// `.retired-unreadable-row..json` (PA.f192, -/// extension renamed from `.msgpack` for Soul's owed item 5, since the -/// content is now genuinely JSON — see `RetiredPlayTurnRow`'s own doc -/// comment). Timestamped so a second unreadable row (a different corruption, -/// on a later run) never collides with or silently overwrites the first -/// one's evidence, and so `retired_row_sidecars_on_disk`'s own lexicographic -/// sort is also chronological. Not `.cc`: this file is a one-shot forensic -/// dump written through `std::fs::write`, never through a -/// `CacheBackingStore`, and never meant to be opened as a CultCache store. -fn retired_row_sidecar_path(store_path: &Path) -> PathBuf { - let stamp = Utc::now().format("%Y%m%dT%H%M%S%.6fZ"); - let stem = store_path - .file_stem() - .and_then(|stem| stem.to_str()) - .unwrap_or("play-turn"); - store_path.with_file_name(format!("{stem}.retired-unreadable-row.{stamp}.json")) -} - -/// PA.f193-E: every sidecar `retire_unreadable_row` has ever written beside -/// `store_path`, oldest first (the timestamp sorts lexicographically, since -/// `retired_row_sidecar_path`'s own stamp format is fixed-width and -/// zero-padded). A fresh directory scan on every call, not a fact cached once -/// at `open` — the whole point is that this survives a restart: a clean -/// reopen after a retirement finds no unreadable row of its own to retire, -/// but the *evidence* that a prior process retired one is still sitting on -/// disk until an operator clears it. Filters by this store's own filename -/// stem so a second, unrelated `.cc` store's sidecars in the same directory -/// are never mixed in. -fn retired_row_sidecars_on_disk(store_path: &Path) -> Vec { - let Some(directory) = store_path.parent() else { - return Vec::new(); - }; - let Some(stem) = store_path.file_stem().and_then(|stem| stem.to_str()) else { - return Vec::new(); - }; - let prefix = format!("{stem}.retired-unreadable-row."); - let Ok(entries) = std::fs::read_dir(directory) else { - return Vec::new(); - }; - let mut sidecars: Vec = entries - .filter_map(|entry| entry.ok()) - .map(|entry| entry.path()) - .filter(|path| { - path.file_name() - .and_then(|name| name.to_str()) - .is_some_and(|name| name.starts_with(&prefix) && name.ends_with(".json")) - }) - .collect(); - sidecars.sort(); - sidecars -} - #[derive(Debug, thiserror::Error)] pub(crate) enum PlayError { #[error("the play table is poisoned by a prior kernel invariant fault; restart to clear it")] @@ -1338,14 +851,6 @@ pub(crate) struct PlayTable { /// written. Held in memory only: a restart before the entry lands loses /// the link, never the entry. pending_retry: std::sync::Mutex>, - /// PA.f186/PA.f193-E: the store's own on-disk path, kept beside `store` - /// so `retired_row_sidecar` can scan for sidecars without taking - /// `store`'s lock. Not the fact of a retirement itself — that is derived - /// fresh from disk on every read, on purpose: a cached "did this - /// process's own `open` retire something" flag reported `ok` again after - /// any restart, even though the sidecar evidence a prior process wrote - /// was still sitting right there. - store_path: PathBuf, /// One turn at a time for this table (PA.f68/PA.f112): held for the /// whole body of `run`, so the key check and the turn open happen under /// one acquisition and two concurrent `run` calls can never interleave. @@ -1394,8 +899,8 @@ impl PlayTable { store_path: impl AsRef, ) -> anyhow::Result { let play = PlayPort::new(world.clone()); - let store_path = store_path.as_ref().to_path_buf(); - let store = PlayTurnStore::open(&store_path)?; + let store_path = store_path.as_ref(); + let store = PlayTurnStore::open(store_path)?; // Beside the play row, named from it: one log per play store. let log = TurnLog::open(store_path.with_extension("turn-log.cc"))?; Ok(Self { @@ -1410,7 +915,6 @@ impl PlayTable { knobs: None, log: Mutex::new(log), pending_retry: std::sync::Mutex::new(None), - store_path, run_lock: Arc::new(Mutex::new(())), poisoned: AtomicBool::new(false), retry_delay_base_ms: std::sync::atomic::AtomicU64::new(RETRY_DELAY_BASE_MS), @@ -1435,19 +939,6 @@ impl PlayTable { self.log.lock().await.last_seq() } - /// PA.f186/PA.f193-E: the most recent sidecar this store's directory - /// carries, if any — not only one this process's own `open` wrote. - /// Scanned fresh from disk on every call (`retired_row_sidecars_on_disk`, - /// one directory listing), so `runtime.rs`'s `/health` surface reports a - /// retirement across a restart: a clean reopen after a retirement finds - /// no unreadable row of its own, but the sidecar a prior process wrote is - /// still on disk until an operator clears it, and this keeps naming it. - /// `None` once every sidecar for this store has actually been cleared — - /// a healthy daemon still reports plain `ok`. - pub(crate) fn retired_row_sidecar(&self) -> Option { - retired_row_sidecars_on_disk(&self.store_path).pop() - } - /// Installs PA.f99's own before-submit test hook (see the field's own /// doc comment). Test-only: no production call site exists. #[cfg(test)] @@ -3499,31 +2990,6 @@ pub(crate) mod tests { }; use tokio::task::JoinHandle; - /// PA.f186's own cross-module seam: `runtime.rs`'s readiness tests need - /// to prove a retirement during `PlayTable::new` reaches `/health` - /// end-to-end, but `STORE_TYPE`/`STORE_KEY`/`STORE_SCHEMA` and - /// `CultCacheEnvelope` are this module's own store internals. Rather than - /// re-importing `cultcache_rs` and duplicating this shape in - /// `runtime.rs`, this writes one row `PlayTurnStore::open` cannot read — - /// the exact same undecodable-bytes shape - /// `a_row_with_the_current_schema_id_and_undecodable_bytes_is_retired_to_a_sidecar_and_play_starts_fresh` - /// seeds below — at `store_path`, before a caller opens a `PlayTable` - /// over it. - pub(crate) fn seed_unreadable_row_for_test(store_path: &std::path::Path) { - let corrupt_row = CultCacheEnvelope { - key: STORE_KEY.into(), - r#type: STORE_TYPE.into(), - payload: vec![0xC1], // msgpack's own reserved "never used" marker byte - stored_at: Utc::now().to_rfc3339(), - schema_id: Some(STORE_SCHEMA.into()), - }; - let raw_store = OwnedRedbMessagePackBackingStore::new(store_path).unwrap(); - assert!( - raw_store.compare_and_swap_batch(&[], vec![corrupt_row]).unwrap(), - "seeding the corrupt row must succeed against an empty store" - ); - } - /// Every `.rs` file under `src`, with everything a `#[cfg(test)]` item /// removed, the same extent-by-indent scan `app_session.rs`'s own /// forbidden-writer test uses. @@ -4638,890 +4104,123 @@ pub(crate) mod tests { ); } - /// A pre-Cut-11 process's own `PlayTurn`, replicated field-for-field - /// minus `question_surface_version`/`question_token` — the shape every - /// row actually written under `LEGACY_STORE_SCHEMA_V1` carries (PA.f172). - /// Test-only: no production writer ever mints this shape again. - #[derive(Clone, Serialize)] - struct LegacyPlayTurnV1 { - turn_id: String, - applied_keys: Vec, - opening_prompt: String, - player_prose: Vec, - rounds: Vec, - calls: Vec, - persona_turns: Vec<(SubjectId, PersonaTurn)>, - question: Option, - refusal: Option, - narration: Option, - fault: Option, - state: PlayTurnState, - } + #[test] + fn open_refuses_mismatched_schema_or_unreadable_rows_without_migration_or_sidecars() { + for schema in [ + "ghostlight.play_turn_store.v1", + "ghostlight.play_turn_store.v2", + "ghostlight.play_turn_store.v4", + ] { + let directory = tempfile::tempdir().unwrap(); + let store_path = directory.path().join("play-turn-v1.cc"); + let state = PlayTurnStoreState { + schema: schema.into(), + turn: None, + ledger: KeyLedger::default(), + revision: 3, + }; + let row = CultCacheEnvelope { + key: STORE_KEY.into(), + r#type: STORE_TYPE.into(), + payload: rmp_serde::to_vec_named(&state).unwrap(), + stored_at: Utc::now().to_rfc3339(), + schema_id: Some(schema.into()), + }; + { + let raw_store = OwnedRedbMessagePackBackingStore::new(&store_path).unwrap(); + assert!(raw_store.compare_and_swap_batch(&[], vec![row]).unwrap()); + } - #[derive(Clone, Serialize)] - struct LegacyPlayTurnStoreStateV1 { - schema: String, - turn: Option, - ledger: KeyLedger, - revision: u64, - } - - /// A between-PA.f172-and-PA.f170 process's own `PlayTurn`: it has - /// `question_surface_version` (deleted by this cut) but not - /// `question_token` — the shape every row actually written under - /// `LEGACY_STORE_SCHEMA_V2` carries. Test-only: no production writer - /// ever mints this shape again. - #[derive(Clone, Serialize)] - struct LegacyPlayTurnV2 { - turn_id: String, - applied_keys: Vec, - opening_prompt: String, - player_prose: Vec, - rounds: Vec, - calls: Vec, - persona_turns: Vec<(SubjectId, PersonaTurn)>, - question: Option, - question_surface_version: Option, - refusal: Option, - narration: Option, - fault: Option, - state: PlayTurnState, - } - - #[derive(Clone, Serialize)] - struct LegacyPlayTurnStoreStateV2 { - schema: String, - turn: Option, - ledger: KeyLedger, - revision: u64, - } - - /// PA.f172: a row written before `question_token` existed — under - /// `LEGACY_STORE_SCHEMA_V1`, the schema id every pre-Cut-11 process - /// actually wrote (it is exactly what `STORE_SCHEMA` used to be) — is - /// recognized by `PlayTurnStore::open` as legacy, not corrupt, and its - /// turn recovered rather than discarded: the missing field decodes to - /// `None`, exactly what "no question ever recorded a token" means for a - /// turn this old. The row is also upgraded to `STORE_SCHEMA` in place, - /// durably, so the legacy path is only ever taken once. - /// - /// Mutation: remove the `schema_id.as_deref() == - /// Some(LEGACY_STORE_SCHEMA_V1)` arm from `PlayTurnStore::open` — this - /// row would then fall through to the catch-all and `open` would return - /// `Err`, exactly PA.f172's own bug: a workstation's pre-Cut-11 row - /// silently disables play with "the play table is unavailable". - #[tokio::test] - async fn a_legacy_v1_row_is_recognized_and_upgraded_not_refused_as_corrupt() { - let directory = tempfile::tempdir().unwrap(); - let store_path = directory.path().join("play-turn-v1.cc"); - - let legacy_turn = LegacyPlayTurnV1 { - turn_id: "11111111-1111-1111-1111-111111111111".into(), - applied_keys: vec!["key-a".into()], - opening_prompt: "You stand at the gate.".into(), - player_prose: vec!["I knock.".into()], - rounds: Vec::new(), - calls: Vec::new(), - persona_turns: Vec::new(), - question: None, - refusal: None, - narration: None, - fault: None, - state: PlayTurnState::Running, - }; - let legacy_state = LegacyPlayTurnStoreStateV1 { - schema: LEGACY_STORE_SCHEMA_V1.into(), - turn: Some(legacy_turn), - ledger: KeyLedger::default(), - revision: 3, - }; - let legacy_row = CultCacheEnvelope { - key: STORE_KEY.into(), - r#type: STORE_TYPE.into(), - payload: rmp_serde::to_vec_named(&legacy_state).unwrap(), - stored_at: Utc::now().to_rfc3339(), - schema_id: Some(LEGACY_STORE_SCHEMA_V1.into()), - }; - { - let raw_store = OwnedRedbMessagePackBackingStore::new(&store_path).unwrap(); + let error = PlayTurnStore::open(&store_path) + .err() + .expect("mismatched schema version must be refused on open"); assert!( - raw_store - .compare_and_swap_batch(&[], vec![legacy_row]) - .unwrap(), - "seeding the legacy row must succeed against an empty store" + format!("{error:#}").contains("mismatched-schema"), + "unexpected error for {schema}: {error:#}" ); + assert!( + std::fs::read_dir(directory.path()) + .unwrap() + .filter_map(|entry| entry.ok()) + .all(|entry| entry.path().extension().and_then(|ext| ext.to_str()) != Some("json")), + "open must not dump a JSON sidecar for {schema}" + ); + let raw_store = OwnedRedbMessagePackBackingStore::new(&store_path).unwrap(); + let rows = raw_store.pull_all().unwrap(); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].schema_id.as_deref(), Some(schema)); } - let store = PlayTurnStore::open(&store_path) - .expect("a genuine pre-Cut-11 row must open, not be refused as corrupt"); - let recovered = store.current().expect("the legacy row's own turn must be recovered"); - assert_eq!(recovered.turn_id, "11111111-1111-1111-1111-111111111111"); - assert_eq!(recovered.opening_prompt, "You stand at the gate."); - assert_eq!( - recovered.question_token, None, - "a pre-Cut-11 turn never recorded a token, and its own question is not open (Running); \ - the missing field must decode to None and no token must be minted for it" - ); - assert_eq!( - store.row.schema_id.as_deref(), - Some(STORE_SCHEMA), - "the legacy row must be upgraded to the current schema in place, not left at v1" - ); - - // Reopening must now take the strict current-schema path, proving - // the upgrade was actually durably persisted, not only held in - // memory on the first `open`. `store` must be dropped first: CultCache's - // own single-owner lock refuses a second `OwnedRedbMessagePackBackingStore::new` - // on the same path while the first is still held (the same custody - // rule `pull_current_from_disk_for_test`'s own doc comment names). - let recovered_turn_id = recovered.turn_id.clone(); - drop(store); - let reopened = PlayTurnStore::open(&store_path).unwrap(); - assert_eq!(reopened.current().unwrap().turn_id, recovered_turn_id); - } - - /// PA.f170: the same recognition and in-place upgrade `a_legacy_v1_row_*` - /// proves, for a row written between PA.f172 and PA.f170 instead — it - /// carries `question_surface_version` (now deleted, silently ignored on - /// decode) but not `question_token`. - /// - /// Mutation: remove the `schema_id.as_deref() == - /// Some(LEGACY_STORE_SCHEMA_V2)` arm from `PlayTurnStore::open` — this - /// row would then fall through to the catch-all and `open` would return - /// `Err`, silently disabling play on any workstation that ran Dungeon - /// between Cut 11 and Cut 13. - #[tokio::test] - async fn a_legacy_v2_row_is_recognized_and_upgraded_not_refused_as_corrupt() { + // Corrupt bytes, non-canonical wire order, and inner-schema mismatches under the current + // schema id are also refused cleanly without writing sidecars. let directory = tempfile::tempdir().unwrap(); - let store_path = directory.path().join("play-turn-v1.cc"); - - let legacy_turn = LegacyPlayTurnV2 { - turn_id: "22222222-2222-2222-2222-222222222222".into(), - applied_keys: vec!["key-b".into()], - opening_prompt: "You stand at the gate.".into(), - player_prose: vec!["I knock.".into()], - rounds: Vec::new(), - calls: Vec::new(), - persona_turns: Vec::new(), - question: None, - question_surface_version: None, - refusal: None, - narration: None, - fault: None, - state: PlayTurnState::Running, - }; - let legacy_state = LegacyPlayTurnStoreStateV2 { - schema: LEGACY_STORE_SCHEMA_V2.into(), - turn: Some(legacy_turn), - ledger: KeyLedger::default(), - revision: 4, - }; - let legacy_row = CultCacheEnvelope { - key: STORE_KEY.into(), - r#type: STORE_TYPE.into(), - payload: rmp_serde::to_vec_named(&legacy_state).unwrap(), - stored_at: Utc::now().to_rfc3339(), - schema_id: Some(LEGACY_STORE_SCHEMA_V2.into()), - }; + let corrupt_path = directory.path().join("corrupt.cc"); { - let raw_store = OwnedRedbMessagePackBackingStore::new(&store_path).unwrap(); - assert!( - raw_store - .compare_and_swap_batch(&[], vec![legacy_row]) - .unwrap(), - "seeding the legacy row must succeed against an empty store" - ); + let raw_store = OwnedRedbMessagePackBackingStore::new(&corrupt_path).unwrap(); + let row = CultCacheEnvelope { + key: STORE_KEY.into(), + r#type: STORE_TYPE.into(), + payload: vec![0xC1], + stored_at: Utc::now().to_rfc3339(), + schema_id: Some(STORE_SCHEMA.into()), + }; + assert!(raw_store.compare_and_swap_batch(&[], vec![row]).unwrap()); } + assert!(PlayTurnStore::open(&corrupt_path).is_err()); - let store = PlayTurnStore::open(&store_path) - .expect("a genuine v2 row must open, not be refused as corrupt"); - let recovered = store.current().expect("the legacy row's own turn must be recovered"); - assert_eq!(recovered.turn_id, "22222222-2222-2222-2222-222222222222"); - assert_eq!( - recovered.question_token, None, - "a v2 turn never recorded a token, and its own question is not open (Running); \ - the missing field must decode to None and no token must be minted for it" - ); - assert_eq!( - store.row.schema_id.as_deref(), - Some(STORE_SCHEMA), - "the legacy row must be upgraded to the current schema in place, not left at v2" - ); - } - - /// PA.f170: an upgraded row whose question is still open gets a freshly - /// minted token as part of the upgrade — no earlier schema ever recorded - /// one, and the card is re-rendered with whatever the row holds, so a - /// player returning to an upgraded session (Raven's workstation, named in - /// the cut's own spec) must still be able to answer. - /// - /// Mutation: remove the mint-if-open branch from `upgrade_legacy_row` — - /// the recovered turn's own `question_token` would then stay `None` while - /// `AwaitingPlayer`, and the answer this test goes on to submit would be - /// refused as stale by `runtime.rs`'s own boundary (no token to match) - /// even though the question is genuinely still open. - #[tokio::test] - async fn an_upgraded_legacy_row_whose_question_is_still_open_mints_a_fresh_token() { - let directory = tempfile::tempdir().unwrap(); - let store_path = directory.path().join("play-turn-v1.cc"); - - let legacy_turn = LegacyPlayTurnV1 { - turn_id: "33333333-3333-3333-3333-333333333333".into(), - applied_keys: vec!["key-c".into()], - opening_prompt: "You stand at the gate.".into(), - player_prose: vec!["I knock.".into()], - rounds: vec![output( - "r0", - vec![call_event( - "c0", - ASK_PLAYER_TOOL, - serde_json::json!({"question": "Which way?"}), - )], - )], - calls: vec![CallRecord { - call_id: "c0".into(), - round: 0, - slot: 0, - body: Some(RecordedCall::AskPlayer("Which way?".into())), - result: None, - }], - persona_turns: Vec::new(), - question: Some("Which way?".into()), - refusal: None, - narration: None, - fault: None, - state: PlayTurnState::AwaitingPlayer, - }; - let legacy_state = LegacyPlayTurnStoreStateV1 { - schema: LEGACY_STORE_SCHEMA_V1.into(), - turn: Some(legacy_turn), - ledger: KeyLedger::default(), - revision: 5, - }; - let legacy_row = CultCacheEnvelope { - key: STORE_KEY.into(), - r#type: STORE_TYPE.into(), - payload: rmp_serde::to_vec_named(&legacy_state).unwrap(), - stored_at: Utc::now().to_rfc3339(), - schema_id: Some(LEGACY_STORE_SCHEMA_V1.into()), - }; + let inner_mismatch_path = directory.path().join("inner-mismatch.cc"); { - let raw_store = OwnedRedbMessagePackBackingStore::new(&store_path).unwrap(); - assert!( - raw_store - .compare_and_swap_batch(&[], vec![legacy_row]) - .unwrap(), - "seeding the legacy row must succeed against an empty store" - ); + let raw_store = OwnedRedbMessagePackBackingStore::new(&inner_mismatch_path).unwrap(); + let state = PlayTurnStoreState { + schema: "ghostlight.play_turn_store.v1".into(), + turn: None, + ledger: KeyLedger::default(), + revision: 7, + }; + let row = CultCacheEnvelope { + key: STORE_KEY.into(), + r#type: STORE_TYPE.into(), + payload: rmp_serde::to_vec_named(&state).unwrap(), + stored_at: Utc::now().to_rfc3339(), + schema_id: Some(STORE_SCHEMA.into()), + }; + assert!(raw_store.compare_and_swap_batch(&[], vec![row]).unwrap()); } + let error = PlayTurnStore::open(&inner_mismatch_path).err().unwrap(); + assert!(format!("{error:#}").contains("schema is invalid"), "{error:#}"); - let store = PlayTurnStore::open(&store_path) - .expect("a genuine pre-Cut-11 row must open, not be refused as corrupt"); - let recovered = store.current().expect("the legacy row's own turn must be recovered"); - assert_eq!(recovered.state, PlayTurnState::AwaitingPlayer); - let token = recovered - .question_token - .clone() - .expect("an upgraded row whose question is still open must mint a fresh token"); - assert!(!token.is_empty(), "a minted token must not be the empty-string fallback"); - } - - /// PA.f184: a row that matches the *current* schema id but whose bytes do - /// not decode at all used to leave `open` refusing forever — `open_play` - /// caught the `Err`, logged it, and `state.play` stayed `None` across - /// every future restart, exactly the PA.f177 gap this fix closes for the - /// arm PA.f177 itself did not touch. It is now retired to a sidecar file - /// beside the store, the same path a damaged legacy row already took, so - /// the play card comes back (empty) instead of staying gone. - /// - /// Mutation: change `read_current_schema_row`'s decode line back to a - /// bare `rmp_serde::from_slice(&row.payload)?` (or otherwise make this - /// arm `bail!` instead of calling `retire_unreadable_row`) — `open` then - /// returns `Err` for this row and `store.expect(...)` below panics. - #[tokio::test] - async fn a_row_with_the_current_schema_id_and_undecodable_bytes_is_retired_to_a_sidecar_and_play_starts_fresh() { - let directory = tempfile::tempdir().unwrap(); - let store_path = directory.path().join("play-turn-v1.cc"); - seed_unreadable_row_for_test(&store_path); - - let store = PlayTurnStore::open(&store_path) - .expect("a damaged current-schema row must be retired, not fail open outright"); - assert!( - store.current().is_none(), - "play must start fresh with no current turn once the old row is retired" - ); - - let sidecar = std::fs::read_dir(directory.path()) - .unwrap() - .filter_map(|entry| entry.ok()) - .find(|entry| entry.file_name().to_string_lossy().contains("retired-unreadable-row")) - .expect("the damaged row must be written to a sidecar file beside the store"); - assert!( - sidecar.file_name().to_string_lossy().ends_with(".json"), - "the sidecar must be named for what it is (PA.f192), not `.cc`: {:?}", - sidecar.file_name() - ); - let sidecar_bytes = std::fs::read(sidecar.path()).unwrap(); - assert!(!sidecar_bytes.is_empty(), "the sidecar must actually carry the retired row's bytes"); - - // Soul's owed item 5: the sidecar must actually be readable, and the - // original bytes must actually be recoverable from it — not merely - // "the file is non-empty". Parse it as JSON, decode `payload_base64`, - // and prove the result is byte-for-byte `seed_unreadable_row_for_test`'s - // own `vec![0xC1]`. - let decoded: serde_json::Value = serde_json::from_slice(&sidecar_bytes) - .expect("the sidecar must be readable JSON, not another CultCache-shaped blob"); - let payload_base64 = decoded["payload_base64"] - .as_str() - .expect("the sidecar must carry the original payload as a base64 string field"); - let recovered_payload = base64::engine::general_purpose::STANDARD - .decode(payload_base64) - .expect("payload_base64 must actually decode as base64"); - assert_eq!( - recovered_payload, - vec![0xC1], - "the sidecar's payload_base64 must decode to the exact original bytes, not a lossy copy" - ); - - // Reopening must not hit the same row again: it was cleared from the - // store as part of retiring it, not merely skipped this once. - drop(store); - let reopened = PlayTurnStore::open(&store_path) - .expect("reopening after retirement must not refuse the store again"); - assert!(reopened.current().is_none()); - let sidecars_after_reopen = std::fs::read_dir(directory.path()) - .unwrap() - .filter_map(|entry| entry.ok()) - .filter(|entry| entry.file_name().to_string_lossy().contains("retired-unreadable-row")) - .count(); - assert_eq!( - sidecars_after_reopen, 1, - "a clean reopen after retirement must not itself perform a fresh retirement and write a \ - second sidecar" - ); - } - - /// PA.f184: a single row under this store's own `type`/`key` but a - /// schema id no arm recognizes — a future schema this build has never - /// seen — is retired exactly like a damaged row, not left bailing - /// forever with "foreign or otherwise-unreadable records". - /// - /// Mutation: delete the catch-all `[row] if row.r#type == STORE_TYPE && - /// row.key == STORE_KEY => { ... }` arm from `PlayTurnStore::open` — this - /// row then falls through to the final `_ => bail!(...)` and - /// `store.expect(...)` below panics. - #[tokio::test] - async fn a_row_declaring_an_unrecognized_future_schema_is_retired_not_refused_forever() { - let directory = tempfile::tempdir().unwrap(); - let store_path = directory.path().join("play-turn-v1.cc"); - - let future_row = CultCacheEnvelope { - key: STORE_KEY.into(), - r#type: STORE_TYPE.into(), - payload: vec![1, 2, 3], - stored_at: Utc::now().to_rfc3339(), - schema_id: Some("ghostlight.play_turn_store.v4".into()), - }; + let non_canonical_path = directory.path().join("non-canonical.cc"); { - let raw_store = OwnedRedbMessagePackBackingStore::new(&store_path).unwrap(); - assert!( - raw_store.compare_and_swap_batch(&[], vec![future_row]).unwrap(), - "seeding the future-schema row must succeed against an empty store" - ); + let mut fields = std::collections::BTreeMap::new(); + fields.insert("ledger", serde_json::to_value(KeyLedger::default()).unwrap()); + fields.insert("revision", Value::Number(5.into())); + fields.insert("schema", Value::String(STORE_SCHEMA.into())); + fields.insert("turn", Value::Null); + let payload = rmp_serde::to_vec_named(&Value::Object( + fields.into_iter().map(|(k, v)| (k.to_string(), v)).collect(), + )) + .unwrap(); + let raw_store = OwnedRedbMessagePackBackingStore::new(&non_canonical_path).unwrap(); + let row = CultCacheEnvelope { + key: STORE_KEY.into(), + r#type: STORE_TYPE.into(), + payload, + stored_at: Utc::now().to_rfc3339(), + schema_id: Some(STORE_SCHEMA.into()), + }; + assert!(raw_store.compare_and_swap_batch(&[], vec![row]).unwrap()); } - - let store = PlayTurnStore::open(&store_path) - .expect("an unrecognized future schema must be retired, not fail open outright"); - assert!(store.current().is_none()); + let error = PlayTurnStore::open(&non_canonical_path).err().unwrap(); + assert!(format!("{error:#}").contains("not canonical"), "{error:#}"); assert!( std::fs::read_dir(directory.path()) .unwrap() .filter_map(|entry| entry.ok()) - .any(|entry| entry.file_name().to_string_lossy().contains("retired-unreadable-row")), - "the future-schema row must be written to a sidecar file beside the store" + .all(|entry| entry.path().extension().and_then(|ext| ext.to_str()) != Some("json")), + "refused stores must not emit JSON sidecars" ); } - /// PA.f194-A: Soul's own probe — a row declaring a schema id this build - /// has never seen (an Idunn rollback across a schema-id move landing - /// this build in front of a row a newer build wrote) whose payload still - /// decodes cleanly into the current `PlayTurnStoreState` shape, holding - /// an open question and its token. Before this fix the catch-all arm - /// retired every unrecognized schema id on the id alone, with no decode - /// attempted — this canonical, perfectly readable row lost its one open - /// turn, and the sidecar's own `reason` field falsely claimed the row - /// "could not be read". Now `open` attempts the decode first, the decode - /// succeeds, and `open` fails loudly instead of destroying a readable - /// turn — the same shape the current- and legacy-schema arms already use - /// for their own `Other` cases. - /// - /// Mutation: delete the `match rmp_serde::from_slice::(&row.payload)` - /// decode attempt from the catch-all arm (or its `Ok(_) => return Err(...)` - /// case) and route straight to `retire_unreadable_row` again — `open` then - /// succeeds with `current().is_none()`, a sidecar appears, and the - /// assertions below fail. - #[tokio::test] - async fn a_readable_row_declaring_an_unrecognized_future_schema_is_not_retired() { - let directory = tempfile::tempdir().unwrap(); - let store_path = directory.path().join("play-turn-v1.cc"); - - let turn = PlayTurn { - turn_id: "44444444-4444-4444-4444-444444444444".into(), - applied_keys: vec!["key-d".into()], - opening_prompt: "You stand at a crossroads.".into(), - player_prose: vec!["I look around.".into()], - rounds: vec![output( - "r0", - vec![call_event( - "c0", - ASK_PLAYER_TOOL, - serde_json::json!({"question": "Which way?"}), - )], - )], - calls: vec![CallRecord { - call_id: "c0".into(), - round: 0, - slot: 0, - body: Some(RecordedCall::AskPlayer("Which way?".into())), - result: None, - }], - persona_turns: Vec::new(), - question: Some("Which way?".into()), - question_token: Some("future-schema-token".into()), - refusal: None, - narration: None, - fault: None, - state: PlayTurnState::AwaitingPlayer, - }; - let future_state = PlayTurnStoreState { - schema: "ghostlight.play_turn_store.v4".into(), - turn: Some(turn), - ledger: KeyLedger::default(), - revision: 7, - }; - let future_payload = rmp_serde::to_vec_named(&future_state).unwrap(); - // Sanity: the fixture really is readable under the current shape, so - // this test exercises the "decodes cleanly" branch and not a decode - // failure in disguise. - rmp_serde::from_slice::(&future_payload) - .expect("the test fixture must actually decode as a valid PlayTurnStoreState"); - - let future_row = CultCacheEnvelope { - key: STORE_KEY.into(), - r#type: STORE_TYPE.into(), - payload: future_payload, - stored_at: Utc::now().to_rfc3339(), - schema_id: Some("ghostlight.play_turn_store.v4".into()), - }; - { - let raw_store = OwnedRedbMessagePackBackingStore::new(&store_path).unwrap(); - assert!( - raw_store.compare_and_swap_batch(&[], vec![future_row]).unwrap(), - "seeding the readable future-schema row must succeed against an empty store" - ); - } - - let error = match PlayTurnStore::open(&store_path) { - Ok(_) => panic!("a readable future-schema row must not silently succeed, and must not be retired"), - Err(error) => error, - }; - let full_chain = format!("{error:#}"); - assert!( - full_chain.contains("decodes cleanly") || full_chain.contains("v4"), - "the failure must name that the row is readable, not claim it could not be read: {full_chain}" - ); - - assert!( - std::fs::read_dir(directory.path()) - .unwrap() - .filter_map(|entry| entry.ok()) - .all(|entry| !entry.file_name().to_string_lossy().contains("retired-unreadable-row")), - "a readable future-schema row must not be retired to a sidecar" - ); - - let raw_store = OwnedRedbMessagePackBackingStore::new(&store_path).unwrap(); - let rows = raw_store.pull_all().unwrap(); - assert_eq!(rows.len(), 1, "the original readable row must still be the only row in the store"); - assert_eq!(rows[0].schema_id.as_deref(), Some("ghostlight.play_turn_store.v4")); - } - - /// PA.f193-A: Soul's own probe — a row declaring the *current* - /// `STORE_SCHEMA` whose bytes decode into a perfectly valid - /// `PlayTurnStoreState` (every field reads back, including the turn - /// itself) but whose on-disk field order is not what this build's own - /// `to_vec_named` would produce, so the canonical re-encode check - /// disagrees. Before this fix `read_current_schema_row` returned a plain - /// `anyhow::Error` for this exactly like a genuine decode failure, and - /// `open` retired the row, destroying a readable turn. Now `open` returns - /// `Err` and leaves the row untouched. - /// - /// Mutation: change `Err(CurrentSchemaRowError::Other(error)) => return - /// Err(error)...` back to routing through `retire_unreadable_row` (or - /// collapse `CurrentSchemaRowError` back into a single `anyhow::Result` - /// the way it was before PA.f193-A) — the row is then retired, a sidecar - /// appears, and the assertions below fail. - #[tokio::test] - async fn a_current_schema_rows_non_canonical_bytes_are_not_retired() { - let directory = tempfile::tempdir().unwrap(); - let store_path = directory.path().join("play-turn-v1.cc"); - - // Field order alphabetical (ledger, revision, schema, turn) rather - // than `PlayTurnStoreState`'s own declared order (schema, turn, - // ledger, revision): `rmp_serde` decodes a named-struct map by key - // regardless of wire order, so this still parses into a valid state, - // but re-encoding it through the real struct produces different - // bytes than what is on disk. - let mut state_fields = std::collections::BTreeMap::new(); - state_fields.insert("ledger", serde_json::to_value(KeyLedger::default()).unwrap()); - state_fields.insert("revision", Value::Number(5.into())); - state_fields.insert("schema", Value::String(STORE_SCHEMA.into())); - state_fields.insert("turn", Value::Null); - let state_json = Value::Object(state_fields.into_iter().map(|(k, v)| (k.to_string(), v)).collect()); - let payload = rmp_serde::to_vec_named(&state_json).unwrap(); - - // Sanity: this payload really does decode into a valid state, so the - // test is actually exercising the canonical check and not a decode - // failure in disguise. - let decoded: PlayTurnStoreState = rmp_serde::from_slice(&payload) - .expect("the hand-ordered payload must still decode as a valid PlayTurnStoreState"); - assert!(rmp_serde::to_vec_named(&decoded).unwrap() != payload, "the test fixture must actually be non-canonical"); - - let row = CultCacheEnvelope { - key: STORE_KEY.into(), - r#type: STORE_TYPE.into(), - payload, - stored_at: Utc::now().to_rfc3339(), - schema_id: Some(STORE_SCHEMA.into()), - }; - { - let raw_store = OwnedRedbMessagePackBackingStore::new(&store_path).unwrap(); - assert!( - raw_store.compare_and_swap_batch(&[], vec![row]).unwrap(), - "seeding the non-canonical row must succeed against an empty store" - ); - } - - let error = match PlayTurnStore::open(&store_path) { - Ok(_) => panic!("a non-canonical current-schema row must not silently succeed either"), - Err(error) => error, - }; - let full_chain = format!("{error:#}"); - assert!( - full_chain.contains("canonical"), - "the failure must name the canonical mismatch: {full_chain}" - ); - assert!( - std::fs::read_dir(directory.path()) - .unwrap() - .filter_map(|entry| entry.ok()) - .all(|entry| !entry.file_name().to_string_lossy().contains("retired-unreadable-row")), - "a readable turn must not be retired over a non-canonical re-encode alone" - ); - - let raw_store = OwnedRedbMessagePackBackingStore::new(&store_path).unwrap(); - let rows = raw_store.pull_all().unwrap(); - assert_eq!(rows.len(), 1, "the original row must still be the only row in the store"); - assert_eq!(rows[0].schema_id.as_deref(), Some(STORE_SCHEMA)); - } - - /// PA.f193-B: a row declaring the current `STORE_SCHEMA` in its envelope, - /// canonical on the wire, but whose inner `schema` field names something - /// else — the same class of disagreement PA.f185 already covers for the - /// legacy arms, here for the current-schema arm PA.f185 did not touch. - /// The row decodes fine; only the inner tag disagrees. Before this fix - /// that reached `retire_unreadable_row` exactly like a decode failure. - /// - /// Mutation: delete the `if state.schema != STORE_SCHEMA` check from - /// `read_current_schema_row` (or route its `Other` arm back through - /// `retire_unreadable_row`) — the assertions below fail: with the check - /// deleted `open` succeeds instead of refusing; with retirement restored - /// a sidecar appears. - #[tokio::test] - async fn a_current_schema_rows_inner_schema_disagreeing_with_its_envelope_is_not_retired() { - let directory = tempfile::tempdir().unwrap(); - let store_path = directory.path().join("play-turn-v1.cc"); - - let state = PlayTurnStoreState { - schema: LEGACY_STORE_SCHEMA_V1.into(), - turn: None, - ledger: KeyLedger::default(), - revision: 7, - }; - let payload = rmp_serde::to_vec_named(&state).unwrap(); - let row = CultCacheEnvelope { - key: STORE_KEY.into(), - r#type: STORE_TYPE.into(), - payload, - stored_at: Utc::now().to_rfc3339(), - // Envelope says current schema; the payload's own inner `schema` - // field says otherwise (LEGACY_STORE_SCHEMA_V1 above) — the exact - // disagreement this arm exists to catch. - schema_id: Some(STORE_SCHEMA.into()), - }; - { - let raw_store = OwnedRedbMessagePackBackingStore::new(&store_path).unwrap(); - assert!( - raw_store.compare_and_swap_batch(&[], vec![row]).unwrap(), - "seeding the mismatched-inner-schema row must succeed against an empty store" - ); - } - - let error = match PlayTurnStore::open(&store_path) { - Ok(_) => panic!("an inner-schema mismatch must not silently succeed either"), - Err(error) => error, - }; - let full_chain = format!("{error:#}"); - assert!( - full_chain.contains("schema"), - "the failure must name the schema mismatch: {full_chain}" - ); - assert!( - std::fs::read_dir(directory.path()) - .unwrap() - .filter_map(|entry| entry.ok()) - .all(|entry| !entry.file_name().to_string_lossy().contains("retired-unreadable-row")), - "a readable turn must not be retired over an inner-schema tag mismatch alone" - ); - - let raw_store = OwnedRedbMessagePackBackingStore::new(&store_path).unwrap(); - let rows = raw_store.pull_all().unwrap(); - assert_eq!(rows.len(), 1, "the original row must still be the only row in the store"); - assert_eq!(rows[0].schema_id.as_deref(), Some(STORE_SCHEMA)); - } - - /// PA.f185: Soul's own probe — a row whose envelope declares - /// `LEGACY_STORE_SCHEMA_V1` but whose inner `schema` field says - /// `LEGACY_STORE_SCHEMA_V2` decodes its turn perfectly - /// (`opening_prompt` reads back intact), yet before this fix `open` - /// routed the inner-schema mismatch into `retire_unreadable_row` anyway, - /// destroying a readable turn under a sidecar reason ("did not decode - /// even leniently") that was false. Now `open` returns `Err` and leaves - /// the row untouched: no sidecar, no destructive compare-and-swap, - /// because an inconsistent inner tag is not the same failure as bytes - /// that will not parse at all. - /// - /// Mutation: change `Err(LegacyRowError::Other(error)) => return - /// Err(error)...` (in either legacy arm) back to - /// `retire_unreadable_row(&store, path.as_ref(), row, - /// LEGACY_STORE_SCHEMA_V1, &error)?` — the row is then retired, a - /// sidecar appears, and the assertions below fail. - #[tokio::test] - async fn a_legacy_rows_inner_schema_disagreeing_with_its_envelope_is_not_retired() { - let directory = tempfile::tempdir().unwrap(); - let store_path = directory.path().join("play-turn-v1.cc"); - - let legacy_turn = LegacyPlayTurnV1 { - turn_id: "55555555-5555-5555-5555-555555555555".into(), - applied_keys: Vec::new(), - opening_prompt: "You stand at the gate.".into(), - player_prose: vec!["I knock.".into()], - rounds: Vec::new(), - calls: Vec::new(), - persona_turns: Vec::new(), - question: None, - refusal: None, - narration: None, - fault: None, - state: PlayTurnState::Running, - }; - // Envelope's own `schema_id` says v1 (handled by this arm); the - // payload's own inner `schema` field says v2 — the exact disagreement - // Soul's probe found, constructed by hand since no production writer - // ever mints this shape. - let legacy_state = LegacyPlayTurnStoreStateV1 { - schema: LEGACY_STORE_SCHEMA_V2.into(), - turn: Some(legacy_turn), - ledger: KeyLedger::default(), - revision: 3, - }; - let legacy_row = CultCacheEnvelope { - key: STORE_KEY.into(), - r#type: STORE_TYPE.into(), - payload: rmp_serde::to_vec_named(&legacy_state).unwrap(), - stored_at: Utc::now().to_rfc3339(), - schema_id: Some(LEGACY_STORE_SCHEMA_V1.into()), - }; - { - let raw_store = OwnedRedbMessagePackBackingStore::new(&store_path).unwrap(); - assert!( - raw_store.compare_and_swap_batch(&[], vec![legacy_row]).unwrap(), - "seeding the mismatched-inner-schema row must succeed against an empty store" - ); - } - - let error = match PlayTurnStore::open(&store_path) { - Ok(_) => panic!("an inner-schema mismatch must not silently succeed either"), - Err(error) => error, - }; - // `{error:#}` (anyhow's alternate form) walks the whole `.context(...)` - // chain; `{error}` alone would only show `open`'s own outer wrapper - // ("upgrading a legacy play-turn row failed") and never actually - // check that the underlying cause names the schema mismatch at all. - let full_chain = format!("{error:#}"); - assert!( - full_chain.contains("schema"), - "the failure must name the schema mismatch, not read as a plain decode failure: {full_chain}" - ); - assert!( - std::fs::read_dir(directory.path()) - .unwrap() - .filter_map(|entry| entry.ok()) - .all(|entry| !entry.file_name().to_string_lossy().contains("retired-unreadable-row")), - "a readable turn must not be retired over an inner-schema tag mismatch alone" - ); - - // The row itself is untouched: no destructive compare-and-swap ran. - let raw_store = OwnedRedbMessagePackBackingStore::new(&store_path).unwrap(); - let rows = raw_store.pull_all().unwrap(); - assert_eq!(rows.len(), 1, "the original row must still be the only row in the store"); - assert_eq!(rows[0].schema_id.as_deref(), Some(LEGACY_STORE_SCHEMA_V1)); - } - - /// PA.f177: a row older than `applied_keys`/`fault` themselves — written - /// before either field existed, still under `LEGACY_STORE_SCHEMA_V1`, the - /// schema id that never changed for them — must open and upgrade exactly - /// like any other legacy row, not fail `upgrade_legacy_row`'s decode with - /// "missing field `applied_keys`". Soul's probe row, named in PA.f177. - /// - /// Mutation: remove `#[serde(default)]` from `PlayTurn::applied_keys` (or - /// `fault`) — this row's msgpack bytes name neither field at all, so the - /// decode in `upgrade_legacy_row` fails, `open` falls into - /// `retire_unreadable_row` instead of recovering the turn, and the - /// `recovered.applied_keys`/`turn_id` assertions below fail because there - /// is no recovered turn to read. - #[tokio::test] - async fn a_legacy_v1_row_predating_applied_keys_and_fault_still_opens_and_upgrades() { - let directory = tempfile::tempdir().unwrap(); - let store_path = directory.path().join("play-turn-v1.cc"); - - // Encoded by hand, not through `LegacyPlayTurnV1`: that struct itself - // already carries `applied_keys`/`fault`. This is the shape an even - // earlier process wrote, before either field was added to `PlayTurn` - // at all — the exact gap PA.f177 named. - let mut turn_fields = std::collections::BTreeMap::new(); - turn_fields.insert("turn_id", Value::String("44444444-4444-4444-4444-444444444444".into())); - turn_fields.insert("opening_prompt", Value::String("You stand at the gate.".into())); - turn_fields.insert("player_prose", Value::Array(vec![Value::String("I knock.".into())])); - turn_fields.insert("rounds", Value::Array(Vec::new())); - turn_fields.insert("calls", Value::Array(Vec::new())); - turn_fields.insert("persona_turns", Value::Array(Vec::new())); - turn_fields.insert("question", Value::Null); - turn_fields.insert("refusal", Value::Null); - turn_fields.insert("narration", Value::Null); - turn_fields.insert("state", Value::String("Running".into())); - let turn_json = Value::Object(turn_fields.into_iter().map(|(k, v)| (k.to_string(), v)).collect()); - let mut state_fields = std::collections::BTreeMap::new(); - state_fields.insert("schema", Value::String(LEGACY_STORE_SCHEMA_V1.into())); - state_fields.insert("turn", turn_json); - state_fields.insert( - "ledger", - serde_json::to_value(KeyLedger::default()).unwrap(), - ); - state_fields.insert("revision", Value::Number(2.into())); - let state_json = Value::Object(state_fields.into_iter().map(|(k, v)| (k.to_string(), v)).collect()); - // Round-trip through `serde_json::Value` into msgpack (`rmp_serde` - // encodes any `Serialize` type, including a dynamic `Value`), so the - // wire bytes genuinely lack `applied_keys`/`fault` rather than - // merely being constructed from a Rust struct that happens to. - let payload = rmp_serde::to_vec_named(&state_json).unwrap(); - - let legacy_row = CultCacheEnvelope { - key: STORE_KEY.into(), - r#type: STORE_TYPE.into(), - payload, - stored_at: Utc::now().to_rfc3339(), - schema_id: Some(LEGACY_STORE_SCHEMA_V1.into()), - }; - { - let raw_store = OwnedRedbMessagePackBackingStore::new(&store_path).unwrap(); - assert!( - raw_store - .compare_and_swap_batch(&[], vec![legacy_row]) - .unwrap(), - "seeding the pre-applied_keys/fault row must succeed against an empty store" - ); - } - - let store = PlayTurnStore::open(&store_path) - .expect("a row predating applied_keys/fault must still open leniently, not be refused"); - let recovered = store.current().expect("the legacy row's own turn must be recovered"); - assert_eq!(recovered.turn_id, "44444444-4444-4444-4444-444444444444"); - assert!( - recovered.applied_keys.is_empty(), - "a field the row never recorded at all must default, not fail the decode" - ); - assert_eq!(recovered.fault, None); - assert_eq!( - store.row.schema_id.as_deref(), - Some(STORE_SCHEMA), - "the row must be upgraded to the current schema in place" - ); - assert!( - std::fs::read_dir(directory.path()) - .unwrap() - .filter_map(|entry| entry.ok()) - .all(|entry| !entry.file_name().to_string_lossy().contains("retired-unreadable-row")), - "a row that decoded leniently must not also be retired to a sidecar" - ); - } - - /// PA.f177: a legacy-schema row that is genuinely damaged — not merely - /// missing a field the lenient reader now defaults — must not leave - /// `PlayTurnStore::open` returning `Err` forever. It is retired to a - /// sidecar file beside the store, and the store opens fresh with no - /// current turn, so `open_play` succeeds and the play card comes back - /// (empty) instead of staying gone across every future restart. - /// - /// Mutation: delete the `Err(error) => retire_unreadable_row(...)` arm - /// from `PlayTurnStore::open`'s `LEGACY_STORE_SCHEMA_V1` branch (leaving - /// only `upgrade_legacy_row(&store, row, LEGACY_STORE_SCHEMA_V1)?`) — - /// `open` then returns `Err` for this row, exactly PA.f177's own bug, and - /// `store.expect(...)` below panics. - #[tokio::test] - async fn a_genuinely_undecodable_legacy_row_is_retired_to_a_sidecar_and_play_starts_fresh() { - let directory = tempfile::tempdir().unwrap(); - let store_path = directory.path().join("play-turn-v1.cc"); - - let damaged_row = CultCacheEnvelope { - key: STORE_KEY.into(), - r#type: STORE_TYPE.into(), - payload: vec![0xC1], // msgpack's own reserved "never used" marker byte - stored_at: Utc::now().to_rfc3339(), - schema_id: Some(LEGACY_STORE_SCHEMA_V1.into()), - }; - { - let raw_store = OwnedRedbMessagePackBackingStore::new(&store_path).unwrap(); - assert!( - raw_store - .compare_and_swap_batch(&[], vec![damaged_row]) - .unwrap(), - "seeding the damaged legacy row must succeed against an empty store" - ); - } - - let store = PlayTurnStore::open(&store_path) - .expect("a damaged legacy row must be retired, not fail open outright"); - assert!( - store.current().is_none(), - "play must start fresh with no current turn once the old row is retired" - ); - - let sidecar = std::fs::read_dir(directory.path()) - .unwrap() - .filter_map(|entry| entry.ok()) - .find(|entry| entry.file_name().to_string_lossy().contains("retired-unreadable-row")) - .expect("the damaged row must be written to a sidecar file beside the store"); - let sidecar_bytes = std::fs::read(sidecar.path()).unwrap(); - assert!(!sidecar_bytes.is_empty(), "the sidecar must actually carry the retired row's bytes"); - - // Reopening must not hit the same row again: it was cleared from the - // store as part of retiring it, not merely skipped this once. - drop(store); - let reopened = PlayTurnStore::open(&store_path) - .expect("reopening after retirement must not refuse the store again"); - assert!(reopened.current().is_none()); - } - /// The fork Self ruled on, isolated: a commit that changes only /// `turn.refusal` — exactly the shape `execute_actor_call`'s /// `ActionRejected` arm leaves a row in (the call's own record is diff --git a/crates/ghostlight-dungeon/src/runtime.rs b/crates/ghostlight-dungeon/src/runtime.rs index 36529a7..c5d6b54 100644 --- a/crates/ghostlight-dungeon/src/runtime.rs +++ b/crates/ghostlight-dungeon/src/runtime.rs @@ -240,7 +240,7 @@ pub(crate) async fn run(state_root_binding: Option) -> anyhow::Result<( // Heimdall is discovered through Odin at use and is not an Idunn // dependency; loopback-only, non-secret-bearing, app-bound envelopes are // enforced regardless. - let heimdall = Arc::new(HeimdallClient::from_env(&runtime_id, odin_endpoint, None)?); + let heimdall = Arc::new(HeimdallClient::from_env(&runtime_id, odin_endpoint)?); require_no_runtime_custody_failure(&mut fatal_events)?; let mut state = AppState { catalog: Arc::new(Mutex::new(catalog)), @@ -435,8 +435,7 @@ async fn runtime_readiness(state: &AppState) -> anyhow::Result { let mut health = canonical_readiness(state).await?; let opened = state.timelines.opened().await; let mut controller_status = "ok"; - let mut play_status = "ok".to_owned(); - for (id, host) in &opened { + for (_id, host) in &opened { match tokio::time::timeout(Duration::from_millis(100), host.controllers.custody_probe()) .await { @@ -446,17 +445,12 @@ async fn runtime_readiness(state: &AppState) -> anyhow::Result { } Err(_) => controller_status = "busy", } - // A retired unreadable play row is reported, not hidden. - if let Some(sidecar) = host.play.retired_row_sidecar() { - play_status = format!("a play-turn row of {id} was retired to {}", sidecar.display()); - } } if state.timelines.shared().permits.available_permits() == 0 && controller_status == "ok" { controller_status = "active"; } health["openTimelines"] = json!(opened.len()); health["controllerStatus"] = Value::String(controller_status.into()); - health["playStatus"] = Value::String(play_status); Ok(health) } diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 5d8ce69..1d93215 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -4,19 +4,20 @@ This is a pointer. It does not carry open work; the Eureka mind does. ## What exists -Nothing is deployed. The Dungeon (daemon, play table, Eve surface, browser host, -`vendor/eve`, Idunn recipe) is parked at the tag `parked/ghostlight-eve-surface` -and is not on main. A Thing 2 rebuild starts from that tag. +`crates/ghostlight-dungeon` and `deployment/idunn/recipe.toml` are live on `main` +for the Dungeon playtest (brake release admitted in +`ghostlight-verse:ruling:ghostlight-brake-release-granted`). The earlier Eve +surface remains at tag `parked/ghostlight-eve-surface` as history. What is in the tree is the kernel (`crates/ghostlight`), the persona projection -(`crates/ghostlight-persona-projection`) and the verse runner -(`crates/ghostlight-verse`). `cargo test` runs them on Linux; use the -`ygg-verify` stopgap on Yggdrasil, not the workstation, and say which host -you used. +(`crates/ghostlight-persona-projection`), the verse runner +(`crates/ghostlight-verse`), and the Dungeon daemon (`crates/ghostlight-dungeon`). +`cargo test` runs them on Linux; use the `ygg-verify` stopgap on Yggdrasil, not +the workstation, and say which host you used. -The Idunn target `ghostlight` is braked and stopped, not retired. Its state is in -`gamecult-ops/runbooks/ghostlight-dungeon-yggdrasil.md`. Do not run -`idunn up ghostlight`, the v1 actuator, or `ghostlight-dungeon.service`. +Dungeon deployment and lifecycle on Yggdrasil are managed through Idunn from +`deployment/idunn/recipe.toml` (runbook: `gamecult-ops/runbooks/ghostlight-dungeon-yggdrasil.md`). +Do not run the legacy v1 actuator or `ghostlight-dungeon.service`. ## Where open work is diff --git a/probes/page/01-signin-desktop.png b/probes/page/01-signin-desktop.png deleted file mode 100644 index 16e8743..0000000 Binary files a/probes/page/01-signin-desktop.png and /dev/null differ diff --git a/probes/page/01-signin-phone.png b/probes/page/01-signin-phone.png deleted file mode 100644 index 534d480..0000000 Binary files a/probes/page/01-signin-phone.png and /dev/null differ diff --git a/probes/page/02-worlds-empty-desktop.png b/probes/page/02-worlds-empty-desktop.png deleted file mode 100644 index abb1246..0000000 Binary files a/probes/page/02-worlds-empty-desktop.png and /dev/null differ diff --git a/probes/page/02-worlds-empty-phone.png b/probes/page/02-worlds-empty-phone.png deleted file mode 100644 index 6876b96..0000000 Binary files a/probes/page/02-worlds-empty-phone.png and /dev/null differ diff --git a/probes/page/03-begin-desktop.png b/probes/page/03-begin-desktop.png deleted file mode 100644 index 80544b1..0000000 Binary files a/probes/page/03-begin-desktop.png and /dev/null differ diff --git a/probes/page/03-begin-phone.png b/probes/page/03-begin-phone.png deleted file mode 100644 index 51e754d..0000000 Binary files a/probes/page/03-begin-phone.png and /dev/null differ diff --git a/probes/page/04-ready-desktop.png b/probes/page/04-ready-desktop.png deleted file mode 100644 index 3bca952..0000000 Binary files a/probes/page/04-ready-desktop.png and /dev/null differ diff --git a/probes/page/04-ready-phone.png b/probes/page/04-ready-phone.png deleted file mode 100644 index b54038e..0000000 Binary files a/probes/page/04-ready-phone.png and /dev/null differ diff --git a/probes/page/05-narration-desktop.png b/probes/page/05-narration-desktop.png deleted file mode 100644 index 5c03f42..0000000 Binary files a/probes/page/05-narration-desktop.png and /dev/null differ diff --git a/probes/page/05-narration-phone.png b/probes/page/05-narration-phone.png deleted file mode 100644 index f5190c2..0000000 Binary files a/probes/page/05-narration-phone.png and /dev/null differ diff --git a/probes/page/06-question-desktop.png b/probes/page/06-question-desktop.png deleted file mode 100644 index a052aa5..0000000 Binary files a/probes/page/06-question-desktop.png and /dev/null differ diff --git a/probes/page/06-question-phone.png b/probes/page/06-question-phone.png deleted file mode 100644 index 0f8146d..0000000 Binary files a/probes/page/06-question-phone.png and /dev/null differ diff --git a/probes/page/07-answered-scrollback-desktop.png b/probes/page/07-answered-scrollback-desktop.png deleted file mode 100644 index 019032e..0000000 Binary files a/probes/page/07-answered-scrollback-desktop.png and /dev/null differ diff --git a/probes/page/07-answered-scrollback-phone.png b/probes/page/07-answered-scrollback-phone.png deleted file mode 100644 index 11597f1..0000000 Binary files a/probes/page/07-answered-scrollback-phone.png and /dev/null differ diff --git a/probes/page/08-fault-retry-desktop.png b/probes/page/08-fault-retry-desktop.png deleted file mode 100644 index b80642a..0000000 Binary files a/probes/page/08-fault-retry-desktop.png and /dev/null differ diff --git a/probes/page/08-fault-retry-phone.png b/probes/page/08-fault-retry-phone.png deleted file mode 100644 index fe878ef..0000000 Binary files a/probes/page/08-fault-retry-phone.png and /dev/null differ diff --git a/probes/page/09-fault-after-retry-desktop.png b/probes/page/09-fault-after-retry-desktop.png deleted file mode 100644 index 203e841..0000000 Binary files a/probes/page/09-fault-after-retry-desktop.png and /dev/null differ diff --git a/probes/page/09-fault-after-retry-phone.png b/probes/page/09-fault-after-retry-phone.png deleted file mode 100644 index 9e0a3b1..0000000 Binary files a/probes/page/09-fault-after-retry-phone.png and /dev/null differ diff --git a/probes/page/10-refusal-line-desktop.png b/probes/page/10-refusal-line-desktop.png deleted file mode 100644 index 85cbef6..0000000 Binary files a/probes/page/10-refusal-line-desktop.png and /dev/null differ diff --git a/probes/page/10-refusal-line-phone.png b/probes/page/10-refusal-line-phone.png deleted file mode 100644 index 97dfcb1..0000000 Binary files a/probes/page/10-refusal-line-phone.png and /dev/null differ diff --git a/probes/page/11-worlds-seeding-failed-ready-desktop.png b/probes/page/11-worlds-seeding-failed-ready-desktop.png deleted file mode 100644 index efa61dd..0000000 Binary files a/probes/page/11-worlds-seeding-failed-ready-desktop.png and /dev/null differ diff --git a/probes/page/11-worlds-seeding-failed-ready-phone.png b/probes/page/11-worlds-seeding-failed-ready-phone.png deleted file mode 100644 index 67a4be6..0000000 Binary files a/probes/page/11-worlds-seeding-failed-ready-phone.png and /dev/null differ diff --git a/probes/page/12-seeding-progress-desktop.png b/probes/page/12-seeding-progress-desktop.png deleted file mode 100644 index cd5e4ea..0000000 Binary files a/probes/page/12-seeding-progress-desktop.png and /dev/null differ diff --git a/probes/page/12-seeding-progress-phone.png b/probes/page/12-seeding-progress-phone.png deleted file mode 100644 index f3b3081..0000000 Binary files a/probes/page/12-seeding-progress-phone.png and /dev/null differ diff --git a/probes/page/13-history-live-360.png b/probes/page/13-history-live-360.png deleted file mode 100644 index 5097d12..0000000 Binary files a/probes/page/13-history-live-360.png and /dev/null differ diff --git a/probes/page/14-history-after-reload-360.png b/probes/page/14-history-after-reload-360.png deleted file mode 100644 index 2d54c1d..0000000 Binary files a/probes/page/14-history-after-reload-360.png and /dev/null differ diff --git a/probes/page/15-history-older-loaded-360.png b/probes/page/15-history-older-loaded-360.png deleted file mode 100644 index 7f53342..0000000 Binary files a/probes/page/15-history-older-loaded-360.png and /dev/null differ diff --git a/probes/page/16-second-context-360.png b/probes/page/16-second-context-360.png deleted file mode 100644 index 2d54c1d..0000000 Binary files a/probes/page/16-second-context-360.png and /dev/null differ diff --git a/probes/page/17-second-context-older-loaded-360.png b/probes/page/17-second-context-older-loaded-360.png deleted file mode 100644 index 7f53342..0000000 Binary files a/probes/page/17-second-context-older-loaded-360.png and /dev/null differ diff --git a/probes/page/18-begin-era-lenses-360.png b/probes/page/18-begin-era-lenses-360.png deleted file mode 100644 index d4ef8f9..0000000 Binary files a/probes/page/18-begin-era-lenses-360.png and /dev/null differ diff --git a/probes/page/19-begin-post-elysium-charter3-veil0-360.png b/probes/page/19-begin-post-elysium-charter3-veil0-360.png deleted file mode 100644 index d807a08..0000000 Binary files a/probes/page/19-begin-post-elysium-charter3-veil0-360.png and /dev/null differ