From 07d71173df628fb1650ddfa8216c265c791766d3 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 18 Aug 2026 19:15:54 +0200 Subject: [PATCH] Bind strategic outcomes to causal authority --- .../bin/ghostlight-gestalt-dynamics-smoke.rs | 69 ++- crates/ghostlight-dungeon/src/outcome.rs | 504 +++++++++++++++++- crates/ghostlight-dungeon/src/persona.rs | 2 +- .../ghostlight-multiresolution-agency.md | 32 +- notes/fresh-workspace-handoff.md | 38 +- notes/ghostlight-current-system-map.md | 10 + notes/ghostlight-implementation-plan.md | 25 +- state/evidence.jsonl | 1 + state/map.yaml | 4 +- 9 files changed, 624 insertions(+), 61 deletions(-) diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-dynamics-smoke.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-dynamics-smoke.rs index 2e1b8be..268b0bc 100644 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-dynamics-smoke.rs +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-dynamics-smoke.rs @@ -208,22 +208,45 @@ async fn main() -> anyhow::Result<()> { calls: model_calls.clone(), }); let started = Instant::now(); - let output = match propose_resolution_wave( - model.clone(), - Arc::new(SnapshotPermit::new_resolution( - store.clone(), - campaign.id, - campaign.revision, - campaign.resolution_policy.resolution_epoch, - )), - &campaign, - ) - .await - { - Ok(output) => output, - Err(error) => { - write_wave_failure(&root, 0, 1, 1, &error, &model_calls, 0)?; - return Err(error); + let mut rejected_wave_pulses = Vec::new(); + let mut initial_rejected_pulses = 0; + let output = loop { + let trace_start = model_calls.lock().expect("live-fire trace lock").len(); + match propose_resolution_wave( + model.clone(), + Arc::new(SnapshotPermit::new_resolution( + store.clone(), + campaign.id, + campaign.revision, + campaign.resolution_policy.resolution_epoch, + )), + &campaign, + ) + .await + { + Ok(output) => break output, + Err(error) => { + initial_rejected_pulses += 1; + write_wave_failure( + &root, + 0, + initial_rejected_pulses, + campaign.resolution_policy.active_cell_budget, + &error, + &model_calls, + trace_start, + )?; + rejected_wave_pulses.push(serde_json::json!({ + "wave_index":0, + "pulse_attempt":initial_rejected_pulses, + "world_revision":campaign.revision, + "resolution_epoch":campaign.resolution_policy.resolution_epoch, + "error":error.to_string(), + })); + if initial_rejected_pulses > max_rejected_pulses_per_wave { + return Err(error); + } + } } }; let preflight = serde_json::json!({ @@ -394,7 +417,6 @@ async fn main() -> anyhow::Result<()> { anyhow::bail!("initial Mira delta changed without an exact member-bound outcome") } let mut sustained_waves = Vec::new(); - let mut rejected_wave_pulses = Vec::new(); let mut background_subject_ids = BTreeSet::new(); let mut detail_focus_subject_ids = BTreeSet::new(); let mut sustained_material_consequence_count = 0usize; @@ -574,6 +596,15 @@ async fn main() -> anyhow::Result<()> { if !presence_only && sustained_material_consequence_count == 0 { anyhow::bail!("sustained multiresolution waves resolved no material background consequence") } + if !presence_only && sustained_material_outcome_count == 0 { + std::fs::write( + root.join("private-model-calls.json"), + serde_json::to_vec_pretty(&*model_calls.lock().expect("live-fire trace lock"))?, + )?; + anyhow::bail!( + "strategic outcome resolver produced no typed material result across sustained waves" + ) + } let fairness_missing_subject_ids = if fairness_stress_waves == 0 { BTreeSet::new() } else { @@ -723,6 +754,10 @@ async fn main() -> anyhow::Result<()> { "preflight_path":root.join("preflight.json"), "result_path":root.join("result.json") }); + std::fs::write( + root.join("private-model-calls.json"), + serde_json::to_vec_pretty(&*model_calls.lock().expect("live-fire trace lock"))?, + )?; std::fs::write( root.join("result.json"), serde_json::to_vec_pretty(&result)?, diff --git a/crates/ghostlight-dungeon/src/outcome.rs b/crates/ghostlight-dungeon/src/outcome.rs index 45cd1bf..3b3edbe 100644 --- a/crates/ghostlight-dungeon/src/outcome.rs +++ b/crates/ghostlight-dungeon/src/outcome.rs @@ -12,7 +12,8 @@ use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet}; -const OUTCOME_PROPOSAL_OUTPUT_CONTRACT: &str = r#"The top-level object has exactly one field named outcomes—never action_resolutions, results, or resolutions. outcomes is an array with one item per supplied action_digest. Every item requires action_digest, band (success, mixed, or failure), effect_kind, and supporting_state_references. The remaining permitted fields are owner_subject_id, other_subject_id, relation_id, strength_delta, resource, pressure_additions, pressure_resolutions, member_id, memory, obligation, relationship_description, fact_id, and reason. Omit every optional field not used by the chosen effect_kind. Do not emit summary; Ghostlight derives it from the validated typed effect. Example no-op shape: {"outcomes":[{"action_digest":"sha256:","band":"mixed","effect_kind":"no_material_change","supporting_state_references":[],"reason":"No durable state changed."}]}"#; +const OUTCOME_PROPOSAL_OUTPUT_CONTRACT: &str = r#"The top-level object has exactly one field named outcomes—never action_resolutions, results, or resolutions. outcomes is an array with one item per supplied action_digest. Every item requires action_digest, band (success, mixed, or failure), effect_kind, and supporting_state_references. The remaining permitted fields are owner_subject_id, other_subject_id, relation_id, strength_delta, resource, pressure_additions, pressure_resolutions, member_id, memory, obligation, relationship_description, fact_id, and reason. pressure_additions and pressure_resolutions are arrays of plain strings, never objects. Omit every optional field not used by the chosen effect_kind. Do not emit summary; Ghostlight derives it from the validated typed effect. When resource_created is admissible and concrete capability-backed making or repair establishes a durable source-owned result, the resource field names that resulting object, stock, repair, or usable arrangement. It never restates an action or an unnamed recipient's response. Example no-op shape: {"outcomes":[{"action_digest":"sha256:","band":"mixed","effect_kind":"no_material_change","supporting_state_references":[],"reason":"No durable state changed."}]}"#; +const OUTCOME_VERIFIER_OUTPUT_CONTRACT: &str = r#"The top-level object has exactly one field named verdicts—never verifications, outcomes, results, or resolutions. verdicts is an array with one item per supplied action_digest. Every item has exactly action_digest, result, and repair_guidance. Example: {"verdicts":[{"action_digest":"sha256:","result":"match","repair_guidance":null}]}"#; #[derive(Clone, Debug, Serialize)] struct OutcomeContext { @@ -34,11 +35,12 @@ struct ActionOutcomeContext { source_state: serde_json::Value, target_state: Vec, active_relations: Vec, - pressure_owner_ids: Vec, + pressure_owner_subject_ids: Vec, resource_owner_id: String, resource_recipient_ids: Vec, discoverable_facts: Vec, member_state_owner_id: Option, + admissible_effect_kinds: Vec, allowed_state_references: Vec, } @@ -48,7 +50,7 @@ struct OutcomeProposalBundle { outcomes: Vec, } -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] #[serde(rename_all = "snake_case")] enum OutcomeEffectKind { NoMaterialChange, @@ -99,6 +101,28 @@ struct OutcomeProposal { reason: Option, } +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +struct OutcomeVerifierBundle { + verdicts: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +enum OutcomeVerifierResult { + Match, + Mismatch, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +struct OutcomeVerifierVerdict { + action_digest: String, + result: OutcomeVerifierResult, + #[serde(default)] + repair_guidance: Option, +} + pub async fn resolve_activity_outcomes( model: &dyn ModelPort, campaign: &Campaign, @@ -120,14 +144,14 @@ pub async fn resolve_activity_outcomes( ); let mut schema = serde_json::to_value(schema_for!(OutcomeProposalBundle))?; constrain_digest_schema(&mut schema, &digests); - let source_receipt_ids = proposals + let source_receipt_ids: Vec = proposals .iter() .flat_map(|proposal| outcome_source_receipts(campaign, proposal)) .collect::>() .into_iter() .collect(); let static_contract = format!( - "You are Ghostlight's private strategic outcome resolver. The Interpreter already established each exact constituent's selected attempt; you alone assess opposition and choose its bounded durable result. Resolve every supplied action_digest exactly once. Never add or remove an action. Use only IDs, resources, pressure resolutions, relations, facts, member owners, targets, and state references supplied for that same action. Never mutate the player. Never treat an arena as an actor or union constituents' private state. A success may still have no durable material change when the attempt was speech, preparation, or inquiry whose response is not established. A failure may create a pressure or spend a committed resource when causally supported. Every material effect must actually change the supplied state; do not repeat an existing resource, pressure, memory, obligation, relationship description, or known fact. Choose exactly one effect_kind. Populate only its fields and omit every irrelevant optional field. no_material_change requires reason. resource_created creates one bounded branch-local resource for the source only and requires a capability reference. resource_consumed spends one exact existing source resource. resource_transferred gives one exact existing source resource to one supplied resource_recipient_id; it cannot take from a target. Every resource effect's owner_subject_id must copy that action's exact resource_owner_id, including any member: prefix. gestalt_pressure uses one supplied pressure_owner_id; resolutions must copy exact current pressure text. agency_relation_shift uses one supplied active relation and a nonzero delta from -10 through 10. Member memory, obligation, or relationship may change only the supplied member_state_owner_id; member_id omits the member: prefix. A relationship's other_subject_id must be one exact action target. knowledge_learned uses one supplied discoverable fact and teaches only the source. Every material effect needs at least one supplied supporting_state_reference. Return one JSON object and no prose outside JSON.\n\nOUTPUT CONTRACT:\n{OUTCOME_PROPOSAL_OUTPUT_CONTRACT}" + "You are Ghostlight's private strategic outcome resolver. The Interpreter already established each exact constituent's selected attempt; you alone assess opposition and choose its bounded durable result. Resolve every supplied action_digest exactly once. Never add or remove an action. For each action, effect_kind must come from that action's admissible_effect_kinds; this is the runtime's exact projection of locally valid consequence handles. Use only IDs, resources, pressure resolutions, relations, facts, member owners, targets, and state references supplied for that same action. Never mutate the player. Never treat an arena as an actor or union constituents' private state. Prefer the most specific causally supported durable effect when the attempt and its band establish one. A mixed result should preserve bounded progress, cost, or a new unresolved pressure when a supplied handle supports it; do not collapse concrete partial work into no change merely because it is incomplete. Use no_material_change when none of the other supplied handles honestly represents a durable result; success or mixed success does not itself authorize inventing a response, fact, relationship, or resource. A failure may create a pressure or spend a committed resource when causally supported. Every material effect must actually change the supplied state; do not repeat an existing resource, pressure, memory, obligation, relationship description, or known fact. Choose exactly one effect_kind. Populate only its fields and omit every irrelevant optional field. no_material_change requires reason. resource_created creates one bounded branch-local resource for the source only and requires a capability reference. resource_consumed spends one exact existing source resource. resource_transferred gives one exact existing source resource to one supplied resource_recipient_id; it cannot take from a target. Every resource effect's owner_subject_id must copy that action's exact resource_owner_id, including any member: prefix. gestalt_pressure copies one exact pressure_owner_subject_ids value into owner_subject_id; resolutions must copy exact current pressure text. agency_relation_shift uses one supplied active relation and a nonzero delta from -10 through 10. Member memory, obligation, or relationship may change only the supplied member_state_owner_id; member_id omits the member: prefix. A relationship's other_subject_id must be one exact action target. knowledge_learned uses one supplied discoverable fact and teaches only the source. Every material effect needs at least one supplied supporting_state_reference. Return one JSON object and no prose outside JSON.\n\nOUTPUT CONTRACT:\n{OUTCOME_PROPOSAL_OUTPUT_CONTRACT}" ); let mut request = ModelStageRequest { stage: "strategic_outcome_resolver".into(), @@ -138,7 +162,7 @@ pub async fn resolve_activity_outcomes( serde_json::to_string(&context)? ), output_schema: Some(schema), - source_receipt_ids, + source_receipt_ids: source_receipt_ids.clone(), temperature: Some(0.0), max_output_tokens: Some(2_400), }; @@ -154,7 +178,53 @@ pub async fn resolve_activity_outcomes( match bind_outcomes(campaign, proposals, proposal_bundle) { Ok(outcomes) => { stages.push(stage); - return Ok((outcomes, stages)); + let semantic_outcomes = outcomes + .iter() + .filter(|outcome| requires_semantic_outcome_verifier(&outcome.effect)) + .cloned() + .collect::>(); + if semantic_outcomes.is_empty() { + return Ok((outcomes, stages)); + } + let semantic_digests = semantic_outcomes + .iter() + .map(|outcome| outcome.action_digest.clone()) + .collect::>(); + let semantic_digest_set = semantic_digests.iter().cloned().collect::>(); + let semantic_proposals = proposals + .iter() + .filter(|proposal| { + cell_action_digest(proposal) + .is_ok_and(|digest| semantic_digest_set.contains(&digest)) + }) + .cloned() + .collect::>(); + let semantic_context = build_context(campaign, &semantic_proposals)?; + let (verifier, mismatches) = verify_outcomes( + model, + campaign, + &semantic_context, + &semantic_outcomes, + &semantic_digests, + &source_receipt_ids, + ) + .await?; + stages.push(verifier); + if mismatches.is_empty() { + return Ok((outcomes, stages)); + } + if semantic_attempt == 0 { + request.lived_stream.push_str(&format!( + "\n\nCORRECTION TASK—THE INDEPENDENT OUTCOME VERIFIER REJECTED THE PREVIOUS BUNDLE.\nREPAIRS:\n{}\nPREVIOUS_REJECTED_OUTCOMES:\n{}\nReturn one complete corrected bundle against the exact same snapshot and action digests. Do not preserve a rejected effect_kind unless its repair explicitly says that kind remains valid. When no exact supplied handle can express the repair, use no_material_change with a concrete reason.", + mismatches.join("\n"), + serde_json::to_string(&outcomes)? + )); + } else { + return Err(anyhow!( + "strategic outcome verifier rejected the corrected bundle: {}", + mismatches.join("; ") + )); + } } Err(error) if semantic_attempt == 0 => { let rejected = stage.narrative.clone(); @@ -176,6 +246,91 @@ pub async fn resolve_activity_outcomes( unreachable!() } +fn requires_semantic_outcome_verifier(effect: &StrategicOutcomeEffect) -> bool { + matches!( + effect, + StrategicOutcomeEffect::ResourceConsumed { .. } + | StrategicOutcomeEffect::ResourceTransferred { .. } + | StrategicOutcomeEffect::AgencyRelationShift { .. } + | StrategicOutcomeEffect::MemberMemory { .. } + | StrategicOutcomeEffect::MemberObligation { .. } + | StrategicOutcomeEffect::MemberRelationship { .. } + ) +} + +async fn verify_outcomes( + model: &dyn ModelPort, + campaign: &Campaign, + context: &OutcomeContext, + outcomes: &[StrategicActivityOutcome], + digests: &[String], + source_receipt_ids: &[String], +) -> Result<(ModelStageOutput, Vec)> { + let mut schema = serde_json::to_value(schema_for!(OutcomeVerifierBundle))?; + constrain_verifier_schema(&mut schema, digests); + let outcome_hash = format!( + "sha256:{:x}", + Sha256::digest(rmp_serde::to_vec_named(outcomes)?) + ); + let request = ModelStageRequest { + stage: "strategic_outcome_verifier".into(), + model: "deepseek-v4-flash".into(), + snapshot_binding: format!( + "{}:verifier:{outcome_hash}", + activity_outcome_binding( + campaign.id, + campaign.revision, + campaign.resolution_policy.resolution_epoch, + digests, + ) + ), + lived_stream: format!( + "You are Ghostlight's independent semantic verifier for high-risk strategic outcomes. The local validator has already proved IDs, custody, scope, and bounds. Judge only whether each proposed resource expenditure, transfer, relation shift, or named-member private delta is causally entailed by that exact subject's attempt and supplied state. Return one verdict per action_digest in supplied order. A resource_consumed must be an exact resource the attempt actually uses, spends, gives up, damages, or transforms; reject unrelated inventory charges. A resource_transferred requires the attempt to give that exact resource to that exact recipient. A relation shift requires an interaction capable of changing that relationship, not merely a message, proximity, or unrelated work. Member memory, obligation, and relationship effects require an event in the attempt that could create that exact personal delta. Do not review low-risk resource creation, pressure, knowledge, or no-change outcomes here. result is match or mismatch. match requires null repair_guidance; mismatch requires one concrete correction sentence of at most 240 characters. Return JSON only.\n\nOUTPUT CONTRACT:\n{OUTCOME_VERIFIER_OUTPUT_CONTRACT}\n\nACTION_CONTEXT:\n{}\n\nPROPOSED_OUTCOMES:\n{}", + serde_json::to_string(context)?, + serde_json::to_string(outcomes)?, + ), + output_schema: Some(schema), + source_receipt_ids: source_receipt_ids.to_vec(), + temperature: Some(0.0), + max_output_tokens: Some(1_200), + }; + let stage = run_validated_stage(model, &request).await?; + let bundle: OutcomeVerifierBundle = serde_json::from_value( + stage + .structured + .clone() + .ok_or_else(|| anyhow!("strategic outcome verifier produced no typed output"))?, + )?; + let expected = digests.iter().cloned().collect::>(); + let mut seen = BTreeSet::new(); + let mut mismatches = Vec::new(); + for verdict in bundle.verdicts { + if !expected.contains(&verdict.action_digest) || !seen.insert(verdict.action_digest.clone()) + { + return Err(anyhow!( + "strategic outcome verifier changed or duplicated an action digest" + )); + } + match (verdict.result, verdict.repair_guidance) { + (OutcomeVerifierResult::Match, None) => {} + (OutcomeVerifierResult::Mismatch, Some(guidance)) if bounded_text(&guidance, 240) => { + mismatches.push(format!("{}: {guidance}", verdict.action_digest)); + } + _ => { + return Err(anyhow!( + "strategic outcome verifier returned incoherent result or repair guidance" + )); + } + } + } + if seen != expected { + return Err(anyhow!( + "strategic outcome verifier omitted an action digest" + )); + } + Ok((stage, mismatches)) +} + pub fn activity_outcome_binding( campaign_id: uuid::Uuid, world_revision: u64, @@ -319,7 +474,15 @@ fn validate_outcomes_against_expected( "strategic outcome cites state outside its exact slice" )); } - validate_effect(campaign, proposal, outcome, &mut exclusive_effects)?; + validate_effect(campaign, proposal, outcome, &mut exclusive_effects).map_err(|error| { + let admissible = admissible_effect_kinds(campaign, proposal) + .and_then(|kinds| serde_json::to_string(&kinds).map_err(Into::into)) + .unwrap_or_else(|_| "[unavailable]".into()); + anyhow!( + "outcome {} is invalid: {error}; exact admissible_effect_kinds are {admissible}", + outcome.action_digest + ) + })?; if let StrategicOutcomeEffect::AgencyRelationShift { relation_id, strength_delta, @@ -380,9 +543,12 @@ fn bind_effect(proposal: &OutcomeProposal) -> Result { let populated = proposal.populated_effect_fields(); let require_exact = |allowed: &[&str]| -> Result<()> { let allowed = allowed.iter().copied().collect::>(); - if populated.iter().any(|field| !allowed.contains(field)) { + let irrelevant = populated.difference(&allowed).copied().collect::>(); + if !irrelevant.is_empty() { return Err(anyhow!( - "outcome populated fields irrelevant to its effect_kind" + "outcome populated irrelevant fields [{}]; the chosen effect_kind permits only [{}]", + irrelevant.join(", "), + allowed.into_iter().collect::>().join(", ") )); } Ok(()) @@ -924,7 +1090,7 @@ fn action_context( source_state, target_state, active_relations, - pressure_owner_ids: pressure_owner_ids(campaign, proposal)? + pressure_owner_subject_ids: pressure_owner_ids(campaign, proposal)? .into_iter() .collect(), resource_owner_id: proposal.subject_id.clone(), @@ -934,12 +1100,93 @@ fn action_context( .subject_id .strip_prefix("member:") .map(str::to_owned), + admissible_effect_kinds: admissible_effect_kinds(campaign, proposal)?, allowed_state_references: allowed_state_references(campaign, proposal)? .into_iter() .collect(), }) } +fn admissible_effect_kinds( + campaign: &Campaign, + proposal: &CellActionProposal, +) -> Result> { + let (activity, targets, _) = activity_parts(proposal)?; + let source = proposal.subject_id.as_str(); + let resources = subject_resources(campaign, source)?; + let references = allowed_state_references(campaign, proposal)?; + let mut kinds = vec![OutcomeEffectKind::NoMaterialChange]; + + if matches!(activity, StrategicActivityKind::Prepare) + && resources.len() < 64 + && can_hold_resources(campaign, source) + && references + .iter() + .any(|reference| reference.starts_with("capability:")) + { + kinds.push(OutcomeEffectKind::ResourceCreated); + } + if !resources.is_empty() { + kinds.push(OutcomeEffectKind::ResourceConsumed); + } + if !resources.is_empty() + && matches!( + activity, + StrategicActivityKind::Trade + | StrategicActivityKind::Communicate + | StrategicActivityKind::Recruit + | StrategicActivityKind::Coordinate + ) + && targets.iter().any(|target| { + target != &campaign.player_actor_id && can_hold_resources(campaign, target) + }) + { + kinds.push(OutcomeEffectKind::ResourceTransferred); + } + if !pressure_owner_ids(campaign, proposal)?.is_empty() { + kinds.push(OutcomeEffectKind::GestaltPressure); + } + if !source.starts_with("member:") + && matches!( + activity, + StrategicActivityKind::Coordinate + | StrategicActivityKind::Recruit + | StrategicActivityKind::Obstruct + | StrategicActivityKind::Trade + | StrategicActivityKind::Communicate + ) + && campaign.agency_relations.values().any(|relation| { + relation.active + && ((relation.from_subject_id == source + && targets.contains(&relation.to_subject_id)) + || (relation.to_subject_id == source + && targets.contains(&relation.from_subject_id))) + }) + { + kinds.push(OutcomeEffectKind::AgencyRelationShift); + } + if let Some(member_id) = source.strip_prefix("member:") { + let member = &campaign.gestalt_members[member_id]; + if member.memories.len() < 64 { + kinds.push(OutcomeEffectKind::MemberMemory); + } + if member.obligations.len() < 64 { + kinds.push(OutcomeEffectKind::MemberObligation); + } + if !targets.is_empty() { + kinds.push(OutcomeEffectKind::MemberRelationship); + } + } + if matches!( + activity, + StrategicActivityKind::Investigate | StrategicActivityKind::Communicate + ) && !discoverable_fact_ids(campaign, proposal)?.is_empty() + { + kinds.push(OutcomeEffectKind::KnowledgeLearned); + } + Ok(kinds) +} + fn subject_summary(campaign: &Campaign, subject_id: &str) -> Result { if let Some(member_id) = subject_id.strip_prefix("member:") { let member = campaign @@ -1195,6 +1442,16 @@ fn constrain_digest_schema(schema: &mut serde_json::Value, digests: &[String]) { } } +fn constrain_verifier_schema(schema: &mut serde_json::Value, digests: &[String]) { + if let Some(value) = schema.pointer_mut("/properties/verdicts/items/properties/action_digest") { + value["enum"] = serde_json::json!(digests); + } + if let Some(verdicts) = schema.pointer_mut("/properties/verdicts") { + verdicts["minItems"] = serde_json::json!(digests.len()); + verdicts["maxItems"] = serde_json::json!(digests.len()); + } +} + fn required(value: &Option, field: &str) -> Result { value .clone() @@ -1243,10 +1500,100 @@ mod tests { requests: Mutex>, } + struct RejectingVerifierModel { + action_digest: String, + } + + struct CorrectingOutcomeModel { + action_digest: String, + resolver_calls: Mutex, + } + + #[async_trait::async_trait] + impl ModelPort for CorrectingOutcomeModel { + async fn run(&self, request: &ModelStageRequest) -> Result { + if request.stage == "strategic_outcome_verifier" { + let rejects_consumption = request + .lived_stream + .contains("\"type\":\"resource_consumed\""); + return Ok(serde_json::json!({ + "verdicts":[{ + "action_digest":self.action_digest, + "result":if rejects_consumption {"mismatch"} else {"match"}, + "repair_guidance":if rejects_consumption { + Some("The inspection does not use spare rope; choose no_material_change.") + } else { + None + } + }] + }) + .to_string()); + } + let mut calls = self.resolver_calls.lock().unwrap(); + *calls += 1; + if *calls == 1 { + return Ok(serde_json::json!({ + "outcomes":[{ + "action_digest":self.action_digest, + "band":"mixed", + "effect_kind":"resource_consumed", + "supporting_state_references":["resource:spare rope"], + "owner_subject_id":"dockers", + "resource":"spare rope" + }] + }) + .to_string()); + } + Ok(serde_json::json!({ + "outcomes":[{ + "action_digest":self.action_digest, + "band":"mixed", + "effect_kind":"no_material_change", + "supporting_state_references":[], + "reason":"The inspection does not use or alter any durable resource." + }] + }) + .to_string()) + } + + fn provider(&self) -> &'static str { + "correcting-outcome-model" + } + } + + #[async_trait::async_trait] + impl ModelPort for RejectingVerifierModel { + async fn run(&self, request: &ModelStageRequest) -> Result { + assert_eq!(request.stage, "strategic_outcome_verifier"); + Ok(serde_json::json!({ + "verdicts":[{ + "action_digest":self.action_digest, + "result":"mismatch", + "repair_guidance":"The inspection never uses or expends spare rope; choose no_material_change." + }] + }) + .to_string()) + } + + fn provider(&self) -> &'static str { + "rejecting-outcome-verifier" + } + } + #[async_trait::async_trait] impl ModelPort for OutcomeFixtureModel { async fn run(&self, request: &ModelStageRequest) -> Result { self.requests.lock().unwrap().push(request.clone()); + if request.stage == "strategic_outcome_verifier" { + return Ok(serde_json::json!({ + "verdicts":[{ + "action_digest":self.action_digest, + "result":"match", + "repair_guidance":null + }] + }) + .to_string()); + } Ok(serde_json::json!({ "outcomes":[{ "action_digest":self.action_digest, @@ -1444,6 +1791,7 @@ mod tests { .to_string() .contains("owner_subject_id must copy exact resource_owner_id dockers") ); + assert!(error.to_string().contains("exact admissible_effect_kinds")); } #[tokio::test] @@ -1484,6 +1832,8 @@ mod tests { .contains("never action_resolutions") ); assert!(requests[0].lived_stream.contains("Do not emit summary")); + assert!(requests[0].lived_stream.contains("admissible_effect_kinds")); + assert!(requests[0].lived_stream.contains("knowledge_learned")); assert_eq!( requests[0].snapshot_binding, activity_outcome_binding( @@ -1494,4 +1844,136 @@ mod tests { ) ); } + + #[test] + fn prepare_context_projects_only_locally_admissible_durable_handles() { + let value = campaign(); + let mut action = proposal(); + action.effect = StrategicCellEffect::GestaltActivity { + gestalt_id: "dockers".into(), + activity: StrategicActivityKind::Prepare, + target_subject_ids: vec![], + location_ids: vec!["dock".into()], + }; + + let context = action_context(&value, &action).unwrap(); + + assert!( + context + .admissible_effect_kinds + .contains(&OutcomeEffectKind::NoMaterialChange) + ); + assert!( + context + .admissible_effect_kinds + .contains(&OutcomeEffectKind::ResourceCreated) + ); + assert!( + context + .admissible_effect_kinds + .contains(&OutcomeEffectKind::ResourceConsumed) + ); + assert!( + context + .admissible_effect_kinds + .contains(&OutcomeEffectKind::GestaltPressure) + ); + assert!( + !context + .admissible_effect_kinds + .contains(&OutcomeEffectKind::KnowledgeLearned) + ); + } + + #[test] + fn outcome_shape_error_names_the_exact_irrelevant_fields() { + let proposal = OutcomeProposal { + action_digest: "sha256:ignored".into(), + band: StrategicOutcomeBand::Success, + effect_kind: OutcomeEffectKind::AgencyRelationShift, + supporting_state_references: vec![], + owner_subject_id: Some("dockers".into()), + other_subject_id: Some("rivals".into()), + relation_id: Some("dock-rivalry".into()), + strength_delta: Some(-2), + resource: None, + pressure_additions: vec![], + pressure_resolutions: vec![], + member_id: None, + memory: None, + obligation: None, + relationship_description: None, + fact_id: None, + reason: None, + }; + + let error = bind_effect(&proposal).unwrap_err().to_string(); + + assert!(error.contains("other_subject_id, owner_subject_id")); + assert!(error.contains("relation_id, strength_delta")); + } + + #[tokio::test] + async fn independent_verifier_can_reject_a_structurally_legal_unrelated_resource_cost() { + let value = campaign(); + let action = proposal(); + let digest = cell_action_digest(&action).unwrap(); + let outcome = StrategicActivityOutcome { + schema: "ghostlight.strategic_activity_outcome.v1".into(), + action_digest: digest.clone(), + source_subject_id: "dockers".into(), + band: StrategicOutcomeBand::Mixed, + summary: "Dockers expends spare rope.".into(), + supporting_state_references: vec!["resource:spare rope".into()], + effect: StrategicOutcomeEffect::ResourceConsumed { + owner_subject_id: "dockers".into(), + resource: "spare rope".into(), + }, + }; + validate_activity_outcomes( + &value, + std::slice::from_ref(&action), + std::slice::from_ref(&outcome), + ) + .unwrap(); + let context = build_context(&value, std::slice::from_ref(&action)).unwrap(); + + let (_, mismatches) = verify_outcomes( + &RejectingVerifierModel { + action_digest: digest.clone(), + }, + &value, + &context, + &[outcome], + &[digest], + &[], + ) + .await + .unwrap(); + + assert_eq!(mismatches.len(), 1); + assert!(mismatches[0].contains("never uses or expends spare rope")); + } + + #[tokio::test] + async fn verifier_rejection_returns_to_resolver_without_mutating_the_effect() { + let value = campaign(); + let action = proposal(); + let digest = cell_action_digest(&action).unwrap(); + let model = CorrectingOutcomeModel { + action_digest: digest, + resolver_calls: Mutex::new(0), + }; + + let (outcomes, stages) = resolve_activity_outcomes(&model, &value, &[action]) + .await + .unwrap(); + + assert_eq!(stages.len(), 3); + assert!(matches!( + outcomes[0].effect, + StrategicOutcomeEffect::NoMaterialChange { .. } + )); + assert_eq!(*model.resolver_calls.lock().unwrap(), 2); + } } diff --git a/crates/ghostlight-dungeon/src/persona.rs b/crates/ghostlight-dungeon/src/persona.rs index c12cec8..fe2e151 100644 --- a/crates/ghostlight-dungeon/src/persona.rs +++ b/crates/ghostlight-dungeon/src/persona.rs @@ -838,7 +838,7 @@ impl CellProjectionEngine { "Copy each subject's allowed_effect_type: institution -> institution, gestalt -> gestalt pressure transition, gestalt_activity, or gestalt_migration, actor -> actor_move, named member -> member_migration or member_activity. ", "Use gestalt_activity or member_activity for a concrete attempt that does not itself change pressure. Map attempts narrowly: communicate means speak, send, offer, ask, or notify; coordinate means arrange a joint attempt; prepare means the subject's own concrete work; investigate means seek information; recruit means invite; trade means offer an exchange; obstruct means attempt interference. ", "target_subject_ids and location_ids must come from that exact subject's permissions. Every activity has at most four unique target_subject_ids; choose the four most causally relevant when more permitted subjects are involved. A member_activity uses exactly the member's source_location_id. Internal work is prepare with no targets. A local investigate may have no target and use the exact current location to seek information from the environment or an unnamed ordinary role; asking an unnamed clerk or dock master for facts maps here and records only the inquiry, never a reply or discovery. A local communicate may likewise have no target at the exact current location when the Persona speaks, sends, offers, asks permission, or notifies an unnamed ordinary role; it records only the source's outgoing attempt, never a listener, reply, acceptance, or outcome. Communication with a canonical subject requires that exact target ID. Never substitute a containing population, related institution, or merely permitted ID for an unnamed role. ", - "Write intended_effect as the attempted act, never its hoped-for outcome or target response. Institution posture must be a specific materially new commitment or withholding of at most 240 characters. already_committed_posture is state already in force: maintaining, continuing, or restating it is inaction and must not emit an institution action. Gestalt pressure_resolutions copy exact current_pressures; additions are new unresolved constraints, never completed actions. Use only permitted state references and public channels. ", + "Write intended_effect as the attempted act, never its hoped-for outcome or target response. Merely waiting, watching, staying, holding position, or remaining ready is attributed inaction, not prepare. prepare requires concrete work on a bounded arrangement, repair, resource, or capability-backed readiness change. Institution posture must be a specific materially new commitment or withholding of at most 240 characters. already_committed_posture is state already in force: maintaining, continuing, or restating it is inaction and must not emit an institution action. Gestalt pressure_resolutions copy exact current_pressures; additions are new unresolved constraints, never completed actions. Use only permitted state references and public channels. ", "A population that chooses to board, depart, or relocate together to one supplied migration_destinations key emits gestalt_migration; do not reduce it to prepare. It relocates only that exact population leaf and never implies a named member traveled. A named member who chooses to board, depart, travel, or join a supplied destination emits member_migration; use prepare only while departure remains unchosen. ", "A population or arena cannot migrate a person. Runtime binds identity and effect owner IDs from subject_id. Do not emit institution_id, gestalt_id, actor_id, or member_id inside effect. An inaction means that exact subject takes no strategic action in this horizon. Record only a subject that explicitly holds, waits without making another attempt, or merely continues already_committed_posture in the Persona turn as an inaction, using its exact subject_id and a concrete reason of at most 160 characters. Waiting for the result of an action, withholding a different possible action, or declining one option after choosing another does not make the chosen action an inaction. Never invent an inaction for an unvoiced subject or use absence of a Persona decision as a reason. Inactions share the same count limit stated for actions. A subject cannot appear in both actions and inactions. When nobody acts, actions is empty and inactions must still contain at least one exact attributed decision from the Persona turn." ), diff --git a/docs/architecture/ghostlight-multiresolution-agency.md b/docs/architecture/ghostlight-multiresolution-agency.md index b95d35f..42a71d7 100644 --- a/docs/architecture/ghostlight-multiresolution-agency.md +++ b/docs/architecture/ghostlight-multiresolution-agency.md @@ -768,14 +768,30 @@ bound. The contract now admits inaction only for a subject that explicitly holds or waits in the Persona turn, forbids absence-as-inaction, and asks for a reason of at most 160 characters while retaining the 240-character hard bound. -The run also exposes the next authority gap. Institution postures, population -migration, clocks, and history changed canonically, but most Gestalt activities -remain attributed attempts recorded as events. Over many ticks this can repeat -an unresolved pressure instead of producing enough typed resource, bargain, -relationship, or obligation changes. A strategic outcome resolver must own -those consequences after proposal attribution and before the atomic -WorldKernel commit; the Interpreter must not gain authority to declare its own -hoped-for outcome. +The strategic outcome resolver closes the attempt/result authority gap. +Institution postures, population migration, clocks, and history remain kernel +state; selected Gestalt activities are digest-bound attempts. One batched +resolver receives only those attempts and deterministic admissible consequence +handles, then returns one typed result per attempt. The Interpreter cannot +declare its own hoped-for outcome. + +Local validation owns ordinary bounded preparations, pressure changes, and +discoverable knowledge. Effects with easy-to-hide private authority mistakes— +resource consumption or transfer, agency-relation shifts, and named-member +memory, obligation, or relationship deltas—also pass through an independent +same-snapshot semantic verifier. Its verdict is advisory to the resolver retry, +never a writer. Applying that verifier to every harmless preparation was both +expensive and over-strict, so the risk boundary is deliberately selective. + +The current provider-backed golden completed four waves across budgets +`1 -> 4 -> 8 -> 4` in 81.28 seconds in a debug build. It produced ten durable +consequences and seven typed material activity outcomes, with three explicit +no-material-change results, zero rejected pulses, exact member attribution, +the player unchanged, and the same Mira returning with her persistent delta. +It used 126,826 prompt tokens, 14,477 completion tokens, and a 58.34% prompt +cache-hit ratio. This proves the ordinary material-outcome path live; the +selective high-risk verifier is covered locally and still needs a forced live +provider witness. The Starfire deployment smoke ran a live provider-backed wave over three eligible singleton cells, committed three offscreen events and three diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 5b97797..342323e 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -377,14 +377,21 @@ correct binding commits the material result, and a malformed late outcome cannot partially apply an earlier one. CultCache stores outcomes individually and the operator Eve projection exposes them. -Do not call setting-wide material agency finished until the revised live -Gestalt harness passes. It now refuses to count an activity attempt as a -material consequence, requires at least one sustained direct or typed material -result, and permits Mira's dormant delta to evolve only when an exact -member-bound outcome accounts for the change. Run a small golden first, then a -budget/parallelism pressure profile; inspect material-outcome rate, no-change -rate, retries, cache hits, and player/arena invariants before the two-tester -playtest. +The revised live Gestalt harness now passes. Its four provider-backed waves at +budgets `1 -> 4 -> 8 -> 4` produced ten durable consequences and seven typed +material activity outcomes, with three explicit no-change results and zero +rejected pulses. The player remained unchanged, member changes stayed bound to +exact outcomes, and the same Mira returned with effective personal state. The +run used 126,826 prompt tokens, 14,477 completion tokens, and a 58.34% prompt +cache-hit ratio. The harness requires at least one typed material activity +outcome, so unrelated direct consequences cannot counterfeit success. + +High-risk effects—custody consumption/transfers, agency-relation shifts, and +named-member private deltas—now receive an independent same-snapshot semantic +verdict before admission. Low-risk preparations and pressures remain locally +validated; a verifier on every effect caused disproportionate retries and was +cut. The high-risk path has local regression proof but still needs a forced +live provider witness. The multiresolution body is deployed on Starfire. Typed health matched the immutable release, DeepSeek was ready, and the disposable live strategic-cell @@ -750,12 +757,15 @@ remote candidates into an approval-visible non-canonical coverage gap. Authenticated HTTP/browser, session isolation, lifecycle, export, persistence, restart, strategic agency, and live/background exclusion have isolated-runtime -evidence. The deployment smoke is complete. The multiresolution live profile -now makes the next runtime cut concrete: design a strategic outcome resolver -between attributed attempts and kernel commit, then pressure its typed material -effects before the two-tester playtest. Inspect the semantic-verifier rejection -tail alongside that work; do not recover efficiency by weakening atomic waves -or letting the Interpreter claim outcomes. +evidence. The strategic outcome resolver now has a clean provider-backed +four-wave golden: ten durable consequences, seven typed material activity +outcomes, zero rejected pulses, exact member binding, no player mutation, and +Mira's persistent identity across consolidation. High-risk custody, relation, +and named-member effects receive an independent same-snapshot semantic verdict; +ordinary preparations remain deterministically bounded without paying that +model tax. The next action is to commit this exact candidate, deploy its +optimized immutable build, and repeat authenticated browser/restart/persistence +checks against the served commit before the two-tester playtest. ## Warnings diff --git a/notes/ghostlight-current-system-map.md b/notes/ghostlight-current-system-map.md index 85be09c..3c9eecb 100644 --- a/notes/ghostlight-current-system-map.md +++ b/notes/ghostlight-current-system-map.md @@ -140,6 +140,16 @@ CultCache and projected on the operator Eve surface. All effects apply to the same private campaign copy as the rest of the strategic wave, so a late invalid outcome cannot leave an earlier action, clock, detail debt, or event committed. +Deterministic admissible-effect handles constrain every resolver decision. +Ordinary bounded preparation, pressure, and knowledge effects stop at local +validation. Resource consumption/transfers, agency-relation shifts, and named +member private deltas additionally receive an independent same-snapshot +semantic verdict because those effects can be structurally valid while charging +the wrong inventory or person. The verifier proposes no state and cannot +commit. The latest provider-backed four-wave golden produced seven typed +material activity outcomes, ten durable consequences, and zero rejected pulses +while leaving the player unchanged and returning the same Mira. + `gestalt_migration` records a collective decision by one exact active leaf to move along an explicit migration relation and reachable route. WorldKernel changes the leaf's home location and agency-profile location together. The diff --git a/notes/ghostlight-implementation-plan.md b/notes/ghostlight-implementation-plan.md index 063b30d..1d75a9f 100644 --- a/notes/ghostlight-implementation-plan.md +++ b/notes/ghostlight-implementation-plan.md @@ -74,15 +74,24 @@ ownership, single-use invite rejection, fork/reset/export, four persisted campaigns, and exact-commit restart. Live priority cancels in-flight scheduler inference and excludes its commit gate. -Next, run the revised Gestalt live golden and a bounded multiresolution pressure -profile. The harness must observe real typed background change rather than -counting attempts, preserve exact arena/member/player authority, and report -material-outcome rate, no-change rate, retries, cache hits, and token cost. -Then run the two-tester playtest. Treat player confusion, dramatic flatness, and +The revised provider-backed Gestalt golden now passes across four waves and +budget changes `1 -> 4 -> 8 -> 4`. It committed ten durable consequences, +including seven typed material activity outcomes, while preserving exact +member binding, the absent player, and Mira's persistent identity. All four +pulses committed without retry. The run used 126,826 prompt tokens with a +58.34% cache-hit ratio and 14,477 completion tokens. The harness now requires a +typed material outcome; unrelated direct consequences can no longer hide an +inert outcome resolver. + +The next gate is release truth: commit and publish this exact candidate, deploy +an immutable optimized build to Starfire, and repeat authenticated browser and +restart checks against the served commit. Then begin the two-tester playtest. +Treat player confusion, dramatic flatness, composite consequences, and token-heavy low-consequence stages as evidence about missing context or -misplaced authority. Use model-stage cache usage, rejection receipts, cover -plans, outcomes, and world commits to improve satisfaction and cognitive -efficiency without weakening state admission. +misplaced authority. Keep the independent semantic outcome verifier selective: +it checks custody transfers, relation shifts, and named-member private deltas, +while deterministic local validation owns ordinary bounded preparations and +pressure changes. Multiplayer remains outside the current paid-alpha gate but is now an explicit architectural intention. Do not fork the simulation into a multiplayer room diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 17ba93b..5a59111 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -85,3 +85,4 @@ {"ts":"2026-08-17T16:54:00Z","type":"verification","status":"ok","branch":"codex/ghostlight-dungeon-mvp","note":"Exact commit 84951fda6f17d06a03456ecef5d79f833006b92d completed the live VoidBot/DeepSeek compiler in 43.35 seconds with five first-attempt-valid stages. The seed admitted one local institution and a separately compiled global skeleton of 17 remote institutions; every remote agency profile carries only coarse deterministic facets plus nonempty evidence receipt IDs drawn from the preview's exact five Vault receipts. Ten unsupported agency candidates were omitted into one approval-visible coverage gap, and remote coverage gaps did not become canon candidates. Witness: F:\\GameCult\\GhostlightDungeon\\acceptance\\compiler-20260817-165127\\result.json."} {"ts":"2026-08-17T17:22:30Z","type":"deployment","status":"ok","branch":"codex/ghostlight-dungeon-mvp","note":"Starfire activated immutable release f1d55b181ad60ace8e8e92859c4d0b2f1a94fc87 with binary SHA-256 119772af15859d8c26e7239d705a229ce01b24d6a7e70105b78e4df227ef0583. Active junction, release manifest, executable hash, PID 26140, typed health, persisted campaign count, ready DeepSeek startup inference, and the Ghostlight-owned CultMesh store agree. Periwinkle at 192.168.178.158 received exact health over the LocalSubnet lane and HTTP 401 for unauthenticated campaign access; Raven and Yggdrasil independently received exact health over WireGuard. Windows-generated public prompt rules were removed; the only Ghostlight rules admit TCP 8831 from LocalSubnet and 10.77.0.0/24. Live VoidBot retrieval returned the canonical Aetheria factions source, and the deployed browser renders a non-interactive authentication gate when no valid session exists."} {"ts":"2026-08-18T14:36:02Z","type":"design","status":"accepted","branch":"codex/ghostlight-dungeon-mvp","note":"Multiplayer is an intended post-solo extension of the existing one-WorldKernel, many-actor authority model. Multiple authenticated humans will control distinct actors through the same campaign mailbox, perception gates, initiative, and atomic commit path; no party prompt or room-state authority is introduced. The paid alpha remains single-player while multiresolution Gestalt proof stays the immediate forge priority."} +{"ts":"2026-08-18T16:15:00Z","type":"verification","status":"ok","branch":"codex/ghostlight-dungeon-mvp","note":"The provider-backed strategic-outcome golden completed four waves across active-cell budgets 1, 4, 8, and 4 in 81.28 seconds in a debug build. It committed ten durable consequences including seven typed material activity outcomes, recorded three explicit no-material-change results, rejected zero pulses, preserved exact member attribution, left the player unchanged, and returned the same Mira with persistent state. Usage was 126826 prompt tokens, 73984 cache-hit prompt tokens (58.34%), and 14477 completion tokens. The harness now requires a typed material activity outcome. Selective independent semantic verification protects resource custody/transfers, agency-relation shifts, and named-member private deltas; its local regressions pass, while a forced live high-risk witness remains outstanding. Witness: F:\\GameCult\\GhostlightDungeon\\acceptance\\outcome-risk-verifier-20260818\\result.json."} diff --git a/state/map.yaml b/state/map.yaml index 7ce9fe1..e3f48a9 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -270,6 +270,6 @@ data_flow: - If state grows faster than understanding, cut it back. current_status: - summary: GhostlightDungeon production remains on the verified Starfire release. Exact-build live witness gestalt-lease-b8p8-d044951-1 completed 23 budget-8/provider-8 waves over all 24 subjects, committed 175 consequences, preserved rival and named-member agency through 90 arena cells, recovered 19 rejected pulses without partial mutation, and automatically returned the same Mira with effective personal state intact. The immutable-snapshot strategic apply path held. Production state remains untouched. - next_action: Design the strategic outcome resolver as a separate authority between attributed attempts and WorldKernel commit, so population activity can produce typed resources, bargains, obligations, relationships, and pressure changes without letting the Interpreter assert success. In parallel, inspect the semantic-verifier failure tail: rejected pulses consumed 40.59% of observed prompt work despite a 66.64% overall cache-hit rate. + summary: GhostlightDungeon production remains on the verified older Starfire release. The current candidate's provider-backed material-outcome golden completed four waves across budgets 1, 4, 8, and 4 with zero rejected pulses, ten durable consequences, seven typed material activity outcomes, exact member binding, no player mutation, and the same Mira returning with persistent state. A selective independent verifier now protects high-risk custody, relation, and named-member private effects without taxing every low-risk preparation. + next_action: Commit and push the exact accepted candidate, build and deploy its immutable optimized release to Starfire, and repeat authenticated browser, restart, served-commit, and persistence checks. Then force one live high-risk outcome-verifier witness and begin human playtesting while measuring composite consequences, retries, cache hits, and dramatic yield per token. gestalt_population: Gestalt Personas own shared population baselines; persistent member deltas own named individuality; WorldKernel materialization and approval-gated fission preserve lineage and identity. Presence projection is limited to nearby active leaves and exact-location dormant members, includes reciprocal player relationship evidence, and may propose an earned cast without committing it. Simulation cells are derived covers only.