From ed136f52c1c6dd6b70e28cf139579156b19667ae Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 17 Aug 2026 17:19:34 +0200 Subject: [PATCH] Harden model boundaries and live acceptance --- crates/ghostlight-dungeon/src/assessor.rs | 19 +- .../src/bin/ghostlight-action-smoke.rs | 264 ++++++++++ .../src/bin/ghostlight-compiler-smoke.rs | 26 +- .../src/bin/ghostlight-gestalt-scale-smoke.rs | 299 ++++++++++++ .../src/bin/ghostlight-live-turn-smoke.rs | 4 +- .../src/bin/ghostlight-narrator-smoke.rs | 65 +++ .../src/bin/ghostlight-strategic-smoke.rs | 1 + crates/ghostlight-dungeon/src/compiler.rs | 458 +++++++++++++++--- crates/ghostlight-dungeon/src/domain.rs | 3 + crates/ghostlight-dungeon/src/gestalt.rs | 2 + crates/ghostlight-dungeon/src/kernel.rs | 4 + crates/ghostlight-dungeon/src/main.rs | 2 + crates/ghostlight-dungeon/src/model.rs | 284 ++++++++++- crates/ghostlight-dungeon/src/narrator.rs | 4 +- crates/ghostlight-dungeon/src/persona.rs | 232 ++++++--- crates/ghostlight-dungeon/src/registry.rs | 4 + crates/ghostlight-dungeon/src/resolution.rs | 44 +- crates/ghostlight-dungeon/src/scheduler.rs | 117 +++-- crates/ghostlight-dungeon/src/surface.rs | 61 ++- crates/ghostlight-dungeon/src/vault.rs | 52 +- .../ghostlight-persona-projection/src/lib.rs | 11 +- docs/architecture/ghostlight-dungeon-mvp.md | 25 +- notes/fresh-workspace-handoff.md | 22 +- notes/ghostlight-current-system-map.md | 12 +- notes/ghostlight-implementation-plan.md | 30 +- state/evidence.jsonl | 1 + state/map.yaml | 7 +- 27 files changed, 1815 insertions(+), 238 deletions(-) create mode 100644 crates/ghostlight-dungeon/src/bin/ghostlight-action-smoke.rs create mode 100644 crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-scale-smoke.rs create mode 100644 crates/ghostlight-dungeon/src/bin/ghostlight-narrator-smoke.rs diff --git a/crates/ghostlight-dungeon/src/assessor.rs b/crates/ghostlight-dungeon/src/assessor.rs index 7ec91f3..fd5ca58 100644 --- a/crates/ghostlight-dungeon/src/assessor.rs +++ b/crates/ghostlight-dungeon/src/assessor.rs @@ -70,16 +70,25 @@ impl ActionAssessor { }) .collect(); let allowed_references = allowed_references(campaign, actor); - let schema = serde_json::to_value(schema_for!(AssessmentProposal))?; + let mut schema = serde_json::to_value(schema_for!(AssessmentProposal))?; + schema["properties"]["dc"] = serde_json::json!({ + "type":"integer", + "enum":[5,10,15,20,25,30] + }); + schema["$defs"]["ContextModifier"]["properties"]["value"] = serde_json::json!({ + "type":"integer", + "minimum":-10, + "maximum":10 + }); let base_prompt = format!( - "Assess an attempted effect, not whether words can be spoken. Impossible actions are inadmissible and receive bargains, not a roll. Choose DC only from 5,10,15,20,25,30. Every modifier reference must be copied exactly from ALLOWED REFERENCES. Modifier total is capped at +/-10. Never grant capability, custody, access, knowledge, or spatial reach absent from state. State concrete success, mixed, and failure consequences and a bounded effect ceiling. Outcome deltas may only name actor IDs copied exactly from PRESENT ACTORS, change their conditions or relationships, move only the acting actor along an existing route, advance existing clocks, or change existing institution posture. Keep a delta empty when prose consequence has no canonical state change.\nINTENT:\n{}\nACTOR:\n{}\nLOCATION:\n{}\nPRESENT ACTORS:\n{}\nVISIBLE INSTITUTIONS:\n{}\nALLOWED REFERENCES:\n{}\nOUTPUT JSON SCHEMA:\n{}", + "OUTPUT JSON SCHEMA (follow exactly):\n{}\n\nAssess an attempted effect, not whether words can be spoken. Impossible actions are inadmissible and receive bargains, not a roll. Choose DC only from 5,10,15,20,25,30. Every modifier reference must be copied exactly from ALLOWED REFERENCES. Modifier total is capped at +/-10. Never grant capability, custody, access, knowledge, or spatial reach absent from state. State concrete success, mixed, and failure consequences and a bounded effect ceiling. Outcome deltas may only name actor IDs copied exactly from PRESENT ACTORS, change their conditions or relationships, move only the acting actor along an existing route, advance existing clocks, or change existing institution posture. Keep a delta empty when prose consequence has no canonical state change.\nINTENT:\n{}\nACTOR:\n{}\nLOCATION:\n{}\nPRESENT ACTORS:\n{}\nVISIBLE INSTITUTIONS:\n{}\nALLOWED REFERENCES:\n{}", + serde_json::to_string(&schema)?, serde_json::to_string(&intent)?, serde_json::to_string(actor)?, serde_json::to_string(location)?, serde_json::to_string(&present_actors)?, serde_json::to_string(&visible_institutions)?, - serde_json::to_string(&allowed_references)?, - serde_json::to_string_pretty(&schema)? + serde_json::to_string(&allowed_references)? ); let snapshot_binding = format!("campaign:{}:revision:{}", campaign.id, campaign.revision); let mut correction = String::new(); @@ -95,6 +104,8 @@ impl ActionAssessor { lived_stream: format!("{base_prompt}{correction}"), output_schema: Some(schema.clone()), source_receipt_ids: campaign.branch_origin.evidence_receipt_ids.clone(), + temperature: Some(0.0), + max_output_tokens: Some(1_800), }, ) .await?; diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-action-smoke.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-action-smoke.rs new file mode 100644 index 0000000..805e489 --- /dev/null +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-action-smoke.rs @@ -0,0 +1,264 @@ +#[cfg(not(windows))] +fn main() -> anyhow::Result<()> { + anyhow::bail!("the live action smoke uses Starfire's DPAPI credential") +} + +#[cfg(windows)] +#[tokio::main] +async fn main() -> anyhow::Result<()> { + use chrono::Utc; + use ghostlight_dungeon::{ + assessor::ActionAssessor, + domain::{ActionIntent, Campaign, WorldCommand}, + kernel::{CommandResult, KernelError, WorldKernel}, + model::{DeepSeekPort, ModelPort}, + narrator::Narrator, + persistence::CampaignStore, + }; + use std::{path::PathBuf, sync::Arc, time::Instant}; + + 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 root = PathBuf::from(r"F:\GameCult\GhostlightDungeon\acceptance") + .join(format!("action-{}", Utc::now().format("%Y%m%d-%H%M%S"))); + std::fs::create_dir_all(&root)?; + let campaign = action_campaign(); + let store = CampaignStore::open(root.join("campaign.cc"))?; + store.create_campaign(&campaign, &[], &[])?; + let model: Arc = Arc::new(DeepSeekPort::from_machine_dpapi(secret)?); + let assessor = ActionAssessor::new(model.clone(), "deepseek-v4-pro"); + let kernel = WorldKernel::start(store.clone()); + let started = Instant::now(); + + let impossible_intent = ActionIntent { + actor_id: "player".into(), + description: "I teleport the entire station into the sun by force of will.".into(), + intended_effect: "destroy the station instantly".into(), + }; + let (impossible, impossible_receipt) = assessor + .assess(&campaign, impossible_intent.clone()) + .await?; + if impossible.admissible || impossible.missing_permission.is_none() { + anyhow::bail!("impossible action was offered a roll") + } + let CommandResult::Assessed { + assessment: admitted_impossible, + } = kernel + .command(WorldCommand::Assess { + expected_revision: 0, + intent: impossible_intent, + proposal: Some(impossible.clone()), + }) + .await? + else { + anyhow::bail!("kernel did not return the impossible assessment") + }; + let impossible_error = kernel + .command(WorldCommand::Attempt { + assessment_digest: admitted_impossible.digest, + }) + .await + .expect_err("impossible attempt must not roll"); + if !matches!(impossible_error, KernelError::Impossible(_)) { + anyhow::bail!("impossible attempt failed for the wrong reason: {impossible_error}") + } + let after_impossible = store + .load::("campaign.v1", &campaign.id.to_string())? + .map(|(_, value)| value) + .ok_or_else(|| anyhow::anyhow!("campaign disappeared"))?; + if after_impossible.revision != 0 { + anyhow::bail!("impossible attempt mutated the campaign") + } + + let feasible_intent = ActionIntent { + actor_id: "player".into(), + description: + "I connect my multimeter to the accessible coolant panel and inspect its readings." + .into(), + intended_effect: + "identify whether the coolant fault is electrical without changing the machinery".into(), + }; + let (feasible, feasible_receipt) = assessor + .assess(&after_impossible, feasible_intent.clone()) + .await?; + if !feasible.admissible { + anyhow::bail!( + "grounded maintenance attempt was rejected: {:?}", + feasible.missing_permission + ) + } + let CommandResult::Assessed { + assessment: admitted_feasible, + } = kernel + .command(WorldCommand::Assess { + expected_revision: 0, + intent: feasible_intent, + proposal: Some(feasible.clone()), + }) + .await? + else { + anyhow::bail!("kernel did not return the feasible assessment") + }; + let attempt = kernel + .command(WorldCommand::Attempt { + assessment_digest: admitted_feasible.digest, + }) + .await?; + let post = store + .load::("campaign.v1", &campaign.id.to_string())? + .map(|(_, value)| value) + .ok_or_else(|| anyhow::anyhow!("campaign disappeared after attempt"))?; + if post.revision != 1 { + anyhow::bail!("confirmed attempt did not commit exactly one revision") + } + + for receipt in [&impossible_receipt, &feasible_receipt] { + store.insert( + "persona_stage_receipt.v1", + "ghostlight.persona_stage_receipt.v1", + receipt.storage_key(), + receipt, + )?; + } + let narrator = Narrator { + model, + model_name: "deepseek-v4-pro".into(), + }; + let (narration, narration_receipt) = narrator.project(&store, &post).await?; + store.insert( + "persona_stage_receipt.v1", + "ghostlight.persona_stage_receipt.v1", + narration_receipt.storage_key(), + &narration_receipt, + )?; + + let result = serde_json::json!({ + "schema":"ghostlight.action_smoke.v1", + "elapsed_seconds":started.elapsed().as_secs_f64(), + "impossible_assessment":impossible, + "impossible_attempt_error":impossible_error.to_string(), + "feasible_assessment":feasible, + "attempt":attempt, + "narration":narration, + "model_stage_receipts":[impossible_receipt, feasible_receipt, narration_receipt], + "campaign_revision":post.revision, + "store":root.join("campaign.cc"), + "result_path":root.join("result.json") + }); + std::fs::write( + root.join("result.json"), + serde_json::to_vec_pretty(&result)?, + )?; + println!("{}", serde_json::to_string_pretty(&result)?); + Ok(()) +} + +#[cfg(windows)] +fn action_campaign() -> ghostlight_dungeon::domain::Campaign { + use chrono::Utc; + use ghostlight_dungeon::domain::{ + ActorState, BranchOrigin, Campaign, InstitutionState, Location, WorldClock, + }; + use std::collections::{BTreeMap, BTreeSet}; + + let id = uuid::Uuid::new_v4(); + let now = Utc::now(); + let player = ActorState { + id: "player".into(), + name: "Dana Voss".into(), + location_id: "maintenance-bay".into(), + capabilities: BTreeSet::from([ + "basic electrical diagnosis".into(), + "safe multimeter use".into(), + ]), + knowledge: BTreeSet::from([ + "the coolant alarm began this shift".into(), + "the accessible panel exposes diagnostic test points".into(), + ]), + equipment: BTreeSet::from(["calibrated multimeter".into()]), + conditions: BTreeSet::from(["tired".into()]), + obligations: BTreeSet::from(["report hazards to the shift foreman".into()]), + relationships: BTreeMap::new(), + goals: vec!["prevent a coolant failure without damaging the system".into()], + memories: vec![], + }; + let foreman = ActorState { + id: "foreman".into(), + name: "Ilyan Kesh".into(), + location_id: "maintenance-bay".into(), + capabilities: BTreeSet::from(["authorize invasive maintenance".into()]), + knowledge: BTreeSet::from(["the work-order backlog".into()]), + equipment: BTreeSet::new(), + conditions: BTreeSet::new(), + obligations: BTreeSet::from(["keep the shift on schedule".into()]), + relationships: BTreeMap::new(), + goals: vec!["avoid an unscheduled shutdown".into()], + memories: vec![], + }; + Campaign { + schema: "ghostlight.campaign.v1".into(), + id, + name: "Action resolution acceptance".into(), + revision: 0, + branch_origin: BranchOrigin { + canon_cutoff: "acceptance-fixture".into(), + evidence_receipt_ids: vec![], + }, + world_time: now, + tick_hours: 6, + player_actor_id: "player".into(), + locations: BTreeMap::from([( + "maintenance-bay".into(), + Location { + id: "maintenance-bay".into(), + name: "Coolant Maintenance Bay".into(), + container_id: None, + routes: BTreeMap::new(), + persistent_features: vec![ + "an accessible coolant diagnostic panel".into(), + "a sealed valve housing requiring foreman authorization".into(), + ], + }, + )]), + actors: BTreeMap::from([("player".into(), player), ("foreman".into(), foreman)]), + institutions: BTreeMap::from([( + "station-operations".into(), + InstitutionState { + id: "station-operations".into(), + name: "Station Operations".into(), + resources: vec!["maintenance authority".into()], + goals: vec!["avoid shutdown".into()], + posture: "dismissive of unscheduled work".into(), + }, + )]), + clocks: BTreeMap::from([( + "coolant-failure".into(), + WorldClock { + id: "coolant-failure".into(), + label: "Coolant failure".into(), + progress: 2, + threshold: 5, + consequence: "the coolant loop trips offline".into(), + }, + )]), + facts: BTreeMap::new(), + transcript: vec![], + last_player_activity: 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![], + agency_profiles: BTreeMap::new(), + agency_relations: BTreeMap::new(), + gestalt_lineages: BTreeMap::new(), + resolution_policy: Default::default(), + resolution_pins: BTreeMap::new(), + resolution_cover: None, + strategic_tick_count: 0, + } +} diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-compiler-smoke.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-compiler-smoke.rs index acbef76..569ac52 100644 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-compiler-smoke.rs +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-compiler-smoke.rs @@ -6,12 +6,13 @@ fn main() -> anyhow::Result<()> { #[cfg(windows)] #[tokio::main] async fn main() -> anyhow::Result<()> { + use chrono::Utc; use ghostlight_dungeon::{ compiler::{CustomStart, WorldCompiler}, model::{DeepSeekPort, ModelPort}, vault::VoidBotMcpVault, }; - use std::{path::PathBuf, sync::Arc}; + use std::{path::PathBuf, sync::Arc, time::Instant}; let secret = std::env::var_os("GHOSTLIGHT_DEEPSEEK_BLOB") .map(PathBuf::from) @@ -23,17 +24,20 @@ async fn main() -> anyhow::Result<()> { "deepseek-v4-flash", "deepseek-v4-pro", ); - let (preview, receipt) = compiler.compile_custom(CustomStart { + let root = PathBuf::from(r"F:\GameCult\GhostlightDungeon\acceptance") + .join(format!("compiler-{}", Utc::now().format("%Y%m%d-%H%M%S"))); + std::fs::create_dir_all(&root)?; + let started = Instant::now(); + let (preview, model_receipts) = 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!({ + let result = serde_json::json!({ "schema":"ghostlight.world_compile_smoke.v1", + "elapsed_seconds":started.elapsed().as_secs_f64(), "title":preview.title, "location_count":preview.campaign.locations.len(), "actor_count":preview.campaign.actors.len(), @@ -45,8 +49,14 @@ async fn main() -> anyhow::Result<()> { "branch_assumptions":preview.branch_assumptions, "requires_approval":preview.requires_approval, "campaign_revision":preview.campaign.revision, - "model_receipt":receipt - }))? - ); + "preview":preview, + "model_receipts":model_receipts, + "result_path":root.join("result.json") + }); + std::fs::write( + root.join("result.json"), + serde_json::to_vec_pretty(&result)?, + )?; + println!("{}", serde_json::to_string_pretty(&result)?); Ok(()) } diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-scale-smoke.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-scale-smoke.rs new file mode 100644 index 0000000..80d064a --- /dev/null +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-scale-smoke.rs @@ -0,0 +1,299 @@ +#[cfg(not(windows))] +fn main() -> anyhow::Result<()> { + anyhow::bail!("the live gestalt scale smoke uses Starfire's DPAPI credential") +} + +#[cfg(windows)] +#[tokio::main] +async fn main() -> anyhow::Result<()> { + use chrono::Utc; + use ghostlight_dungeon::{ + domain::{SimulationCellMode, TickSource, WorldCommand}, + kernel::{CommandResult, WorldKernel}, + model::{DeepSeekPort, ModelPort}, + persistence::CampaignStore, + resolution::validate_and_resolve_wave, + scheduler::propose_resolution_wave, + turn::SnapshotPermit, + }; + use std::{collections::BTreeSet, path::PathBuf, sync::Arc, time::Instant}; + + 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 root = PathBuf::from(r"F:\GameCult\GhostlightDungeon\acceptance").join(format!( + "gestalt-scale-{}", + Utc::now().format("%Y%m%d-%H%M%S") + )); + std::fs::create_dir_all(&root)?; + let campaign = scale_campaign(); + let player_location = campaign.actors[&campaign.player_actor_id] + .location_id + .clone(); + let store = CampaignStore::open(root.join("campaign.cc"))?; + store.create_campaign(&campaign, &[], &[])?; + let model: Arc = Arc::new(DeepSeekPort::from_machine_dpapi(secret)?); + let started = Instant::now(); + let output = propose_resolution_wave( + model, + Arc::new(SnapshotPermit::new_resolution( + store.clone(), + campaign.id, + campaign.revision, + campaign.resolution_policy.resolution_epoch, + )), + &campaign, + ) + .await?; + + let preflight = serde_json::json!({ + "schema":"ghostlight.gestalt_scale_preflight.v1", + "campaign_id":campaign.id, + "elapsed_seconds":started.elapsed().as_secs_f64(), + "cover":&output.wave.cover, + "appraisals":&output.wave.appraisals, + "model_stage_receipts":output.stages.iter().map(|stage|&stage.receipt).collect::>() + }); + std::fs::write( + root.join("preflight.json"), + serde_json::to_vec_pretty(&preflight)?, + )?; + + let cover = &output.wave.cover; + if cover.cells.len() != 4 || cover.effective_budget != 4 { + anyhow::bail!( + "budget-4 cover produced {} cells at effective budget {}", + cover.cells.len(), + cover.effective_budget + ) + } + let covered = cover + .cells + .iter() + .flat_map(|cell| cell.subject_ids.iter().cloned()) + .collect::>(); + if covered.len() != 24 || covered.iter().collect::>().len() != 24 { + anyhow::bail!("scale cover omitted or duplicated canonical subjects") + } + let arena_count = cover + .cells + .iter() + .filter(|cell| cell.mode == SimulationCellMode::Arena) + .count(); + if arena_count == 0 { + anyhow::bail!("cross-faction budget pressure produced no arena cells") + } + let plan = validate_and_resolve_wave(&campaign, &output.wave)?; + if plan.institution_actions.is_empty() { + anyhow::bail!("24-subject strategic wave proposed no material institution action") + } + for stage in &output.stages { + store.insert( + "persona_stage_receipt.v1", + "ghostlight.persona_stage_receipt.v1", + stage.receipt.storage_key(), + &stage.receipt, + )?; + } + let kernel = WorldKernel::start(store.clone()); + let committed = kernel + .command(WorldCommand::AdvanceStrategicTick { + expected_revision: 0, + source: TickSource::Scheduler, + plan: None, + model_receipt_hash: Some(output.aggregate_receipt_hash.clone()), + resolution_wave: Some(output.wave.clone()), + }) + .await?; + let CommandResult::Committed { + campaign: advanced, .. + } = &committed + else { + anyhow::bail!("scale wave did not commit") + }; + if advanced.actors[&advanced.player_actor_id].location_id != player_location { + anyhow::bail!("scale wave puppeted the absent player") + } + let result = serde_json::json!({ + "schema":"ghostlight.gestalt_scale_smoke.v1", + "campaign_id":campaign.id, + "subject_count":24, + "configured_budget":4, + "cell_count":cover.cells.len(), + "arena_count":arena_count, + "elapsed_seconds":started.elapsed().as_secs_f64(), + "cover":cover, + "appraisals":output.wave.appraisals, + "plan":plan, + "model_stage_receipts":output.stages.iter().map(|stage|&stage.receipt).collect::>(), + "commit":committed, + "player_location_unchanged":true, + "news_count":advanced.news.len(), + "store":root.join("campaign.cc"), + "result_path":root.join("result.json") + }); + std::fs::write( + root.join("result.json"), + serde_json::to_vec_pretty(&result)?, + )?; + println!("{}", serde_json::to_string_pretty(&result)?); + Ok(()) +} + +#[cfg(windows)] +fn scale_campaign() -> ghostlight_dungeon::domain::Campaign { + use chrono::{Duration, Utc}; + use ghostlight_dungeon::domain::*; + use std::collections::{BTreeMap, BTreeSet}; + + let now = Utc::now(); + let player = ActorState { + id: "player".into(), + name: "Observer".into(), + location_id: "forum".into(), + capabilities: BTreeSet::new(), + knowledge: BTreeSet::from(["public bulletin".into()]), + equipment: BTreeSet::new(), + conditions: BTreeSet::new(), + obligations: BTreeSet::new(), + relationships: BTreeMap::new(), + goals: vec!["observe the election without being puppeted".into()], + memories: vec![], + }; + let institutions = (0..24) + .map(|index| { + let id = format!("faction-{index:02}"); + ( + id.clone(), + InstitutionState { + id, + name: format!("Faction {index:02}"), + resources: vec![ + format!("private reserve {index:02}"), + format!("regional office {}", index % 4), + "public bulletin publishing access".into(), + ], + goals: vec![ + format!("advance platform {}", index % 6), + "publish a concrete commitment before the final vote".into(), + ], + posture: format!( + "final vote in six hours; campaigning bloc {} must choose whether to commit its reserve", + index % 3 + ), + }, + ) + }) + .collect(); + let mut campaign = Campaign { + schema: "ghostlight.campaign.v1".into(), + id: uuid::Uuid::new_v4(), + name: "Twenty-four faction gestalt acceptance".into(), + revision: 0, + branch_origin: BranchOrigin { + canon_cutoff: "acceptance-fixture".into(), + evidence_receipt_ids: vec![], + }, + world_time: now, + tick_hours: 6, + player_actor_id: "player".into(), + locations: BTreeMap::from([( + "forum".into(), + Location { + id: "forum".into(), + name: "Federation Forum".into(), + container_id: None, + routes: BTreeMap::new(), + persistent_features: vec!["a public election bulletin".into()], + }, + )]), + actors: BTreeMap::from([("player".into(), player)]), + institutions, + clocks: BTreeMap::from([( + "election".into(), + WorldClock { + id: "election".into(), + label: "Federation election".into(), + progress: 5, + threshold: 6, + consequence: "the governing coalition is chosen".into(), + }, + )]), + facts: BTreeMap::new(), + transcript: vec![], + last_player_activity: now - Duration::hours(2), + pending_ticks: 1, + away_ticks_processed: 0, + events: vec![Event { + id: "final-vote-notice".into(), + at: now, + kind: "public_notice".into(), + summary: "The public bulletin announces that the final vote occurs in six hours; each faction has one last chance to publish a binding commitment.".into(), + actor_ids: vec![], + institution_ids: (0..24).map(|index| format!("faction-{index:02}")).collect(), + location_ids: vec!["forum".into()], + public_channels: vec!["public bulletin".into()], + }], + news: vec![], + canon_candidates: BTreeMap::new(), + gestalts: BTreeMap::new(), + gestalt_members: BTreeMap::new(), + pending_world_proposals: vec![], + agency_profiles: BTreeMap::new(), + agency_relations: BTreeMap::new(), + gestalt_lineages: BTreeMap::new(), + resolution_policy: ResolutionPolicy { + active_cell_budget: 4, + provider_parallelism: 4, + ..ResolutionPolicy::default() + }, + resolution_pins: BTreeMap::new(), + resolution_cover: None, + strategic_tick_count: 0, + }; + ghostlight_dungeon::resolution::ensure_agency_profiles(&mut campaign); + for (index, id) in (0..24).map(|index| (index, format!("faction-{index:02}"))) { + let profile = campaign + .agency_profiles + .get_mut(&id) + .expect("institution profile"); + profile.location_ids.insert("forum".into()); + profile + .information_channels + .insert("public bulletin".into()); + profile.facets.insert( + AgencyAxis::Geography, + BTreeSet::from([format!("region-{}", index % 4)]), + ); + profile.facets.insert( + AgencyAxis::Ideology, + BTreeSet::from([format!("platform-{}", index % 6)]), + ); + profile.facets.insert( + AgencyAxis::Information, + BTreeSet::from([format!("private-channel-{index:02}")]), + ); + profile.facets.insert( + AgencyAxis::SpeciesBody, + BTreeSet::from([format!("body-{}", index % 2)]), + ); + if index % 2 == 1 { + let previous = format!("faction-{:02}", index - 1); + let relation_id = format!("rivalry-{previous}-{id}"); + campaign.agency_relations.insert( + relation_id.clone(), + AgencyRelation { + schema: "ghostlight.agency_relation.v1".into(), + id: relation_id, + from_subject_id: previous, + to_subject_id: id, + kind: AgencyRelationKind::Rivalry, + strength: 90, + active: true, + evidence_receipt_ids: vec![], + }, + ); + } + } + campaign +} diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-live-turn-smoke.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-live-turn-smoke.rs index 6d7a0e9..5dd836a 100644 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-live-turn-smoke.rs +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-live-turn-smoke.rs @@ -63,7 +63,7 @@ async fn main() -> anyhow::Result<()> { expected_revision: 0, event_summary: "The player asks all three witnesses what they believe is at stake." .into(), - reactions: wave.reactions, + reactions: wave.reactions.clone(), }) .await?; let total_seconds = started.elapsed().as_secs_f64(); @@ -77,6 +77,8 @@ async fn main() -> anyhow::Result<()> { "total_seconds":total_seconds, "target_seconds":20, "within_target":total_seconds <= 20.0, + "reactions":wave.reactions, + "model_stage_receipts":wave.receipts, "commit":committed, "store":root.join("campaign.cc") }); diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-narrator-smoke.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-narrator-smoke.rs new file mode 100644 index 0000000..46560de --- /dev/null +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-narrator-smoke.rs @@ -0,0 +1,65 @@ +#[cfg(not(windows))] +fn main() -> anyhow::Result<()> { + anyhow::bail!("the live narrator smoke uses Starfire's DPAPI credential") +} + +#[cfg(windows)] +#[tokio::main] +async fn main() -> anyhow::Result<()> { + use chrono::Utc; + use ghostlight_dungeon::{ + domain::Campaign, + model::{DeepSeekPort, ModelPort}, + narrator::Narrator, + persistence::CampaignStore, + }; + use std::{path::PathBuf, sync::Arc, time::Instant}; + + let store_path = std::env::var_os("GHOSTLIGHT_NARRATOR_STORE") + .map(PathBuf::from) + .ok_or_else(|| anyhow::anyhow!("GHOSTLIGHT_NARRATOR_STORE is required"))?; + 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 store = CampaignStore::open(&store_path)?; + let campaign_id = store + .keys("campaign.v1")? + .into_iter() + .next() + .ok_or_else(|| anyhow::anyhow!("narrator smoke store has no campaign"))?; + let campaign = store + .load::("campaign.v1", &campaign_id)? + .map(|(_, value)| value) + .ok_or_else(|| anyhow::anyhow!("campaign disappeared"))?; + let model: Arc = Arc::new(DeepSeekPort::from_machine_dpapi(secret)?); + let narrator = Narrator { + model, + model_name: "deepseek-v4-pro".into(), + }; + let started = Instant::now(); + let (projection, receipt) = narrator.project(&store, &campaign).await?; + store.insert( + "persona_stage_receipt.v1", + "ghostlight.persona_stage_receipt.v1", + receipt.storage_key(), + &receipt, + )?; + let result_path = store_path + .parent() + .unwrap_or_else(|| std::path::Path::new(".")) + .join(format!( + "narrator-repeat-{}.json", + Utc::now().format("%Y%m%d-%H%M%S") + )); + let result = serde_json::json!({ + "schema":"ghostlight.narrator_smoke.v1", + "elapsed_seconds":started.elapsed().as_secs_f64(), + "projection":projection, + "model_stage_receipt":receipt, + "campaign_revision":campaign.revision, + "result_path":result_path + }); + std::fs::write(&result_path, serde_json::to_vec_pretty(&result)?)?; + println!("{}", serde_json::to_string_pretty(&result)?); + Ok(()) +} diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs index 838ed79..dd63d56 100644 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs @@ -87,6 +87,7 @@ async fn main() -> anyhow::Result<()> { "campaign_id":campaign.id, "elapsed_seconds":started.elapsed().as_secs_f64(), "model_receipt_hash":output.aggregate_receipt_hash, + "model_stage_receipts":output.stages.iter().map(|stage|&stage.receipt).collect::>(), "plan":plan, "event_count":advanced.events.len(), "news_count":advanced.news.len(), diff --git a/crates/ghostlight-dungeon/src/compiler.rs b/crates/ghostlight-dungeon/src/compiler.rs index bc81bce..d1754fb 100644 --- a/crates/ghostlight-dungeon/src/compiler.rs +++ b/crates/ghostlight-dungeon/src/compiler.rs @@ -5,7 +5,10 @@ use crate::{ InstitutionState, Location, VaultEvidenceReceipt, WorldClock, WorldCompilePreview, WorldFact, }, - model::{ModelPort, ModelStageReceipt, ModelStageRequest, run_validated_stage}, + model::{ + ModelPort, ModelStageReceipt, ModelStageRequest, run_validated_stage, + run_validated_stage_with_timeout, + }, vault::{VaultProvider, VaultQuery}, }; use anyhow::{Result, anyhow}; @@ -105,6 +108,7 @@ struct CompiledSeed { title: String, canon_cutoff: String, world_time: DateTime, + #[schemars(range(min = 1))] tick_hours: u32, player: ActorState, locations: Vec, @@ -119,12 +123,26 @@ struct CompiledSeed { gaps: Vec, branch_assumptions: Vec, opening_narration: String, - #[serde(default)] +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +struct CompiledAgencySkeleton { agency_profiles: Vec, - #[serde(default)] agency_relations: Vec, } +#[derive(Clone, Debug, Serialize, JsonSchema, PartialEq)] +struct AgencySubjectBrief { + subject_id: String, + subject_kind: AgencySubjectKind, + name: String, + location_ids: BTreeSet, + capabilities_or_resources: Vec, + knowledge_or_posture: Vec, + goals: Vec, + pressures_or_obligations: Vec, +} + #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] struct CompiledAgencyProfile { subject_id: String, @@ -141,6 +159,7 @@ struct CompiledAgencyRelation { from_subject_id: String, to_subject_id: String, kind: AgencyRelationKind, + #[schemars(range(min = 1, max = 100))] strength: u8, } @@ -242,12 +261,15 @@ impl WorldCompiler { 3, ) .await?; - let receipts = self.retrieve_all(&queries, &start.when, 18).await?; - let base_prompt = format!( - "Compile two deliberately different scales. First, compile a bounded playable region with stable topology, local actors, populations, and clocks. Second, compile a global agency skeleton covering every source-supported major power, coarse region, institution, important relation, information channel, and strategic pressure relevant to this era. Major remote powers belong in institutions and agency profiles; do not eagerly invent their settlements, routes, or people. Agency profile facets use exactly geography, ideology, authority, economy_role, species_body, and information. Agency relations use exact supplied subject IDs. 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. Represent populations that can act collectively (villages, crews, crowds, departments, corporations) as gestalt Personas. Seed a small roster of plausible durable member identities for people the player may encounter; member deltas contain only departures from their gestalt baseline and begin dematerialized. Do not duplicate a gestalt member in actors. Keep named plot-critical people as ordinary actors. Every gestalt home location and member gestalt reference must exist. Every non-player actor, institution, and gestalt must have exactly one agency profile; location IDs must already exist. Cross-faction relations never imply shared authority. START:\n{}\nEVIDENCE:\n{}", + let receipts = self.retrieve_all(&queries, &start.when, 8).await?; + let shared_prefix = format!( + "SOURCE-GROUNDED WORLD COMPILATION\nSTART:\n{}\nEVIDENCE:\n{}\n\n", serde_json::to_string(&start)?, evidence_text(&receipts) ); + let base_prompt = format!( + "{shared_prefix}Compile a bounded playable region with stable topology, local actors, populations, clocks, and enough remote institutions to represent every source-supported major power relevant to this era. Do not eagerly invent remote settlements, routes, or people. Emit only supported canon facts; mark reversible texture provisional_local and list material gaps. A canon_baseline fact must cite one or more exact receipt_id values printed in EVIDENCE whose witnesses directly support the whole statement. Never label an invented proper noun canon. 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. Represent populations that can act collectively (villages, crews, crowds, departments, corporations) as gestalt Personas. Seed a small roster of plausible durable member identities for people the player may encounter; member deltas contain only departures from their gestalt baseline and begin dematerialized. Do not duplicate a gestalt member in actors. Keep named plot-critical people as ordinary actors. Every gestalt home location and member gestalt reference must exist. Do not emit agency profiles or relations; those are compiled from the exact validated subject roster in the next stage." + ); let schema = serde_json::to_value(schema_for!(CompiledSeed))?; let sources = receipt_ids(&receipts); let mut compiler_receipts = Vec::new(); @@ -269,6 +291,12 @@ impl WorldCompiler { { Ok(campaign) => break (seed, campaign), Err(error) if compiler_receipts.len() == 1 => { + mark_semantic_invalid( + compiler_receipts + .last_mut() + .expect("receipt was just stored"), + &error, + ); correction = format!( "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS CANDIDATE: {error}\nReturn a corrected complete candidate against the same START and EVIDENCE." ); @@ -280,6 +308,56 @@ impl WorldCompiler { } } }; + let subject_briefs = agency_subject_briefs(&campaign); + let agency_prompt = format!( + "{shared_prefix}Compile the multiresolution global agency skeleton for this exact, already validated subject roster:\n{}\n\nReturn exactly one agency profile for every supplied subject and no other subject. Copy every subject_id, subject_kind, and location_ids exactly. Every profile must contain exactly the six facet axes geography, ideology, authority, economy_role, species_body, and information. Use an explicit unknown value when evidence cannot support a sharper claim. collective_authority_id must be null or one supplied subject ID; it denotes real shared authority, never mere alliance or proximity. Relations may use only supplied subject IDs and strength must be an integer from 1 through 100. Cross-faction relations never imply shared speech, knowledge, or authority. Preserve source-supported geographic, ideological, institutional, economic, biological, and information boundaries that predict different behavior under pressure.", + serde_json::to_string(&subject_briefs)? + ); + let agency_schema = serde_json::to_value(schema_for!(CompiledAgencySkeleton))?; + let mut agency_correction = String::new(); + let mut campaign = campaign; + loop { + let output = self + .structured( + "agency_compile", + "custom-start", + &format!("{agency_prompt}{agency_correction}"), + agency_schema.clone(), + sources.clone(), + ) + .await?; + compiler_receipts.push(output.1); + let skeleton: CompiledAgencySkeleton = serde_json::from_value(output.0)?; + let mut candidate = campaign.clone(); + match apply_compiled_agency_skeleton( + &mut candidate, + skeleton.agency_profiles, + skeleton.agency_relations, + ) + .and_then(|_| validate_campaign_seed(&candidate)) + { + Ok(()) => { + campaign = candidate; + break; + } + Err(error) if agency_correction.is_empty() => { + mark_semantic_invalid( + compiler_receipts + .last_mut() + .expect("receipt was just stored"), + &error, + ); + agency_correction = format!( + "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS AGENCY SKELETON: {error}\nReturn one corrected complete agency skeleton for the same exact roster." + ); + } + Err(error) => { + return Err(anyhow!( + "agency compiler failed local validation after one correction: {error}" + )); + } + } + } let mut model_receipts = vec![retrieval_receipt]; model_receipts.extend(compiler_receipts); Ok(( @@ -455,6 +533,10 @@ impl WorldCompiler { }) { Ok(()) => return Ok((preview, receipts, stages)), Err(error) if attempt == 0 => { + mark_semantic_invalid( + stages.last_mut().expect("receipt was just stored"), + &error, + ); correction = format!( "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS FISSION: {error}\nReturn one corrected complete preview against the same subject and evidence." ); @@ -529,6 +611,12 @@ impl WorldCompiler { match validate_region_expansion(campaign, &expansion) { Ok(()) => break (seed, expansion), Err(error) if compiler_receipts.len() == 1 => { + mark_semantic_invalid( + compiler_receipts + .last_mut() + .expect("receipt was just stored"), + &error, + ); correction = format!( "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS CANDIDATE: {error}\nReturn a corrected complete candidate against the same CAMPAIGN, REQUEST, and EVIDENCE." ); @@ -656,8 +744,8 @@ impl WorldCompiler { ) -> Result<(Vec, ModelStageReceipt)> { let schema = serde_json::to_value(schema_for!(RetrievalQueryPlan))?; let prompt = format!( - "Plan exactly {count} distinct source-search queries for the supplied subject. Each query must be a concise natural-language search string of 1 to 240 Unicode characters. Preserve proper nouns, era, place, institutions, mechanics, geography, and pressure when relevant. Do not answer the subject. SUBJECT:\n{subject}\n\nOUTPUT JSON SCHEMA (follow exactly):\n{}", - serde_json::to_string_pretty(&schema)? + "OUTPUT JSON SCHEMA (follow exactly):\n{}\n\nPlan exactly {count} distinct source-search queries for the supplied subject. Each query must be a concise natural-language search string of 1 to 240 Unicode characters. Preserve proper nouns, era, place, institutions, mechanics, geography, and pressure when relevant. Do not answer the subject. SUBJECT:\n{subject}", + serde_json::to_string(&schema)? ); let output = run_validated_stage( self.model.as_ref(), @@ -668,6 +756,8 @@ impl WorldCompiler { lived_stream: prompt, output_schema: Some(schema), source_receipt_ids: vec![], + temperature: Some(0.0), + max_output_tokens: Some(512), }, ) .await?; @@ -707,21 +797,37 @@ impl WorldCompiler { sources: Vec, ) -> Result<(serde_json::Value, ModelStageReceipt)> { let prompt = format!( - "{prompt}\n\nOUTPUT JSON SCHEMA (follow exactly):\n{}", - serde_json::to_string_pretty(&schema)? + "OUTPUT JSON SCHEMA (follow exactly):\n{}\n\nTASK CONTEXT:\n{prompt}", + serde_json::to_string(&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?; + let request = ModelStageRequest { + stage: stage.into(), + model: self.compiler_model.clone(), + snapshot_binding: binding.into(), + lived_stream: prompt, + output_schema: Some(schema), + source_receipt_ids: sources, + temperature: Some(0.0), + max_output_tokens: Some(match stage { + "world_compile" => 6_000, + "agency_compile" => 3_500, + "world_openings" => 1_800, + "world_roles" => 1_200, + "destination_compile" => 3_000, + "gestalt_fission" => 2_500, + _ => 2_500, + }), + }; + let out = if stage == "world_compile" { + run_validated_stage_with_timeout( + self.model.as_ref(), + &request, + std::time::Duration::from_secs(120), + ) + .await? + } else { + run_validated_stage(self.model.as_ref(), &request).await? + }; Ok(( out.structured .ok_or_else(|| anyhow!("compiler returned no structured output"))?, @@ -736,6 +842,11 @@ fn normalized_contains(document: &str, excerpt: &str) -> bool { !excerpt.is_empty() && document.contains(&excerpt) } +fn mark_semantic_invalid(receipt: &mut ModelStageReceipt, error: &impl std::fmt::Display) { + receipt.validation_result = "semantic_invalid".into(); + receipt.local_validation_error = Some(error.to_string().chars().take(1_000).collect()); +} + pub fn validate_region_expansion( campaign: &Campaign, expansion: &crate::domain::RegionExpansion, @@ -777,13 +888,30 @@ pub fn validate_region_expansion( } fn evidence_text(receipts: &[VaultEvidenceReceipt]) -> String { + let mut seen = BTreeSet::new(); receipts .iter() - .flat_map(|r| r.witnesses.iter()) - .map(|w| { + .flat_map(|receipt| { + receipt + .witnesses + .iter() + .map(move |witness| (receipt.id.as_str(), witness)) + }) + .filter(|(_, witness)| { + seen.insert(( + witness.source_id.clone(), + witness.exact_locator.clone(), + witness.content_hash.clone(), + )) + }) + .map(|(receipt_id, witness)| { format!( - "[{} | {} | {}] {}", - w.source_id, w.exact_locator, w.content_hash, w.excerpt + "[receipt_id={} | source={} | locator={} | content_hash={}] {}", + receipt_id, + witness.source_id, + witness.exact_locator, + witness.content_hash, + witness.excerpt ) }) .collect::>() @@ -812,9 +940,36 @@ fn ensure_distinct_openings(items: &[OpeningSuggestion]) -> Result<()> { } fn seed_to_campaign(seed: CompiledSeed, receipts: &[VaultEvidenceReceipt]) -> Result { + require_unique_ids( + "location", + seed.locations.iter().map(|item| item.id.as_str()), + )?; + require_unique_ids("actor", seed.actors.iter().map(|item| item.id.as_str()))?; + require_unique_ids( + "institution", + seed.institutions.iter().map(|item| item.id.as_str()), + )?; + require_unique_ids("clock", seed.clocks.iter().map(|item| item.id.as_str()))?; + require_unique_ids("fact", seed.facts.iter().map(|item| item.id.as_str()))?; + require_unique_ids("gestalt", seed.gestalts.iter().map(|item| item.id.as_str()))?; + require_unique_ids( + "gestalt member", + seed.gestalt_members.iter().map(|item| item.id.as_str()), + )?; + require_unique_ids( + "canonical subject", + std::iter::once(seed.player.id.as_str()) + .chain(seed.actors.iter().map(|item| item.id.as_str())) + .chain(seed.institutions.iter().map(|item| item.id.as_str())) + .chain(seed.gestalts.iter().map(|item| item.id.as_str())), + )?; + require_unique_ids( + "actor or gestalt member", + std::iter::once(seed.player.id.as_str()) + .chain(seed.actors.iter().map(|item| item.id.as_str())) + .chain(seed.gestalt_members.iter().map(|item| item.id.as_str())), + )?; let id = Uuid::new_v4(); - let compiled_agency_profiles = seed.agency_profiles.clone(); - let compiled_agency_relations = seed.agency_relations.clone(); 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(); @@ -822,6 +977,10 @@ fn seed_to_campaign(seed: CompiledSeed, receipts: &[VaultEvidenceReceipt]) -> Re return Err(anyhow!("player id duplicates an NPC")); } let evidence_receipt_ids = receipt_ids(receipts); + let valid_evidence_receipt_ids = evidence_receipt_ids + .iter() + .cloned() + .collect::>(); let affected_sources: Vec = receipts .iter() .flat_map(|r| r.witnesses.iter().map(|w| w.source_id.clone())) @@ -875,8 +1034,14 @@ fn seed_to_campaign(seed: CompiledSeed, receipts: &[VaultEvidenceReceipt]) -> Re .facts .into_iter() .map(|mut x| { - if x.scope == FactScope::CanonBaseline && x.evidence_receipt_ids.is_empty() { - x.scope = FactScope::ProvisionalLocal + let supplied_reference_count = x.evidence_receipt_ids.len(); + x.evidence_receipt_ids + .retain(|id| valid_evidence_receipt_ids.contains(id)); + if x.scope == FactScope::CanonBaseline + && (supplied_reference_count == 0 + || x.evidence_receipt_ids.len() != supplied_reference_count) + { + x.scope = FactScope::ProvisionalLocal; }; (x.id.clone(), x) }) @@ -913,14 +1078,87 @@ fn seed_to_campaign(seed: CompiledSeed, receipts: &[VaultEvidenceReceipt]) -> Re strategic_tick_count: 0, }; crate::resolution::ensure_agency_profiles(&mut campaign); - apply_compiled_agency_skeleton( - &mut campaign, - compiled_agency_profiles, - compiled_agency_relations, - )?; Ok(campaign) } +fn require_unique_ids<'a>(label: &str, ids: impl IntoIterator) -> Result<()> { + let mut seen = BTreeSet::new(); + let mut duplicates = BTreeSet::new(); + for id in ids { + if id.trim().is_empty() || !seen.insert(id.to_owned()) { + duplicates.insert(id.to_owned()); + } + } + if duplicates.is_empty() { + Ok(()) + } else { + Err(anyhow!( + "{label} IDs must be non-empty and unique; rejected IDs={duplicates:?}" + )) + } +} + +fn agency_subject_briefs(campaign: &Campaign) -> Vec { + let mut briefs = Vec::new(); + for actor in campaign + .actors + .values() + .filter(|actor| actor.id != campaign.player_actor_id) + { + briefs.push(AgencySubjectBrief { + subject_id: actor.id.clone(), + subject_kind: AgencySubjectKind::Actor, + name: actor.name.clone(), + location_ids: BTreeSet::from([actor.location_id.clone()]), + capabilities_or_resources: actor + .capabilities + .iter() + .chain(actor.equipment.iter()) + .cloned() + .collect(), + knowledge_or_posture: actor.knowledge.iter().cloned().collect(), + goals: actor.goals.clone(), + pressures_or_obligations: actor + .obligations + .iter() + .chain(actor.conditions.iter()) + .cloned() + .collect(), + }); + } + for institution in campaign.institutions.values() { + briefs.push(AgencySubjectBrief { + subject_id: institution.id.clone(), + subject_kind: AgencySubjectKind::Institution, + name: institution.name.clone(), + location_ids: BTreeSet::new(), + capabilities_or_resources: institution.resources.clone(), + knowledge_or_posture: vec![institution.posture.clone()], + goals: institution.goals.clone(), + pressures_or_obligations: Vec::new(), + }); + } + for gestalt in campaign.gestalts.values() { + briefs.push(AgencySubjectBrief { + subject_id: gestalt.id.clone(), + subject_kind: AgencySubjectKind::Gestalt, + name: gestalt.name.clone(), + location_ids: BTreeSet::from([gestalt.home_location_id.clone()]), + capabilities_or_resources: gestalt + .shared_capabilities + .iter() + .chain(gestalt.resources.iter()) + .cloned() + .collect(), + knowledge_or_posture: gestalt.shared_knowledge.iter().cloned().collect(), + goals: gestalt.goals.clone(), + pressures_or_obligations: gestalt.pressures.clone(), + }); + } + briefs.sort_by(|left, right| left.subject_id.cmp(&right.subject_id)); + briefs +} + fn apply_compiled_agency_skeleton( campaign: &mut Campaign, profiles: Vec, @@ -948,8 +1186,12 @@ fn apply_compiled_agency_skeleton( AgencyAxis::Information, ]); if supplied != expected || supplied.len() != profiles.len() { + let missing = expected.difference(&supplied).cloned().collect::>(); + let unexpected = supplied.difference(&expected).cloned().collect::>(); + let duplicate_count = profiles.len().saturating_sub(supplied.len()); return Err(anyhow!( - "global agency skeleton must profile every non-player actor, institution, and gestalt exactly once" + "global agency skeleton coverage mismatch: missing={missing:?}; unexpected={unexpected:?}; duplicate_profile_count={duplicate_count}; expected_subject_ids={:?}", + expected )); } for input in profiles { @@ -962,15 +1204,29 @@ fn apply_compiled_agency_skeleton( .get_mut(&input.subject_id) .ok_or_else(|| anyhow!("agency profile references an unknown subject"))?; let input_axes: BTreeSet<_> = input.facets.keys().cloned().collect(); + let unknown_locations = input + .location_ids + .iter() + .filter(|id| !campaign.locations.contains_key(*id)) + .cloned() + .collect::>(); if profile.subject_kind != input.subject_kind || input_axes != axes - || input - .location_ids - .iter() - .any(|id| !campaign.locations.contains_key(id)) + || input.location_ids != profile.location_ids + || !unknown_locations.is_empty() || !authority_known { - return Err(anyhow!("compiled agency profile is malformed")); + let missing_axes = axes.difference(&input_axes).cloned().collect::>(); + let unexpected_axes = input_axes.difference(&axes).cloned().collect::>(); + return Err(anyhow!( + "agency profile {} malformed: expected_kind={:?}; supplied_kind={:?}; expected_location_ids={:?}; supplied_location_ids={:?}; missing_axes={missing_axes:?}; unexpected_axes={unexpected_axes:?}; unknown_locations={unknown_locations:?}; unknown_collective_authority={:?}", + input.subject_id, + profile.subject_kind, + input.subject_kind, + profile.location_ids, + input.location_ids, + input.collective_authority_id.filter(|_| !authority_known) + )); } profile.collective_authority_id = input.collective_authority_id; profile.facets = input.facets; @@ -980,15 +1236,21 @@ fn apply_compiled_agency_skeleton( } let mut relation_ids = BTreeSet::new(); for input in relations { - if !relation_ids.insert(input.id.clone()) - || input.id.trim().is_empty() - || input.from_subject_id == input.to_subject_id - || !expected.contains(&input.from_subject_id) - || !expected.contains(&input.to_subject_id) - || input.strength == 0 - || input.strength > 100 - { - return Err(anyhow!("compiled agency relation is malformed")); + let duplicate_id = !relation_ids.insert(input.id.clone()); + let empty_id = input.id.trim().is_empty(); + let self_edge = input.from_subject_id == input.to_subject_id; + let unknown_from = !expected.contains(&input.from_subject_id); + let unknown_to = !expected.contains(&input.to_subject_id); + let invalid_strength = input.strength == 0 || input.strength > 100; + if duplicate_id || empty_id || self_edge || unknown_from || unknown_to || invalid_strength { + return Err(anyhow!( + "agency relation {:?} malformed: duplicate_id={duplicate_id}; empty_id={empty_id}; self_edge={self_edge}; unknown_from_subject={unknown_from} ({:?}); unknown_to_subject={unknown_to} ({:?}); invalid_strength={invalid_strength} ({}) ; supplied_subject_ids={:?}", + input.id, + input.from_subject_id, + input.to_subject_id, + input.strength, + expected + )); } campaign.agency_relations.insert( input.id.clone(), @@ -1072,11 +1334,29 @@ pub fn validate_campaign_seed(c: &Campaign) -> Result<()> { if let Some(parent) = &location.container_id && (parent == &location.id || !c.locations.contains_key(parent)) { - return Err(anyhow!("location {} has invalid container", location.id)); + return Err(anyhow!( + "location {} has invalid container_id {:?}; it must name a different supplied location or be null", + location.id, + location.container_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 (route_id, route) in &location.routes { + if route.travel_minutes == 0 { + return Err(anyhow!( + "location {} route {} to {} has zero travel_minutes", + location.id, + route_id, + route.destination_id + )); + } + if !c.locations.contains_key(&route.destination_id) { + return Err(anyhow!( + "location {} route {} references missing destination_id {}; supplied location IDs={:?}", + location.id, + route_id, + route.destination_id, + c.locations.keys().collect::>() + )); } } } @@ -1139,11 +1419,13 @@ mod tests { "gestalt_members":[{"schema":"ghostlight.gestalt_member_delta.v1","id":"john","gestalt_id":"yard-workers","version":0,"name":"John the smith","capability_additions":["forge hinges"],"capability_removals":[],"knowledge_additions":[],"knowledge_removals":[],"equipment":["hammer"],"conditions":[],"obligations":[],"relationships":{},"goals":[],"memories":[],"last_location_id":"yard","materialized_actor_id":null}], "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":["Who owns the outer gate?"],"branch_assumptions":[],"opening_narration":"The yard persists.", - "agency_profiles":[{"subject_id":"yard-workers","subject_kind":"gestalt","collective_authority_id":"yard-workers","facets":{"geography":["yard"],"ideology":["mutual aid"],"authority":["yard-workers"],"economy_role":["maintenance"],"species_body":["human"],"information":["yard routines"]},"location_ids":["yard"],"information_channels":["yard routines"]}], - "agency_relations":[] + "gaps":["Who owns the outer gate?"],"branch_assumptions":[],"opening_narration":"The yard persists." }).to_string() } + "agency_compile" => serde_json::json!({ + "agency_profiles":[{"subject_id":"yard-workers","subject_kind":"gestalt","collective_authority_id":"yard-workers","facets":{"geography":["yard"],"ideology":["mutual aid"],"authority":["yard-workers"],"economy_role":["maintenance"],"species_body":["human"],"information":["yard routines"]},"location_ids":["yard"],"information_channels":["yard routines"]}], + "agency_relations":[] + }).to_string(), _ => return Err(anyhow!("unexpected stage")), }) } @@ -1268,7 +1550,7 @@ mod tests { "flash", "pro", ); - let (preview, _) = compiler + let (preview, receipts) = compiler .compile_custom(CustomStart { campaign_name: "Test".into(), who: "worker".into(), @@ -1278,12 +1560,24 @@ mod tests { }) .await .unwrap(); + assert_eq!( + receipts + .iter() + .map(|receipt| receipt.stage.as_str()) + .collect::>(), + vec!["custom_retrieval_plan", "world_compile", "agency_compile"] + ); assert!(preview.requires_approval); assert_eq!(preview.campaign.revision, 0); assert_eq!(preview.campaign.locations.len(), 1); assert_eq!(preview.campaign.canon_candidates.len(), 1); assert_eq!(preview.campaign.gestalts.len(), 1); assert_eq!(preview.campaign.agency_profiles.len(), 2); + assert_eq!( + preview.campaign.facts["f"].scope, + FactScope::ProvisionalLocal + ); + assert!(preview.campaign.facts["f"].evidence_receipt_ids.is_empty()); assert_eq!( preview.campaign.agency_profiles["yard-workers"].facets[&AgencyAxis::Ideology], BTreeSet::from(["mutual aid".into()]) @@ -1299,6 +1593,47 @@ mod tests { ); } + #[test] + fn evidence_projection_carries_exact_receipt_ids_and_deduplicates_witnesses() { + let witness = 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(), + }; + let text = evidence_text(&[ + VaultEvidenceReceipt { + schema: "ghostlight.vault_evidence_receipt.v1".into(), + id: "vault:receipt-one".into(), + provider: "fixture".into(), + query_hash: "sha256:one".into(), + witnesses: vec![witness.clone()], + retrieved_at: Utc::now(), + }, + VaultEvidenceReceipt { + schema: "ghostlight.vault_evidence_receipt.v1".into(), + id: "vault:receipt-two".into(), + provider: "fixture".into(), + query_hash: "sha256:two".into(), + witnesses: vec![witness], + retrieved_at: Utc::now(), + }, + ]); + assert_eq!(text.matches("A stable witnessed place.").count(), 1); + assert!(text.contains("receipt_id=vault:receipt-one")); + assert!(!text.contains("receipt_id=vault:receipt-two")); + } + + #[test] + fn agency_compile_schema_exposes_relation_strength_domain() { + let schema = serde_json::to_value(schema_for!(CompiledAgencySkeleton)).unwrap(); + let serialized = serde_json::to_string(&schema).unwrap(); + assert!(serialized.contains("\"minimum\":1")); + assert!(serialized.contains("\"maximum\":100")); + } + #[tokio::test] async fn compiler_refuses_dream_route_to_unknown_location() { let compiler = WorldCompiler::new( @@ -1318,6 +1653,11 @@ mod tests { goal: "learn".into(), }) .await; - assert!(result.unwrap_err().to_string().contains("invalid route")); + assert!( + result + .unwrap_err() + .to_string() + .contains("references missing destination_id missing") + ); } } diff --git a/crates/ghostlight-dungeon/src/domain.rs b/crates/ghostlight-dungeon/src/domain.rs index c246ecf..59c23b6 100644 --- a/crates/ghostlight-dungeon/src/domain.rs +++ b/crates/ghostlight-dungeon/src/domain.rs @@ -80,6 +80,7 @@ pub struct Location { pub struct Route { pub destination_id: String, pub distance: String, + #[schemars(range(min = 1))] pub travel_minutes: u32, } @@ -268,6 +269,7 @@ pub struct AgencyRelation { pub from_subject_id: String, pub to_subject_id: String, pub kind: AgencyRelationKind, + #[schemars(range(min = 1, max = 100))] pub strength: u8, pub active: bool, pub evidence_receipt_ids: Vec, @@ -525,6 +527,7 @@ pub struct WorldClock { pub id: String, pub label: String, pub progress: u8, + #[schemars(range(min = 1))] pub threshold: u8, pub consequence: String, } diff --git a/crates/ghostlight-dungeon/src/gestalt.rs b/crates/ghostlight-dungeon/src/gestalt.rs index df8c180..a823877 100644 --- a/crates/ghostlight-dungeon/src/gestalt.rs +++ b/crates/ghostlight-dungeon/src/gestalt.rs @@ -39,6 +39,8 @@ impl GestaltPresencePlanner { ), output_schema: Some(schema), source_receipt_ids: campaign.branch_origin.evidence_receipt_ids.clone(), + temperature: Some(0.0), + max_output_tokens: Some(1_500), }, ) .await?; diff --git a/crates/ghostlight-dungeon/src/kernel.rs b/crates/ghostlight-dungeon/src/kernel.rs index 8fca19a..f127aa3 100644 --- a/crates/ghostlight-dungeon/src/kernel.rs +++ b/crates/ghostlight-dungeon/src/kernel.rs @@ -2615,6 +2615,10 @@ mod tests { source_receipt_ids: vec![], latency_ms: 1, validation_result: "valid".into(), + local_validation_error: None, + input_chars: 7, + output_chars: 7, + provider_attempts: vec![], } } diff --git a/crates/ghostlight-dungeon/src/main.rs b/crates/ghostlight-dungeon/src/main.rs index 462ecde..8f3ab15 100644 --- a/crates/ghostlight-dungeon/src/main.rs +++ b/crates/ghostlight-dungeon/src/main.rs @@ -183,6 +183,8 @@ async fn main() -> anyhow::Result<()> { lived_stream: "Reply with the single word ready.".into(), output_schema: None, source_receipt_ids: vec![], + temperature: Some(0.0), + max_output_tokens: Some(16), }, ) .await?; diff --git a/crates/ghostlight-dungeon/src/model.rs b/crates/ghostlight-dungeon/src/model.rs index bdfa1fa..4ad4d73 100644 --- a/crates/ghostlight-dungeon/src/model.rs +++ b/crates/ghostlight-dungeon/src/model.rs @@ -14,6 +14,8 @@ pub struct ModelStageRequest { pub lived_stream: String, pub output_schema: Option, pub source_receipt_ids: Vec, + pub temperature: Option, + pub max_output_tokens: Option, } #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] @@ -30,6 +32,37 @@ pub struct ModelStageReceipt { pub source_receipt_ids: Vec, pub latency_ms: u64, pub validation_result: String, + #[serde(default)] + pub local_validation_error: Option, + #[serde(default)] + pub input_chars: usize, + #[serde(default)] + pub output_chars: usize, + #[serde(default)] + pub provider_attempts: Vec, +} + +#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct ModelTokenUsage { + pub prompt_tokens: u64, + pub completion_tokens: u64, + pub total_tokens: u64, + pub prompt_cache_hit_tokens: u64, + pub prompt_cache_miss_tokens: u64, + pub reasoning_tokens: u64, +} + +#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct ModelProviderAttemptReceipt { + pub provider_request_id: Option, + pub system_fingerprint: Option, + pub finish_reason: Option, + pub latency_ms: u64, + pub token_usage: Option, + #[serde(default)] + pub local_validation_result: String, + #[serde(default)] + pub local_validation_error: Option, } impl ModelStageReceipt { @@ -49,9 +82,24 @@ pub struct ModelStageOutput { pub receipt: ModelStageReceipt, } +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ModelProviderOutput { + pub content: String, + pub provider_request_id: Option, + pub system_fingerprint: Option, + pub finish_reason: Option, + pub token_usage: Option, +} + #[async_trait] pub trait ModelPort: Send + Sync { async fn run(&self, request: &ModelStageRequest) -> Result; + async fn run_observed(&self, request: &ModelStageRequest) -> Result { + Ok(ModelProviderOutput { + content: self.run(request).await?, + ..Default::default() + }) + } fn provider(&self) -> &'static str; } @@ -74,12 +122,45 @@ pub async fn run_validated_stage_with_timeout( .transpose() .map_err(|error| anyhow!("invalid local output schema: {error}"))?; let mut attempt_request = request.clone(); + let stage_started = Instant::now(); + let mut provider_attempts = Vec::new(); for attempt in 0..2 { let started = Instant::now(); - let output = tokio::time::timeout(timeout, port.run(&attempt_request)) + let provider_output = tokio::time::timeout(timeout, port.run_observed(&attempt_request)) .await - .map_err(|_| anyhow!("model stage {} timed out", request.stage))??; + .map_err(|_| { + anyhow!( + "model stage {} timed out after {} seconds with {} input characters", + request.stage, + timeout.as_secs(), + attempt_request.lived_stream.chars().count() + ) + })??; + let ModelProviderOutput { + content: output, + provider_request_id, + system_fingerprint, + finish_reason, + token_usage, + } = provider_output; + provider_attempts.push(ModelProviderAttemptReceipt { + provider_request_id, + system_fingerprint, + finish_reason, + latency_ms: started.elapsed().as_millis() as u64, + token_usage, + local_validation_result: "pending".into(), + local_validation_error: None, + }); if output.trim().is_empty() { + provider_attempts + .last_mut() + .expect("attempt was just recorded") + .local_validation_result = "empty".into(); + provider_attempts + .last_mut() + .expect("attempt was just recorded") + .local_validation_error = Some("provider returned an empty response".into()); if attempt == 0 { attempt_request.lived_stream.push_str( "\n\nLOCAL VALIDATOR: The previous response was empty. Return one complete response against the same snapshot and output contract.", @@ -93,6 +174,14 @@ pub async fn run_validated_stage_with_timeout( Ok(value) => { let validation = validator.as_ref().expect("structured validator"); if let Err(error) = validation.validate(&value) { + provider_attempts + .last_mut() + .expect("attempt was just recorded") + .local_validation_result = "schema_invalid".into(); + provider_attempts + .last_mut() + .expect("attempt was just recorded") + .local_validation_error = Some(bounded_validation_error(&error)); if attempt == 0 { attempt_request.lived_stream.push_str(&format!( "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS JSON: {error}\nReturn one corrected complete JSON object against the same snapshot and schema." @@ -104,15 +193,37 @@ pub async fn run_validated_stage_with_timeout( Some(value) } Err(error) if attempt == 0 => { + provider_attempts + .last_mut() + .expect("attempt was just recorded") + .local_validation_result = "malformed_json".into(); + provider_attempts + .last_mut() + .expect("attempt was just recorded") + .local_validation_error = Some(bounded_validation_error(&error)); attempt_request.lived_stream.push_str(&format!( "\n\nLOCAL VALIDATOR COULD NOT PARSE THE PREVIOUS RESPONSE AS JSON: {error}\nReturn one corrected complete JSON object against the same snapshot and schema." )); continue; } - Err(error) => return Err(anyhow!("model returned malformed JSON twice: {error}")), + Err(error) => { + provider_attempts + .last_mut() + .expect("attempt was just recorded") + .local_validation_result = "malformed_json".into(); + provider_attempts + .last_mut() + .expect("attempt was just recorded") + .local_validation_error = Some(bounded_validation_error(&error)); + return Err(anyhow!("model returned malformed JSON twice: {error}")); + } }, None => None, }; + provider_attempts + .last_mut() + .expect("attempt was just recorded") + .local_validation_result = "valid".into(); let request_bytes = serde_json::to_vec(&attempt_request)?; let provider = port.provider().to_owned(); let request_hash = format!("sha256:{:x}", Sha256::digest(&request_bytes)); @@ -145,14 +256,22 @@ pub async fn run_validated_stage_with_timeout( request_hash, output_hash, source_receipt_ids: request.source_receipt_ids.clone(), - latency_ms: started.elapsed().as_millis() as u64, + latency_ms: stage_started.elapsed().as_millis() as u64, validation_result: "valid".into(), + local_validation_error: None, + input_chars: attempt_request.lived_stream.chars().count(), + output_chars: output.chars().count(), + provider_attempts, }, }); } unreachable!() } +fn bounded_validation_error(error: &impl std::fmt::Display) -> String { + error.to_string().chars().take(1_000).collect() +} + #[cfg(test)] mod tests { use super::*; @@ -227,10 +346,13 @@ mod tests { "properties":{"answer":{"type":"string"}} })), source_receipt_ids: vec![], + temperature: None, + max_output_tokens: None, }; let output = run_validated_stage(&port, &request).await.unwrap(); assert_eq!(port.calls.load(Ordering::SeqCst), 2); assert_eq!(output.structured.unwrap()["answer"], "ready"); + assert_eq!(output.receipt.provider_attempts.len(), 2); assert_eq!(output.receipt.snapshot_binding, request.snapshot_binding); } @@ -251,6 +373,8 @@ mod tests { "properties":{"answer":{"type":"string"}} })), source_receipt_ids: vec![], + temperature: None, + max_output_tokens: None, }; let output = run_validated_stage(&port, &request).await.unwrap(); assert_eq!(port.calls.load(Ordering::SeqCst), 2); @@ -267,6 +391,8 @@ mod tests { lived_stream: "fixture".into(), output_schema: None, source_receipt_ids: vec![], + temperature: None, + max_output_tokens: None, }; let error = run_validated_stage_with_timeout( &NeverReturns, @@ -277,6 +403,72 @@ mod tests { .unwrap_err(); assert!(error.to_string().contains("timed out")); } + + #[test] + fn deepseek_response_preserves_usage_metadata_without_reasoning_content() { + let output = decode_deepseek_response(&serde_json::json!({ + "id":"request-7", + "system_fingerprint":"fp-live", + "choices":[{ + "finish_reason":"stop", + "message":{ + "content":"ready", + "reasoning_content":"must never enter the receipt" + } + }], + "usage":{ + "prompt_tokens":120, + "completion_tokens":30, + "total_tokens":150, + "prompt_cache_hit_tokens":80, + "prompt_cache_miss_tokens":40, + "completion_tokens_details":{"reasoning_tokens":0} + } + })) + .unwrap(); + assert_eq!(output.content, "ready"); + assert_eq!(output.provider_request_id.as_deref(), Some("request-7")); + assert_eq!(output.finish_reason.as_deref(), Some("stop")); + assert_eq!(output.token_usage.as_ref().unwrap().total_tokens, 150); + let receipt_shape = serde_json::to_value(ModelProviderAttemptReceipt { + provider_request_id: output.provider_request_id, + system_fingerprint: output.system_fingerprint, + finish_reason: output.finish_reason, + latency_ms: 1, + token_usage: output.token_usage, + local_validation_result: "valid".into(), + local_validation_error: None, + }) + .unwrap(); + assert!( + !serde_json::to_string(&receipt_shape) + .unwrap() + .contains("reasoning_content") + ); + } + + #[test] + fn deepseek_structured_requests_are_deterministic_but_narrative_requests_are_not_forced() { + let mut request = ModelStageRequest { + stage: "interpreter".into(), + model: "deepseek-v4-flash".into(), + snapshot_binding: "campaign:one:revision:4".into(), + lived_stream: "fixture".into(), + output_schema: Some(serde_json::json!({"type":"object"})), + source_receipt_ids: vec![], + temperature: None, + max_output_tokens: Some(321), + }; + let structured = deepseek_request_body(&request); + assert_eq!(structured["temperature"].as_f64(), Some(0.0)); + assert_eq!(structured["response_format"]["type"], "json_object"); + assert_eq!(structured["max_tokens"], 321); + + request.output_schema = None; + let narrative = deepseek_request_body(&request); + assert!(narrative.get("temperature").is_none()); + assert!(narrative.get("response_format").is_none()); + } } #[derive(Clone)] @@ -304,7 +496,7 @@ impl DeepSeekPort { pub fn new(api_key: String) -> Self { Self { client: reqwest::Client::builder() - .timeout(std::time::Duration::from_secs(45)) + .connect_timeout(std::time::Duration::from_secs(10)) .build() .expect("static DeepSeek client configuration is valid"), api_key: Zeroizing::new(api_key), @@ -318,14 +510,12 @@ impl DeepSeekPort { path, )?)) } -} -#[async_trait] -impl ModelPort for DeepSeekPort { - async fn run(&self, request: &ModelStageRequest) -> Result { - let mut body = serde_json::json!({"model":request.model,"messages":[{"role":"user","content":request.lived_stream}],"stream":false,"thinking":{"type":"disabled"}}); - if request.output_schema.is_some() { - body["response_format"] = serde_json::json!({"type":"json_object"}); - } + + async fn run_with_observation( + &self, + request: &ModelStageRequest, + ) -> Result { + let body = deepseek_request_body(request); let value: serde_json::Value = self .client .post(&self.endpoint) @@ -336,13 +526,71 @@ impl ModelPort for DeepSeekPort { .error_for_status()? .json() .await?; - value - .pointer("/choices/0/message/content") - .and_then(|v| v.as_str()) - .map(str::to_owned) - .ok_or_else(|| anyhow!("DeepSeek response contained no assistant content")) + decode_deepseek_response(&value) + } +} + +fn deepseek_request_body(request: &ModelStageRequest) -> serde_json::Value { + let mut body = serde_json::json!({ + "model": request.model, + "messages": [{"role": "user", "content": request.lived_stream}], + "stream": false, + "thinking": {"type": "disabled"} + }); + if request.output_schema.is_some() { + body["response_format"] = serde_json::json!({"type":"json_object"}); + body["temperature"] = serde_json::json!(request.temperature.unwrap_or(0.0)); + } else if let Some(temperature) = request.temperature { + body["temperature"] = serde_json::json!(temperature); + } + if let Some(max_tokens) = request.max_output_tokens { + body["max_tokens"] = serde_json::json!(max_tokens); + } + body +} +#[async_trait] +impl ModelPort for DeepSeekPort { + async fn run(&self, request: &ModelStageRequest) -> Result { + Ok(self.run_with_observation(request).await?.content) + } + async fn run_observed(&self, request: &ModelStageRequest) -> Result { + self.run_with_observation(request).await } fn provider(&self) -> &'static str { "deepseek" } } + +fn decode_deepseek_response(value: &serde_json::Value) -> Result { + let content = value + .pointer("/choices/0/message/content") + .and_then(|v| v.as_str()) + .map(str::to_owned) + .ok_or_else(|| anyhow!("DeepSeek response contained no assistant content"))?; + let token_usage = value + .get("usage") + .filter(|usage| !usage.is_null()) + .map(|usage| ModelTokenUsage { + prompt_tokens: usage["prompt_tokens"].as_u64().unwrap_or_default(), + completion_tokens: usage["completion_tokens"].as_u64().unwrap_or_default(), + total_tokens: usage["total_tokens"].as_u64().unwrap_or_default(), + prompt_cache_hit_tokens: usage["prompt_cache_hit_tokens"] + .as_u64() + .unwrap_or_default(), + prompt_cache_miss_tokens: usage["prompt_cache_miss_tokens"] + .as_u64() + .unwrap_or_default(), + reasoning_tokens: usage["completion_tokens_details"]["reasoning_tokens"] + .as_u64() + .unwrap_or_default(), + }); + Ok(ModelProviderOutput { + content, + provider_request_id: value["id"].as_str().map(str::to_owned), + system_fingerprint: value["system_fingerprint"].as_str().map(str::to_owned), + finish_reason: value["choices"][0]["finish_reason"] + .as_str() + .map(str::to_owned), + token_usage, + }) +} diff --git a/crates/ghostlight-dungeon/src/narrator.rs b/crates/ghostlight-dungeon/src/narrator.rs index d46ad6b..582bb47 100644 --- a/crates/ghostlight-dungeon/src/narrator.rs +++ b/crates/ghostlight-dungeon/src/narrator.rs @@ -52,11 +52,13 @@ impl Narrator { campaign.id, campaign.revision ), lived_stream: format!( - "Narrate the latest committed change in vivid, concise second-person interactive-fiction prose. Describe only the supplied committed state, speech, and accessible sensory consequences. Do not add actions, facts, private thoughts, expertise, geography, outcomes, or dialogue. Emit prose only.\n\n{}", + "Narrate the latest committed change in concrete, concise second-person interactive-fiction prose. Integrate supplied facts into fluent prose; do not mention JSON, state, commits, revisions, or the source representation. Every environmental noun, sensory adjective, object state, action, and consequence must be traceable to the supplied JSON. Do not invent lighting, temperature, sound, motion, posture, dialogue, private thoughts, expertise, geography, or outcomes. It is better to be spare than to fabricate texture. Emit prose only.\n\n{}", serde_json::to_string(&public_slice)? ), output_schema: None, source_receipt_ids: campaign.branch_origin.evidence_receipt_ids.clone(), + temperature: Some(0.2), + max_output_tokens: Some(256), }, ) .await?; diff --git a/crates/ghostlight-dungeon/src/persona.rs b/crates/ghostlight-dungeon/src/persona.rs index 7e881be..ad637b4 100644 --- a/crates/ghostlight-dungeon/src/persona.rs +++ b/crates/ghostlight-dungeon/src/persona.rs @@ -93,6 +93,13 @@ pub struct CellTerminalBundle { pub stage_receipts: Vec, } +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +#[serde(deny_unknown_fields)] +struct CellAppraisalProposal { + actions: Vec, + inaction_reason: Option, +} + #[async_trait] pub trait ExecutionPermit: Send + Sync { async fn require(&self, actor_id: &str, snapshot_binding: &str, stage: &str) -> Result<()>; @@ -128,6 +135,7 @@ impl PersonaProjectionEngine { typed_context: &typed_context, visible_stimulus: &visible_stimulus, domain_guidance: "The runtime is a persistent fictional world. Distances, knowledge, capabilities, relationships, and custody remain bounded by the supplied slice.", + word_budget: 140, }); let projected = run_validated_stage( self.model.as_ref(), @@ -138,6 +146,8 @@ impl PersonaProjectionEngine { lived_stream: projector_prompt, output_schema: None, source_receipt_ids: slice.source_receipt_ids.clone(), + temperature: Some(0.0), + max_output_tokens: Some(256), }, ) .await?; @@ -145,7 +155,7 @@ impl PersonaProjectionEngine { return Err(anyhow!("projector violated lived-narrative membrane")); } let lived = LivedNarrativeStream { - text: projected.narrative.clone(), + text: ground_actor_lived_stream(&slice, &projected.narrative), snapshot_binding: slice.snapshot_binding.clone(), projector_receipt: projected.receipt.clone(), }; @@ -163,10 +173,13 @@ impl PersonaProjectionEngine { lived_stream: build_persona_prompt(&PersonaPrompt { identity: &slice.actor_id, lived_stream: &lived.text, - domain_guidance: "Respond as a situated character. Speech and attempted effects are distinct; the world kernel resolves consequences.", + domain_guidance: "Respond as a situated character. Answer direct questions at human conversational length. Speech and attempted effects are distinct; the world kernel resolves consequences.", + word_budget: 160, }), output_schema: None, source_receipt_ids: vec![], + temperature: Some(0.7), + max_output_tokens: Some(256), }, ) .await?; @@ -174,8 +187,15 @@ impl PersonaProjectionEngine { self.permit .require(&slice.actor_id, &slice.snapshot_binding, "interpreter") .await?; - let mut schema = serde_json::to_value(schema_for!(PersonaProposalBundle))?; + let prompt_schema = serde_json::to_value(schema_for!(PersonaProposalBundle))?; + let mut schema = prompt_schema.clone(); constrain_interpreter_schema(&mut schema, &slice)?; + let permission_guidance = format!( + "Record only private changes supported by the lived stream and typed context. World actions are attempts, not completed effects. actor_id must be {:?}. Exact allowed state references are {:?}. Relationship update keys may only be {:?}.", + slice.actor_id, + allowed_actor_references(&slice), + slice.perceived_actors.keys().collect::>() + ); let interpreted = run_validated_stage( self.model.as_ref(), &ModelStageRequest { @@ -187,11 +207,13 @@ impl PersonaProjectionEngine { typed_context: &typed_context, lived_stream: &lived.text, persona_output: &persona.narrative, - output_schema: &serde_json::to_string_pretty(&schema)?, - domain_guidance: "Record only private changes supported by the lived stream and typed context. World actions are attempts, not completed effects. Use only exact actor ids and state-reference tokens admitted by the output schema.", + output_schema: &serde_json::to_string(&prompt_schema)?, + domain_guidance: &permission_guidance, }), output_schema: Some(schema), source_receipt_ids: slice.source_receipt_ids, + temperature: Some(0.0), + max_output_tokens: Some(768), }, ) .await?; @@ -213,6 +235,80 @@ impl PersonaProjectionEngine { } } +fn ground_actor_lived_stream(slice: &PermittedActorSlice, projection: &str) -> String { + let reliable_knowledge = if slice.knowledge.is_empty() { + "no additional external fact beyond what is happening in front of you".to_owned() + } else { + slice.knowledge.join("; ") + }; + let visible_now = if slice.perceived_events.is_empty() { + "nothing new beyond the immediate situation".to_owned() + } else { + slice.perceived_events.join("; ") + }; + let people_now = if slice.perceived_actors.is_empty() { + "no one else clearly perceived".to_owned() + } else { + slice + .perceived_actors + .values() + .cloned() + .collect::>() + .join(", ") + }; + format!( + "{projection}\n\nYour reliable footing in this moment is narrow. What you know as external fact: {reliable_knowledge}. What is happening now: {visible_now}. People you can presently perceive: {people_now}. Everything else in your impressions is feeling, inference, uncertainty, or possibility—not a remembered or witnessed fact." + ) +} + +fn cell_projector_context(slice: &PermittedCellSlice) -> serde_json::Value { + serde_json::json!({ + "cell_id": slice.cell_id, + "mode": slice.mode, + "world_revision": slice.world_revision, + "resolution_epoch": slice.resolution_epoch, + "constituents": slice.constituents.iter().map(|subject| serde_json::json!({ + "subject_id": subject.subject_id, + "subject_kind": subject.subject_kind, + "name": subject.name, + "collective_authority_id": subject.collective_authority_id, + "location_ids": subject.location_ids, + "knowledge": subject.knowledge, + "capabilities": subject.capabilities, + "resources": subject.resources, + "information_channels": subject.information_channels, + "reachable_destination_ids": subject.reachable_destination_ids, + "goals": subject.goals, + "pressures": subject.pressures, + })).collect::>(), + "shared_knowledge": slice.shared_knowledge, + "shared_capabilities": slice.shared_capabilities, + "world_clock_pressure": slice.world_clock_pressure, + "detail_focus_subject_id": slice.detail_focus_subject_id, + "max_actions": slice.max_actions, + }) +} + +fn cell_interpreter_context(slice: &PermittedCellSlice) -> serde_json::Value { + serde_json::json!({ + "cell_id": slice.cell_id, + "mode": slice.mode, + "world_revision": slice.world_revision, + "resolution_epoch": slice.resolution_epoch, + "detail_focus_subject_id": slice.detail_focus_subject_id, + "max_actions": slice.max_actions, + "exact_permissions": slice.constituents.iter().map(|subject| serde_json::json!({ + "subject_id": subject.subject_id, + "subject_kind": subject.subject_kind, + "collective_authority_id": subject.collective_authority_id, + "location_ids": subject.location_ids, + "information_channels": subject.information_channels, + "permitted_state_references": subject.permitted_state_references, + "reachable_destination_ids": subject.reachable_destination_ids, + })).collect::>(), + }) +} + #[derive(Clone)] pub struct CellProjectionEngine { pub model: Arc, @@ -227,7 +323,7 @@ impl CellProjectionEngine { self.permit .require(&slice.cell_id, &slice.snapshot_binding, "cell_projector") .await?; - let typed_context = serde_json::to_string(&slice)?; + let projector_context = serde_json::to_string(&cell_projector_context(&slice))?; let visible_stimulus = slice.perceived_events.join("\n"); let mode_guidance = match slice.mode { crate::domain::SimulationCellMode::Cohesive => { @@ -245,12 +341,15 @@ impl CellProjectionEngine { snapshot_binding: slice.snapshot_binding.clone(), lived_stream: build_projector_prompt(&ProjectorPrompt { identity: &slice.cell_id, - typed_context: &typed_context, + typed_context: &projector_context, visible_stimulus: &visible_stimulus, domain_guidance: mode_guidance, + word_budget: (120 + 45 * slice.constituents.len()).min(360), }), output_schema: None, source_receipt_ids: slice.source_receipt_ids.clone(), + temperature: Some(0.0), + max_output_tokens: Some(640), }, ) .await?; @@ -282,41 +381,53 @@ impl CellProjectionEngine { "Appraise the strategic horizon polyphonically. Attribute every intention to a constituent. The arena itself cannot speak, know, decide, or act. Action is optional, but inaction must be explicit." } }, + word_budget: (160 + 30 * slice.constituents.len()).min(320), }), output_schema: None, source_receipt_ids: vec![], + temperature: Some(0.7), + max_output_tokens: Some(512), }, ) .await?; self.permit .require(&slice.cell_id, &slice.snapshot_binding, "cell_interpreter") .await?; - let mut schema = serde_json::to_value(schema_for!(crate::domain::CellAppraisal))?; - constrain_cell_schema(&mut schema, &slice)?; + let prompt_schema = serde_json::to_value(schema_for!(CellAppraisalProposal))?; + let mut schema = prompt_schema.clone(); + constrain_cell_proposal_schema(&mut schema, &slice)?; + let interpreter_context = serde_json::to_string(&cell_interpreter_context(&slice))?; + let permission_guidance = format!( + "Emit at most {} exact constituent-attributed attempts supported by that constituent's permission references. The runtime, not you, binds cell identity, revisions, and complete membership. The cell id is not an actor id. Use an empty actions array plus a concrete inaction_reason when nobody acts.", + slice.max_actions + ); let mut request = ModelStageRequest { stage: "cell_interpreter".into(), model: self.interpreter_model.clone(), snapshot_binding: slice.snapshot_binding.clone(), lived_stream: build_interpreter_prompt(&InterpreterPrompt { identity: &slice.cell_id, - typed_context: &typed_context, + typed_context: &interpreter_context, lived_stream: &lived.text, persona_output: &persona.narrative, - output_schema: &serde_json::to_string_pretty(&schema)?, - domain_guidance: "Emit only exact constituent-attributed attempts supported by that constituent's typed state. The cell id is not an actor id. Use an empty actions array plus a concrete inaction_reason when nobody acts.", + output_schema: &serde_json::to_string(&prompt_schema)?, + domain_guidance: &permission_guidance, }), output_schema: Some(schema), source_receipt_ids: slice.source_receipt_ids.clone(), + temperature: Some(0.0), + max_output_tokens: Some(1_600), }; let mut stage_receipts = vec![projected.receipt, persona.receipt]; for attempt in 0..2 { let mut interpreted = run_validated_stage(self.model.as_ref(), &request).await?; - let appraisal = interpreted + let proposal = interpreted .structured .clone() - .ok_or_else(|| anyhow!("cell interpreter produced no typed appraisal")) + .ok_or_else(|| anyhow!("cell interpreter produced no typed proposal")) .and_then(|value| serde_json::from_value(value).map_err(Into::into)); - match appraisal.and_then(|appraisal| { + match proposal.and_then(|proposal: CellAppraisalProposal| { + let appraisal = bind_cell_appraisal(&slice, proposal); validate_cell_appraisal(&slice, &appraisal)?; Ok(appraisal) }) { @@ -334,6 +445,8 @@ impl CellProjectionEngine { } Err(error) if attempt == 0 => { interpreted.receipt.validation_result = "semantic_invalid".into(); + interpreted.receipt.local_validation_error = + Some(error.to_string().chars().take(1_000).collect()); stage_receipts.push(interpreted.receipt); request.lived_stream.push_str(&format!( "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS APPRAISAL: {error}\nReturn one corrected complete appraisal against the same snapshot, lived stream, and Persona turn." @@ -350,6 +463,25 @@ impl CellProjectionEngine { } } +fn bind_cell_appraisal( + slice: &PermittedCellSlice, + proposal: CellAppraisalProposal, +) -> crate::domain::CellAppraisal { + crate::domain::CellAppraisal { + schema: "ghostlight.cell_appraisal.v1".into(), + cell_id: slice.cell_id.clone(), + world_revision: slice.world_revision, + resolution_epoch: slice.resolution_epoch, + considered_subject_ids: slice + .constituents + .iter() + .map(|subject| subject.subject_id.clone()) + .collect(), + actions: proposal.actions, + inaction_reason: proposal.inaction_reason, + } +} + fn validate_cell_appraisal( slice: &PermittedCellSlice, appraisal: &crate::domain::CellAppraisal, @@ -425,34 +557,14 @@ fn validate_cell_appraisal( Ok(()) } -fn constrain_cell_schema(schema: &mut serde_json::Value, slice: &PermittedCellSlice) -> Result<()> { +fn constrain_cell_proposal_schema( + schema: &mut serde_json::Value, + slice: &PermittedCellSlice, +) -> Result<()> { let properties = schema .pointer_mut("/properties") .and_then(serde_json::Value::as_object_mut) - .ok_or_else(|| anyhow!("cell appraisal schema has no properties"))?; - properties.insert( - "schema".into(), - serde_json::json!({"const":"ghostlight.cell_appraisal.v1"}), - ); - properties.insert("cell_id".into(), serde_json::json!({"const":slice.cell_id})); - properties.insert( - "world_revision".into(), - serde_json::json!({"const":slice.world_revision}), - ); - properties.insert( - "resolution_epoch".into(), - serde_json::json!({"const":slice.resolution_epoch}), - ); - properties.insert( - "considered_subject_ids".into(), - serde_json::json!({ - "type":"array", - "uniqueItems":true, - "minItems":slice.constituents.len(), - "maxItems":slice.constituents.len(), - "items":{"type":"string","enum":slice.constituents.iter().map(|value| &value.subject_id).collect::>()} - }), - ); + .ok_or_else(|| anyhow!("cell proposal schema has no properties"))?; let actions = properties .get_mut("actions") .and_then(serde_json::Value::as_object_mut) @@ -473,24 +585,7 @@ fn constrain_interpreter_schema( schema: &mut serde_json::Value, slice: &PermittedActorSlice, ) -> Result<()> { - let allowed_references = slice - .capabilities - .iter() - .map(|value| format!("capability:{value}")) - .chain( - slice - .knowledge - .iter() - .map(|value| format!("knowledge:{value}")), - ) - .chain( - slice - .affordances - .iter() - .map(|value| format!("equipment:{value}")), - ) - .chain(std::iter::once(format!("location:{}", slice.location_id))) - .collect::>(); + let allowed_references = allowed_actor_references(slice); let world_action = schema .pointer_mut("/$defs/WorldActionProposal/properties") .and_then(|value| value.as_object_mut()) @@ -514,6 +609,27 @@ fn constrain_interpreter_schema( Ok(()) } +fn allowed_actor_references(slice: &PermittedActorSlice) -> Vec { + slice + .capabilities + .iter() + .map(|value| format!("capability:{value}")) + .chain( + slice + .knowledge + .iter() + .map(|value| format!("knowledge:{value}")), + ) + .chain( + slice + .affordances + .iter() + .map(|value| format!("equipment:{value}")), + ) + .chain(std::iter::once(format!("location:{}", slice.location_id))) + .collect() +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ghostlight-dungeon/src/registry.rs b/crates/ghostlight-dungeon/src/registry.rs index 68d9f62..49181f7 100644 --- a/crates/ghostlight-dungeon/src/registry.rs +++ b/crates/ghostlight-dungeon/src/registry.rs @@ -342,6 +342,10 @@ mod tests { source_receipt_ids: vec![], latency_ms: 1, validation_result: "valid".into(), + local_validation_error: None, + input_chars: 7, + output_chars: 7, + provider_attempts: vec![], }; registry .create(original.clone(), vec![], vec![model_receipt.clone()]) diff --git a/crates/ghostlight-dungeon/src/resolution.rs b/crates/ghostlight-dungeon/src/resolution.rs index 3c40f89..d987292 100644 --- a/crates/ghostlight-dungeon/src/resolution.rs +++ b/crates/ghostlight-dungeon/src/resolution.rs @@ -400,7 +400,7 @@ pub fn plan_cover(campaign: &Campaign, demand: ResolutionDemand) -> Result usize { } } -fn mandatory_subjects(campaign: &Campaign, demand: &ResolutionDemand) -> BTreeSet { - let mut mandatory = demand.focal_subject_ids.clone(); +fn mandatory_subjects(campaign: &Campaign) -> BTreeSet { + let mut mandatory = BTreeSet::new(); for pin in campaign.resolution_pins.values() { if pin.kind == ResolutionPinKind::MinimumIndividualDetail { mandatory.extend(pin.subject_ids.iter().cloned()); @@ -2150,13 +2150,21 @@ pub(crate) mod tests { #[test] fn foreground_subjects_create_reported_temporary_overage() { - let value = campaign(5, 1); - let mut demand = default_demand(&value, "foreground"); - demand.focal_subject_ids = BTreeSet::from([ - "faction-0000".into(), - "faction-0001".into(), - "faction-0002".into(), - ]); + let mut value = campaign(5, 1); + for id in ["faction-0000", "faction-0001", "faction-0002"] { + value.resolution_pins.insert( + format!("foreground:{id}"), + ResolutionPin { + schema: "ghostlight.resolution_pin.v1".into(), + id: format!("foreground:{id}"), + kind: ResolutionPinKind::MinimumIndividualDetail, + subject_ids: BTreeSet::from([id.into()]), + reason: "directly engaged foreground subject".into(), + created_world_revision: value.revision, + }, + ); + } + let demand = default_demand(&value, "foreground"); let cover = plan_cover(&value, demand).unwrap(); assert_eq!(cover.effective_budget, 4); assert_eq!(cover.mandatory_overage, 3); @@ -2170,6 +2178,22 @@ pub(crate) mod tests { } } + #[test] + fn model_focal_subjects_raise_salience_without_overriding_the_budget() { + let value = campaign(5, 1); + let mut demand = default_demand(&value, "broad pressure"); + demand.focal_subject_ids = value + .agency_profiles + .values() + .filter(|profile| profile.simulation_eligible) + .map(|profile| profile.subject_id.clone()) + .collect(); + let cover = plan_cover(&value, demand).unwrap(); + assert_eq!(cover.effective_budget, 1); + assert_eq!(cover.mandatory_overage, 0); + assert_eq!(cover.cells[0].subject_ids.len(), 5); + } + #[test] fn contradictory_pins_are_rejected() { let mut value = campaign(3, 2); diff --git a/crates/ghostlight-dungeon/src/scheduler.rs b/crates/ghostlight-dungeon/src/scheduler.rs index 7e51e88..eaba6cb 100644 --- a/crates/ghostlight-dungeon/src/scheduler.rs +++ b/crates/ghostlight-dungeon/src/scheduler.rs @@ -132,16 +132,58 @@ async fn project_resolution_demand( .filter(|profile| profile.active_leaf && profile.simulation_eligible) .map(|profile| profile.subject_id.clone()) .collect(); + let compact_profiles = campaign + .agency_profiles + .values() + .filter(|profile| profile.active_leaf && profile.simulation_eligible) + .map(|profile| { + serde_json::json!({ + "subject_id":profile.subject_id, + "subject_kind":profile.subject_kind, + "collective_authority_id":profile.collective_authority_id, + "location_ids":profile.location_ids, + "facets":profile.facets, + "information_channels":profile.information_channels, + "detail_debt":profile.detail_debt, + }) + }) + .collect::>(); + let compact_relations = campaign + .agency_relations + .values() + .filter(|relation| relation.active) + .map(|relation| { + serde_json::json!({ + "from_subject_id":relation.from_subject_id, + "to_subject_id":relation.to_subject_id, + "kind":relation.kind, + "strength":relation.strength, + }) + }) + .collect::>(); let context = serde_json::json!({ "campaign_id": campaign.id, "world_revision": campaign.revision, "resolution_epoch": campaign.resolution_policy.resolution_epoch, "horizon_minutes": campaign.tick_hours.saturating_mul(60), - "allowed_subject_ids": active_ids, - "clocks": campaign.clocks, - "recent_events": campaign.events.iter().rev().take(12).collect::>(), - "relations": campaign.agency_relations.values().filter(|relation| relation.active).collect::>(), - "profiles": campaign.agency_profiles.values().filter(|profile| profile.active_leaf && profile.simulation_eligible).collect::>() + "allowed_subject_ids": &active_ids, + "clocks": campaign.clocks.values().map(|clock| serde_json::json!({ + "id":clock.id, + "label":clock.label, + "progress":clock.progress, + "threshold":clock.threshold, + "consequence":clock.consequence, + })).collect::>(), + "recent_events": campaign.events.iter().rev().take(12).map(|event| serde_json::json!({ + "id":event.id, + "kind":event.kind, + "summary":event.summary, + "institution_ids":event.institution_ids, + "location_ids":event.location_ids, + "public_channels":event.public_channels, + })).collect::>(), + "relations": compact_relations, + "profiles": compact_profiles, }); let mut schema = match serde_json::to_value(schema_for!(DemandProjection)) { Ok(value) => value, @@ -150,10 +192,22 @@ async fn project_resolution_demand( if let Some(items) = schema.pointer_mut("/properties/focal_subject_ids/items") { *items = serde_json::json!({"type":"string","enum":active_ids}); } + if let Some(focal) = schema + .pointer_mut("/properties/focal_subject_ids") + .and_then(serde_json::Value::as_object_mut) + { + focal.insert("uniqueItems".into(), true.into()); + focal.insert( + "maxItems".into(), + usize::from(campaign.resolution_policy.active_cell_budget) + .min(active_ids.len()) + .into(), + ); + } let base_prompt = format!( - "Project which boundaries best predict different strategic behavior for the next horizon. Return all six axis weights (geography, ideology, authority, economy_role, species_body, information), each from 0 to 1 and summing to 1. Focal subjects may only use supplied IDs. This stage proposes relevance and cannot change world state. Return one JSON object matching the schema.\nSTATE:\n{}\nOUTPUT JSON SCHEMA:\n{}", + "OUTPUT JSON SCHEMA (follow exactly):\n{}\n\nProject which boundaries best predict different strategic behavior for the next horizon. Return all six axis weights (geography, ideology, authority, economy_role, species_body, information), each from 0 to 1 and summing to 1. Focal subjects are exceptional salience hints only, may use only supplied IDs, and cannot force partition boundaries or budget overage. This stage proposes relevance and cannot change world state.\nSTATE:\n{}", + serde_json::to_string(&schema).unwrap_or_default(), serde_json::to_string(&context).unwrap_or_default(), - serde_json::to_string_pretty(&schema).unwrap_or_default(), ); let mut request = ModelStageRequest { stage: "resolution_demand".into(), @@ -165,6 +219,8 @@ async fn project_resolution_demand( lived_stream: base_prompt, output_schema: Some(schema), source_receipt_ids: campaign.branch_origin.evidence_receipt_ids.clone(), + temperature: Some(0.0), + max_output_tokens: Some(512), }; let mut outputs = Vec::new(); for attempt in 0..2 { @@ -186,12 +242,22 @@ async fn project_resolution_demand( horizon_minutes: campaign.tick_hours.saturating_mul(60), rationale: projection.rationale, }; - if validate_demand(campaign, &demand).is_ok() { - outputs.push(output); - return (demand, outputs); + match validate_demand(campaign, &demand) { + Ok(()) => { + outputs.push(output); + return (demand, outputs); + } + Err(error) => { + output.receipt.validation_result = "semantic_invalid".into(); + output.receipt.local_validation_error = + Some(error.to_string().chars().take(1_000).collect()); + } } + } else { + output.receipt.validation_result = "semantic_invalid".into(); + output.receipt.local_validation_error = + Some("resolution demand could not be decoded".into()); } - output.receipt.validation_result = "semantic_invalid".into(); outputs.push(output); if attempt == 0 { request.lived_stream.push_str( @@ -390,30 +456,11 @@ mod tests { "cell_projector" => Ok("Several powers feel the horizon tightening.".into()), "cell_persona" => Ok("Each constituent watches and deliberately holds.".into()), "cell_interpreter" if self.malformed_cell => Ok("not-json".into()), - "cell_interpreter" => { - let context = request - .lived_stream - .split("Permissioned typed context:\n") - .nth(1) - .and_then(|value| value.split("\n\nLived stream:").next()) - .context("fixture could not locate typed cell context")?; - let slice: PermittedCellSlice = serde_json::from_str(context)?; - Ok(serde_json::to_string(&crate::domain::CellAppraisal { - schema: "ghostlight.cell_appraisal.v1".into(), - cell_id: slice.cell_id, - world_revision: slice.world_revision, - resolution_epoch: slice.resolution_epoch, - considered_subject_ids: slice - .constituents - .into_iter() - .map(|value| value.subject_id) - .collect(), - actions: vec![], - inaction_reason: Some( - "No constituent has a justified move this horizon.".into(), - ), - })?) - } + "cell_interpreter" => Ok(serde_json::json!({ + "actions": [], + "inaction_reason": "No constituent has a justified move this horizon." + }) + .to_string()), stage => Err(anyhow!("unexpected fixture stage {stage}")), } } diff --git a/crates/ghostlight-dungeon/src/surface.rs b/crates/ghostlight-dungeon/src/surface.rs index fe93a81..6fb781b 100644 --- a/crates/ghostlight-dungeon/src/surface.rs +++ b/crates/ghostlight-dungeon/src/surface.rs @@ -138,24 +138,61 @@ pub fn operator_surface( }) .collect::>() .join("\n"); + let provider_attempt_count = stages + .iter() + .map(|stage| stage.provider_attempts.len()) + .sum::(); + let retry_count = provider_attempt_count.saturating_sub(stages.len()); + let token_usage = stages + .iter() + .flat_map(|stage| &stage.provider_attempts) + .filter_map(|attempt| attempt.token_usage.as_ref()) + .fold( + crate::model::ModelTokenUsage::default(), + |mut total, usage| { + total.prompt_tokens = total.prompt_tokens.saturating_add(usage.prompt_tokens); + total.completion_tokens = total + .completion_tokens + .saturating_add(usage.completion_tokens); + total.total_tokens = total.total_tokens.saturating_add(usage.total_tokens); + total.prompt_cache_hit_tokens = total + .prompt_cache_hit_tokens + .saturating_add(usage.prompt_cache_hit_tokens); + total.prompt_cache_miss_tokens = total + .prompt_cache_miss_tokens + .saturating_add(usage.prompt_cache_miss_tokens); + total.reasoning_tokens = total + .reasoning_tokens + .saturating_add(usage.reasoning_tokens); + total + }, + ); let typed = json!({ - "campaign": campaign, - "evidence": evidence, - "commit_receipts": commits, - "model_stage_receipts": stages, - "strategic_ticks": strategic_ticks, - "gestalt_materialization_receipts": gestalt_receipts, - "rejected_proposals": rejected, - "resolution_plan_receipts": resolution_plans, - "cell_appraisals": cell_appraisals, - "resolution_control_receipts": resolution_controls, - "scheduler": {"live_turn_pressure": live_turn_pressure} + "campaign": campaign, + "evidence": evidence, + "commit_receipts": commits, + "model_stage_receipts": stages, + "strategic_ticks": strategic_ticks, + "gestalt_materialization_receipts": gestalt_receipts, + "rejected_proposals": rejected, + "resolution_plan_receipts": resolution_plans, + "cell_appraisals": cell_appraisals, + "resolution_control_receipts": resolution_controls, + "scheduler": {"live_turn_pressure": live_turn_pressure} }); + let cache_observed_tokens = token_usage + .prompt_cache_hit_tokens + .saturating_add(token_usage.prompt_cache_miss_tokens); + let cache_hit_percent = if cache_observed_tokens == 0 { + 0 + } else { + token_usage.prompt_cache_hit_tokens.saturating_mul(100) / cache_observed_tokens + }; json!({ "type":"surface-state", "schema":"gamecult.eve.surface.v1", "providerId":"gamecult.ghostlight.dungeon", "providerKind":"narrative.simulation.operator", "title":format!("{} operator",campaign.name), "version":interface_version, "surface":{"id":format!("ghostlight.operator.{}",campaign.id),"root":{"id":"dungeon.operator.root","kind":"surface","props":{},"children":[ - {"id":"dungeon.operator.status","kind":"card","props":{"title":format!("Revision {} · {} model stages · {} rejected proposals",campaign.revision,stages.len(),rejected.len())},"children":[]}, + {"id":"dungeon.operator.status","kind":"card","props":{"title":format!("Revision {} · {} model stages / {} provider attempts · {} tokens · {} rejected proposals",campaign.revision,stages.len(),provider_attempt_count,token_usage.total_tokens,rejected.len())},"children":[{"id":"dungeon.operator.usage","kind":"text","props":{"value":format!("Prompt {} (cache hit {}, miss {}, {}%) · completion {} · reasoning {} · retries {}",token_usage.prompt_tokens,token_usage.prompt_cache_hit_tokens,token_usage.prompt_cache_miss_tokens,cache_hit_percent,token_usage.completion_tokens,token_usage.reasoning_tokens,retry_count)},"children":[]}]}, {"id":"dungeon.operator.cover","kind":"card","props":{"title":format!("Agency cover · epoch {} · budget {}",campaign.resolution_policy.resolution_epoch,campaign.resolution_policy.active_cell_budget)},"children":[{"id":"dungeon.operator.cover.text","kind":"text","props":{"value":cover_text},"children":[]}]}, {"id":"dungeon.operator.graph","kind":"card","props":{"title":format!("Agency graph · {} profiles · {} relations",campaign.agency_profiles.len(),campaign.agency_relations.len())},"children":[{"id":"dungeon.operator.graph.text","kind":"text","props":{"value":graph_text},"children":[]}]}, {"id":"dungeon.operator.typed","kind":"code","props":{"language":"json","value":serde_json::to_string_pretty(&typed).unwrap_or_else(|_| "operator projection failed".into())},"children":[]} diff --git a/crates/ghostlight-dungeon/src/vault.rs b/crates/ghostlight-dungeon/src/vault.rs index a0f7be2..0d4e66f 100644 --- a/crates/ghostlight-dungeon/src/vault.rs +++ b/crates/ghostlight-dungeon/src/vault.rs @@ -6,6 +6,8 @@ use reqwest::Client; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; +const VOIDBOT_SEARCH_RESULT_LIMIT: u8 = 12; + #[derive(Clone, Debug, Serialize, Deserialize)] pub struct VaultQuery { pub query: String, @@ -127,6 +129,44 @@ mod tests { assert_eq!(result.witnesses[0].authority_lane, "AetheriaLore"); } + #[tokio::test] + async fn voidbot_search_caps_requests_to_the_provider_contract() { + let app = Router::new().route( + "/mcp", + post(|axum::Json(body): axum::Json| async move { + assert_eq!( + body.pointer("/params/arguments/limit") + .and_then(|value| value.as_u64()), + Some(VOIDBOT_SEARCH_RESULT_LIMIT as u64) + ); + ([ + ("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 requested = VaultQuery { + query: "route".into(), + authority_lanes: vec!["AetheriaLore".into()], + temporal_scope: "era".into(), + limit: 18, + }; + let result = VoidBotMcpVault::new(format!("http://{address}/mcp")) + .search(&requested) + .await + .unwrap(); + let mut effective = requested; + effective.limit = VOIDBOT_SEARCH_RESULT_LIMIT; + assert_eq!( + result.query_hash, + receipt("voidbot.aetheria", &effective, vec![]).query_hash + ); + } + #[tokio::test] async fn voidbot_exact_document_is_hashed_as_the_complete_archive_witness() { let app=Router::new().route("/mcp",post(||async { ([ ("content-type","text/event-stream") ], "event: message\ndata: {\"result\":{\"structuredContent\":{\"found\":true,\"sourceId\":\"AetheriaLore:forge.md\",\"repoName\":\"AetheriaLore\",\"path\":\"forge.md\",\"content\":\"John keeps the forge.\\nThe road takes six hours.\",\"lastModifiedAt\":\"2026-01-01T00:00:00Z\"}}}\n\n").into_response() })); @@ -170,13 +210,15 @@ mod tests { #[async_trait] impl VaultProvider for VoidBotMcpVault { async fn search(&self, query: &VaultQuery) -> Result { + let mut effective_query = query.clone(); + effective_query.limit = effective_query.limit.min(VOIDBOT_SEARCH_RESULT_LIMIT); let response = self .call_tool( "search_sources", serde_json::json!({ - "query":query.query, - "limit":query.limit, - "repoName": if query.authority_lanes.iter().any(|lane| lane == "AetheriaLore") { + "query":effective_query.query, + "limit":effective_query.limit, + "repoName": if effective_query.authority_lanes.iter().any(|lane| lane == "AetheriaLore") { Some("AetheriaLore") } else { None @@ -190,9 +232,9 @@ impl VaultProvider for VoidBotMcpVault { .ok_or_else(|| anyhow!("VoidBot MCP returned no typed search results"))?; let witnesses = results .iter() - .map(|item| witness_from_result(item, query)) + .map(|item| witness_from_result(item, &effective_query)) .collect::>>()?; - Ok(receipt(self.provider_id(), query, witnesses)) + Ok(receipt(self.provider_id(), &effective_query, witnesses)) } async fn surrounding_context( &self, diff --git a/crates/ghostlight-persona-projection/src/lib.rs b/crates/ghostlight-persona-projection/src/lib.rs index 5b76dbf..074cc63 100644 --- a/crates/ghostlight-persona-projection/src/lib.rs +++ b/crates/ghostlight-persona-projection/src/lib.rs @@ -9,6 +9,7 @@ pub struct ProjectorPrompt<'a> { pub typed_context: &'a str, pub visible_stimulus: &'a str, pub domain_guidance: &'a str, + pub word_budget: usize, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -16,6 +17,7 @@ pub struct PersonaPrompt<'a> { pub identity: &'a str, pub lived_stream: &'a str, pub domain_guidance: &'a str, + pub word_budget: usize, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -30,26 +32,28 @@ pub struct InterpreterPrompt<'a> { pub fn build_projector_prompt(input: &ProjectorPrompt<'_>) -> String { format!( - "\nYou are the private Projector for {identity}. Convert the permitted typed context and visible stimulus into one lived narrative stream. Project what this person perceives, remembers, wants, fears, knows, and does not know. Do not choose actions, emit schemas, expose field names, or claim world effects.\n\nDomain guidance:\n{guidance}\n\nPermitted typed context:\n{context}\n\nVisible stimulus:\n{stimulus}\n\nReturn only the lived narrative stream.", + "\nYou are a private Projector. Convert only the permitted typed context and visible stimulus into one compact lived narrative stream. Project what this person perceives, remembers, wants, fears, knows, and explicitly does not know. Anything absent from the permitted context is unavailable: render imagination, suspicion, or speculation as uncertainty, never as remembered or perceived fact. Do not choose actions, emit schemas, expose field names, or claim world effects. Use at most {word_budget} words; omit decorative recap that does not change the decision.\n\nDomain guidance:\n{guidance}\n\nIdentity:\n{identity}\n\nPermitted typed context:\n{context}\n\nVisible stimulus:\n{stimulus}\n\nReturn only the lived narrative stream.", identity = input.identity, guidance = input.domain_guidance, context = input.typed_context, stimulus = input.visible_stimulus, + word_budget = input.word_budget, ) } pub fn build_persona_prompt(input: &PersonaPrompt<'_>) -> String { format!( - "\nYou are {identity}. The text below is your complete lived stream for this turn. Respond naturally from inside it. You may speak, remain silent, wonder, decide, or attempt something, but do not emit JSON, schemas, action DSL, tool calls, state patches, or claims that an external consequence already occurred.\n\nDomain guidance:\n{guidance}\n\nLived stream:\n{stream}\n\nReturn only the natural Persona turn.", + "\nThe text below is the character's complete lived stream for this turn. Respond naturally from inside it. Treat only asserted perceptions and memories in that stream as known. New external details may appear only as explicit conjecture, imagination, or deliberate invention by the character. You may speak, remain silent, wonder, decide, or attempt something, but do not emit JSON, schemas, action DSL, tool calls, state patches, or claims that an external consequence already occurred. Use at most {word_budget} words and spend them in proportion to the moment.\n\nDomain guidance:\n{guidance}\n\nIdentity:\n{identity}\n\nLived stream:\n{stream}\n\nReturn only the natural Persona turn.", identity = input.identity, guidance = input.domain_guidance, stream = input.lived_stream, + word_budget = input.word_budget, ) } pub fn build_interpreter_prompt(input: &InterpreterPrompt<'_>) -> String { format!( - "\nYou are the private Interpreter for {identity}. Convert the natural Persona turn into typed candidate effects supported by the lived stream and permissioned typed context. Candidates are proposals only; the owning runtime validates and commits them. Do not invent knowledge, capability, custody, perception, identifiers, state references, or completed consequences.\n\nDomain guidance:\n{guidance}\n\nPermissioned typed context:\n{context}\n\nLived stream:\n{stream}\n\nPersona turn:\n{output}\n\nReturn exactly one JSON object matching this schema:\n{schema}", + "\nYou are a private Interpreter. Convert a natural Persona turn into typed candidate effects supported by the lived stream and permissioned typed context. Candidates are proposals only; the owning runtime validates and commits them. Do not invent knowledge, capability, custody, perception, identifiers, state references, or completed consequences.\n\nReturn exactly one JSON object matching this stable shape:\n{schema}\n\nDomain guidance and exact permissions:\n{guidance}\n\nIdentity:\n{identity}\n\nPermissioned typed context:\n{context}\n\nLived stream:\n{stream}\n\nPersona turn:\n{output}", identity = input.identity, guidance = input.domain_guidance, context = input.typed_context, @@ -83,6 +87,7 @@ mod tests { identity: "John", lived_stream: "The forge is hot and the traveler looks worried.", domain_guidance: "Speak as a villager.", + word_budget: 140, }); assert!(prompt.contains("The forge is hot")); assert!(!prompt.contains("typed context")); diff --git a/docs/architecture/ghostlight-dungeon-mvp.md b/docs/architecture/ghostlight-dungeon-mvp.md index 9b6447d..89be472 100644 --- a/docs/architecture/ghostlight-dungeon-mvp.md +++ b/docs/architecture/ghostlight-dungeon-mvp.md @@ -623,11 +623,34 @@ scheduler pulse or return catch-up uses the same strategic-tick command. ## Model boundary The provider-neutral model port records provider, model, request hash, source -receipt ids, latency, output hash, validation result, and state version. +receipt ids, latency, output hash, validation result, state version, provider +request id/fingerprint/finish reason, and prompt/completion/cache-hit/cache-miss +token counts for every provider attempt. Local schema and semantic failures carry +a bounded exact error. The runtime never records provider reasoning content. Structured stages request JSON Output and then validate locally. Empty or malformed output gets one retry against the same snapshot. A second failure, timeout, retrieval outage, or stale result produces no mutation. +Prompt projection follows the authority boundary instead of shipping one large +state packet to every stage: + +- stable instructions and schemas precede changing campaign context so provider + prefix caches can do useful work; +- Projectors receive only the typed facts needed to form the actor or cell's + lived situation; +- Personas receive only the resulting narrative stream; +- Interpreters receive the narrative output plus exact action permissions, not + a second copy of the entire state slice; +- deterministic bindings already owned by the runtime—cell membership, cell id, + world revision, and resolution epoch—are attached locally after interpretation + rather than copied by a model. + +This is both a safety and cognitive-efficiency rule. Models spend tokens on +judgment and voice; the kernel spends deterministic work on identity, versions, +coverage, references, and commit authority. A resolution-demand model may raise +subject salience, but only pins and active relevance leases may force singleton +cells or an effective-budget overage. + Live model allocation: - `deepseek-v4-flash`, non-thinking: projection, interpretation, retrieval diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index d9fd89b..d41d44e 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -357,13 +357,21 @@ steering surfaces unless the user explicitly asks for archaeology. ## Current Next Action -The Persona extraction and Epiphany handback are complete. Continue the hosted -MVP acceptance pass: prove live strategic scheduling and return catch-up use the -flash-model `StrategicTickPlan`, malformed or forbidden plans do not mutate the -campaign, gestalt individuals survive dematerialization and later population -ticks, four-actor live latency meets target, remote CultMesh publication works, -and the normal-process Starfire release has exact restart/firewall/provenance -evidence. +The Persona extraction and Epiphany handback are complete. The current local +candidate is an acceptance-hardening pass, not the older deployed release. It +adds per-attempt DeepSeek usage/cache/error receipts, splits world and agency +compilation, minimizes Projector/Persona/Interpreter context by authority, makes +cell identity/membership/revisions runtime-derived, and prevents demand-model +focal hints from overruling the Persona-cell budget. Live proof under +`F:\GameCult\GhostlightDungeon\acceptance` includes grounded compilation, +four-actor appraisal, impossible/rolled actions, grounded narration, strategic +cells, and a 24-faction budget-4 wave. + +Next: commit this coherent pass, run the authenticated HTTP/browser campaign +path in an isolated runtime, prove away catch-up/concurrency/persistence/fork/ +export/restart against the candidate, then deploy the exact commit and repeat +LAN/firewall/CultMesh/provenance smokes. Do not describe the current Starfire +process as running the candidate until the immutable release switch is proven. ## Warnings diff --git a/notes/ghostlight-current-system-map.md b/notes/ghostlight-current-system-map.md index 106b6a6..f62c7fe 100644 --- a/notes/ghostlight-current-system-map.md +++ b/notes/ghostlight-current-system-map.md @@ -31,7 +31,8 @@ exact campaign revision -> connected agency graph + budget/pins/leases/detail debt -> cohesive or arena simulation-cell cover -> one private Projector/Persona/Interpreter membrane per cell - -> exact constituent-attributed appraisals and proposals + -> model proposes exact constituent-attributed actions or explicit inaction + -> runtime binds complete cell membership + world/resolution revisions -> WorldKernel validates cover, receipts, knowledge, scope, topology, and bounds -> AdvanceStrategicTick through the campaign mailbox -> one atomic campaign/event/news/cover/appraisal commit @@ -42,6 +43,15 @@ the campaign revision and world time untouched. Background inference checks live-turn pressure before launch and again before commit; return catch-up uses the same command path with player-turn priority. +Resolution-demand focal IDs are salience hints, not partition commands. They +cannot create mandatory singleton cells or exceed the configured budget. Cell +Projectors receive decision-relevant situation state; cell Interpreters receive +exact permissions and the narrative products. Membership and revision bindings +are derived by the runtime, so a model is never asked to copy an invariant that +the planner already owns. Stable prompt prefixes are deliberately placed before +dynamic state, and provider receipts expose per-attempt token/cache usage plus +bounded local validation failures. + Population scale uses reversible individuation: ```text diff --git a/notes/ghostlight-implementation-plan.md b/notes/ghostlight-implementation-plan.md index b79bedb..9579c7e 100644 --- a/notes/ghostlight-implementation-plan.md +++ b/notes/ghostlight-implementation-plan.md @@ -28,20 +28,24 @@ a 1–32 player budget, persistent pins, approval-gated gestalt fission, graph a cover receipts, and a separate operator provider-concurrency limit. The specific authority map is `docs/architecture/ghostlight-multiresolution-agency.md`. -The implementation cut is closed. Final acceptance evidence covers hosted -VoidBot compilation, invite isolation, automatic gestalt presence, three NPC -reactions, a 13.57-second four-actor parallel wave, model-driven institutional, -gestalt, and remote-actor away simulation, exact-channel news, full workspace -tests, legacy Pallas/Lucent/Corvid validation, CultMesh publication, explicit -process restart, and exact release provenance. Future work belongs in a new -post-MVP plan rather than silently extending this one. +The implementation is in acceptance hardening. The currently deployed Starfire +process is a known older immutable release; the working candidate is not live +until its exact commit, binary hash, process, CultMesh projection, firewall, and +restart evidence agree. This pass makes model work inspectable and cheaper: +provider attempts expose prompt/completion/cache usage and exact local failures; +stable prefixes precede dynamic context; world and agency compilation are +separate stages; Projectors receive situation state while Interpreters receive +exact permissions; deterministic cell bindings are attached by the runtime. -The multiresolution release is live on Starfire. Its deployment smoke selected -three isolated cells, committed three material offscreen events and three -accessible news items in one wave, preserved the player, and wrote a disposable -CultCache witness under `acceptance/strategic-20260817-073632`. The fixture's -default budget did not force aggregation; the 20-plus-faction budget matrix is -the aggregation proof. +Live local evidence now covers grounded VoidBot compilation, a four-actor wave, +impossible and receipted d20 actions, grounded narration, strategic cells, and a +24-faction budget-4 wave. The first scale baseline used 37,327 prompt tokens and +17.81 seconds. After the authority/context cuts, the same complete four-cell +cover used 20,760 prompt tokens and 14.38 seconds, with 13 of 13 stages valid on +their first attempt, two material institutional consequences, exact constituent +authority, and no player mutation. Remaining work is authenticated surface and +lifecycle acceptance, away/live concurrency, exact deployment, and final +regression/provenance verification. ## Prior research-program phase diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 9712814..8e59a21 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -81,3 +81,4 @@ {"ts":"2026-08-16T21:58:30+00:00","type":"architecture","status":"accepted","branch":"codex/ghostlight-dungeon-mvp","note":"Live acceptance falsified split NPC initiative ownership: the old begin commit could survive a later malformed assessment. ResolveNpcAction now validates the selected proposal and same-revision assessment, obtains the server d20, applies the typed effect, consumes sibling proposals, and persists receipts in one WorldKernel commit. The assessor now receives exact present-actor IDs and gets one same-snapshot local-semantic correction; tests prove an invented actor leaves revision and pending proposals unchanged."} {"ts":"2026-08-17T09:30:12+02:00","type":"implementation","status":"ok","branch":"codex/ghostlight-dungeon-mvp","note":"The flat strategic proposer is removed. Ghostlight now compiles a complete global agency skeleton, derives deterministic connected cohesive/arena covers under player budget and pins, runs one Ghostlight-owned Projector-Persona-Interpreter membrane per cell, validates exact constituent knowledge/authority/topology and all model receipts, and commits the whole strategic wave atomically. Approval-gated fission preserves parent lineage and member deltas; detail debt provides quiet-world fairness. Fifty-two dungeon tests and all workspace tests pass; the optimized 1,000-subject budget-8 partition completes in about 50 ms, below the 100 ms contract. Provider concurrency has a separate operator epoch and cannot repartition or advance fiction."} {"ts":"2026-08-17T09:38:18+02:00","type":"deployment","status":"ok","branch":"codex/ghostlight-dungeon-mvp","note":"Starfire activated the immutable multiresolution release from commit bf586b90d0bad28816ec1cdf99ac74c7d53bf3f8 with binary SHA-256 9469f539a9e309cf3af149fd63efaff61170a7fa0a90cfb4f00043d919c4b193. Typed health matched the release and DeepSeek was ready. A disposable live strategic-cell wave completed in 19.55 seconds with three selected cells, three offscreen events, three exact-channel news items, and no player movement. Witness: F:\\GameCult\\GhostlightDungeon\\acceptance\\strategic-20260817-073632\\campaign.cc. The default-budget fixture exercised cell isolation and atomicity; aggregation budgets remain proven by the deterministic 20-plus-faction matrix."} +{"ts":"2026-08-17T15:20:00Z","type":"verification","status":"ok","branch":"codex/ghostlight-dungeon-mvp","note":"Live DeepSeek acceptance drove a 24-faction global agency skeleton through a budget-4 cover: all subjects appeared exactly once in four connected cells, three cross-faction cells remained arenas, two exact-constituent institutional consequences committed atomically, and the absent player was unchanged. Cutting model ownership of focal overage and deterministic cell bindings, splitting Projector situation context from Interpreter permissions, and stabilizing prompt prefixes reduced prompt use from 37,327 tokens/17.81s to 20,760 tokens/14.38s; all 13 stages validated first try. Witness: F:\\GameCult\\GhostlightDungeon\\acceptance\\gestalt-scale-20260817-151658\\result.json."} diff --git a/state/map.yaml b/state/map.yaml index 9989fe6..498c461 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -71,6 +71,9 @@ live_architecture: - Gestalt Personas own shared population state; first-relevance individuation and later folding are revisioned WorldKernel commits, and durable member deltas preserve specific people between appearances. - The multiresolution agency graph derives a connected cohesive/arena cell cover from canonical actors, institutions, and gestalt leaves under a player-selected 1–32 budget. - Model-driven strategic cell waves can change remote actors, institutions, gestalts, clocks, and exact-channel news while the absent player remains outside their write authority; the entire wave validates and commits atomically. + - Resolution-demand focal IDs are salience hints only; model output cannot force singleton cells or override the player-selected Persona-cell budget. + - Projectors receive decision-relevant situation state, Personas receive only lived narrative, and Interpreters receive exact action permissions; runtime-owned cell membership and revisions are bound locally rather than copied by a model. + - Model-stage receipts expose per-attempt provider identity, latency, validation errors, and prompt/completion/cache token usage without storing reasoning content. - Budget and pins own `resolution_epoch`; provider concurrency owns a separate configuration epoch and cannot repartition or advance fiction. - Approval-gated gestalt fission creates explicit child leaves plus `other/unknown`, preserves inactive parent lineage, and never erases member deltas. - Existing v0 training fixtures are regression evidence and have no runtime write authority. @@ -257,6 +260,6 @@ data_flow: - If state grows faster than understanding, cut it back. current_status: - summary: GhostlightDungeon is the active MVP program. The approval-gated compiler persists exact VoidBot evidence, canon candidates, bounded topology, a global agency skeleton, gestalt baselines, and durable member deltas. Fiction-first player and NPC attempts use deterministic initiative, model assessment, server-side d20, and prevalidated typed outcome deltas. Present NPCs appraise events in parallel; gestalt populations materialize durable individuals and fold them back without losing identity. Ghostlight owns the generalized Persona projection membrane and Epiphany consumes it at an exact Git revision. CampaignRegistry isolates per-campaign stores/mailboxes and sessions. CultMesh/Eve publication owns hosted state sight. Away-time ticks now project demand, select a connected budgeted cohesive/arena cover, run one private Persona membrane per cell, validate exact constituent knowledge and authority, and commit the whole strategic wave atomically. Invalid covers, malformed cells, stale epochs, player puppeting, borrowed secrets, invented IDs, and unreachable movement cannot mutate state. - next_action: Preserve the deployed multiresolution release and acceptance receipts, then treat additional rulesets, Vault adapters, multiplayer, and richer Persona projections as post-MVP work requiring a new authority map. + summary: GhostlightDungeon is in acceptance hardening. The local candidate adds exact model-attempt usage/cache/error receipts, split world/agency compilation, provenance demotion for unsupported model facts, authority-shaped Persona contexts, and runtime-derived strategic cell bindings. A live 24-faction budget-4 wave covered every subject exactly once in four connected cells, committed two exact-constituent consequences without player mutation, and reduced prompt use from 37,327 to 20,760 tokens while all 13 stages validated first try. The active Starfire daemon remains an older immutable release until the candidate is committed, deployed, and proven. + next_action: Commit and push the candidate, run authenticated browser/HTTP and lifecycle/concurrency acceptance in an isolated runtime, then deploy the exact commit and verify restart, LAN/firewall, CultMesh, persistence, VoidBot, DeepSeek, and release provenance. gestalt_population: Gestalt Personas own shared population baselines; persistent member deltas own named individuality; WorldKernel materialization and approval-gated fission preserve lineage and identity. Simulation cells are derived covers only.