Preserve member agency across gestalt migration
This commit is contained in:
parent
fc16476d11
commit
902a703c36
6 changed files with 1766 additions and 60 deletions
|
|
@ -0,0 +1,650 @@
|
|||
#[cfg(not(windows))]
|
||||
fn main() -> anyhow::Result<()> {
|
||||
anyhow::bail!("the live gestalt dynamics smoke uses Starfire's DPAPI credential")
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
use chrono::Utc;
|
||||
use ghostlight_dungeon::{
|
||||
domain::{SimulationCellMode, TickSource, WorldCommand},
|
||||
kernel::{CommandResult, WorldKernel},
|
||||
model::{DeepSeekPort, ModelPort},
|
||||
persistence::CampaignStore,
|
||||
resolution::{
|
||||
effective_member_capabilities, effective_member_knowledge, validate_and_resolve_wave,
|
||||
},
|
||||
scheduler::propose_resolution_wave,
|
||||
turn::SnapshotPermit,
|
||||
};
|
||||
use std::{path::PathBuf, sync::Arc, time::Instant};
|
||||
|
||||
let secret = std::env::var_os("GHOSTLIGHT_DEEPSEEK_BLOB")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from(r"F:\GameCult\GhostlightDungeon\secrets\deepseek.dpapi"));
|
||||
let scenario_id = std::env::var("GHOSTLIGHT_LIVE_FIRE_SCENARIO")
|
||||
.unwrap_or_else(|_| "gestalt-dynamics-refugee-return".into());
|
||||
let root = std::env::var_os("GHOSTLIGHT_LIVE_FIRE_RESULT_ROOT")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| {
|
||||
PathBuf::from(r"F:\GameCult\GhostlightDungeon\acceptance").join(format!(
|
||||
"gestalt-dynamics-{}-{}",
|
||||
Utc::now().format("%Y%m%d-%H%M%S"),
|
||||
uuid::Uuid::new_v4()
|
||||
))
|
||||
});
|
||||
std::fs::create_dir_all(&root)?;
|
||||
let campaign = dynamics_campaign();
|
||||
let player_before = campaign.actors[&campaign.player_actor_id].clone();
|
||||
let member_before = campaign.gestalt_members["mira-venn"].clone();
|
||||
let capabilities_before = effective_member_capabilities(&campaign, "mira-venn")?;
|
||||
let knowledge_before = effective_member_knowledge(&campaign, "mira-venn")?;
|
||||
let store = CampaignStore::open(root.join("campaign.cc"))?;
|
||||
store.create_campaign(&campaign, &[], &[])?;
|
||||
let model: Arc<dyn ModelPort> = Arc::new(DeepSeekPort::from_machine_dpapi(secret)?);
|
||||
let started = Instant::now();
|
||||
let output = propose_resolution_wave(
|
||||
model,
|
||||
Arc::new(SnapshotPermit::new_resolution(
|
||||
store.clone(),
|
||||
campaign.id,
|
||||
campaign.revision,
|
||||
campaign.resolution_policy.resolution_epoch,
|
||||
)),
|
||||
&campaign,
|
||||
)
|
||||
.await?;
|
||||
let preflight = serde_json::json!({
|
||||
"schema":"ghostlight.gestalt_dynamics_preflight.v1",
|
||||
"scenario_id":scenario_id,
|
||||
"elapsed_seconds":started.elapsed().as_secs_f64(),
|
||||
"cover":&output.wave.cover,
|
||||
"appraisals":&output.wave.appraisals,
|
||||
"model_stage_receipts":output.stages.iter().map(|stage|&stage.receipt).collect::<Vec<_>>()
|
||||
});
|
||||
std::fs::write(
|
||||
root.join("preflight.json"),
|
||||
serde_json::to_vec_pretty(&preflight)?,
|
||||
)?;
|
||||
|
||||
if output.wave.cover.cells.len() != 1
|
||||
|| output.wave.cover.cells[0].mode != SimulationCellMode::Arena
|
||||
{
|
||||
anyhow::bail!("budget-one whole-setting cover was not one arena")
|
||||
}
|
||||
let root_cell = &output.wave.cover.cells[0];
|
||||
if !root_cell.subject_ids.contains("refugees-east")
|
||||
|| !root_cell.subject_ids.contains("harbor-neighbors")
|
||||
|| root_cell.subject_ids.len() != 24
|
||||
{
|
||||
anyhow::bail!("whole-setting arena lost a rival population or canonical subject")
|
||||
}
|
||||
let migration_proposal = output
|
||||
.wave
|
||||
.appraisals
|
||||
.iter()
|
||||
.flat_map(|appraisal| &appraisal.actions)
|
||||
.find(|proposal| {
|
||||
proposal.subject_id == "member:mira-venn"
|
||||
&& matches!(
|
||||
&proposal.effect,
|
||||
ghostlight_dungeon::domain::StrategicCellEffect::MemberMigration {
|
||||
member_id,
|
||||
source_gestalt_id,
|
||||
destination_gestalt_id,
|
||||
destination_location_id,
|
||||
} if member_id == "mira-venn"
|
||||
&& source_gestalt_id == "refugees-east"
|
||||
&& destination_gestalt_id == "harbor-neighbors"
|
||||
&& destination_location_id == "south-harbor"
|
||||
)
|
||||
})
|
||||
.cloned()
|
||||
.ok_or_else(|| {
|
||||
anyhow::anyhow!(
|
||||
"whole-setting arena did not preserve Mira's agency as an attributed migration proposal"
|
||||
)
|
||||
})?;
|
||||
if output.wave.appraisals.iter().any(|appraisal| {
|
||||
appraisal
|
||||
.actions
|
||||
.iter()
|
||||
.any(|proposal| proposal.subject_id == root_cell.id)
|
||||
}) {
|
||||
anyhow::bail!("arena emitted an action as if it were a person")
|
||||
}
|
||||
let plan = validate_and_resolve_wave(&campaign, &output.wave)?;
|
||||
if plan.member_migrations.len() != 1 {
|
||||
anyhow::bail!("validated wave did not preserve exactly one member migration")
|
||||
}
|
||||
let background_action_count =
|
||||
plan.institution_actions.len() + plan.gestalt_actions.len() + plan.actor_moves.len();
|
||||
for stage in &output.stages {
|
||||
store.insert(
|
||||
"persona_stage_receipt.v1",
|
||||
"ghostlight.persona_stage_receipt.v1",
|
||||
stage.receipt.storage_key(),
|
||||
&stage.receipt,
|
||||
)?;
|
||||
}
|
||||
let kernel = WorldKernel::start(store.clone());
|
||||
let committed = kernel
|
||||
.command(WorldCommand::AdvanceStrategicTick {
|
||||
expected_revision: campaign.revision,
|
||||
source: TickSource::Scheduler,
|
||||
plan: None,
|
||||
model_receipt_hash: Some(output.aggregate_receipt_hash.clone()),
|
||||
resolution_wave: Some(output.wave.clone()),
|
||||
})
|
||||
.await?;
|
||||
let CommandResult::Committed {
|
||||
campaign: advanced, ..
|
||||
} = &committed
|
||||
else {
|
||||
anyhow::bail!("gestalt dynamics wave did not commit")
|
||||
};
|
||||
let member_after = &advanced.gestalt_members["mira-venn"];
|
||||
if member_after.gestalt_id != "harbor-neighbors"
|
||||
|| member_after.last_location_id.as_deref() != Some("south-harbor")
|
||||
|| member_after.name != member_before.name
|
||||
|| member_after.relationships != member_before.relationships
|
||||
|| member_after.memories != member_before.memories
|
||||
|| member_after.equipment != member_before.equipment
|
||||
|| member_after.conditions != member_before.conditions
|
||||
|| member_after.obligations != member_before.obligations
|
||||
|| effective_member_capabilities(advanced, "mira-venn")? != capabilities_before
|
||||
|| effective_member_knowledge(advanced, "mira-venn")? != knowledge_before
|
||||
{
|
||||
anyhow::bail!("migration changed Mira's identity or effective personal state")
|
||||
}
|
||||
if advanced.actors[&advanced.player_actor_id] != player_before {
|
||||
anyhow::bail!("background simulation puppeted the player")
|
||||
}
|
||||
|
||||
let materialized = kernel
|
||||
.command(WorldCommand::MaterializeGestaltMember {
|
||||
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.version,
|
||||
location_id: "south-harbor".into(),
|
||||
})
|
||||
.await?;
|
||||
let CommandResult::Committed {
|
||||
campaign: returned, ..
|
||||
} = &materialized
|
||||
else {
|
||||
anyhow::bail!("Mira did not rematerialize at her destination")
|
||||
};
|
||||
let actor = &returned.actors["member:mira-venn"];
|
||||
if actor.location_id != returned.actors[&returned.player_actor_id].location_id
|
||||
|| actor.name != member_before.name
|
||||
|| actor.relationships != member_before.relationships
|
||||
|| actor.memories != member_before.memories
|
||||
|| actor.capabilities != capabilities_before
|
||||
|| actor.knowledge != knowledge_before
|
||||
{
|
||||
anyhow::bail!("return encounter did not rematerialize the same person")
|
||||
}
|
||||
let event_kinds = returned
|
||||
.events
|
||||
.iter()
|
||||
.map(|event| event.kind.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let stage_receipts = output
|
||||
.stages
|
||||
.iter()
|
||||
.map(|stage| &stage.receipt)
|
||||
.collect::<Vec<_>>();
|
||||
let result = serde_json::json!({
|
||||
"schema":"ghostlight.gestalt_dynamics_smoke.v1",
|
||||
"scenario_id":scenario_id,
|
||||
"elapsed_seconds":started.elapsed().as_secs_f64(),
|
||||
"subject_count":root_cell.subject_ids.len(),
|
||||
"configured_budget":campaign.resolution_policy.active_cell_budget,
|
||||
"effective_budget":output.wave.cover.effective_budget,
|
||||
"cell_mode":root_cell.mode,
|
||||
"rivals_share_arena":true,
|
||||
"migration_proposal":migration_proposal,
|
||||
"background_action_count":background_action_count,
|
||||
"plan":plan,
|
||||
"commit":committed,
|
||||
"materialization":materialized,
|
||||
"identity_preserved":true,
|
||||
"effective_state_preserved":true,
|
||||
"player_unchanged":true,
|
||||
"return_encounter_same_person":true,
|
||||
"event_kinds":event_kinds,
|
||||
"model_stage_receipts":stage_receipts,
|
||||
"store":root.join("campaign.cc"),
|
||||
"preflight_path":root.join("preflight.json"),
|
||||
"result_path":root.join("result.json")
|
||||
});
|
||||
std::fs::write(
|
||||
root.join("result.json"),
|
||||
serde_json::to_vec_pretty(&result)?,
|
||||
)?;
|
||||
println!("{}", serde_json::to_string_pretty(&result)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn dynamics_campaign() -> ghostlight_dungeon::domain::Campaign {
|
||||
use chrono::{Duration, Utc};
|
||||
use ghostlight_dungeon::domain::*;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
let now = Utc::now();
|
||||
let locations = BTreeMap::from([
|
||||
(
|
||||
"south-harbor".into(),
|
||||
Location {
|
||||
id: "south-harbor".into(),
|
||||
name: "South Harbor".into(),
|
||||
container_id: None,
|
||||
routes: BTreeMap::new(),
|
||||
persistent_features: vec!["ferry steps", "weathered net lofts"]
|
||||
.into_iter()
|
||||
.map(str::to_owned)
|
||||
.collect(),
|
||||
},
|
||||
),
|
||||
(
|
||||
"transit-camp".into(),
|
||||
Location {
|
||||
id: "transit-camp".into(),
|
||||
name: "Eastern Transit Camp".into(),
|
||||
container_id: None,
|
||||
routes: BTreeMap::from([(
|
||||
"resettlement-ferry".into(),
|
||||
Route {
|
||||
destination_id: "south-harbor".into(),
|
||||
distance: "across the protected bay".into(),
|
||||
travel_minutes: 90,
|
||||
},
|
||||
)]),
|
||||
persistent_features: vec!["departure board", "storm-damaged shelter rows"]
|
||||
.into_iter()
|
||||
.map(str::to_owned)
|
||||
.collect(),
|
||||
},
|
||||
),
|
||||
]);
|
||||
let player = ActorState {
|
||||
id: "player".into(),
|
||||
name: "The gate runner".into(),
|
||||
location_id: "south-harbor".into(),
|
||||
capabilities: BTreeSet::from(["open emergency access routes".into()]),
|
||||
knowledge: BTreeSet::from(["public harbor bulletin".into()]),
|
||||
equipment: BTreeSet::new(),
|
||||
conditions: BTreeSet::new(),
|
||||
obligations: BTreeSet::new(),
|
||||
relationships: BTreeMap::from([(
|
||||
"member:mira-venn".into(),
|
||||
"helped her family escape the eastern fire".into(),
|
||||
)]),
|
||||
goals: vec!["help rebuild the harbor without commanding its people".into()],
|
||||
memories: vec!["Mira disappeared into the evacuation crowd weeks ago.".into()],
|
||||
};
|
||||
let institutions = (0..16)
|
||||
.map(|index| {
|
||||
let id = match index {
|
||||
0 => "port-authority".into(),
|
||||
1 => "relief-union".into(),
|
||||
_ => format!("regional-power-{index:02}"),
|
||||
};
|
||||
(
|
||||
id.clone(),
|
||||
InstitutionState {
|
||||
id,
|
||||
name: format!("Regional Power {index:02}"),
|
||||
resources: vec![
|
||||
format!("regional reserve {index:02}"),
|
||||
"public harbor bulletin".into(),
|
||||
],
|
||||
goals: vec![format!("shape resettlement policy bloc {}", index % 5)],
|
||||
posture: format!(
|
||||
"Bloc {} weighs shelter, labor, and political costs before the storm.",
|
||||
index % 4
|
||||
),
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let gestalt = |id: &str,
|
||||
name: &str,
|
||||
home: &str,
|
||||
capabilities: &[&str],
|
||||
knowledge: &[&str],
|
||||
goals: &[&str],
|
||||
pressures: &[&str]| GestaltPersonaState {
|
||||
schema: "ghostlight.gestalt_persona_state.v1".into(),
|
||||
id: id.into(),
|
||||
name: name.into(),
|
||||
version: 0,
|
||||
home_location_id: home.into(),
|
||||
shared_capabilities: capabilities.iter().map(|value| (*value).into()).collect(),
|
||||
shared_knowledge: knowledge.iter().map(|value| (*value).into()).collect(),
|
||||
resources: BTreeSet::new(),
|
||||
goals: goals.iter().map(|value| (*value).into()).collect(),
|
||||
pressures: pressures.iter().map(|value| (*value).into()).collect(),
|
||||
};
|
||||
let mut gestalts = BTreeMap::from([
|
||||
(
|
||||
"refugees-east".into(),
|
||||
gestalt(
|
||||
"refugees-east",
|
||||
"Eastern fire refugees",
|
||||
"transit-camp",
|
||||
&["survive transit", "organize shelter rows"],
|
||||
&["camp departure board", "public harbor bulletin"],
|
||||
&["find durable homes before the storm"],
|
||||
&["the camp closes after this ferry"],
|
||||
),
|
||||
),
|
||||
(
|
||||
"harbor-neighbors".into(),
|
||||
gestalt(
|
||||
"harbor-neighbors",
|
||||
"South Harbor neighbors",
|
||||
"south-harbor",
|
||||
&["repair nets", "organize harbor kitchens"],
|
||||
&["harbor routines", "public harbor bulletin"],
|
||||
&["keep the harbor alive through the storm"],
|
||||
&["some residents resent the resettlement order"],
|
||||
),
|
||||
),
|
||||
(
|
||||
"relief-crews".into(),
|
||||
gestalt(
|
||||
"relief-crews",
|
||||
"Mutual-aid relief crews",
|
||||
"south-harbor",
|
||||
&["distribute shelter supplies"],
|
||||
&["public harbor bulletin"],
|
||||
&["keep arrivals alive"],
|
||||
&["supplies cover only one more night"],
|
||||
),
|
||||
),
|
||||
(
|
||||
"dock-guild".into(),
|
||||
gestalt(
|
||||
"dock-guild",
|
||||
"Dock labor guild",
|
||||
"south-harbor",
|
||||
&["load ferries", "repair cranes"],
|
||||
&["dock shift board", "public harbor bulletin"],
|
||||
&["protect shifts and keep ferries moving"],
|
||||
&["the storm deadline compresses every shift"],
|
||||
),
|
||||
),
|
||||
]);
|
||||
for (id, name, home) in [
|
||||
("displaced-root", "All displaced people", "transit-camp"),
|
||||
(
|
||||
"crisis-refugees",
|
||||
"Crisis refugee populations",
|
||||
"transit-camp",
|
||||
),
|
||||
("displaced-other", "Other displaced people", "transit-camp"),
|
||||
("crisis-other", "Other crisis refugees", "transit-camp"),
|
||||
(
|
||||
"southport-root",
|
||||
"All Southport populations",
|
||||
"south-harbor",
|
||||
),
|
||||
("harbor-populations", "Harbor populations", "south-harbor"),
|
||||
(
|
||||
"inland-other",
|
||||
"Other Southport populations",
|
||||
"south-harbor",
|
||||
),
|
||||
("harbor-other", "Other harbor populations", "south-harbor"),
|
||||
] {
|
||||
gestalts.insert(id.into(), gestalt(id, name, home, &[], &[], &[], &[]));
|
||||
}
|
||||
let member = GestaltMemberDelta {
|
||||
schema: "ghostlight.gestalt_member_delta.v1".into(),
|
||||
id: "mira-venn".into(),
|
||||
gestalt_id: "refugees-east".into(),
|
||||
version: 3,
|
||||
name: "Mira Venn".into(),
|
||||
capability_additions: BTreeSet::from(["weave signal cord".into()]),
|
||||
capability_removals: BTreeSet::from(["organize shelter rows".into()]),
|
||||
knowledge_additions: BTreeSet::from(["the player kept the evacuation gate open".into()]),
|
||||
knowledge_removals: BTreeSet::new(),
|
||||
equipment: BTreeSet::from(["patched blue satchel".into()]),
|
||||
conditions: BTreeSet::from(["healed smoke burn".into()]),
|
||||
obligations: BTreeSet::from(["thank the player if their paths cross again".into()]),
|
||||
relationships: BTreeMap::from([(
|
||||
"player".into(),
|
||||
"trusts them for opening the evacuation gate without demanding obedience".into(),
|
||||
)]),
|
||||
goals: vec!["take the verified South Harbor berth and build a quiet life".into()],
|
||||
memories: vec![
|
||||
"The player held the eastern gate while Mira carried her brother through the smoke."
|
||||
.into(),
|
||||
],
|
||||
last_location_id: Some("transit-camp".into()),
|
||||
materialized_actor_id: None,
|
||||
last_relevant_revision: 7,
|
||||
relevance_lease_until_revision: 0,
|
||||
};
|
||||
let pressure = "The last protected ferry leaves the Eastern Transit Camp before the storm. Mira Venn has one verified berth in South Harbor, where the harbor neighbors dispute the resettlement order. The port authority, relief union, dock guild, and regional powers must also act on shelter, labor, and supply pressures; none may decide for Mira or speak as the arena.";
|
||||
let mut campaign = Campaign {
|
||||
schema: "ghostlight.campaign.v1".into(),
|
||||
id: uuid::Uuid::new_v4(),
|
||||
name: "Longitudinal refugee return acceptance".into(),
|
||||
revision: 0,
|
||||
branch_origin: BranchOrigin {
|
||||
canon_cutoff: "acceptance-fixture".into(),
|
||||
evidence_receipt_ids: vec![],
|
||||
},
|
||||
world_time: now,
|
||||
tick_hours: 6,
|
||||
player_actor_id: "player".into(),
|
||||
locations,
|
||||
actors: BTreeMap::from([("player".into(), player)]),
|
||||
institutions,
|
||||
clocks: BTreeMap::from([(
|
||||
"storm-ferry".into(),
|
||||
WorldClock {
|
||||
id: "storm-ferry".into(),
|
||||
label: "Last protected ferry".into(),
|
||||
progress: 3,
|
||||
threshold: 4,
|
||||
consequence: "the camp is cut off by the storm".into(),
|
||||
},
|
||||
)]),
|
||||
facts: BTreeMap::new(),
|
||||
transcript: vec![],
|
||||
last_player_activity: now - Duration::hours(2),
|
||||
pending_ticks: 1,
|
||||
away_ticks_processed: 0,
|
||||
events: vec![Event {
|
||||
id: "resettlement-deadline".into(),
|
||||
at: now,
|
||||
kind: "public_notice".into(),
|
||||
summary: pressure.into(),
|
||||
actor_ids: vec![],
|
||||
institution_ids: vec![],
|
||||
location_ids: vec!["transit-camp".into(), "south-harbor".into()],
|
||||
public_channels: vec!["public harbor bulletin".into()],
|
||||
}],
|
||||
news: vec![],
|
||||
canon_candidates: BTreeMap::new(),
|
||||
gestalts,
|
||||
gestalt_members: BTreeMap::from([("mira-venn".into(), member)]),
|
||||
pending_world_proposals: vec![],
|
||||
agency_profiles: BTreeMap::new(),
|
||||
agency_relations: BTreeMap::new(),
|
||||
gestalt_lineages: BTreeMap::new(),
|
||||
resolution_policy: ResolutionPolicy {
|
||||
active_cell_budget: 1,
|
||||
provider_parallelism: 4,
|
||||
..ResolutionPolicy::default()
|
||||
},
|
||||
resolution_pins: BTreeMap::new(),
|
||||
resolution_cover: None,
|
||||
strategic_tick_count: 0,
|
||||
};
|
||||
ghostlight_dungeon::resolution::ensure_agency_profiles(&mut campaign);
|
||||
for id in [
|
||||
"displaced-root",
|
||||
"crisis-refugees",
|
||||
"southport-root",
|
||||
"harbor-populations",
|
||||
] {
|
||||
let profile = campaign.agency_profiles.get_mut(id).unwrap();
|
||||
profile.active_leaf = false;
|
||||
profile.simulation_eligible = false;
|
||||
}
|
||||
campaign
|
||||
.agency_profiles
|
||||
.get_mut("crisis-refugees")
|
||||
.unwrap()
|
||||
.parent_subject_id = Some("displaced-root".into());
|
||||
campaign
|
||||
.agency_profiles
|
||||
.get_mut("displaced-other")
|
||||
.unwrap()
|
||||
.parent_subject_id = Some("displaced-root".into());
|
||||
campaign
|
||||
.agency_profiles
|
||||
.get_mut("refugees-east")
|
||||
.unwrap()
|
||||
.parent_subject_id = Some("crisis-refugees".into());
|
||||
campaign
|
||||
.agency_profiles
|
||||
.get_mut("crisis-other")
|
||||
.unwrap()
|
||||
.parent_subject_id = Some("crisis-refugees".into());
|
||||
campaign
|
||||
.agency_profiles
|
||||
.get_mut("harbor-populations")
|
||||
.unwrap()
|
||||
.parent_subject_id = Some("southport-root".into());
|
||||
campaign
|
||||
.agency_profiles
|
||||
.get_mut("inland-other")
|
||||
.unwrap()
|
||||
.parent_subject_id = Some("southport-root".into());
|
||||
campaign
|
||||
.agency_profiles
|
||||
.get_mut("harbor-neighbors")
|
||||
.unwrap()
|
||||
.parent_subject_id = Some("harbor-populations".into());
|
||||
campaign
|
||||
.agency_profiles
|
||||
.get_mut("harbor-other")
|
||||
.unwrap()
|
||||
.parent_subject_id = Some("harbor-populations".into());
|
||||
for (index, profile) in campaign
|
||||
.agency_profiles
|
||||
.values_mut()
|
||||
.filter(|profile| profile.active_leaf && profile.simulation_eligible)
|
||||
.enumerate()
|
||||
{
|
||||
profile.facets.insert(
|
||||
AgencyAxis::Geography,
|
||||
BTreeSet::from([format!("region-{}", index % 4)]),
|
||||
);
|
||||
profile.facets.insert(
|
||||
AgencyAxis::Ideology,
|
||||
BTreeSet::from([format!("bloc-{}", index % 5)]),
|
||||
);
|
||||
profile.facets.insert(
|
||||
AgencyAxis::Information,
|
||||
BTreeSet::from([format!("channel-{}", index % 6)]),
|
||||
);
|
||||
}
|
||||
campaign.agency_relations.insert(
|
||||
"resettlement-route".into(),
|
||||
AgencyRelation {
|
||||
schema: "ghostlight.agency_relation.v1".into(),
|
||||
id: "resettlement-route".into(),
|
||||
from_subject_id: "refugees-east".into(),
|
||||
to_subject_id: "harbor-neighbors".into(),
|
||||
kind: AgencyRelationKind::Migration,
|
||||
strength: 95,
|
||||
active: true,
|
||||
evidence_receipt_ids: vec![],
|
||||
},
|
||||
);
|
||||
campaign.agency_relations.insert(
|
||||
"resettlement-rivalry".into(),
|
||||
AgencyRelation {
|
||||
schema: "ghostlight.agency_relation.v1".into(),
|
||||
id: "resettlement-rivalry".into(),
|
||||
from_subject_id: "refugees-east".into(),
|
||||
to_subject_id: "harbor-neighbors".into(),
|
||||
kind: AgencyRelationKind::Rivalry,
|
||||
strength: 80,
|
||||
active: true,
|
||||
evidence_receipt_ids: vec![],
|
||||
},
|
||||
);
|
||||
campaign.gestalt_lineages.insert(
|
||||
"displaced-root".into(),
|
||||
GestaltLineage {
|
||||
schema: "ghostlight.gestalt_lineage.v1".into(),
|
||||
parent_gestalt_id: "displaced-root".into(),
|
||||
child_gestalt_ids: vec!["crisis-refugees".into(), "displaced-other".into()],
|
||||
partition_axis: AgencyAxis::Ideology,
|
||||
partition_values: BTreeMap::from([
|
||||
("crisis-refugees".into(), "crisis".into()),
|
||||
("displaced-other".into(), "other/unknown".into()),
|
||||
]),
|
||||
residual_child_id: "displaced-other".into(),
|
||||
source_revision: 0,
|
||||
},
|
||||
);
|
||||
campaign.gestalt_lineages.insert(
|
||||
"crisis-refugees".into(),
|
||||
GestaltLineage {
|
||||
schema: "ghostlight.gestalt_lineage.v1".into(),
|
||||
parent_gestalt_id: "crisis-refugees".into(),
|
||||
child_gestalt_ids: vec!["refugees-east".into(), "crisis-other".into()],
|
||||
partition_axis: AgencyAxis::Geography,
|
||||
partition_values: BTreeMap::from([
|
||||
("refugees-east".into(), "east".into()),
|
||||
("crisis-other".into(), "other/unknown".into()),
|
||||
]),
|
||||
residual_child_id: "crisis-other".into(),
|
||||
source_revision: 0,
|
||||
},
|
||||
);
|
||||
campaign.gestalt_lineages.insert(
|
||||
"southport-root".into(),
|
||||
GestaltLineage {
|
||||
schema: "ghostlight.gestalt_lineage.v1".into(),
|
||||
parent_gestalt_id: "southport-root".into(),
|
||||
child_gestalt_ids: vec!["harbor-populations".into(), "inland-other".into()],
|
||||
partition_axis: AgencyAxis::Geography,
|
||||
partition_values: BTreeMap::from([
|
||||
("harbor-populations".into(), "harbor".into()),
|
||||
("inland-other".into(), "other/unknown".into()),
|
||||
]),
|
||||
residual_child_id: "inland-other".into(),
|
||||
source_revision: 0,
|
||||
},
|
||||
);
|
||||
campaign.gestalt_lineages.insert(
|
||||
"harbor-populations".into(),
|
||||
GestaltLineage {
|
||||
schema: "ghostlight.gestalt_lineage.v1".into(),
|
||||
parent_gestalt_id: "harbor-populations".into(),
|
||||
child_gestalt_ids: vec!["harbor-neighbors".into(), "harbor-other".into()],
|
||||
partition_axis: AgencyAxis::EconomyRole,
|
||||
partition_values: BTreeMap::from([
|
||||
("harbor-neighbors".into(), "neighbors".into()),
|
||||
("harbor-other".into(), "other/unknown".into()),
|
||||
]),
|
||||
residual_child_id: "harbor-other".into(),
|
||||
source_revision: 0,
|
||||
},
|
||||
);
|
||||
campaign
|
||||
}
|
||||
|
|
@ -433,6 +433,12 @@ pub enum StrategicCellEffect {
|
|||
actor_id: String,
|
||||
destination_id: String,
|
||||
},
|
||||
MemberMigration {
|
||||
member_id: String,
|
||||
source_gestalt_id: String,
|
||||
destination_gestalt_id: String,
|
||||
destination_location_id: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
|
|
@ -572,6 +578,8 @@ pub struct StrategicTickPlan {
|
|||
pub institution_actions: Vec<StrategicInstitutionAction>,
|
||||
pub gestalt_actions: Vec<StrategicGestaltAction>,
|
||||
pub actor_moves: Vec<StrategicActorMove>,
|
||||
#[serde(default)]
|
||||
pub member_migrations: Vec<StrategicMemberMigration>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
|
|
@ -599,6 +607,16 @@ pub struct StrategicActorMove {
|
|||
pub public_channels: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
pub struct StrategicMemberMigration {
|
||||
pub member_id: String,
|
||||
pub source_gestalt_id: String,
|
||||
pub destination_gestalt_id: String,
|
||||
pub destination_location_id: String,
|
||||
pub summary: String,
|
||||
pub public_channels: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
pub struct StrategicTickReceipt {
|
||||
pub schema: String,
|
||||
|
|
|
|||
|
|
@ -1324,9 +1324,114 @@ fn apply_strategic_tick_plan(
|
|||
public_channels: action.public_channels,
|
||||
});
|
||||
}
|
||||
|
||||
let mut seen_members = BTreeSet::new();
|
||||
for action in plan.member_migrations {
|
||||
if !seen_members.insert(action.member_id.clone()) {
|
||||
return Err(KernelError::Invalid(
|
||||
"gestalt member migrates twice in one strategic tick".into(),
|
||||
));
|
||||
}
|
||||
if action.summary.trim().is_empty() {
|
||||
return Err(KernelError::Invalid(
|
||||
"strategic member migration has no summary".into(),
|
||||
));
|
||||
}
|
||||
validate_public_channels(&action.public_channels)?;
|
||||
crate::resolution::validate_member_migration(
|
||||
campaign,
|
||||
&action.member_id,
|
||||
&action.source_gestalt_id,
|
||||
&action.destination_gestalt_id,
|
||||
&action.destination_location_id,
|
||||
)
|
||||
.map_err(|error| KernelError::Invalid(error.to_string()))?;
|
||||
let origin = campaign.gestalt_members[&action.member_id]
|
||||
.last_location_id
|
||||
.clone()
|
||||
.unwrap_or_else(|| {
|
||||
campaign.gestalts[&action.source_gestalt_id]
|
||||
.home_location_id
|
||||
.clone()
|
||||
});
|
||||
rebase_member_migration(campaign, &action)?;
|
||||
events.push(crate::domain::Event {
|
||||
id: format!("strategic:{revision}:member:{}", action.member_id),
|
||||
at,
|
||||
kind: "gestalt_member_migration".into(),
|
||||
summary: action.summary,
|
||||
actor_ids: vec![format!("member:{}", action.member_id)],
|
||||
institution_ids: vec![],
|
||||
location_ids: vec![origin, action.destination_location_id],
|
||||
public_channels: action.public_channels,
|
||||
});
|
||||
}
|
||||
Ok(events)
|
||||
}
|
||||
|
||||
fn rebase_member_migration(
|
||||
campaign: &mut Campaign,
|
||||
action: &crate::domain::StrategicMemberMigration,
|
||||
) -> Result<(), KernelError> {
|
||||
let effective_capabilities =
|
||||
crate::resolution::effective_member_capabilities(campaign, &action.member_id)
|
||||
.map_err(|error| KernelError::Invalid(error.to_string()))?;
|
||||
let effective_knowledge =
|
||||
crate::resolution::effective_member_knowledge(campaign, &action.member_id)
|
||||
.map_err(|error| KernelError::Invalid(error.to_string()))?;
|
||||
let source_goals = campaign.gestalts[&action.source_gestalt_id].goals.clone();
|
||||
let destination = campaign.gestalts[&action.destination_gestalt_id].clone();
|
||||
let effective_goals = {
|
||||
let member = &campaign.gestalt_members[&action.member_id];
|
||||
if member.goals.is_empty() {
|
||||
source_goals
|
||||
} else {
|
||||
member.goals.clone()
|
||||
}
|
||||
};
|
||||
let member = campaign
|
||||
.gestalt_members
|
||||
.get_mut(&action.member_id)
|
||||
.expect("member migration was validated");
|
||||
member.capability_additions = effective_capabilities
|
||||
.difference(&destination.shared_capabilities)
|
||||
.cloned()
|
||||
.collect();
|
||||
member.capability_removals = destination
|
||||
.shared_capabilities
|
||||
.difference(&effective_capabilities)
|
||||
.cloned()
|
||||
.collect();
|
||||
member.knowledge_additions = effective_knowledge
|
||||
.difference(&destination.shared_knowledge)
|
||||
.cloned()
|
||||
.collect();
|
||||
member.knowledge_removals = destination
|
||||
.shared_knowledge
|
||||
.difference(&effective_knowledge)
|
||||
.cloned()
|
||||
.collect();
|
||||
member.goals = if effective_goals == destination.goals {
|
||||
vec![]
|
||||
} else {
|
||||
effective_goals
|
||||
};
|
||||
member.gestalt_id = action.destination_gestalt_id.clone();
|
||||
member.last_location_id = Some(action.destination_location_id.clone());
|
||||
member.version = member.version.saturating_add(1);
|
||||
campaign
|
||||
.gestalts
|
||||
.get_mut(&action.source_gestalt_id)
|
||||
.expect("source gestalt was validated")
|
||||
.version += 1;
|
||||
campaign
|
||||
.gestalts
|
||||
.get_mut(&action.destination_gestalt_id)
|
||||
.expect("destination gestalt was validated")
|
||||
.version += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn deterministic_strategic_tick(
|
||||
campaign: &mut Campaign,
|
||||
tick_number: u8,
|
||||
|
|
@ -1679,6 +1784,213 @@ mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
fn hierarchical_refugee_campaign() -> Campaign {
|
||||
let mut value = campaign();
|
||||
value.locations.insert(
|
||||
"camp".into(),
|
||||
Location {
|
||||
id: "camp".into(),
|
||||
name: "Transit camp".into(),
|
||||
container_id: None,
|
||||
routes: BTreeMap::from([(
|
||||
"to-docks".into(),
|
||||
Route {
|
||||
destination_id: "docks".into(),
|
||||
distance: "across the bay".into(),
|
||||
travel_minutes: 90,
|
||||
},
|
||||
)]),
|
||||
persistent_features: vec!["departure board".into()],
|
||||
},
|
||||
);
|
||||
value.locations.insert(
|
||||
"docks".into(),
|
||||
Location {
|
||||
id: "docks".into(),
|
||||
name: "South docks".into(),
|
||||
container_id: None,
|
||||
routes: BTreeMap::new(),
|
||||
persistent_features: vec!["net lofts".into()],
|
||||
},
|
||||
);
|
||||
let gestalt = |id: &str,
|
||||
name: &str,
|
||||
location: &str,
|
||||
capabilities: &[&str],
|
||||
knowledge: &[&str],
|
||||
goals: &[&str]| GestaltPersonaState {
|
||||
schema: "ghostlight.gestalt_persona_state.v1".into(),
|
||||
id: id.into(),
|
||||
name: name.into(),
|
||||
version: 0,
|
||||
home_location_id: location.into(),
|
||||
shared_capabilities: capabilities.iter().map(|value| (*value).into()).collect(),
|
||||
shared_knowledge: knowledge.iter().map(|value| (*value).into()).collect(),
|
||||
resources: BTreeSet::new(),
|
||||
goals: goals.iter().map(|value| (*value).into()).collect(),
|
||||
pressures: vec![],
|
||||
};
|
||||
value.gestalts.insert(
|
||||
"refugees-east".into(),
|
||||
gestalt(
|
||||
"refugees-east",
|
||||
"Eastern transit refugees",
|
||||
"camp",
|
||||
&["survive transit", "speak old dialect"],
|
||||
&["camp alarm", "old village"],
|
||||
&["find safety"],
|
||||
),
|
||||
);
|
||||
value.gestalts.insert(
|
||||
"dock-neighbors".into(),
|
||||
gestalt(
|
||||
"dock-neighbors",
|
||||
"South dock neighbors",
|
||||
"docks",
|
||||
&["repair nets"],
|
||||
&["harbor routines", "public bulletin"],
|
||||
&["keep the docks running"],
|
||||
),
|
||||
);
|
||||
value.gestalt_members.insert(
|
||||
"mira".into(),
|
||||
GestaltMemberDelta {
|
||||
schema: "ghostlight.gestalt_member_delta.v1".into(),
|
||||
id: "mira".into(),
|
||||
gestalt_id: "refugees-east".into(),
|
||||
version: 3,
|
||||
name: "Mira Venn".into(),
|
||||
capability_additions: BTreeSet::from(["weave signal cord".into()]),
|
||||
capability_removals: BTreeSet::from(["speak old dialect".into()]),
|
||||
knowledge_additions: BTreeSet::from(["the player kept a promise".into()]),
|
||||
knowledge_removals: BTreeSet::from(["camp alarm".into()]),
|
||||
equipment: BTreeSet::from(["patched blue satchel".into()]),
|
||||
conditions: BTreeSet::from(["healed burn scar".into()]),
|
||||
obligations: BTreeSet::from(["repay the player's help".into()]),
|
||||
relationships: BTreeMap::from([(
|
||||
"player".into(),
|
||||
"trusts them for opening the evacuation gate".into(),
|
||||
)]),
|
||||
goals: vec![],
|
||||
memories: vec!["The player carried her brother through the smoke.".into()],
|
||||
last_location_id: Some("camp".into()),
|
||||
materialized_actor_id: None,
|
||||
last_relevant_revision: 7,
|
||||
relevance_lease_until_revision: 0,
|
||||
},
|
||||
);
|
||||
crate::resolution::ensure_agency_profiles(&mut value);
|
||||
value
|
||||
.agency_profiles
|
||||
.get_mut("refugees-east")
|
||||
.unwrap()
|
||||
.parent_subject_id = Some("refugees-by-destination".into());
|
||||
value
|
||||
.agency_profiles
|
||||
.get_mut("dock-neighbors")
|
||||
.unwrap()
|
||||
.parent_subject_id = Some("southport-populations".into());
|
||||
value.agency_relations.insert(
|
||||
"refugee-resettlement".into(),
|
||||
AgencyRelation {
|
||||
schema: "ghostlight.agency_relation.v1".into(),
|
||||
id: "refugee-resettlement".into(),
|
||||
from_subject_id: "refugees-east".into(),
|
||||
to_subject_id: "dock-neighbors".into(),
|
||||
kind: AgencyRelationKind::Migration,
|
||||
strength: 90,
|
||||
active: true,
|
||||
evidence_receipt_ids: vec![],
|
||||
},
|
||||
);
|
||||
value
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn member_migration_rebases_across_unrelated_hierarchy_without_changing_the_person() {
|
||||
let mut value = hierarchical_refugee_campaign();
|
||||
let capabilities_before =
|
||||
crate::resolution::effective_member_capabilities(&value, "mira").unwrap();
|
||||
let knowledge_before =
|
||||
crate::resolution::effective_member_knowledge(&value, "mira").unwrap();
|
||||
let identity_before = value.gestalt_members["mira"].clone();
|
||||
let events = apply_strategic_tick_plan(
|
||||
&mut value,
|
||||
StrategicTickPlan {
|
||||
member_migrations: vec![StrategicMemberMigration {
|
||||
member_id: "mira".into(),
|
||||
source_gestalt_id: "refugees-east".into(),
|
||||
destination_gestalt_id: "dock-neighbors".into(),
|
||||
destination_location_id: "docks".into(),
|
||||
summary:
|
||||
"Mira takes the resettlement ferry and joins the south-dock neighbors."
|
||||
.into(),
|
||||
public_channels: vec![],
|
||||
}],
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let member = &value.gestalt_members["mira"];
|
||||
assert_eq!(member.gestalt_id, "dock-neighbors");
|
||||
assert_eq!(member.last_location_id.as_deref(), Some("docks"));
|
||||
assert_eq!(member.version, identity_before.version + 1);
|
||||
assert_eq!(member.name, identity_before.name);
|
||||
assert_eq!(member.relationships, identity_before.relationships);
|
||||
assert_eq!(member.memories, identity_before.memories);
|
||||
assert_eq!(member.equipment, identity_before.equipment);
|
||||
assert_eq!(member.conditions, identity_before.conditions);
|
||||
assert_eq!(member.obligations, identity_before.obligations);
|
||||
assert_eq!(member.goals, vec!["find safety"]);
|
||||
assert_eq!(
|
||||
crate::resolution::effective_member_capabilities(&value, "mira").unwrap(),
|
||||
capabilities_before
|
||||
);
|
||||
assert_eq!(
|
||||
crate::resolution::effective_member_knowledge(&value, "mira").unwrap(),
|
||||
knowledge_before
|
||||
);
|
||||
assert_eq!(events.len(), 1);
|
||||
assert_eq!(events[0].kind, "gestalt_member_migration");
|
||||
assert_eq!(events[0].actor_ids, vec!["member:mira"]);
|
||||
|
||||
let actor = materialize_actor(
|
||||
&value.gestalts["dock-neighbors"],
|
||||
member,
|
||||
"member:mira",
|
||||
"docks",
|
||||
);
|
||||
assert_eq!(actor.name, "Mira Venn");
|
||||
assert_eq!(actor.capabilities, capabilities_before);
|
||||
assert_eq!(actor.knowledge, knowledge_before);
|
||||
assert_eq!(actor.relationships, identity_before.relationships);
|
||||
assert_eq!(actor.memories, identity_before.memories);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn member_migration_requires_the_persons_route_and_typed_population_relation() {
|
||||
let mut value = hierarchical_refugee_campaign();
|
||||
value.agency_relations.clear();
|
||||
let before = value.clone();
|
||||
let error = apply_strategic_tick_plan(
|
||||
&mut value,
|
||||
StrategicTickPlan {
|
||||
member_migrations: vec![StrategicMemberMigration {
|
||||
member_id: "mira".into(),
|
||||
source_gestalt_id: "refugees-east".into(),
|
||||
destination_gestalt_id: "dock-neighbors".into(),
|
||||
destination_location_id: "docks".into(),
|
||||
summary: "Mira relocates.".into(),
|
||||
public_channels: vec![],
|
||||
}],
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("migration relation"));
|
||||
assert_eq!(value.gestalt_members, before.gestalt_members);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stale_command_cannot_mutate_campaign() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ use ghostlight_persona_projection::{
|
|||
};
|
||||
use schemars::{JsonSchema, schema_for};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
|
|
@ -68,6 +68,25 @@ pub struct CellConstituentSlice {
|
|||
pub pressures: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct CellMemberSlice {
|
||||
pub subject_id: String,
|
||||
pub member_id: String,
|
||||
pub name: String,
|
||||
pub source_gestalt_id: String,
|
||||
pub source_location_id: String,
|
||||
pub knowledge: BTreeSet<String>,
|
||||
pub capabilities: BTreeSet<String>,
|
||||
pub resources: BTreeSet<String>,
|
||||
pub information_channels: BTreeSet<String>,
|
||||
pub permitted_state_references: BTreeSet<String>,
|
||||
pub migration_destinations: BTreeMap<String, String>,
|
||||
pub goals: Vec<String>,
|
||||
pub pressures: Vec<String>,
|
||||
pub relationships: BTreeMap<String, String>,
|
||||
pub memories: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct PermittedCellSlice {
|
||||
pub cell_id: String,
|
||||
|
|
@ -76,6 +95,7 @@ pub struct PermittedCellSlice {
|
|||
pub resolution_epoch: u64,
|
||||
pub snapshot_binding: String,
|
||||
pub constituents: Vec<CellConstituentSlice>,
|
||||
pub member_exceptions: Vec<CellMemberSlice>,
|
||||
pub shared_knowledge: BTreeSet<String>,
|
||||
pub shared_capabilities: BTreeSet<String>,
|
||||
pub perceived_events: Vec<String>,
|
||||
|
|
@ -285,6 +305,21 @@ fn cell_projector_context(slice: &PermittedCellSlice) -> serde_json::Value {
|
|||
"goals": subject.goals,
|
||||
"pressures": subject.pressures,
|
||||
})).collect::<Vec<_>>(),
|
||||
"member_exceptions": slice.member_exceptions.iter().map(|member| serde_json::json!({
|
||||
"subject_id": member.subject_id,
|
||||
"member_id": member.member_id,
|
||||
"name": member.name,
|
||||
"source_gestalt_id": member.source_gestalt_id,
|
||||
"source_location_id": member.source_location_id,
|
||||
"knowledge": member.knowledge,
|
||||
"capabilities": member.capabilities,
|
||||
"resources": member.resources,
|
||||
"migration_destinations": member.migration_destinations,
|
||||
"goals": member.goals,
|
||||
"pressures": member.pressures,
|
||||
"relationships": member.relationships,
|
||||
"memories": member.memories,
|
||||
})).collect::<Vec<_>>(),
|
||||
"shared_knowledge": slice.shared_knowledge,
|
||||
"shared_capabilities": slice.shared_capabilities,
|
||||
"world_clock_pressure": slice.world_clock_pressure,
|
||||
|
|
@ -310,6 +345,15 @@ fn cell_interpreter_context(slice: &PermittedCellSlice) -> serde_json::Value {
|
|||
"permitted_state_references": subject.permitted_state_references,
|
||||
"reachable_destination_ids": subject.reachable_destination_ids,
|
||||
})).collect::<Vec<_>>(),
|
||||
"member_permissions": slice.member_exceptions.iter().map(|member| serde_json::json!({
|
||||
"subject_id": member.subject_id,
|
||||
"member_id": member.member_id,
|
||||
"source_gestalt_id": member.source_gestalt_id,
|
||||
"source_location_id": member.source_location_id,
|
||||
"information_channels": member.information_channels,
|
||||
"permitted_state_references": member.permitted_state_references,
|
||||
"migration_destinations": member.migration_destinations,
|
||||
})).collect::<Vec<_>>(),
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -331,12 +375,15 @@ impl CellProjectionEngine {
|
|||
let visible_stimulus = slice.perceived_events.join("\n");
|
||||
let mode_guidance = match slice.mode {
|
||||
crate::domain::SimulationCellMode::Cohesive => {
|
||||
"This cell has real collective authority. Render a plural lived perspective from genuinely shared knowledge and capability only; describe constituent exceptions as exceptions."
|
||||
"This cell has real collective authority. Render a plural lived perspective from genuinely shared knowledge and capability only; describe constituent and named-member exceptions as separately attributed exceptions. A population cannot decide for a named member."
|
||||
}
|
||||
crate::domain::SimulationCellMode::Arena => {
|
||||
"This cell is an arena, never a person or faction. Render an attributed polyphonic situation. Never union secrets, knowledge, resources, intentions, authority, or voice between constituents."
|
||||
"This cell is an arena, never a person or faction. Render an attributed polyphonic situation. Never union secrets, knowledge, resources, intentions, authority, or voice between constituents or named-member exceptions."
|
||||
}
|
||||
};
|
||||
let mode_guidance = format!(
|
||||
"{mode_guidance} Every supplied member_exception was selected because that person has an actionable decision in this horizon. Render each selected person explicitly by name, with only their own footing and choices."
|
||||
);
|
||||
let projected = run_validated_stage(
|
||||
self.model.as_ref(),
|
||||
&ModelStageRequest {
|
||||
|
|
@ -347,7 +394,7 @@ impl CellProjectionEngine {
|
|||
identity: &slice.cell_id,
|
||||
typed_context: &projector_context,
|
||||
visible_stimulus: &visible_stimulus,
|
||||
domain_guidance: mode_guidance,
|
||||
domain_guidance: &mode_guidance,
|
||||
word_budget: (120 + 45 * slice.constituents.len()).min(360),
|
||||
}),
|
||||
output_schema: None,
|
||||
|
|
@ -402,7 +449,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-attributed attempts supported by that constituent's permission references. The runtime, not you, binds cell identity, revisions, and complete membership. 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 supported by that exact subject's permission references. A named member may only emit member_migration, using one supplied destination mapping; a population or arena cannot migrate a person. The runtime, not you, binds cell identity, revisions, complete 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 {
|
||||
|
|
@ -529,69 +576,109 @@ fn validate_cell_appraisal(
|
|||
));
|
||||
}
|
||||
for action in &appraisal.actions {
|
||||
let subject = slice
|
||||
.constituents
|
||||
.iter()
|
||||
.find(|value| value.subject_id == action.subject_id)
|
||||
.ok_or_else(|| anyhow!("action is attributed outside the cell"))?;
|
||||
if action.intent.trim().is_empty() || action.intended_effect.trim().is_empty() {
|
||||
return Err(anyhow!(
|
||||
"action for subject {} requires non-empty intent and intended_effect",
|
||||
subject.subject_id
|
||||
action.subject_id
|
||||
));
|
||||
}
|
||||
let invalid_references = action
|
||||
.state_references
|
||||
if let Some(subject) = slice
|
||||
.constituents
|
||||
.iter()
|
||||
.filter(|reference| !subject.permitted_state_references.contains(*reference))
|
||||
.collect::<Vec<_>>();
|
||||
let invalid_channels = action
|
||||
.public_channels
|
||||
.iter()
|
||||
.filter(|channel| !subject.information_channels.contains(*channel))
|
||||
.collect::<Vec<_>>();
|
||||
if !invalid_references.is_empty() || !invalid_channels.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"action for subject {} borrowed forbidden state references {:?} or information channels {:?}",
|
||||
subject.subject_id,
|
||||
invalid_references,
|
||||
invalid_channels
|
||||
));
|
||||
}
|
||||
match &action.effect {
|
||||
crate::domain::StrategicCellEffect::Institution {
|
||||
institution_id,
|
||||
location_ids,
|
||||
..
|
||||
} if subject.subject_kind == crate::domain::AgencySubjectKind::Institution
|
||||
&& institution_id == &subject.subject_id
|
||||
&& location_ids
|
||||
.iter()
|
||||
.all(|location| subject.location_ids.contains(location)) => {}
|
||||
crate::domain::StrategicCellEffect::Gestalt { gestalt_id, .. }
|
||||
if subject.subject_kind == crate::domain::AgencySubjectKind::Gestalt
|
||||
&& gestalt_id == &subject.subject_id => {}
|
||||
crate::domain::StrategicCellEffect::ActorMove {
|
||||
actor_id,
|
||||
destination_id,
|
||||
} if subject.subject_kind == crate::domain::AgencySubjectKind::Actor
|
||||
&& actor_id == &subject.subject_id
|
||||
&& subject.reachable_destination_ids.contains(destination_id) => {}
|
||||
_ => {
|
||||
return Err(anyhow!(
|
||||
"action for subject {} has effect {:?}, which exceeds exact authority for kind {:?}, locations {:?}, and reachable destinations {:?}",
|
||||
subject.subject_id,
|
||||
action.effect,
|
||||
subject.subject_kind,
|
||||
subject.location_ids,
|
||||
subject.reachable_destination_ids
|
||||
));
|
||||
.find(|value| value.subject_id == action.subject_id)
|
||||
{
|
||||
validate_action_permissions(
|
||||
action,
|
||||
&subject.permitted_state_references,
|
||||
&subject.information_channels,
|
||||
)?;
|
||||
match &action.effect {
|
||||
crate::domain::StrategicCellEffect::Institution {
|
||||
institution_id,
|
||||
location_ids,
|
||||
..
|
||||
} if subject.subject_kind == crate::domain::AgencySubjectKind::Institution
|
||||
&& institution_id == &subject.subject_id
|
||||
&& location_ids
|
||||
.iter()
|
||||
.all(|location| subject.location_ids.contains(location)) => {}
|
||||
crate::domain::StrategicCellEffect::Gestalt { gestalt_id, .. }
|
||||
if subject.subject_kind == crate::domain::AgencySubjectKind::Gestalt
|
||||
&& gestalt_id == &subject.subject_id => {}
|
||||
crate::domain::StrategicCellEffect::ActorMove {
|
||||
actor_id,
|
||||
destination_id,
|
||||
} if subject.subject_kind == crate::domain::AgencySubjectKind::Actor
|
||||
&& actor_id == &subject.subject_id
|
||||
&& subject.reachable_destination_ids.contains(destination_id) => {}
|
||||
_ => {
|
||||
return Err(anyhow!(
|
||||
"action for subject {} has effect {:?}, which exceeds exact constituent authority",
|
||||
subject.subject_id,
|
||||
action.effect,
|
||||
));
|
||||
}
|
||||
}
|
||||
} else if let Some(member) = slice
|
||||
.member_exceptions
|
||||
.iter()
|
||||
.find(|value| value.subject_id == action.subject_id)
|
||||
{
|
||||
validate_action_permissions(
|
||||
action,
|
||||
&member.permitted_state_references,
|
||||
&member.information_channels,
|
||||
)?;
|
||||
match &action.effect {
|
||||
crate::domain::StrategicCellEffect::MemberMigration {
|
||||
member_id,
|
||||
source_gestalt_id,
|
||||
destination_gestalt_id,
|
||||
destination_location_id,
|
||||
} if member_id == &member.member_id
|
||||
&& source_gestalt_id == &member.source_gestalt_id
|
||||
&& member.migration_destinations.get(destination_gestalt_id)
|
||||
== Some(destination_location_id) => {}
|
||||
_ => {
|
||||
return Err(anyhow!(
|
||||
"action for named member {} exceeds exact personal authority or supplied migration destinations",
|
||||
member.member_id
|
||||
));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return Err(anyhow!("action is attributed outside the cell"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_action_permissions(
|
||||
action: &crate::domain::CellActionProposal,
|
||||
permitted_state_references: &BTreeSet<String>,
|
||||
information_channels: &BTreeSet<String>,
|
||||
) -> Result<()> {
|
||||
let invalid_references = action
|
||||
.state_references
|
||||
.iter()
|
||||
.filter(|reference| !permitted_state_references.contains(*reference))
|
||||
.collect::<Vec<_>>();
|
||||
let invalid_channels = action
|
||||
.public_channels
|
||||
.iter()
|
||||
.filter(|channel| !information_channels.contains(*channel))
|
||||
.collect::<Vec<_>>();
|
||||
if !invalid_references.is_empty() || !invalid_channels.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"action for subject {} borrowed forbidden state references {:?} or information channels {:?}",
|
||||
action.subject_id,
|
||||
invalid_references,
|
||||
invalid_channels
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn constrain_cell_proposal_schema(
|
||||
schema: &mut serde_json::Value,
|
||||
slice: &PermittedCellSlice,
|
||||
|
|
@ -609,9 +696,20 @@ fn constrain_cell_proposal_schema(
|
|||
.pointer_mut("/$defs/CellActionProposal/properties")
|
||||
.and_then(serde_json::Value::as_object_mut)
|
||||
.ok_or_else(|| anyhow!("cell appraisal schema has no proposal properties"))?;
|
||||
let subject_ids = slice
|
||||
.constituents
|
||||
.iter()
|
||||
.map(|value| value.subject_id.as_str())
|
||||
.chain(
|
||||
slice
|
||||
.member_exceptions
|
||||
.iter()
|
||||
.map(|value| value.subject_id.as_str()),
|
||||
)
|
||||
.collect::<Vec<_>>();
|
||||
proposal.insert(
|
||||
"subject_id".into(),
|
||||
serde_json::json!({"type":"string","enum":slice.constituents.iter().map(|value| &value.subject_id).collect::<Vec<_>>() }),
|
||||
serde_json::json!({"type":"string","enum":subject_ids}),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -734,6 +832,7 @@ mod tests {
|
|||
goals: vec!["publish a position".into()],
|
||||
pressures: vec!["the vote is near".into()],
|
||||
}],
|
||||
member_exceptions: vec![],
|
||||
shared_knowledge: BTreeSet::new(),
|
||||
shared_capabilities: BTreeSet::new(),
|
||||
perceived_events: vec!["The final vote is public.".into()],
|
||||
|
|
|
|||
|
|
@ -1652,8 +1652,24 @@ pub fn validate_and_resolve_wave(
|
|||
summary: proposal.intended_effect,
|
||||
public_channels: proposal.public_channels,
|
||||
}),
|
||||
StrategicCellEffect::MemberMigration {
|
||||
member_id,
|
||||
source_gestalt_id,
|
||||
destination_gestalt_id,
|
||||
destination_location_id,
|
||||
} => plan.member_migrations.push(StrategicMemberMigration {
|
||||
member_id,
|
||||
source_gestalt_id,
|
||||
destination_gestalt_id,
|
||||
destination_location_id,
|
||||
summary: proposal.intended_effect,
|
||||
public_channels: proposal.public_channels,
|
||||
}),
|
||||
}
|
||||
if plan.institution_actions.len() + plan.gestalt_actions.len() + plan.actor_moves.len()
|
||||
if plan.institution_actions.len()
|
||||
+ plan.gestalt_actions.len()
|
||||
+ plan.actor_moves.len()
|
||||
+ plan.member_migrations.len()
|
||||
>= consequence_limit
|
||||
{
|
||||
break;
|
||||
|
|
@ -1667,13 +1683,18 @@ fn validate_cell_proposal(
|
|||
cell: &SimulationCell,
|
||||
proposal: &CellActionProposal,
|
||||
) -> Result<()> {
|
||||
if !cell.subject_ids.contains(&proposal.subject_id)
|
||||
|| proposal.subject_id == campaign.player_actor_id
|
||||
if proposal.subject_id == campaign.player_actor_id
|
||||
|| proposal.intent.trim().is_empty()
|
||||
|| proposal.intended_effect.trim().is_empty()
|
||||
{
|
||||
return Err(anyhow!("cell proposal has no exact constituent authority"));
|
||||
}
|
||||
if let Some(member_id) = proposal.subject_id.strip_prefix("member:") {
|
||||
return validate_member_cell_proposal(campaign, cell, member_id, proposal);
|
||||
}
|
||||
if !cell.subject_ids.contains(&proposal.subject_id) {
|
||||
return Err(anyhow!("cell proposal has no exact constituent authority"));
|
||||
}
|
||||
let profile = campaign
|
||||
.agency_profiles
|
||||
.get(&proposal.subject_id)
|
||||
|
|
@ -1737,10 +1758,232 @@ fn validate_cell_proposal(
|
|||
return Err(anyhow!("actor proposal exceeds spatial reach"));
|
||||
}
|
||||
}
|
||||
StrategicCellEffect::MemberMigration { .. } => {
|
||||
return Err(anyhow!(
|
||||
"a population, institution, actor, or arena cannot migrate a named member"
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_member_cell_proposal(
|
||||
campaign: &Campaign,
|
||||
cell: &SimulationCell,
|
||||
member_id: &str,
|
||||
proposal: &CellActionProposal,
|
||||
) -> Result<()> {
|
||||
let member = campaign
|
||||
.gestalt_members
|
||||
.get(member_id)
|
||||
.filter(|member| {
|
||||
member.materialized_actor_id.is_none() && cell.subject_ids.contains(&member.gestalt_id)
|
||||
})
|
||||
.ok_or_else(|| anyhow!("named member is not a dematerialized exception of this cell"))?;
|
||||
let permitted_references = member_state_references(campaign, member_id)?;
|
||||
let information_channels = effective_member_knowledge(campaign, member_id)?;
|
||||
if proposal
|
||||
.state_references
|
||||
.iter()
|
||||
.any(|reference| !permitted_references.contains(reference))
|
||||
|| proposal
|
||||
.public_channels
|
||||
.iter()
|
||||
.any(|channel| !information_channels.contains(channel))
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"named member proposal borrowed another subject's state or information channel"
|
||||
));
|
||||
}
|
||||
match &proposal.effect {
|
||||
StrategicCellEffect::MemberMigration {
|
||||
member_id: effect_member_id,
|
||||
source_gestalt_id,
|
||||
destination_gestalt_id,
|
||||
destination_location_id,
|
||||
} if effect_member_id == member_id && source_gestalt_id == &member.gestalt_id => {
|
||||
validate_member_migration(
|
||||
campaign,
|
||||
member_id,
|
||||
source_gestalt_id,
|
||||
destination_gestalt_id,
|
||||
destination_location_id,
|
||||
)
|
||||
}
|
||||
_ => Err(anyhow!(
|
||||
"named member exception may propose only its own validated migration"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn validate_member_migration(
|
||||
campaign: &Campaign,
|
||||
member_id: &str,
|
||||
source_gestalt_id: &str,
|
||||
destination_gestalt_id: &str,
|
||||
destination_location_id: &str,
|
||||
) -> Result<()> {
|
||||
let member = campaign
|
||||
.gestalt_members
|
||||
.get(member_id)
|
||||
.filter(|member| {
|
||||
member.materialized_actor_id.is_none() && member.gestalt_id == source_gestalt_id
|
||||
})
|
||||
.ok_or_else(|| anyhow!("member migration source is stale or individually active"))?;
|
||||
if source_gestalt_id == destination_gestalt_id {
|
||||
return Err(anyhow!(
|
||||
"member migration must change active population leaf"
|
||||
));
|
||||
}
|
||||
let source = campaign
|
||||
.gestalts
|
||||
.get(source_gestalt_id)
|
||||
.ok_or_else(|| anyhow!("member migration source gestalt is unknown"))?;
|
||||
let destination = campaign
|
||||
.gestalts
|
||||
.get(destination_gestalt_id)
|
||||
.filter(|destination| destination.home_location_id == destination_location_id)
|
||||
.ok_or_else(|| anyhow!("member migration destination gestalt or location is unknown"))?;
|
||||
for gestalt_id in [source_gestalt_id, destination_gestalt_id] {
|
||||
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!("member migration endpoint is not an active gestalt leaf"))?;
|
||||
if !profile
|
||||
.location_ids
|
||||
.contains(if gestalt_id == source_gestalt_id {
|
||||
&source.home_location_id
|
||||
} else {
|
||||
&destination.home_location_id
|
||||
})
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"member migration endpoint has incoherent location state"
|
||||
));
|
||||
}
|
||||
}
|
||||
let relation_exists = campaign.agency_relations.values().any(|relation| {
|
||||
relation.active
|
||||
&& relation.kind == AgencyRelationKind::Migration
|
||||
&& relation.from_subject_id == source_gestalt_id
|
||||
&& relation.to_subject_id == destination_gestalt_id
|
||||
});
|
||||
if !relation_exists {
|
||||
return Err(anyhow!(
|
||||
"member migration lacks an explicit source-to-destination migration relation"
|
||||
));
|
||||
}
|
||||
let origin = member
|
||||
.last_location_id
|
||||
.as_deref()
|
||||
.unwrap_or(&source.home_location_id);
|
||||
let reachable = origin == destination_location_id
|
||||
|| campaign.locations.get(origin).is_some_and(|location| {
|
||||
location.routes.values().any(|route| {
|
||||
route.destination_id == destination_location_id
|
||||
&& route.travel_minutes <= campaign.tick_hours.saturating_mul(60)
|
||||
})
|
||||
});
|
||||
if !reachable {
|
||||
return Err(anyhow!("member migration exceeds the strategic horizon"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn member_state_references(campaign: &Campaign, member_id: &str) -> Result<BTreeSet<String>> {
|
||||
let member = campaign
|
||||
.gestalt_members
|
||||
.get(member_id)
|
||||
.ok_or_else(|| anyhow!("gestalt member is unknown"))?;
|
||||
let gestalt = campaign
|
||||
.gestalts
|
||||
.get(&member.gestalt_id)
|
||||
.ok_or_else(|| anyhow!("gestalt member baseline is unknown"))?;
|
||||
let mut references = BTreeSet::from([
|
||||
format!("member:{member_id}"),
|
||||
format!("gestalt:{}", member.gestalt_id),
|
||||
format!(
|
||||
"location:{}",
|
||||
member
|
||||
.last_location_id
|
||||
.as_deref()
|
||||
.unwrap_or(&gestalt.home_location_id)
|
||||
),
|
||||
]);
|
||||
references.extend(
|
||||
effective_member_capabilities(campaign, member_id)?
|
||||
.into_iter()
|
||||
.map(|value| format!("capability:{value}")),
|
||||
);
|
||||
references.extend(
|
||||
effective_member_knowledge(campaign, member_id)?
|
||||
.into_iter()
|
||||
.map(|value| format!("knowledge:{value}")),
|
||||
);
|
||||
references.extend(
|
||||
member
|
||||
.equipment
|
||||
.iter()
|
||||
.map(|value| format!("resource:{value}")),
|
||||
);
|
||||
for relation in campaign.agency_relations.values().filter(|relation| {
|
||||
relation.active
|
||||
&& relation.kind == AgencyRelationKind::Migration
|
||||
&& relation.from_subject_id == member.gestalt_id
|
||||
}) {
|
||||
if let Some(destination) = campaign.gestalts.get(&relation.to_subject_id) {
|
||||
references.insert(format!("gestalt:{}", destination.id));
|
||||
references.insert(format!("location:{}", destination.home_location_id));
|
||||
}
|
||||
}
|
||||
Ok(references)
|
||||
}
|
||||
|
||||
pub fn effective_member_capabilities(
|
||||
campaign: &Campaign,
|
||||
member_id: &str,
|
||||
) -> Result<BTreeSet<String>> {
|
||||
let member = campaign
|
||||
.gestalt_members
|
||||
.get(member_id)
|
||||
.ok_or_else(|| anyhow!("gestalt member is unknown"))?;
|
||||
let gestalt = campaign
|
||||
.gestalts
|
||||
.get(&member.gestalt_id)
|
||||
.ok_or_else(|| anyhow!("gestalt member baseline is unknown"))?;
|
||||
Ok(gestalt
|
||||
.shared_capabilities
|
||||
.union(&member.capability_additions)
|
||||
.filter(|value| !member.capability_removals.contains(*value))
|
||||
.cloned()
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn effective_member_knowledge(
|
||||
campaign: &Campaign,
|
||||
member_id: &str,
|
||||
) -> Result<BTreeSet<String>> {
|
||||
let member = campaign
|
||||
.gestalt_members
|
||||
.get(member_id)
|
||||
.ok_or_else(|| anyhow!("gestalt member is unknown"))?;
|
||||
let gestalt = campaign
|
||||
.gestalts
|
||||
.get(&member.gestalt_id)
|
||||
.ok_or_else(|| anyhow!("gestalt member baseline is unknown"))?;
|
||||
Ok(gestalt
|
||||
.shared_knowledge
|
||||
.union(&member.knowledge_additions)
|
||||
.filter(|value| !member.knowledge_removals.contains(*value))
|
||||
.cloned()
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn subject_state_references(campaign: &Campaign, subject_id: &str) -> Result<BTreeSet<String>> {
|
||||
let profile = campaign
|
||||
.agency_profiles
|
||||
|
|
@ -1828,6 +2071,9 @@ fn proposal_target_key(effect: &StrategicCellEffect) -> String {
|
|||
}
|
||||
StrategicCellEffect::Gestalt { gestalt_id, .. } => format!("gestalt:{gestalt_id}"),
|
||||
StrategicCellEffect::ActorMove { actor_id, .. } => format!("actor:{actor_id}"),
|
||||
StrategicCellEffect::MemberMigration { member_id, .. } => {
|
||||
format!("member:{member_id}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -2335,6 +2581,133 @@ pub(crate) mod tests {
|
|||
assert!(validate_and_resolve_wave(&value, &make_wave(borrowed_secret)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rival_arena_preserves_named_member_agency_and_exact_private_state() {
|
||||
let mut value = campaign(0, 1);
|
||||
let gestalt = |id: &str, name: &str, knowledge: &[&str]| GestaltPersonaState {
|
||||
schema: "ghostlight.gestalt_persona_state.v1".into(),
|
||||
id: id.into(),
|
||||
name: name.into(),
|
||||
version: 0,
|
||||
home_location_id: "center".into(),
|
||||
shared_capabilities: BTreeSet::new(),
|
||||
shared_knowledge: knowledge.iter().map(|value| (*value).into()).collect(),
|
||||
resources: BTreeSet::new(),
|
||||
goals: vec![],
|
||||
pressures: vec![],
|
||||
};
|
||||
value.gestalts.insert(
|
||||
"refugees".into(),
|
||||
gestalt("refugees", "Transit refugees", &["camp schedule"]),
|
||||
);
|
||||
value.gestalts.insert(
|
||||
"dockers".into(),
|
||||
gestalt("dockers", "Dock residents", &["private dock code"]),
|
||||
);
|
||||
value.gestalt_members.insert(
|
||||
"mira".into(),
|
||||
GestaltMemberDelta {
|
||||
schema: "ghostlight.gestalt_member_delta.v1".into(),
|
||||
id: "mira".into(),
|
||||
gestalt_id: "refugees".into(),
|
||||
version: 1,
|
||||
name: "Mira".into(),
|
||||
capability_additions: BTreeSet::new(),
|
||||
capability_removals: BTreeSet::new(),
|
||||
knowledge_additions: BTreeSet::from(["the player helped me".into()]),
|
||||
knowledge_removals: BTreeSet::new(),
|
||||
equipment: BTreeSet::new(),
|
||||
conditions: BTreeSet::new(),
|
||||
obligations: BTreeSet::new(),
|
||||
relationships: BTreeMap::from([("player".into(), "trusted rescuer".into())]),
|
||||
goals: vec!["settle somewhere safe".into()],
|
||||
memories: vec!["escaped the fire with the player's help".into()],
|
||||
last_location_id: Some("center".into()),
|
||||
materialized_actor_id: None,
|
||||
last_relevant_revision: 1,
|
||||
relevance_lease_until_revision: 0,
|
||||
},
|
||||
);
|
||||
ensure_agency_profiles(&mut value);
|
||||
value.agency_relations.insert(
|
||||
"rivalry".into(),
|
||||
AgencyRelation {
|
||||
schema: "ghostlight.agency_relation.v1".into(),
|
||||
id: "rivalry".into(),
|
||||
from_subject_id: "refugees".into(),
|
||||
to_subject_id: "dockers".into(),
|
||||
kind: AgencyRelationKind::Rivalry,
|
||||
strength: 70,
|
||||
active: true,
|
||||
evidence_receipt_ids: vec![],
|
||||
},
|
||||
);
|
||||
value.agency_relations.insert(
|
||||
"migration".into(),
|
||||
AgencyRelation {
|
||||
schema: "ghostlight.agency_relation.v1".into(),
|
||||
id: "migration".into(),
|
||||
from_subject_id: "refugees".into(),
|
||||
to_subject_id: "dockers".into(),
|
||||
kind: AgencyRelationKind::Migration,
|
||||
strength: 90,
|
||||
active: true,
|
||||
evidence_receipt_ids: vec![],
|
||||
},
|
||||
);
|
||||
let demand = default_demand(&value, "resettlement under hostile pressure");
|
||||
let cover = plan_cover(&value, demand).unwrap();
|
||||
assert_eq!(cover.cells.len(), 1);
|
||||
assert_eq!(cover.cells[0].mode, SimulationCellMode::Arena);
|
||||
let proposal = CellActionProposal {
|
||||
subject_id: "member:mira".into(),
|
||||
intent: "take the offered berth".into(),
|
||||
intended_effect:
|
||||
"Mira joins the dock residents without speaking for either population.".into(),
|
||||
priority: 5,
|
||||
state_references: vec![
|
||||
"member:mira".into(),
|
||||
"knowledge:the player helped me".into(),
|
||||
],
|
||||
public_channels: vec![],
|
||||
effect: StrategicCellEffect::MemberMigration {
|
||||
member_id: "mira".into(),
|
||||
source_gestalt_id: "refugees".into(),
|
||||
destination_gestalt_id: "dockers".into(),
|
||||
destination_location_id: "center".into(),
|
||||
},
|
||||
};
|
||||
let make_wave = |proposal: CellActionProposal| 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![proposal],
|
||||
inaction_reason: None,
|
||||
}],
|
||||
cover: cover.clone(),
|
||||
model_receipt_hashes: vec![],
|
||||
};
|
||||
let plan = validate_and_resolve_wave(&value, &make_wave(proposal.clone())).unwrap();
|
||||
assert_eq!(plan.member_migrations.len(), 1);
|
||||
|
||||
let mut collective_theft = proposal.clone();
|
||||
collective_theft.subject_id = "refugees".into();
|
||||
assert!(validate_and_resolve_wave(&value, &make_wave(collective_theft)).is_err());
|
||||
|
||||
let mut borrowed_secret = proposal;
|
||||
borrowed_secret
|
||||
.state_references
|
||||
.push("knowledge:private dock code".into());
|
||||
assert!(validate_and_resolve_wave(&value, &make_wave(borrowed_secret)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fission_preserves_parent_and_member_delta_while_activating_child_leaves() {
|
||||
let mut value = campaign(1, 1);
|
||||
|
|
|
|||
|
|
@ -4,7 +4,10 @@ use crate::{
|
|||
SimulationCell,
|
||||
},
|
||||
model::{ModelPort, ModelStageOutput, ModelStageRequest, run_validated_stage},
|
||||
persona::{CellConstituentSlice, CellProjectionEngine, ExecutionPermit, PermittedCellSlice},
|
||||
persona::{
|
||||
CellConstituentSlice, CellMemberSlice, CellProjectionEngine, ExecutionPermit,
|
||||
PermittedCellSlice,
|
||||
},
|
||||
resolution::{
|
||||
cell_action_limit, default_demand, plan_cover, plan_receipt, validate_and_resolve_wave,
|
||||
validate_demand,
|
||||
|
|
@ -372,6 +375,7 @@ fn cell_slice(campaign: &Campaign, cell: &SimulationCell) -> Result<PermittedCel
|
|||
.map(|subject| &subject.capabilities)
|
||||
.collect(),
|
||||
);
|
||||
let member_exceptions = member_exceptions(campaign, cell)?;
|
||||
Ok(PermittedCellSlice {
|
||||
cell_id: cell.id.clone(),
|
||||
mode: cell.mode.clone(),
|
||||
|
|
@ -382,6 +386,7 @@ fn cell_slice(campaign: &Campaign, cell: &SimulationCell) -> Result<PermittedCel
|
|||
campaign.id, campaign.revision, campaign.resolution_policy.resolution_epoch, cell.id
|
||||
),
|
||||
constituents,
|
||||
member_exceptions,
|
||||
shared_knowledge,
|
||||
shared_capabilities,
|
||||
perceived_events: campaign
|
||||
|
|
@ -407,6 +412,161 @@ fn cell_slice(campaign: &Campaign, cell: &SimulationCell) -> Result<PermittedCel
|
|||
})
|
||||
}
|
||||
|
||||
fn member_exceptions(campaign: &Campaign, cell: &SimulationCell) -> Result<Vec<CellMemberSlice>> {
|
||||
let player_id = &campaign.player_actor_id;
|
||||
let mut candidates = campaign
|
||||
.gestalt_members
|
||||
.values()
|
||||
.filter(|member| {
|
||||
member.materialized_actor_id.is_none() && cell.subject_ids.contains(&member.gestalt_id)
|
||||
})
|
||||
.filter_map(|member| {
|
||||
let source = campaign.gestalts.get(&member.gestalt_id)?;
|
||||
let origin = member
|
||||
.last_location_id
|
||||
.clone()
|
||||
.unwrap_or_else(|| source.home_location_id.clone());
|
||||
let destinations = migration_destinations(campaign, &member.gestalt_id, &origin);
|
||||
if destinations.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let player_relationship = member.relationships.contains_key(player_id) as u8;
|
||||
let personal_pressure = (!member.conditions.is_empty()
|
||||
|| !member.obligations.is_empty()
|
||||
|| !member.goals.is_empty()) as u8;
|
||||
Some((
|
||||
player_relationship,
|
||||
personal_pressure,
|
||||
member.last_relevant_revision,
|
||||
member.id.clone(),
|
||||
origin,
|
||||
destinations,
|
||||
))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
candidates.sort_by(|left, right| {
|
||||
right
|
||||
.0
|
||||
.cmp(&left.0)
|
||||
.then_with(|| right.1.cmp(&left.1))
|
||||
.then_with(|| right.2.cmp(&left.2))
|
||||
.then_with(|| left.3.cmp(&right.3))
|
||||
});
|
||||
candidates
|
||||
.into_iter()
|
||||
.take(cell_action_limit(cell).min(4))
|
||||
.map(|(_, _, _, member_id, origin, destinations)| {
|
||||
let member = &campaign.gestalt_members[&member_id];
|
||||
let source = &campaign.gestalts[&member.gestalt_id];
|
||||
let capabilities = overlay(
|
||||
&source.shared_capabilities,
|
||||
&member.capability_additions,
|
||||
&member.capability_removals,
|
||||
);
|
||||
let knowledge = overlay(
|
||||
&source.shared_knowledge,
|
||||
&member.knowledge_additions,
|
||||
&member.knowledge_removals,
|
||||
);
|
||||
let goals = if member.goals.is_empty() {
|
||||
source.goals.clone()
|
||||
} else {
|
||||
member.goals.clone()
|
||||
};
|
||||
let mut permitted_state_references = BTreeSet::from([
|
||||
format!("member:{}", member.id),
|
||||
format!("gestalt:{}", member.gestalt_id),
|
||||
format!("location:{origin}"),
|
||||
]);
|
||||
permitted_state_references.extend(
|
||||
capabilities
|
||||
.iter()
|
||||
.map(|value| format!("capability:{value}")),
|
||||
);
|
||||
permitted_state_references
|
||||
.extend(knowledge.iter().map(|value| format!("knowledge:{value}")));
|
||||
permitted_state_references.extend(
|
||||
member
|
||||
.equipment
|
||||
.iter()
|
||||
.map(|value| format!("resource:{value}")),
|
||||
);
|
||||
for (gestalt_id, location_id) in &destinations {
|
||||
permitted_state_references.insert(format!("gestalt:{gestalt_id}"));
|
||||
permitted_state_references.insert(format!("location:{location_id}"));
|
||||
}
|
||||
Ok(CellMemberSlice {
|
||||
subject_id: format!("member:{}", member.id),
|
||||
member_id: member.id.clone(),
|
||||
name: member.name.clone(),
|
||||
source_gestalt_id: member.gestalt_id.clone(),
|
||||
source_location_id: origin,
|
||||
knowledge: knowledge.clone(),
|
||||
capabilities,
|
||||
resources: member.equipment.clone(),
|
||||
information_channels: knowledge,
|
||||
permitted_state_references,
|
||||
migration_destinations: destinations,
|
||||
goals,
|
||||
pressures: member
|
||||
.conditions
|
||||
.iter()
|
||||
.chain(&member.obligations)
|
||||
.cloned()
|
||||
.collect(),
|
||||
relationships: member.relationships.clone(),
|
||||
memories: member.memories.clone(),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn migration_destinations(
|
||||
campaign: &Campaign,
|
||||
source_gestalt_id: &str,
|
||||
origin_location_id: &str,
|
||||
) -> BTreeMap<String, String> {
|
||||
campaign
|
||||
.agency_relations
|
||||
.values()
|
||||
.filter(|relation| {
|
||||
relation.active
|
||||
&& relation.kind == crate::domain::AgencyRelationKind::Migration
|
||||
&& relation.from_subject_id == source_gestalt_id
|
||||
})
|
||||
.filter_map(|relation| {
|
||||
let destination = campaign.gestalts.get(&relation.to_subject_id)?;
|
||||
let profile = campaign.agency_profiles.get(&destination.id)?;
|
||||
if !profile.active_leaf || !profile.simulation_eligible {
|
||||
return None;
|
||||
}
|
||||
let reachable = origin_location_id == destination.home_location_id
|
||||
|| campaign
|
||||
.locations
|
||||
.get(origin_location_id)
|
||||
.is_some_and(|location| {
|
||||
location.routes.values().any(|route| {
|
||||
route.destination_id == destination.home_location_id
|
||||
&& route.travel_minutes <= campaign.tick_hours.saturating_mul(60)
|
||||
})
|
||||
});
|
||||
reachable.then(|| (destination.id.clone(), destination.home_location_id.clone()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn overlay(
|
||||
baseline: &BTreeSet<String>,
|
||||
additions: &BTreeSet<String>,
|
||||
removals: &BTreeSet<String>,
|
||||
) -> BTreeSet<String> {
|
||||
baseline
|
||||
.union(additions)
|
||||
.filter(|value| !removals.contains(*value))
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn constituent_slice(campaign: &Campaign, id: &str) -> Result<CellConstituentSlice> {
|
||||
let profile = campaign
|
||||
.agency_profiles
|
||||
|
|
@ -609,6 +769,100 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_slice_projects_only_actionable_salient_member_exceptions() {
|
||||
use crate::domain::*;
|
||||
let mut campaign = crate::resolution::tests::campaign(0, 1);
|
||||
let gestalt = |id: &str, name: &str| GestaltPersonaState {
|
||||
schema: "ghostlight.gestalt_persona_state.v1".into(),
|
||||
id: id.into(),
|
||||
name: name.into(),
|
||||
version: 0,
|
||||
home_location_id: "center".into(),
|
||||
shared_capabilities: BTreeSet::new(),
|
||||
shared_knowledge: BTreeSet::new(),
|
||||
resources: BTreeSet::new(),
|
||||
goals: vec![],
|
||||
pressures: vec![],
|
||||
};
|
||||
campaign
|
||||
.gestalts
|
||||
.insert("refugees".into(), gestalt("refugees", "Refugees"));
|
||||
campaign
|
||||
.gestalts
|
||||
.insert("neighbors".into(), gestalt("neighbors", "Neighbors"));
|
||||
let member = |id: &str, player_relationship: bool| GestaltMemberDelta {
|
||||
schema: "ghostlight.gestalt_member_delta.v1".into(),
|
||||
id: id.into(),
|
||||
gestalt_id: "refugees".into(),
|
||||
version: 1,
|
||||
name: id.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: if player_relationship {
|
||||
BTreeMap::from([("player".into(), "trusted rescuer".into())])
|
||||
} else {
|
||||
BTreeMap::new()
|
||||
},
|
||||
goals: vec!["find a home".into()],
|
||||
memories: vec![],
|
||||
last_location_id: Some("center".into()),
|
||||
materialized_actor_id: None,
|
||||
last_relevant_revision: 1,
|
||||
relevance_lease_until_revision: 0,
|
||||
};
|
||||
campaign
|
||||
.gestalt_members
|
||||
.insert("mira".into(), member("mira", true));
|
||||
campaign
|
||||
.gestalt_members
|
||||
.insert("other".into(), member("other", false));
|
||||
crate::resolution::ensure_agency_profiles(&mut campaign);
|
||||
campaign.agency_relations.insert(
|
||||
"migration".into(),
|
||||
AgencyRelation {
|
||||
schema: "ghostlight.agency_relation.v1".into(),
|
||||
id: "migration".into(),
|
||||
from_subject_id: "refugees".into(),
|
||||
to_subject_id: "neighbors".into(),
|
||||
kind: AgencyRelationKind::Migration,
|
||||
strength: 90,
|
||||
active: true,
|
||||
evidence_receipt_ids: vec![],
|
||||
},
|
||||
);
|
||||
let cover = crate::resolution::plan_cover(
|
||||
&campaign,
|
||||
crate::resolution::default_demand(&campaign, "resettlement"),
|
||||
)
|
||||
.unwrap();
|
||||
let slice = cell_slice(&campaign, &cover.cells[0]).unwrap();
|
||||
assert_eq!(slice.member_exceptions.len(), 2);
|
||||
assert_eq!(slice.member_exceptions[0].member_id, "mira");
|
||||
assert_eq!(
|
||||
slice.member_exceptions[0]
|
||||
.migration_destinations
|
||||
.get("neighbors")
|
||||
.map(String::as_str),
|
||||
Some("center")
|
||||
);
|
||||
assert!(
|
||||
slice.member_exceptions[0]
|
||||
.permitted_state_references
|
||||
.contains("member:mira")
|
||||
);
|
||||
assert!(
|
||||
!serde_json::to_string(&slice)
|
||||
.unwrap()
|
||||
.contains("private dock code")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn every_selected_cell_runs_one_membrane_pipeline() {
|
||||
let mut campaign = crate::resolution::tests::campaign(6, 2);
|
||||
|
|
|
|||
Loading…
Reference in a new issue