Build grounded world compiler flow

This commit is contained in:
Meta Vens 2026-08-16 20:12:53 +02:00
commit ab39d8cdac
25 changed files with 1350 additions and 225 deletions

1
.gitignore vendored
View file

@ -4,3 +4,4 @@ __pycache__/
node_modules/
state/scratch-compaction-*.md
experiments/images/
target/

View file

@ -35,20 +35,20 @@ inside another project.
## Important Paths
- Project root: `E:\Projects\Ghostlight`
- Canonical map: `E:\Projects\Ghostlight\state\map.yaml`
- Scratch surface: `E:\Projects\Ghostlight\state\scratch.md`
- Distilled evidence ledger: `E:\Projects\Ghostlight\state\evidence.jsonl`
- Branch ledger: `E:\Projects\Ghostlight\state\branches.json`
- Handoff summary: `E:\Projects\Ghostlight\notes\fresh-workspace-handoff.md`
- System map: `E:\Projects\Ghostlight\notes\ghostlight-current-system-map.md`
- Implementation plan: `E:\Projects\Ghostlight\notes\ghostlight-implementation-plan.md`
- Architecture rationale: `E:\Projects\Ghostlight\notes\architecture-rationale.md`
- State CLI: `E:\Projects\Ghostlight\tools\ghostlight_state.py`
- CultCache state seam: `E:\Projects\Ghostlight\tools\ghostlight_state_store.py`
- CultCache-Py submodule: `E:\Projects\Ghostlight\vendor\cultcache-py`
- CultCache state store: `E:\Projects\Ghostlight\state\ghostlight-state.cultcache.jsonl`
- Pre-compaction helper: `E:\Projects\Ghostlight\tools\ghostlight_prepare_compaction.py`
- Project root: `F:\Projects\Ghostlight`
- Canonical map: `F:\Projects\Ghostlight\state\map.yaml`
- Scratch surface: `F:\Projects\Ghostlight\state\scratch.md`
- Distilled evidence ledger: `F:\Projects\Ghostlight\state\evidence.jsonl`
- Branch ledger: `F:\Projects\Ghostlight\state\branches.json`
- Handoff summary: `F:\Projects\Ghostlight\notes\fresh-workspace-handoff.md`
- System map: `F:\Projects\Ghostlight\notes\ghostlight-current-system-map.md`
- Implementation plan: `F:\Projects\Ghostlight\notes\ghostlight-implementation-plan.md`
- Architecture rationale: `F:\Projects\Ghostlight\notes\architecture-rationale.md`
- State CLI: `F:\Projects\Ghostlight\tools\ghostlight_state.py`
- CultCache state seam: `F:\Projects\Ghostlight\tools\ghostlight_state_store.py`
- CultCache-Py submodule: `F:\Projects\Ghostlight\vendor\cultcache-py`
- CultCache state store: `F:\Projects\Ghostlight\state\ghostlight-state.cultcache.jsonl`
- Pre-compaction helper: `F:\Projects\Ghostlight\tools\ghostlight_prepare_compaction.py`
## Useful Commands

View file

@ -0,0 +1,51 @@
#[cfg(not(windows))]
fn main() -> anyhow::Result<()> {
anyhow::bail!("the live compiler smoke uses Starfire's DPAPI credential")
}
#[cfg(windows)]
#[tokio::main]
async fn main() -> anyhow::Result<()> {
use ghostlight_dungeon::{
compiler::{CustomStart, WorldCompiler},
model::{DeepSeekPort, ModelPort},
vault::VoidBotMcpVault,
};
use std::{path::PathBuf, sync::Arc};
let secret = std::env::var_os("GHOSTLIGHT_DEEPSEEK_BLOB")
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from(r"F:\GameCult\GhostlightDungeon\secrets\deepseek.dpapi"));
let model: Arc<dyn ModelPort> = Arc::new(DeepSeekPort::from_machine_dpapi(secret)?);
let compiler = WorldCompiler::new(
Arc::new(VoidBotMcpVault::starfire_loopback()),
model,
"deepseek-v4-pro",
);
let (preview, receipt) = compiler.compile_custom(CustomStart {
campaign_name: "Compiler acceptance smoke".into(),
who: "A low-status maintenance worker with local access but no institutional authority".into(),
where_: "an obscure inhabited Aetheria location supported by the retrieved sources".into(),
when: "a source-supported pre-Elysium period".into(),
goal: "prevent an approaching institutional failure without inventing expertise or geography".into(),
}).await?;
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"schema":"ghostlight.world_compile_smoke.v1",
"title":preview.title,
"location_count":preview.campaign.locations.len(),
"actor_count":preview.campaign.actors.len(),
"institution_count":preview.campaign.institutions.len(),
"clock_count":preview.campaign.clocks.len(),
"evidence_receipt_count":preview.evidence_receipts.len(),
"evidence_witness_count":preview.evidence_receipts.iter().map(|r|r.witnesses.len()).sum::<usize>(),
"gaps":preview.gaps,
"branch_assumptions":preview.branch_assumptions,
"requires_approval":preview.requires_approval,
"campaign_revision":preview.campaign.revision,
"model_receipt":receipt
}))?
);
Ok(())
}

View file

