Admit playable destination populations
This commit is contained in:
parent
13c386f6d1
commit
837cf512c1
6 changed files with 909 additions and 33 deletions
|
|
@ -551,9 +551,42 @@ struct CompiledExpansionSeed {
|
|||
origin_routes: Vec<CompiledRoute>,
|
||||
locations: Vec<CompiledLocation>,
|
||||
facts: Vec<WorldFact>,
|
||||
#[serde(default)]
|
||||
#[schemars(length(max = 8))]
|
||||
populations: Vec<CompiledDestinationPopulation>,
|
||||
#[serde(default)]
|
||||
#[schemars(length(max = 32))]
|
||||
migration_relations: Vec<CompiledDestinationMigrationRelation>,
|
||||
gaps: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
struct CompiledDestinationPopulation {
|
||||
id: String,
|
||||
name: String,
|
||||
home_location_id: String,
|
||||
shared_capabilities: BTreeSet<String>,
|
||||
/// Exact IDs from this expansion's `facts`. The compiler resolves them to
|
||||
/// statements after validation so a population cannot acquire unsupported
|
||||
/// free-text knowledge during admission.
|
||||
shared_fact_ids: BTreeSet<String>,
|
||||
resources: BTreeSet<String>,
|
||||
goals: Vec<String>,
|
||||
pressures: Vec<String>,
|
||||
collective_authority_id: Option<String>,
|
||||
facets: CompiledAgencyFacets,
|
||||
information_channels: BTreeSet<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
struct CompiledDestinationMigrationRelation {
|
||||
id: String,
|
||||
from_gestalt_id: String,
|
||||
to_gestalt_id: String,
|
||||
#[schemars(range(min = 1, max = 100))]
|
||||
strength: u8,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
struct CompiledFissionSeed {
|
||||
children: Vec<GestaltPersonaState>,
|
||||
|
|
@ -1493,14 +1526,54 @@ impl WorldCompiler {
|
|||
.retrieve_all(&queries, &campaign.branch_origin.canon_cutoff, 10)
|
||||
.await?;
|
||||
let snapshot = format!("campaign:{}:revision:{}", campaign.id, campaign.revision);
|
||||
let source_population_ids = campaign
|
||||
.gestalts
|
||||
.values()
|
||||
.filter(|gestalt| {
|
||||
gestalt.home_location_id == origin_location_id
|
||||
&& campaign
|
||||
.agency_profiles
|
||||
.get(&gestalt.id)
|
||||
.is_some_and(|profile| profile.active_leaf)
|
||||
})
|
||||
.map(|gestalt| gestalt.id.clone())
|
||||
.collect::<BTreeSet<_>>();
|
||||
let origin_population_context = campaign
|
||||
.gestalts
|
||||
.values()
|
||||
.filter(|gestalt| source_population_ids.contains(&gestalt.id))
|
||||
.map(|gestalt| {
|
||||
serde_json::json!({
|
||||
"id":gestalt.id,
|
||||
"name":gestalt.name,
|
||||
"home_location_id":gestalt.home_location_id,
|
||||
"goals":gestalt.goals,
|
||||
"pressures":gestalt.pressures,
|
||||
"named_members":campaign.gestalt_members.values()
|
||||
.filter(|member| member.gestalt_id == gestalt.id
|
||||
&& member.materialized_actor_id.is_none()
|
||||
&& member.last_location_id.as_deref().unwrap_or(&gestalt.home_location_id) == origin_location_id)
|
||||
.map(|member| serde_json::json!({
|
||||
"id":member.id,
|
||||
"name":member.name,
|
||||
"goals":member.goals,
|
||||
"obligations":member.obligations,
|
||||
"memories":member.memories,
|
||||
}))
|
||||
.collect::<Vec<_>>(),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let base_prompt = format!(
|
||||
"Compile only the requested bounded destination region. Every new location id must be new. Return explicit origin_routes records owned by origin id {} into the new region, and give every such destination a reciprocal route record back to the origin with the same positive travel time. Every route record needs a stable route_id local to its exact origin, an exact destination_id, a distance, and positive travel_minutes; the same local route_id may exist under another origin without naming the same route. Do not rewrite existing geography. Every place has a non-empty name, valid container, and concrete persistent features. Any locally observable clue must already exist as a fact and list exact discoverable_at_location_ids from the combined existing and new topology; later action assessment can reveal facts but cannot invent them. CAMPAIGN LOCATIONS:\n{}\nREQUEST:\n{}\nEVIDENCE:\n{}",
|
||||
"Compile only the requested bounded destination region. Every new location id must be new. Return explicit origin_routes records owned by origin id {} into the new region, and give every such destination a reciprocal route record back to the origin with the same positive travel time. Every route record needs a stable route_id local to its exact origin, an exact destination_id, a distance, and positive travel_minutes; the same local route_id may exist under another origin without naming the same route. Do not rewrite existing geography. Every place has a non-empty name, valid container, and concrete persistent features. Any locally observable clue must already exist as a fact and list exact discoverable_at_location_ids from the combined existing and new topology; later action assessment can reveal facts but cannot invent them.\n\nA playable inhabited destination also needs one to eight non-overlapping destination population leaves. Synthesize reversible branch-local names, capabilities, resources, goals, pressures, six-axis agency facets, and concrete information channels even when canon does not specify settlement-scale detail; record the unsupported canon detail in gaps rather than withholding the playable population. Each population home_location_id must be one new location. shared_fact_ids may contain only exact fact IDs returned in this same candidate, never free-text knowledge. collective_authority_id may be null or the exact ID of one new population and denotes real shared authority.\n\nA migration relation is a directed available path for a later voluntary strategic choice; it does not move anyone, establish that admission occurred, or erase destination-community agency. It may originate only from one exact co-located active population ID supplied below and may target only one new population ID. Emit a relation only when the request and supplied source population/member goals support that migration possibility. Never invent a source population or named member. The approval preview must make all branch-local assumptions and unresolved admission or capacity questions explicit.\n\nCAMPAIGN LOCATIONS:\n{}\nCO-LOCATED SOURCE POPULATIONS AND NAMED MEMBER DELTAS:\n{}\nREQUEST:\n{}\nEVIDENCE:\n{}",
|
||||
origin_location_id,
|
||||
serde_json::to_string(&campaign.locations)?,
|
||||
serde_json::to_string(&origin_population_context)?,
|
||||
destination_request,
|
||||
evidence_text(&receipts)
|
||||
);
|
||||
let schema = serde_json::to_value(schema_for!(CompiledExpansionSeed))?;
|
||||
let mut schema = serde_json::to_value(schema_for!(CompiledExpansionSeed))?;
|
||||
constrain_destination_expansion_schema(&mut schema, &source_population_ids)?;
|
||||
let sources = receipt_ids(&receipts);
|
||||
let mut compiler_receipts = Vec::new();
|
||||
let mut correction = String::new();
|
||||
|
|
@ -1516,6 +1589,72 @@ impl WorldCompiler {
|
|||
.await?;
|
||||
compiler_receipts.push(output.1);
|
||||
let seed: CompiledExpansionSeed = serde_json::from_value(output.0)?;
|
||||
let fact_statements = seed
|
||||
.facts
|
||||
.iter()
|
||||
.map(|fact| (fact.id.as_str(), fact.statement.as_str()))
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
let populations = seed
|
||||
.populations
|
||||
.iter()
|
||||
.map(|population| {
|
||||
let shared_knowledge = population
|
||||
.shared_fact_ids
|
||||
.iter()
|
||||
.map(|fact_id| {
|
||||
fact_statements.get(fact_id.as_str()).map(|value| (*value).to_owned())
|
||||
.ok_or_else(|| anyhow!("destination population {} references unknown shared fact {fact_id}", population.id))
|
||||
})
|
||||
.collect::<Result<BTreeSet<_>>>()?;
|
||||
Ok(GestaltPersonaState {
|
||||
schema: "ghostlight.gestalt_persona_state.v1".into(),
|
||||
id: population.id.clone(),
|
||||
name: population.name.clone(),
|
||||
version: 0,
|
||||
home_location_id: population.home_location_id.clone(),
|
||||
shared_capabilities: population.shared_capabilities.clone(),
|
||||
shared_knowledge,
|
||||
resources: population.resources.clone(),
|
||||
goals: population.goals.clone(),
|
||||
pressures: population.pressures.clone(),
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let population_profiles = seed
|
||||
.populations
|
||||
.iter()
|
||||
.map(|population| AgencyProfile {
|
||||
schema: "ghostlight.agency_profile.v1".into(),
|
||||
id: format!("agency:{}", population.id),
|
||||
subject_id: population.id.clone(),
|
||||
subject_kind: AgencySubjectKind::Gestalt,
|
||||
profile_version: 0,
|
||||
collective_authority_id: population.collective_authority_id.clone(),
|
||||
parent_subject_id: None,
|
||||
active_leaf: true,
|
||||
simulation_eligible: true,
|
||||
facets: population.facets.clone().into_map(),
|
||||
location_ids: BTreeSet::from([population.home_location_id.clone()]),
|
||||
information_channels: population.information_channels.clone(),
|
||||
detail_debt: 0,
|
||||
last_detail_tick: campaign.strategic_tick_count,
|
||||
evidence_receipt_ids: sources.clone(),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let migration_relations = seed
|
||||
.migration_relations
|
||||
.iter()
|
||||
.map(|relation| AgencyRelation {
|
||||
schema: "ghostlight.agency_relation.v1".into(),
|
||||
id: relation.id.clone(),
|
||||
from_subject_id: relation.from_gestalt_id.clone(),
|
||||
to_subject_id: relation.to_gestalt_id.clone(),
|
||||
kind: AgencyRelationKind::Migration,
|
||||
strength: relation.strength,
|
||||
active: true,
|
||||
evidence_receipt_ids: sources.clone(),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let expansion = crate::domain::RegionExpansion {
|
||||
origin_location_id: origin_location_id.into(),
|
||||
origin_routes: compiled_route_map(seed.origin_routes.clone(), origin_location_id)?,
|
||||
|
|
@ -1526,6 +1665,9 @@ impl WorldCompiler {
|
|||
.map(CompiledLocation::into_location)
|
||||
.collect::<Result<Vec<_>>>()?,
|
||||
facts: seed.facts.clone(),
|
||||
populations,
|
||||
population_profiles,
|
||||
migration_relations,
|
||||
};
|
||||
match validate_region_expansion(campaign, &expansion) {
|
||||
Ok(()) => break (seed, expansion),
|
||||
|
|
@ -2489,6 +2631,27 @@ fn constrain_private_relationship_actor_schema(
|
|||
Ok(())
|
||||
}
|
||||
|
||||
fn constrain_destination_expansion_schema(
|
||||
schema: &mut serde_json::Value,
|
||||
source_population_ids: &BTreeSet<String>,
|
||||
) -> Result<()> {
|
||||
if source_population_ids.is_empty() {
|
||||
let relations = schema
|
||||
.pointer_mut("/properties/migration_relations")
|
||||
.ok_or_else(|| anyhow!("destination schema has no migration_relations property"))?;
|
||||
relations["maxItems"] = serde_json::json!(0);
|
||||
return Ok(());
|
||||
}
|
||||
let relation = schema
|
||||
.pointer_mut("/$defs/CompiledDestinationMigrationRelation")
|
||||
.ok_or_else(|| anyhow!("destination schema has no migration relation definition"))?;
|
||||
relation["properties"]["from_gestalt_id"] = serde_json::json!({
|
||||
"type":"string",
|
||||
"enum":source_population_ids.iter().cloned().collect::<Vec<_>>()
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_required_relationship_actors(
|
||||
campaign: &Campaign,
|
||||
anchors: &[RequiredRelationshipActor],
|
||||
|
|
@ -3216,6 +3379,182 @@ pub fn validate_region_expansion(
|
|||
));
|
||||
}
|
||||
}
|
||||
let population_ids = expansion
|
||||
.populations
|
||||
.iter()
|
||||
.map(|population| population.id.as_str())
|
||||
.collect::<BTreeSet<_>>();
|
||||
if expansion.populations.len() > 8
|
||||
|| population_ids.len() != expansion.populations.len()
|
||||
|| population_ids.iter().any(|id| {
|
||||
id.trim().is_empty()
|
||||
|| campaign.gestalts.contains_key(*id)
|
||||
|| campaign.actors.contains_key(*id)
|
||||
|| campaign.institutions.contains_key(*id)
|
||||
})
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"destination populations need at most eight unique new canonical subject IDs"
|
||||
));
|
||||
}
|
||||
let profile_ids = expansion
|
||||
.population_profiles
|
||||
.iter()
|
||||
.map(|profile| profile.subject_id.as_str())
|
||||
.collect::<BTreeSet<_>>();
|
||||
if profile_ids != population_ids
|
||||
|| expansion.population_profiles.len() != expansion.populations.len()
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"destination population profiles must cover every new population exactly once"
|
||||
));
|
||||
}
|
||||
let axes = BTreeSet::from([
|
||||
AgencyAxis::Geography,
|
||||
AgencyAxis::Ideology,
|
||||
AgencyAxis::Authority,
|
||||
AgencyAxis::EconomyRole,
|
||||
AgencyAxis::SpeciesBody,
|
||||
AgencyAxis::Information,
|
||||
]);
|
||||
for population in &expansion.populations {
|
||||
if population.schema != "ghostlight.gestalt_persona_state.v1"
|
||||
|| population.version != 0
|
||||
|| population.name.trim().is_empty()
|
||||
|| !new_ids.contains(population.home_location_id.as_str())
|
||||
|| population.goals.is_empty()
|
||||
|| population
|
||||
.shared_capabilities
|
||||
.iter()
|
||||
.chain(population.shared_knowledge.iter())
|
||||
.chain(population.resources.iter())
|
||||
.chain(population.goals.iter())
|
||||
.chain(population.pressures.iter())
|
||||
.any(|value| value.trim().is_empty())
|
||||
|| population
|
||||
.shared_knowledge
|
||||
.iter()
|
||||
.any(|statement| !fact_statements.contains(statement))
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"destination population {} has malformed or unsupported canonical state",
|
||||
population.id
|
||||
));
|
||||
}
|
||||
let profile = expansion
|
||||
.population_profiles
|
||||
.iter()
|
||||
.find(|profile| profile.subject_id == population.id)
|
||||
.expect("profile coverage was checked above");
|
||||
let profile_axes = profile.facets.keys().cloned().collect::<BTreeSet<_>>();
|
||||
if profile.schema != "ghostlight.agency_profile.v1"
|
||||
|| profile.id != format!("agency:{}", population.id)
|
||||
|| profile.subject_kind != AgencySubjectKind::Gestalt
|
||||
|| profile.profile_version != 0
|
||||
|| profile.parent_subject_id.is_some()
|
||||
|| !profile.active_leaf
|
||||
|| !profile.simulation_eligible
|
||||
|| profile.location_ids != BTreeSet::from([population.home_location_id.clone()])
|
||||
|| profile_axes != axes
|
||||
|| profile
|
||||
.collective_authority_id
|
||||
.as_ref()
|
||||
.is_some_and(|authority| !population_ids.contains(authority.as_str()))
|
||||
|| profile
|
||||
.information_channels
|
||||
.iter()
|
||||
.any(|channel| !crate::resolution::information_channel_is_concrete(channel))
|
||||
|| profile
|
||||
.information_channels
|
||||
.intersection(&population.shared_knowledge)
|
||||
.next()
|
||||
.is_some()
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"destination population {} has a malformed agency profile",
|
||||
population.id
|
||||
));
|
||||
}
|
||||
}
|
||||
let mut relation_ids = BTreeSet::new();
|
||||
for relation in &expansion.migration_relations {
|
||||
let source_is_exact_origin_leaf = campaign
|
||||
.gestalts
|
||||
.get(&relation.from_subject_id)
|
||||
.is_some_and(|source| source.home_location_id == expansion.origin_location_id)
|
||||
&& campaign
|
||||
.agency_profiles
|
||||
.get(&relation.from_subject_id)
|
||||
.is_some_and(|profile| {
|
||||
profile.subject_kind == AgencySubjectKind::Gestalt
|
||||
&& profile.active_leaf
|
||||
&& profile.simulation_eligible
|
||||
});
|
||||
if expansion.migration_relations.len() > 32
|
||||
|| relation.schema != "ghostlight.agency_relation.v1"
|
||||
|| relation.id.trim().is_empty()
|
||||
|| !relation_ids.insert(relation.id.as_str())
|
||||
|| campaign.agency_relations.contains_key(&relation.id)
|
||||
|| relation.kind != AgencyRelationKind::Migration
|
||||
|| !relation.active
|
||||
|| relation.strength == 0
|
||||
|| relation.strength > 100
|
||||
|| relation.from_subject_id == relation.to_subject_id
|
||||
|| !source_is_exact_origin_leaf
|
||||
|| !population_ids.contains(relation.to_subject_id.as_str())
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"destination migration relation {} is not an exact origin-leaf to new-population edge",
|
||||
relation.id
|
||||
));
|
||||
}
|
||||
}
|
||||
if !expansion.migration_relations.is_empty() {
|
||||
let mut candidate = campaign.clone();
|
||||
for location in &expansion.locations {
|
||||
candidate
|
||||
.locations
|
||||
.insert(location.id.clone(), location.clone());
|
||||
}
|
||||
candidate
|
||||
.locations
|
||||
.get_mut(&expansion.origin_location_id)
|
||||
.expect("origin was checked above")
|
||||
.routes
|
||||
.extend(expansion.origin_routes.clone());
|
||||
for population in &expansion.populations {
|
||||
candidate
|
||||
.gestalts
|
||||
.insert(population.id.clone(), population.clone());
|
||||
}
|
||||
for profile in &expansion.population_profiles {
|
||||
candidate
|
||||
.agency_profiles
|
||||
.insert(profile.subject_id.clone(), profile.clone());
|
||||
}
|
||||
for relation in &expansion.migration_relations {
|
||||
candidate
|
||||
.agency_relations
|
||||
.insert(relation.id.clone(), relation.clone());
|
||||
let destination = candidate
|
||||
.gestalts
|
||||
.get(&relation.to_subject_id)
|
||||
.expect("migration target was checked above");
|
||||
if crate::resolution::route_travel_minutes_within(
|
||||
&candidate,
|
||||
&expansion.origin_location_id,
|
||||
&destination.home_location_id,
|
||||
campaign.tick_hours.saturating_mul(60),
|
||||
)
|
||||
.is_none()
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"destination migration relation {} exceeds the strategic travel horizon",
|
||||
relation.id
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -6355,6 +6694,9 @@ mod tests {
|
|||
persistent_features: vec!["sealed gate".into()],
|
||||
}],
|
||||
facts: vec![],
|
||||
populations: vec![],
|
||||
population_profiles: vec![],
|
||||
migration_relations: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -6392,6 +6734,134 @@ mod tests {
|
|||
validate_region_expansion(&campaign, &expansion).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inhabited_expansion_admits_only_reachable_population_migration_edges() {
|
||||
let mut campaign = crate::resolution::tests::campaign(0, 1);
|
||||
campaign.gestalts.insert(
|
||||
"refugees".into(),
|
||||
GestaltPersonaState {
|
||||
schema: "ghostlight.gestalt_persona_state.v1".into(),
|
||||
id: "refugees".into(),
|
||||
name: "Refugees".into(),
|
||||
version: 0,
|
||||
home_location_id: "center".into(),
|
||||
shared_capabilities: BTreeSet::new(),
|
||||
shared_knowledge: BTreeSet::new(),
|
||||
resources: BTreeSet::new(),
|
||||
goals: vec!["find voluntary settlement".into()],
|
||||
pressures: vec![],
|
||||
},
|
||||
);
|
||||
crate::resolution::ensure_agency_profiles(&mut campaign);
|
||||
let mut expansion = valid_region_expansion();
|
||||
expansion.locations[0].id = "pass".into();
|
||||
expansion.locations[0].name = "Ridge Pass".into();
|
||||
expansion.locations[0].routes = BTreeMap::from([
|
||||
(
|
||||
"back".into(),
|
||||
Route {
|
||||
destination_id: "center".into(),
|
||||
distance: "near".into(),
|
||||
travel_minutes: 10,
|
||||
},
|
||||
),
|
||||
(
|
||||
"onward".into(),
|
||||
Route {
|
||||
destination_id: "village".into(),
|
||||
distance: "near".into(),
|
||||
travel_minutes: 10,
|
||||
},
|
||||
),
|
||||
]);
|
||||
expansion
|
||||
.origin_routes
|
||||
.values_mut()
|
||||
.next()
|
||||
.unwrap()
|
||||
.destination_id = "pass".into();
|
||||
expansion.locations.push(Location {
|
||||
id: "village".into(),
|
||||
name: "Ridge Village".into(),
|
||||
container_id: None,
|
||||
routes: BTreeMap::from([(
|
||||
"return".into(),
|
||||
Route {
|
||||
destination_id: "pass".into(),
|
||||
distance: "near".into(),
|
||||
travel_minutes: 10,
|
||||
},
|
||||
)]),
|
||||
persistent_features: vec!["assembly hall".into()],
|
||||
});
|
||||
let statement = "The ridge assembly governs voluntary admission.".to_owned();
|
||||
expansion.facts.push(WorldFact {
|
||||
id: "ridge-admission".into(),
|
||||
statement: statement.clone(),
|
||||
scope: FactScope::ProvisionalLocal,
|
||||
evidence_receipt_ids: vec![],
|
||||
discoverable_at_location_ids: BTreeSet::from(["village".into()]),
|
||||
});
|
||||
expansion.populations.push(GestaltPersonaState {
|
||||
schema: "ghostlight.gestalt_persona_state.v1".into(),
|
||||
id: "ridge-households".into(),
|
||||
name: "Ridge Households".into(),
|
||||
version: 0,
|
||||
home_location_id: "village".into(),
|
||||
shared_capabilities: BTreeSet::from(["communal agriculture".into()]),
|
||||
shared_knowledge: BTreeSet::from([statement]),
|
||||
resources: BTreeSet::from(["shared kitchen".into()]),
|
||||
goals: vec!["admit newcomers without surrendering local consent".into()],
|
||||
pressures: vec!["winter capacity is finite".into()],
|
||||
});
|
||||
expansion.population_profiles.push(AgencyProfile {
|
||||
schema: "ghostlight.agency_profile.v1".into(),
|
||||
id: "agency:ridge-households".into(),
|
||||
subject_id: "ridge-households".into(),
|
||||
subject_kind: AgencySubjectKind::Gestalt,
|
||||
profile_version: 0,
|
||||
collective_authority_id: Some("ridge-households".into()),
|
||||
parent_subject_id: None,
|
||||
active_leaf: true,
|
||||
simulation_eligible: true,
|
||||
facets: BTreeMap::from([
|
||||
(AgencyAxis::Geography, BTreeSet::from(["ridge".into()])),
|
||||
(AgencyAxis::Ideology, BTreeSet::from(["consent".into()])),
|
||||
(AgencyAxis::Authority, BTreeSet::from(["assembly".into()])),
|
||||
(
|
||||
AgencyAxis::EconomyRole,
|
||||
BTreeSet::from(["agriculture".into()]),
|
||||
),
|
||||
(AgencyAxis::SpeciesBody, BTreeSet::from(["mixed".into()])),
|
||||
(AgencyAxis::Information, BTreeSet::from(["local".into()])),
|
||||
]),
|
||||
location_ids: BTreeSet::from(["village".into()]),
|
||||
information_channels: BTreeSet::from(["village assembly bulletin".into()]),
|
||||
detail_debt: 0,
|
||||
last_detail_tick: 0,
|
||||
evidence_receipt_ids: vec![],
|
||||
});
|
||||
expansion.migration_relations.push(AgencyRelation {
|
||||
schema: "ghostlight.agency_relation.v1".into(),
|
||||
id: "migration:refugees:ridge".into(),
|
||||
from_subject_id: "refugees".into(),
|
||||
to_subject_id: "ridge-households".into(),
|
||||
kind: AgencyRelationKind::Migration,
|
||||
strength: 50,
|
||||
active: true,
|
||||
evidence_receipt_ids: vec![],
|
||||
});
|
||||
|
||||
validate_region_expansion(&campaign, &expansion).unwrap();
|
||||
expansion.locations[0].routes.remove("onward");
|
||||
assert!(
|
||||
validate_region_expansion(&campaign, &expansion)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("strategic travel horizon")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn region_expansion_rejects_containment_cycles() {
|
||||
let campaign = crate::resolution::tests::campaign(0, 1);
|
||||
|
|
|
|||
|
|
@ -1084,6 +1084,21 @@ pub struct RegionExpansion {
|
|||
pub origin_routes: BTreeMap<String, Route>,
|
||||
pub locations: Vec<Location>,
|
||||
pub facts: Vec<WorldFact>,
|
||||
/// Optional population leaves that make an inhabited destination part of
|
||||
/// the agency graph. Destination compilation admits these subjects; it
|
||||
/// never moves an existing population or named member into them.
|
||||
#[serde(default)]
|
||||
pub populations: Vec<GestaltPersonaState>,
|
||||
/// Exact agency inputs for `populations`. Keeping these in the approved
|
||||
/// expansion makes the resolution cover reproducible without making the
|
||||
/// cover itself canonical.
|
||||
#[serde(default)]
|
||||
pub population_profiles: Vec<AgencyProfile>,
|
||||
/// Directed population routes admitted with the destination. A migration
|
||||
/// remains a later strategic choice validated against one of these exact
|
||||
/// relations and the physical topology.
|
||||
#[serde(default)]
|
||||
pub migration_relations: Vec<AgencyRelation>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
|
|
|
|||
|
|
@ -1137,6 +1137,16 @@ fn execute(
|
|||
fact.evidence_receipt_ids
|
||||
.iter()
|
||||
.any(|id| !supplied_evidence.contains(id.as_str()))
|
||||
}) || expansion.population_profiles.iter().any(|profile| {
|
||||
profile
|
||||
.evidence_receipt_ids
|
||||
.iter()
|
||||
.any(|id| !supplied_evidence.contains(id.as_str()))
|
||||
}) || expansion.migration_relations.iter().any(|relation| {
|
||||
relation
|
||||
.evidence_receipt_ids
|
||||
.iter()
|
||||
.any(|id| !supplied_evidence.contains(id.as_str()))
|
||||
}) || canon_candidates.iter().any(|candidate| {
|
||||
candidate
|
||||
.evidence_receipt_ids
|
||||
|
|
@ -5918,6 +5928,9 @@ mod tests {
|
|||
evidence_receipt_ids: vec![evidence.id.clone()],
|
||||
discoverable_at_location_ids: BTreeSet::from(["annex".into()]),
|
||||
}],
|
||||
populations: vec![],
|
||||
population_profiles: vec![],
|
||||
migration_relations: vec![],
|
||||
},
|
||||
evidence_receipts: vec![evidence],
|
||||
canon_candidates: vec![candidate],
|
||||
|
|
@ -5966,6 +5979,188 @@ mod tests {
|
|||
assert!(manifest.temporal_scopes.contains("fixture-era"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn inhabited_region_admission_preserves_people_and_invalidates_only_derived_cover() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap();
|
||||
let kernel = WorldKernel::start(store.clone());
|
||||
let mut seed = campaign();
|
||||
seed.gestalts.insert(
|
||||
"refugees".into(),
|
||||
GestaltPersonaState {
|
||||
schema: "ghostlight.gestalt_persona_state.v1".into(),
|
||||
id: "refugees".into(),
|
||||
name: "Refugees".into(),
|
||||
version: 0,
|
||||
home_location_id: "room".into(),
|
||||
shared_capabilities: BTreeSet::new(),
|
||||
shared_knowledge: BTreeSet::new(),
|
||||
resources: BTreeSet::new(),
|
||||
goals: vec!["seek voluntary settlement".into()],
|
||||
pressures: vec![],
|
||||
},
|
||||
);
|
||||
seed.gestalt_members.insert(
|
||||
"taren".into(),
|
||||
GestaltMemberDelta {
|
||||
schema: "ghostlight.gestalt_member_delta.v1".into(),
|
||||
id: "taren".into(),
|
||||
gestalt_id: "refugees".into(),
|
||||
version: 3,
|
||||
name: "Taren".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!["reach the ridge villages".into()],
|
||||
memories: vec!["Ash repaired my regulator".into()],
|
||||
last_location_id: Some("room".into()),
|
||||
materialized_actor_id: None,
|
||||
last_relevant_revision: 0,
|
||||
relevance_lease_until_revision: 0,
|
||||
},
|
||||
);
|
||||
crate::resolution::ensure_agency_profiles(&mut seed);
|
||||
let original_member = seed.gestalt_members["taren"].clone();
|
||||
let original_epoch = seed.resolution_policy.resolution_epoch;
|
||||
kernel
|
||||
.command(WorldCommand::CreateCampaign {
|
||||
campaign: seed,
|
||||
evidence_receipts: vec![],
|
||||
model_stage_receipts: vec![],
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let evidence = VaultEvidenceReceipt {
|
||||
schema: "ghostlight.vault_evidence_receipt.v1".into(),
|
||||
id: "vault:ridge".into(),
|
||||
provider: "fixture".into(),
|
||||
query_hash: "sha256:q".into(),
|
||||
witnesses: vec![],
|
||||
retrieved_at: Utc::now(),
|
||||
};
|
||||
let statement = "The ridge assembly governs voluntary admission.".to_owned();
|
||||
let population = GestaltPersonaState {
|
||||
schema: "ghostlight.gestalt_persona_state.v1".into(),
|
||||
id: "ridge-households".into(),
|
||||
name: "Ridge Households".into(),
|
||||
version: 0,
|
||||
home_location_id: "ridge".into(),
|
||||
shared_capabilities: BTreeSet::from(["communal agriculture".into()]),
|
||||
shared_knowledge: BTreeSet::from([statement.clone()]),
|
||||
resources: BTreeSet::from(["shared kitchen".into()]),
|
||||
goals: vec!["decide admissions collectively".into()],
|
||||
pressures: vec!["winter capacity is finite".into()],
|
||||
};
|
||||
let profile = AgencyProfile {
|
||||
schema: "ghostlight.agency_profile.v1".into(),
|
||||
id: "agency:ridge-households".into(),
|
||||
subject_id: population.id.clone(),
|
||||
subject_kind: AgencySubjectKind::Gestalt,
|
||||
profile_version: 0,
|
||||
collective_authority_id: Some(population.id.clone()),
|
||||
parent_subject_id: None,
|
||||
active_leaf: true,
|
||||
simulation_eligible: true,
|
||||
facets: BTreeMap::from([
|
||||
(AgencyAxis::Geography, BTreeSet::from(["ridge".into()])),
|
||||
(AgencyAxis::Ideology, BTreeSet::from(["consent".into()])),
|
||||
(AgencyAxis::Authority, BTreeSet::from(["assembly".into()])),
|
||||
(
|
||||
AgencyAxis::EconomyRole,
|
||||
BTreeSet::from(["agriculture".into()]),
|
||||
),
|
||||
(AgencyAxis::SpeciesBody, BTreeSet::from(["mixed".into()])),
|
||||
(AgencyAxis::Information, BTreeSet::from(["local".into()])),
|
||||
]),
|
||||
location_ids: BTreeSet::from(["ridge".into()]),
|
||||
information_channels: BTreeSet::from(["village assembly bulletin".into()]),
|
||||
detail_debt: 0,
|
||||
last_detail_tick: 0,
|
||||
evidence_receipt_ids: vec![evidence.id.clone()],
|
||||
};
|
||||
let relation = AgencyRelation {
|
||||
schema: "ghostlight.agency_relation.v1".into(),
|
||||
id: "migration:refugees:ridge".into(),
|
||||
from_subject_id: "refugees".into(),
|
||||
to_subject_id: population.id.clone(),
|
||||
kind: AgencyRelationKind::Migration,
|
||||
strength: 50,
|
||||
active: true,
|
||||
evidence_receipt_ids: vec![evidence.id.clone()],
|
||||
};
|
||||
let result = kernel
|
||||
.command(WorldCommand::ExpandRegion {
|
||||
expected_revision: 0,
|
||||
expansion: RegionExpansion {
|
||||
origin_location_id: "room".into(),
|
||||
origin_routes: BTreeMap::from([(
|
||||
"to-ridge".into(),
|
||||
Route {
|
||||
destination_id: "ridge".into(),
|
||||
distance: "2 km".into(),
|
||||
travel_minutes: 20,
|
||||
},
|
||||
)]),
|
||||
locations: vec![Location {
|
||||
id: "ridge".into(),
|
||||
name: "Ridge Village".into(),
|
||||
container_id: None,
|
||||
routes: BTreeMap::from([(
|
||||
"to-room".into(),
|
||||
Route {
|
||||
destination_id: "room".into(),
|
||||
distance: "2 km".into(),
|
||||
travel_minutes: 20,
|
||||
},
|
||||
)]),
|
||||
persistent_features: vec!["assembly hall".into()],
|
||||
}],
|
||||
facts: vec![WorldFact {
|
||||
id: "ridge-admission".into(),
|
||||
statement,
|
||||
scope: FactScope::ProvisionalLocal,
|
||||
evidence_receipt_ids: vec![evidence.id.clone()],
|
||||
discoverable_at_location_ids: BTreeSet::from(["ridge".into()]),
|
||||
}],
|
||||
populations: vec![population],
|
||||
population_profiles: vec![profile],
|
||||
migration_relations: vec![relation],
|
||||
},
|
||||
evidence_receipts: vec![evidence],
|
||||
canon_candidates: vec![],
|
||||
model_stage_receipts: vec![],
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let CommandResult::Committed { campaign, .. } = result else {
|
||||
panic!("expected commit")
|
||||
};
|
||||
assert_eq!(campaign.gestalt_members["taren"], original_member);
|
||||
assert_eq!(campaign.gestalts["refugees"].home_location_id, "room");
|
||||
assert_eq!(
|
||||
campaign.gestalts["ridge-households"].home_location_id,
|
||||
"ridge"
|
||||
);
|
||||
assert_eq!(
|
||||
campaign.agency_relations["migration:refugees:ridge"].kind,
|
||||
AgencyRelationKind::Migration
|
||||
);
|
||||
assert_eq!(
|
||||
campaign.resolution_policy.resolution_epoch,
|
||||
original_epoch + 1
|
||||
);
|
||||
assert!(campaign.resolution_cover.is_none());
|
||||
assert_eq!(
|
||||
crate::resolution::gestalt_migration_destinations(&campaign, "refugees", "room")["ridge-households"],
|
||||
"ridge"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gestalt_member_dematerializes_to_delta_and_returns_as_same_person() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
|
|
|||
|
|
@ -8,9 +8,9 @@
|
|||
|
||||
use crate::{
|
||||
domain::{
|
||||
ActorReaction, Campaign, FactScope, GestaltFissionPreview, GestaltLineage,
|
||||
GestaltPersonaState, OutcomeBand, StrategicActivityOutcome, StrategicOutcomeEffect,
|
||||
StrategicTickPlan, WorldEffectDelta, WorldFact,
|
||||
ActorReaction, AgencyProfile, AgencyRelation, Campaign, FactScope, GestaltFissionPreview,
|
||||
GestaltLineage, GestaltPersonaState, OutcomeBand, StrategicActivityOutcome,
|
||||
StrategicOutcomeEffect, StrategicTickPlan, WorldEffectDelta, WorldFact,
|
||||
},
|
||||
transition::*,
|
||||
};
|
||||
|
|
@ -301,6 +301,88 @@ pub fn lower_region_expansion(
|
|||
admission_receipt_id: source_receipt_id.clone(),
|
||||
});
|
||||
}
|
||||
for population in &expansion.populations {
|
||||
let subject = population_subject(&population.id);
|
||||
mutations.push(WorldMutation::AdmitEntity {
|
||||
subject: subject.clone(),
|
||||
initial_components: BTreeSet::from([
|
||||
WorldComponentKind::Identity,
|
||||
WorldComponentKind::Occupancy,
|
||||
WorldComponentKind::Capability,
|
||||
WorldComponentKind::Knowledge,
|
||||
WorldComponentKind::Commitment,
|
||||
WorldComponentKind::Pressure,
|
||||
]),
|
||||
initial_place: Some(place_subject(&population.home_location_id)),
|
||||
initial_profile: None,
|
||||
admission_receipt_id: source_receipt_id.clone(),
|
||||
});
|
||||
mutations.push(WorldMutation::ChangeIdentity {
|
||||
subject: subject.clone(),
|
||||
operation: IdentityMutationOperation::Adopt,
|
||||
handle_id: format!("identity:canonical:{}", population.id),
|
||||
handle_value: Some(population.name.clone()),
|
||||
audience: Vec::new(),
|
||||
});
|
||||
for capability in &population.shared_capabilities {
|
||||
mutations.push(WorldMutation::ChangeCapability {
|
||||
subject: subject.clone(),
|
||||
operation: CapabilityMutationOperation::Grant,
|
||||
capability_id: capability.clone(),
|
||||
description: Some(capability.clone()),
|
||||
});
|
||||
}
|
||||
for statement in &population.shared_knowledge {
|
||||
let fact = expansion
|
||||
.facts
|
||||
.iter()
|
||||
.chain(campaign.facts.values())
|
||||
.find(|fact| fact.statement == *statement)
|
||||
.ok_or_else(|| {
|
||||
anyhow!("destination population knowledge lacks an admitted fact")
|
||||
})?;
|
||||
mutations.push(WorldMutation::ChangeKnowledge {
|
||||
operation: KnowledgeMutationOperation::Acquire,
|
||||
proposition: proposition_subject(&fact.id),
|
||||
knower: Some(subject.clone()),
|
||||
speaker: None,
|
||||
recipients: Vec::new(),
|
||||
channel: None,
|
||||
});
|
||||
}
|
||||
for (index, goal) in population.goals.iter().enumerate() {
|
||||
mutations.push(WorldMutation::ChangeCommitment {
|
||||
subject: subject.clone(),
|
||||
operation: CommitmentMutationOperation::Create,
|
||||
kind: CommitmentKind::Goal,
|
||||
commitment_id: format!("goal:compiler:{index}:{}", short_digest(goal)),
|
||||
counterparty: None,
|
||||
description: Some(goal.clone()),
|
||||
});
|
||||
}
|
||||
for pressure in &population.pressures {
|
||||
mutations.push(WorldMutation::ChangePressure {
|
||||
pressure: gestalt_pressure_subject(&population.id, pressure),
|
||||
owner: subject.clone(),
|
||||
operation: PressureMutationOperation::Create,
|
||||
amount: Some(4),
|
||||
label: Some(pressure.clone()),
|
||||
});
|
||||
}
|
||||
for resource in &population.resources {
|
||||
mutations.push(WorldMutation::MutateResource {
|
||||
resource: resource_subject(campaign, &subject, resource),
|
||||
operation: ResourceMutationOperation::Create,
|
||||
custodian: Some(subject.clone()),
|
||||
related_resources: Vec::new(),
|
||||
resource_kind: Some("population_resource".into()),
|
||||
resource_label: Some(resource.clone()),
|
||||
recipe_id: None,
|
||||
quantity: Some(1),
|
||||
integrity: Some(100),
|
||||
});
|
||||
}
|
||||
}
|
||||
let origin = place_subject(&expansion.origin_location_id);
|
||||
for (route_id, route) in &expansion.origin_routes {
|
||||
mutations.push(WorldMutation::ChangeTopology {
|
||||
|
|
@ -324,6 +406,16 @@ pub fn lower_region_expansion(
|
|||
});
|
||||
}
|
||||
}
|
||||
for relation in &expansion.migration_relations {
|
||||
mutations.push(WorldMutation::ChangeRelationship {
|
||||
source: population_subject(&relation.from_subject_id),
|
||||
target: population_subject(&relation.to_subject_id),
|
||||
operation: RelationshipMutationOperation::Create,
|
||||
relationship_id: relation.id.clone(),
|
||||
description: Some("migration".into()),
|
||||
strength_delta: Some(i64::from(relation.strength)),
|
||||
});
|
||||
}
|
||||
lower_exact_mutations(
|
||||
campaign,
|
||||
mutations,
|
||||
|
|
@ -331,7 +423,7 @@ pub fn lower_region_expansion(
|
|||
None,
|
||||
MutationOutcomeBinding::Deterministic,
|
||||
None,
|
||||
"Admit only the approved place profiles and proposition contents, then add the exact approved route edges without rewriting existing geography.",
|
||||
"Admit only the approved place profiles, proposition contents, population leaves, agency inputs, and directed migration relations, then add the exact approved route edges without rewriting existing geography or moving any existing subject.",
|
||||
&source_receipt_id,
|
||||
Some(digest_serializable(&(
|
||||
"compile_destination",
|
||||
|
|
@ -445,6 +537,62 @@ fn project_accepted_region_expansion(
|
|||
},
|
||||
);
|
||||
}
|
||||
for requested in &expansion.populations {
|
||||
let subject = population_subject(&requested.id);
|
||||
let place = next
|
||||
.occupancy
|
||||
.get(&subject)
|
||||
.filter(|place| place.kind == SubjectKind::Place)
|
||||
.ok_or_else(|| anyhow!("accepted destination population lost occupancy"))?;
|
||||
let identity = next
|
||||
.identities
|
||||
.get(&format!("identity:canonical:{}", requested.id))
|
||||
.filter(|identity| identity.subject == subject && identity.active)
|
||||
.ok_or_else(|| anyhow!("accepted destination population lost identity"))?;
|
||||
let mut population = requested.clone();
|
||||
population.name = identity.value.clone();
|
||||
population.home_location_id = place.id.clone();
|
||||
campaign.gestalts.insert(population.id.clone(), population);
|
||||
}
|
||||
for requested in &expansion.population_profiles {
|
||||
let mut profile: AgencyProfile = requested.clone();
|
||||
profile.location_ids = BTreeSet::from([campaign
|
||||
.gestalts
|
||||
.get(&profile.subject_id)
|
||||
.ok_or_else(|| anyhow!("accepted destination profile lost population"))?
|
||||
.home_location_id
|
||||
.clone()]);
|
||||
campaign
|
||||
.agency_profiles
|
||||
.insert(profile.subject_id.clone(), profile);
|
||||
}
|
||||
for requested in &expansion.migration_relations {
|
||||
let value = next
|
||||
.relationships
|
||||
.get(&requested.id)
|
||||
.filter(|value| {
|
||||
value.source == population_subject(&requested.from_subject_id)
|
||||
&& value.target == population_subject(&requested.to_subject_id)
|
||||
})
|
||||
.ok_or_else(|| anyhow!("accepted destination migration relation vanished"))?;
|
||||
let mut relation: AgencyRelation = requested.clone();
|
||||
relation.strength = u8::try_from(
|
||||
value
|
||||
.strength
|
||||
.ok_or_else(|| anyhow!("accepted destination relation lost strength"))?,
|
||||
)
|
||||
.map_err(|_| anyhow!("accepted destination relation exceeds aggregate storage"))?;
|
||||
campaign
|
||||
.agency_relations
|
||||
.insert(relation.id.clone(), relation);
|
||||
}
|
||||
if !expansion.populations.is_empty() {
|
||||
campaign.resolution_cover = None;
|
||||
campaign.resolution_policy.resolution_epoch = campaign
|
||||
.resolution_policy
|
||||
.resolution_epoch
|
||||
.saturating_add(1);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -5379,6 +5379,9 @@ fn region_expansion_preview_projection(preview: &RegionExpansionPreview) -> serd
|
|||
"origin_routes":preview.expansion.origin_routes,
|
||||
"locations":preview.expansion.locations,
|
||||
"facts":preview.expansion.facts,
|
||||
"populations":preview.expansion.populations,
|
||||
"population_profiles":preview.expansion.population_profiles,
|
||||
"migration_relations":preview.expansion.migration_relations,
|
||||
"gaps":preview.gaps,
|
||||
"requires_approval":preview.requires_approval,
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
use crate::domain::*;
|
||||
use anyhow::{Result, anyhow};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::cmp::Ordering;
|
||||
use std::cmp::{Ordering, Reverse};
|
||||
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, VecDeque};
|
||||
|
||||
pub const MIN_ACTIVE_CELL_BUDGET: u8 = 1;
|
||||
|
|
@ -2323,15 +2323,13 @@ pub fn validate_gestalt_migration(
|
|||
"gestalt migration lacks an explicit source-to-destination relation"
|
||||
));
|
||||
}
|
||||
let reachable = campaign
|
||||
.locations
|
||||
.get(&source.home_location_id)
|
||||
.is_some_and(|location| {
|
||||
location.routes.values().any(|route| {
|
||||
route.destination_id == destination_location_id
|
||||
&& route.travel_minutes <= campaign.tick_hours.saturating_mul(60)
|
||||
})
|
||||
});
|
||||
let reachable = route_travel_minutes_within(
|
||||
campaign,
|
||||
&source.home_location_id,
|
||||
destination_location_id,
|
||||
campaign.tick_hours.saturating_mul(60),
|
||||
)
|
||||
.is_some();
|
||||
if !reachable {
|
||||
return Err(anyhow!(
|
||||
"gestalt migration destination is not reachable within the strategic horizon"
|
||||
|
|
@ -2406,13 +2404,13 @@ pub fn validate_member_migration(
|
|||
.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)
|
||||
})
|
||||
});
|
||||
let reachable = route_travel_minutes_within(
|
||||
campaign,
|
||||
origin,
|
||||
destination_location_id,
|
||||
campaign.tick_hours.saturating_mul(60),
|
||||
)
|
||||
.is_some();
|
||||
if !reachable {
|
||||
return Err(anyhow!("member migration exceeds the strategic horizon"));
|
||||
}
|
||||
|
|
@ -2438,21 +2436,68 @@ pub fn gestalt_migration_destinations(
|
|||
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)
|
||||
})
|
||||
});
|
||||
let reachable = route_travel_minutes_within(
|
||||
campaign,
|
||||
origin_location_id,
|
||||
&destination.home_location_id,
|
||||
campaign.tick_hours.saturating_mul(60),
|
||||
)
|
||||
.is_some();
|
||||
reachable.then(|| (destination.id.clone(), destination.home_location_id.clone()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Directed shortest-path travel time bounded by the simulation horizon.
|
||||
/// Containment is intentionally absent: only explicit topology edges carry
|
||||
/// movement authority.
|
||||
pub(crate) fn route_travel_minutes_within(
|
||||
campaign: &Campaign,
|
||||
origin_location_id: &str,
|
||||
destination_location_id: &str,
|
||||
maximum_minutes: u32,
|
||||
) -> Option<u32> {
|
||||
if origin_location_id == destination_location_id {
|
||||
return campaign
|
||||
.locations
|
||||
.contains_key(origin_location_id)
|
||||
.then_some(0);
|
||||
}
|
||||
if !campaign.locations.contains_key(origin_location_id)
|
||||
|| !campaign.locations.contains_key(destination_location_id)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut best = BTreeMap::from([(origin_location_id.to_owned(), 0_u32)]);
|
||||
let mut frontier = BinaryHeap::from([(Reverse(0_u32), origin_location_id.to_owned())]);
|
||||
while let Some((Reverse(elapsed), location_id)) = frontier.pop() {
|
||||
if elapsed > maximum_minutes || best.get(&location_id).is_some_and(|known| elapsed > *known)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if location_id == destination_location_id {
|
||||
return Some(elapsed);
|
||||
}
|
||||
let location = campaign.locations.get(&location_id)?;
|
||||
for route in location.routes.values() {
|
||||
let Some(next) = elapsed.checked_add(route.travel_minutes) else {
|
||||
continue;
|
||||
};
|
||||
if next > maximum_minutes || !campaign.locations.contains_key(&route.destination_id) {
|
||||
continue;
|
||||
}
|
||||
if best
|
||||
.get(&route.destination_id)
|
||||
.is_none_or(|known| next < *known)
|
||||
{
|
||||
best.insert(route.destination_id.clone(), next);
|
||||
frontier.push((Reverse(next), route.destination_id.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn member_state_references(campaign: &Campaign, member_id: &str) -> Result<BTreeSet<String>> {
|
||||
let member = campaign
|
||||
.gestalt_members
|
||||
|
|
|
|||
Loading…
Reference in a new issue