Protect player and compiler projection boundaries

This commit is contained in:
Meta Vens 2026-08-17 17:45:13 +02:00
commit 66b7986cca
17 changed files with 803 additions and 236 deletions

View file

@ -81,7 +81,7 @@ impl ActionAssessor {
"maximum":10
});
let base_prompt = format!(
"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{}",
"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. When an outcome directly reveals information to the acting actor, actor_knowledge_additions must contain the specific observed finding, not a vague claim that a reading or clue exists; copy each exact finding verbatim into that outcome's visible stake. Such findings become provisional branch facts on commit, so do not invent remote events, hidden actors, unsupported proper nouns, or conclusions beyond the effect ceiling. Keep a delta empty only when the outcome truly 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)?,
@ -116,13 +116,13 @@ impl ActionAssessor {
.ok_or_else(|| anyhow!("assessor returned no typed proposal"))?,
)?;
validate_proposal(&proposal, &allowed_references)?;
for effect in [
&proposal.strong_effect,
&proposal.success_effect,
&proposal.mixed_effect,
&proposal.failure_effect,
for (effect, stake) in [
(&proposal.strong_effect, &proposal.success_stake),
(&proposal.success_effect, &proposal.success_stake),
(&proposal.mixed_effect, &proposal.mixed_stake),
(&proposal.failure_effect, &proposal.failure_stake),
] {
validate_effect(campaign, actor, effect)?;
validate_effect(campaign, actor, effect, stake)?;
}
Ok(proposal)
})();
@ -130,7 +130,7 @@ impl ActionAssessor {
Ok(proposal) => break (proposal, out),
Err(error) if attempts == 1 => {
correction = format!(
"\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS ASSESSMENT: {error}\nReturn a corrected complete assessment against the same snapshot. Copy every actor and destination ID exactly from the supplied state; leave typed deltas empty when no legal mutation is needed."
"\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS ASSESSMENT: {error}\nReturn a corrected complete assessment against the same snapshot. Copy every actor and destination ID exactly from the supplied state. Bind specific directly observed findings to the acting actor and repeat them verbatim in the matching visible stake; otherwise leave the typed delta empty."
);
}
Err(error) => {
@ -223,10 +223,12 @@ pub(crate) fn validate_effect(
campaign: &Campaign,
acting_actor: &crate::domain::ActorState,
effect: &WorldEffectDelta,
stake: &str,
) -> Result<()> {
let affected = effect
.actor_conditions
.keys()
.chain(effect.actor_knowledge_additions.keys())
.chain(effect.actor_relationship_updates.keys());
for id in affected {
let target = campaign
@ -245,6 +247,22 @@ pub(crate) fn validate_effect(
return Err(anyhow!("outcome condition delta is contradictory"));
}
}
for (actor_id, additions) in &effect.actor_knowledge_additions {
if actor_id != &acting_actor.id
|| additions.is_empty()
|| additions.len() > 4
|| additions.iter().any(|finding| {
finding.trim().is_empty()
|| finding.chars().count() > 500
|| acting_actor.knowledge.contains(finding)
|| !stake.contains(finding)
})
{
return Err(anyhow!(
"outcome knowledge must be new, bounded, directly observed by the acting actor, and visible verbatim in its stake"
));
}
}
for relationships in effect.actor_relationship_updates.values() {
if relationships.iter().any(|(id, value)| {
(!campaign.actors.contains_key(id) && !campaign.institutions.contains_key(id))

View file

@ -1,9 +1,9 @@
use crate::{
domain::{
ActorState, AgencyAxis, AgencyRelation, AgencyRelationKind, AgencySubjectKind,
BranchOrigin, Campaign, FactScope, GestaltMemberDelta, GestaltPersonaState,
InstitutionState, Location, VaultEvidenceReceipt, WorldClock, WorldCompilePreview,
WorldFact,
BranchOrigin, Campaign, EvidenceCoverage, EvidenceUseLane, FactScope, GestaltMemberDelta,
GestaltPersonaState, InstitutionState, Location, VaultEvidenceReceipt, WorldClock,
WorldCompilePreview, WorldFact,
},
model::{
ModelPort, ModelStageReceipt, ModelStageRequest, run_validated_stage,
@ -103,6 +103,11 @@ struct RetrievalQueryPlan {
queries: Vec<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
struct EvidenceUsePlan {
coverage: Vec<EvidenceCoverage>,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
struct CompiledSeed {
title: String,
@ -262,16 +267,19 @@ impl WorldCompiler {
)
.await?;
let receipts = self.retrieve_all(&queries, &start.when, 8).await?;
let (evidence_coverage, relevance_receipts) =
self.classify_evidence(&start, &receipts).await?;
let scoped_evidence = scoped_evidence_text(&receipts, &evidence_coverage);
let shared_prefix = format!(
"SOURCE-GROUNDED WORLD COMPILATION\nSTART:\n{}\nEVIDENCE:\n{}\n\n",
"SOURCE-GROUNDED WORLD COMPILATION\nSTART:\n{}\nSCOPED EVIDENCE:\n{}\n\n",
serde_json::to_string(&start)?,
evidence_text(&receipts)
scoped_evidence
);
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."
"{shared_prefix}Compile a bounded playable region with stable topology, local actors, populations, clocks, and only those remote institutions that have a direct causal relationship to this requested start. Evidence marked direct_seed may shape the local situation. Evidence marked setting_background may establish general history, mechanics, or institutions, but must not import its story-specific cast, incident, clock, location state, goals, or institutional posture into the current branch. A matching place name or era alone does not make another source episode current. When the evidence cannot ground a requested local detail, keep the local cast sparse, mark reversible texture provisional_local, and list the material gap instead of borrowing a nearby story. Do not eagerly invent remote settlements, routes, or people. Emit only supported canon facts. A canon_baseline fact must cite one or more exact receipt_id values printed in SCOPED 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 sources = receipt_ids_for_coverage(&receipts, &evidence_coverage);
let mut compiler_receipts = Vec::new();
let mut correction = String::new();
let (seed, campaign) = loop {
@ -310,7 +318,7 @@ 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.",
"MULTIRESOLUTION AGENCY SKELETON\nCompile only 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. Derive facets only from the supplied roster fields; use an explicit unknown value when they do not 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 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))?;
@ -359,6 +367,7 @@ impl WorldCompiler {
}
}
let mut model_receipts = vec![retrieval_receipt];
model_receipts.extend(relevance_receipts);
model_receipts.extend(compiler_receipts);
Ok((
WorldCompilePreview {
@ -366,6 +375,7 @@ impl WorldCompiler {
title: seed.title,
campaign,
evidence_receipts: receipts,
evidence_coverage,
gaps: seed.gaps,
branch_assumptions: seed.branch_assumptions,
requires_approval: true,
@ -788,6 +798,96 @@ impl WorldCompiler {
Ok((normalized, output.receipt))
}
async fn classify_evidence(
&self,
start: &CustomStart,
receipts: &[VaultEvidenceReceipt],
) -> Result<(Vec<EvidenceCoverage>, Vec<ModelStageReceipt>)> {
let mut source_briefs = BTreeMap::new();
for witness in receipts.iter().flat_map(|receipt| &receipt.witnesses) {
source_briefs
.entry(witness.source_id.clone())
.or_insert_with(|| {
serde_json::json!({
"source_id":witness.source_id,
"authority_lane":witness.authority_lane,
"temporal_scope":witness.temporal_scope,
"excerpt":witness.excerpt.chars().take(1_200).collect::<String>(),
})
});
}
let expected: BTreeSet<_> = source_briefs.keys().cloned().collect();
// Keep the provider schema stable across campaigns for prefix-cache reuse.
// Exact membership and cardinality belong to the local validator below.
let schema = serde_json::to_value(schema_for!(EvidenceUsePlan))?;
let base_prompt = format!(
"OUTPUT JSON SCHEMA (follow exactly):\n{}\n\nClassify every supplied source exactly once for this requested custom start. direct_seed means the source directly supports this specific local place, era, role, goal, pressure, or a causal actor/institution that should actually be present. setting_background means the source supports general setting history, mechanics, geography, or institution identity, but its story-specific cast, incident, clocks, goals, and postures must not be imported into the new branch. excluded means it is merely nearby in search space. A shared place name or era alone does not make another story episode current. Keep each rationale to one short sentence.\nSTART:\n{}\nSOURCES:\n{}",
serde_json::to_string(&schema)?,
serde_json::to_string(start)?,
serde_json::to_string(&source_briefs.values().collect::<Vec<_>>())?,
);
let source_receipt_ids = receipt_ids(receipts);
let mut stage_receipts = Vec::new();
let mut correction = String::new();
for attempt in 0..2 {
let output = run_validated_stage(
self.model.as_ref(),
&ModelStageRequest {
stage: "evidence_relevance".into(),
model: self.retrieval_model.clone(),
snapshot_binding: "custom-start".into(),
lived_stream: format!("{base_prompt}{correction}"),
output_schema: Some(schema.clone()),
source_receipt_ids: source_receipt_ids.clone(),
temperature: Some(0.0),
max_output_tokens: Some(2_500),
},
)
.await?;
let candidate = output
.structured
.clone()
.ok_or_else(|| anyhow!("evidence classifier returned no structured output"))
.and_then(|value| serde_json::from_value::<EvidenceUsePlan>(value).map_err(Into::into))
.and_then(|plan| {
let actual = plan
.coverage
.iter()
.map(|item| item.source_id.clone())
.collect::<BTreeSet<_>>();
if plan.coverage.len() != expected.len()
|| actual != expected
|| plan.coverage.iter().any(|item| item.rationale.trim().is_empty())
{
return Err(anyhow!(
"evidence classifier must cover every exact source once with a rationale"
));
}
Ok(plan.coverage)
});
let mut receipt = output.receipt;
match candidate {
Ok(coverage) => {
stage_receipts.push(receipt);
return Ok((coverage, stage_receipts));
}
Err(error) if attempt == 0 => {
mark_semantic_invalid(&mut receipt, &error);
stage_receipts.push(receipt);
correction = format!(
"\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS CLASSIFICATION: {error}\nReturn one corrected complete classification against the same START and SOURCES."
);
}
Err(error) => {
return Err(anyhow!(
"evidence classifier failed local validation after one correction: {error}"
));
}
}
}
unreachable!()
}
async fn structured(
&self,
stage: &str,
@ -917,6 +1017,76 @@ fn evidence_text(receipts: &[VaultEvidenceReceipt]) -> String {
.collect::<Vec<_>>()
.join("\n\n")
}
fn scoped_evidence_text(
receipts: &[VaultEvidenceReceipt],
coverage: &[EvidenceCoverage],
) -> String {
let coverage = coverage
.iter()
.map(|item| (item.source_id.as_str(), item))
.collect::<BTreeMap<_, _>>();
let mut seen = BTreeSet::new();
receipts
.iter()
.flat_map(|receipt| {
receipt
.witnesses
.iter()
.map(move |witness| (receipt.id.as_str(), witness))
})
.filter_map(|(receipt_id, witness)| {
let use_plan = coverage.get(witness.source_id.as_str())?;
if use_plan.lane == EvidenceUseLane::Excluded
|| !seen.insert((
witness.source_id.clone(),
witness.exact_locator.clone(),
witness.content_hash.clone(),
))
{
return None;
}
let lane = match use_plan.lane {
EvidenceUseLane::DirectSeed => "direct_seed",
EvidenceUseLane::SettingBackground => "setting_background",
EvidenceUseLane::Excluded => unreachable!(),
};
Some(format!(
"[usage_lane={} | rationale={} | receipt_id={} | source={} | locator={} | content_hash={}] {}",
lane,
use_plan.rationale,
receipt_id,
witness.source_id,
witness.exact_locator,
witness.content_hash,
witness.excerpt
))
})
.collect::<Vec<_>>()
.join("\n\n")
}
fn receipt_ids_for_coverage(
receipts: &[VaultEvidenceReceipt],
coverage: &[EvidenceCoverage],
) -> Vec<String> {
let included_sources = coverage
.iter()
.filter(|item| item.lane != EvidenceUseLane::Excluded)
.map(|item| item.source_id.as_str())
.collect::<BTreeSet<_>>();
receipts
.iter()
.filter(|receipt| {
receipt
.witnesses
.iter()
.any(|witness| included_sources.contains(witness.source_id.as_str()))
})
.map(|receipt| receipt.id.clone())
.collect()
}
fn receipt_ids(receipts: &[VaultEvidenceReceipt]) -> Vec<String> {
receipts.iter().map(|r| r.id.clone()).collect()
}
@ -1403,6 +1573,13 @@ mod tests {
};
serde_json::json!({"queries":(1..=count).map(|index|format!("fixture grounded query {index}")).collect::<Vec<_>>()}).to_string()
}
"evidence_relevance" => serde_json::json!({
"coverage":[{
"source_id":"AetheriaLore:test.md",
"lane":"direct_seed",
"rationale":"The fixture source directly grounds the requested place."
}]
}).to_string(),
"world_openings" => serde_json::json!({"openings":[
{"id":"a","title":"Ash","era":"early","place":"ring","pressure":"strike","player_hook":"work","evidence_receipt_ids":[]},
{"id":"b","title":"Glass","era":"middle","place":"moon","pressure":"siege","player_hook":"survive","evidence_receipt_ids":[]},
@ -1565,9 +1742,19 @@ mod tests {
.iter()
.map(|receipt| receipt.stage.as_str())
.collect::<Vec<_>>(),
vec!["custom_retrieval_plan", "world_compile", "agency_compile"]
vec![
"custom_retrieval_plan",
"evidence_relevance",
"world_compile",
"agency_compile"
]
);
assert!(preview.requires_approval);
assert_eq!(preview.evidence_coverage.len(), 1);
assert_eq!(
preview.evidence_coverage[0].lane,
EvidenceUseLane::DirectSeed
);
assert_eq!(preview.campaign.revision, 0);
assert_eq!(preview.campaign.locations.len(), 1);
assert_eq!(preview.campaign.canon_candidates.len(), 1);
@ -1626,6 +1813,60 @@ mod tests {
assert!(!text.contains("receipt_id=vault:receipt-two"));
}
#[test]
fn scoped_evidence_excludes_nearby_story_incidents_from_world_context() {
let direct = VaultEvidenceReceipt {
schema: "ghostlight.vault_evidence_receipt.v1".into(),
id: "vault:direct".into(),
provider: "fixture".into(),
query_hash: "sha256:direct".into(),
witnesses: vec![SourceWitness {
source_id: "AetheriaLore:place.md".into(),
exact_locator: "place.md:1".into(),
content_hash: "sha256:place".into(),
excerpt: "The requested station exists.".into(),
authority_lane: "AetheriaLore".into(),
temporal_scope: "fixture".into(),
}],
retrieved_at: Utc::now(),
};
let nearby_story = VaultEvidenceReceipt {
schema: "ghostlight.vault_evidence_receipt.v1".into(),
id: "vault:story".into(),
provider: "fixture".into(),
query_hash: "sha256:story".into(),
witnesses: vec![SourceWitness {
source_id: "AetheriaLore:unrelated-story.md".into(),
exact_locator: "unrelated-story.md:1".into(),
content_hash: "sha256:story".into(),
excerpt: "An unrelated named cast has a crisis nearby.".into(),
authority_lane: "AetheriaLore".into(),
temporal_scope: "fixture".into(),
}],
retrieved_at: Utc::now(),
};
let receipts = vec![direct, nearby_story];
let coverage = vec![
EvidenceCoverage {
source_id: "AetheriaLore:place.md".into(),
lane: EvidenceUseLane::DirectSeed,
rationale: "Directly grounds the requested station.".into(),
},
EvidenceCoverage {
source_id: "AetheriaLore:unrelated-story.md".into(),
lane: EvidenceUseLane::Excluded,
rationale: "The incident is unrelated to the requested start.".into(),
},
];
let text = scoped_evidence_text(&receipts, &coverage);
assert!(text.contains("The requested station exists."));
assert!(!text.contains("unrelated named cast"));
assert_eq!(
receipt_ids_for_coverage(&receipts, &coverage),
vec!["vault:direct"]
);
}
#[test]
fn agency_compile_schema_exposes_relation_strength_domain() {
let schema = serde_json::to_value(schema_for!(CompiledAgencySkeleton)).unwrap();

View file

@ -830,6 +830,8 @@ pub struct ConditionDelta {
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Default)]
pub struct WorldEffectDelta {
pub actor_conditions: BTreeMap<String, ConditionDelta>,
#[serde(default)]
pub actor_knowledge_additions: BTreeMap<String, BTreeSet<String>>,
pub actor_relationship_updates: BTreeMap<String, BTreeMap<String, String>>,
pub actor_moves: BTreeMap<String, String>,
pub clock_advances: BTreeMap<String, u8>,
@ -921,7 +923,24 @@ pub struct WorldCompilePreview {
pub title: String,
pub campaign: Campaign,
pub evidence_receipts: Vec<VaultEvidenceReceipt>,
#[serde(default)]
pub evidence_coverage: Vec<EvidenceCoverage>,
pub gaps: Vec<String>,
pub branch_assumptions: Vec<String>,
pub requires_approval: bool,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum EvidenceUseLane {
DirectSeed,
SettingBackground,
Excluded,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct EvidenceCoverage {
pub source_id: String,
pub lane: EvidenceUseLane,
pub rationale: String,
}

View file

@ -136,13 +136,13 @@ fn execute(
.actors
.get(&assessment.intent.actor_id)
.ok_or_else(|| KernelError::Invalid("assessment actor vanished".into()))?;
for effect in [
&assessment.strong_effect,
&assessment.success_effect,
&assessment.mixed_effect,
&assessment.failure_effect,
for (effect, stake) in [
(&assessment.strong_effect, &assessment.success_stake),
(&assessment.success_effect, &assessment.success_stake),
(&assessment.mixed_effect, &assessment.mixed_stake),
(&assessment.failure_effect, &assessment.failure_stake),
] {
crate::assessor::validate_effect(&campaign, actor, effect)
crate::assessor::validate_effect(&campaign, actor, effect, stake)
.map_err(|error| KernelError::Invalid(error.to_string()))?;
}
assessment
@ -719,13 +719,13 @@ fn execute(
"NPC assessment is stale or invalid".into(),
));
}
for effect in [
&assessment.strong_effect,
&assessment.success_effect,
&assessment.mixed_effect,
&assessment.failure_effect,
for (effect, stake) in [
(&assessment.strong_effect, &assessment.success_stake),
(&assessment.success_effect, &assessment.success_stake),
(&assessment.mixed_effect, &assessment.mixed_stake),
(&assessment.failure_effect, &assessment.failure_stake),
] {
crate::assessor::validate_effect(&campaign, actor, effect)
crate::assessor::validate_effect(&campaign, actor, effect, stake)
.map_err(|error| KernelError::Invalid(error.to_string()))?;
}
let actor_name = actor.name.clone();
@ -882,6 +882,25 @@ fn apply_world_effect(
actor.conditions.remove(value);
}
}
for (actor_id, additions) in &effect.actor_knowledge_additions {
let actor = campaign
.actors
.get_mut(actor_id)
.ok_or_else(|| KernelError::Invalid("outcome actor vanished".into()))?;
actor.knowledge.extend(additions.clone());
for finding in additions {
let fact_id = format!(
"fact:outcome:{:x}",
Sha256::digest(format!("{}:{finding}", campaign.id).as_bytes())
);
campaign.facts.entry(fact_id.clone()).or_insert(WorldFact {
id: fact_id,
statement: finding.clone(),
scope: FactScope::BranchLocal,
evidence_receipt_ids: vec![],
});
}
}
for (actor_id, relationships) in &effect.actor_relationship_updates {
campaign
.actors
@ -2551,6 +2570,25 @@ mod tests {
.await
.is_err()
);
let mut hidden_finding = assess(&seed, intent.clone());
hidden_finding
.success_effect
.actor_knowledge_additions
.insert(
"player".into(),
BTreeSet::from(["The hidden latch is broken.".into()]),
);
hidden_finding.digest = crate::assessor::assessment_digest(&hidden_finding).unwrap();
assert!(
kernel
.command(WorldCommand::Assess {
expected_revision: 0,
intent: intent.clone(),
proposal: Some(hidden_finding),
})
.await
.is_err()
);
let delta = WorldEffectDelta {
actor_conditions: BTreeMap::from([(
"player".into(),
@ -2559,9 +2597,17 @@ mod tests {
remove: BTreeSet::new(),
},
)]),
actor_knowledge_additions: BTreeMap::from([(
"player".into(),
BTreeSet::from(["The door brace is seated against the frame.".into()]),
)]),
..Default::default()
};
let mut valid = assess(&seed, intent.clone());
valid.success_stake =
"The door brace is seated against the frame. You become braced.".into();
valid.mixed_stake = valid.success_stake.clone();
valid.failure_stake = valid.success_stake.clone();
valid.strong_effect = delta.clone();
valid.success_effect = delta.clone();
valid.mixed_effect = delta.clone();
@ -2588,6 +2634,15 @@ mod tests {
.1;
assert_eq!(persisted.revision, 1);
assert!(persisted.actors["player"].conditions.contains("braced"));
assert!(
persisted.actors["player"]
.knowledge
.contains("The door brace is seated against the frame.")
);
assert!(persisted.facts.values().any(|fact| {
fact.statement == "The door brace is seated against the frame."
&& fact.scope == FactScope::BranchLocal
}));
}
fn resolution_stage(

View file

@ -1045,7 +1045,7 @@ async fn command(
.await
{
Ok(reaction) => {
let initiative = match resolve_npc_initiative(
let _initiative = match resolve_npc_initiative(
&state, &runtime, &reaction,
)
.await
@ -1069,7 +1069,10 @@ async fn command(
if let Err(error) = refresh_mesh(&state).await {
tracing::warn!(%error, "post-command CultMesh publication failed");
}
return Json(serde_json::json!({"primary":result,"presence":presence_result,"reaction_wave":reaction,"npc_initiative":initiative,"narration":narration})).into_response();
return Json(player_command_projection(
&result, narration,
))
.into_response();
}
Err(error) => {
return (
@ -1102,10 +1105,8 @@ async fn command(
if let Err(error) = refresh_mesh(&state).await {
tracing::warn!(%error, "post-command CultMesh publication failed");
}
return Json(
serde_json::json!({"primary":result,"presence":presence_result,"narration":narration}),
)
.into_response();
return Json(player_command_projection(&result, narration))
.into_response();
}
}
}
@ -1121,9 +1122,9 @@ async fn command(
if let Err(error) = refresh_mesh(&state).await {
tracing::warn!(%error, "post-command CultMesh publication failed");
}
Json(serde_json::json!({"result":result,"narration":narration})).into_response()
Json(player_command_projection(&result, narration)).into_response()
} else {
Json(result).into_response()
Json(player_command_projection(&result, None)).into_response()
}
}
Err(error) => {
@ -1166,7 +1167,9 @@ async fn command(
})
.await
{
Ok(result) => Json(result).into_response(),
Ok(result) => {
Json(player_command_projection(&result, None)).into_response()
}
Err(recompile_error) => (
StatusCode::CONFLICT,
Json(ErrorBody {
@ -1215,6 +1218,31 @@ async fn command(
}
}
fn player_command_projection(
result: &CommandResult,
narration: Option<NarrationProjection>,
) -> serde_json::Value {
match result {
CommandResult::Assessed { assessment } => serde_json::json!({
"kind":"assessed",
"assessment":assessment,
}),
CommandResult::Committed { receipt, .. } => serde_json::json!({
"kind":"committed",
"revision":receipt.revision,
"receipt":receipt,
"narration":narration,
}),
CommandResult::ResolutionUpdated { receipt, .. } => serde_json::json!({
"kind":"resolution_updated",
"receipt":receipt,
}),
CommandResult::Created { .. } => serde_json::json!({
"kind":"created",
}),
}
}
fn player_http_command_allowed(command: &WorldCommand, player_actor_id: &str) -> bool {
match command {
WorldCommand::Speak { actor_id, .. } => actor_id == player_actor_id,
@ -1996,4 +2024,28 @@ mod tests {
"player",
));
}
#[test]
fn player_command_projection_never_serializes_campaign_state() {
let campaign = seed("Private state");
let result = CommandResult::Committed {
receipt: ghostlight_dungeon::domain::WorldCommitReceipt {
schema: "ghostlight.world_commit_receipt.v1".into(),
campaign_id: campaign.id,
previous_revision: 0,
revision: 1,
command_kind: "attempt".into(),
committed_at: chrono::Utc::now(),
roll: None,
},
campaign,
};
let projection = player_command_projection(&result, None);
assert_eq!(projection["kind"], "committed");
assert_eq!(projection["revision"], 1);
let encoded = serde_json::to_string(&projection).unwrap();
assert!(!encoded.contains("Private state"));
assert!(!encoded.contains("actors"));
assert!(!encoded.contains("facts"));
}
}

View file

@ -21,8 +21,8 @@ impl Narrator {
) -> Result<(NarrationProjection, ModelStageReceipt)> {
let player = &campaign.actors[&campaign.player_actor_id];
let location = &campaign.locations[&player.location_id];
let recent_events: Vec<_> = campaign.events.iter().rev().take(8).cloned().collect();
let recent_turns: Vec<_> = campaign.transcript.iter().rev().take(12).cloned().collect();
let recent_events: Vec<_> = campaign.events.iter().rev().take(4).cloned().collect();
let latest_turn = campaign.transcript.last().cloned();
let visible_actors: Vec<_> = campaign
.actors
.values()
@ -37,10 +37,14 @@ impl Narrator {
.collect();
let public_slice = serde_json::json!({
"world_time": campaign.world_time,
"location": location,
"location": {
"id": location.id,
"name": location.name,
"persistent_features": location.persistent_features,
},
"visible_actors": visible_actors,
"recent_events": recent_events,
"recent_explicit_speech_and_stakes": recent_turns,
"latest_events": recent_events,
"latest_committed_turn": latest_turn,
});
let output = run_validated_stage(
self.model.as_ref(),
@ -52,7 +56,7 @@ impl Narrator {
campaign.id, campaign.revision
),
lived_stream: format!(
"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{}",
"Narrate only latest_committed_turn and any latest_events it directly caused, in concrete, concise second-person interactive-fiction prose. Location, time, and visible actors are grounding constraints, not a request to restate every field. Do not repeat older setup, list routes, or recap unrelated world state. 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, findings, 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,

View file

@ -26,6 +26,9 @@ The Rust runtime now contains the first honest world-compiler seam:
- role generation requires exactly three grounded roles;
- custom compilation emits a bounded typed campaign, evidence receipts, gaps,
branch assumptions, and an approval-required preview;
- custom compilation classifies every exact witness as direct seed, setting
background, or excluded before world generation, so a nearby story cannot
donate its cast, incident, clocks, or institutional posture to a new branch;
- deterministic seed validation rejects missing occupancy, dangling or
zero-time routes, invalid containment, invalid clocks, and missing players;
- approval alone submits `CreateCampaign`, which atomically stores the campaign
@ -547,6 +550,7 @@ Compilation is staged and approval-gated:
opening request
-> retrieval plan
-> exact evidence receipts
-> source-use classification: direct seed / setting background / excluded
-> three distinct openings or custom opening
-> three grounded roles or custom role
-> bounded region + institutional pressure graph
@ -558,6 +562,11 @@ opening request
Reversible local texture may enter as provisional branch fact. Material gaps in
geography, mechanics, institutions, or extraordinary capability require
approval. Canon candidates are review/export records and cannot edit the Vault.
The approval preview exposes the source-use coverage. Direct evidence may shape
the local seed; background evidence may constrain history, mechanics, or known
institutions; excluded evidence remains receipted but never enters the world
compiler prompt. This separation preserves provenance without making retrieved
adjacency into fictional causality.
### Fiction-first resolution
@ -572,6 +581,12 @@ receive no roll. Natural 20 and 1 shift one band and cannot cross impossibility
or the effect ceiling. Speech occurs as speech; persuasion, deception, and
intimidation are separate intended effects.
Informational attempts must preview the exact finding that becomes knowledge.
On resolution, only the acting character may receive those bounded knowledge
additions; the same statement is committed as a provisional branch fact. A
vague promise such as “identify any faults” is not a valid informational
outcome, and an unstated hidden finding cannot appear after the roll.
### Actor and world action loop
After a committed event, every affected present actor receives a parallel
@ -601,6 +616,13 @@ The TypeScript browser host pins Eve's browser lowering package and owns only
transport, sessions, and local rendering. It does not invent a parallel UI
state model.
The player HTTP command boundary returns a dedicated spoiler-safe projection:
assessments, public commit receipts, roll results, and narration. It never
serializes the canonical campaign snapshot. Full actor, institution, evidence,
and model-stage state belongs to the authenticated operator projection only.
Player and model strings enter the DOM through text nodes rather than HTML
insertion, and all laboratory inputs have programmatic labels.
The player surface includes compilation, transcript, composer, Assess/Attempt,
roll confirmation, Wait, character ledger, current place/time/pressure, news,
campaign management, fork/reset/export, and optional operator inspection.
@ -651,6 +673,13 @@ 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.
Prompt quality is judged by useful decision work per token, not prompt brevity
alone. Each stage receives one stable, cacheable contract followed by the
smallest revision-bound context that can support its decision. Receipts make
prompt, completion, cache-hit, and cache-miss tokens visible per attempt so
acceptance can reject stages that spend heavily while producing no meaningful
appraisal, state proposal, or player-facing consequence.
Live model allocation:
- `deepseek-v4-flash`, non-thinking: projection, interpretation, retrieval

View file

@ -367,11 +367,22 @@ focal hints from overruling the Persona-cell budget. Live proof under
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.
The authenticated browser rehearsal exposed three authority failures in the
candidate: a player command response serialized the canonical campaign, a
successful diagnostic promised a finding without committing specific
knowledge, and a custom Huygens seed borrowed the Lucent fixture's cast and
incident from merely adjacent retrieval evidence. The repaired candidate now
projects spoiler-safe player responses, requires exact visible informational
findings that become player knowledge plus branch fact, classifies retrieval
evidence into direct/background/excluded lanes before compilation, and narrows
narration to the latest causal turn. Browser strings use text nodes and the
laboratory inputs have programmatic labels.
Next: commit and build this repaired candidate, replay the same authenticated
Huygens campaign in an isolated runtime, inspect both the visible surface and
the literal HTTP response, then prove away catch-up/concurrency/persistence/
fork/export/restart. Deploy only that exact accepted commit and repeat LAN,
firewall, CultMesh, VoidBot, DeepSeek, scheduler, and provenance smokes.
## Warnings

View file

@ -80,6 +80,15 @@ approval has its own route. Strategic ticks, region commits, gestalt presence,
reaction waves, NPC initiative, and campaign creation are internal mailbox
commands and cannot be invoked through `/api/command`.
That boundary also projects less state outward than the kernel returns inward.
Player HTTP responses contain only assessment, public commit/roll receipts, and
narration. Canonical campaign state and spoiler-bearing actor or institution
state are operator-only. Informational rolls add only their exact previewed
finding to the acting character and a provisional branch fact. The compiler
classifies each retrieved source as direct seed, setting background, or excluded
before generation; excluded sources remain provenance but never become prompt
context, and background sources cannot donate story incidents or cast.
Relationship documents in the schema catalog are revision-bound projections
of actor-owned relationship maps; they are not a second relationship writer.
Vault manifests summarize the exact provider/source/authority/temporal lanes
@ -98,6 +107,11 @@ baseline/member presence transition.
5. Persist only belief-changing evidence.
6. Commit and push completed work.
Model acceptance also measures useful work per token. Stable contracts precede
revision-bound context for cache reuse; each stage receives only the state it
can legitimately judge; provider receipts expose cache, prompt, completion, and
validation cost per attempt.
## Core Surfaces
- `state/map.yaml`: canonical mission, boundaries, live architecture, next action.

View file

@ -37,6 +37,14 @@ 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 current browser/compiler hardening adds three ownership cuts before the
next isolated acceptance run: compiler evidence is triaged into direct,
background, and excluded lanes before generation; informational action effects
must name the exact player-visible finding they commit; and player HTTP command
responses are spoiler-safe projections rather than serialized campaigns. The
browser renders these projections as labeled, escaped human-readable controls,
and narration receives only the latest causal turn rather than a route dump.
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
@ -47,6 +55,12 @@ authority, and no player mutation. Remaining work is authenticated surface and
lifecycle acceptance, away/live concurrency, exact deployment, and final
regression/provenance verification.
Next, build the exact committed candidate and replay the authenticated Huygens
campaign. Prove the literal HTTP response is spoiler-safe, the evidence lanes
exclude adjacent story incidents, and a diagnostic roll commits its exact
previewed finding. Then run away/live concurrency, persistence, fork, export,
restart, deployment, LAN/firewall, CultMesh, and provenance acceptance.
## Prior research-program phase
Build a reliable data-generation loop for socially persistent Aetheria agents.

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

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

18
web/dist/index.html vendored
View file

@ -1,17 +1,17 @@
<!doctype html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>GhostlightDungeon</title> <script type="module" crossorigin src="/assets/index-DlJlHpS2.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-BnHnsfZy.css">
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>GhostlightDungeon</title> <script type="module" crossorigin src="/assets/index-AKBKut3T.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-DLoOYHpE.css">
</head>
<body><header><p class="eyebrow">STARFIRE / PRIVATE VERSE</p><h1>GhostlightDungeon</h1><p id="status">Reading the world…</p></header><main>
<body><header><p class="eyebrow">STARFIRE / PRIVATE VERSE</p><h1>GhostlightDungeon</h1><p id="status" role="status" aria-live="polite">Reading the world…</p></header><main>
<section id="compiler" hidden><h2>Compile a world</h2><div class="compiler-grid">
<form id="suggest-form"><label for="setting">Generate three grounded openings</label><input id="setting" value="Aetheria" required><button type="submit">Retrieve and suggest</button></form>
<form id="custom-form"><label>Or describe your own beginning</label><input name="campaign_name" placeholder="Campaign name" required><input name="who" placeholder="Who are you?" required><input name="where_" placeholder="Where?" required><input name="when" placeholder="When?" required><textarea name="goal" placeholder="What do you want?" required></textarea><button type="submit">Compile custom start</button></form>
<form id="custom-form"><p class="form-heading">Or describe your own beginning</p><label for="campaign-name">Campaign name</label><input id="campaign-name" name="campaign_name" required><label for="custom-who">Who are you?</label><input id="custom-who" name="who" required><label for="custom-where">Where are you?</label><input id="custom-where" name="where_" required><label for="custom-when">When?</label><input id="custom-when" name="when" required><label for="custom-goal">What do you want?</label><textarea id="custom-goal" name="goal" required></textarea><button type="submit">Compile custom start</button></form>
</div><div id="compiler-results"></div></section><section id="surface"></section>
<form id="composer"><label for="attempt">Describe what you attempt</label><textarea id="attempt" required></textarea><div><button type="submit">Assess</button><button type="button" id="wait">Wait one hour</button></div></form><pre id="receipt" hidden></pre>
<form id="destination-form"><label>Compile a destination without moving there</label><input name="origin_location_id" placeholder="Current location id" required><input name="destination" placeholder="Where do you want the world to extend?" required><button type="submit">Retrieve destination</button></form>
<form id="composer"><label for="attempt">Describe what you attempt</label><textarea id="attempt" name="attempt" required></textarea><div><button type="submit">Assess</button><button type="button" id="wait">Wait one hour</button></div></form><section id="receipt" class="card" hidden aria-live="polite"></section>
<form id="destination-form"><p class="form-heading">Compile a destination without moving there</p><label for="destination-origin">Current location id</label><input id="destination-origin" name="origin_location_id" required><label for="destination-request">Where do you want the world to extend?</label><input id="destination-request" name="destination" required><button type="submit">Retrieve destination</button></form>
<section id="campaign-lab" hidden><h2>Campaign laboratory</h2><div id="campaign-list"></div>
<form id="resolution-form"><label for="active-cell-budget">Active Persona-cell budget: <output id="active-cell-budget-value">8</output></label><input id="active-cell-budget" name="active_cell_budget" type="range" min="1" max="32" value="8"><p id="resolution-status"></p><button type="submit">Apply at safe boundary</button></form>
<form id="pin-form"><label>Resolution pin</label><select name="kind"><option value="minimum_individual_detail">Keep one subject individual</option><option value="keep_separate">Keep subjects separate</option><option value="keep_together">Keep subjects together</option></select><input name="subject_ids" placeholder="Exact subject IDs, comma separated" required><input name="reason" placeholder="Why preserve this cut?" required><button type="submit">Add pin</button><div id="pin-list"></div></form>
<form id="fission-form"><label>Approval-gated population fission</label><select name="parent_gestalt_id" id="fission-parent" required></select><select name="partition_axis"><option value="geography">Geography</option><option value="ideology">Ideology</option><option value="authority">Authority</option><option value="economy_role">Economic role</option><option value="species_body">Species/body</option><option value="information">Information</option></select><input name="requested_partition_values" placeholder="Named cuts, comma separated" required><input name="reason" placeholder="Why the population needs canonical leaves" required><button type="submit">Compile fission preview</button></form>
<form id="fork-form"><input name="name" placeholder="Fork name" required><button type="submit">Fork selected campaign</button></form><form id="reset-form"><input name="name" placeholder="Reset branch name" required><button type="submit">Reset from approved seed</button></form><a href="/api/campaigns/export" download>Export selected CultCache .cc</a> <a href="/api/campaigns/canon-candidates.md" download>Export canon candidates Markdown</a><details><summary>Operator inspector</summary><form id="provider-parallelism-form"><label for="provider-parallelism">Provider request parallelism: <output id="provider-parallelism-value">8</output></label><input id="provider-parallelism" type="range" min="1" max="32" value="8"><button type="submit">Apply operator limit</button></form><button type="button" id="load-operator">Load private state and receipts</button><div id="operator-output"></div></details></section>
<form id="pin-form"><label for="pin-kind">Resolution pin</label><select id="pin-kind" name="kind"><option value="minimum_individual_detail">Keep one subject individual</option><option value="keep_separate">Keep subjects separate</option><option value="keep_together">Keep subjects together</option></select><label for="pin-subjects">Exact subject IDs, comma separated</label><input id="pin-subjects" name="subject_ids" required><label for="pin-reason">Why preserve this cut?</label><input id="pin-reason" name="reason" required><button type="submit">Add pin</button><div id="pin-list"></div></form>
<form id="fission-form"><p class="form-heading">Approval-gated population fission</p><label for="fission-parent">Population</label><select name="parent_gestalt_id" id="fission-parent" required></select><label for="fission-axis">Partition axis</label><select id="fission-axis" name="partition_axis"><option value="geography">Geography</option><option value="ideology">Ideology</option><option value="authority">Authority</option><option value="economy_role">Economic role</option><option value="species_body">Species/body</option><option value="information">Information</option></select><label for="fission-values">Named cuts, comma separated</label><input id="fission-values" name="requested_partition_values" required><label for="fission-reason">Why does this population need canonical leaves?</label><input id="fission-reason" name="reason" required><button type="submit">Compile fission preview</button></form>
<form id="fork-form"><label for="fork-name">Fork name</label><input id="fork-name" name="name" required><button type="submit">Fork selected campaign</button></form><form id="reset-form"><label for="reset-name">Reset branch name</label><input id="reset-name" name="name" required><button type="submit">Reset from approved seed</button></form><a href="/api/campaigns/export" download>Export selected CultCache .cc</a> <a href="/api/campaigns/canon-candidates.md" download>Export canon candidates Markdown</a><details><summary>Operator inspector</summary><form id="provider-parallelism-form"><label for="provider-parallelism">Provider request parallelism: <output id="provider-parallelism-value">8</output></label><input id="provider-parallelism" type="range" min="1" max="32" value="8"><button type="submit">Apply operator limit</button></form><button type="button" id="load-operator">Load private state and receipts</button><div id="operator-output"></div></details></section>
</main></body></html>

View file

@ -1,15 +1,15 @@
<!doctype html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>GhostlightDungeon</title></head>
<body><header><p class="eyebrow">STARFIRE / PRIVATE VERSE</p><h1>GhostlightDungeon</h1><p id="status">Reading the world…</p></header><main>
<body><header><p class="eyebrow">STARFIRE / PRIVATE VERSE</p><h1>GhostlightDungeon</h1><p id="status" role="status" aria-live="polite">Reading the world…</p></header><main>
<section id="compiler" hidden><h2>Compile a world</h2><div class="compiler-grid">
<form id="suggest-form"><label for="setting">Generate three grounded openings</label><input id="setting" value="Aetheria" required><button type="submit">Retrieve and suggest</button></form>
<form id="custom-form"><label>Or describe your own beginning</label><input name="campaign_name" placeholder="Campaign name" required><input name="who" placeholder="Who are you?" required><input name="where_" placeholder="Where?" required><input name="when" placeholder="When?" required><textarea name="goal" placeholder="What do you want?" required></textarea><button type="submit">Compile custom start</button></form>
<form id="custom-form"><p class="form-heading">Or describe your own beginning</p><label for="campaign-name">Campaign name</label><input id="campaign-name" name="campaign_name" required><label for="custom-who">Who are you?</label><input id="custom-who" name="who" required><label for="custom-where">Where are you?</label><input id="custom-where" name="where_" required><label for="custom-when">When?</label><input id="custom-when" name="when" required><label for="custom-goal">What do you want?</label><textarea id="custom-goal" name="goal" required></textarea><button type="submit">Compile custom start</button></form>
</div><div id="compiler-results"></div></section><section id="surface"></section>
<form id="composer"><label for="attempt">Describe what you attempt</label><textarea id="attempt" required></textarea><div><button type="submit">Assess</button><button type="button" id="wait">Wait one hour</button></div></form><pre id="receipt" hidden></pre>
<form id="destination-form"><label>Compile a destination without moving there</label><input name="origin_location_id" placeholder="Current location id" required><input name="destination" placeholder="Where do you want the world to extend?" required><button type="submit">Retrieve destination</button></form>
<form id="composer"><label for="attempt">Describe what you attempt</label><textarea id="attempt" name="attempt" required></textarea><div><button type="submit">Assess</button><button type="button" id="wait">Wait one hour</button></div></form><section id="receipt" class="card" hidden aria-live="polite"></section>
<form id="destination-form"><p class="form-heading">Compile a destination without moving there</p><label for="destination-origin">Current location id</label><input id="destination-origin" name="origin_location_id" required><label for="destination-request">Where do you want the world to extend?</label><input id="destination-request" name="destination" required><button type="submit">Retrieve destination</button></form>
<section id="campaign-lab" hidden><h2>Campaign laboratory</h2><div id="campaign-list"></div>
<form id="resolution-form"><label for="active-cell-budget">Active Persona-cell budget: <output id="active-cell-budget-value">8</output></label><input id="active-cell-budget" name="active_cell_budget" type="range" min="1" max="32" value="8"><p id="resolution-status"></p><button type="submit">Apply at safe boundary</button></form>
<form id="pin-form"><label>Resolution pin</label><select name="kind"><option value="minimum_individual_detail">Keep one subject individual</option><option value="keep_separate">Keep subjects separate</option><option value="keep_together">Keep subjects together</option></select><input name="subject_ids" placeholder="Exact subject IDs, comma separated" required><input name="reason" placeholder="Why preserve this cut?" required><button type="submit">Add pin</button><div id="pin-list"></div></form>
<form id="fission-form"><label>Approval-gated population fission</label><select name="parent_gestalt_id" id="fission-parent" required></select><select name="partition_axis"><option value="geography">Geography</option><option value="ideology">Ideology</option><option value="authority">Authority</option><option value="economy_role">Economic role</option><option value="species_body">Species/body</option><option value="information">Information</option></select><input name="requested_partition_values" placeholder="Named cuts, comma separated" required><input name="reason" placeholder="Why the population needs canonical leaves" required><button type="submit">Compile fission preview</button></form>
<form id="fork-form"><input name="name" placeholder="Fork name" required><button type="submit">Fork selected campaign</button></form><form id="reset-form"><input name="name" placeholder="Reset branch name" required><button type="submit">Reset from approved seed</button></form><a href="/api/campaigns/export" download>Export selected CultCache .cc</a> <a href="/api/campaigns/canon-candidates.md" download>Export canon candidates Markdown</a><details><summary>Operator inspector</summary><form id="provider-parallelism-form"><label for="provider-parallelism">Provider request parallelism: <output id="provider-parallelism-value">8</output></label><input id="provider-parallelism" type="range" min="1" max="32" value="8"><button type="submit">Apply operator limit</button></form><button type="button" id="load-operator">Load private state and receipts</button><div id="operator-output"></div></details></section>
<form id="pin-form"><label for="pin-kind">Resolution pin</label><select id="pin-kind" name="kind"><option value="minimum_individual_detail">Keep one subject individual</option><option value="keep_separate">Keep subjects separate</option><option value="keep_together">Keep subjects together</option></select><label for="pin-subjects">Exact subject IDs, comma separated</label><input id="pin-subjects" name="subject_ids" required><label for="pin-reason">Why preserve this cut?</label><input id="pin-reason" name="reason" required><button type="submit">Add pin</button><div id="pin-list"></div></form>
<form id="fission-form"><p class="form-heading">Approval-gated population fission</p><label for="fission-parent">Population</label><select name="parent_gestalt_id" id="fission-parent" required></select><label for="fission-axis">Partition axis</label><select id="fission-axis" name="partition_axis"><option value="geography">Geography</option><option value="ideology">Ideology</option><option value="authority">Authority</option><option value="economy_role">Economic role</option><option value="species_body">Species/body</option><option value="information">Information</option></select><label for="fission-values">Named cuts, comma separated</label><input id="fission-values" name="requested_partition_values" required><label for="fission-reason">Why does this population need canonical leaves?</label><input id="fission-reason" name="reason" required><button type="submit">Compile fission preview</button></form>
<form id="fork-form"><label for="fork-name">Fork name</label><input id="fork-name" name="name" required><button type="submit">Fork selected campaign</button></form><form id="reset-form"><label for="reset-name">Reset branch name</label><input id="reset-name" name="name" required><button type="submit">Reset from approved seed</button></form><a href="/api/campaigns/export" download>Export selected CultCache .cc</a> <a href="/api/campaigns/canon-candidates.md" download>Export canon candidates Markdown</a><details><summary>Operator inspector</summary><form id="provider-parallelism-form"><label for="provider-parallelism">Provider request parallelism: <output id="provider-parallelism-value">8</output></label><input id="provider-parallelism" type="range" min="1" max="32" value="8"><button type="submit">Apply operator limit</button></form><button type="button" id="load-operator">Load private state and receipts</button><div id="operator-output"></div></details></section>
</main><script type="module" src="/src/main.ts"></script></body></html>

View file

@ -16,6 +16,66 @@ let resolutionEpoch = 0;
let providerConfigurationEpoch = 0;
let resolutionPins: any[] = [];
function node<K extends keyof HTMLElementTagNameMap>(
tag: K,
text?: string,
className?: string,
): HTMLElementTagNameMap[K] {
const value = document.createElement(tag);
if (text !== undefined) value.textContent = text;
if (className) value.className = className;
return value;
}
function showSummary(title: string, lines: string[]) {
const children: HTMLElement[] = [node("h3", title)];
for (const line of lines.filter(Boolean)) children.push(node("p", line));
receipt.replaceChildren(...children);
receipt.hidden = false;
}
function renderCommandReceipt(body: any) {
if (body?.kind === "assessed") {
const assessment = body.assessment;
const children: HTMLElement[] = [node("h3", assessment.admissible ? "Action assessment" : "That attempt is not possible")];
if (assessment.admissible) {
children.push(node("p", `DC ${assessment.dc} · modifier ${assessment.modifier_total >= 0 ? "+" : ""}${assessment.modifier_total}`));
const modifiers = node("ul");
for (const modifier of assessment.modifiers ?? []) {
modifiers.append(node("li", `${modifier.label}: ${modifier.value >= 0 ? "+" : ""}${modifier.value}`));
}
children.push(modifiers);
children.push(node("p", `Strong/success: ${assessment.success_stake}`));
children.push(node("p", `Mixed: ${assessment.mixed_stake}`));
children.push(node("p", `Failure: ${assessment.failure_stake}`));
children.push(node("p", `Effect ceiling: ${assessment.effect_ceiling}`, "quiet"));
} else {
children.push(node("p", assessment.missing_permission ?? "The attempt has no admissible path from current state."));
for (const bargain of assessment.bargains ?? []) children.push(node("p", `Possible bargain: ${bargain}`));
}
receipt.replaceChildren(...children);
receipt.hidden = false;
return;
}
if (body?.kind === "committed") {
const roll = body.receipt?.roll;
if (roll) {
const outcome = String(roll.outcome).replaceAll("_", " ");
showSummary(outcome.charAt(0).toUpperCase() + outcome.slice(1), [
`d20 ${roll.d20} ${roll.modifier_total >= 0 ? "+" : "−"} ${Math.abs(roll.modifier_total)} = ${roll.total} against DC ${roll.dc}`,
]);
} else {
showSummary("World advanced", [`Revision ${body.revision}`]);
}
return;
}
if (body?.kind === "resolution_updated") {
showSummary("World resolution updated", [`Resolution epoch ${body.receipt?.resolution_epoch ?? "advanced"}`]);
return;
}
showSummary("Command result", [body?.error ?? "The world returned no player-facing detail."]);
}
async function refresh() {
const response = await fetch("/api/surface");
if (response.status === 401) { status.textContent = "This laboratory requires an unused invite link."; return; }
@ -36,17 +96,35 @@ async function refresh() {
document.querySelector<HTMLInputElement>("#provider-parallelism")!.value = String(providerParallelism);
document.querySelector<HTMLOutputElement>("#provider-parallelism-value")!.value = String(providerParallelism);
const pinList = document.querySelector<HTMLElement>("#pin-list")!;
pinList.innerHTML = resolutionPins.map(pin => `<p><code>${pin.kind}</code> ${[...pin.subject_ids].join(", ")} — ${pin.reason} <button type="button" data-remove-pin="${pin.id}">Remove</button></p>`).join("") || "<p>No persistent pins.</p>";
pinList.querySelectorAll<HTMLButtonElement>("[data-remove-pin]").forEach(button => button.addEventListener("click", async () => {
await send({ type: "replace_resolution_pins", expected_revision: revision, expected_resolution_epoch: resolutionEpoch, pins: resolutionPins.filter(pin => pin.id !== button.dataset.removePin) });
}));
pinList.replaceChildren();
if (resolutionPins.length === 0) pinList.append(node("p", "No persistent pins."));
for (const pin of resolutionPins) {
const row = node("p");
row.append(node("code", String(pin.kind)), document.createTextNode(` ${[...pin.subject_ids].join(", ")} — ${pin.reason} `));
const remove = node("button", "Remove");
remove.type = "button";
remove.addEventListener("click", async () => {
await send({ type: "replace_resolution_pins", expected_revision: revision, expected_resolution_epoch: resolutionEpoch, pins: resolutionPins.filter(candidate => candidate.id !== pin.id) });
});
row.append(remove);
pinList.append(row);
}
const fissionParent = document.querySelector<HTMLSelectElement>("#fission-parent")!;
fissionParent.innerHTML = (surface.resolution?.fission_targets ?? []).map((target: any) => `<option value="${target.id}">${target.name} · ${target.id}</option>`).join("");
fissionParent.replaceChildren(...(surface.resolution?.fission_targets ?? []).map((target: any) => {
const option = node("option", `${target.name} · ${target.id}`);
option.value = target.id;
return option;
}));
document.querySelector<HTMLFormElement>("#fission-form")!.hidden = fissionParent.options.length === 0;
renderEveSurface(surface, host, { body: document.body, clientId: "ghostlight.browser", statusElement: status });
const campaigns = await fetch("/api/campaigns").then(response => response.json());
campaignList.innerHTML = campaigns.campaigns.map((item: any) => `<button data-campaign-id="${item.id}" ${item.selected ? "disabled" : ""}>${item.selected ? "●" : "○"} ${item.name} · revision ${item.revision}</button>`).join("");
campaignList.querySelectorAll<HTMLButtonElement>("button:not(:disabled)").forEach(button=>button.addEventListener("click",async()=>{await compilerPost(`/api/campaigns/select/${button.dataset.campaignId}`,{});await refresh();}));
campaignList.replaceChildren(...campaigns.campaigns.map((item: any) => {
const button = node("button", `${item.selected ? "●" : "○"} ${item.name} · revision ${item.revision}`);
button.type = "button";
button.disabled = Boolean(item.selected);
if (!item.selected) button.addEventListener("click", async () => { await compilerPost(`/api/campaigns/select/${item.id}`, {}); await refresh(); });
return button;
}));
}
async function compilerPost(path: string, body: unknown) {
@ -58,8 +136,18 @@ async function compilerPost(path: string, body: unknown) {
}
function showCards(items: any[], action: string, choose: (item: any) => void) {
compilerResults.innerHTML = `<div class="cards">${items.map((item, index) => `<article class="card"><h3>${item.title ?? item.name}</h3><p>${item.player_hook ?? item.premise}</p><p>${item.era ? `${item.era} · ${item.place} · ${item.pressure}` : ""}</p><button data-index="${index}">${action}</button></article>`).join("")}</div>`;
compilerResults.querySelectorAll<HTMLButtonElement>("button").forEach(button => button.addEventListener("click", () => choose(items[Number(button.dataset.index)])));
const cards = node("div", undefined, "cards");
items.forEach((item, index) => {
const card = node("article", undefined, "card");
card.append(node("h3", item.title ?? item.name), node("p", item.player_hook ?? item.premise));
if (item.era) card.append(node("p", `${item.era} · ${item.place} · ${item.pressure}`));
const button = node("button", action);
button.type = "button";
button.addEventListener("click", () => choose(items[index]));
card.append(button);
cards.append(card);
});
compilerResults.replaceChildren(cards);
}
document.querySelector<HTMLFormElement>("#suggest-form")!.addEventListener("submit", async event => {
@ -75,12 +163,32 @@ document.querySelector<HTMLFormElement>("#custom-form")!.addEventListener("submi
async function showPreview(result: any) {
const preview = result.preview;
compilerResults.innerHTML = `<article class="card"><h3>${preview.title}</h3><p>${preview.campaign.transcript?.[0]?.text ?? ""}</p><p>${Object.keys(preview.campaign.locations).length} locations · ${Object.keys(preview.campaign.actors).length} actors · ${Object.keys(preview.campaign.institutions).length} institutions</p><p class="warning">${preview.gaps.length ? `Material gaps: ${preview.gaps.join("; ")}` : "No declared material gaps."}</p><p>Branch assumptions: ${preview.branch_assumptions.join("; ") || "none"}</p><button id="approve-world">Approve and enter</button></article>`;
document.querySelector<HTMLButtonElement>("#approve-world")!.addEventListener("click", async () => { await compilerPost(`/api/compiler/approve/${result.preview_id}`, {}); await refresh(); });
const coverage = Array.isArray(preview.evidence_coverage) ? preview.evidence_coverage : [];
const evidenceCounts = coverage.reduce((counts: Record<string, number>, item: any) => {
const lane = String(item?.lane ?? "excluded");
counts[lane] = (counts[lane] ?? 0) + 1;
return counts;
}, {});
const card = node("article", undefined, "card");
card.append(
node("h3", preview.title),
node("p", preview.campaign.transcript?.[0]?.text ?? ""),
node("p", `${Object.keys(preview.campaign.locations).length} locations · ${Object.keys(preview.campaign.actors).length} actors · ${Object.keys(preview.campaign.institutions).length} institutions`),
node("p", preview.gaps.length ? `Material gaps: ${preview.gaps.join("; ")}` : "No declared material gaps.", "warning"),
node("p", `Branch assumptions: ${preview.branch_assumptions.join("; ") || "none"}`),
node("p", coverage.length
? `Evidence use: ${evidenceCounts.direct_seed ?? 0} direct · ${evidenceCounts.setting_background ?? 0} background · ${evidenceCounts.excluded ?? 0} excluded`
: "Evidence use: no retrieved sources were admitted to this seed.", "quiet"),
);
const approve = node("button", "Approve and enter");
approve.type = "button";
approve.addEventListener("click", async () => { await compilerPost(`/api/compiler/approve/${result.preview_id}`, {}); await refresh(); });
card.append(approve);
compilerResults.replaceChildren(card);
status.textContent = "Preview compiled. Nothing has entered world state yet.";
}
async function send(command: unknown) { status.textContent = "The world is considering the command…"; const response = await fetch("/api/command", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(command) }); const body = await response.json(); receipt.hidden = false; receipt.textContent = JSON.stringify(body, null, 2); if (!response.ok) { status.textContent = body.error ?? "The command was refused."; await refresh(); return body; } await refresh(); return body; }
async function send(command: unknown) { status.textContent = "The world is considering the command…"; const response = await fetch("/api/command", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(command) }); const body = await response.json(); renderCommandReceipt(body); if (!response.ok) { status.textContent = body.error ?? "The command was refused."; await refresh(); return body; } await refresh(); return body; }
function installAssessment(result: any) {
if (result?.kind !== "assessed") return;
const button = document.createElement("button");
@ -133,8 +241,7 @@ document.querySelector<HTMLFormElement>("#provider-parallelism-form")!.addEventL
}),
});
const body = await response.json();
receipt.hidden = false;
receipt.textContent = JSON.stringify(body, null, 2);
showSummary(response.ok ? "Provider concurrency updated" : "Provider concurrency refused", [response.ok ? `Parallel requests: ${body.receipt?.provider_parallelism ?? body.provider_parallelism ?? "updated"}` : body.error ?? "The operator limit was refused."]);
if (!response.ok) status.textContent = body.error ?? "The operator limit was refused.";
await refresh();
});
@ -152,7 +259,7 @@ document.querySelector<HTMLFormElement>("#pin-form")!.addEventListener("submit",
};
await send({ type: "replace_resolution_pins", expected_revision: revision, expected_resolution_epoch: resolutionEpoch, pins: [...resolutionPins, pin] });
});
destinationForm.addEventListener("submit",async event=>{event.preventDefault();const result=await compilerPost("/api/compiler/destination",Object.fromEntries(new FormData(destinationForm)));const preview=result.preview;receipt.hidden=false;receipt.textContent=JSON.stringify(preview,null,2);status.textContent="Destination preview compiled; topology is unchanged until approval.";const button=document.createElement("button");button.textContent="Approve destination";button.addEventListener("click",async()=>{await compilerPost(`/api/compiler/destination/approve/${result.preview_id}`,{});button.remove();await refresh();});destinationForm.append(button);});
destinationForm.addEventListener("submit",async event=>{event.preventDefault();const result=await compilerPost("/api/compiler/destination",Object.fromEntries(new FormData(destinationForm)));const preview=result.preview;showSummary("Destination preview",[...(preview.locations ?? []).map((location:any)=>location.name),...(preview.gaps ?? []).map((gap:string)=>`Material gap: ${gap}`)]);status.textContent="Destination preview compiled; topology is unchanged until approval.";const button=node("button","Approve destination");button.type="button";button.addEventListener("click",async()=>{await compilerPost(`/api/compiler/destination/approve/${result.preview_id}`,{});button.remove();await refresh();});destinationForm.append(button);});
document.querySelector<HTMLFormElement>("#fission-form")!.addEventListener("submit", async event => {
event.preventDefault();
const data = new FormData(event.currentTarget as HTMLFormElement);
@ -162,8 +269,10 @@ document.querySelector<HTMLFormElement>("#fission-form")!.addEventListener("subm
requested_partition_values: String(data.get("requested_partition_values") ?? "").split(",").map(value => value.trim()).filter(Boolean),
reason: data.get("reason"),
});
receipt.hidden = false;
receipt.textContent = JSON.stringify(result.preview, null, 2);
showSummary("Population fission preview", [
...(result.preview?.children ?? []).map((child: any) => `${child.name} · ${child.id}`),
...(result.preview?.gaps ?? []).map((gap: string) => `Material gap: ${gap}`),
]);
status.textContent = "Fission preview compiled. Canonical leaves are unchanged until approval.";
const button = document.createElement("button");
button.type = "button";

View file

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