@ -0,0 +1,507 @@
use crate::{
domain::{
ActorState, BranchOrigin, Campaign, FactScope, InstitutionState, Location,
VaultEvidenceReceipt, WorldClock, WorldCompilePreview, WorldFact,
},
model::{ModelPort, ModelStageReceipt, ModelStageRequest, run_validated_stage},
vault::{VaultProvider, VaultQuery},
};
use anyhow::{Result, anyhow};
use chrono::{DateTime, Utc};
use schemars::{JsonSchema, schema_for};
use serde::{Deserialize, Serialize};
use std::{
collections::{BTreeMap, BTreeSet},
sync::Arc,
};
use uuid::Uuid;
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct OpeningRequest {
pub setting: String,
pub constraints: Vec<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct OpeningSuggestion {
pub id: String,
pub title: String,
pub era: String,
pub place: String,
pub pressure: String,
pub player_hook: String,
pub evidence_receipt_ids: Vec<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct RoleSuggestion {
pub id: String,
pub name: String,
pub premise: String,
pub capabilities: Vec<String>,
pub obligations: Vec<String>,
pub evidence_receipt_ids: Vec<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct CustomStart {
pub campaign_name: String,
pub who: String,
pub where_: String,
pub when: String,
pub goal: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct SelectedStart {
pub campaign_name: String,
pub opening: OpeningSuggestion,
pub role: RoleSuggestion,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct SuggestedOpenings {
pub openings: Vec<OpeningSuggestion>,
pub evidence_receipts: Vec<VaultEvidenceReceipt>,
pub model_receipt: ModelStageReceipt,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct SuggestedRoles {
pub roles: Vec<RoleSuggestion>,
pub evidence_receipts: Vec<VaultEvidenceReceipt>,
pub model_receipt: ModelStageReceipt,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
struct OpeningSet {
openings: Vec<OpeningSuggestion>,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
struct RoleSet {
roles: Vec<RoleSuggestion>,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
struct CompiledSeed {
title: String,
canon_cutoff: String,
world_time: DateTime<Utc>,
tick_hours: u32,
player: ActorState,
locations: Vec<Location>,
actors: Vec<ActorState>,
institutions: Vec<InstitutionState>,
clocks: Vec<WorldClock>,
facts: Vec<WorldFact>,
gaps: Vec<String>,
branch_assumptions: Vec<String>,
opening_narration: String,
}
pub struct WorldCompiler {
vault: Arc<dyn VaultProvider>,
model: Arc<dyn ModelPort>,
compiler_model: String,
}
impl WorldCompiler {
pub fn new(
vault: Arc<dyn VaultProvider>,
model: Arc<dyn ModelPort>,
compiler_model: impl Into<String>,
) -> Self {
Self {
vault,
model,
compiler_model: compiler_model.into(),
}
}
pub async fn suggest_openings(&self, request: OpeningRequest) -> Result<SuggestedOpenings> {
let queries = [
format!("{} history eras locations institutions", request.setting),
format!("{} conflicts pressures ordinary life", request.setting),
format!("{} travel geography routes", request.setting),
];
let receipts = self.retrieve_all(&queries, "all", 8).await?;
let evidence = evidence_text(&receipts);
let output = self.structured("world_openings", "opening-suggestions", &format!("Generate exactly three source-grounded openings. They must use distinct eras, places, and pressures. Do not fill material evidence gaps with invention. REQUEST:\n{}\nEVIDENCE:\n{}", serde_json::to_string(&request)?, evidence), serde_json::to_value(schema_for!(OpeningSet))?, receipt_ids(&receipts)).await?;
let parsed: OpeningSet = serde_json::from_value(output.0)?;
if parsed.openings.len() != 3 {
return Err(anyhow!("world compiler must return exactly three openings"));
}
ensure_distinct_openings(&parsed.openings)?;
Ok(SuggestedOpenings {
openings: parsed.openings,
evidence_receipts: receipts,
model_receipt: output.1,
})
}
pub async fn suggest_roles(&self, opening: &OpeningSuggestion) -> Result<SuggestedRoles> {
let queries = [
format!(
"{} {} people occupations institutions",
opening.era, opening.place
),
format!(
"{} capabilities obligations {}",
opening.place, opening.pressure
),
];
let receipts = self.retrieve_all(&queries, &opening.era, 8).await?;
let output = self.structured("world_roles", &format!("roles:{}", opening.id), &format!("Generate exactly three materially distinct player roles grounded in this opening and evidence. OPENING:\n{}\nEVIDENCE:\n{}", serde_json::to_string(opening)?, evidence_text(&receipts)), serde_json::to_value(schema_for!(RoleSet))?, receipt_ids(&receipts)).await?;
let parsed: RoleSet = serde_json::from_value(output.0)?;
if parsed.roles.len() != 3 {
return Err(anyhow!("world compiler must return exactly three roles"));
}
Ok(SuggestedRoles {
roles: parsed.roles,
evidence_receipts: receipts,
model_receipt: output.1,
})
}
pub async fn compile_custom(
&self,
start: CustomStart,
) -> Result<(WorldCompilePreview, ModelStageReceipt)> {
let queries = [
format!(
"{} {} geography routes containment",
start.where_, start.when
),
format!("{} {} people institutions powers", start.where_, start.when),
format!("{} capabilities mechanics {}", start.who, start.goal),
];
let receipts = self.retrieve_all(&queries, &start.when, 10).await?;
let output = self.structured("world_compile", "custom-start", &format!("Compile a bounded playable region and institutional pressure graph. Emit only supported canon facts; mark reversible texture provisional_local and list material gaps. The player location and every actor location must exist. Every route destination must exist, travel time must be positive, clocks need positive thresholds, and the player id must be unique. START:\n{}\nEVIDENCE:\n{}", serde_json::to_string(&start)?, evidence_text(&receipts)), serde_json::to_value(schema_for!(CompiledSeed))?, receipt_ids(&receipts)).await?;
let seed: CompiledSeed = serde_json::from_value(output.0)?;
let campaign = seed_to_campaign(seed.clone(), &receipts)?;
validate_campaign_seed(&campaign)?;
Ok((
WorldCompilePreview {
schema: "ghostlight.world_compile_preview.v1".into(),
title: seed.title,
campaign,
evidence_receipts: receipts,
gaps: seed.gaps,
branch_assumptions: seed.branch_assumptions,
requires_approval: true,
},
output.1,
))
}
pub async fn compile_selected(
&self,
start: SelectedStart,
) -> Result<(WorldCompilePreview, ModelStageReceipt)> {
self.compile_custom(CustomStart {
campaign_name: start.campaign_name,
who: format!("{} — {}", start.role.name, start.role.premise),
where_: start.opening.place,
when: start.opening.era,
goal: format!("{}; {}", start.opening.player_hook, start.opening.pressure),
})
.await
}
async fn retrieve_all(
&self,
queries: &[String],
temporal_scope: &str,
limit: u8,
) -> Result<Vec<VaultEvidenceReceipt>> {
let mut receipts = Vec::new();
for query in queries {
receipts.push(
self.vault
.search(&VaultQuery {
query: query.clone(),
authority_lanes: vec!["Aetheria".into(), "AetheriaLore".into()],
temporal_scope: temporal_scope.into(),
limit,
})
.await?,
);
}
if receipts.iter().all(|r| r.witnesses.is_empty()) {
return Err(anyhow!("Vault returned no evidence; compilation refused"));
}
Ok(receipts)
}
async fn structured(
&self,
stage: &str,
binding: &str,
prompt: &str,
schema: serde_json::Value,
sources: Vec<String>,
) -> Result<(serde_json::Value, ModelStageReceipt)> {
let prompt = format!(
"{prompt}\n\nOUTPUT JSON SCHEMA (follow exactly):\n{}",
serde_json::to_string_pretty(&schema)?
);
let out = run_validated_stage(
self.model.as_ref(),
&ModelStageRequest {
stage: stage.into(),
model: self.compiler_model.clone(),
snapshot_binding: binding.into(),
lived_stream: prompt,
output_schema: Some(schema),
source_receipt_ids: sources,
},
)
.await?;
Ok((
out.structured
.ok_or_else(|| anyhow!("compiler returned no structured output"))?,
out.receipt,
))
}
}
fn evidence_text(receipts: &[VaultEvidenceReceipt]) -> String {
receipts
.iter()
.flat_map(|r| r.witnesses.iter())
.map(|w| {
format!(
"[{} | {} | {}] {}",
w.source_id, w.exact_locator, w.content_hash, w.excerpt
)
})
.collect::<Vec<_>>()
.join("\n\n")
}
fn receipt_ids(receipts: &[VaultEvidenceReceipt]) -> Vec<String> {
receipts.iter().map(|r| r.id.clone()).collect()
}
fn ensure_distinct_openings(items: &[OpeningSuggestion]) -> Result<()> {
let eras: BTreeSet<_> = items.iter().map(|x| x.era.trim().to_lowercase()).collect();
let places: BTreeSet<_> = items
.iter()
.map(|x| x.place.trim().to_lowercase())
.collect();
let pressures: BTreeSet<_> = items
.iter()
.map(|x| x.pressure.trim().to_lowercase())
.collect();
if eras.len() != 3 || places.len() != 3 || pressures.len() != 3 {
Err(anyhow!(
"openings are not distinct across era, place, and pressure"
))
} else {
Ok(())
}
}
fn seed_to_campaign(seed: CompiledSeed, receipts: &[VaultEvidenceReceipt]) -> Result<Campaign> {
let id = Uuid::new_v4();
let player_id = seed.player.id.clone();
let now = Utc::now();
let mut actors: BTreeMap<_, _> = seed.actors.into_iter().map(|x| (x.id.clone(), x)).collect();
if actors.insert(player_id.clone(), seed.player).is_some() {
return Err(anyhow!("player id duplicates an NPC"));
}
Ok(Campaign {
schema: "ghostlight.campaign.v1".into(),
id,
name: seed.title,
revision: 0,
branch_origin: BranchOrigin {
canon_cutoff: seed.canon_cutoff,
evidence_receipt_ids: receipt_ids(receipts),
},
world_time: seed.world_time,
tick_hours: seed.tick_hours,
player_actor_id: player_id,
locations: seed
.locations
.into_iter()
.map(|x| (x.id.clone(), x))
.collect(),
actors,
institutions: seed
.institutions
.into_iter()
.map(|x| (x.id.clone(), x))
.collect(),
clocks: seed.clocks.into_iter().map(|x| (x.id.clone(), x)).collect(),
facts: seed
.facts
.into_iter()
.map(|mut x| {
if x.scope == FactScope::CanonBaseline && x.evidence_receipt_ids.is_empty() {
x.scope = FactScope::ProvisionalLocal
};
(x.id.clone(), x)
})
.collect(),
transcript: vec![crate::domain::NarrativeTurn {
revision: 0,
at: now,
speaker: "world".into(),
text: seed.opening_narration,
}],
last_player_activity: now,
pending_ticks: 0,
})
}
pub fn validate_campaign_seed(c: &Campaign) -> Result<()> {
if c.tick_hours == 0 {
return Err(anyhow!("strategic tick duration must be positive"));
}
if !c.actors.contains_key(&c.player_actor_id) {
return Err(anyhow!("player actor is missing"));
}
for actor in c.actors.values() {
if !c.locations.contains_key(&actor.location_id) {
return Err(anyhow!(
"actor {} occupies unknown location {}",
actor.id,
actor.location_id
));
}
}
for location in c.locations.values() {
if let Some(parent) = &location.container_id {
if parent == &location.id || !c.locations.contains_key(parent) {
return Err(anyhow!("location {} has invalid container", location.id));
}
}
for route in location.routes.values() {
if route.travel_minutes == 0 || !c.locations.contains_key(&route.destination_id) {
return Err(anyhow!("location {} has invalid route", location.id));
}
}
}
for clock in c.clocks.values() {
if clock.threshold == 0 || clock.progress > clock.threshold {
return Err(anyhow!("clock {} is invalid", clock.id));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{domain::SourceWitness, model::ModelPort, vault::FixtureVault};
use async_trait::async_trait;
struct CompilerModel {
invalid_route: bool,
}
#[async_trait]
impl ModelPort for CompilerModel {
async fn run(&self, request: &ModelStageRequest) -> Result<String> {
Ok(match request.stage.as_str() {
"world_openings" => serde_json::json!({"openings":[
{"id":"a","title":"Ash","era":"early","place":"ring","pressure":"strike","player_hook":"work","evidence_receipt_ids":[]},
{"id":"b","title":"Glass","era":"middle","place":"moon","pressure":"siege","player_hook":"survive","evidence_receipt_ids":[]},
{"id":"c","title":"Rain","era":"late","place":"station","pressure":"election","player_hook":"choose","evidence_receipt_ids":[]}
]}).to_string(),
"world_compile" => {
let destination = if self.invalid_route { "missing" } else { "yard" };
serde_json::json!({
"title":"Grounded test", "canon_cutoff":"fixture", "world_time":"2026-01-01T00:00:00Z", "tick_hours":6,
"player":{"id":"player","name":"Tester","location_id":"yard","capabilities":[],"knowledge":[],"equipment":[],"conditions":[],"obligations":[],"relationships":{},"goals":["learn"]},
"locations":[{"id":"yard","name":"Yard","container_id":null,"routes":{"out":{"destination_id":destination,"distance":"near","travel_minutes":5}},"persistent_features":["same yard"]}],
"actors":[],"institutions":[],"clocks":[{"id":"shift","label":"Shift ends","progress":0,"threshold":4,"consequence":"night"}],
"facts":[{"id":"f","statement":"A witnessed fact","scope":"canon_baseline","evidence_receipt_ids":["fixture"]}],
"gaps":[],"branch_assumptions":[],"opening_narration":"The yard persists."
}).to_string()
}
_ => return Err(anyhow!("unexpected stage")),
})
}
fn provider(&self) -> &'static str {
"compiler-fixture"
}
}
fn vault() -> Arc<FixtureVault> {
Arc::new(FixtureVault {
witnesses: vec![SourceWitness {
source_id: "AetheriaLore:test.md".into(),
exact_locator: "test.md:1-2".into(),
content_hash: "sha256:test".into(),
excerpt: "A stable witnessed place.".into(),
authority_lane: "AetheriaLore".into(),
temporal_scope: "fixture".into(),
}],
})
}
#[tokio::test]
async fn opening_stage_requires_three_distinct_axes() {
let compiler = WorldCompiler::new(
vault(),
Arc::new(CompilerModel {
invalid_route: false,
}),
"pro",
);
let output = compiler
.suggest_openings(OpeningRequest {
setting: "Aetheria".into(),
constraints: vec![],
})
.await
.unwrap();
assert_eq!(output.openings.len(), 3);
assert_eq!(output.evidence_receipts.len(), 3);
}
#[tokio::test]
async fn compile_returns_approval_preview_without_committing() {
let compiler = WorldCompiler::new(
vault(),
Arc::new(CompilerModel {
invalid_route: false,
}),
"pro",
);
let (preview, _) = compiler
.compile_custom(CustomStart {
campaign_name: "Test".into(),
who: "worker".into(),
where_: "yard".into(),
when: "fixture".into(),
goal: "learn".into(),
})
.await
.unwrap();
assert!(preview.requires_approval);
assert_eq!(preview.campaign.revision, 0);
assert_eq!(preview.campaign.locations.len(), 1);
}
#[tokio::test]
async fn compiler_refuses_dream_route_to_unknown_location() {
let compiler = WorldCompiler::new(
vault(),
Arc::new(CompilerModel {
invalid_route: true,
}),
"pro",
);
let result = compiler
.compile_custom(CustomStart {
campaign_name: "Test".into(),
who: "worker".into(),
where_: "yard".into(),
when: "fixture".into(),
goal: "learn".into(),
})
.await;
assert!(result.unwrap_err().to_string().contains("invalid route"));
}
}

View file

@ -114,6 +114,7 @@ pub struct ActionIntent {
pub enum WorldCommand {
CreateCampaign {
campaign: Campaign,
evidence_receipts: Vec<VaultEvidenceReceipt>,
},
Speak {
expected_revision: u64,

View file

@ -78,14 +78,18 @@ fn execute(
assessments: &mut BTreeMap<String, ActionAssessment>,
command: WorldCommand,
) -> Result<CommandResult, KernelError> {
if let WorldCommand::CreateCampaign { campaign } = command {
if let WorldCommand::CreateCampaign {
campaign,
evidence_receipts,
} = command
{
if !store.keys("campaign.v1").map_err(persist)?.is_empty() {
return Err(KernelError::Invalid("campaign already exists".into()));
}
crate::compiler::validate_campaign_seed(&campaign)
.map_err(|error| KernelError::Invalid(error.to_string()))?;
store
.insert(
"campaign.v1",
"ghostlight.campaign.v1",
&campaign.id.to_string(),
&campaign,
)
.create_campaign(&campaign, &evidence_receipts)
.map_err(persist)?;
return Ok(CommandResult::Created { campaign });
}
@ -351,6 +355,7 @@ mod tests {
kernel
.command(WorldCommand::CreateCampaign {
campaign: seed.clone(),
evidence_receipts: vec![],
})
.await
.unwrap();
@ -385,6 +390,7 @@ mod tests {
kernel
.command(WorldCommand::CreateCampaign {
campaign: seed.clone(),
evidence_receipts: vec![],
})
.await
.unwrap();

View file

@ -1,3 +1,4 @@
pub mod compiler;
pub mod d20;
pub mod domain;
pub mod kernel;

View file

@ -9,10 +9,12 @@ use axum::{
use ghostlight_dungeon::windows_secret::unprotect_machine_utf8;
use ghostlight_dungeon::{
WorldKernel,
domain::{Campaign, WorldCommand},
model::{DeepSeekPort, ModelStageRequest, run_validated_stage},
compiler::{CustomStart, OpeningRequest, OpeningSuggestion, SelectedStart, WorldCompiler},
domain::{Campaign, WorldCommand, WorldCompilePreview},
model::{DeepSeekPort, ModelPort, ModelStageRequest, run_validated_stage},
persistence::CampaignStore,
surface::player_surface,
vault::VoidBotMcpVault,
};
use serde::Serialize;
use std::{
@ -32,6 +34,8 @@ struct AppState {
invites: Arc<Mutex<BTreeSet<String>>>,
sessions: Arc<Mutex<BTreeSet<String>>>,
deepseek_status: String,
compiler: Option<Arc<WorldCompiler>>,
compile_previews: Arc<Mutex<BTreeMap<String, WorldCompilePreview>>>,
}
#[tokio::main]
@ -45,13 +49,6 @@ async fn main() -> anyhow::Result<()> {
std::fs::create_dir_all(runtime_root.join("campaigns/default"))?;
let store = CampaignStore::open(runtime_root.join("campaigns/default/campaign.cc"))?;
let kernel = WorldKernel::start(store.clone());
if store.keys("campaign.v1")?.is_empty() {
kernel
.command(WorldCommand::CreateCampaign {
campaign: seed_campaign(),
})
.await?;
}
let invite_blob = runtime_root.join("secrets/invites.dpapi");
#[cfg(windows)]
let invite_material = if invite_blob.is_file() {
@ -78,10 +75,11 @@ async fn main() -> anyhow::Result<()> {
));
}
let secret_path = runtime_root.join("secrets/deepseek.dpapi");
let deepseek_status = if secret_path.is_file() {
let provider = DeepSeekPort::from_machine_dpapi(&secret_path)?;
let (deepseek_status, compiler) = if secret_path.is_file() {
let provider: Arc<dyn ModelPort> =
Arc::new(DeepSeekPort::from_machine_dpapi(&secret_path)?);
let probe = run_validated_stage(
&provider,
provider.as_ref(),
&ModelStageRequest {
stage: "startup_probe".into(),
model: "deepseek-v4-flash".into(),
@ -92,9 +90,16 @@ async fn main() -> anyhow::Result<()> {
},
)
.await?;
format!("ready:{}", probe.receipt.output_hash)
(
format!("ready:{}", probe.receipt.output_hash),
Some(Arc::new(WorldCompiler::new(
Arc::new(VoidBotMcpVault::starfire_loopback()),
provider,
"deepseek-v4-pro",
))),
)
} else {
"missing-secret".into()
("missing-secret".into(), None)
};
let state = AppState {
kernel,
@ -102,6 +107,8 @@ async fn main() -> anyhow::Result<()> {
invites: Arc::new(Mutex::new(invite_tokens)),
sessions: Arc::new(Mutex::new(BTreeSet::new())),
deepseek_status,
compiler,
compile_previews: Arc::new(Mutex::new(BTreeMap::new())),
};
let release_web_root = std::env::current_exe()?
.parent()
@ -113,6 +120,11 @@ async fn main() -> anyhow::Result<()> {
.route("/health", get(health))
.route("/invite/{token}", get(invite))
.route("/api/surface", get(surface))
.route("/api/compiler/openings", post(compile_openings))
.route("/api/compiler/roles", post(compile_roles))
.route("/api/compiler/selected", post(compile_selected))
.route("/api/compiler/custom", post(compile_custom))
.route("/api/compiler/approve/{preview_id}", post(approve_preview))
.route("/api/command", post(command))
.fallback_service(ServeDir::new(web_root).append_index_html_on_directories(true))
.with_state(state);
@ -152,7 +164,159 @@ async fn surface(headers: HeaderMap, State(state): State<AppState>) -> Response
}
match load_campaign(&state.store) {
Ok(campaign) => Json(player_surface(&campaign)).into_response(),
Err(error) => (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(),
Err(_) => Json(serde_json::json!({"schema":"gamecult.eve.surface.v1","surface_id":"ghostlight.compiler","version":0,"title":"Compile a world","layout":{"kind":"stack","children":[]}})).into_response(),
}
}
async fn compile_openings(
headers: HeaderMap,
State(state): State<AppState>,
Json(request): Json<OpeningRequest>,
) -> Response {
if !authorized(&headers, &state).await {
return StatusCode::UNAUTHORIZED.into_response();
}
let Some(compiler) = &state.compiler else {
return (
StatusCode::SERVICE_UNAVAILABLE,
"DeepSeek credential is unavailable",
)
.into_response();
};
match compiler.suggest_openings(request).await {
Ok(value) => Json(value).into_response(),
Err(error) => (StatusCode::BAD_GATEWAY, error.to_string()).into_response(),
}
}
async fn compile_custom(
headers: HeaderMap,
State(state): State<AppState>,
Json(request): Json<CustomStart>,
) -> Response {
if !authorized(&headers, &state).await {
return StatusCode::UNAUTHORIZED.into_response();
}
if !state
.store
.keys("campaign.v1")
.unwrap_or_default()
.is_empty()
{
return (StatusCode::CONFLICT, "campaign already exists").into_response();
}
let Some(compiler) = &state.compiler else {
return (
StatusCode::SERVICE_UNAVAILABLE,
"DeepSeek credential is unavailable",
)
.into_response();
};
match compiler.compile_custom(request).await {
Ok((preview, receipt)) => {
let id = uuid::Uuid::new_v4().to_string();
state
.compile_previews
.lock()
.await
.insert(id.clone(), preview.clone());
Json(serde_json::json!({"preview_id":id,"preview":preview,"model_receipt":receipt}))
.into_response()
}
Err(error) => (StatusCode::UNPROCESSABLE_ENTITY, error.to_string()).into_response(),
}
}
async fn compile_roles(
headers: HeaderMap,
State(state): State<AppState>,
Json(opening): Json<OpeningSuggestion>,
) -> Response {
if !authorized(&headers, &state).await {
return StatusCode::UNAUTHORIZED.into_response();
}
let Some(compiler) = &state.compiler else {
return (
StatusCode::SERVICE_UNAVAILABLE,
"DeepSeek credential is unavailable",
)
.into_response();
};
match compiler.suggest_roles(&opening).await {
Ok(value) => Json(value).into_response(),
Err(error) => (StatusCode::BAD_GATEWAY, error.to_string()).into_response(),
}
}
async fn compile_selected(
headers: HeaderMap,
State(state): State<AppState>,
Json(request): Json<SelectedStart>,
) -> Response {
if !authorized(&headers, &state).await {
return StatusCode::UNAUTHORIZED.into_response();
}
if !state
.store
.keys("campaign.v1")
.unwrap_or_default()
.is_empty()
{
return (StatusCode::CONFLICT, "campaign already exists").into_response();
}
let Some(compiler) = &state.compiler else {
return (
StatusCode::SERVICE_UNAVAILABLE,
"DeepSeek credential is unavailable",
)
.into_response();
};
store_preview(&state, compiler.compile_selected(request).await).await
}
async fn store_preview(
state: &AppState,
result: anyhow::Result<(
WorldCompilePreview,
ghostlight_dungeon::model::ModelStageReceipt,
)>,
) -> Response {
match result {
Ok((preview, receipt)) => {
let id = uuid::Uuid::new_v4().to_string();
state
.compile_previews
.lock()
.await
.insert(id.clone(), preview.clone());
Json(serde_json::json!({"preview_id":id,"preview":preview,"model_receipt":receipt}))
.into_response()
}
Err(error) => (StatusCode::UNPROCESSABLE_ENTITY, error.to_string()).into_response(),
}
}
async fn approve_preview(
Path(preview_id): Path<String>,
headers: HeaderMap,
State(state): State<AppState>,
) -> Response {
if !authorized(&headers, &state).await {
return StatusCode::UNAUTHORIZED.into_response();
}
let Some(preview) = state.compile_previews.lock().await.remove(&preview_id) else {
return (StatusCode::NOT_FOUND, "preview missing or already consumed").into_response();
};
match state
.kernel
.command(WorldCommand::CreateCampaign {
campaign: preview.campaign,
evidence_receipts: preview.evidence_receipts,
})
.await
{
Ok(value) => Json(value).into_response(),
Err(error) => (StatusCode::CONFLICT, error.to_string()).into_response(),
}
}
@ -209,6 +373,7 @@ struct ErrorBody {
error: String,
}
#[allow(dead_code)]
fn seed_campaign() -> Campaign {
let id = uuid::Uuid::new_v4();
let location = ghostlight_dungeon::domain::Location {

View file

@ -1,3 +1,4 @@
use crate::domain::{Campaign, VaultEvidenceReceipt};
use anyhow::{Context, Result, anyhow};
use chrono::Utc;
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
@ -60,6 +61,32 @@ impl CampaignStore {
Ok(row)
}
pub fn create_campaign(
&self,
campaign: &Campaign,
receipts: &[VaultEvidenceReceipt],
) -> Result<CultCacheEnvelope> {
let campaign_row = envelope(
"campaign.v1",
"ghostlight.campaign.v1",
&campaign.id.to_string(),
campaign,
)?;
let mut rows = vec![campaign_row.clone()];
for receipt in receipts {
rows.push(envelope(
"vault_evidence_receipt.v1",
"ghostlight.vault_evidence_receipt.v1",
&receipt.id,
receipt,
)?);
}
if !self.inner.compare_and_swap_batch(&[], rows)? {
return Err(anyhow!("campaign store is not empty"));
}
Ok(campaign_row)
}
pub fn replace<T: Serialize>(
&self,
expected: &CultCacheEnvelope,

View file

@ -17,6 +17,8 @@ pub struct VaultQuery {
#[async_trait]
pub trait VaultProvider: Send + Sync {
async fn search(&self, query: &VaultQuery) -> Result<VaultEvidenceReceipt>;
async fn surrounding_context(&self, source_id: &str, chunk_index: u32)
-> Result<SourceWitness>;
async fn exact_document(&self, source_id: &str) -> Result<SourceWitness>;
fn provider_id(&self) -> &'static str;
}
@ -45,6 +47,9 @@ impl VaultProvider for FixtureVault {
.cloned()
.ok_or_else(|| anyhow!("fixture source not found"))
}
async fn surrounding_context(&self, source_id: &str, _: u32) -> Result<SourceWitness> {
self.exact_document(source_id).await
}
fn provider_id(&self) -> &'static str {
"fixture"
}
@ -56,24 +61,108 @@ pub struct VoidBotMcpVault {
endpoint: String,
}
impl VoidBotMcpVault {
pub fn starfire_loopback() -> Self {
pub fn new(endpoint: impl Into<String>) -> Self {
Self {
client: Client::new(),
endpoint: "http://127.0.0.1:17875/mcp".into(),
endpoint: endpoint.into(),
}
}
pub fn starfire_loopback() -> Self {
Self::new("http://127.0.0.1:17875/mcp")
}
async fn call_tool(
&self,
name: &str,
arguments: serde_json::Value,
) -> Result<serde_json::Value> {
let text = self.client.post(&self.endpoint)
.header("accept", "application/json, text/event-stream")
.json(&serde_json::json!({"jsonrpc":"2.0","id":"ghostlight-vault","method":"tools/call","params":{"name":name,"arguments":arguments}}))
.send().await?.error_for_status()?.text().await?;
let payload = text
.lines()
.find_map(|line| line.strip_prefix("data: "))
.ok_or_else(|| anyhow!("VoidBot MCP returned no event payload"))?;
Ok(serde_json::from_str(payload)?)
}
}
#[cfg(test)]
mod tests {
use super::*;
use axum::{Router, response::IntoResponse, routing::post};
#[tokio::test]
async fn voidbot_search_results_become_exact_evidence_witnesses() {
let app=Router::new().route("/mcp",post(||async { ([("content-type","text/event-stream")], "event: message\ndata: {\"result\":{\"structuredContent\":{\"results\":[{\"sourceId\":\"AetheriaLore:place.md\",\"path\":\"place.md\",\"lineStart\":7,\"lineEnd\":9,\"text\":\"The route takes six hours.\"}]}}}\n\n").into_response() }));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
let vault = VoidBotMcpVault::new(format!("http://{address}/mcp"));
let result = vault
.search(&VaultQuery {
query: "route".into(),
authority_lanes: vec!["AetheriaLore".into()],
temporal_scope: "era".into(),
limit: 3,
})
.await
.unwrap();
assert_eq!(result.witnesses[0].exact_locator, "place.md:7-9");
assert!(result.witnesses[0].content_hash.starts_with("sha256:"));
assert_eq!(result.witnesses[0].authority_lane, "AetheriaLore");
}
}
#[async_trait]
impl VaultProvider for VoidBotMcpVault {
async fn search(&self, query: &VaultQuery) -> Result<VaultEvidenceReceipt> {
let response: serde_json::Value = self.client.post(&self.endpoint).json(&serde_json::json!({"jsonrpc":"2.0","id":"ghostlight-vault","method":"tools/call","params":{"name":"search_sources","arguments":{"query":query.query,"limit":query.limit}}})).send().await?.error_for_status()?.json().await?;
let witnesses = response
.pointer("/result/structuredContent/witnesses")
.cloned()
.and_then(|v| serde_json::from_value(v).ok())
.ok_or_else(|| anyhow!("VoidBot MCP returned no typed witnesses"))?;
let response = self
.call_tool(
"search_sources",
serde_json::json!({"query":query.query,"limit":query.limit}),
)
.await?;
let results = response
.pointer("/result/structuredContent/results")
.and_then(|v| v.as_array())
.ok_or_else(|| anyhow!("VoidBot MCP returned no typed search results"))?;
let witnesses = results
.iter()
.map(|item| witness_from_result(item, query))
.collect::<Result<Vec<_>>>()?;
Ok(receipt(self.provider_id(), query, witnesses))
}
async fn surrounding_context(
&self,
source_id: &str,
chunk_index: u32,
) -> Result<SourceWitness> {
let response = self
.call_tool(
"get_source_context",
serde_json::json!({"sourceId":source_id,"chunkIndex":chunk_index}),
)
.await?;
let value = response
.pointer("/result/structuredContent")
.ok_or_else(|| anyhow!("VoidBot MCP returned no source context"))?;
let excerpt = value
.get("text")
.and_then(|v| v.as_str())
.or_else(|| value.get("context").and_then(|v| v.as_str()))
.ok_or_else(|| anyhow!("VoidBot source context contained no text"))?;
Ok(SourceWitness {
source_id: source_id.into(),
exact_locator: format!("{source_id}#chunk={chunk_index}"),
content_hash: format!("sha256:{:x}", Sha256::digest(excerpt.as_bytes())),
excerpt: excerpt.into(),
authority_lane: "source_context".into(),
temporal_scope: "unspecified".into(),
})
}
async fn exact_document(&self, _source_id: &str) -> Result<SourceWitness> {
Err(anyhow!(
"exact-document VoidBot adapter awaits restored trusted crossing contract verification"
@ -84,6 +173,33 @@ impl VaultProvider for VoidBotMcpVault {
}
}
fn witness_from_result(item: &serde_json::Value, query: &VaultQuery) -> Result<SourceWitness> {
let source_id = item
.get("sourceId")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow!("search result missing sourceId"))?;
let excerpt = item
.get("text")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow!("search result missing text"))?;
let locator = match (
item.get("path").and_then(|v| v.as_str()),
item.get("lineStart").and_then(|v| v.as_u64()),
item.get("lineEnd").and_then(|v| v.as_u64()),
) {
(Some(path), Some(start), Some(end)) => format!("{path}:{start}-{end}"),
_ => source_id.into(),
};
Ok(SourceWitness {
source_id: source_id.into(),
exact_locator: locator,
content_hash: format!("sha256:{:x}", Sha256::digest(excerpt.as_bytes())),
excerpt: excerpt.into(),
authority_lane: query.authority_lanes.join(","),
temporal_scope: query.temporal_scope.clone(),
})
}
fn receipt(
provider: &str,
query: &VaultQuery,

View file

@ -15,6 +15,31 @@ core world, Persona, and Vault contracts remain setting-neutral.
Ghostlight's existing v0 schemas and Pallas, Lucent, and Corvid fixtures are
evidence and regression scenarios. They do not own runtime state or commits.
## Implementation frontier
The Rust runtime now contains the first honest world-compiler seam:
- `VaultProvider` search results become exact, hashed evidence witnesses from
VoidBot's live streamable MCP response shape;
- opening generation requires exactly three distinct eras, places, and
pressures;
- role generation requires exactly three grounded roles;
- custom compilation emits a bounded typed campaign, evidence receipts, gaps,
branch assumptions, and an approval-required preview;
- deterministic seed validation rejects missing occupancy, dangling or
zero-time routes, invalid containment, invalid clocks, and missing players;
- approval alone submits `CreateCampaign`, which atomically stores the campaign
and the exact Vault receipts in the campaign `.cc` store.
This is not yet the complete MVP compiler. The browser compiler flow, selected
opening/role compilation path, material-gap approval controls, exact-document
retrieval beyond bounded source context, on-demand destination compilation,
canon-candidate persistence remain. A live custom-start acceptance run on
2026-08-16 consumed 30 VoidBot witnesses across three exact receipts and
produced three locations, three actors, two institutions, two clocks,
explicit gaps, and branch assumptions. It remained an uncommitted revision-0
preview with `requires_approval: true`.
## Body and faculty map
| Faculty | Owner | Body | Authority |

View file

@ -33,9 +33,17 @@ per-campaign WorldKernel mailbox is the sole canonical writer. Ghostlight owns
the generalized Projector → Persona → Interpreter organ; Epiphany retains her
canonical Persona mind and will consume the shared organ through an adapter.
The immediate next action is to map Epiphany's existing projection machinery
into move/stay/split/delete ownership before continuing the Rust scaffold.
Existing Ghostlight fixtures remain regression evidence.
The Epiphany extraction map is complete. The active bounded organ is the world
compiler. Its Rust seam now retrieves hashed VoidBot witnesses, generates
distinct openings and roles, compiles approval-gated custom starts, rejects
invalid topology, and atomically admits campaign plus evidence only on
approval. The browser now exposes generated opening/role selection and custom
starts. A live DeepSeek plus VoidBot custom compilation passed with 30 witnessed
source chunks and remained an uncommitted approval preview. Next, prove browser
session/invite flow plus approval persistence against a disposable campaign
store, then add material-gap decisions, on-demand destination compilation, and
canon-candidate persistence. Existing Ghostlight fixtures remain regression
evidence.
## Prior research pipeline focus

View file

@ -203,6 +203,9 @@ paths as active state surfaces.
## Missing Or Incomplete Organs
- World compiler browser flow, selected-opening/role path, live provider
acceptance, material-gap approval, on-demand destination expansion, and
canon-candidate persistence
- Deterministic speaker-local input slicer
- Full prompt renderer
- Classifier/appraiser pipeline

171
notes/ghostlight-dungeon.md Normal file
View file

@ -0,0 +1,171 @@
# GhostlightDungeon MVP — Starfire-Hosted AI Dungeon Master
## Summary
Build `GhostlightDungeon` inside `GameCult/Ghostlight`: a persistent, Vault-grounded, single-player narrative simulation with a private web chat interface for two testers.
The runtime will be a Rust daemon on Starfire. It will own world compilation, typed CultCache state, d20 resolution, NPC Persona loops, offscreen simulation, narration, and Eve/CultUI publication. A thin TypeScript browser client will lower the Eve surface and submit typed commands.
Ghostlight’s existing v0 schemas and training fixtures remain evidence and regression material; they do not become runtime authorities.
## Authority and invariants
- The per-campaign `WorldKernel` is the sole owner of canonical state and revision numbers.
- Player commands, NPC actions, scheduled ticks, travel, waits, imports, and reloads all enter the same `WorldCommand → validate → atomic commit` path.
- Projectors, Personas, Interpreters, retrieval, initiative, narration, news generation, dice previews, and the browser may propose or project state; none may commit it.
- Scenes are derived from persistent occupancy, topology, perception, and current events. Leaving a location does not delete it.
- RAG evidence remains owned by the Vault provider. For Aetheria, Ghostlight consumes VoidBot’s canonical retrieval service and stores only exact evidence receipts used by each campaign—never a rival semantic index.
- Every campaign branches from canon at creation. Later historical records describe the baseline trajectory, not an outcome the player must be railroaded into.
- Improvised facts are explicitly branch-local. Broadly useful gaps become reviewable canon candidates, never silent Vault edits.
- Player text describes an attempt, not a completed fact. Impossible actions do not receive a roll.
- Model failures, malformed outputs, stale projections, or retrieval outages produce no partial world mutation.
## Implementation changes
### Runtime and persistence
- Add a Rust 2024 workspace using Tokio/Axum, the Rust CultCache/redb backend, CultMesh/CultNet publication, and a provider-neutral model port.
- Store service state under `F:\GameCult\GhostlightDungeon`:
- service/control and schema catalog `.cc`;
- one row-oriented `.cc` store per campaign;
- exact Vault evidence receipts;
- private model-stage records and commit receipts;
- exported campaign and canon-candidate bundles.
- Route all writers through an in-process campaign mailbox. Background ticks and HTTP commands cannot race or repair each other afterward.
- Publish the player surface, operator inspector, health, scheduler pressure, model receipts, and command results through CultMesh/Eve. HTTP health remains a probe of that state, not separate truth.
### Vault and world compiler
- Define a generic `VaultProvider` contract for source search, surrounding context, source witnesses, authority lanes, temporal scope, and exact-document retrieval.
- Implement the bundled Aetheria adapter against VoidBot’s streamable MCP endpoint at Starfire loopback.
- At campaign creation:
1. Retrieve broad Aetheria evidence and generate three distinct suggested openings across different eras, places, and pressures.
2. For the selected opening, generate three source-grounded player roles plus a custom-role path.
3. Alternatively compile a fully custom who/where/when/goal description.
4. Produce an approval preview containing the initial topology, cast, institutions, capabilities, clocks, evidence coverage, gaps, and branch-local assumptions.
5. Commit only after approval.
- Materialize a bounded playable region and surrounding institutional pressure graph, not the entire universe. New destinations compile on demand and attach to stable containment, route, distance, and travel-time records.
- Automatically improvise reversible local texture as provisional branch fact. Material gaps in geography, mechanics, institutions, or extraordinary abilities require approval before the world seed or action is admitted.
- Store useful gaps as `CanonCandidate` records with originating campaign, evidence, conflicts, proposed wording, and affected Vault sources. The lab can review and export Markdown plus `.cc` evidence; it cannot edit AetheriaLore or open PRs.
### Persona and world action loop
Ghostlight owns its own generalized projection machinery:
1. Projector converts the actor’s permitted typed slice, memories, perceived events, relationships, goals, and retrieved knowledge into a private lived narrative stream.
2. Persona receives only that narrative stream and responds naturally—no schemas, action DSL, or raw state.
3. Interpreter extracts typed private deltas, explicit speech, reaction priority, and `WorldActionProposal` candidates.
4. WorldKernel validates spatial reach, knowledge, custody, resources, capability, opposition, and state version before committing anything.
All affected scene participants appraise a committed event in parallel. Actor-private deltas commit against their own snapshot versions; initiative then chooses compatible reactions or actions for world resolution. This ensures present characters continue perceiving and reacting even when another character currently holds conversational focus.
Use DeepSeek’s current API directly:
- `deepseek-v4-flash`, non-thinking: Projectors, Interpreters, retrieval planning/reranking, verification, and offscreen actors.
- `deepseek-v4-pro`, non-thinking for live work: world compilation, action assessment, live Personas, and narration.
- Structured stages use JSON Output followed by local schema validation. Empty or malformed output receives one same-snapshot retry, then fails without mutation.
- Record provider, model, request hash, source receipts, latency, output hash, validation result, and state version. Never persist or display `reasoning_content`.
DeepSeek currently documents both V4 model IDs, streaming, and JSON output through its OpenAI-compatible Chat Completions API. [Models](https://api-docs.deepseek.com/quick_start/pricing), [Chat API](https://api-docs.deepseek.com/api/create-chat-completion), [JSON Output](https://api-docs.deepseek.com/guides/json_mode/).
### Fiction-first d20 resolution
- Provide separate `Assess` and `Attempt` commands. Assessment never becomes visible to NPCs or changes state.
- An assessment contains:
- normalized intent and intended effect;
- admissibility or the missing permission;
- DC on the 5/10/15/20/25/30 resistance scale;
- itemized contextual modifiers with state or evidence references;
- modifier total capped at ±10;
- effect ceiling;
- success, mixed-result, and failure stakes;
- campaign revision and expiring assessment digest.
- Contextual modifiers come from capabilities, knowledge, tools, access, assistance, leverage, position, opposition, injuries, and conditions. There are no base attributes.
- Confirmation checks the assessment revision, obtains a server-side OS-random d20, and atomically stores the roll receipt and world transition.
- Outcomes:
- total ≥ DC + 10: strong success;
- total ≥ DC: success;
- total within 5 below DC: mixed result;
- lower: failure with the previewed consequence.
- Natural 20/1 moves one outcome band, but cannot make an impossible action possible or exceed its effect ceiling.
- Stale assessments are recompiled rather than rebased.
- Overreach returns explicit sacrifices or bargains that could admit a new assessment.
- Speech and its intended effect are separated: the character may successfully say something while failing to persuade, deceive, or intimidate.
### Away-time world agency
- The daemon owns a five-minute scheduler pulse. Campaigns enter away simulation after fifteen minutes without player activity.
- Each real hour awards one strategic tick, capped at eight pending ticks per absence. The compiled campaign chooses the in-world tick duration; default is six hours.
- Background simulation affects remote actors, institutions, resources, movement, bargains, investigations, preparation, recruitment, obstruction, and clocks. The absent player is never puppeted or directly harmed.
- The scheduler and return-time catch-up invoke the same `AdvanceStrategicTick` command. Catch-up processes missed ticks before accepting the next player action.
- Live play has inference priority; background work stops launching new calls while a player turn is active.
- Offscreen events generate information-channel-aware news leads. On return, the player may receive newspapers, reports, messages, or rumors only when the character has access to them; the news layer cannot reveal omniscient state.
### Web laboratory and hosting
- Build the interface as a Ghostlight-owned `gamecult.eve.surface.v1` document and lower it with Eve’s pinned browser renderer.
- Provide:
- generated-opening and custom-start compiler;
- narrative transcript and composer;
- Assess, Attempt, confirm-roll, revise, and Wait controls;
- character ledger for capabilities, equipment, conditions, obligations, relationships, and known facts;
- location/time/pressure display;
- news and rumor drawer;
- named campaign creation, fork, reset, and `.cc` export;
- optional operator inspector for evidence, topology, state versions, model receipts, rejected proposals, and private spoiler traces.
- Do not expose model chain-of-thought or secrets.
- Serve the embedded web bundle on TCP `8831`. Firewall access is limited to Starfire’s private LAN and `10.77.0.0/24`; no public listener or Yggdrasil web gateway is added.
- Use two single-use invite links that establish separate HttpOnly sessions. Campaigns are single-player; simultaneous co-op is outside the MVP.
- Install `GhostlightDungeon` as an automatic Windows service under a dedicated virtual service identity. ACL the runtime root to administrators and the service identity.
- Read the DeepSeek key from stdin during setup, protect it with machine-scoped DPAPI plus file ACLs, and never place it in source, arguments, logs, or environment projections.
- Build immutable release directories from the exact Git commit, switch the active release atomically, record provenance in CultCache, and configure service restart recovery.
### Repository and operational documentation
- Implement on `codex/ghostlight-dungeon-mvp`, with coherent foundation, runtime, interface, and deployment commits pushed to GitHub.
- Add the authoritative GhostlightDungeon architecture/build document and update Ghostlight’s system map, implementation plan, handoff, state map, and evidence ledger.
- Keep Starfire service/firewall/tunnel ownership in `gamecult-ops`, with a deployment and rollback runbook.
- Before live VoidBot integration, resolve the current Yggdrasil inventory/DNS split and independently verify the offered SSH host fingerprint. Then repair the tunnel task’s stale `E:\Projects` path to `F:\Projects`, restore `127.0.0.1:17875/mcp`, and update ops truth. Never bypass host-key verification or revive Starfire’s retired VoidBot/Qdrant writers.
## Public contracts
- `ghostlight.vault_manifest.v1`, `vault_evidence_receipt.v1`, `world_compile_preview.v1`
- `campaign.v1`, `world_fact.v1`, `location.v1`, `actor_state.v1`, `institution_state.v1`, `relationship_state.v1`, `world_clock.v1`, `event.v1`
- `player_action_assessment.v1`, `roll_receipt.v1`, `world_commit_receipt.v1`
- `persona_stage_receipt.v1`, `actor_state_delta.v1`, `world_action_proposal.v1`
- `strategic_tick.v1`, `news_issue.v1`, `canon_candidate.v1`
- Existing `gamecult.eve.surface.v1` and `gamecult.eve.command.v1`
Publish JSON Schema only as the schema catalog. Runtime documents and exports use MessagePack-backed CultCache `.cc`; JSON exists only at browser, MCP, and model-provider boundaries.
## Test and acceptance plan
- Unit-test every schema, redb/CultCache round trip, optimistic commit, topology invariant, knowledge gate, DC/modifier rule, outcome band, roll receipt, branch fact, and scheduler budget.
- Use injected clocks, RNG, Vault provider, DeepSeek transport, and persistence ports.
- Prove malformed/empty DeepSeek JSON, timeout, retrieval loss, daemon restart, stale assessment, stale Persona output, and concurrent scheduler/player commands cannot partially mutate state.
- Run existing Pallas, Lucent, and Corvid fixtures as regression scenarios, even though hosted opening suggestions are generated.
- Acceptance scenarios:
- compile an obscure Aetheria time/place or return an honest evidence-gap preview;
- leave a location, advance the world, and return to the same geometry and inhabitants;
- show reactions from every affected present actor;
- prevent an NPC from acquiring unearned knowledge or expertise;
- reject impossible action claims and offer explicit bargains;
- preview and confirm a fully receipted d20 action;
- observe institutions exploiting, resisting, or redirecting the protagonist;
- produce material offscreen changes and accessible news after absence;
- reload/fork/export a campaign without losing continuity;
- verify two invite sessions and rejection of unauthenticated access.
- Performance targets under a healthy provider:
- first progress update within 300 ms;
- all actor stages execute in parallel waves;
- a four-actor live turn completes within 20 seconds;
- background inference yields immediately to live work.
- Final deployment smoke verifies service restart, LAN and WireGuard access, blocked public access, DeepSeek inference, VoidBot-grounded retrieval, scheduler continuation, state persistence, CultMesh/Eve publication, and exact deployed commit provenance.
## Assumptions and exclusions
- Aetheria is the only bundled Vault adapter, but no compiler logic is Aetheria-specific.
- Generated suggestions plus unrestricted custom compilation replace fixed featured openings.
- No D&D classes, spell slots, six-ability statistics, or 5e sheet are canonical in the MVP. The typed character ledger remains sufficient for later D&D-shaped projections.
- No arbitrary Vault upload/import UI, multiplayer campaign, voice, image generation, direct canon mutation, or public internet exposure.
- The live deployment requires a DeepSeek key and restoration of the trusted VoidBot retrieval crossing; fixture-backed development may proceed before those two setup gates.

View file

@ -8,12 +8,19 @@ architecture and ownership map is
pipeline and fixtures remain regression evidence; they do not become hosted
runtime authorities.
The first required cut is documentation and extraction mapping: inventory the
Projector → Persona → Interpreter machinery currently embedded in Epiphany,
classify move/stay/split/delete ownership, and only then continue runtime code.
The Epiphany Projector → Persona → Interpreter extraction map is complete.
Ghostlight owns the generalized projection organ. Epiphany keeps her canonical
Persona mind and consumes the shared organ through a narrow adapter.
The active implementation cut is the world compiler. The first Rust seam now
owns Vault witness conversion, distinct opening and role proposals,
approval-gated custom compilation, deterministic seed validation, atomic
campaign-plus-evidence admission, and the browser opening/role/custom flow. A
live DeepSeek plus VoidBot custom compilation passed without committing. Prove
invite/session plus approval persistence against a disposable campaign store,
then implement material-gap decisions, on-demand destination compilation, and
canon-candidate persistence before moving to the action/Persona loop.
## Prior research-program phase
Build a reliable data-generation loop for socially persistent Aetheria agents.

View file

@ -69,4 +69,5 @@
{"note": "GhostlightDungeon ownership map accepted: Ghostlight owns generalized Projector-Persona-Interpreter machinery; consuming Personas such as Epiphany retain canonical mind and commit authority through narrow adapters. WorldKernel is the sole campaign writer.", "status": "accepted", "ts": "2026-08-16T14:26:32+00:00", "type": "architecture"}
{"note": "Epiphany extraction map grounded in persona_turn.rs, persona_executor.rs, persona-service, conversation, and Discord crossing: shared orchestration moves to Ghostlight; Epiphany Mind/state/mouth stay; narrow slicer, transport, receipt, schema, and permit ports split; strict v1 removes second-channel state from Persona turn.", "status": "accepted", "ts": "2026-08-16T14:28:19+00:00", "type": "architecture"}
{"note": "DeepSeek credential validated and migrated from plaintext ops ingress to machine-scoped DPAPI at the runtime root; native Rust DPAPI loading and live deepseek-v4-flash startup probe passed without persisting or displaying secret or reasoning content. Service ACL and protected invite generation remain in the elevated ops install.", "status": "ok", "ts": "2026-08-16T14:46:04+00:00", "type": "verification"}
{"ts": "2026-08-16T15:00:31+00:00", "type": "deployment", "status": "ok", "note": "GhostlightDungeon MVP deployed on Starfire as a normal detached operator process, not a Windows service. Exact release 747b27e9 listens on 8831, DeepSeek DPAPI startup inference is ready, unauthenticated surface access returns 401, PID/executable/log witnesses are recorded, and the obsolete stopped service was deleted."}
{"note": "GhostlightDungeon MVP deployed on Starfire as a normal detached operator process, not a Windows service. Exact release 747b27e9 listens on 8831, DeepSeek DPAPI startup inference is ready, unauthenticated surface access returns 401, PID/executable/log witnesses are recorded, and the obsolete stopped service was deleted.", "status": "ok", "ts": "2026-08-16T15:00:31+00:00", "type": "deployment"}
{"ts": "2026-08-16T18:12:28+00:00", "type": "implementation", "status": "ok", "note": "World compiler live acceptance passed on 2026-08-16: DeepSeek v4 Pro consumed 30 hashed VoidBot witnesses across three receipts, emitted three locations, three actors, two institutions, two clocks, explicit gaps and branch assumptions, and remained an uncommitted revision-0 approval preview. Deterministic tests reject dangling routes and malformed typed seeds."}

View file

@ -71,3 +71,4 @@
{"key": "2026-08-16T142819Z0000-0069-97f4de27c74a", "payload": "eyJub3RlIjogIkVwaXBoYW55IGV4dHJhY3Rpb24gbWFwIGdyb3VuZGVkIGluIHBlcnNvbmFfdHVybi5ycywgcGVyc29uYV9leGVjdXRvci5ycywgcGVyc29uYS1zZXJ2aWNlLCBjb252ZXJzYXRpb24sIGFuZCBEaXNjb3JkIGNyb3NzaW5nOiBzaGFyZWQgb3JjaGVzdHJhdGlvbiBtb3ZlcyB0byBHaG9zdGxpZ2h0OyBFcGlwaGFueSBNaW5kL3N0YXRlL21vdXRoIHN0YXk7IG5hcnJvdyBzbGljZXIsIHRyYW5zcG9ydCwgcmVjZWlwdCwgc2NoZW1hLCBhbmQgcGVybWl0IHBvcnRzIHNwbGl0OyBzdHJpY3QgdjEgcmVtb3ZlcyBzZWNvbmQtY2hhbm5lbCBzdGF0ZSBmcm9tIFBlcnNvbmEgdHVybi4iLCAic3RhdHVzIjogImFjY2VwdGVkIiwgInRzIjogIjIwMjYtMDgtMTZUMTQ6Mjg6MTkrMDA6MDAiLCAidHlwZSI6ICJhcmNoaXRlY3R1cmUifQ==", "stored_at": "2026-08-16T14:28:19.728049+00:00", "type": "ghostlight.evidence_record.v0"}
{"key": "2026-08-16T144604Z0000-0070-b7d6330d1d5c", "payload": "eyJub3RlIjogIkRlZXBTZWVrIGNyZWRlbnRpYWwgdmFsaWRhdGVkIGFuZCBtaWdyYXRlZCBmcm9tIHBsYWludGV4dCBvcHMgaW5ncmVzcyB0byBtYWNoaW5lLXNjb3BlZCBEUEFQSSBhdCB0aGUgcnVudGltZSByb290OyBuYXRpdmUgUnVzdCBEUEFQSSBsb2FkaW5nIGFuZCBsaXZlIGRlZXBzZWVrLXY0LWZsYXNoIHN0YXJ0dXAgcHJvYmUgcGFzc2VkIHdpdGhvdXQgcGVyc2lzdGluZyBvciBkaXNwbGF5aW5nIHNlY3JldCBvciByZWFzb25pbmcgY29udGVudC4gU2VydmljZSBBQ0wgYW5kIHByb3RlY3RlZCBpbnZpdGUgZ2VuZXJhdGlvbiByZW1haW4gaW4gdGhlIGVsZXZhdGVkIG9wcyBpbnN0YWxsLiIsICJzdGF0dXMiOiAib2siLCAidHMiOiAiMjAyNi0wOC0xNlQxNDo0NjowNCswMDowMCIsICJ0eXBlIjogInZlcmlmaWNhdGlvbiJ9", "stored_at": "2026-08-16T14:46:04.295343+00:00", "type": "ghostlight.evidence_record.v0"}
{"key": "2026-08-16T150031Z0000-0071-f1b3502e505f", "payload": "eyJub3RlIjogIkdob3N0bGlnaHREdW5nZW9uIE1WUCBkZXBsb3llZCBvbiBTdGFyZmlyZSBhcyBhIG5vcm1hbCBkZXRhY2hlZCBvcGVyYXRvciBwcm9jZXNzLCBub3QgYSBXaW5kb3dzIHNlcnZpY2UuIEV4YWN0IHJlbGVhc2UgNzQ3YjI3ZTkgbGlzdGVucyBvbiA4ODMxLCBEZWVwU2VlayBEUEFQSSBzdGFydHVwIGluZmVyZW5jZSBpcyByZWFkeSwgdW5hdXRoZW50aWNhdGVkIHN1cmZhY2UgYWNjZXNzIHJldHVybnMgNDAxLCBQSUQvZXhlY3V0YWJsZS9sb2cgd2l0bmVzc2VzIGFyZSByZWNvcmRlZCwgYW5kIHRoZSBvYnNvbGV0ZSBzdG9wcGVkIHNlcnZpY2Ugd2FzIGRlbGV0ZWQuIiwgInN0YXR1cyI6ICJvayIsICJ0cyI6ICIyMDI2LTA4LTE2VDE1OjAwOjMxKzAwOjAwIiwgInR5cGUiOiAiZGVwbG95bWVudCJ9", "stored_at": "2026-08-16T15:00:31.447772+00:00", "type": "ghostlight.evidence_record.v0"}
{"key": "2026-08-16T181228Z0000-0072-4445afe2af66", "payload": "eyJub3RlIjogIldvcmxkIGNvbXBpbGVyIGxpdmUgYWNjZXB0YW5jZSBwYXNzZWQgb24gMjAyNi0wOC0xNjogRGVlcFNlZWsgdjQgUHJvIGNvbnN1bWVkIDMwIGhhc2hlZCBWb2lkQm90IHdpdG5lc3NlcyBhY3Jvc3MgdGhyZWUgcmVjZWlwdHMsIGVtaXR0ZWQgdGhyZWUgbG9jYXRpb25zLCB0aHJlZSBhY3RvcnMsIHR3byBpbnN0aXR1dGlvbnMsIHR3byBjbG9ja3MsIGV4cGxpY2l0IGdhcHMgYW5kIGJyYW5jaCBhc3N1bXB0aW9ucywgYW5kIHJlbWFpbmVkIGFuIHVuY29tbWl0dGVkIHJldmlzaW9uLTAgYXBwcm92YWwgcHJldmlldy4gRGV0ZXJtaW5pc3RpYyB0ZXN0cyByZWplY3QgZGFuZ2xpbmcgcm91dGVzIGFuZCBtYWxmb3JtZWQgdHlwZWQgc2VlZHMuIiwgInN0YXR1cyI6ICJvayIsICJ0cyI6ICIyMDI2LTA4LTE2VDE4OjEyOjI4KzAwOjAwIiwgInR5cGUiOiAiaW1wbGVtZW50YXRpb24ifQ==", "stored_at": "2026-08-16T18:12:28.266343+00:00", "type": "ghostlight.evidence_record.v0"}

View file

@ -254,5 +254,5 @@ data_flow:
- If state grows faster than understanding, cut it back.
current_status:
summary: GhostlightDungeon is the active MVP program. Its authority map assigns canonical campaign state and revision ownership to a per-campaign WorldKernel mailbox, preserves existing fixtures as regression evidence, and assigns the generalized Projector-Persona-Interpreter organ to Ghostlight while each consuming Persona retains its own canonical mind and commit authority.
next_action: Map Epiphany's current Persona projection implementation in plain language and source references, classify every part as move to Ghostlight, stay in Epiphany, split at a narrow port, or delete, then revise the inert Rust scaffold against that map before continuing implementation.
summary: GhostlightDungeon is the active MVP program. The world-compiler seam retrieves hashed VoidBot witnesses, generates distinct openings and roles, compiles approval-gated custom starts, rejects invalid typed topology, and admits campaign plus evidence through the WorldKernel only after approval. Its browser flow is built and a live DeepSeek plus VoidBot custom compilation passed with 30 witnessed chunks while remaining uncommitted. The broader hosted MVP remains incomplete.
next_action: Prove invite/session and approval persistence through the HTTP harness against a disposable campaign store, then implement material-gap decisions, on-demand destination compilation, and canon-candidate persistence before moving to the action and Persona loop.

File diff suppressed because one or more lines are too long

153
web/dist/assets/index-Dqaht4pv.js vendored Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

12
web/dist/index.html vendored
View file

@ -1,5 +1,11 @@
<!doctype html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>GhostlightDungeon</title> <script type="module" crossorigin src="/assets/index-CmB__dez.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-CyG_836Q.css">
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>GhostlightDungeon</title> <script type="module" crossorigin src="/assets/index-Dqaht4pv.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-Dt7lvyL0.css">
</head>
<body><header><p class="eyebrow">STARFIRE / PRIVATE VERSE</p><h1>GhostlightDungeon</h1><p id="status">Reading the world…</p></header><main><section id="surface"></section><form id="composer"><label for="attempt">Describe what you attempt</label><textarea id="attempt" required></textarea><div><button type="submit">Assess</button><button type="button" id="wait">Wait one hour</button></div></form><pre id="receipt" hidden></pre></main></body></html>
<body><header><p class="eyebrow">STARFIRE / PRIVATE VERSE</p><h1>GhostlightDungeon</h1><p id="status">Reading the world…</p></header><main>
<section id="compiler" hidden><h2>Compile a world</h2><div class="compiler-grid">
<form id="suggest-form"><label for="setting">Generate three grounded openings</label><input id="setting" value="Aetheria" required><button type="submit">Retrieve and suggest</button></form>
<form id="custom-form"><label>Or describe your own beginning</label><input name="campaign_name" placeholder="Campaign name" required><input name="who" placeholder="Who are you?" required><input name="where_" placeholder="Where?" required><input name="when" placeholder="When?" required><textarea name="goal" placeholder="What do you want?" required></textarea><button type="submit">Compile custom start</button></form>
</div><div id="compiler-results"></div></section><section id="surface"></section>
<form id="composer"><label for="attempt">Describe what you attempt</label><textarea id="attempt" required></textarea><div><button type="submit">Assess</button><button type="button" id="wait">Wait one hour</button></div></form><pre id="receipt" hidden></pre>
</main></body></html>

View file

@ -1,3 +1,9 @@
<!doctype html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>GhostlightDungeon</title></head>
<body><header><p class="eyebrow">STARFIRE / PRIVATE VERSE</p><h1>GhostlightDungeon</h1><p id="status">Reading the world…</p></header><main><section id="surface"></section><form id="composer"><label for="attempt">Describe what you attempt</label><textarea id="attempt" required></textarea><div><button type="submit">Assess</button><button type="button" id="wait">Wait one hour</button></div></form><pre id="receipt" hidden></pre></main><script type="module" src="/src/main.ts"></script></body></html>
<body><header><p class="eyebrow">STARFIRE / PRIVATE VERSE</p><h1>GhostlightDungeon</h1><p id="status">Reading the world…</p></header><main>
<section id="compiler" hidden><h2>Compile a world</h2><div class="compiler-grid">
<form id="suggest-form"><label for="setting">Generate three grounded openings</label><input id="setting" value="Aetheria" required><button type="submit">Retrieve and suggest</button></form>
<form id="custom-form"><label>Or describe your own beginning</label><input name="campaign_name" placeholder="Campaign name" required><input name="who" placeholder="Who are you?" required><input name="where_" placeholder="Where?" required><input name="when" placeholder="When?" required><textarea name="goal" placeholder="What do you want?" required></textarea><button type="submit">Compile custom start</button></form>
</div><div id="compiler-results"></div></section><section id="surface"></section>
<form id="composer"><label for="attempt">Describe what you attempt</label><textarea id="attempt" required></textarea><div><button type="submit">Assess</button><button type="button" id="wait">Wait one hour</button></div></form><pre id="receipt" hidden></pre>
</main><script type="module" src="/src/main.ts"></script></body></html>

View file

@ -5,32 +5,54 @@ import "./style.css";
const host = document.querySelector<HTMLElement>("#surface")!;
const status = document.querySelector<HTMLElement>("#status")!;
const receipt = document.querySelector<HTMLElement>("#receipt")!;
const compiler = document.querySelector<HTMLElement>("#compiler")!;
const composer = document.querySelector<HTMLFormElement>("#composer")!;
const compilerResults = document.querySelector<HTMLElement>("#compiler-results")!;
let revision = 0;
let actorId = "player";
async function refresh() {
const response = await fetch("/api/surface");
if (response.status === 401) { status.textContent = "This laboratory requires an unused invite link."; return; }
const surface = await response.json();
const needsCompilation = surface.surface_id === "ghostlight.compiler";
compiler.hidden = !needsCompilation; composer.hidden = needsCompilation; host.hidden = needsCompilation;
if (needsCompilation) { status.textContent = "No campaign exists. Retrieve the Vault and approve a world seed."; return; }
revision = Number(surface.version ?? 0);
renderEveSurface(surface, host, { body: document.body, clientId: "ghostlight.browser", statusElement: status });
}
async function send(command: unknown) {
status.textContent = "The world is considering the command…";
const response = await fetch("/api/command", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(command) });
const body = await response.json();
receipt.hidden = false;
receipt.textContent = JSON.stringify(body, null, 2);
if (!response.ok) { status.textContent = body.error ?? "The command was refused."; return; }
await refresh();
async function compilerPost(path: string, body: unknown) {
status.textContent = "Retrieving evidence and compiling…";
const response = await fetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
const value = response.headers.get("content-type")?.includes("json") ? await response.json() : await response.text();
if (!response.ok) { status.textContent = typeof value === "string" ? value : "Compilation failed"; throw new Error(status.textContent); }
return value;
}
document.querySelector<HTMLFormElement>("#composer")!.addEventListener("submit", event => {
function showCards(items: any[], action: string, choose: (item: any) => void) {
compilerResults.innerHTML = `<div class="cards">${items.map((item, index) => `<article class="card"><h3>${item.title ?? item.name}</h3><p>${item.player_hook ?? item.premise}</p><p>${item.era ? `${item.era} · ${item.place} · ${item.pressure}` : ""}</p><button data-index="${index}">${action}</button></article>`).join("")}</div>`;
compilerResults.querySelectorAll<HTMLButtonElement>("button").forEach(button => button.addEventListener("click", () => choose(items[Number(button.dataset.index)])));
}
document.querySelector<HTMLFormElement>("#suggest-form")!.addEventListener("submit", async event => {
event.preventDefault();
const text = document.querySelector<HTMLTextAreaElement>("#attempt")!.value.trim();
if (!text) return;
void send({ type: "assess", expected_revision: revision, intent: { actor_id: actorId, description: text, intended_effect: text } });
const result = await compilerPost("/api/compiler/openings", { setting: document.querySelector<HTMLInputElement>("#setting")!.value, constraints: [] });
showCards(result.openings, "Choose opening", async opening => {
const roles = await compilerPost("/api/compiler/roles", opening);
showCards(roles.roles, "Choose role", async role => showPreview(await compilerPost("/api/compiler/selected", { campaign_name: opening.title, opening, role })));
});
});
document.querySelector<HTMLFormElement>("#custom-form")!.addEventListener("submit", async event => { event.preventDefault(); await showPreview(await compilerPost("/api/compiler/custom", Object.fromEntries(new FormData(event.currentTarget as HTMLFormElement)))); });
async function showPreview(result: any) {
const preview = result.preview;
compilerResults.innerHTML = `<article class="card"><h3>${preview.title}</h3><p>${preview.campaign.transcript?.[0]?.text ?? ""}</p><p>${Object.keys(preview.campaign.locations).length} locations · ${Object.keys(preview.campaign.actors).length} actors · ${Object.keys(preview.campaign.institutions).length} institutions</p><p class="warning">${preview.gaps.length ? `Material gaps: ${preview.gaps.join("; ")}` : "No declared material gaps."}</p><p>Branch assumptions: ${preview.branch_assumptions.join("; ") || "none"}</p><button id="approve-world">Approve and enter</button></article>`;
document.querySelector<HTMLButtonElement>("#approve-world")!.addEventListener("click", async () => { await compilerPost(`/api/compiler/approve/${result.preview_id}`, {}); await refresh(); });
status.textContent = "Preview compiled. Nothing has entered world state yet.";
}
async function send(command: unknown) { status.textContent = "The world is considering the command…"; const response = await fetch("/api/command", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(command) }); const body = await response.json(); receipt.hidden = false; receipt.textContent = JSON.stringify(body, null, 2); if (!response.ok) { status.textContent = body.error ?? "The command was refused."; return; } await refresh(); }
composer.addEventListener("submit", event => { event.preventDefault(); const text = document.querySelector<HTMLTextAreaElement>("#attempt")!.value.trim(); if (text) void send({ type: "assess", expected_revision: revision, intent: { actor_id: "player", description: text, intended_effect: text } }); });
document.querySelector<HTMLButtonElement>("#wait")!.addEventListener("click", () => void send({ type: "wait", expected_revision: revision, minutes: 60 }));
void refresh();

View file

@ -1,2 +1,2 @@
@import url('https://fonts.googleapis.com/css2?family=Crimson+Pro:opsz,wght@8..144,400;8..144,600&family=IBM+Plex+Mono:wght@400;600&display=swap');
:root{color-scheme:dark;font-family:"Crimson Pro",serif;background:#0c1110;color:#e8e1cf}body{margin:0;min-height:100vh;background:radial-gradient(circle at 15% 0,#253229 0,transparent 38rem),linear-gradient(145deg,#0c1110,#111513)}header,main{width:min(920px,calc(100% - 2rem));margin:auto}header{padding:3rem 0 1.25rem;border-bottom:1px solid #66543d}h1{font-size:clamp(2.6rem,8vw,5.5rem);font-weight:400;letter-spacing:-.045em;margin:.1rem 0}.eyebrow,#status,label,button,pre{font-family:"IBM Plex Mono",monospace}.eyebrow{color:#d49b58;letter-spacing:.18em;font-size:.72rem}#status{color:#9aa69f;font-size:.78rem}main{padding:1.5rem 0 5rem}#surface{min-height:15rem}form{margin-top:1.5rem;padding:1rem;border:1px solid #66543d;background:#17201ddd}label{display:block;font-size:.72rem;text-transform:uppercase;letter-spacing:.12em;margin-bottom:.65rem}textarea{box-sizing:border-box;width:100%;min-height:7rem;resize:vertical;background:#0b0f0d;color:#f2e7d0;border:1px solid #4a5148;padding:.9rem;font:1.25rem/1.4 "Crimson Pro",serif}button{margin:.8rem .5rem 0 0;padding:.65rem 1rem;border:1px solid #d49b58;background:#d49b58;color:#17120c;cursor:pointer}button+button{background:transparent;color:#d49b58}pre{white-space:pre-wrap;padding:1rem;background:#080b09;color:#aeb9af;overflow:auto;font-size:.72rem}@media(max-width:600px){header{padding-top:2rem}h1{font-size:3rem}}
:root{color-scheme:dark;font-family:"Crimson Pro",serif;background:#0c1110;color:#e8e1cf}body{margin:0;min-height:100vh;background:radial-gradient(circle at 15% 0,#253229 0,transparent 38rem),linear-gradient(145deg,#0c1110,#111513)}header,main{width:min(920px,calc(100% - 2rem));margin:auto}header{padding:3rem 0 1.25rem;border-bottom:1px solid #66543d}h1{font-size:clamp(2.6rem,8vw,5.5rem);font-weight:400;letter-spacing:-.045em;margin:.1rem 0}.eyebrow,#status,label,button,pre{font-family:"IBM Plex Mono",monospace}.eyebrow{color:#d49b58;letter-spacing:.18em;font-size:.72rem}#status{color:#9aa69f;font-size:.78rem}main{padding:1.5rem 0 5rem}#surface{min-height:15rem}form,.card{margin-top:1.5rem;padding:1rem;border:1px solid #66543d;background:#17201ddd}label{display:block;font-size:.72rem;text-transform:uppercase;letter-spacing:.12em;margin-bottom:.65rem}textarea,input{box-sizing:border-box;width:100%;resize:vertical;background:#0b0f0d;color:#f2e7d0;border:1px solid #4a5148;padding:.9rem;margin:.35rem 0;font:1.05rem/1.4 "Crimson Pro",serif}textarea{min-height:7rem}button{margin:.8rem .5rem 0 0;padding:.65rem 1rem;border:1px solid #d49b58;background:#d49b58;color:#17120c;cursor:pointer}button+button{background:transparent;color:#d49b58}pre{white-space:pre-wrap;padding:1rem;background:#080b09;color:#aeb9af;overflow:auto;font-size:.72rem}.compiler-grid{display:grid;grid-template-columns:1fr 1fr;gap:1rem}.cards{display:grid;gap:.7rem}.card h3{margin:.1rem 0}.card p{color:#b9c0b7}.warning{color:#e4a86a!important}@media(max-width:700px){.compiler-grid{grid-template-columns:1fr}}@media(max-width:600px){header{padding-top:2rem}h1{font-size:3rem}}