From 37f1e873b1f932da0498e733a8cea676b7d5ac1f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 17 Aug 2026 22:39:52 +0200 Subject: [PATCH] Verify Persona effects before world resolution --- crates/ghostlight-dungeon/src/kernel.rs | 116 +++++++++- crates/ghostlight-dungeon/src/persona.rs | 215 +++++++++++++++++- .../ghostlight-multiresolution-agency.md | 10 + notes/ghostlight-dungeon.md | 8 +- 4 files changed, 339 insertions(+), 10 deletions(-) diff --git a/crates/ghostlight-dungeon/src/kernel.rs b/crates/ghostlight-dungeon/src/kernel.rs index 1c00f92..91635cf 100644 --- a/crates/ghostlight-dungeon/src/kernel.rs +++ b/crates/ghostlight-dungeon/src/kernel.rs @@ -399,8 +399,19 @@ fn execute( } if let Some(wave) = &resolution_wave { let unique_hashes: BTreeSet<_> = wave.model_receipt_hashes.iter().collect(); + let actionful_cell_count = wave + .appraisals + .iter() + .filter(|appraisal| !appraisal.actions.is_empty()) + .count(); if unique_hashes.len() != wave.model_receipt_hashes.len() - || wave.model_receipt_hashes.len() < wave.cover.cells.len().saturating_mul(3) + || wave.model_receipt_hashes.len() + < wave + .cover + .cells + .len() + .saturating_mul(3) + .saturating_add(actionful_cell_count) { return Err(KernelError::Invalid( "resolution wave does not carry one distinct stage receipt per cell stage" @@ -422,8 +433,10 @@ fn execute( "resolution wave contains a mismatched model receipt".into(), )); } - stage_bindings - .insert((receipt.stage.clone(), receipt.snapshot_binding.clone())); + if receipt.validation_result == "valid" { + stage_bindings + .insert((receipt.stage.clone(), receipt.snapshot_binding.clone())); + } } for cell in &wave.cover.cells { let binding = format!( @@ -441,6 +454,20 @@ fn execute( ))); } } + let actionful = wave + .appraisals + .iter() + .find(|appraisal| appraisal.cell_id == cell.id) + .is_some_and(|appraisal| !appraisal.actions.is_empty()); + if actionful + && !stage_bindings + .contains(&("cell_effect_verifier".into(), binding.clone())) + { + return Err(KernelError::Invalid(format!( + "resolution wave lacks cell_effect_verifier receipt for {}", + cell.id + ))); + } } } campaign.world_time += Duration::hours(i64::from(campaign.tick_hours)); @@ -3299,6 +3326,89 @@ mod tests { assert_eq!(store.keys("strategic_tick.v1").unwrap().len(), 1); } + #[tokio::test] + async fn invalid_effect_verifier_receipt_cannot_authorize_an_actionful_cell() { + let dir = tempfile::tempdir().unwrap(); + let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); + let kernel = WorldKernel::start(store.clone()); + let seed = crate::resolution::tests::campaign(3, 1); + kernel + .command(WorldCommand::CreateCampaign { + campaign: seed.clone(), + evidence_receipts: vec![], + model_stage_receipts: vec![], + }) + .await + .unwrap(); + let persisted = store + .load::("campaign.v1", &seed.id.to_string()) + .unwrap() + .unwrap() + .1; + let mut wave = inaction_wave(&persisted, &store); + let subject_id = wave.cover.cells[0] + .subject_ids + .iter() + .next() + .unwrap() + .clone(); + wave.appraisals[0].actions = vec![CellActionProposal { + subject_id: subject_id.clone(), + intent: "adopt a new position".into(), + intended_effect: "publish a different commitment".into(), + priority: 1, + state_references: vec![], + public_channels: vec![], + effect: StrategicCellEffect::Institution { + institution_id: subject_id, + posture: "publishing a bounded new commitment".into(), + location_ids: vec![], + }, + }]; + wave.appraisals[0].inaction_reason = None; + let mut rejected_verifier = resolution_stage( + &wave.cover.cells[0].id, + &persisted, + "cell_effect_verifier", + 'd', + ); + rejected_verifier.validation_result = "semantic_invalid".into(); + rejected_verifier.local_validation_error = + Some("typed effect reverses the decision".into()); + store + .insert( + "persona_stage_receipt.v1", + "ghostlight.persona_stage_receipt.v1", + rejected_verifier.storage_key(), + &rejected_verifier, + ) + .unwrap(); + wave.model_receipt_hashes + .push(rejected_verifier.storage_key().to_owned()); + + let error = kernel + .command(WorldCommand::AdvanceStrategicTick { + expected_revision: 0, + source: TickSource::Scheduler, + plan: None, + model_receipt_hash: Some(format!("sha256:{}", "9".repeat(64))), + resolution_wave: Some(wave), + }) + .await + .unwrap_err(); + assert!( + error.to_string().contains("lacks cell_effect_verifier"), + "unexpected kernel rejection: {error}" + ); + let stored = store + .load::("campaign.v1", &seed.id.to_string()) + .unwrap() + .unwrap() + .1; + assert_eq!(stored.revision, 0); + assert_eq!(stored.world_time, seed.world_time); + } + #[tokio::test] async fn stale_resolution_wave_leaves_time_clocks_and_campaign_unmutated() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/ghostlight-dungeon/src/persona.rs b/crates/ghostlight-dungeon/src/persona.rs index 0e224f0..2782584 100644 --- a/crates/ghostlight-dungeon/src/persona.rs +++ b/crates/ghostlight-dungeon/src/persona.rs @@ -127,6 +127,14 @@ struct CellAppraisalProposal { inaction_reason: Option, } +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +#[serde(deny_unknown_fields)] +struct CellEffectVerification { + supported: bool, + rejected_action_indices: Vec, + rationale: String, +} + const CELL_APPRAISAL_OUTPUT_CONTRACT: &str = r#"{ "type":"object", "required":["actions","inaction_reason"], @@ -536,6 +544,74 @@ impl CellProjectionEngine { }) { Ok(appraisal) => { stage_receipts.push(interpreted.receipt); + if !appraisal.actions.is_empty() { + self.permit + .require( + &slice.cell_id, + &slice.snapshot_binding, + "cell_effect_verifier", + ) + .await?; + let verifier_context = serde_json::json!({ + "persona_turn":persona.narrative, + "candidate_actions":appraisal.actions.iter().enumerate().map(|(index, action)| serde_json::json!({ + "index":index, + "subject_id":action.subject_id, + "intent":action.intent, + "intended_effect":action.intended_effect, + "typed_effect":action.effect, + })).collect::>(), + "subject_names":slice.constituents.iter().map(|subject|(&subject.subject_id, &subject.name)).chain(slice.member_exceptions.iter().map(|member|(&member.subject_id, &member.name))).collect::>(), + }); + let mut verified = run_validated_stage( + self.model.as_ref(), + &ModelStageRequest { + stage: "cell_effect_verifier".into(), + model: self.interpreter_model.clone(), + snapshot_binding: slice.snapshot_binding.clone(), + lived_stream: format!( + "You are the private semantic verifier between an Interpreter and the world kernel. Decide whether every candidate typed effect faithfully represents the exact attributed subject's own attempted consequence in the Persona turn. Structural permissions were already checked. A member_migration means that named member personally chooses to travel to the destination; giving away a berth, sending somebody else, waiting, or merely considering travel does not entail it. An institution posture must express its stated commitment or withholding. A gestalt pressure resolution must be causally supported by its stated attempt, and an added pressure must be a resulting unresolved condition rather than completed-action prose. Reject omissions, reversals, subject swaps, wishful outcomes, and effects that the Persona did not choose. Be concise. Return JSON only.\n\nCONTEXT:\n{}", + serde_json::to_string(&verifier_context)? + ), + output_schema: Some(serde_json::to_value(schema_for!( + CellEffectVerification + ))?), + source_receipt_ids: slice.source_receipt_ids.clone(), + temperature: Some(0.0), + max_output_tokens: Some(384), + }, + ) + .await?; + let verification: CellEffectVerification = + serde_json::from_value(verified.structured.clone().ok_or_else( + || anyhow!("cell effect verifier produced no typed verdict"), + )?)?; + validate_effect_verification(&verification, appraisal.actions.len())?; + if verification.supported { + stage_receipts.push(verified.receipt); + } else { + let error = anyhow!( + "effect verifier rejected action indices {:?}: {}", + verification.rejected_action_indices, + verification.rationale + ); + verified.receipt.validation_result = "semantic_invalid".into(); + verified.receipt.local_validation_error = + Some(error.to_string().chars().take(1_000).collect()); + stage_receipts.push(verified.receipt); + if attempt == 0 { + append_cell_correction( + &mut request, + &error, + &serde_json::to_string(&appraisal.actions)?, + ); + continue; + } + return Err(anyhow!( + "cell effect verifier rejected the corrected appraisal: {error}" + )); + } + } self.permit .require(&slice.cell_id, &slice.snapshot_binding, "cell_terminal") .await?; @@ -557,9 +633,7 @@ impl CellProjectionEngine { interpreted.receipt.local_validation_error = Some(error.to_string().chars().take(1_000).collect()); stage_receipts.push(interpreted.receipt); - request.lived_stream.push_str(&format!( - "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS APPRAISAL: {error}\nPREVIOUS_REJECTED_APPRAISAL:\n{rejected_appraisal}\nReturn one corrected complete appraisal against the same snapshot, lived stream, Persona turn, and exact permission context. Change or remove every action that exceeds its attributed constituent's permissions; explicit inaction is valid." - )); + append_cell_correction(&mut request, &error, &rejected_appraisal); } Err(error) => { return Err(anyhow!( @@ -572,6 +646,35 @@ impl CellProjectionEngine { } } +fn append_cell_correction( + request: &mut ModelStageRequest, + error: &anyhow::Error, + rejected_appraisal: &str, +) { + request.lived_stream.push_str(&format!( + "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS APPRAISAL: {error}\nPREVIOUS_REJECTED_APPRAISAL:\n{rejected_appraisal}\nReturn one corrected complete appraisal against the same snapshot, lived stream, Persona turn, and exact permission context. Change or remove every action that is unsupported or exceeds its attributed subject's permissions; explicit inaction is valid." + )); +} + +fn validate_effect_verification( + verification: &CellEffectVerification, + action_count: usize, +) -> Result<()> { + if verification.rationale.trim().is_empty() + || (verification.supported && !verification.rejected_action_indices.is_empty()) + || (!verification.supported && verification.rejected_action_indices.is_empty()) + || verification + .rejected_action_indices + .iter() + .any(|index| *index >= action_count) + { + return Err(anyhow!( + "cell effect verifier returned an incoherent verdict" + )); + } + Ok(()) +} + fn bind_cell_appraisal( slice: &PermittedCellSlice, proposal: CellAppraisalProposal, @@ -925,6 +1028,12 @@ mod tests { "inaction_reason":null }).to_string()) } + "cell_effect_verifier" => Ok(serde_json::json!({ + "supported":true, + "rejected_action_indices":[], + "rationale":"The institution's typed posture matches its stated commitment." + }) + .to_string()), stage => Err(anyhow!("unexpected fixture stage {stage}")), } } @@ -986,7 +1095,7 @@ mod tests { }; let output = engine.execute(fixture_cell_slice()).await.unwrap(); assert!(model.saw_rejected_appraisal.load(Ordering::SeqCst)); - assert_eq!(output.stage_receipts.len(), 4); + assert_eq!(output.stage_receipts.len(), 5); assert_eq!( output.stage_receipts[2].validation_result, "semantic_invalid" @@ -997,6 +1106,104 @@ mod tests { )); } + struct SemanticallyCorrectingCellModel { + interpreter_calls: AtomicUsize, + verifier_calls: AtomicUsize, + saw_verifier_rejection: AtomicBool, + } + + #[async_trait] + impl ModelPort for SemanticallyCorrectingCellModel { + async fn run(&self, request: &ModelStageRequest) -> Result { + match request.stage.as_str() { + "cell_projector" => Ok( + "Faction Six sees the deadline but lacks evidence for an immediate release." + .into(), + ), + "cell_persona" => Ok( + "We will withhold the reserve commitment until the public count is verified." + .into(), + ), + "cell_interpreter" => { + let correction = self.interpreter_calls.fetch_add(1, Ordering::SeqCst) > 0; + if correction { + self.saw_verifier_rejection.store( + request.lived_stream.contains("effect verifier rejected") + && request.lived_stream.contains("releases the reserve"), + Ordering::SeqCst, + ); + } + Ok(serde_json::json!({ + "actions":[{ + "subject_id":"faction-06", + "intent":"state the reserve decision", + "intended_effect":if correction {"withhold release pending a verified count"} else {"release the reserve immediately"}, + "priority":5, + "state_references":["institution:faction-06"], + "public_channels":["public bulletin"], + "effect":{ + "type":"institution", + "institution_id":"faction-06", + "posture":if correction {"withholding reserve commitment pending a verified public count"} else {"releases the reserve immediately"}, + "location_ids":["forum"] + } + }], + "inaction_reason":null + }).to_string()) + } + "cell_effect_verifier" => { + let correction = self.verifier_calls.fetch_add(1, Ordering::SeqCst) > 0; + Ok(serde_json::json!({ + "supported":correction, + "rejected_action_indices":if correction { vec![] } else { vec![0] }, + "rationale":if correction { + "The corrected posture matches the institution's stated withholding." + } else { + "The Persona withheld the reserve, but the typed effect releases it." + } + }) + .to_string()) + } + stage => Err(anyhow!("unexpected fixture stage {stage}")), + } + } + + fn provider(&self) -> &'static str { + "semantic-correction-fixture" + } + } + + #[tokio::test] + async fn effect_verifier_rejects_a_reversed_decision_before_terminal_output() { + let model = Arc::new(SemanticallyCorrectingCellModel { + interpreter_calls: AtomicUsize::new(0), + verifier_calls: AtomicUsize::new(0), + saw_verifier_rejection: AtomicBool::new(false), + }); + let output = CellProjectionEngine { + model: model.clone(), + permit: Arc::new(AllowAllPermit), + projector_model: "flash".into(), + persona_model: "flash".into(), + interpreter_model: "flash".into(), + } + .execute(fixture_cell_slice()) + .await + .unwrap(); + assert!(model.saw_verifier_rejection.load(Ordering::SeqCst)); + assert_eq!(output.stage_receipts.len(), 6); + assert_eq!(output.stage_receipts[3].stage, "cell_effect_verifier"); + assert_eq!( + output.stage_receipts[3].validation_result, + "semantic_invalid" + ); + let StrategicCellEffect::Institution { posture, .. } = &output.appraisal.actions[0].effect + else { + panic!("corrected effect changed type") + }; + assert!(posture.contains("withholding reserve")); + } + #[test] fn empty_cell_appraisal_names_the_missing_inaction_reason() { let slice = fixture_cell_slice(); diff --git a/docs/architecture/ghostlight-multiresolution-agency.md b/docs/architecture/ghostlight-multiresolution-agency.md index 862176c..fe6f6dc 100644 --- a/docs/architecture/ghostlight-multiresolution-agency.md +++ b/docs/architecture/ghostlight-multiresolution-agency.md @@ -266,6 +266,16 @@ population transition receives its exact current pressure set and the failed transition reason. The correction model is not expected to reconstruct a validator from a generic rejection. +An actionful cell has a fourth private stage after the Interpreter: the +`cell_effect_verifier`. This cheap structured reader compares the natural +Persona decision with each attributed typed effect. It rejects reversals, +subject swaps, omissions, wishful outcomes, or lossy mappings—for example, +mapping “Mira gives her berth to somebody else” into a migration of Mira +herself. The rejected appraisal and concise rationale return to one +same-snapshot Interpreter correction. Inaction cells skip the call. The kernel +requires a valid verifier receipt for every actionful cell; an invalid or +missing verifier cannot satisfy the wave receipt gate. + ## Public state and controls The schema catalog and CultCache stores publish: diff --git a/notes/ghostlight-dungeon.md b/notes/ghostlight-dungeon.md index 484cdca..e3661ee 100644 --- a/notes/ghostlight-dungeon.md +++ b/notes/ghostlight-dungeon.md @@ -188,9 +188,11 @@ stake prose alone never impersonates world mutation. authority, while opposed or cross-faction cells are arenas with no synthetic actor or shared knowledge. - Every active cell receives one private Projector → Persona → Interpreter - pipeline. Arena output is constituent-attributed. All cells, receipts, and - effects validate against one world revision and resolution epoch before one - atomic strategic commit. + pipeline, followed by a semantic effect verifier when the cell proposes an + action. Arena output is constituent-attributed. The verifier proves that the + typed effect represents the Persona's actual choice rather than a reversed or + lossy interpretation. All cells, receipts, and effects validate against one + world revision and resolution epoch before one atomic strategic commit. - Persistent detail debt rotates direct attention through quiet subjects. All clocks and deterministic obligations advance regardless of selected detail. - Population fission is a separate approval-gated canonical operation. It