From 622d5ba167ad0167723763c9bbb3a05e457791e3 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 18 Aug 2026 10:12:17 +0200 Subject: [PATCH] Resolve strategic activities into typed outcomes --- .../bin/ghostlight-gestalt-dynamics-smoke.rs | 91 +- .../src/bin/ghostlight-strategic-smoke.rs | 18 +- crates/ghostlight-dungeon/src/domain.rs | 76 + crates/ghostlight-dungeon/src/kernel.rs | 757 +++++++++- crates/ghostlight-dungeon/src/lib.rs | 1 + crates/ghostlight-dungeon/src/main.rs | 1 + crates/ghostlight-dungeon/src/mesh.rs | 13 +- crates/ghostlight-dungeon/src/outcome.rs | 1332 +++++++++++++++++ crates/ghostlight-dungeon/src/persistence.rs | 11 + crates/ghostlight-dungeon/src/resolution.rs | 81 +- crates/ghostlight-dungeon/src/scheduler.rs | 64 +- crates/ghostlight-dungeon/src/surface.rs | 3 + docs/architecture/ghostlight-dungeon-mvp.md | 1 + .../ghostlight-multiresolution-agency.md | 95 +- notes/fresh-workspace-handoff.md | 31 +- notes/ghostlight-current-system-map.md | 21 +- notes/ghostlight-implementation-plan.md | 21 +- 17 files changed, 2539 insertions(+), 78 deletions(-) create mode 100644 crates/ghostlight-dungeon/src/outcome.rs 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 92573cf..b594abe 100644 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-dynamics-smoke.rs +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-dynamics-smoke.rs @@ -232,6 +232,7 @@ async fn main() -> anyhow::Result<()> { "elapsed_seconds":started.elapsed().as_secs_f64(), "cover":&output.wave.cover, "appraisals":&output.wave.appraisals, + "activity_outcomes":&output.wave.activity_outcomes, "model_stage_receipts":output.stages.iter().map(|stage|&stage.receipt).collect::>(), "private_cell_traces":&output.private_cell_traces, "private_model_stage_outputs":output.stages.iter().map(|stage|serde_json::json!({ @@ -380,6 +381,9 @@ async fn main() -> anyhow::Result<()> { 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; + let mut sustained_material_outcome_count = 0usize; + let mut mira_outcome_kinds = BTreeSet::new(); detail_focus_subject_ids.extend(direct_resolution_subject_ids(&output.wave.cover.cells)); let sustained_budgets = if presence_only { vec![] @@ -469,11 +473,34 @@ async fn main() -> anyhow::Result<()> { "budget":budget, "cover":&sustained_output.wave.cover, "appraisals":&sustained_output.wave.appraisals, + "activity_outcomes":&sustained_output.wave.activity_outcomes, "private_cell_traces":&sustained_output.private_cell_traces, "model_stage_receipts":sustained_output.stages.iter().map(|stage|&stage.receipt).collect::>(), }))?, )?; let sustained_plan = validate_and_resolve_wave(&advanced, &sustained_output.wave)?; + let direct_material_count = sustained_plan.institution_actions.len() + + sustained_plan.gestalt_actions.len() + + sustained_plan.gestalt_migrations.len() + + sustained_plan.actor_moves.len() + + sustained_plan.member_migrations.len(); + let material_outcome_count = sustained_plan + .activity_outcomes + .iter() + .filter(|outcome| { + !matches!( + outcome.effect, + ghostlight_dungeon::domain::StrategicOutcomeEffect::NoMaterialChange { .. } + ) + }) + .count(); + sustained_material_consequence_count += direct_material_count + material_outcome_count; + sustained_material_outcome_count += material_outcome_count; + for outcome in &sustained_plan.activity_outcomes { + if let Some(kind) = member_outcome_kind(&outcome.effect, "mira-venn") { + mira_outcome_kinds.insert(kind.to_owned()); + } + } for appraisal in &sustained_output.wave.appraisals { for proposal in &appraisal.actions { if proposal.subject_id != "member:mira-venn" { @@ -529,6 +556,9 @@ async fn main() -> anyhow::Result<()> { background_subject_ids.len() ) } + if !presence_only && sustained_material_consequence_count == 0 { + anyhow::bail!("sustained multiresolution waves resolved no material background consequence") + } let fairness_missing_subject_ids = if fairness_stress_waves == 0 { BTreeSet::new() } else { @@ -546,13 +576,25 @@ async fn main() -> anyhow::Result<()> { } let member_after_sustained = &advanced.gestalt_members["mira-venn"]; if member_after_sustained.gestalt_id != "harbor-neighbors" - || member_after_sustained.relationships != member_before.relationships - || member_after_sustained.memories != member_before.memories + || member_after_sustained.name != member_before.name + || member_after_sustained.conditions != member_before.conditions || effective_member_capabilities(&advanced, "mira-venn")? != capabilities_before - || effective_member_knowledge(&advanced, "mira-venn")? != knowledge_before { anyhow::bail!("sustained population simulation damaged Mira's dormant identity") } + if (member_after_sustained.relationships != member_before.relationships + && !mira_outcome_kinds.contains("relationship")) + || (member_after_sustained.memories != member_before.memories + && !mira_outcome_kinds.contains("memory")) + || (member_after_sustained.obligations != member_before.obligations + && !mira_outcome_kinds.contains("obligation")) + || (member_after_sustained.equipment != member_before.equipment + && !mira_outcome_kinds.contains("resource")) + || (effective_member_knowledge(&advanced, "mira-venn")? != knowledge_before + && !mira_outcome_kinds.contains("knowledge")) + { + anyhow::bail!("Mira's dormant delta changed without an exact member-bound outcome") + } let return_event = "The player spends a quiet afternoon repairing the South Harbor ferry steps after the resettlement. The settled harbor populations move through their ordinary routines nearby."; let presence_planner = GestaltPresencePlanner { @@ -634,6 +676,9 @@ async fn main() -> anyhow::Result<()> { "initial_background_action_count":background_action_count, "sustained_background_subject_ids":background_subject_ids, "sustained_detail_focus_subject_ids":detail_focus_subject_ids, + "sustained_material_consequence_count":sustained_material_consequence_count, + "sustained_material_outcome_count":sustained_material_outcome_count, + "mira_outcome_kinds":mira_outcome_kinds, "fairness_stress_waves":fairness_stress_waves, "presence_only":presence_only, "fairness_stress_budget":fairness_stress_budget, @@ -650,7 +695,7 @@ async fn main() -> anyhow::Result<()> { "automatic_presence_plan":presence_plan, "automatic_presence_receipt":presence_receipt, "identity_preserved":true, - "effective_state_preserved":true, + "member_delta_changes_bound_to_outcomes":true, "player_unchanged":true, "return_encounter_same_person":true, "event_kinds":event_kinds, @@ -667,6 +712,44 @@ async fn main() -> anyhow::Result<()> { Ok(()) } +#[cfg(windows)] +fn member_outcome_kind( + effect: &ghostlight_dungeon::domain::StrategicOutcomeEffect, + member_id: &str, +) -> Option<&'static str> { + use ghostlight_dungeon::domain::StrategicOutcomeEffect; + + let member_subject_id = format!("member:{member_id}"); + match effect { + StrategicOutcomeEffect::MemberMemory { + member_id: owner, .. + } if owner == member_id => Some("memory"), + StrategicOutcomeEffect::MemberObligation { + member_id: owner, .. + } if owner == member_id => Some("obligation"), + StrategicOutcomeEffect::MemberRelationship { + member_id: owner, .. + } if owner == member_id => Some("relationship"), + StrategicOutcomeEffect::KnowledgeLearned { + owner_subject_id, .. + } if owner_subject_id == &member_subject_id => Some("knowledge"), + StrategicOutcomeEffect::ResourceCreated { + owner_subject_id, .. + } + | StrategicOutcomeEffect::ResourceConsumed { + owner_subject_id, .. + } if owner_subject_id == &member_subject_id => Some("resource"), + StrategicOutcomeEffect::ResourceTransferred { + from_subject_id, + to_subject_id, + .. + } if from_subject_id == &member_subject_id || to_subject_id == &member_subject_id => { + Some("resource") + } + _ => None, + } +} + #[cfg(windows)] fn lineage_depth( campaign: &ghostlight_dungeon::domain::Campaign, diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs index cce18fe..d5b0108 100644 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs @@ -66,15 +66,25 @@ async fn main() -> anyhow::Result<()> { ) .await?; let plan = ghostlight_dungeon::resolution::validate_and_resolve_wave(&campaign, &output.wave)?; + let material_activity_outcomes = plan + .activity_outcomes + .iter() + .filter(|outcome| { + !matches!( + outcome.effect, + ghostlight_dungeon::domain::StrategicOutcomeEffect::NoMaterialChange { .. } + ) + }) + .count(); if plan.institution_actions.is_empty() && plan.gestalt_actions.is_empty() - && plan.gestalt_activities.is_empty() + && plan.gestalt_migrations.is_empty() && plan.actor_moves.is_empty() - && plan.member_activities.is_empty() + && plan.member_migrations.is_empty() + && material_activity_outcomes == 0 { anyhow::bail!( - "strategic model proposed no material offscreen change: {}", - "all cells explicitly chose inaction" + "strategic model resolved no material offscreen change: direct transitions were empty and every selected activity outcome was no_material_change" ); } for stage in &output.stages { diff --git a/crates/ghostlight-dungeon/src/domain.rs b/crates/ghostlight-dungeon/src/domain.rs index 3b1fc2a..c142e4d 100644 --- a/crates/ghostlight-dungeon/src/domain.rs +++ b/crates/ghostlight-dungeon/src/domain.rs @@ -516,9 +516,81 @@ pub struct ResolutionWaveCommit { pub cover: ResolutionCover, pub plan_receipt: ResolutionPlanReceipt, pub appraisals: Vec, + #[serde(default)] + pub activity_outcomes: Vec, pub model_receipt_hashes: Vec, } +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum StrategicOutcomeBand { + Success, + Mixed, + Failure, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct StrategicActivityOutcome { + pub schema: String, + pub action_digest: String, + pub source_subject_id: String, + pub band: StrategicOutcomeBand, + #[schemars(length(min = 1, max = 240))] + pub summary: String, + #[serde(default)] + pub supporting_state_references: Vec, + pub effect: StrategicOutcomeEffect, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum StrategicOutcomeEffect { + NoMaterialChange { + reason: String, + }, + ResourceCreated { + owner_subject_id: String, + resource: String, + }, + ResourceConsumed { + owner_subject_id: String, + resource: String, + }, + ResourceTransferred { + from_subject_id: String, + to_subject_id: String, + resource: String, + }, + GestaltPressure { + gestalt_id: String, + #[serde(default)] + pressure_additions: Vec, + #[serde(default)] + pressure_resolutions: Vec, + }, + AgencyRelationShift { + relation_id: String, + strength_delta: i16, + }, + MemberMemory { + member_id: String, + memory: String, + }, + MemberObligation { + member_id: String, + obligation: String, + }, + MemberRelationship { + member_id: String, + other_subject_id: String, + description: String, + }, + KnowledgeLearned { + owner_subject_id: String, + fact_id: String, + }, +} + #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] pub struct GestaltFissionPreview { pub schema: String, @@ -633,6 +705,8 @@ pub struct StrategicTickPlan { pub member_migrations: Vec, #[serde(default)] pub member_activities: Vec, + #[serde(default)] + pub activity_outcomes: Vec, } #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] @@ -653,6 +727,7 @@ pub struct StrategicGestaltAction { #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] pub struct StrategicGestaltActivity { + pub action_digest: String, pub gestalt_id: String, pub activity: StrategicActivityKind, pub target_subject_ids: Vec, @@ -686,6 +761,7 @@ pub struct StrategicMemberMigration { #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] pub struct StrategicMemberActivity { + pub action_digest: String, pub member_id: String, pub source_gestalt_id: String, pub activity: StrategicActivityKind, diff --git a/crates/ghostlight-dungeon/src/kernel.rs b/crates/ghostlight-dungeon/src/kernel.rs index b039ece..b8c44d3 100644 --- a/crates/ghostlight-dungeon/src/kernel.rs +++ b/crates/ghostlight-dungeon/src/kernel.rs @@ -414,6 +414,11 @@ fn execute( .iter() .filter(|appraisal| !appraisal.actions.is_empty()) .count(); + let outcome_digests = resolved_plan + .as_ref() + .map(crate::outcome::plan_activity_digests) + .unwrap_or_default(); + let outcome_stage_count = usize::from(!outcome_digests.is_empty()); if unique_hashes.len() != wave.model_receipt_hashes.len() || wave.model_receipt_hashes.len() < wave @@ -422,6 +427,7 @@ fn execute( .len() .saturating_mul(3) .saturating_add(actionful_cell_count) + .saturating_add(outcome_stage_count) { return Err(KernelError::Invalid( "resolution wave does not carry one distinct stage receipt per cell stage" @@ -490,6 +496,20 @@ fn execute( } } } + if !outcome_digests.is_empty() { + let binding = crate::outcome::activity_outcome_binding( + campaign.id, + campaign.revision, + campaign.resolution_policy.resolution_epoch, + &outcome_digests, + ); + if !stage_bindings.contains(&("strategic_outcome_resolver".into(), binding)) { + return Err(KernelError::Invalid( + "resolution wave lacks an activity-bound strategic outcome receipt" + .into(), + )); + } + } } campaign.world_time += Duration::hours(i64::from(campaign.tick_hours)); for clock in campaign.clocks.values_mut() { @@ -1270,6 +1290,30 @@ fn apply_strategic_tick_plan( campaign: &mut Campaign, plan: crate::domain::StrategicTickPlan, ) -> Result, KernelError> { + crate::outcome::validate_plan_activity_outcomes(campaign, &plan) + .map_err(|error| KernelError::Invalid(error.to_string()))?; + let activity_outcomes = plan.activity_outcomes.clone(); + let mut outcome_event_context = BTreeMap::new(); + for activity in &plan.gestalt_activities { + outcome_event_context.insert( + activity.action_digest.clone(), + ( + activity.gestalt_id.clone(), + activity.location_ids.clone(), + activity.public_channels.clone(), + ), + ); + } + for activity in &plan.member_activities { + outcome_event_context.insert( + activity.action_digest.clone(), + ( + format!("member:{}", activity.member_id), + activity.location_ids.clone(), + activity.public_channels.clone(), + ), + ); + } // Every action in a strategic wave was chosen against the same committed // snapshot. Keep that snapshot immutable while applying to a private copy // so action ordering cannot rewrite another action's permissions and an @@ -1706,10 +1750,291 @@ fn apply_strategic_tick_plan( public_channels: action.public_channels, }); } + for outcome in activity_outcomes { + let (source_subject_id, locations, public_channels) = outcome_event_context + .remove(&outcome.action_digest) + .ok_or_else(|| { + KernelError::Invalid("strategic outcome lost its activity context".into()) + })?; + apply_strategic_outcome_effect(&mut next, &outcome.effect)?; + let mut subject_ids = BTreeSet::from([source_subject_id]); + collect_outcome_subject_ids(&outcome.effect, &mut subject_ids); + let mut actor_ids = Vec::new(); + let mut institution_ids = Vec::new(); + let mut gestalt_ids = Vec::new(); + for subject_id in subject_ids { + if let Some(member_id) = subject_id.strip_prefix("member:") { + actor_ids.push(subject_id.clone()); + if let Some(member) = next.gestalt_members.get(member_id) { + gestalt_ids.push(member.gestalt_id.clone()); + } + } else if next.actors.contains_key(&subject_id) { + actor_ids.push(subject_id); + } else if next.institutions.contains_key(&subject_id) { + institution_ids.push(subject_id); + } else if next.gestalts.contains_key(&subject_id) { + gestalt_ids.push(subject_id); + } + } + actor_ids.sort(); + actor_ids.dedup(); + institution_ids.sort(); + institution_ids.dedup(); + gestalt_ids.sort(); + gestalt_ids.dedup(); + let digest_suffix = outcome + .action_digest + .strip_prefix("sha256:") + .unwrap_or(&outcome.action_digest) + .chars() + .take(16) + .collect::(); + events.push(Event { + id: format!("strategic:{revision}:activity-outcome:{digest_suffix}"), + at, + kind: "strategic_activity_outcome".into(), + summary: outcome.summary, + actor_ids, + institution_ids, + gestalt_ids, + location_ids: locations, + public_channels, + }); + } *campaign = next; Ok(events) } +fn apply_strategic_outcome_effect( + campaign: &mut Campaign, + effect: &crate::domain::StrategicOutcomeEffect, +) -> Result<(), KernelError> { + use crate::domain::StrategicOutcomeEffect; + match effect { + StrategicOutcomeEffect::NoMaterialChange { .. } => {} + StrategicOutcomeEffect::ResourceCreated { + owner_subject_id, + resource, + } => insert_subject_resource(campaign, owner_subject_id, resource)?, + StrategicOutcomeEffect::ResourceConsumed { + owner_subject_id, + resource, + } => remove_subject_resource(campaign, owner_subject_id, resource)?, + StrategicOutcomeEffect::ResourceTransferred { + from_subject_id, + to_subject_id, + resource, + } => { + remove_subject_resource(campaign, from_subject_id, resource)?; + insert_subject_resource(campaign, to_subject_id, resource)?; + } + StrategicOutcomeEffect::GestaltPressure { + gestalt_id, + pressure_additions, + pressure_resolutions, + } => { + let gestalt = campaign + .gestalts + .get_mut(gestalt_id) + .ok_or_else(|| KernelError::Invalid("outcome gestalt vanished".into()))?; + crate::resolution::validate_gestalt_pressure_transition( + &gestalt.pressures, + pressure_additions, + pressure_resolutions, + ) + .map_err(|error| KernelError::Invalid(error.to_string()))?; + let resolved = pressure_resolutions.iter().collect::>(); + gestalt + .pressures + .retain(|pressure| !resolved.contains(pressure)); + gestalt.pressures.extend(pressure_additions.iter().cloned()); + gestalt.version = gestalt.version.saturating_add(1); + } + StrategicOutcomeEffect::AgencyRelationShift { + relation_id, + strength_delta, + } => { + let relation = campaign + .agency_relations + .get_mut(relation_id) + .ok_or_else(|| KernelError::Invalid("outcome relation vanished".into()))?; + relation.strength = u8::try_from(i16::from(relation.strength) + strength_delta) + .map_err(|_| KernelError::Invalid("outcome relation shift overflowed".into()))?; + } + StrategicOutcomeEffect::MemberMemory { member_id, memory } => { + let member = campaign + .gestalt_members + .get_mut(member_id) + .ok_or_else(|| KernelError::Invalid("outcome member vanished".into()))?; + if !member.memories.contains(memory) { + member.memories.push(memory.clone()); + } + member.version = member.version.saturating_add(1); + } + StrategicOutcomeEffect::MemberObligation { + member_id, + obligation, + } => { + let member = campaign + .gestalt_members + .get_mut(member_id) + .ok_or_else(|| KernelError::Invalid("outcome member vanished".into()))?; + member.obligations.insert(obligation.clone()); + member.version = member.version.saturating_add(1); + } + StrategicOutcomeEffect::MemberRelationship { + member_id, + other_subject_id, + description, + } => { + let member = campaign + .gestalt_members + .get_mut(member_id) + .ok_or_else(|| KernelError::Invalid("outcome member vanished".into()))?; + member + .relationships + .insert(other_subject_id.clone(), description.clone()); + member.version = member.version.saturating_add(1); + } + StrategicOutcomeEffect::KnowledgeLearned { + owner_subject_id, + fact_id, + } => { + let statement = campaign + .facts + .get(fact_id) + .map(|fact| fact.statement.clone()) + .ok_or_else(|| KernelError::Invalid("outcome fact vanished".into()))?; + if let Some(member_id) = owner_subject_id.strip_prefix("member:") { + let member = campaign + .gestalt_members + .get_mut(member_id) + .ok_or_else(|| KernelError::Invalid("outcome member vanished".into()))?; + member.knowledge_removals.remove(&statement); + member.knowledge_additions.insert(statement); + member.version = member.version.saturating_add(1); + } else { + let gestalt = campaign.gestalts.get_mut(owner_subject_id).ok_or_else(|| { + KernelError::Invalid("outcome knowledge owner vanished".into()) + })?; + gestalt.shared_knowledge.insert(statement); + gestalt.version = gestalt.version.saturating_add(1); + } + } + } + Ok(()) +} + +fn insert_subject_resource( + campaign: &mut Campaign, + subject_id: &str, + resource: &str, +) -> Result<(), KernelError> { + if let Some(member_id) = subject_id.strip_prefix("member:") { + let member = campaign + .gestalt_members + .get_mut(member_id) + .ok_or_else(|| KernelError::Invalid("resource member vanished".into()))?; + member.equipment.insert(resource.into()); + member.version = member.version.saturating_add(1); + return Ok(()); + } + if let Some(gestalt) = campaign.gestalts.get_mut(subject_id) { + gestalt.resources.insert(resource.into()); + gestalt.version = gestalt.version.saturating_add(1); + return Ok(()); + } + if let Some(institution) = campaign.institutions.get_mut(subject_id) { + institution.resources.push(resource.into()); + institution.resources.sort(); + institution.resources.dedup(); + return Ok(()); + } + if let Some(actor) = campaign.actors.get_mut(subject_id) { + actor.equipment.insert(resource.into()); + return Ok(()); + } + Err(KernelError::Invalid("resource recipient vanished".into())) +} + +fn remove_subject_resource( + campaign: &mut Campaign, + subject_id: &str, + resource: &str, +) -> Result<(), KernelError> { + let removed = if let Some(member_id) = subject_id.strip_prefix("member:") { + let member = campaign + .gestalt_members + .get_mut(member_id) + .ok_or_else(|| KernelError::Invalid("resource member vanished".into()))?; + let removed = member.equipment.remove(resource); + member.version = member.version.saturating_add(1); + removed + } else if let Some(gestalt) = campaign.gestalts.get_mut(subject_id) { + let removed = gestalt.resources.remove(resource); + gestalt.version = gestalt.version.saturating_add(1); + removed + } else if let Some(institution) = campaign.institutions.get_mut(subject_id) { + let previous = institution.resources.len(); + institution.resources.retain(|value| value != resource); + institution.resources.len() != previous + } else if let Some(actor) = campaign.actors.get_mut(subject_id) { + actor.equipment.remove(resource) + } else { + return Err(KernelError::Invalid("resource owner vanished".into())); + }; + if !removed { + return Err(KernelError::Invalid( + "outcome attempted to spend a missing resource".into(), + )); + } + Ok(()) +} + +fn collect_outcome_subject_ids( + effect: &crate::domain::StrategicOutcomeEffect, + subjects: &mut BTreeSet, +) { + use crate::domain::StrategicOutcomeEffect; + match effect { + StrategicOutcomeEffect::NoMaterialChange { .. } => {} + StrategicOutcomeEffect::ResourceCreated { + owner_subject_id, .. + } + | StrategicOutcomeEffect::ResourceConsumed { + owner_subject_id, .. + } + | StrategicOutcomeEffect::KnowledgeLearned { + owner_subject_id, .. + } => { + subjects.insert(owner_subject_id.clone()); + } + StrategicOutcomeEffect::ResourceTransferred { + from_subject_id, + to_subject_id, + .. + } => { + subjects.insert(from_subject_id.clone()); + subjects.insert(to_subject_id.clone()); + } + StrategicOutcomeEffect::GestaltPressure { gestalt_id, .. } => { + subjects.insert(gestalt_id.clone()); + } + StrategicOutcomeEffect::AgencyRelationShift { .. } => {} + StrategicOutcomeEffect::MemberMemory { member_id, .. } + | StrategicOutcomeEffect::MemberObligation { member_id, .. } + | StrategicOutcomeEffect::MemberRelationship { member_id, .. } => { + subjects.insert(format!("member:{member_id}")); + if let StrategicOutcomeEffect::MemberRelationship { + other_subject_id, .. + } = effect + { + subjects.insert(other_subject_id.clone()); + } + } + } +} + fn strategic_activity_summary( source_name: &str, activity: &StrategicActivityKind, @@ -2132,8 +2457,41 @@ fn persist(e: anyhow::Error) -> KernelError { #[cfg(test)] mod tests { use super::*; + use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet}; + fn test_action_digest(label: &str) -> String { + format!("sha256:{:x}", Sha256::digest(label.as_bytes())) + } + + fn resolve_test_activities(mut plan: StrategicTickPlan) -> StrategicTickPlan { + plan.activity_outcomes.extend( + plan.gestalt_activities + .iter() + .map(|activity| (activity.action_digest.clone(), activity.gestalt_id.clone())) + .chain(plan.member_activities.iter().map(|activity| { + ( + activity.action_digest.clone(), + format!("member:{}", activity.member_id), + ) + })) + .map( + |(action_digest, source_subject_id)| StrategicActivityOutcome { + schema: "ghostlight.strategic_activity_outcome.v1".into(), + action_digest, + source_subject_id, + band: StrategicOutcomeBand::Mixed, + summary: "The attempt produces no durable material change.".into(), + supporting_state_references: vec![], + effect: StrategicOutcomeEffect::NoMaterialChange { + reason: "No response is established in this test snapshot.".into(), + }, + }, + ), + ); + plan + } + fn campaign() -> Campaign { let id = uuid::Uuid::new_v4(); let actor = ActorState { @@ -2741,7 +3099,7 @@ mod tests { let events = apply_strategic_tick_plan( &mut value, - StrategicTickPlan { + resolve_test_activities(StrategicTickPlan { gestalt_migrations: vec![StrategicGestaltMigration { gestalt_id: "refugees-east".into(), destination_gestalt_id: "dock-neighbors".into(), @@ -2749,6 +3107,7 @@ mod tests { public_channels: vec![], }], gestalt_activities: vec![StrategicGestaltActivity { + action_digest: test_action_digest("simultaneous communication"), gestalt_id: "camp-neighbors".into(), activity: StrategicActivityKind::Communicate, target_subject_ids: vec!["refugees-east".into()], @@ -2756,12 +3115,12 @@ mod tests { public_channels: vec![], }], ..Default::default() - }, + }), ) .unwrap(); assert_eq!(value.gestalts["refugees-east"].home_location_id, "docks"); - assert_eq!(events.len(), 2); + assert_eq!(events.len(), 3); assert_eq!(events[1].kind, "gestalt_activity"); assert_eq!(events[1].location_ids, vec!["camp"]); assert_eq!( @@ -2776,7 +3135,7 @@ mod tests { let before = value.clone(); let error = apply_strategic_tick_plan( &mut value, - StrategicTickPlan { + resolve_test_activities(StrategicTickPlan { gestalt_migrations: vec![StrategicGestaltMigration { gestalt_id: "refugees-east".into(), destination_gestalt_id: "dock-neighbors".into(), @@ -2784,6 +3143,7 @@ mod tests { public_channels: vec![], }], gestalt_activities: vec![StrategicGestaltActivity { + action_digest: test_action_digest("conflicting refugee preparation"), gestalt_id: "refugees-east".into(), activity: StrategicActivityKind::Prepare, target_subject_ids: vec![], @@ -2791,7 +3151,7 @@ mod tests { public_channels: vec![], }], ..Default::default() - }, + }), ) .unwrap_err(); @@ -2896,13 +3256,14 @@ mod tests { } #[test] - fn gestalt_activity_records_an_attributed_attempt_without_claiming_an_outcome() { + fn gestalt_activity_requires_an_explicit_resolved_no_material_outcome() { let mut value = hierarchical_refugee_campaign(); let before = value.clone(); let events = apply_strategic_tick_plan( &mut value, - StrategicTickPlan { + resolve_test_activities(StrategicTickPlan { gestalt_activities: vec![StrategicGestaltActivity { + action_digest: test_action_digest("refugee coordination"), gestalt_id: "refugees-east".into(), activity: StrategicActivityKind::Coordinate, target_subject_ids: vec!["dock-neighbors".into()], @@ -2910,11 +3271,11 @@ mod tests { public_channels: vec![], }], ..Default::default() - }, + }), ) .unwrap(); assert_eq!(value, before); - assert_eq!(events.len(), 1); + assert_eq!(events.len(), 2); assert_eq!(events[0].kind, "gestalt_activity"); assert_eq!( events[0].summary, @@ -2926,6 +3287,173 @@ mod tests { ); assert!(events[0].actor_ids.is_empty()); assert!(events[0].institution_ids.is_empty()); + assert_eq!(events[1].kind, "strategic_activity_outcome"); + assert_eq!( + events[1].summary, + "The attempt produces no durable material change." + ); + } + + #[test] + fn strategic_outcome_materializes_a_bounded_resource_from_exact_capability() { + let mut value = hierarchical_refugee_campaign(); + let digest = test_action_digest("refugees prepare storm lashings"); + let events = apply_strategic_tick_plan( + &mut value, + StrategicTickPlan { + gestalt_activities: vec![StrategicGestaltActivity { + action_digest: digest.clone(), + gestalt_id: "refugees-east".into(), + activity: StrategicActivityKind::Prepare, + target_subject_ids: vec![], + location_ids: vec!["camp".into()], + public_channels: vec![], + }], + activity_outcomes: vec![StrategicActivityOutcome { + schema: "ghostlight.strategic_activity_outcome.v1".into(), + action_digest: digest, + source_subject_id: "refugees-east".into(), + band: StrategicOutcomeBand::Success, + summary: "The refugees finish a set of storm lashings.".into(), + supporting_state_references: vec![ + "capability:survive transit".into(), + "location:camp".into(), + ], + effect: StrategicOutcomeEffect::ResourceCreated { + owner_subject_id: "refugees-east".into(), + resource: "storm lashings".into(), + }, + }], + ..Default::default() + }, + ) + .unwrap(); + + assert!( + value.gestalts["refugees-east"] + .resources + .contains("storm lashings") + ); + assert_eq!(value.gestalts["refugees-east"].version, 1); + assert_eq!(events.len(), 2); + assert_eq!(events[1].kind, "strategic_activity_outcome"); + } + + #[test] + fn invalid_outcome_bundle_cannot_apply_an_earlier_material_effect() { + let mut value = hierarchical_refugee_campaign(); + let before = value.clone(); + let first = test_action_digest("valid material preparation"); + let second = test_action_digest("invalid resource spend"); + let error = apply_strategic_tick_plan( + &mut value, + StrategicTickPlan { + gestalt_activities: vec![ + StrategicGestaltActivity { + action_digest: first.clone(), + gestalt_id: "refugees-east".into(), + activity: StrategicActivityKind::Prepare, + target_subject_ids: vec![], + location_ids: vec!["camp".into()], + public_channels: vec![], + }, + StrategicGestaltActivity { + action_digest: second.clone(), + gestalt_id: "dock-neighbors".into(), + activity: StrategicActivityKind::Prepare, + target_subject_ids: vec![], + location_ids: vec!["docks".into()], + public_channels: vec![], + }, + ], + activity_outcomes: vec![ + StrategicActivityOutcome { + schema: "ghostlight.strategic_activity_outcome.v1".into(), + action_digest: first, + source_subject_id: "refugees-east".into(), + band: StrategicOutcomeBand::Success, + summary: "A valid first result.".into(), + supporting_state_references: vec!["capability:survive transit".into()], + effect: StrategicOutcomeEffect::ResourceCreated { + owner_subject_id: "refugees-east".into(), + resource: "valid new shelter frame".into(), + }, + }, + StrategicActivityOutcome { + schema: "ghostlight.strategic_activity_outcome.v1".into(), + action_digest: second, + source_subject_id: "dock-neighbors".into(), + band: StrategicOutcomeBand::Failure, + summary: "An invalid second result.".into(), + supporting_state_references: vec!["capability:repair nets".into()], + effect: StrategicOutcomeEffect::ResourceConsumed { + owner_subject_id: "dock-neighbors".into(), + resource: "invented missing winch".into(), + }, + }, + ], + ..Default::default() + }, + ) + .unwrap_err(); + + assert!(error.to_string().contains("custody")); + assert_eq!(value, before); + } + + #[test] + fn member_outcome_preserves_its_own_relationship_without_mutating_the_player() { + let mut value = hierarchical_refugee_campaign(); + value.agency_relations.insert( + "refugee-message-to-player".into(), + AgencyRelation { + schema: "ghostlight.agency_relation.v1".into(), + id: "refugee-message-to-player".into(), + from_subject_id: "refugees-east".into(), + to_subject_id: "player".into(), + kind: AgencyRelationKind::Communication, + strength: 40, + active: true, + evidence_receipt_ids: vec![], + }, + ); + let player_before = value.actors["player"].clone(); + let digest = test_action_digest("mira renews her promise"); + apply_strategic_tick_plan( + &mut value, + StrategicTickPlan { + member_activities: vec![StrategicMemberActivity { + action_digest: digest.clone(), + member_id: "mira".into(), + source_gestalt_id: "refugees-east".into(), + activity: StrategicActivityKind::Communicate, + target_subject_ids: vec!["player".into()], + location_ids: vec!["camp".into()], + public_channels: vec![], + }], + activity_outcomes: vec![StrategicActivityOutcome { + schema: "ghostlight.strategic_activity_outcome.v1".into(), + action_digest: digest, + source_subject_id: "member:mira".into(), + band: StrategicOutcomeBand::Success, + summary: "Mira keeps the promise alive despite the distance.".into(), + supporting_state_references: vec!["member:mira".into()], + effect: StrategicOutcomeEffect::MemberRelationship { + member_id: "mira".into(), + other_subject_id: "player".into(), + description: "intends to find and repay the rescuer after settling".into(), + }, + }], + ..Default::default() + }, + ) + .unwrap(); + + assert_eq!(value.actors["player"], player_before); + assert_eq!( + value.gestalt_members["mira"].relationships["player"], + "intends to find and repay the rescuer after settling" + ); } #[test] @@ -2934,8 +3462,9 @@ mod tests { let before = value.clone(); let events = apply_strategic_tick_plan( &mut value, - StrategicTickPlan { + resolve_test_activities(StrategicTickPlan { gestalt_activities: vec![StrategicGestaltActivity { + action_digest: test_action_digest("local refugee investigation"), gestalt_id: "refugees-east".into(), activity: StrategicActivityKind::Investigate, target_subject_ids: vec![], @@ -2943,7 +3472,7 @@ mod tests { public_channels: vec![], }], ..Default::default() - }, + }), ) .unwrap(); assert_eq!(value, before); @@ -2961,8 +3490,9 @@ mod tests { let before = value.clone(); let events = apply_strategic_tick_plan( &mut value, - StrategicTickPlan { + resolve_test_activities(StrategicTickPlan { gestalt_activities: vec![StrategicGestaltActivity { + action_digest: test_action_digest("local refugee communication"), gestalt_id: "refugees-east".into(), activity: StrategicActivityKind::Communicate, target_subject_ids: vec![], @@ -2970,7 +3500,7 @@ mod tests { public_channels: vec![], }], ..Default::default() - }, + }), ) .unwrap(); assert_eq!(value, before); @@ -2989,8 +3519,9 @@ mod tests { let before = value.clone(); let events = apply_strategic_tick_plan( &mut value, - StrategicTickPlan { + resolve_test_activities(StrategicTickPlan { member_activities: vec![StrategicMemberActivity { + action_digest: test_action_digest("mira local communication"), member_id: "mira".into(), source_gestalt_id: "refugees-east".into(), activity: StrategicActivityKind::Communicate, @@ -2999,7 +3530,7 @@ mod tests { public_channels: vec![], }], ..Default::default() - }, + }), ) .unwrap(); assert_eq!(value, before); @@ -3024,8 +3555,9 @@ mod tests { let before = value.clone(); let events = apply_strategic_tick_plan( &mut value, - StrategicTickPlan { + resolve_test_activities(StrategicTickPlan { gestalt_activities: vec![StrategicGestaltActivity { + action_digest: test_action_digest("neighbors address mira"), gestalt_id: "dock-neighbors".into(), activity: StrategicActivityKind::Communicate, target_subject_ids: vec!["member:mira".into()], @@ -3033,11 +3565,11 @@ mod tests { public_channels: vec![], }], ..Default::default() - }, + }), ) .unwrap(); assert_eq!(value, before); - assert_eq!(events.len(), 1); + assert_eq!(events.len(), 2); assert_eq!( events[0].summary, "South dock neighbors sends a communication to Mira Venn." @@ -3052,8 +3584,9 @@ mod tests { let before = value.clone(); let error = apply_strategic_tick_plan( &mut value, - StrategicTickPlan { + resolve_test_activities(StrategicTickPlan { gestalt_activities: vec![StrategicGestaltActivity { + action_digest: test_action_digest("remote address mira"), gestalt_id: "dock-neighbors".into(), activity: StrategicActivityKind::Communicate, target_subject_ids: vec!["member:mira".into()], @@ -3061,7 +3594,7 @@ mod tests { public_channels: vec![], }], ..Default::default() - }, + }), ) .unwrap_err(); assert!(error.to_string().contains("exact graph or location scope")); @@ -3090,8 +3623,9 @@ mod tests { let before = value.clone(); let error = apply_strategic_tick_plan( &mut value, - StrategicTickPlan { + resolve_test_activities(StrategicTickPlan { gestalt_activities: vec![StrategicGestaltActivity { + action_digest: test_action_digest("nonadjacent communication"), gestalt_id: "refugees-east".into(), activity: StrategicActivityKind::Communicate, target_subject_ids: vec!["distant-crowd".into()], @@ -3099,7 +3633,7 @@ mod tests { public_channels: vec![], }], ..Default::default() - }, + }), ) .unwrap_err(); assert!(error.to_string().contains("exact graph or location scope")); @@ -3112,8 +3646,9 @@ mod tests { let before = value.clone(); let events = apply_strategic_tick_plan( &mut value, - StrategicTickPlan { + resolve_test_activities(StrategicTickPlan { member_activities: vec![StrategicMemberActivity { + action_digest: test_action_digest("mira addresses refugees"), member_id: "mira".into(), source_gestalt_id: "refugees-east".into(), activity: StrategicActivityKind::Communicate, @@ -3122,11 +3657,11 @@ mod tests { public_channels: vec![], }], ..Default::default() - }, + }), ) .unwrap(); assert_eq!(value, before); - assert_eq!(events.len(), 1); + assert_eq!(events.len(), 2); assert_eq!(events[0].kind, "gestalt_member_activity"); assert_eq!( events[0].summary, @@ -4263,6 +4798,7 @@ mod tests { }) .collect(), cover, + activity_outcomes: vec![], model_receipt_hashes: hashes, } } @@ -4510,6 +5046,177 @@ mod tests { assert_eq!(stored.world_time, seed.world_time); } + #[tokio::test] + async fn activity_outcome_receipt_must_bind_the_exact_selected_digest_set() { + let dir = tempfile::tempdir().unwrap(); + let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); + let kernel = WorldKernel::start(store.clone()); + let seed = hierarchical_refugee_campaign(); + 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 appraisal = wave + .appraisals + .iter_mut() + .find(|appraisal| appraisal.considered_subject_ids.contains("refugees-east")) + .unwrap(); + let proposal = CellActionProposal { + subject_id: "refugees-east".into(), + intent: "prepare storm lashings".into(), + intended_effect: "finish one bounded set of camp lashings".into(), + priority: 60, + state_references: vec![ + "subject:refugees-east".into(), + "capability:survive transit".into(), + "location:camp".into(), + ], + public_channels: vec![], + effect: StrategicCellEffect::GestaltActivity { + gestalt_id: "refugees-east".into(), + activity: StrategicActivityKind::Prepare, + target_subject_ids: vec![], + location_ids: vec!["camp".into()], + }, + }; + let action_digest = crate::resolution::cell_action_digest(&proposal).unwrap(); + appraisal.actions = vec![proposal]; + appraisal.inactions.clear(); + let appraisal_cell_id = appraisal.cell_id.clone(); + let appraisal_actions = appraisal.actions.clone(); + wave.activity_outcomes = vec![StrategicActivityOutcome { + schema: "ghostlight.strategic_activity_outcome.v1".into(), + action_digest: action_digest.clone(), + source_subject_id: "refugees-east".into(), + band: StrategicOutcomeBand::Success, + summary: "The camp finishes one set of storm lashings.".into(), + supporting_state_references: vec!["capability:survive transit".into()], + effect: StrategicOutcomeEffect::ResourceCreated { + owner_subject_id: "refugees-east".into(), + resource: "storm lashings".into(), + }, + }]; + + let base_binding = format!( + "campaign:{}:revision:{}:resolution:{}:cell:{}", + persisted.id, + persisted.revision, + persisted.resolution_policy.resolution_epoch, + appraisal_cell_id + ); + let mut verifier = + resolution_stage(&appraisal_cell_id, &persisted, "cell_effect_verifier", '7'); + verifier.snapshot_binding = + crate::persona::cell_effect_verification_binding(&base_binding, &appraisal_actions) + .unwrap(); + let wrong_outcome = resolution_stage( + &appraisal_cell_id, + &persisted, + "strategic_outcome_resolver", + '8', + ); + for receipt in [verifier, wrong_outcome] { + store + .insert( + "persona_stage_receipt.v1", + "ghostlight.persona_stage_receipt.v1", + receipt.storage_key(), + &receipt, + ) + .unwrap(); + wave.model_receipt_hashes + .push(receipt.storage_key().to_owned()); + } + let mut correct_wave = wave.clone(); + let mut correct_outcome = resolution_stage( + &appraisal_cell_id, + &persisted, + "strategic_outcome_resolver", + '9', + ); + correct_outcome.snapshot_binding = crate::outcome::activity_outcome_binding( + persisted.id, + persisted.revision, + persisted.resolution_policy.resolution_epoch, + &[action_digest], + ); + store + .insert( + "persona_stage_receipt.v1", + "ghostlight.persona_stage_receipt.v1", + correct_outcome.storage_key(), + &correct_outcome, + ) + .unwrap(); + correct_wave.model_receipt_hashes.pop(); + correct_wave + .model_receipt_hashes + .push(correct_outcome.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 an activity-bound strategic outcome receipt"), + "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); + assert!( + !stored.gestalts["refugees-east"] + .resources + .contains("storm lashings") + ); + + let result = kernel + .command(WorldCommand::AdvanceStrategicTick { + expected_revision: 0, + source: TickSource::Scheduler, + plan: None, + model_receipt_hash: Some(format!("sha256:{}", "a".repeat(64))), + resolution_wave: Some(correct_wave), + }) + .await + .unwrap(); + let CommandResult::Committed { campaign, .. } = result else { + panic!() + }; + assert_eq!(campaign.revision, 1); + assert!( + campaign.gestalts["refugees-east"] + .resources + .contains("storm lashings") + ); + assert_eq!( + store.keys("strategic_activity_outcome.v1").unwrap().len(), + 1 + ); + } + #[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/lib.rs b/crates/ghostlight-dungeon/src/lib.rs index 0da350d..2f75b33 100644 --- a/crates/ghostlight-dungeon/src/lib.rs +++ b/crates/ghostlight-dungeon/src/lib.rs @@ -8,6 +8,7 @@ pub mod kernel; pub mod mesh; pub mod model; pub mod narrator; +pub mod outcome; pub mod persistence; pub mod persona; pub mod registry; diff --git a/crates/ghostlight-dungeon/src/main.rs b/crates/ghostlight-dungeon/src/main.rs index 1151c58..ce9cd9e 100644 --- a/crates/ghostlight-dungeon/src/main.rs +++ b/crates/ghostlight-dungeon/src/main.rs @@ -1518,6 +1518,7 @@ async fn refresh_mesh(state: &AppState) -> anyhow::Result { rejected: runtime.store.load_all("rejected_proposal_receipt.v1")?, resolution_plans: runtime.store.load_all("resolution_plan_receipt.v1")?, cell_appraisals: runtime.store.load_all("cell_appraisal.v1")?, + activity_outcomes: runtime.store.load_all("strategic_activity_outcome.v1")?, resolution_controls: runtime.store.load_all("resolution_control_receipt.v1")?, }); } diff --git a/crates/ghostlight-dungeon/src/mesh.rs b/crates/ghostlight-dungeon/src/mesh.rs index 0641435..b345dbd 100644 --- a/crates/ghostlight-dungeon/src/mesh.rs +++ b/crates/ghostlight-dungeon/src/mesh.rs @@ -7,9 +7,9 @@ use crate::{ RegionExpansionPreview, RejectedProposalReceipt, RelationshipState, ResolutionControlReceipt, ResolutionCover, ResolutionDemand, ResolutionPin, ResolutionPlanReceipt, ResolutionPolicy, RollReceipt, SimulationCell, - StrategicGestaltMigration, StrategicMemberMigration, StrategicTickPlan, - StrategicTickReceipt, VaultEvidenceReceipt, VaultManifest, WorldActionProposal, WorldClock, - WorldCommitReceipt, WorldCompilePreview, WorldFact, + StrategicActivityOutcome, StrategicGestaltMigration, StrategicMemberMigration, + StrategicTickPlan, StrategicTickReceipt, VaultEvidenceReceipt, VaultManifest, + WorldActionProposal, WorldClock, WorldCommitReceipt, WorldCompilePreview, WorldFact, }, model::ModelStageReceipt, surface::{operator_surface, player_surface}, @@ -43,6 +43,7 @@ pub struct CampaignMeshSnapshot { pub rejected: Vec, pub resolution_plans: Vec, pub cell_appraisals: Vec, + pub activity_outcomes: Vec, pub resolution_controls: Vec, } @@ -279,6 +280,7 @@ impl MeshPublisher { &snapshot.rejected, &snapshot.resolution_plans, &snapshot.cell_appraisals, + &snapshot.activity_outcomes, &snapshot.resolution_controls, live_turn_pressure, ); @@ -405,6 +407,11 @@ fn schema_catalog() -> Value { let schemas = catalog .as_object_mut() .expect("schema catalog literal is an object"); + schemas.insert( + "ghostlight.strategic_activity_outcome.v1".into(), + serde_json::to_value(schemars::schema_for!(StrategicActivityOutcome)) + .expect("strategic activity outcome schema serializes"), + ); schemas.insert( "ghostlight.gestalt_migration.v1".into(), serde_json::to_value(schemars::schema_for!(StrategicGestaltMigration)) diff --git a/crates/ghostlight-dungeon/src/outcome.rs b/crates/ghostlight-dungeon/src/outcome.rs new file mode 100644 index 0000000..5a27524 --- /dev/null +++ b/crates/ghostlight-dungeon/src/outcome.rs @@ -0,0 +1,1332 @@ +use crate::{ + domain::{ + Campaign, CellActionProposal, StrategicActivityKind, StrategicActivityOutcome, + StrategicCellEffect, StrategicOutcomeBand, StrategicOutcomeEffect, StrategicTickPlan, + }, + model::{ModelPort, ModelStageOutput, ModelStageRequest, run_validated_stage}, + resolution::{cell_action_digest, effective_member_knowledge, subject_state_references}, +}; +use anyhow::{Result, anyhow}; +use schemars::{JsonSchema, schema_for}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, BTreeSet}; + +#[derive(Clone, Debug, Serialize)] +struct OutcomeContext { + world_revision: u64, + resolution_epoch: u64, + actions: Vec, +} + +#[derive(Clone, Debug, Serialize)] +struct ActionOutcomeContext { + action_digest: String, + source_subject_id: String, + source_name: String, + intent: String, + intended_effect: String, + activity: StrategicActivityKind, + target_subject_ids: Vec, + location_ids: Vec, + source_state: serde_json::Value, + target_state: Vec, + active_relations: Vec, + pressure_owner_ids: Vec, + resource_recipient_ids: Vec, + discoverable_facts: Vec, + member_state_owner_id: Option, + allowed_state_references: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +struct OutcomeProposalBundle { + outcomes: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +enum OutcomeEffectKind { + NoMaterialChange, + ResourceCreated, + ResourceConsumed, + ResourceTransferred, + GestaltPressure, + AgencyRelationShift, + MemberMemory, + MemberObligation, + MemberRelationship, + KnowledgeLearned, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +struct OutcomeProposal { + action_digest: String, + band: StrategicOutcomeBand, + summary: String, + effect_kind: OutcomeEffectKind, + #[serde(default)] + supporting_state_references: Vec, + #[serde(default)] + owner_subject_id: Option, + #[serde(default)] + other_subject_id: Option, + #[serde(default)] + relation_id: Option, + #[serde(default)] + strength_delta: Option, + #[serde(default)] + resource: Option, + #[serde(default)] + pressure_additions: Vec, + #[serde(default)] + pressure_resolutions: Vec, + #[serde(default)] + member_id: Option, + #[serde(default)] + memory: Option, + #[serde(default)] + obligation: Option, + #[serde(default)] + relationship_description: Option, + #[serde(default)] + fact_id: Option, + #[serde(default)] + reason: Option, +} + +pub async fn resolve_activity_outcomes( + model: &dyn ModelPort, + campaign: &Campaign, + proposals: &[CellActionProposal], +) -> Result<(Vec, Vec)> { + if proposals.is_empty() { + return Ok((Vec::new(), Vec::new())); + } + let context = build_context(campaign, proposals)?; + let digests = proposals + .iter() + .map(cell_action_digest) + .collect::>>()?; + let binding = activity_outcome_binding( + campaign.id, + campaign.revision, + campaign.resolution_policy.resolution_epoch, + &digests, + ); + let mut schema = serde_json::to_value(schema_for!(OutcomeProposalBundle))?; + constrain_digest_schema(&mut schema, &digests); + let source_receipt_ids = proposals + .iter() + .flat_map(|proposal| outcome_source_receipts(campaign, proposal)) + .collect::>() + .into_iter() + .collect(); + let static_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. 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. Summary describes the resolved consequence, not a new attempt. 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. 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; 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."; + let mut request = ModelStageRequest { + stage: "strategic_outcome_resolver".into(), + model: "deepseek-v4-flash".into(), + snapshot_binding: binding, + lived_stream: format!( + "{static_contract}\n\nOUTCOME_CONTEXT:\n{}", + serde_json::to_string(&context)? + ), + output_schema: Some(schema), + source_receipt_ids, + temperature: Some(0.0), + max_output_tokens: Some(2_400), + }; + let mut stages = Vec::new(); + for semantic_attempt in 0..2 { + let mut stage = run_validated_stage(model, &request).await?; + let proposal_bundle: OutcomeProposalBundle = serde_json::from_value( + stage + .structured + .clone() + .ok_or_else(|| anyhow!("strategic outcome resolver produced no typed output"))?, + )?; + match bind_outcomes(campaign, proposals, proposal_bundle) { + Ok(outcomes) => { + stages.push(stage); + return Ok((outcomes, stages)); + } + Err(error) if semantic_attempt == 0 => { + let rejected = stage.narrative.clone(); + stage.receipt.validation_result = "semantic_invalid".into(); + stage.receipt.local_validation_error = + Some(error.to_string().chars().take(1_000).collect()); + stages.push(stage); + request.lived_stream.push_str(&format!( + "\n\nCORRECTION TASK—THE PREVIOUS OUTCOME BUNDLE WAS REJECTED.\nREJECTION: {error}\nPREVIOUS_REJECTED_BUNDLE:\n{rejected}\nReturn one complete corrected bundle against the exact same snapshot and action digests. Do not preserve an effect that violates the stated handle set." + )); + } + Err(error) => { + return Err(anyhow!( + "strategic outcome resolver failed semantic validation after one correction: {error}" + )); + } + } + } + unreachable!() +} + +pub fn activity_outcome_binding( + campaign_id: uuid::Uuid, + world_revision: u64, + resolution_epoch: u64, + digests: &[String], +) -> String { + let mut exact = digests.to_vec(); + exact.sort(); + let digest = format!("sha256:{:x}", Sha256::digest(exact.join("|").as_bytes())); + format!( + "campaign:{campaign_id}:revision:{world_revision}:resolution:{resolution_epoch}:strategic-outcomes:{digest}" + ) +} + +pub fn plan_activity_digests(plan: &StrategicTickPlan) -> Vec { + plan.gestalt_activities + .iter() + .map(|activity| activity.action_digest.clone()) + .chain( + plan.member_activities + .iter() + .map(|activity| activity.action_digest.clone()), + ) + .collect() +} + +pub fn validate_activity_outcomes( + campaign: &Campaign, + proposals: &[CellActionProposal], + outcomes: &[StrategicActivityOutcome], +) -> Result<()> { + let expected = proposals + .iter() + .map(|proposal| Ok((cell_action_digest(proposal)?, proposal))) + .collect::>>()?; + validate_outcomes_against_expected(campaign, &expected, outcomes) +} + +pub fn validate_plan_activity_outcomes( + campaign: &Campaign, + plan: &StrategicTickPlan, +) -> Result<()> { + let synthetic = plan + .gestalt_activities + .iter() + .map(|activity| { + ( + activity.action_digest.clone(), + CellActionProposal { + subject_id: activity.gestalt_id.clone(), + intent: "committed strategic activity".into(), + intended_effect: "resolve the committed strategic activity".into(), + priority: 0, + state_references: vec![], + public_channels: activity.public_channels.clone(), + effect: StrategicCellEffect::GestaltActivity { + gestalt_id: activity.gestalt_id.clone(), + activity: activity.activity.clone(), + target_subject_ids: activity.target_subject_ids.clone(), + location_ids: activity.location_ids.clone(), + }, + }, + ) + }) + .chain(plan.member_activities.iter().map(|activity| { + ( + activity.action_digest.clone(), + CellActionProposal { + subject_id: format!("member:{}", activity.member_id), + intent: "committed strategic activity".into(), + intended_effect: "resolve the committed strategic activity".into(), + priority: 0, + state_references: vec![], + public_channels: activity.public_channels.clone(), + effect: StrategicCellEffect::MemberActivity { + member_id: activity.member_id.clone(), + activity: activity.activity.clone(), + target_subject_ids: activity.target_subject_ids.clone(), + location_ids: activity.location_ids.clone(), + }, + }, + ) + })) + .collect::>(); + if synthetic.len() != plan.gestalt_activities.len() + plan.member_activities.len() { + return Err(anyhow!( + "strategic activities contain duplicate action digests" + )); + } + let expected = synthetic + .iter() + .map(|(digest, proposal)| (digest.clone(), proposal)) + .collect(); + validate_outcomes_against_expected(campaign, &expected, &plan.activity_outcomes) +} + +fn validate_outcomes_against_expected( + campaign: &Campaign, + expected: &BTreeMap, + outcomes: &[StrategicActivityOutcome], +) -> Result<()> { + if outcomes.len() != expected.len() { + return Err(anyhow!( + "every selected strategic activity requires exactly one outcome" + )); + } + let mut seen = BTreeSet::new(); + let mut exclusive_effects = BTreeSet::new(); + let mut relation_totals = BTreeMap::::new(); + for outcome in outcomes { + let proposal = expected + .get(&outcome.action_digest) + .ok_or_else(|| anyhow!("strategic outcome is not bound to a selected activity"))?; + if !seen.insert(outcome.action_digest.clone()) + || outcome.schema != "ghostlight.strategic_activity_outcome.v1" + || outcome.source_subject_id != proposal.subject_id + || !valid_sha256(&outcome.action_digest) + || !bounded_text(&outcome.summary, 240) + { + return Err(anyhow!( + "strategic outcome identity or summary is malformed" + )); + } + let allowed_references = allowed_state_references(campaign, proposal)?; + let unique_references = outcome + .supporting_state_references + .iter() + .collect::>(); + if unique_references.len() != outcome.supporting_state_references.len() + || outcome.supporting_state_references.len() > 8 + || outcome + .supporting_state_references + .iter() + .any(|reference| !allowed_references.contains(reference)) + || (!matches!( + outcome.effect, + StrategicOutcomeEffect::NoMaterialChange { .. } + ) && outcome.supporting_state_references.is_empty()) + { + return Err(anyhow!( + "strategic outcome cites state outside its exact slice" + )); + } + validate_effect(campaign, proposal, outcome, &mut exclusive_effects)?; + if let StrategicOutcomeEffect::AgencyRelationShift { + relation_id, + strength_delta, + } = &outcome.effect + { + *relation_totals.entry(relation_id.clone()).or_default() += *strength_delta; + } + } + if seen.len() != expected.len() { + return Err(anyhow!("strategic outcome bundle omitted an activity")); + } + for (relation_id, total) in relation_totals { + let relation = &campaign.agency_relations[&relation_id]; + if total.abs() > 10 || !(1..=100).contains(&(i16::from(relation.strength) + total)) { + return Err(anyhow!( + "strategic outcome relation shifts exceed one bounded wave" + )); + } + } + Ok(()) +} + +fn bind_outcomes( + campaign: &Campaign, + proposals: &[CellActionProposal], + bundle: OutcomeProposalBundle, +) -> Result> { + let sources = proposals + .iter() + .map(|proposal| Ok((cell_action_digest(proposal)?, proposal.subject_id.clone()))) + .collect::>>()?; + let outcomes = bundle + .outcomes + .into_iter() + .map(|proposal| { + let source_subject_id = sources + .get(&proposal.action_digest) + .cloned() + .ok_or_else(|| anyhow!("outcome used an unknown action digest"))?; + let effect = bind_effect(&proposal)?; + Ok(StrategicActivityOutcome { + schema: "ghostlight.strategic_activity_outcome.v1".into(), + action_digest: proposal.action_digest, + source_subject_id, + band: proposal.band, + summary: proposal.summary, + supporting_state_references: proposal.supporting_state_references, + effect, + }) + }) + .collect::>>()?; + validate_activity_outcomes(campaign, proposals, &outcomes)?; + Ok(outcomes) +} + +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)) { + return Err(anyhow!( + "outcome populated fields irrelevant to its effect_kind" + )); + } + Ok(()) + }; + Ok(match proposal.effect_kind { + OutcomeEffectKind::NoMaterialChange => { + require_exact(&["reason"])?; + StrategicOutcomeEffect::NoMaterialChange { + reason: required(&proposal.reason, "reason")?, + } + } + OutcomeEffectKind::ResourceCreated => { + require_exact(&["owner_subject_id", "resource"])?; + StrategicOutcomeEffect::ResourceCreated { + owner_subject_id: required(&proposal.owner_subject_id, "owner_subject_id")?, + resource: required(&proposal.resource, "resource")?, + } + } + OutcomeEffectKind::ResourceConsumed => { + require_exact(&["owner_subject_id", "resource"])?; + StrategicOutcomeEffect::ResourceConsumed { + owner_subject_id: required(&proposal.owner_subject_id, "owner_subject_id")?, + resource: required(&proposal.resource, "resource")?, + } + } + OutcomeEffectKind::ResourceTransferred => { + require_exact(&["owner_subject_id", "other_subject_id", "resource"])?; + StrategicOutcomeEffect::ResourceTransferred { + from_subject_id: required(&proposal.owner_subject_id, "owner_subject_id")?, + to_subject_id: required(&proposal.other_subject_id, "other_subject_id")?, + resource: required(&proposal.resource, "resource")?, + } + } + OutcomeEffectKind::GestaltPressure => { + require_exact(&[ + "owner_subject_id", + "pressure_additions", + "pressure_resolutions", + ])?; + StrategicOutcomeEffect::GestaltPressure { + gestalt_id: required(&proposal.owner_subject_id, "owner_subject_id")?, + pressure_additions: proposal.pressure_additions.clone(), + pressure_resolutions: proposal.pressure_resolutions.clone(), + } + } + OutcomeEffectKind::AgencyRelationShift => { + require_exact(&["relation_id", "strength_delta"])?; + StrategicOutcomeEffect::AgencyRelationShift { + relation_id: required(&proposal.relation_id, "relation_id")?, + strength_delta: proposal + .strength_delta + .ok_or_else(|| anyhow!("outcome omitted strength_delta"))?, + } + } + OutcomeEffectKind::MemberMemory => { + require_exact(&["member_id", "memory"])?; + StrategicOutcomeEffect::MemberMemory { + member_id: required(&proposal.member_id, "member_id")?, + memory: required(&proposal.memory, "memory")?, + } + } + OutcomeEffectKind::MemberObligation => { + require_exact(&["member_id", "obligation"])?; + StrategicOutcomeEffect::MemberObligation { + member_id: required(&proposal.member_id, "member_id")?, + obligation: required(&proposal.obligation, "obligation")?, + } + } + OutcomeEffectKind::MemberRelationship => { + require_exact(&["member_id", "other_subject_id", "relationship_description"])?; + StrategicOutcomeEffect::MemberRelationship { + member_id: required(&proposal.member_id, "member_id")?, + other_subject_id: required(&proposal.other_subject_id, "other_subject_id")?, + description: required( + &proposal.relationship_description, + "relationship_description", + )?, + } + } + OutcomeEffectKind::KnowledgeLearned => { + require_exact(&["owner_subject_id", "fact_id"])?; + StrategicOutcomeEffect::KnowledgeLearned { + owner_subject_id: required(&proposal.owner_subject_id, "owner_subject_id")?, + fact_id: required(&proposal.fact_id, "fact_id")?, + } + } + }) +} + +impl OutcomeProposal { + fn populated_effect_fields(&self) -> BTreeSet<&'static str> { + let mut fields = BTreeSet::new(); + macro_rules! present { + ($field:ident) => { + if self.$field.is_some() { + fields.insert(stringify!($field)); + } + }; + } + present!(owner_subject_id); + present!(other_subject_id); + present!(relation_id); + present!(strength_delta); + present!(resource); + present!(member_id); + present!(memory); + present!(obligation); + present!(relationship_description); + present!(fact_id); + present!(reason); + if !self.pressure_additions.is_empty() { + fields.insert("pressure_additions"); + } + if !self.pressure_resolutions.is_empty() { + fields.insert("pressure_resolutions"); + } + fields + } +} + +fn validate_effect( + campaign: &Campaign, + proposal: &CellActionProposal, + outcome: &StrategicActivityOutcome, + exclusive_effects: &mut BTreeSet, +) -> Result<()> { + let source = proposal.subject_id.as_str(); + let (activity, targets, locations) = activity_parts(proposal)?; + let target_set = targets.iter().cloned().collect::>(); + match &outcome.effect { + StrategicOutcomeEffect::NoMaterialChange { reason } => { + if !bounded_text(reason, 240) { + return Err(anyhow!("no-change outcome requires a bounded reason")); + } + } + StrategicOutcomeEffect::ResourceCreated { + owner_subject_id, + resource, + } => { + if owner_subject_id != source + || !matches!(activity, StrategicActivityKind::Prepare) + || !bounded_text(resource, 160) + || contains_normalized(&subject_resources(campaign, source)?, resource) + || subject_resources(campaign, source)?.len() >= 64 + || !can_hold_resources(campaign, source) + || !outcome + .supporting_state_references + .iter() + .any(|reference| reference.starts_with("capability:")) + || !exclusive_effects.insert(format!("resource:{source}:{resource}")) + { + return Err(anyhow!( + "resource creation exceeds the acting subject's scope" + )); + } + } + StrategicOutcomeEffect::ResourceConsumed { + owner_subject_id, + resource, + } => { + if owner_subject_id != source + || !subject_resources(campaign, source)?.contains(resource) + || !exclusive_effects.insert(format!("resource:{source}:{resource}")) + { + return Err(anyhow!("resource consumption lacks exact source custody")); + } + } + StrategicOutcomeEffect::ResourceTransferred { + from_subject_id, + to_subject_id, + resource, + } => { + if from_subject_id != source + || !target_set.contains(to_subject_id) + || to_subject_id == &campaign.player_actor_id + || !can_hold_resources(campaign, to_subject_id) + || !subject_resources(campaign, source)?.contains(resource) + || contains_normalized(&subject_resources(campaign, to_subject_id)?, resource) + || subject_resources(campaign, to_subject_id)?.len() >= 64 + || !matches!( + activity, + StrategicActivityKind::Trade + | StrategicActivityKind::Communicate + | StrategicActivityKind::Recruit + | StrategicActivityKind::Coordinate + ) + || !exclusive_effects.insert(format!("resource:{source}:{resource}")) + { + return Err(anyhow!( + "resource transfer exceeds exact custody or target scope" + )); + } + } + StrategicOutcomeEffect::GestaltPressure { + gestalt_id, + pressure_additions, + pressure_resolutions, + } => { + let allowed = pressure_owner_ids(campaign, proposal)?; + let gestalt = campaign + .gestalts + .get(gestalt_id) + .ok_or_else(|| anyhow!("outcome pressure owner is not a gestalt"))?; + crate::resolution::validate_gestalt_pressure_transition( + &gestalt.pressures, + pressure_additions, + pressure_resolutions, + )?; + if !allowed.contains(gestalt_id) + || gestalt.pressures.len() + pressure_additions.len() + > 64 + pressure_resolutions.len() + || !exclusive_effects.insert(format!("pressure:{gestalt_id}")) + { + return Err(anyhow!( + "outcome pressure transition exceeds exact target scope" + )); + } + } + StrategicOutcomeEffect::AgencyRelationShift { + relation_id, + strength_delta, + } => { + let relation = campaign + .agency_relations + .get(relation_id) + .filter(|relation| relation.active) + .ok_or_else(|| anyhow!("outcome relation is not active"))?; + let other = if relation.from_subject_id == source { + &relation.to_subject_id + } else if relation.to_subject_id == source { + &relation.from_subject_id + } else { + return Err(anyhow!("outcome relation is not incident to its source")); + }; + if source.starts_with("member:") + || !target_set.contains(other) + || *strength_delta == 0 + || strength_delta.abs() > 10 + || !matches!( + activity, + StrategicActivityKind::Coordinate + | StrategicActivityKind::Recruit + | StrategicActivityKind::Obstruct + | StrategicActivityKind::Trade + | StrategicActivityKind::Communicate + ) + { + return Err(anyhow!( + "outcome relation shift exceeds exact source or activity" + )); + } + } + StrategicOutcomeEffect::MemberMemory { member_id, memory } => { + validate_member_owner(source, member_id, memory, "memory", exclusive_effects)?; + let member = &campaign.gestalt_members[member_id]; + if member.memories.len() >= 64 || contains_normalized_slice(&member.memories, memory) { + return Err(anyhow!( + "member memory outcome is duplicate or over capacity" + )); + } + } + StrategicOutcomeEffect::MemberObligation { + member_id, + obligation, + } => { + validate_member_owner( + source, + member_id, + obligation, + "obligation", + exclusive_effects, + )?; + let member = &campaign.gestalt_members[member_id]; + if member.obligations.len() >= 64 + || contains_normalized(&member.obligations, obligation) + { + return Err(anyhow!( + "member obligation outcome is duplicate or over capacity" + )); + } + } + StrategicOutcomeEffect::MemberRelationship { + member_id, + other_subject_id, + description, + } => { + validate_member_owner( + source, + member_id, + description, + &format!("relationship:{other_subject_id}"), + exclusive_effects, + )?; + if !target_set.contains(other_subject_id) { + return Err(anyhow!( + "member relationship target was not part of the attempt" + )); + } + let member = &campaign.gestalt_members[member_id]; + if (member.relationships.len() >= 64 + && !member.relationships.contains_key(other_subject_id)) + || member + .relationships + .get(other_subject_id) + .is_some_and(|current| { + !crate::resolution::substantive_text_change(current, description) + }) + { + return Err(anyhow!( + "member relationship outcome is unchanged or over capacity" + )); + } + } + StrategicOutcomeEffect::KnowledgeLearned { + owner_subject_id, + fact_id, + } => { + if owner_subject_id != source + || !matches!( + activity, + StrategicActivityKind::Investigate | StrategicActivityKind::Communicate + ) + || !discoverable_fact_ids(campaign, proposal)?.contains(fact_id) + || source_knowledge(campaign, source)?.contains(&campaign.facts[fact_id].statement) + || !exclusive_effects.insert(format!("knowledge:{source}:{fact_id}")) + { + return Err(anyhow!("knowledge outcome exceeds exact fact access")); + } + } + } + if locations + .iter() + .any(|location| !campaign.locations.contains_key(location)) + { + return Err(anyhow!("outcome activity location vanished")); + } + Ok(()) +} + +fn validate_member_owner( + source: &str, + member_id: &str, + text: &str, + field: &str, + exclusive_effects: &mut BTreeSet, +) -> Result<()> { + if source.strip_prefix("member:") != Some(member_id) + || !bounded_text(text, 240) + || !exclusive_effects.insert(format!("member:{member_id}:{field}")) + { + return Err(anyhow!( + "member outcome does not belong to its exact person" + )); + } + Ok(()) +} + +fn build_context(campaign: &Campaign, proposals: &[CellActionProposal]) -> Result { + Ok(OutcomeContext { + world_revision: campaign.revision, + resolution_epoch: campaign.resolution_policy.resolution_epoch, + actions: proposals + .iter() + .map(|proposal| action_context(campaign, proposal)) + .collect::>()?, + }) +} + +fn action_context( + campaign: &Campaign, + proposal: &CellActionProposal, +) -> Result { + let (activity, targets, locations) = activity_parts(proposal)?; + let source_name = subject_name(campaign, &proposal.subject_id)?; + let source_state = subject_summary(campaign, &proposal.subject_id)?; + let target_state = targets + .iter() + .map(|target| subject_summary(campaign, target)) + .collect::>()?; + let target_set = targets.iter().collect::>(); + let active_relations = campaign + .agency_relations + .values() + .filter(|relation| { + relation.active + && ((relation.from_subject_id == proposal.subject_id + && target_set.contains(&relation.to_subject_id)) + || (relation.to_subject_id == proposal.subject_id + && target_set.contains(&relation.from_subject_id))) + }) + .map(|relation| { + serde_json::json!({ + "relation_id":relation.id, + "from_subject_id":relation.from_subject_id, + "to_subject_id":relation.to_subject_id, + "kind":relation.kind, + "strength":relation.strength, + }) + }) + .collect(); + let resource_recipient_ids = targets + .iter() + .filter(|target| { + *target != &campaign.player_actor_id && can_hold_resources(campaign, target) + }) + .cloned() + .collect(); + let discoverable_facts = discoverable_fact_ids(campaign, proposal)? + .into_iter() + .map(|fact_id| { + let fact = &campaign.facts[&fact_id]; + serde_json::json!({"fact_id":fact.id,"statement":fact.statement}) + }) + .collect(); + Ok(ActionOutcomeContext { + action_digest: cell_action_digest(proposal)?, + source_subject_id: proposal.subject_id.clone(), + source_name, + intent: proposal.intent.clone(), + intended_effect: proposal.intended_effect.clone(), + activity, + target_subject_ids: targets, + location_ids: locations, + source_state, + target_state, + active_relations, + pressure_owner_ids: pressure_owner_ids(campaign, proposal)? + .into_iter() + .collect(), + resource_recipient_ids, + discoverable_facts, + member_state_owner_id: proposal + .subject_id + .strip_prefix("member:") + .map(str::to_owned), + allowed_state_references: allowed_state_references(campaign, proposal)? + .into_iter() + .collect(), + }) +} + +fn subject_summary(campaign: &Campaign, subject_id: &str) -> Result { + if let Some(member_id) = subject_id.strip_prefix("member:") { + let member = campaign + .gestalt_members + .get(member_id) + .ok_or_else(|| anyhow!("outcome context member vanished"))?; + return Ok(serde_json::json!({ + "subject_id":subject_id, + "name":member.name, + "kind":"member", + "gestalt_id":member.gestalt_id, + "capabilities":crate::resolution::effective_member_capabilities(campaign, member_id)?, + "knowledge":effective_member_knowledge(campaign, member_id)?, + "resources":member.equipment, + "conditions":member.conditions, + "obligations":member.obligations, + "relationships":member.relationships, + "goals":member.goals, + })); + } + if let Some(gestalt) = campaign.gestalts.get(subject_id) { + return Ok(serde_json::json!({ + "subject_id":subject_id,"name":gestalt.name,"kind":"gestalt", + "capabilities":gestalt.shared_capabilities,"knowledge":gestalt.shared_knowledge, + "resources":gestalt.resources,"goals":gestalt.goals,"pressures":gestalt.pressures, + })); + } + if let Some(institution) = campaign.institutions.get(subject_id) { + return Ok(serde_json::json!({ + "subject_id":subject_id,"name":institution.name,"kind":"institution", + "resources":institution.resources,"goals":institution.goals,"posture":institution.posture, + })); + } + if let Some(actor) = campaign.actors.get(subject_id) { + return Ok(serde_json::json!({ + "subject_id":subject_id,"name":actor.name,"kind":"actor", + "capabilities":actor.capabilities,"knowledge":actor.knowledge, + "resources":actor.equipment,"conditions":actor.conditions, + "obligations":actor.obligations,"relationships":actor.relationships,"goals":actor.goals, + })); + } + Err(anyhow!("outcome context subject vanished")) +} + +fn allowed_state_references( + campaign: &Campaign, + proposal: &CellActionProposal, +) -> Result> { + let mut references = if let Some(member_id) = proposal.subject_id.strip_prefix("member:") { + crate::resolution::member_state_references(campaign, member_id)? + } else { + subject_state_references(campaign, &proposal.subject_id)? + }; + for relation in campaign + .agency_relations + .values() + .filter(|relation| relation.active) + { + if relation.from_subject_id == proposal.subject_id + || relation.to_subject_id == proposal.subject_id + { + references.insert(format!("relation:{}", relation.id)); + } + } + for owner_id in pressure_owner_ids(campaign, proposal)? { + if let Some(gestalt) = campaign.gestalts.get(&owner_id) { + references.extend( + gestalt + .pressures + .iter() + .map(|pressure| format!("pressure:{owner_id}:{pressure}")), + ); + } + } + for fact_id in discoverable_fact_ids(campaign, proposal)? { + references.insert(format!("fact:{fact_id}")); + } + Ok(references) +} + +fn pressure_owner_ids( + campaign: &Campaign, + proposal: &CellActionProposal, +) -> Result> { + let (_, targets, _) = activity_parts(proposal)?; + let mut ids = targets + .into_iter() + .filter(|target| campaign.gestalts.contains_key(target)) + .collect::>(); + if campaign.gestalts.contains_key(&proposal.subject_id) { + ids.insert(proposal.subject_id.clone()); + } + Ok(ids) +} + +fn discoverable_fact_ids( + campaign: &Campaign, + proposal: &CellActionProposal, +) -> Result> { + let (activity, targets, locations) = activity_parts(proposal)?; + let mut facts = campaign + .facts + .values() + .filter(|fact| { + !fact.discoverable_at_location_ids.is_empty() + && locations + .iter() + .any(|location| fact.discoverable_at_location_ids.contains(location)) + }) + .map(|fact| fact.id.clone()) + .collect::>(); + if matches!(activity, StrategicActivityKind::Communicate) { + for target in targets { + let known = source_knowledge(campaign, &target)?; + facts.extend( + campaign + .facts + .values() + .filter(|fact| known.contains(&fact.id) || known.contains(&fact.statement)) + .map(|fact| fact.id.clone()), + ); + } + } + let source_known = source_knowledge(campaign, &proposal.subject_id)?; + facts.retain(|fact_id| { + let fact = &campaign.facts[fact_id]; + !source_known.contains(fact_id) && !source_known.contains(&fact.statement) + }); + Ok(facts) +} + +fn source_knowledge(campaign: &Campaign, subject_id: &str) -> Result> { + if let Some(member_id) = subject_id.strip_prefix("member:") { + return effective_member_knowledge(campaign, member_id); + } + if let Some(gestalt) = campaign.gestalts.get(subject_id) { + return Ok(gestalt.shared_knowledge.clone()); + } + if let Some(actor) = campaign.actors.get(subject_id) { + return Ok(actor.knowledge.clone()); + } + Ok(BTreeSet::new()) +} + +pub fn subject_resources(campaign: &Campaign, subject_id: &str) -> Result> { + if let Some(member_id) = subject_id.strip_prefix("member:") { + return campaign + .gestalt_members + .get(member_id) + .map(|member| member.equipment.clone()) + .ok_or_else(|| anyhow!("resource owner member is unknown")); + } + if let Some(gestalt) = campaign.gestalts.get(subject_id) { + return Ok(gestalt.resources.clone()); + } + if let Some(institution) = campaign.institutions.get(subject_id) { + return Ok(institution.resources.iter().cloned().collect()); + } + if let Some(actor) = campaign.actors.get(subject_id) { + return Ok(actor.equipment.clone()); + } + Err(anyhow!("resource owner is unknown")) +} + +pub fn can_hold_resources(campaign: &Campaign, subject_id: &str) -> bool { + subject_id + .strip_prefix("member:") + .is_some_and(|member_id| campaign.gestalt_members.contains_key(member_id)) + || campaign.gestalts.contains_key(subject_id) + || campaign.institutions.contains_key(subject_id) + || campaign.actors.contains_key(subject_id) +} + +fn activity_parts( + proposal: &CellActionProposal, +) -> Result<(StrategicActivityKind, Vec, Vec)> { + match &proposal.effect { + StrategicCellEffect::GestaltActivity { + activity, + target_subject_ids, + location_ids, + .. + } + | StrategicCellEffect::MemberActivity { + activity, + target_subject_ids, + location_ids, + .. + } => Ok(( + activity.clone(), + target_subject_ids.clone(), + location_ids.clone(), + )), + _ => Err(anyhow!( + "strategic outcome was requested for a non-activity" + )), + } +} + +fn subject_name(campaign: &Campaign, subject_id: &str) -> Result { + if let Some(member_id) = subject_id.strip_prefix("member:") { + return campaign + .gestalt_members + .get(member_id) + .map(|member| member.name.clone()) + .ok_or_else(|| anyhow!("outcome source member vanished")); + } + campaign + .actors + .get(subject_id) + .map(|value| value.name.clone()) + .or_else(|| { + campaign + .institutions + .get(subject_id) + .map(|value| value.name.clone()) + }) + .or_else(|| { + campaign + .gestalts + .get(subject_id) + .map(|value| value.name.clone()) + }) + .ok_or_else(|| anyhow!("outcome source vanished")) +} + +fn outcome_source_receipts(campaign: &Campaign, proposal: &CellActionProposal) -> Vec { + let mut ids = Vec::new(); + let mut subjects = vec![proposal.subject_id.clone()]; + if let Ok((_, targets, _)) = activity_parts(proposal) { + subjects.extend(targets); + } + for subject in subjects { + let profile_id = subject + .strip_prefix("member:") + .and_then(|member_id| campaign.gestalt_members.get(member_id)) + .map(|member| member.gestalt_id.as_str()) + .unwrap_or(&subject); + if let Some(profile) = campaign.agency_profiles.get(profile_id) { + ids.extend(profile.evidence_receipt_ids.clone()); + } + } + ids +} + +fn constrain_digest_schema(schema: &mut serde_json::Value, digests: &[String]) { + if let Some(value) = schema.pointer_mut("/properties/outcomes/items/properties/action_digest") { + value["enum"] = serde_json::json!(digests); + } + if let Some(outcomes) = schema.pointer_mut("/properties/outcomes") { + outcomes["minItems"] = serde_json::json!(digests.len()); + outcomes["maxItems"] = serde_json::json!(digests.len()); + } +} + +fn required(value: &Option, field: &str) -> Result { + value + .clone() + .filter(|value| !value.trim().is_empty()) + .ok_or_else(|| anyhow!("outcome omitted {field}")) +} + +fn bounded_text(value: &str, max: usize) -> bool { + !value.trim().is_empty() && value.chars().count() <= max +} + +fn contains_normalized(values: &BTreeSet, candidate: &str) -> bool { + values + .iter() + .any(|value| value.eq_ignore_ascii_case(candidate)) +} + +fn contains_normalized_slice(values: &[String], candidate: &str) -> bool { + values + .iter() + .any(|value| value.eq_ignore_ascii_case(candidate)) +} + +fn valid_sha256(value: &str) -> bool { + value + .strip_prefix("sha256:") + .is_some_and(|hex| hex.len() == 64 && hex.bytes().all(|byte| byte.is_ascii_hexdigit())) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + domain::{ + AgencyProfile, AgencySubjectKind, BranchOrigin, GestaltPersonaState, Location, + ResolutionPolicy, WorldFact, + }, + resolution::ensure_agency_profiles, + }; + use chrono::Utc; + use std::sync::Mutex; + use uuid::Uuid; + + struct OutcomeFixtureModel { + action_digest: String, + requests: Mutex>, + } + + #[async_trait::async_trait] + impl ModelPort for OutcomeFixtureModel { + async fn run(&self, request: &ModelStageRequest) -> Result { + self.requests.lock().unwrap().push(request.clone()); + Ok(serde_json::json!({ + "outcomes":[{ + "action_digest":self.action_digest, + "band":"success", + "summary":"The inspection confirms the western causeway remains open.", + "effect_kind":"knowledge_learned", + "supporting_state_references":["fact:fact:safe-route"], + "owner_subject_id":"dockers", + "fact_id":"fact:safe-route" + }] + }) + .to_string()) + } + + fn provider(&self) -> &'static str { + "outcome-fixture" + } + } + + fn campaign() -> Campaign { + let mut value = Campaign { + schema: "ghostlight.campaign.v1".into(), + id: Uuid::new_v4(), + name: "outcome-test".into(), + revision: 4, + branch_origin: BranchOrigin { + canon_cutoff: "test".into(), + evidence_receipt_ids: vec![], + }, + world_time: Utc::now(), + tick_hours: 6, + player_actor_id: "player".into(), + locations: BTreeMap::from([( + "dock".into(), + Location { + id: "dock".into(), + name: "Dock".into(), + container_id: None, + routes: BTreeMap::new(), + persistent_features: vec![], + }, + )]), + actors: BTreeMap::new(), + institutions: BTreeMap::new(), + clocks: BTreeMap::new(), + facts: BTreeMap::from([( + "fact:safe-route".into(), + WorldFact { + id: "fact:safe-route".into(), + statement: "the western causeway remains open".into(), + scope: crate::domain::FactScope::BranchLocal, + evidence_receipt_ids: vec![], + discoverable_at_location_ids: BTreeSet::from(["dock".into()]), + }, + )]), + transcript: vec![], + last_player_activity: Utc::now(), + pending_ticks: 0, + away_ticks_processed: 0, + events: vec![], + news: vec![], + canon_candidates: BTreeMap::new(), + gestalts: BTreeMap::from([( + "dockers".into(), + GestaltPersonaState { + schema: "ghostlight.gestalt_persona_state.v1".into(), + id: "dockers".into(), + name: "Dockers".into(), + version: 0, + home_location_id: "dock".into(), + shared_capabilities: BTreeSet::from(["repair nets".into()]), + shared_knowledge: BTreeSet::new(), + resources: BTreeSet::from(["spare rope".into()]), + goals: vec!["keep the harbor working".into()], + pressures: vec!["storm damage".into()], + }, + )]), + gestalt_members: BTreeMap::new(), + pending_world_proposals: vec![], + agency_profiles: BTreeMap::new(), + agency_relations: BTreeMap::new(), + gestalt_lineages: BTreeMap::new(), + resolution_policy: ResolutionPolicy::default(), + resolution_pins: BTreeMap::new(), + resolution_cover: None, + strategic_tick_count: 0, + }; + value.actors.insert( + "player".into(), + crate::domain::ActorState { + id: "player".into(), + name: "Player".into(), + location_id: "dock".into(), + capabilities: BTreeSet::new(), + knowledge: BTreeSet::new(), + equipment: BTreeSet::new(), + conditions: BTreeSet::new(), + obligations: BTreeSet::new(), + relationships: BTreeMap::new(), + goals: vec![], + memories: vec![], + }, + ); + ensure_agency_profiles(&mut value); + value.agency_profiles.insert( + "dockers".into(), + AgencyProfile { + schema: "ghostlight.agency_profile.v1".into(), + id: "profile:dockers".into(), + subject_id: "dockers".into(), + subject_kind: AgencySubjectKind::Gestalt, + profile_version: 0, + collective_authority_id: Some("dockers".into()), + parent_subject_id: None, + active_leaf: true, + simulation_eligible: true, + facets: BTreeMap::new(), + location_ids: BTreeSet::from(["dock".into()]), + information_channels: BTreeSet::new(), + detail_debt: 0, + last_detail_tick: 0, + evidence_receipt_ids: vec![], + }, + ); + value + } + + fn proposal() -> CellActionProposal { + CellActionProposal { + subject_id: "dockers".into(), + intent: "inspect the damaged quay".into(), + intended_effect: "learn whether the western route remains usable".into(), + priority: 50, + state_references: vec!["capability:repair nets".into(), "location:dock".into()], + public_channels: vec![], + effect: StrategicCellEffect::GestaltActivity { + gestalt_id: "dockers".into(), + activity: StrategicActivityKind::Investigate, + target_subject_ids: vec![], + location_ids: vec!["dock".into()], + }, + } + } + + #[test] + fn knowledge_outcome_requires_exact_discoverable_fact() { + 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, + source_subject_id: "dockers".into(), + band: StrategicOutcomeBand::Success, + summary: "The inspection confirms the causeway is open.".into(), + supporting_state_references: vec!["fact:fact:safe-route".into()], + effect: StrategicOutcomeEffect::KnowledgeLearned { + owner_subject_id: "dockers".into(), + fact_id: "fact:safe-route".into(), + }, + }; + validate_activity_outcomes(&value, &[action], &[outcome]).unwrap(); + } + + #[test] + fn missing_outcome_is_rejected() { + let value = campaign(); + assert!(validate_activity_outcomes(&value, &[proposal()], &[]).is_err()); + } + + #[tokio::test] + async fn resolver_batches_selected_attempts_under_one_digest_bound_stage() { + let value = campaign(); + let action = proposal(); + let digest = cell_action_digest(&action).unwrap(); + let model = OutcomeFixtureModel { + action_digest: digest.clone(), + requests: Mutex::new(Vec::new()), + }; + + let (outcomes, stages) = resolve_activity_outcomes(&model, &value, &[action]) + .await + .unwrap(); + + assert_eq!(outcomes.len(), 1); + assert!(matches!( + outcomes[0].effect, + StrategicOutcomeEffect::KnowledgeLearned { .. } + )); + assert_eq!(stages.len(), 1); + let requests = model.requests.lock().unwrap(); + assert_eq!(requests.len(), 1); + assert_eq!(requests[0].stage, "strategic_outcome_resolver"); + assert_eq!( + requests[0].snapshot_binding, + activity_outcome_binding( + value.id, + value.revision, + value.resolution_policy.resolution_epoch, + &[digest] + ) + ); + } +} diff --git a/crates/ghostlight-dungeon/src/persistence.rs b/crates/ghostlight-dungeon/src/persistence.rs index 24fa880..2518451 100644 --- a/crates/ghostlight-dungeon/src/persistence.rs +++ b/crates/ghostlight-dungeon/src/persistence.rs @@ -312,6 +312,17 @@ impl CampaignStore { appraisal, )?); } + for outcome in &wave.activity_outcomes { + rows.push(envelope( + "strategic_activity_outcome.v1", + "ghostlight.strategic_activity_outcome.v1", + &format!( + "{}:{}:{}", + next.revision, wave.resolution_epoch, outcome.action_digest + ), + outcome, + )?); + } } if !self .inner diff --git a/crates/ghostlight-dungeon/src/resolution.rs b/crates/ghostlight-dungeon/src/resolution.rs index 746df38..65a7b92 100644 --- a/crates/ghostlight-dungeon/src/resolution.rs +++ b/crates/ghostlight-dungeon/src/resolution.rs @@ -1564,10 +1564,23 @@ pub fn plan_receipt(campaign: &Campaign, cover: &ResolutionCover) -> ResolutionP } } -pub fn validate_and_resolve_wave( +#[derive(Clone, Debug)] +pub struct ResolutionWaveSelection { + pub plan: StrategicTickPlan, + pub activity_proposals: Vec, +} + +pub fn cell_action_digest(proposal: &CellActionProposal) -> Result { + Ok(format!( + "sha256:{:x}", + Sha256::digest(rmp_serde::to_vec_named(proposal)?) + )) +} + +pub fn select_resolution_wave( campaign: &Campaign, wave: &ResolutionWaveCommit, -) -> Result { +) -> Result { if wave.world_revision != campaign.revision || wave.resolution_epoch != campaign.resolution_policy.resolution_epoch || wave.cover.world_revision != campaign.revision @@ -1655,11 +1668,19 @@ pub fn validate_and_resolve_wave( let consequence_limit = 16usize.min(usize::from(wave.cover.effective_budget) * 2); let mut used = BTreeSet::new(); let mut plan = StrategicTickPlan::default(); + let mut activity_proposals = Vec::new(); for proposal in proposals { let key = proposal_target_key(&proposal); if !used.insert(key) { continue; } + let action_digest = cell_action_digest(&proposal)?; + let is_activity = matches!( + proposal.effect, + StrategicCellEffect::GestaltActivity { .. } + | StrategicCellEffect::MemberActivity { .. } + ); + let selected_activity_proposal = is_activity.then(|| proposal.clone()); match proposal.effect { StrategicCellEffect::Institution { institution_id, @@ -1687,6 +1708,7 @@ pub fn validate_and_resolve_wave( target_subject_ids, location_ids, } => plan.gestalt_activities.push(StrategicGestaltActivity { + action_digest, gestalt_id, activity, target_subject_ids, @@ -1723,6 +1745,7 @@ pub fn validate_and_resolve_wave( } => { let source_gestalt_id = campaign.gestalt_members[&member_id].gestalt_id.clone(); plan.member_activities.push(StrategicMemberActivity { + action_digest, member_id, source_gestalt_id, activity, @@ -1752,6 +1775,9 @@ pub fn validate_and_resolve_wave( }); } } + if let Some(proposal) = selected_activity_proposal { + activity_proposals.push(proposal); + } if plan.institution_actions.len() + plan.gestalt_actions.len() + plan.gestalt_activities.len() @@ -1764,7 +1790,24 @@ pub fn validate_and_resolve_wave( break; } } - Ok(plan) + Ok(ResolutionWaveSelection { + plan, + activity_proposals, + }) +} + +pub fn validate_and_resolve_wave( + campaign: &Campaign, + wave: &ResolutionWaveCommit, +) -> Result { + let mut selection = select_resolution_wave(campaign, wave)?; + crate::outcome::validate_activity_outcomes( + campaign, + &selection.activity_proposals, + &wave.activity_outcomes, + )?; + selection.plan.activity_outcomes = wave.activity_outcomes.clone(); + Ok(selection.plan) } fn validate_cell_proposal( @@ -3113,6 +3156,7 @@ pub(crate) mod tests { inactions: vec![], }], cover: cover.clone(), + activity_outcomes: vec![], model_receipt_hashes: vec![], }; let collective = CellActionProposal { @@ -3286,6 +3330,7 @@ pub(crate) mod tests { inactions: vec![], }], cover: cover.clone(), + activity_outcomes: vec![], model_receipt_hashes: vec![], }; let plan = validate_and_resolve_wave(&value, &make_wave(proposal.clone())).unwrap(); @@ -3305,8 +3350,9 @@ pub(crate) mod tests { location_ids: vec!["center".into()], }, }; - let activity_plan = - validate_and_resolve_wave(&value, &make_wave(member_activity.clone())).unwrap(); + let activity_plan = select_resolution_wave(&value, &make_wave(member_activity.clone())) + .unwrap() + .plan; assert_eq!(activity_plan.member_activities.len(), 1); assert!(activity_plan.member_migrations.is_empty()); @@ -3318,7 +3364,7 @@ pub(crate) mod tests { unreachable!() }; target_subject_ids.clear(); - assert!(validate_and_resolve_wave(&value, &make_wave(local_member_communication)).is_ok()); + assert!(select_resolution_wave(&value, &make_wave(local_member_communication)).is_ok()); let same_member_wave = ResolutionWaveCommit { schema: "ghostlight.resolution_wave_commit.v1".into(), @@ -3335,9 +3381,12 @@ pub(crate) mod tests { inactions: vec![], }], cover: cover.clone(), + activity_outcomes: vec![], model_receipt_hashes: vec![], }; - let same_member_plan = validate_and_resolve_wave(&value, &same_member_wave).unwrap(); + let same_member_plan = select_resolution_wave(&value, &same_member_wave) + .unwrap() + .plan; assert_eq!(same_member_plan.member_activities.len(), 1); assert!(same_member_plan.member_migrations.is_empty()); @@ -3374,7 +3423,9 @@ pub(crate) mod tests { }, }; let activity_plan = - validate_and_resolve_wave(&value, &make_wave(exact_rival_activity.clone())).unwrap(); + select_resolution_wave(&value, &make_wave(exact_rival_activity.clone())) + .unwrap() + .plan; assert_eq!(activity_plan.gestalt_activities.len(), 1); assert!(activity_plan.gestalt_actions.is_empty()); @@ -3406,15 +3457,18 @@ pub(crate) mod tests { inactions: vec![], }], cover: cover.clone(), + activity_outcomes: vec![], model_receipt_hashes: vec![], }; - let same_subject_plan = validate_and_resolve_wave(&value, &same_subject_wave).unwrap(); + let same_subject_plan = select_resolution_wave(&value, &same_subject_wave) + .unwrap() + .plan; assert_eq!(same_subject_plan.gestalt_activities.len(), 1); assert!(same_subject_plan.gestalt_actions.is_empty()); let mut borrowed_rival_channel = exact_rival_activity.clone(); borrowed_rival_channel.public_channels = vec!["private dock code".into()]; - assert!(validate_and_resolve_wave(&value, &make_wave(borrowed_rival_channel)).is_err()); + assert!(select_resolution_wave(&value, &make_wave(borrowed_rival_channel)).is_err()); let mut invented_target = exact_rival_activity; let StrategicCellEffect::GestaltActivity { @@ -3424,7 +3478,7 @@ pub(crate) mod tests { unreachable!() }; *target_subject_ids = vec!["unseen-stranger".into()]; - assert!(validate_and_resolve_wave(&value, &make_wave(invented_target)).is_err()); + assert!(select_resolution_wave(&value, &make_wave(invented_target)).is_err()); assert!(strategic_activity_targets(&value, "dockers").contains("member:mira")); let address_mira = CellActionProposal { @@ -3441,7 +3495,9 @@ pub(crate) mod tests { location_ids: vec!["center".into()], }, }; - let address_plan = validate_and_resolve_wave(&value, &make_wave(address_mira)).unwrap(); + let address_plan = select_resolution_wave(&value, &make_wave(address_mira)) + .unwrap() + .plan; assert_eq!(address_plan.gestalt_activities.len(), 1); assert_eq!(address_plan.gestalt_activities[0].gestalt_id, "dockers"); assert_eq!( @@ -3488,6 +3544,7 @@ pub(crate) mod tests { inactions: vec![], }], cover, + activity_outcomes: vec![], model_receipt_hashes: vec![], }; let plan = validate_and_resolve_wave(&value, &wave).unwrap(); diff --git a/crates/ghostlight-dungeon/src/scheduler.rs b/crates/ghostlight-dungeon/src/scheduler.rs index 30b5617..c43ee63 100644 --- a/crates/ghostlight-dungeon/src/scheduler.rs +++ b/crates/ghostlight-dungeon/src/scheduler.rs @@ -4,13 +4,14 @@ use crate::{ SimulationCell, }, model::{ModelPort, ModelStageOutput, ModelStageRequest, run_validated_stage}, + outcome::{activity_outcome_binding, resolve_activity_outcomes}, persona::{ CellConstituentSlice, CellMemberSlice, CellPerceivedEventSlice, CellProjectionEngine, ExecutionPermit, PermittedCellSlice, }, resolution::{ - cell_action_limit, default_demand, plan_cover, plan_receipt, validate_and_resolve_wave, - validate_demand, + cell_action_digest, cell_action_limit, default_demand, plan_cover, plan_receipt, + select_resolution_wave, validate_and_resolve_wave, validate_demand, }, }; use anyhow::{Context, Result, anyhow}; @@ -57,6 +58,8 @@ pub async fn propose_resolution_wave( let (demand, mut stages) = project_resolution_demand(model.as_ref(), campaign).await; let cover = plan_cover(campaign, demand)?; let receipt = plan_receipt(campaign, &cover); + let outcome_model = model.clone(); + let outcome_permit = permit.clone(); let engine = CellProjectionEngine { model, permit, @@ -110,24 +113,67 @@ pub async fn propose_resolution_wave( }), ); } - let model_receipt_hashes = stages + let cell_model_receipt_hashes = stages .iter() .map(|stage| stage.receipt.storage_key().to_owned()) .collect::>(); - let aggregate_receipt_hash = format!( - "sha256:{:x}", - Sha256::digest(model_receipt_hashes.join("|").as_bytes()) - ); - let wave = ResolutionWaveCommit { + let mut wave = ResolutionWaveCommit { schema: "ghostlight.resolution_wave_commit.v1".into(), world_revision: campaign.revision, resolution_epoch: campaign.resolution_policy.resolution_epoch, cover, plan_receipt: receipt, appraisals, - model_receipt_hashes, + activity_outcomes: Vec::new(), + model_receipt_hashes: cell_model_receipt_hashes, }; + let selection = select_resolution_wave(campaign, &wave)?; + let outcome_digests = selection + .activity_proposals + .iter() + .map(cell_action_digest) + .collect::>>()?; + let outcome_binding = activity_outcome_binding( + campaign.id, + campaign.revision, + campaign.resolution_policy.resolution_epoch, + &outcome_digests, + ); + if !outcome_digests.is_empty() { + outcome_permit + .require( + "strategic-outcomes", + &outcome_binding, + "strategic_outcome_resolver", + ) + .await?; + } + let (activity_outcomes, outcome_stages) = resolve_activity_outcomes( + outcome_model.as_ref(), + campaign, + &selection.activity_proposals, + ) + .await?; + if !outcome_digests.is_empty() { + outcome_permit + .require( + "strategic-outcomes", + &outcome_binding, + "strategic_outcome_terminal", + ) + .await?; + } + stages.extend(outcome_stages); + wave.activity_outcomes = activity_outcomes; + wave.model_receipt_hashes = stages + .iter() + .map(|stage| stage.receipt.storage_key().to_owned()) + .collect(); validate_and_resolve_wave(campaign, &wave)?; + let aggregate_receipt_hash = format!( + "sha256:{:x}", + Sha256::digest(wave.model_receipt_hashes.join("|").as_bytes()) + ); Ok(StrategicResolutionOutput { wave, stages, diff --git a/crates/ghostlight-dungeon/src/surface.rs b/crates/ghostlight-dungeon/src/surface.rs index 7479f03..8485d0c 100644 --- a/crates/ghostlight-dungeon/src/surface.rs +++ b/crates/ghostlight-dungeon/src/surface.rs @@ -115,6 +115,7 @@ pub fn operator_surface( rejected: &[RejectedProposalReceipt], resolution_plans: &[crate::domain::ResolutionPlanReceipt], cell_appraisals: &[crate::domain::CellAppraisal], + activity_outcomes: &[crate::domain::StrategicActivityOutcome], resolution_controls: &[crate::domain::ResolutionControlReceipt], live_turn_pressure: usize, ) -> Value { @@ -205,6 +206,7 @@ pub fn operator_surface( "rejected_proposals": rejected, "resolution_plan_receipts": resolution_plans, "cell_appraisals": cell_appraisals, + "strategic_activity_outcomes": activity_outcomes, "resolution_control_receipts": resolution_controls, "scheduler": {"live_turn_pressure": live_turn_pressure} }); @@ -223,6 +225,7 @@ pub fn operator_surface( {"id":"dungeon.operator.status","kind":"card","props":{"title":format!("Revision {} · {} model stages / {} provider attempts · {} tokens · {} rejected proposals",campaign.revision,stages.len(),provider_attempt_count,token_usage.total_tokens,rejected.len())},"children":[{"id":"dungeon.operator.usage","kind":"text","props":{"value":format!("Prompt {} (cache hit {}, miss {}, {}%) · completion {} · reasoning {} · retries {}",token_usage.prompt_tokens,token_usage.prompt_cache_hit_tokens,token_usage.prompt_cache_miss_tokens,cache_hit_percent,token_usage.completion_tokens,token_usage.reasoning_tokens,retry_count)},"children":[]}]}, {"id":"dungeon.operator.cover","kind":"card","props":{"title":format!("Agency cover · epoch {} · budget {}",campaign.resolution_policy.resolution_epoch,campaign.resolution_policy.active_cell_budget)},"children":[{"id":"dungeon.operator.cover.text","kind":"text","props":{"value":cover_text},"children":[]}]}, {"id":"dungeon.operator.graph","kind":"card","props":{"title":format!("Agency graph · {} profiles · {} relations",campaign.agency_profiles.len(),campaign.agency_relations.len())},"children":[{"id":"dungeon.operator.graph.text","kind":"text","props":{"value":graph_text},"children":[]}]}, + {"id":"dungeon.operator.outcomes","kind":"card","props":{"title":format!("Strategic activity outcomes · {}",activity_outcomes.len())},"children":[{"id":"dungeon.operator.outcomes.text","kind":"text","props":{"value":activity_outcomes.iter().rev().take(16).map(|outcome|format!("{} {:?} — {}",outcome.source_subject_id,outcome.band,outcome.summary)).collect::>().join("\n")},"children":[]}]}, {"id":"dungeon.operator.typed","kind":"code","props":{"language":"json","value":serde_json::to_string_pretty(&typed).unwrap_or_else(|_| "operator projection failed".into())},"children":[]} ]},"styles":{"tokens":{"colorBackground":"#0c1110","colorPanel":"#17201d","colorText":"#e8e1cf","colorMuted":"#9aa69f","colorAccent":"#d49b58"}}}, "commands":[] diff --git a/docs/architecture/ghostlight-dungeon-mvp.md b/docs/architecture/ghostlight-dungeon-mvp.md index 996ff00..18a74db 100644 --- a/docs/architecture/ghostlight-dungeon-mvp.md +++ b/docs/architecture/ghostlight-dungeon-mvp.md @@ -836,6 +836,7 @@ Ghostlight publishes JSON Schema for: - `ghostlight.resolution_control_receipt.v1` - `ghostlight.cell_appraisal.v1` - `ghostlight.cell_action_proposal.v1` +- `ghostlight.strategic_activity_outcome.v1` - `ghostlight.gestalt_fission_preview.v1` The UI consumes existing `gamecult.eve.surface.v1` and diff --git a/docs/architecture/ghostlight-multiresolution-agency.md b/docs/architecture/ghostlight-multiresolution-agency.md index d64d05a..b95d35f 100644 --- a/docs/architecture/ghostlight-multiresolution-agency.md +++ b/docs/architecture/ghostlight-multiresolution-agency.md @@ -256,6 +256,75 @@ exact constituent. The kernel validates that subject's knowledge, information channel, resources, authority, relationships, location, and reachable destinations. Secrets are never unioned. +## Strategic outcome authority + +A valid attributed attempt is not yet a world consequence. The Interpreter +owns the narrow claim that a constituent chose an admissible attempt; it does +not decide whether the attempt worked, what opposition did, or which durable +state changed. Treating the attempt event as a sufficient result made the +world busy in prose while its resources, relationships, knowledge, and +pressures mostly stood still. + +One wave-level strategic outcome resolver owns that missing decision. It runs +after priority and incompatibility selection but before the command enters the +kernel: + +1. Ghostlight content-addresses every selected `gestalt_activity` and + `member_activity` proposal. The digest binds exact source, intent, intended + effect, targets, locations, state references, channels, and typed activity. +2. A local context compiler supplies only those selected attempts and their + legal consequence handles: source capabilities and holdings, exact target + state, active incident relations, current pressures, eligible named-member + deltas, and source-discoverable canonical facts. +3. One cheap structured model call resolves the batch. It returns exactly one + success, mixed, or failure result for every digest and chooses one bounded + typed effect, including an explicit `no_material_change` when the attempt + cannot honestly alter canonical state. +4. Local validation recomputes every permission from the unchanged campaign + snapshot. It rejects invented owners, resources, relations, facts, pressure + resolutions, player mutation, missing outcomes, duplicate outcomes, and + conflicting effect targets. One same-snapshot correction is permitted. +5. `WorldKernel` requires the outcome-stage receipt bound to the complete + ordered digest set, then applies the plan and all outcomes to one private + campaign copy. A late invalid effect aborts the wave; no clock, activity, + outcome, detail debt, or world state reaches the committed campaign. + +The public `strategic_activity_outcome.v1` contract is a typed sum. Its MVP +effects are deliberately small: + +- create, spend, or give away a resource owned by the acting population or + named member; +- add or resolve pressure on the acting population or an exact targeted + population; +- shift one exact active agency relation incident to the source and a supplied + target by a bounded amount; +- add one memory, obligation, or relationship description to an exact named + member who owns that perspective; +- learn one exact canonical fact that was discoverable at the attempt location + or already known by an exact communication target; +- or record an explicit reason why no durable material change occurred. + +The provider boundary uses a flat JSON proposal rather than asking the model to +emit the public tagged sum directly. The private flat shape avoids fragile +`oneOf` generation; a local interpreter is the only component allowed to turn +it into the typed public effect. JSON remains a model-provider boundary. The +accepted outcome, its binding, and its receipt are persisted through the +campaign's CultCache path. + +Outcome resolution does not grant an arena collective authority. Every result +remains bound to the exact constituent proposal digest. A rival can suffer a +pressure or relation consequence, but cannot be made to speak, spend a +resource, reveal knowledge, or acquire a private relationship as though the +arena had chosen for it. Effects on the player are forbidden; accessible news +may later reveal a committed consequence, but the absent player is never +puppeted or directly harmed. + +The resolver is batched once per strategic wave rather than once per cell or +attempt. This keeps the stable rules and schema in one cacheable prompt prefix, +lets it compare simultaneous opposition, and spends completion tokens only on +the handful of attempts that survived selection. Provider concurrency still +controls the preceding Persona-cell wave and does not alter outcome authority. + ## Fairness and quiet-world agency Every active profile carries persistent non-fictional `detail_debt`. Aggregate @@ -496,6 +565,8 @@ The schema catalog and CultCache stores publish: `resolution_plan_receipt.v1`, and `resolution_control_receipt.v1`; - `cell_appraisal.v1`, `cell_action_proposal.v1`, and the internal atomic `resolution_wave_commit.v1` bundle; +- `strategic_activity_outcome.v1`, persisted individually for inspection and + also bound inside the atomic resolution wave; - `gestalt_migration.v1` and `member_migration.v1` as distinct collective and individual movement contracts inside strategic plans; - `gestalt_fission_preview.v1` and approval-gated `FissionGestalt`. @@ -526,6 +597,15 @@ lineage parents as simulation subjects, and repeats the identity/callback check after sustained compression. Both migration endpoints must be active leaves at lineage depth two or greater. +Both modes distinguish selected attempts from resolved material consequences. +The harness counts direct typed transitions and non-`no_material_change` +activity outcomes separately, rejects a sustained run that never changes the +background world materially, and records every outcome in the private +preflight. A named member's dormant delta may now evolve offscreen, but any +change to memory, obligation, relationship, equipment, or knowledge must be +accounted for by an exact member-bound outcome before the return callback is +accepted. + Fairness acceptance treats a rejected provider wave the same way the daemon's scheduler does: the failed pulse records its private trace and commits nothing; a later pulse may try the same still-current revision again. The harness permits @@ -538,7 +618,7 @@ proof of the attributed-inaction and immutable-batch machinery together. It ran 23 sustained waves over 24 active subjects in 742.435 seconds. Every subject received direct resolution attention; 22 background subjects acted, while the two without a committed action were represented by exact attributed inaction. -The wave plans committed 175 consequences: 85 population activities, 66 +The wave plans selected 175 strategic effects: 85 population activities, 66 institution postures, 22 named-member activities, one population migration, and one population-pressure transition. The appraisals also retained 179 attributed inactions, including 31 cells where some constituents acted while @@ -560,11 +640,14 @@ victory lap. Observed traffic used 1,988,812 prompt and 233,146 completion tokens at a 66.64% prompt-cache hit rate. Nineteen rejected pulses consumed 807,304 prompt tokens—40.59% of observed prompt work. Eleven were caught by the action-bound semantic verifier, three by Interpreter semantic validation, two -by JSON Schema, and three by transport failure. Most population consequences -are still attributed attempts recorded in event history rather than resolved -changes to resources, bargains, obligations, relationships, or pressures. A -separate strategic outcome resolver must own those material consequences; the -Interpreter must not be promoted into asserting success. +by JSON Schema, and three by transport failure. In that build, most population +effects were still attributed attempts recorded in event history rather than +resolved changes to resources, obligations, relationships, knowledge, or +pressures. The current candidate adds the separate strategic outcome resolver +described above without promoting the Interpreter into asserting success. A +revised live result is still required; the `d044951` profile is evidence for +cover, fairness, attribution, and atomic batch behavior, not evidence for +material activity outcomes. The callback and fairness claims are independently falsifiable. Strict live mode requires Mira's Persona to choose resettlement and proves the later diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 88a7e81..6f81540 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -354,16 +354,29 @@ recovered 19 rejected pulses with no partial mutation. Observed usage was 1,988,812 prompt / 233,146 completion tokens at 66.64% prompt-cache hits; rejected pulses consumed 807,304 prompt tokens (40.59%). The next efficiency cut is the failed-pulse tail, led by semantic effect-verifier rejection. The -next dramatic cut is a separate strategic outcome resolver: 85 committed -population activities are still attempts, not enough typed material change. +dramatic result was still missing: 85 committed population activities were +attempts rather than typed material change. -Do not call setting-wide material agency finished yet. Most population output -is still an attributed `gestalt_activity` attempt stored as history. The long -run became repetitive around ferry loading and shelter requests because no -separate owner resolved enough attempts into typed resources, bargains, -relationships, obligations, or pressure changes. Add a strategic outcome -resolver between attributed proposals and WorldKernel commit; do not grant the -Interpreter permission to assert successful outcomes. +The candidate now contains that separate owner. Priority selection +content-addresses each selected population/member activity, one batched Flash +stage resolves the exact attempt set, and WorldKernel requires one outcome per +digest plus a stage receipt bound to the whole digest set. Outcomes are locally +limited to exact resources, population pressures, incident relations, +named-member memories/obligations/relationships, discoverable facts, or an +explicit no-material-change result. The Interpreter still owns attempts only. +Kernel tests prove a wrong outcome binding leaves time and state untouched, a +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 multiresolution body is deployed on Starfire. Typed health matched the immutable release, DeepSeek was ready, and the disposable live strategic-cell diff --git a/notes/ghostlight-current-system-map.md b/notes/ghostlight-current-system-map.md index 887174d..53e4f59 100644 --- a/notes/ghostlight-current-system-map.md +++ b/notes/ghostlight-current-system-map.md @@ -42,8 +42,10 @@ exact campaign revision -> cohesive or arena simulation-cell cover -> one private Projector/Persona/Interpreter membrane per cell -> model proposes exact constituent-attributed actions or explicit inaction + -> runtime selects compatible attempts and content-addresses each activity + -> one batched outcome resolver chooses bounded typed consequences -> runtime binds complete cell membership + world/resolution revisions - -> WorldKernel validates cover, receipts, knowledge, scope, topology, and bounds + -> WorldKernel validates cover, stage/outcome receipts, knowledge, scope, custody, topology, and bounds -> AdvanceStrategicTick through the campaign mailbox -> one atomic campaign/event/news/cover/appraisal commit ``` @@ -110,11 +112,26 @@ Gestalt background choices use three distinct typed paths. Pressure transitions change exact unresolved markers. `gestalt_activity` records an attributed preparation, coordination, investigation, recruitment, obstruction, trade, or communication attempt against subjects connected by an explicit agency -relation or exact shared location without claiming the outcome. A selected +relation or exact shared location without claiming the outcome. After +selection, one wave-level Flash resolver receives only those attempts and +precomputed legal consequence handles. It must return one digest-bound +`strategic_activity_outcome.v1` per activity; missing, duplicate, stale, +player-mutating, or invented effects reject the entire wave. Accepted outcomes +may change exact resources, population pressures, incident agency relations, +named-member deltas, or discoverable canonical knowledge, or explicitly record +that no durable material change occurred. A selected dormant member can be addressed by their durable ID; this does not union them into the source population. The kernel derives the event text and exact participant IDs; the arena and model prose own neither. +The outcome resolver does not repair or reinterpret Persona intent. The +Interpreter owns the attempt; the resolver owns opposition and result; +WorldKernel alone owns mutation. Its stage receipt binds the sorted set of +MessagePack proposal digests, and every outcome is stored independently in +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. + `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 b1a7b00..5ba8788 100644 --- a/notes/ghostlight-implementation-plan.md +++ b/notes/ghostlight-implementation-plan.md @@ -43,6 +43,15 @@ strings are bound to witnesses locally, rejected candidates become coverage gaps, and deterministic coarse profiles keep unknown facets unknown. The Pro agency stage no longer spends output tokens restating remote profiles. +Strategic activity outcomes now have their own authority between attempt +selection and commit. One batched Flash resolver receives only selected +digest-bound attempts plus exact legal consequence handles. It emits one +bounded typed result per activity; local validation rejects invented custody, +relations, facts, pressure resolutions, member owners, and player mutation. +WorldKernel requires the action-set-bound stage receipt and applies every +outcome with the rest of the wave on one private campaign copy. Accepted +outcomes are stored in CultCache and shown through the operator Eve surface. + 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, with only direct source text @@ -65,11 +74,15 @@ 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 two-tester playtest. Treat player confusion, dramatic flatness, -and token-heavy low-consequence stages as evidence about missing context or +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 +token-heavy low-consequence stages as evidence about missing context or misplaced authority. Use model-stage cache usage, rejection receipts, cover -plans, and world commits to improve satisfaction and cognitive efficiency -without weakening state admission. +plans, outcomes, and world commits to improve satisfaction and cognitive +efficiency without weakening state admission. ## Prior research-program phase