diff --git a/crates/ghostlight-dungeon/src/domain.rs b/crates/ghostlight-dungeon/src/domain.rs index 5bdcbfb..b2a3e10 100644 --- a/crates/ghostlight-dungeon/src/domain.rs +++ b/crates/ghostlight-dungeon/src/domain.rs @@ -255,6 +255,16 @@ pub struct NarrationProjection { pub published_at: DateTime, } +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct CampaignLifecycleReceipt { + pub schema: String, + pub campaign_id: Uuid, + pub operation: String, + pub parent_campaign_id: Option, + pub parent_revision: Option, + pub created_at: DateTime, +} + #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] pub struct ActionIntent { pub actor_id: String, diff --git a/crates/ghostlight-dungeon/src/lib.rs b/crates/ghostlight-dungeon/src/lib.rs index 2e194c4..2295be4 100644 --- a/crates/ghostlight-dungeon/src/lib.rs +++ b/crates/ghostlight-dungeon/src/lib.rs @@ -9,6 +9,7 @@ pub mod model; pub mod narrator; pub mod persistence; pub mod persona; +pub mod registry; pub mod scheduler; pub mod surface; pub mod turn; diff --git a/crates/ghostlight-dungeon/src/persistence.rs b/crates/ghostlight-dungeon/src/persistence.rs index ece9a8b..86b00bd 100644 --- a/crates/ghostlight-dungeon/src/persistence.rs +++ b/crates/ghostlight-dungeon/src/persistence.rs @@ -73,6 +73,12 @@ impl CampaignStore { campaign, )?; let mut rows = vec![campaign_row.clone()]; + rows.push(envelope( + "campaign_seed.v1", + "ghostlight.campaign.v1", + &campaign.id.to_string(), + campaign, + )?); for receipt in receipts { rows.push(envelope( "vault_evidence_receipt.v1", @@ -95,6 +101,15 @@ impl CampaignStore { Ok(campaign_row) } + pub fn snapshot_to(&self, path: impl AsRef) -> Result<()> { + let rows = self.inner.pull_all()?; + let target = OwnedRedbMessagePackBackingStore::new(path.as_ref())?; + if !target.compare_and_swap_batch(&[], rows)? { + return Err(anyhow!("export target is not empty")); + } + Ok(()) + } + pub fn replace( &self, expected: &CultCacheEnvelope, diff --git a/crates/ghostlight-dungeon/src/registry.rs b/crates/ghostlight-dungeon/src/registry.rs new file mode 100644 index 0000000..a8be2f6 --- /dev/null +++ b/crates/ghostlight-dungeon/src/registry.rs @@ -0,0 +1,311 @@ +use crate::{ + domain::{Campaign, CampaignLifecycleReceipt, VaultEvidenceReceipt}, + kernel::WorldKernel, + persistence::CampaignStore, +}; +use anyhow::{Result, anyhow}; +use chrono::Utc; +use std::{ + collections::BTreeMap, + fs, + path::{Path, PathBuf}, + sync::Arc, +}; +use tokio::sync::RwLock; +use uuid::Uuid; + +#[derive(Clone)] +pub struct CampaignRuntime { + pub store: CampaignStore, + pub kernel: WorldKernel, +} + +#[derive(Clone)] +pub struct CampaignRegistry { + root: PathBuf, + runtimes: Arc>>, +} + +impl CampaignRegistry { + pub fn new(root: impl AsRef) -> Result { + let root = root.as_ref().to_path_buf(); + fs::create_dir_all(&root)?; + Ok(Self { + root, + runtimes: Arc::new(RwLock::new(BTreeMap::new())), + }) + } + + pub async fn load_existing(&self) -> Result<()> { + let mut found = BTreeMap::new(); + for entry in fs::read_dir(&self.root)? { + let entry = entry?; + let path = entry.path().join("campaign.cc"); + if !path.is_file() { + continue; + } + let store = CampaignStore::open(path)?; + let keys = store.keys("campaign.v1")?; + if keys.len() != 1 { + return Err(anyhow!("campaign store must contain exactly one campaign")); + } + let id = Uuid::parse_str(&keys[0])?; + found.insert( + id, + CampaignRuntime { + kernel: WorldKernel::start(store.clone()), + store, + }, + ); + } + *self.runtimes.write().await = found; + Ok(()) + } + + pub async fn runtime(&self, id: Uuid) -> Result { + self.runtimes + .read() + .await + .get(&id) + .cloned() + .ok_or_else(|| anyhow!("campaign runtime is not loaded")) + } + + pub async fn list(&self) -> Vec { + self.runtimes.read().await.keys().copied().collect() + } + + pub async fn create( + &self, + campaign: Campaign, + evidence: Vec, + ) -> Result { + if self.runtimes.read().await.contains_key(&campaign.id) { + return Err(anyhow!("campaign already exists")); + } + let directory = self.root.join(campaign.id.to_string()); + fs::create_dir(&directory)?; + let store = CampaignStore::open(directory.join("campaign.cc"))?; + let kernel = WorldKernel::start(store.clone()); + kernel + .command(crate::domain::WorldCommand::CreateCampaign { + campaign: campaign.clone(), + evidence_receipts: evidence, + }) + .await?; + store.insert( + "campaign_lifecycle_receipt.v1", + "ghostlight.campaign_lifecycle_receipt.v1", + &format!("{}:create", campaign.id), + &CampaignLifecycleReceipt { + schema: "ghostlight.campaign_lifecycle_receipt.v1".into(), + campaign_id: campaign.id, + operation: "create".into(), + parent_campaign_id: None, + parent_revision: None, + created_at: Utc::now(), + }, + )?; + let runtime = CampaignRuntime { store, kernel }; + self.runtimes + .write() + .await + .insert(campaign.id, runtime.clone()); + Ok(runtime) + } + + pub async fn fork(&self, source_id: Uuid, name: String) -> Result { + let source = self.runtime(source_id).await?; + let key = source_id.to_string(); + let (_, parent) = source + .store + .load::("campaign.v1", &key)? + .ok_or_else(|| anyhow!("source campaign vanished"))?; + let mut evidence = Vec::new(); + for id in source.store.keys("vault_evidence_receipt.v1")? { + if let Some((_, receipt)) = source + .store + .load::("vault_evidence_receipt.v1", &id)? + { + evidence.push(receipt); + } + } + let parent_revision = parent.revision; + let mut fork = parent; + fork.id = Uuid::new_v4(); + fork.name = name; + fork.revision = 0; + fork.pending_world_proposals.clear(); + let runtime = self.create(fork.clone(), evidence).await?; + runtime.store.insert( + "campaign_lifecycle_receipt.v1", + "ghostlight.campaign_lifecycle_receipt.v1", + &format!("{}:fork", fork.id), + &CampaignLifecycleReceipt { + schema: "ghostlight.campaign_lifecycle_receipt.v1".into(), + campaign_id: fork.id, + operation: "fork".into(), + parent_campaign_id: Some(source_id), + parent_revision: Some(parent_revision), + created_at: Utc::now(), + }, + )?; + Ok(runtime) + } + + pub async fn reset(&self, source_id: Uuid, name: String) -> Result { + let source = self.runtime(source_id).await?; + let (_, mut seed) = source + .store + .load::("campaign_seed.v1", &source_id.to_string())? + .ok_or_else(|| anyhow!("campaign has no approved seed"))?; + let parent_revision = source + .store + .load::("campaign.v1", &source_id.to_string())? + .ok_or_else(|| anyhow!("source campaign vanished"))? + .1 + .revision; + seed.id = Uuid::new_v4(); + seed.name = name; + seed.revision = 0; + seed.pending_world_proposals.clear(); + let mut evidence = Vec::new(); + for id in source.store.keys("vault_evidence_receipt.v1")? { + if let Some((_, receipt)) = source + .store + .load::("vault_evidence_receipt.v1", &id)? + { + evidence.push(receipt); + } + } + let runtime = self.create(seed.clone(), evidence).await?; + runtime.store.insert( + "campaign_lifecycle_receipt.v1", + "ghostlight.campaign_lifecycle_receipt.v1", + &format!("{}:reset", seed.id), + &CampaignLifecycleReceipt { + schema: "ghostlight.campaign_lifecycle_receipt.v1".into(), + campaign_id: seed.id, + operation: "reset".into(), + parent_campaign_id: Some(source_id), + parent_revision: Some(parent_revision), + created_at: Utc::now(), + }, + )?; + Ok(runtime) + } + + pub async fn export( + &self, + campaign_id: Uuid, + exports_root: impl AsRef, + ) -> Result { + let runtime = self.runtime(campaign_id).await?; + fs::create_dir_all(exports_root.as_ref())?; + let path = exports_root.as_ref().join(format!( + "{}-{}.cc", + campaign_id, + Utc::now().format("%Y%m%dT%H%M%SZ") + )); + runtime.store.snapshot_to(&path)?; + Ok(path) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::{ActorState, BranchOrigin, Location}; + use std::collections::{BTreeMap, BTreeSet}; + + fn seed(name: &str) -> Campaign { + let actor = ActorState { + id: "player".into(), + name: "Player".into(), + location_id: "room".into(), + capabilities: BTreeSet::new(), + knowledge: BTreeSet::new(), + equipment: BTreeSet::new(), + conditions: BTreeSet::new(), + obligations: BTreeSet::new(), + relationships: BTreeMap::new(), + goals: vec![], + memories: vec![], + }; + Campaign { + schema: "ghostlight.campaign.v1".into(), + id: Uuid::new_v4(), + name: name.into(), + revision: 0, + branch_origin: BranchOrigin { + canon_cutoff: "test".into(), + evidence_receipt_ids: vec![], + }, + world_time: Utc::now(), + tick_hours: 6, + player_actor_id: "player".into(), + locations: BTreeMap::from([( + "room".into(), + Location { + id: "room".into(), + name: "Room".into(), + container_id: None, + routes: BTreeMap::new(), + persistent_features: vec![], + }, + )]), + actors: BTreeMap::from([("player".into(), actor)]), + institutions: BTreeMap::new(), + clocks: BTreeMap::new(), + facts: BTreeMap::new(), + transcript: vec![], + last_player_activity: Utc::now(), + pending_ticks: 0, + away_ticks_processed: 0, + events: vec![], + news: vec![], + canon_candidates: BTreeMap::new(), + gestalts: BTreeMap::new(), + gestalt_members: BTreeMap::new(), + pending_world_proposals: vec![], + } + } + + #[tokio::test] + async fn create_fork_reset_and_export_preserve_isolated_stores() { + let dir = tempfile::tempdir().unwrap(); + let registry = CampaignRegistry::new(dir.path().join("campaigns")).unwrap(); + let original = seed("Original"); + registry.create(original.clone(), vec![]).await.unwrap(); + let fork = registry.fork(original.id, "Fork".into()).await.unwrap(); + let fork_id = fork.store.keys("campaign.v1").unwrap()[0] + .parse::() + .unwrap(); + assert_ne!(fork_id, original.id); + let reset = registry.reset(original.id, "Reset".into()).await.unwrap(); + let reset_id = reset.store.keys("campaign.v1").unwrap()[0] + .parse::() + .unwrap(); + assert_ne!(reset_id, original.id); + assert_eq!(registry.list().await.len(), 3); + let exported = registry + .export(fork_id, dir.path().join("exports")) + .await + .unwrap(); + let export_store = CampaignStore::open(exported).unwrap(); + assert_eq!( + export_store.keys("campaign.v1").unwrap(), + vec![fork_id.to_string()] + ); + assert_eq!( + registry + .runtime(original.id) + .await + .unwrap() + .store + .keys("campaign.v1") + .unwrap(), + vec![original.id.to_string()] + ); + } +} diff --git a/docs/architecture/ghostlight-dungeon-mvp.md b/docs/architecture/ghostlight-dungeon-mvp.md index 280cb25..2aad254 100644 --- a/docs/architecture/ghostlight-dungeon-mvp.md +++ b/docs/architecture/ghostlight-dungeon-mvp.md @@ -489,6 +489,33 @@ state use their own `.cc` store. JSON exists only for published JSON Schemas and browser, MCP, and model-provider boundaries. It is not load-bearing runtime state. +### Campaign registry and session authority + +- **Owner:** the service `CampaignRegistry` owns the mapping from authenticated + session hash to selected campaign ID and from campaign ID to its sole + `CampaignRuntime` (`CampaignStore` plus `WorldKernel` mailbox). +- **Inputs:** persisted hashed session authority, named campaign lifecycle + commands, runtime-root inventory, and exact campaign IDs. +- **Outputs:** one selected single-player runtime per session, isolated campaign + `.cc` paths, lifecycle receipts, and immutable export bundles. +- **Derived state:** browser selection, campaign lists, filenames, download + responses, and operator cards are projections of registry/control state. +- **Forbidden writers:** route handlers, invite cookies, filesystem discovery, + fork/reset/export helpers, and the browser cannot select or mutate a campaign + except through the registry's typed lifecycle operations. +- **Shared paths:** campaign creation approval, selection, fork, reset, reload, + scheduler lookup, command dispatch, and export all resolve the same + session-owned registry entry before touching a kernel. +- **Cut line:** `campaigns/default/campaign.cc` and the process-global kernel are + removed as authorities. A session token is authentication, not campaign + identity; its persisted control record explicitly selects a campaign. + +Fork creates a new campaign ID and store from a consistent source snapshot, +records lineage, then starts a fresh mailbox over the fork. Reset creates a new +branch from the campaign's approved seed/export rather than rewriting history +in place. Export snapshots the selected `.cc` plus manifest and evidence +receipts without granting the export path write authority over live state. + ### Vault provider and world compiler `VaultProvider` exposes source search, surrounding context, exact documents, diff --git a/state/map.yaml b/state/map.yaml index 8d23dba..b97c51f 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -255,5 +255,5 @@ data_flow: current_status: summary: GhostlightDungeon is the active MVP program. The approval-gated world compiler now persists evidence, canon candidates, and bounded on-demand region expansion through the WorldKernel. Fiction-first assessments use model proposals with deterministic DC and state-reference validation. Away-time ticks move institutions and gate news by information access. Present NPCs appraise live events in parallel Persona waves, and the kernel atomically validates their private deltas and world-action proposals. Gestalt populations can materialize durable individuals and fold them back into persistent member deltas. Live DeepSeek plus VoidBot compilation and disposable authenticated HTTP restart smokes have passed. The broader hosted MVP remains incomplete. - next_action: Complete named campaign creation, fork/reset and CultCache export plus operator laboratory controls; then acceptance-test narration, automatic gestalt promotion, and typed outcomes with live model output. + next_action: Replace the daemon's process-global default store/kernel with the tested CampaignRegistry and persisted session-to-campaign selection, then expose fork/reset/CultCache export and operator controls; acceptance-test cross-session isolation before calling campaign management complete. gestalt_population: Gestalt Personas own shared population baselines; persistent member deltas own named individuality; WorldKernel materialization commands compose and demote active actors without deleting member identity.