From 774e414b26826e86638e7f893cbb7f3ed1f70241 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 17 Aug 2026 23:37:36 +0200 Subject: [PATCH] Model bounded gestalt background activity --- .../bin/ghostlight-gestalt-dynamics-smoke.rs | 42 ++- .../src/bin/ghostlight-gestalt-scale-smoke.rs | 3 +- .../src/bin/ghostlight-strategic-smoke.rs | 2 + crates/ghostlight-dungeon/src/domain.rs | 33 +++ crates/ghostlight-dungeon/src/gestalt.rs | 179 ++++++++++++- crates/ghostlight-dungeon/src/kernel.rs | 250 ++++++++++++++++++ crates/ghostlight-dungeon/src/persona.rs | 91 ++++++- crates/ghostlight-dungeon/src/resolution.rs | 212 +++++++++++++++ crates/ghostlight-dungeon/src/scheduler.rs | 16 +- .../ghostlight-multiresolution-agency.md | 42 ++- notes/fresh-workspace-handoff.md | 11 + notes/ghostlight-current-system-map.md | 13 + notes/ghostlight-dungeon.md | 12 +- state/map.yaml | 7 +- tools/summarize_ghostlight_live_fire.ps1 | 2 +- 15 files changed, 882 insertions(+), 33 deletions(-) diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-dynamics-smoke.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-dynamics-smoke.rs index bf90f09..0c6dbea 100644 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-dynamics-smoke.rs +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-dynamics-smoke.rs @@ -85,6 +85,7 @@ async fn main() -> anyhow::Result<()> { use chrono::Utc; use ghostlight_dungeon::{ domain::{SimulationCellMode, TickSource, WorldCommand}, + gestalt::GestaltPresencePlanner, kernel::{CommandResult, WorldKernel}, model::{DeepSeekPort, ModelPort}, persistence::CampaignStore, @@ -200,8 +201,10 @@ async fn main() -> anyhow::Result<()> { if plan.member_migrations.len() != usize::from(migration_proposal.is_some()) { anyhow::bail!("validated wave changed the attributed member choice") } - let background_action_count = - plan.institution_actions.len() + plan.gestalt_actions.len() + plan.actor_moves.len(); + let background_action_count = plan.institution_actions.len() + + plan.gestalt_actions.len() + + plan.gestalt_activities.len() + + plan.actor_moves.len(); for stage in &output.stages { store.insert( "persona_stage_receipt.v1", @@ -401,14 +404,34 @@ async fn main() -> anyhow::Result<()> { anyhow::bail!("sustained population simulation damaged Mira's dormant identity") } + 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 { + model: model.clone(), + model_name: "deepseek-v4-flash".into(), + }; + let (presence_plan, presence_receipt) = presence_planner.plan(&advanced, return_event).await?; + if presence_plan.individuations.len() != 0 + || presence_plan.demotions.len() != 0 + || presence_plan.promotions.len() != 1 + || presence_plan.promotions[0].member_id != "mira-venn" + || presence_plan.promotions[0].gestalt_id != "harbor-neighbors" + { + anyhow::bail!( + "automatic presence planning did not surface the existing refugee callback: {}", + serde_json::to_string(&presence_plan)? + ) + } + store.insert( + "persona_stage_receipt.v1", + "ghostlight.persona_stage_receipt.v1", + presence_receipt.storage_key(), + &presence_receipt, + )?; let materialized = kernel - .command(WorldCommand::MaterializeGestaltMember { + .command(WorldCommand::ReconcileGestaltPresence { expected_revision: advanced.revision, - gestalt_id: "harbor-neighbors".into(), - expected_gestalt_version: advanced.gestalts["harbor-neighbors"].version, - member_id: "mira-venn".into(), - expected_member_version: member_after_sustained.version, - location_id: "south-harbor".into(), + reason: return_event.into(), + plan: presence_plan.clone(), }) .await?; let CommandResult::Committed { @@ -454,6 +477,8 @@ async fn main() -> anyhow::Result<()> { "plan":plan, "commit":committed, "materialization":materialized, + "automatic_presence_plan":presence_plan, + "automatic_presence_receipt":presence_receipt, "identity_preserved":true, "effective_state_preserved":true, "player_unchanged":true, @@ -716,6 +741,7 @@ fn dynamics_campaign() -> ghostlight_dungeon::domain::Campaign { summary: pressure.into(), actor_ids: vec![], institution_ids: vec![], + gestalt_ids: vec!["refugees-east".into(), "harbor-neighbors".into()], location_ids: vec!["transit-camp".into(), "south-harbor".into()], public_channels: vec!["public harbor bulletin".into()], }], diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-scale-smoke.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-scale-smoke.rs index 6a4c04e..565d02a 100644 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-scale-smoke.rs +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-scale-smoke.rs @@ -152,7 +152,7 @@ async fn main() -> anyhow::Result<()> { "cover":cover, "appraisals":output.wave.appraisals, "plan":plan, - "material_action_count":plan.institution_actions.len() + plan.gestalt_actions.len() + plan.actor_moves.len() + plan.member_migrations.len(), + "material_action_count":plan.institution_actions.len() + plan.gestalt_actions.len() + plan.gestalt_activities.len() + plan.actor_moves.len() + plan.member_migrations.len(), "explicit_inaction_count":explicit_inaction_count, "model_stage_receipts":output.stages.iter().map(|stage|&stage.receipt).collect::>(), "commit":committed, @@ -260,6 +260,7 @@ fn scale_campaign(budget: u8, pressure: &str) -> ghostlight_dungeon::domain::Cam summary: pressure.into(), actor_ids: vec![], institution_ids: (0..24).map(|index| format!("faction-{index:02}")).collect(), + gestalt_ids: vec![], location_ids: vec!["forum".into()], public_channels: vec!["public bulletin".into()], }], diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs index 45efb9e..6817cf4 100644 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs @@ -43,6 +43,7 @@ async fn main() -> anyhow::Result<()> { summary: pressure.clone(), actor_ids: vec!["runner".into()], institution_ids: vec!["board".into()], + gestalt_ids: vec![], location_ids: vec!["depot".into(), "yard".into()], public_channels: vec!["station radio".into()], }); @@ -67,6 +68,7 @@ async fn main() -> anyhow::Result<()> { let plan = ghostlight_dungeon::resolution::validate_and_resolve_wave(&campaign, &output.wave)?; if plan.institution_actions.is_empty() && plan.gestalt_actions.is_empty() + && plan.gestalt_activities.is_empty() && plan.actor_moves.is_empty() { anyhow::bail!( diff --git a/crates/ghostlight-dungeon/src/domain.rs b/crates/ghostlight-dungeon/src/domain.rs index 5bf9182..c61998d 100644 --- a/crates/ghostlight-dungeon/src/domain.rs +++ b/crates/ghostlight-dungeon/src/domain.rs @@ -432,6 +432,14 @@ pub enum StrategicCellEffect { #[serde(default)] pressure_resolutions: Vec, }, + GestaltActivity { + gestalt_id: String, + activity: StrategicActivityKind, + #[serde(default)] + target_subject_ids: Vec, + #[serde(default)] + location_ids: Vec, + }, ActorMove { actor_id: String, destination_id: String, @@ -441,6 +449,18 @@ pub enum StrategicCellEffect { }, } +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum StrategicActivityKind { + Prepare, + Coordinate, + Investigate, + Recruit, + Obstruct, + Trade, + Communicate, +} + #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] pub struct CellActionProposal { pub subject_id: String, @@ -559,6 +579,8 @@ pub struct Event { pub summary: String, pub actor_ids: Vec, pub institution_ids: Vec, + #[serde(default)] + pub gestalt_ids: Vec, pub location_ids: Vec, pub public_channels: Vec, } @@ -577,6 +599,8 @@ pub struct NewsIssue { pub struct StrategicTickPlan { pub institution_actions: Vec, pub gestalt_actions: Vec, + #[serde(default)] + pub gestalt_activities: Vec, pub actor_moves: Vec, #[serde(default)] pub member_migrations: Vec, @@ -598,6 +622,15 @@ pub struct StrategicGestaltAction { pub public_channels: Vec, } +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct StrategicGestaltActivity { + pub gestalt_id: String, + pub activity: StrategicActivityKind, + pub target_subject_ids: Vec, + pub location_ids: Vec, + pub public_channels: Vec, +} + #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] pub struct StrategicActorMove { pub actor_id: String, diff --git a/crates/ghostlight-dungeon/src/gestalt.rs b/crates/ghostlight-dungeon/src/gestalt.rs index a823877..14b5ad5 100644 --- a/crates/ghostlight-dungeon/src/gestalt.rs +++ b/crates/ghostlight-dungeon/src/gestalt.rs @@ -19,12 +19,51 @@ impl GestaltPresencePlanner { event_summary: &str, ) -> Result<(GestaltPresencePlan, ModelStageReceipt)> { let player_location = &campaign.actors[&campaign.player_actor_id].location_id; + let nearby_gestalts = campaign + .gestalts + .values() + .filter(|gestalt| { + crate::resolution::validate_active_gestalt_presence_location( + campaign, + &gestalt.id, + player_location, + ) + .is_ok() + }) + .collect::>(); + let nearby_gestalt_ids = nearby_gestalts + .iter() + .map(|gestalt| gestalt.id.as_str()) + .collect::>(); + let nearby_dormant_members = campaign + .gestalt_members + .values() + .filter(|member| { + nearby_gestalt_ids.contains(member.gestalt_id.as_str()) + && crate::resolution::dormant_member_location(campaign, &member.id) + .is_ok_and(|location| location == *player_location) + }) + .collect::>(); + let materialized_members = campaign + .gestalt_members + .values() + .filter_map(|member| { + let actor_id = member.materialized_actor_id.as_ref()?; + let actor = campaign.actors.get(actor_id)?; + Some(serde_json::json!({ + "member_id":member.id, + "member_version":member.version, + "actor_id":actor_id, + "actor_location_id":actor.location_id, + "relevance_lease_until_revision":member.relevance_lease_until_revision, + })) + }) + .collect::>(); let candidates = serde_json::json!({ "player_location_id": player_location, - "gestalts": campaign.gestalts, - "members": campaign.gestalt_members, - "materialized_member_actor_ids": campaign.gestalt_members.values() - .filter_map(|member| member.materialized_actor_id.clone()).collect::>(), + "nearby_active_leaf_gestalts": nearby_gestalts, + "nearby_dormant_members": nearby_dormant_members, + "materialized_members": materialized_members, }); let schema = serde_json::to_value(schema_for!(GestaltPresencePlan))?; let output = run_validated_stage( @@ -34,7 +73,7 @@ impl GestaltPresencePlanner { model: self.model_name.clone(), snapshot_binding: format!("campaign:{}:revision:{}", campaign.id, campaign.revision), lived_stream: format!( - "Choose reversible Persona population presence after this event. Promote an existing member when they become individually relevant. If the event makes an anonymous population member individually relevant and no supplied member fits, individuate exactly one durable member delta from the gestalt baseline; use a new stable lowercase id, version 0, the exact gestalt id/version, no materialized actor id, and record only personal departures from the shared baseline. Demote a materialized member when they are no longer scene-relevant. Never place a promoted or individuated member outside the player location. Aggregate deltas must remain empty; population learning requires separate review. Emit the exact JSON schema.\nSCHEMA:\n{}\nCANDIDATES:\n{}\nEVENT:\n{}", + "Choose reversible Persona population presence after this event. Promote an existing member when they become individually relevant. A nearby dormant member with a specific relationship, memory, obligation, or unresolved goal tied to the player may create a natural callback during an otherwise ordinary encounter; prefer that existing person over anonymous individuation when their exact delta supports it. If the event makes an anonymous population member individually relevant and no supplied member fits, individuate exactly one durable member delta from the gestalt baseline; use a new stable lowercase id, version 0, the exact gestalt id/version, no materialized actor id, and record only personal departures from the shared baseline. Demote a materialized member when they are no longer scene-relevant. Never place a promoted or individuated member outside the player location. Aggregate deltas must remain empty; population learning requires separate review. Emit the exact JSON schema.\nSCHEMA:\n{}\nCANDIDATES:\n{}\nEVENT:\n{}", serde_json::to_string_pretty(&schema)?, candidates, event_summary ), output_schema: Some(schema), @@ -66,6 +105,11 @@ fn validate_plan( .gestalts .get(&individuation.gestalt_id) .ok_or_else(|| anyhow!("presence plan invented a gestalt"))?; + crate::resolution::validate_active_gestalt_presence_location( + campaign, + &individuation.gestalt_id, + player_location, + )?; if individuation.expected_gestalt_version != gestalt.version || individuation.location_id != player_location || member.gestalt_id != individuation.gestalt_id @@ -93,11 +137,13 @@ fn validate_plan( .gestalts .get(&promotion.gestalt_id) .ok_or_else(|| anyhow!("presence plan invented a gestalt"))?; + let member_location = crate::resolution::dormant_member_location(campaign, &member.id)?; if member.gestalt_id != promotion.gestalt_id || member.version != promotion.expected_member_version || gestalt.version != promotion.expected_gestalt_version || member.materialized_actor_id.is_some() || promotion.location_id != player_location + || member_location != promotion.location_id { return Err(anyhow!("presence promotion does not match its snapshot")); } @@ -137,3 +183,126 @@ fn validate_plan( } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + domain::{GestaltMemberDelta, GestaltPersonaState, Location}, + model::ModelStageRequest, + }; + use async_trait::async_trait; + use std::{ + collections::{BTreeMap, BTreeSet}, + sync::Mutex, + }; + + struct CapturePresenceModel { + prompt: Arc>, + } + + #[async_trait] + impl ModelPort for CapturePresenceModel { + async fn run(&self, request: &ModelStageRequest) -> Result { + *self.prompt.lock().unwrap() = request.lived_stream.clone(); + Ok(serde_json::json!({ + "individuations":[], + "promotions":[], + "demotions":[] + }) + .to_string()) + } + + fn provider(&self) -> &'static str { + "presence-capture" + } + } + + #[tokio::test] + async fn presence_projection_contains_only_nearby_active_leaves_and_relevant_members() { + let mut campaign = crate::resolution::tests::campaign(0, 8); + campaign.locations.insert( + "far".into(), + Location { + id: "far".into(), + name: "Far".into(), + container_id: None, + routes: BTreeMap::new(), + persistent_features: vec![], + }, + ); + let gestalt = |id: &str, name: &str, location: &str| GestaltPersonaState { + schema: "ghostlight.gestalt_persona_state.v1".into(), + id: id.into(), + name: name.into(), + version: 0, + home_location_id: location.into(), + shared_capabilities: BTreeSet::new(), + shared_knowledge: BTreeSet::new(), + resources: BTreeSet::new(), + goals: vec![], + pressures: vec![], + }; + campaign.gestalts.insert( + "nearby-leaf".into(), + gestalt("nearby-leaf", "Nearby leaf", "center"), + ); + campaign + .gestalts + .insert("far-leaf".into(), gestalt("far-leaf", "Far leaf", "far")); + campaign.gestalts.insert( + "inactive-parent".into(), + gestalt("inactive-parent", "Inactive parent", "center"), + ); + let member = |id: &str, name: &str, gestalt_id: &str, location: &str| GestaltMemberDelta { + schema: "ghostlight.gestalt_member_delta.v1".into(), + id: id.into(), + gestalt_id: gestalt_id.into(), + version: 0, + name: name.into(), + capability_additions: BTreeSet::new(), + capability_removals: BTreeSet::new(), + knowledge_additions: BTreeSet::new(), + knowledge_removals: BTreeSet::new(), + equipment: BTreeSet::new(), + conditions: BTreeSet::new(), + obligations: BTreeSet::new(), + relationships: BTreeMap::new(), + goals: vec![], + memories: vec![], + last_location_id: Some(location.into()), + materialized_actor_id: None, + last_relevant_revision: 0, + relevance_lease_until_revision: 0, + }; + campaign.gestalt_members.insert( + "mira".into(), + member("mira", "Mira Nearby", "nearby-leaf", "center"), + ); + campaign.gestalt_members.insert( + "far-person".into(), + member("far-person", "Far Person", "far-leaf", "far"), + ); + crate::resolution::ensure_agency_profiles(&mut campaign); + let parent = campaign.agency_profiles.get_mut("inactive-parent").unwrap(); + parent.active_leaf = false; + parent.simulation_eligible = false; + + let prompt = Arc::new(Mutex::new(String::new())); + GestaltPresencePlanner { + model: Arc::new(CapturePresenceModel { + prompt: prompt.clone(), + }), + model_name: "fixture".into(), + } + .plan(&campaign, "The player works in the square.") + .await + .unwrap(); + let prompt = prompt.lock().unwrap(); + assert!(prompt.contains("Nearby leaf")); + assert!(prompt.contains("Mira Nearby")); + assert!(!prompt.contains("Far leaf")); + assert!(!prompt.contains("Far Person")); + assert!(!prompt.contains("Inactive parent")); + } +} diff --git a/crates/ghostlight-dungeon/src/kernel.rs b/crates/ghostlight-dungeon/src/kernel.rs index 76c11e6..9f407dc 100644 --- a/crates/ghostlight-dungeon/src/kernel.rs +++ b/crates/ghostlight-dungeon/src/kernel.rs @@ -634,6 +634,21 @@ fn execute( if reason.trim().is_empty() { return Err(KernelError::Invalid("presence plan has no reason".into())); } + let player_location = &campaign.actors[&campaign.player_actor_id].location_id; + if plan + .individuations + .iter() + .any(|entry| &entry.location_id != player_location) + || plan + .promotions + .iter() + .any(|entry| &entry.location_id != player_location) + { + return Err(KernelError::Invalid( + "automatic presence reconciliation is confined to the player's active location" + .into(), + )); + } let before = campaign.clone(); let mut candidate = campaign.clone(); for demotion in &plan.demotions { @@ -717,6 +732,7 @@ fn execute( summary: event_summary, actor_ids: seen.into_iter().collect(), institution_ids: vec![], + gestalt_ids: vec![], location_ids: vec![player_location], public_channels: vec![], }); @@ -806,6 +822,7 @@ fn execute( }, actor_ids: vec![proposal.actor_id.clone()], institution_ids: vec![], + gestalt_ids: vec![], location_ids: vec![actor_location], public_channels: vec![], }); @@ -828,6 +845,12 @@ fn apply_individuation( .gestalts .get(&individuation.gestalt_id) .ok_or_else(|| KernelError::Invalid("gestalt is unknown".into()))?; + crate::resolution::validate_active_gestalt_presence_location( + campaign, + &individuation.gestalt_id, + &individuation.location_id, + ) + .map_err(|error| KernelError::Invalid(error.to_string()))?; if gestalt.version != individuation.expected_gestalt_version || member.gestalt_id != individuation.gestalt_id || member.version != 0 @@ -864,6 +887,12 @@ fn apply_promotion( "materialization location is unknown".into(), )); } + crate::resolution::validate_active_gestalt_presence_location( + campaign, + &promotion.gestalt_id, + &promotion.location_id, + ) + .map_err(|error| KernelError::Invalid(error.to_string()))?; let gestalt = campaign .gestalts .get(&promotion.gestalt_id) @@ -872,6 +901,14 @@ fn apply_promotion( if gestalt.version != promotion.expected_gestalt_version { return Err(KernelError::Invalid("gestalt snapshot is stale".into())); } + let member_location = + crate::resolution::dormant_member_location(campaign, &promotion.member_id) + .map_err(|error| KernelError::Invalid(error.to_string()))?; + if member_location != promotion.location_id { + return Err(KernelError::Invalid( + "gestalt member cannot materialize outside their exact location".into(), + )); + } let member = campaign .gestalt_members .get_mut(&promotion.member_id) @@ -1269,6 +1306,7 @@ fn apply_strategic_tick_plan( summary, actor_ids: vec![], institution_ids: vec![institution.id.clone()], + gestalt_ids: vec![], location_ids: action.location_ids, public_channels: action.public_channels, }); @@ -1320,11 +1358,93 @@ fn apply_strategic_tick_plan( summary: format!("{} {}", gestalt.name, summary_parts.join("; ")), actor_ids: vec![], institution_ids: vec![], + gestalt_ids: vec![gestalt.id.clone()], location_ids: vec![gestalt.home_location_id.clone()], public_channels: action.public_channels, }); } + for action in plan.gestalt_activities { + if !seen_gestalts.insert(action.gestalt_id.clone()) { + return Err(KernelError::Invalid( + "gestalt acts twice in one strategic tick".into(), + )); + } + validate_public_channels(&action.public_channels)?; + let gestalt = campaign + .gestalts + .get(&action.gestalt_id) + .ok_or_else(|| KernelError::Invalid("strategic plan invented a gestalt".into()))?; + let profile = campaign + .agency_profiles + .get(&action.gestalt_id) + .ok_or_else(|| KernelError::Invalid("strategic gestalt lacks agency scope".into()))?; + let allowed_targets = + crate::resolution::strategic_activity_targets(campaign, &action.gestalt_id); + let unique_targets = action.target_subject_ids.iter().collect::>(); + let unique_locations = action.location_ids.iter().collect::>(); + let needs_target = !matches!( + action.activity, + crate::domain::StrategicActivityKind::Prepare + ); + if action.target_subject_ids.len() > 4 + || unique_targets.len() != action.target_subject_ids.len() + || action + .target_subject_ids + .iter() + .any(|target| !allowed_targets.contains(target)) + || (needs_target && action.target_subject_ids.is_empty()) + || action.location_ids.len() > 4 + || unique_locations.len() != action.location_ids.len() + || action + .location_ids + .iter() + .any(|location| !profile.location_ids.contains(location)) + { + return Err(KernelError::Invalid( + "strategic gestalt activity exceeds exact graph or location scope".into(), + )); + } + let target_names = action + .target_subject_ids + .iter() + .map(|target| agency_subject_name(campaign, target)) + .collect::, _>>()?; + let locations = if action.location_ids.is_empty() { + vec![gestalt.home_location_id.clone()] + } else { + action.location_ids + }; + let institution_ids = action + .target_subject_ids + .iter() + .filter(|target| campaign.institutions.contains_key(*target)) + .cloned() + .collect(); + let mut gestalt_ids = vec![action.gestalt_id.clone()]; + gestalt_ids.extend( + action + .target_subject_ids + .iter() + .filter(|target| campaign.gestalts.contains_key(*target)) + .cloned(), + ); + events.push(crate::domain::Event { + id: format!( + "strategic:{revision}:gestalt-activity:{}", + action.gestalt_id + ), + at, + kind: "gestalt_activity".into(), + summary: strategic_activity_summary(&gestalt.name, &action.activity, &target_names), + actor_ids: vec![], + institution_ids, + gestalt_ids, + location_ids: locations, + public_channels: action.public_channels, + }); + } + let mut seen_actors = BTreeSet::new(); for action in plan.actor_moves { if !seen_actors.insert(action.actor_id.clone()) { @@ -1376,6 +1496,7 @@ fn apply_strategic_tick_plan( ), actor_ids: vec![action.actor_id], institution_ids: vec![], + gestalt_ids: vec![], location_ids: vec![origin, action.destination_id], public_channels: action.public_channels, }); @@ -1417,6 +1538,7 @@ fn apply_strategic_tick_plan( ), actor_ids: vec![format!("member:{}", action.member_id)], institution_ids: vec![], + gestalt_ids: vec![action.source_gestalt_id, action.destination_gestalt_id], location_ids: vec![origin, action.destination_location_id], public_channels: action.public_channels, }); @@ -1424,6 +1546,61 @@ fn apply_strategic_tick_plan( Ok(events) } +fn strategic_activity_summary( + source_name: &str, + activity: &StrategicActivityKind, + target_names: &[String], +) -> String { + let targets = target_names.join(", "); + match (activity, target_names.is_empty()) { + (StrategicActivityKind::Prepare, true) => { + format!("{source_name} undertakes preparations.") + } + (StrategicActivityKind::Prepare, false) => { + format!("{source_name} undertakes preparations concerning {targets}.") + } + (StrategicActivityKind::Coordinate, false) => { + format!("{source_name} attempts to coordinate with {targets}.") + } + (StrategicActivityKind::Investigate, false) => { + format!("{source_name} begins investigating {targets}.") + } + (StrategicActivityKind::Recruit, false) => { + format!("{source_name} attempts recruitment involving {targets}.") + } + (StrategicActivityKind::Obstruct, false) => { + format!("{source_name} attempts to obstruct {targets}.") + } + (StrategicActivityKind::Trade, false) => { + format!("{source_name} offers a trade to {targets}.") + } + (StrategicActivityKind::Communicate, false) => { + format!("{source_name} sends a communication to {targets}.") + } + _ => unreachable!("validated strategic activity requires a target"), + } +} + +fn agency_subject_name(campaign: &Campaign, subject_id: &str) -> Result { + 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(|| KernelError::Invalid("strategic activity target vanished".into())) +} + fn rebase_member_migration( campaign: &mut Campaign, action: &crate::domain::StrategicMemberMigration, @@ -1506,6 +1683,7 @@ fn deterministic_strategic_tick( summary, actor_ids: vec![], institution_ids: vec![institution.id.clone()], + gestalt_ids: vec![], location_ids: vec![], public_channels: vec![format!("institution:{}", institution.id)], }); @@ -1524,6 +1702,7 @@ fn deterministic_strategic_tick( summary, actor_ids: vec![], institution_ids: vec![], + gestalt_ids: vec![gestalt.id.clone()], location_ids: vec![gestalt.home_location_id.clone()], public_channels: vec![format!("gestalt:{}", gestalt.id)], }); @@ -2075,6 +2254,77 @@ mod tests { ); } + #[test] + fn gestalt_activity_records_an_attributed_attempt_without_claiming_an_outcome() { + let mut value = hierarchical_refugee_campaign(); + let before = value.clone(); + let events = apply_strategic_tick_plan( + &mut value, + StrategicTickPlan { + gestalt_activities: vec![StrategicGestaltActivity { + gestalt_id: "refugees-east".into(), + activity: StrategicActivityKind::Coordinate, + target_subject_ids: vec!["dock-neighbors".into()], + location_ids: vec!["camp".into()], + public_channels: vec![], + }], + ..Default::default() + }, + ) + .unwrap(); + assert_eq!(value, before); + assert_eq!(events.len(), 1); + assert_eq!(events[0].kind, "gestalt_activity"); + assert_eq!( + events[0].summary, + "Eastern transit refugees attempts to coordinate with South dock neighbors." + ); + assert_eq!( + events[0].gestalt_ids, + vec!["refugees-east", "dock-neighbors"] + ); + assert!(events[0].actor_ids.is_empty()); + assert!(events[0].institution_ids.is_empty()); + } + + #[test] + fn gestalt_activity_rejects_a_nonadjacent_target_without_mutation() { + let mut value = hierarchical_refugee_campaign(); + value.gestalts.insert( + "distant-crowd".into(), + GestaltPersonaState { + schema: "ghostlight.gestalt_persona_state.v1".into(), + id: "distant-crowd".into(), + name: "Distant crowd".into(), + version: 0, + home_location_id: "docks".into(), + shared_capabilities: BTreeSet::new(), + shared_knowledge: BTreeSet::new(), + resources: BTreeSet::new(), + goals: vec![], + pressures: vec![], + }, + ); + crate::resolution::ensure_agency_profiles(&mut value); + let before = value.clone(); + let error = apply_strategic_tick_plan( + &mut value, + StrategicTickPlan { + gestalt_activities: vec![StrategicGestaltActivity { + gestalt_id: "refugees-east".into(), + activity: StrategicActivityKind::Communicate, + target_subject_ids: vec!["distant-crowd".into()], + location_ids: vec!["camp".into()], + public_channels: vec![], + }], + ..Default::default() + }, + ) + .unwrap_err(); + assert!(error.to_string().contains("exact graph or location scope")); + assert_eq!(value, before); + } + #[tokio::test] async fn stale_command_cannot_mutate_campaign() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/ghostlight-dungeon/src/persona.rs b/crates/ghostlight-dungeon/src/persona.rs index b3cdcda..93b6035 100644 --- a/crates/ghostlight-dungeon/src/persona.rs +++ b/crates/ghostlight-dungeon/src/persona.rs @@ -65,6 +65,7 @@ pub struct CellConstituentSlice { pub information_channels: BTreeSet, pub permitted_state_references: BTreeSet, pub reachable_destination_ids: BTreeSet, + pub activity_target_ids: BTreeSet, pub goals: Vec, pub pressures: Vec, } @@ -146,6 +147,7 @@ const CELL_APPRAISAL_OUTPUT_CONTRACT: &str = r#"{ "effect":{"oneOf":[ {"type":"object","required":["type","institution_id","posture","location_ids"],"properties":{"type":{"const":"institution"},"institution_id":{"type":"string"},"posture":{"type":"string"},"location_ids":{"type":"array","items":{"type":"string"}}}}, {"type":"object","required":["type","gestalt_id","pressure_additions","pressure_resolutions"],"properties":{"type":{"const":"gestalt"},"gestalt_id":{"type":"string"},"pressure_additions":{"type":"array","maxItems":4,"items":{"type":"string"}},"pressure_resolutions":{"type":"array","maxItems":4,"items":{"type":"string"}}}}, + {"type":"object","required":["type","gestalt_id","activity","target_subject_ids","location_ids"],"properties":{"type":{"const":"gestalt_activity"},"gestalt_id":{"type":"string"},"activity":{"enum":["prepare","coordinate","investigate","recruit","obstruct","trade","communicate"]},"target_subject_ids":{"type":"array","maxItems":4,"items":{"type":"string"}},"location_ids":{"type":"array","maxItems":4,"items":{"type":"string"}}}}, {"type":"object","required":["type","actor_id","destination_id"],"properties":{"type":{"const":"actor_move"},"actor_id":{"type":"string"},"destination_id":{"type":"string"}}}, {"type":"object","required":["type","destination_gestalt_id"],"properties":{"type":{"const":"member_migration"},"destination_gestalt_id":{"type":"string"}}} ]} @@ -336,6 +338,7 @@ fn cell_projector_context(slice: &PermittedCellSlice) -> serde_json::Value { "resources": subject.resources, "information_channels": subject.information_channels, "reachable_destination_ids": subject.reachable_destination_ids, + "activity_target_ids": subject.activity_target_ids, "goals": subject.goals, "pressures": subject.pressures, })).collect::>(), @@ -380,6 +383,7 @@ fn cell_interpreter_context(slice: &PermittedCellSlice) -> serde_json::Value { "allowed_public_channels": subject.information_channels, "permitted_state_references": subject.permitted_state_references, "reachable_destination_ids": subject.reachable_destination_ids, + "activity_target_ids": subject.activity_target_ids, "current_pressures": subject.pressures, })).collect::>(), "member_permissions": slice.member_exceptions.iter().map(|member| serde_json::json!({ @@ -399,7 +403,7 @@ fn allowed_effect_type(kind: &crate::domain::AgencySubjectKind) -> &'static str match kind { crate::domain::AgencySubjectKind::Actor => "actor_move", crate::domain::AgencySubjectKind::Institution => "institution", - crate::domain::AgencySubjectKind::Gestalt => "gestalt", + crate::domain::AgencySubjectKind::Gestalt => "gestalt_pressure_or_gestalt_activity", } } @@ -496,7 +500,7 @@ impl CellProjectionEngine { constrain_cell_proposal_schema(&mut schema, &slice)?; let interpreter_context = serde_json::to_string(&cell_interpreter_context(&slice))?; let permission_guidance = format!( - "Emit at most {} exact constituent- or named-member-attributed attempts. Priority is an urgency score from 0 to 100 where higher numbers resolve first; never use ordinal list rank where 1 means first. Copy each subject's allowed_effect_type: institution -> institution, gestalt -> gestalt, actor -> actor_move, named member -> member_migration. Institution posture must be a specific new commitment or withholding, never the current posture or a generic label. Gestalt pressure_resolutions must copy exact current_pressures that the attempted action resolves; pressure_additions are only new unresolved constraints, threats, obligations, or conditions, never completed actions. At least one and at most four total pressure changes are required. Use only that subject's permitted_state_references and allowed_public_channels; facet labels are not public channels. A named member uses one supplied migration destination; a population or arena cannot migrate a person. The runtime binds cell identity, revisions, membership, and effective state. The cell id is not an actor id. Use an empty actions array plus a concrete inaction_reason when nobody acts.", + "Emit at most {} exact constituent- or named-member-attributed attempts. Priority is an urgency score from 0 to 100 where higher numbers resolve first; never use ordinal list rank where 1 means first. Copy each subject's allowed_effect_type: institution -> institution, gestalt -> either gestalt pressure transition or gestalt_activity, actor -> actor_move, named member -> member_migration. Use gestalt_activity for a concrete preparation, coordination, investigation, recruitment, obstruction, trade, or communication attempt that does not itself change pressure; target_subject_ids must come from that gestalt's activity_target_ids and location_ids from its exact location_ids. An activity records only the attempt, never success or a target's response. Institution posture must be a specific new commitment or withholding, never the current posture or a generic label. Gestalt pressure_resolutions must copy exact current_pressures that the attempted action resolves; pressure_additions are only new unresolved constraints, threats, obligations, or conditions, never completed actions. A pressure transition requires one to four total changes. Use only that subject's permitted_state_references and allowed_public_channels; facet labels are not public channels. A named member uses one supplied migration destination; a population or arena cannot migrate a person. The runtime binds cell identity, revisions, membership, and effective state. The cell id is not an actor id. Use an empty actions array plus a concrete inaction_reason when nobody acts.", slice.max_actions ); let mut request = ModelStageRequest { @@ -561,7 +565,7 @@ impl CellProjectionEngine { model: self.interpreter_model.clone(), snapshot_binding: verifier_binding, lived_stream: format!( - "You are the private semantic verifier between an Interpreter and the world kernel. Decide whether every candidate typed effect faithfully represents the exact attributed subject's own attempted consequence in the Persona turn. Structural permissions were already checked. A member_migration means that named member personally chooses to travel to the destination; giving away a berth, sending somebody else, waiting, or merely considering travel does not entail it. An institution posture must express its stated commitment or withholding. A gestalt pressure resolution must be causally supported by its stated attempt, and an added pressure must be a resulting unresolved condition rather than completed-action prose. Reject omissions, reversals, subject swaps, wishful outcomes, and effects that the Persona did not choose. Be concise. Return exactly one JSON object with this shape and no other fields: {{\"supported\":true or false,\"rejected_action_indices\":[zero-based integer indices],\"rationale\":\"one concise reason\"}}. When supported is true, rejected_action_indices must be empty. When false, list every rejected action index.\n\nCONTEXT:\n{}", + "You are the private semantic verifier between an Interpreter and the world kernel. Decide whether every candidate typed effect faithfully represents the exact attributed subject's own attempted consequence in the Persona turn. Structural permissions were already checked. A member_migration means that named member personally chooses to travel to the destination; giving away a berth, sending somebody else, waiting, or merely considering travel does not entail it. An institution posture must express its stated commitment or withholding. A gestalt pressure resolution must be causally supported by its stated attempt, and an added pressure must be a resulting unresolved condition rather than completed-action prose. A gestalt_activity records only the exact attempt—never successful preparation, coordination, discovery, recruitment, obstruction, exchange, delivery, persuasion, or target response. Reject omissions, reversals, subject swaps, wishful outcomes, and effects that the Persona did not choose. Be concise. Return exactly one JSON object with this shape and no other fields: {{\"supported\":true or false,\"rejected_action_indices\":[zero-based integer indices],\"rationale\":\"one concise reason\"}}. When supported is true, rejected_action_indices must be empty. When false, list every rejected action index.\n\nCONTEXT:\n{}", serde_json::to_string(&verifier_context)? ), output_schema: Some(serde_json::to_value(schema_for!( @@ -876,6 +880,40 @@ fn validate_constituent_effect( ) })?; } + crate::domain::StrategicCellEffect::GestaltActivity { + gestalt_id, + activity, + target_subject_ids, + location_ids, + } => { + let unique_targets = target_subject_ids.iter().collect::>(); + let unique_locations = location_ids.iter().collect::>(); + let needs_target = !matches!(activity, crate::domain::StrategicActivityKind::Prepare); + if subject.subject_kind != crate::domain::AgencySubjectKind::Gestalt + || gestalt_id != &subject.subject_id + || target_subject_ids.len() > 4 + || unique_targets.len() != target_subject_ids.len() + || target_subject_ids + .iter() + .any(|target| !subject.activity_target_ids.contains(target)) + || (needs_target && target_subject_ids.is_empty()) + || location_ids.len() > 4 + || unique_locations.len() != location_ids.len() + || location_ids + .iter() + .any(|location| !subject.location_ids.contains(location)) + { + return Err(anyhow!( + "gestalt {} proposed {:?} toward {:?} at {:?}; exact allowed targets are {:?} and locations are {:?}", + subject.subject_id, + activity, + target_subject_ids, + location_ids, + subject.activity_target_ids, + subject.location_ids + )); + } + } crate::domain::StrategicCellEffect::ActorMove { actor_id, destination_id, @@ -1090,6 +1128,7 @@ mod tests { information_channels: BTreeSet::from(["public bulletin".into()]), permitted_state_references: BTreeSet::from(["institution:faction-06".into()]), reachable_destination_ids: BTreeSet::new(), + activity_target_ids: BTreeSet::new(), goals: vec!["publish a position".into()], pressures: vec!["the vote is near".into()], }], @@ -1316,6 +1355,52 @@ mod tests { ); } + #[test] + fn gestalt_activity_requires_an_exact_permitted_target_and_location() { + let mut slice = fixture_cell_slice(); + let subject = &mut slice.constituents[0]; + subject.subject_id = "refugees".into(); + subject.subject_kind = AgencySubjectKind::Gestalt; + subject.permitted_state_references = BTreeSet::from(["gestalt:refugees".into()]); + subject.activity_target_ids = BTreeSet::from(["dockers".into()]); + let valid = StrategicCellEffect::GestaltActivity { + gestalt_id: "refugees".into(), + activity: crate::domain::StrategicActivityKind::Coordinate, + target_subject_ids: vec!["dockers".into()], + location_ids: vec!["forum".into()], + }; + validate_constituent_effect(subject, &valid).unwrap(); + + let invented_target = StrategicCellEffect::GestaltActivity { + gestalt_id: "refugees".into(), + activity: crate::domain::StrategicActivityKind::Coordinate, + target_subject_ids: vec!["unseen-ministry".into()], + location_ids: vec!["forum".into()], + }; + assert!( + validate_constituent_effect(subject, &invented_target) + .unwrap_err() + .to_string() + .contains("exact allowed targets") + ); + + let targetless_obstruction = StrategicCellEffect::GestaltActivity { + gestalt_id: "refugees".into(), + activity: crate::domain::StrategicActivityKind::Obstruct, + target_subject_ids: vec![], + location_ids: vec!["forum".into()], + }; + assert!(validate_constituent_effect(subject, &targetless_obstruction).is_err()); + + let internal_preparation = StrategicCellEffect::GestaltActivity { + gestalt_id: "refugees".into(), + activity: crate::domain::StrategicActivityKind::Prepare, + target_subject_ids: vec![], + location_ids: vec!["forum".into()], + }; + validate_constituent_effect(subject, &internal_preparation).unwrap(); + } + #[test] fn repeated_institution_posture_reports_the_exact_missing_change() { let slice = fixture_cell_slice(); diff --git a/crates/ghostlight-dungeon/src/resolution.rs b/crates/ghostlight-dungeon/src/resolution.rs index 47a20ca..a1cb0dc 100644 --- a/crates/ghostlight-dungeon/src/resolution.rs +++ b/crates/ghostlight-dungeon/src/resolution.rs @@ -1238,6 +1238,7 @@ fn subject_salience(campaign: &Campaign, profile: &AgencyProfile) -> f32 { let event = campaign.events.iter().rev().take(16).any(|event| { event.actor_ids.contains(&profile.subject_id) || event.institution_ids.contains(&profile.subject_id) + || event.gestalt_ids.contains(&profile.subject_id) }) as u8 as f32; let conflict = campaign.agency_relations.values().any(|relation| { relation.active @@ -1643,6 +1644,18 @@ pub fn validate_and_resolve_wave( pressure_resolutions, public_channels: proposal.public_channels, }), + StrategicCellEffect::GestaltActivity { + gestalt_id, + activity, + target_subject_ids, + location_ids, + } => plan.gestalt_activities.push(StrategicGestaltActivity { + gestalt_id, + activity, + target_subject_ids, + location_ids, + public_channels: proposal.public_channels, + }), StrategicCellEffect::ActorMove { actor_id, destination_id, @@ -1674,6 +1687,7 @@ pub fn validate_and_resolve_wave( } if plan.institution_actions.len() + plan.gestalt_actions.len() + + plan.gestalt_activities.len() + plan.actor_moves.len() + plan.member_migrations.len() >= consequence_limit @@ -1758,6 +1772,35 @@ fn validate_cell_proposal( return Err(anyhow!("gestalt proposal exceeds constituent state")); } } + StrategicCellEffect::GestaltActivity { + gestalt_id, + activity, + target_subject_ids, + location_ids, + } => { + let allowed_targets = strategic_activity_targets(campaign, gestalt_id); + let unique_targets = target_subject_ids.iter().collect::>(); + let unique_locations = location_ids.iter().collect::>(); + let needs_target = !matches!(activity, StrategicActivityKind::Prepare); + if gestalt_id != &proposal.subject_id + || !campaign.gestalts.contains_key(gestalt_id) + || target_subject_ids.len() > 4 + || unique_targets.len() != target_subject_ids.len() + || target_subject_ids + .iter() + .any(|target| !allowed_targets.contains(target)) + || (needs_target && target_subject_ids.is_empty()) + || location_ids.len() > 4 + || unique_locations.len() != location_ids.len() + || location_ids + .iter() + .any(|location| !profile.location_ids.contains(location)) + { + return Err(anyhow!( + "gestalt activity exceeds exact subject, graph, or location scope" + )); + } + } StrategicCellEffect::ActorMove { actor_id, destination_id, @@ -2153,12 +2196,75 @@ pub fn subject_state_references(campaign: &Campaign, subject_id: &str) -> Result Ok(references) } +pub fn strategic_activity_targets(campaign: &Campaign, subject_id: &str) -> BTreeSet { + campaign + .agency_relations + .values() + .filter(|relation| relation.active) + .filter_map(|relation| { + if relation.from_subject_id == subject_id { + Some(relation.to_subject_id.clone()) + } else if relation.to_subject_id == subject_id { + Some(relation.from_subject_id.clone()) + } else { + None + } + }) + .filter(|target| target != subject_id && campaign.agency_profiles.contains_key(target)) + .collect() +} + +pub fn validate_active_gestalt_presence_location( + campaign: &Campaign, + gestalt_id: &str, + location_id: &str, +) -> Result<()> { + let profile = campaign + .agency_profiles + .get(gestalt_id) + .filter(|profile| { + profile.subject_kind == AgencySubjectKind::Gestalt + && profile.active_leaf + && profile.simulation_eligible + }) + .ok_or_else(|| anyhow!("gestalt presence requires an active population leaf"))?; + if !profile.location_ids.contains(location_id) { + return Err(anyhow!( + "gestalt presence location is outside the population's exact scope" + )); + } + Ok(()) +} + +pub fn dormant_member_location(campaign: &Campaign, member_id: &str) -> Result { + let member = campaign + .gestalt_members + .get(member_id) + .filter(|member| member.materialized_actor_id.is_none()) + .ok_or_else(|| anyhow!("gestalt member is not dormant"))?; + let location_id = member + .last_location_id + .clone() + .or_else(|| { + campaign + .gestalts + .get(&member.gestalt_id) + .map(|gestalt| gestalt.home_location_id.clone()) + }) + .ok_or_else(|| anyhow!("gestalt member has no population location"))?; + validate_active_gestalt_presence_location(campaign, &member.gestalt_id, &location_id)?; + Ok(location_id) +} + fn proposal_target_key(proposal: &CellActionProposal) -> String { match &proposal.effect { StrategicCellEffect::Institution { institution_id, .. } => { format!("institution:{institution_id}") } StrategicCellEffect::Gestalt { gestalt_id, .. } => format!("gestalt:{gestalt_id}"), + StrategicCellEffect::GestaltActivity { gestalt_id, .. } => { + format!("gestalt:{gestalt_id}") + } StrategicCellEffect::ActorMove { actor_id, .. } => format!("actor:{actor_id}"), StrategicCellEffect::MemberMigration { .. } => proposal.subject_id.clone(), } @@ -2842,6 +2948,73 @@ pub(crate) mod tests { .state_references .push("knowledge:private dock code".into()); assert!(validate_and_resolve_wave(&value, &make_wave(borrowed_secret)).is_err()); + + let exact_rival_activity = CellActionProposal { + subject_id: "refugees".into(), + intent: "challenge the dockers' exclusion plan".into(), + intended_effect: "attempt to obstruct the dockers without speaking for them".into(), + priority: 80, + state_references: vec!["subject:refugees".into()], + public_channels: vec!["camp-bulletin".into()], + effect: StrategicCellEffect::GestaltActivity { + gestalt_id: "refugees".into(), + activity: StrategicActivityKind::Obstruct, + target_subject_ids: vec!["dockers".into()], + location_ids: vec!["center".into()], + }, + }; + let activity_plan = + validate_and_resolve_wave(&value, &make_wave(exact_rival_activity.clone())).unwrap(); + assert_eq!(activity_plan.gestalt_activities.len(), 1); + assert!(activity_plan.gestalt_actions.is_empty()); + + let lower_priority_pressure = CellActionProposal { + subject_id: "refugees".into(), + intent: "register the unresolved exclusion".into(), + intended_effect: "add a pressure marker".into(), + priority: 20, + state_references: vec!["subject:refugees".into()], + public_channels: vec![], + effect: StrategicCellEffect::Gestalt { + gestalt_id: "refugees".into(), + pressure_additions: vec!["the dockers' exclusion remains unresolved".into()], + pressure_resolutions: vec![], + }, + }; + let same_subject_wave = ResolutionWaveCommit { + schema: "ghostlight.resolution_wave_commit.v1".into(), + world_revision: value.revision, + resolution_epoch: value.resolution_policy.resolution_epoch, + plan_receipt: plan_receipt(&value, &cover), + appraisals: vec![CellAppraisal { + schema: "ghostlight.cell_appraisal.v1".into(), + cell_id: cover.cells[0].id.clone(), + world_revision: value.revision, + resolution_epoch: value.resolution_policy.resolution_epoch, + considered_subject_ids: cover.cells[0].subject_ids.clone(), + actions: vec![exact_rival_activity.clone(), lower_priority_pressure], + inaction_reason: None, + }], + cover: cover.clone(), + model_receipt_hashes: vec![], + }; + let same_subject_plan = validate_and_resolve_wave(&value, &same_subject_wave).unwrap(); + 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()); + + let mut invented_target = exact_rival_activity; + let StrategicCellEffect::GestaltActivity { + target_subject_ids, .. + } = &mut invented_target.effect + else { + unreachable!() + }; + *target_subject_ids = vec!["player".into()]; + assert!(validate_and_resolve_wave(&value, &make_wave(invented_target)).is_err()); } #[test] @@ -2982,6 +3155,45 @@ pub(crate) mod tests { value.gestalt_lineages["villagers"].residual_child_id, "other" ); + + let nested = GestaltFissionPreview { + schema: "ghostlight.gestalt_fission_preview.v1".into(), + campaign_id: value.id, + expected_world_revision: value.revision, + parent_gestalt_id: "other".into(), + partition_axis: AgencyAxis::EconomyRole, + children: vec![ + child("other-smiths", "Smiths among the other villagers"), + child("other-unknown", "Other unclassified villagers"), + ], + child_partition_values: BTreeMap::from([ + ("other-smiths".into(), "smith".into()), + ("other-unknown".into(), "other/unknown".into()), + ]), + residual_child_id: "other-unknown".into(), + member_child_assignments: BTreeMap::from([("john".into(), "other-smiths".into())]), + evidence_receipt_ids: vec![], + gaps: vec![], + canon_candidates: vec![], + requires_approval: true, + }; + apply_fission(&mut value, &nested).unwrap(); + assert!(!value.agency_profiles["other"].active_leaf); + assert!(value.agency_profiles["other-smiths"].active_leaf); + assert_eq!(value.gestalt_members["john"].gestalt_id, "other-smiths"); + assert_eq!(value.gestalt_members["john"].version, 5); + assert_eq!( + value.gestalt_members["john"].memories, + vec!["met the traveler"] + ); + assert!( + effective_member_capabilities(&value, "john") + .unwrap() + .contains("smith") + ); + validate_active_gestalt_presence_location(&value, "other-smiths", "center").unwrap(); + assert!(validate_active_gestalt_presence_location(&value, "other", "center").is_err()); + assert!(validate_active_gestalt_presence_location(&value, "villagers", "center").is_err()); } #[test] diff --git a/crates/ghostlight-dungeon/src/scheduler.rs b/crates/ghostlight-dungeon/src/scheduler.rs index 4e103d4..b63821a 100644 --- a/crates/ghostlight-dungeon/src/scheduler.rs +++ b/crates/ghostlight-dungeon/src/scheduler.rs @@ -325,6 +325,7 @@ fn resolution_demand_context(campaign: &Campaign) -> (Vec, serde_json::V "summary":event.summary, "actor_ids":event.actor_ids, "institution_ids":event.institution_ids, + "gestalt_ids":event.gestalt_ids, "location_ids":event.location_ids, "public_channels":event.public_channels, }) @@ -335,7 +336,13 @@ fn resolution_demand_context(campaign: &Campaign) -> (Vec, serde_json::V .iter() .rev() .take(12) - .flat_map(|event| event.actor_ids.iter().chain(event.institution_ids.iter())) + .flat_map(|event| { + event + .actor_ids + .iter() + .chain(event.institution_ids.iter()) + .chain(event.gestalt_ids.iter()) + }) .filter(|id| campaign.agency_profiles.contains_key(*id)) .cloned() .collect::>(); @@ -453,6 +460,7 @@ fn cell_perceived_events( .filter(|subject| { event.actor_ids.contains(&subject.subject_id) || event.institution_ids.contains(&subject.subject_id) + || event.gestalt_ids.contains(&subject.subject_id) || !event .location_ids .iter() @@ -660,6 +668,7 @@ fn constituent_slice(campaign: &Campaign, id: &str) -> Result