Prove model-driven away simulation

This commit is contained in:
Meta Vens 2026-08-16 23:37:52 +02:00
commit 0422f93f42
4 changed files with 297 additions and 12 deletions

View file

@ -0,0 +1,225 @@
#[cfg(not(windows))]
fn main() -> anyhow::Result<()> {
anyhow::bail!("the live strategic smoke uses Starfire's DPAPI credential")
}
#[cfg(windows)]
#[tokio::main]
async fn main() -> anyhow::Result<()> {
use chrono::Utc;
use ghostlight_dungeon::{
domain::{TickSource, WorldCommand},
kernel::{CommandResult, WorldKernel},
model::{DeepSeekPort, ModelPort},
persistence::CampaignStore,
scheduler::propose_strategic_tick,
};
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!("strategic-{}", Utc::now().format("%Y%m%d-%H%M%S")));
std::fs::create_dir_all(&root)?;
let campaign = strategic_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<dyn ModelPort> = Arc::new(DeepSeekPort::from_machine_dpapi(secret)?);
let started = Instant::now();
let (plan, output) = propose_strategic_tick(model.as_ref(), &campaign).await?;
if plan.institution_actions.is_empty()
&& plan.gestalt_actions.is_empty()
&& plan.actor_moves.is_empty()
{
anyhow::bail!(
"strategic model proposed no material offscreen change: {}",
output.narrative
);
}
store.insert(
"persona_stage_receipt.v1",
"ghostlight.persona_stage_receipt.v1",
&output.receipt.output_hash,
&output.receipt,
)?;
let kernel = WorldKernel::start(store.clone());
let committed = kernel
.command(WorldCommand::AdvanceStrategicTick {
expected_revision: 0,
source: TickSource::Scheduler,
plan: Some(plan.clone()),
model_receipt_hash: Some(output.receipt.output_hash.clone()),
})
.await?;
let CommandResult::Committed {
campaign: advanced, ..
} = &committed
else {
anyhow::bail!("strategic command did not commit")
};
if advanced.actors[&advanced.player_actor_id].location_id != player_location {
anyhow::bail!("strategic tick puppeted the absent player")
}
if advanced.news.is_empty() {
anyhow::bail!("accessible offscreen events produced no gated news")
}
let result = serde_json::json!({
"schema":"ghostlight.live_strategic_smoke.v1",
"campaign_id":campaign.id,
"elapsed_seconds":started.elapsed().as_secs_f64(),
"model_receipt_hash":output.receipt.output_hash,
"plan":plan,
"event_count":advanced.events.len(),
"news_count":advanced.news.len(),
"player_location_unchanged":true,
"commit":committed,
"store":root.join("campaign.cc")
});
std::fs::write(
root.join("result.json"),
serde_json::to_vec_pretty(&result)?,
)?;
println!("{}", serde_json::to_string_pretty(&result)?);
Ok(())
}
#[cfg(windows)]
fn strategic_campaign() -> ghostlight_dungeon::domain::Campaign {
use chrono::{Duration, Utc};
use ghostlight_dungeon::domain::*;
use std::collections::{BTreeMap, BTreeSet};
fn actor(id: &str, name: &str, location_id: &str, goal: &str) -> ActorState {
ActorState {
id: id.into(),
name: name.into(),
location_id: location_id.into(),
capabilities: BTreeSet::from(["ordinary travel".into()]),
knowledge: BTreeSet::new(),
equipment: BTreeSet::new(),
conditions: BTreeSet::new(),
obligations: BTreeSet::new(),
relationships: BTreeMap::new(),
goals: vec![goal.into()],
memories: vec![],
}
}
let now = Utc::now();
let mut player = actor("player", "Mediator", "room", "rest");
player.knowledge.insert("station radio".into());
Campaign {
schema: "ghostlight.campaign.v1".into(),
id: uuid::Uuid::new_v4(),
name: "Strategic live 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([
(
"room".into(),
Location {
id: "room".into(),
name: "Player quarters".into(),
container_id: None,
routes: BTreeMap::new(),
persistent_features: vec![],
},
),
(
"depot".into(),
Location {
id: "depot".into(),
name: "Supply depot".into(),
container_id: None,
routes: BTreeMap::from([(
"yard".into(),
Route {
destination_id: "yard".into(),
distance: "one hour".into(),
travel_minutes: 60,
},
)]),
persistent_features: vec!["sealed reserve crates".into()],
},
),
(
"yard".into(),
Location {
id: "yard".into(),
name: "Workers' yard".into(),
container_id: None,
routes: BTreeMap::from([(
"depot".into(),
Route {
destination_id: "depot".into(),
distance: "one hour".into(),
travel_minutes: 60,
},
)]),
persistent_features: vec!["idle loading cranes".into()],
},
),
]),
actors: BTreeMap::from([
("player".into(), player),
(
"runner".into(),
actor("runner", "Depot runner", "depot", "warn the workers"),
),
]),
institutions: BTreeMap::from([(
"board".into(),
InstitutionState {
id: "board".into(),
name: "Station board".into(),
resources: vec!["reserve shipment".into()],
goals: vec!["contain the supply dispute".into()],
posture: "deliberating".into(),
},
)]),
clocks: BTreeMap::from([(
"shortage".into(),
WorldClock {
id: "shortage".into(),
label: "Supply shortage".into(),
progress: 1,
threshold: 4,
consequence: "the yard stops work".into(),
},
)]),
facts: BTreeMap::new(),
transcript: vec![],
last_player_activity: now - Duration::hours(2),
pending_ticks: 1,
away_ticks_processed: 0,
events: vec![],
news: vec![],
canon_candidates: BTreeMap::new(),
gestalts: BTreeMap::from([(
"workers".into(),
GestaltPersonaState {
schema: "ghostlight.gestalt_persona_state.v1".into(),
id: "workers".into(),
name: "Yard workers".into(),
version: 0,
home_location_id: "yard".into(),
shared_capabilities: BTreeSet::from(["operate loading cranes".into()]),
shared_knowledge: BTreeSet::from(["two deliveries are missing".into()]),
resources: BTreeSet::from(["union hall".into()]),
goals: vec!["secure the missing supplies".into()],
pressures: vec!["the next shift may refuse work".into()],
},
)]),
gestalt_members: BTreeMap::new(),
pending_world_proposals: vec![],
}
}

View file

@ -276,12 +276,10 @@ fn execute(
};
let player = campaign.actors.get(&campaign.player_actor_id);
for event in &tick_events {
let accessible = event.public_channels.iter().find(|channel| {
player.is_some_and(|actor| {
actor.knowledge.contains(*channel)
|| actor.equipment.contains("communications")
})
});
let accessible = event
.public_channels
.iter()
.find(|channel| player.is_some_and(|actor| actor.knowledge.contains(*channel)));
if let Some(channel) = accessible {
campaign.news.push(crate::domain::NewsIssue {
id: format!("news:{}", event.id),

View file

@ -55,20 +55,23 @@ pub async fn run_validated_stage_with_timeout(
request: &ModelStageRequest,
timeout: std::time::Duration,
) -> Result<ModelStageOutput> {
let request_bytes = serde_json::to_vec(request)?;
let validator = request
.output_schema
.as_ref()
.map(jsonschema::validator_for)
.transpose()
.map_err(|error| anyhow!("invalid local output schema: {error}"))?;
let mut attempt_request = request.clone();
for attempt in 0..2 {
let started = Instant::now();
let output = tokio::time::timeout(timeout, port.run(request))
let output = tokio::time::timeout(timeout, port.run(&attempt_request))
.await
.map_err(|_| anyhow!("model stage {} timed out", request.stage))??;
if output.trim().is_empty() {
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.",
);
continue;
}
return Err(anyhow!("model returned empty output twice"));
@ -79,17 +82,26 @@ pub async fn run_validated_stage_with_timeout(
let validation = validator.as_ref().expect("structured validator");
if let Err(error) = validation.validate(&value) {
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."
));
continue;
}
return Err(anyhow!("model returned schema-invalid JSON twice: {error}"));
}
Some(value)
}
Err(_) if attempt == 0 => continue,
Err(error) if attempt == 0 => {
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}")),
},
None => None,
};
let request_bytes = serde_json::to_vec(&attempt_request)?;
return Ok(ModelStageOutput {
narrative: output.clone(),
structured,
@ -120,6 +132,9 @@ mod tests {
}
struct NeverReturns;
struct CorrectionAware {
calls: AtomicUsize,
}
#[async_trait]
impl ModelPort for NeverReturns {
@ -147,6 +162,23 @@ mod tests {
}
}
#[async_trait]
impl ModelPort for CorrectionAware {
async fn run(&self, request: &ModelStageRequest) -> Result<String> {
assert_eq!(request.snapshot_binding, "campaign:one:revision:4");
self.calls.fetch_add(1, Ordering::SeqCst);
Ok(if request.lived_stream.contains("LOCAL VALIDATOR") {
r#"{"answer":"corrected"}"#.into()
} else {
r#"{"wrong":"shape"}"#.into()
})
}
fn provider(&self) -> &'static str {
"fixture"
}
}
#[tokio::test]
async fn schema_invalid_json_gets_one_same_snapshot_retry() {
let port = InvalidThenValid {
@ -171,6 +203,30 @@ mod tests {
assert_eq!(output.receipt.snapshot_binding, request.snapshot_binding);
}
#[tokio::test]
async fn structured_retry_carries_local_failure_without_rebinding_snapshot() {
let port = CorrectionAware {
calls: AtomicUsize::new(0),
};
let request = ModelStageRequest {
stage: "typed-stage".into(),
model: "fixture".into(),
snapshot_binding: "campaign:one:revision:4".into(),
lived_stream: "fixture".into(),
output_schema: Some(serde_json::json!({
"type":"object",
"additionalProperties":false,
"required":["answer"],
"properties":{"answer":{"type":"string"}}
})),
source_receipt_ids: vec![],
};
let output = run_validated_stage(&port, &request).await.unwrap();
assert_eq!(port.calls.load(Ordering::SeqCst), 2);
assert_eq!(output.structured.unwrap()["answer"], "corrected");
assert_eq!(output.receipt.snapshot_binding, request.snapshot_binding);
}
#[tokio::test]
async fn provider_timeout_returns_no_stage_output() {
let request = ModelStageRequest {

View file

@ -31,12 +31,17 @@ pub async fn propose_strategic_tick(
"world_time":campaign.world_time,
"tick_hours":campaign.tick_hours,
"locations":campaign.locations,
"player_information_access": campaign.actors.get(player_id).map(|actor| serde_json::json!({
"knowledge_channels": actor.knowledge,
"equipment": actor.equipment
})),
"remote_actors":actors,
"institutions":campaign.institutions,
"gestalts":campaign.gestalts,
"clocks":campaign.clocks,
"recent_events":campaign.events.iter().rev().take(12).collect::<Vec<_>>()
});
let schema = serde_json::to_value(schema_for!(StrategicTickPlan))?;
let output = run_validated_stage(
model,
&ModelStageRequest {
@ -44,10 +49,11 @@ pub async fn propose_strategic_tick(
model: "deepseek-v4-flash".into(),
snapshot_binding: format!("campaign:{}:revision:{}", campaign.id, campaign.revision),
lived_stream: format!(
"Propose one bounded offscreen strategic tick. Institutions, remote actors, and gestalt populations act in their own interests. Do not control, move, injure, or directly target the absent player. Use only supplied IDs. Actor movement must use a direct listed route whose travel time fits inside tick_hours. Keep summaries concrete. Pressure additions are branch-local population pressure, not new canon knowledge. Empty arrays are valid when nobody has a credible action. Return only the schema JSON.\nSTATE:\n{}",
serde_json::to_string(&context)?
"Propose one bounded offscreen strategic tick. Institutions, remote actors, and gestalt populations act in their own interests. At least one supplied non-player power with a credible goal, pressure, resource, or reachable movement must act; use empty arrays only when the supplied state genuinely affords no action. Do not control, move, injure, or directly target the absent player. Use only supplied IDs. Actor movement must use a direct listed route whose travel time fits inside tick_hours. Keep summaries concrete. Pressure additions are branch-local population pressure, not new canon knowledge. For each action, public_channels names concrete information mechanisms through which that event can later become known (radio, newspaper, courier, rumor network); leave it empty only for a genuinely secret event. When a public event credibly travels through one of player_information_access.knowledge_channels, copy that channel string exactly. The kernel independently gates news by exact channel access. Return only one JSON object matching the supplied schema.\nSTATE:\n{}\nOUTPUT JSON SCHEMA:\n{}",
serde_json::to_string(&context)?,
serde_json::to_string_pretty(&schema)?
),
output_schema: Some(serde_json::to_value(schema_for!(StrategicTickPlan))?),
output_schema: Some(schema),
source_receipt_ids: campaign.branch_origin.evidence_receipt_ids.clone(),
},
)