diff --git a/crates/ghostlight-dungeon/src/app_session.rs b/crates/ghostlight-dungeon/src/app_session.rs index 96709b1..9863fad 100644 --- a/crates/ghostlight-dungeon/src/app_session.rs +++ b/crates/ghostlight-dungeon/src/app_session.rs @@ -114,6 +114,17 @@ pub struct AppSessionOwner { } impl AppSessionOwner { + #[cfg(test)] + pub fn persisted_bytes_contain(&self, needle: &str) -> anyhow::Result { + let directory = tempfile::tempdir()?; + let snapshot = directory.path().join("app-session-inspection.cc"); + self.store.snapshot_to(&snapshot)?; + let bytes = std::fs::read(snapshot)?; + Ok(bytes + .windows(needle.len()) + .any(|window| window == needle.as_bytes())) + } + pub fn open( store_path: impl AsRef, wrapping_key_path: impl AsRef, diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-action-smoke.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-action-smoke.rs index 50fa69e..ed24e9e 100644 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-action-smoke.rs +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-action-smoke.rs @@ -248,6 +248,7 @@ fn action_campaign() -> ghostlight_dungeon::domain::Campaign { }, )]), facts: BTreeMap::new(), + civic_systems: BTreeMap::new(), transcript: vec![], last_player_activity: now, pending_ticks: 0, diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-dynamics-smoke.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-dynamics-smoke.rs index 8e2d9d0..7aea701 100644 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-dynamics-smoke.rs +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-dynamics-smoke.rs @@ -1088,6 +1088,7 @@ fn dynamics_campaign() -> ghostlight_dungeon::domain::Campaign { }, )]), facts: BTreeMap::new(), + civic_systems: BTreeMap::new(), transcript: vec![], last_player_activity: now - Duration::hours(2), pending_ticks: 1, diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-scale-smoke.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-scale-smoke.rs index e2c12ae..840291d 100644 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-scale-smoke.rs +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-scale-smoke.rs @@ -262,6 +262,7 @@ fn scale_campaign( }, )]), facts: BTreeMap::new(), + civic_systems: BTreeMap::new(), transcript: vec![], last_player_activity: now - Duration::hours(2), pending_ticks: 1, diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-live-turn-smoke.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-live-turn-smoke.rs index 00916dc..b2f981a 100644 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-live-turn-smoke.rs +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-live-turn-smoke.rs @@ -195,6 +195,7 @@ fn four_actor_campaign() -> ghostlight_dungeon::domain::Campaign { institutions: BTreeMap::new(), clocks: BTreeMap::new(), facts: BTreeMap::new(), + civic_systems: BTreeMap::new(), transcript: vec![], last_player_activity: now, pending_ticks: 0, diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs index 5fb118d..47d5980 100644 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs @@ -23,7 +23,8 @@ async fn main() -> anyhow::Result<()> { let scenario_id = std::env::var("GHOSTLIGHT_LIVE_FIRE_SCENARIO") .unwrap_or_else(|_| "strategic-default".into()); let pressure = std::env::var("GHOSTLIGHT_STRATEGIC_PRESSURE").unwrap_or_else(|_| { - "Two reserve deliveries are missing and the next yard shift may refuse work.".into() + "The sovereign deep-hold diverted the White Root aquifer. Two tithe caravans have vanished, the charcoal guilds threaten secession, and somebody pawned the regent's rain seal." + .into() }); let root = std::env::var_os("GHOSTLIGHT_LIVE_FIRE_RESULT_ROOT") .map(PathBuf::from) @@ -42,10 +43,10 @@ async fn main() -> anyhow::Result<()> { kind: "strategic_pressure".into(), summary: pressure.clone(), actor_ids: vec!["runner".into()], - institution_ids: vec!["board".into()], + institution_ids: vec!["board".into(), "synod".into()], gestalt_ids: vec![], location_ids: vec!["depot".into(), "yard".into()], - public_channels: vec!["station radio".into()], + public_channels: vec!["root-wire broadsheet".into()], }); let player_location = campaign.actors[&campaign.player_actor_id] .location_id @@ -117,6 +118,17 @@ async fn main() -> anyhow::Result<()> { if advanced.news.is_empty() { anyhow::bail!("accessible offscreen events produced no gated news") } + let newspaper = ghostlight_dungeon::newspaper::compose_world_newspaper( + advanced, + std::env::var("GHOSTLIGHT_STRATEGIC_NEWSPAPER_TITLE") + .unwrap_or_else(|_| "The Underdeep Clarion".into()), + 24, + )?; + let newspaper_path = root.join("newspaper.md"); + std::fs::write( + &newspaper_path, + ghostlight_dungeon::newspaper::render_world_newspaper_markdown(&newspaper), + )?; let result = serde_json::json!({ "schema":"ghostlight.live_strategic_smoke.v1", "scenario_id":scenario_id, @@ -128,6 +140,8 @@ async fn main() -> anyhow::Result<()> { "plan":plan, "event_count":advanced.events.len(), "news_count":advanced.news.len(), + "newspaper":newspaper, + "newspaper_path":newspaper_path, "player_location_unchanged":true, "commit":committed, "store":root.join("campaign.cc") @@ -162,12 +176,17 @@ fn strategic_campaign() -> ghostlight_dungeon::domain::Campaign { } } let now = Utc::now(); - let mut player = actor("player", "Mediator", "room", "rest"); - player.knowledge.insert("station radio".into()); + let mut player = actor( + "player", + "Deep-hold Envoy", + "room", + "observe without ruling", + ); + player.knowledge.insert("root-wire broadsheet".into()); let mut campaign = Campaign { schema: "ghostlight.campaign.v1".into(), id: uuid::Uuid::new_v4(), - name: "Strategic live acceptance".into(), + name: "The Rainless Marches".into(), revision: 0, branch_origin: BranchOrigin { canon_cutoff: "acceptance-fixture".into(), @@ -181,7 +200,7 @@ fn strategic_campaign() -> ghostlight_dungeon::domain::Campaign { "room".into(), Location { id: "room".into(), - name: "Player quarters".into(), + name: "Greathold Boundary Cairn".into(), container_id: None, routes: BTreeMap::new(), persistent_features: vec![], @@ -191,7 +210,7 @@ fn strategic_campaign() -> ghostlight_dungeon::domain::Campaign { "depot".into(), Location { id: "depot".into(), - name: "Supply depot".into(), + name: "Rootvault Granary".into(), container_id: None, routes: BTreeMap::from([( "yard".into(), @@ -201,14 +220,17 @@ fn strategic_campaign() -> ghostlight_dungeon::domain::Campaign { travel_minutes: 60, }, )]), - persistent_features: vec!["sealed reserve crates".into()], + persistent_features: vec![ + "dry aquifer gauges".into(), + "a rain seal's empty reliquary".into(), + ], }, ), ( "yard".into(), Location { id: "yard".into(), - name: "Workers' yard".into(), + name: "Thornweald Assembly".into(), container_id: None, routes: BTreeMap::from([( "depot".into(), @@ -218,7 +240,10 @@ fn strategic_campaign() -> ghostlight_dungeon::domain::Campaign { travel_minutes: 60, }, )]), - persistent_features: vec!["idle loading cranes".into()], + persistent_features: vec![ + "charcoal tithe scales".into(), + "three freshly painted secession banners".into(), + ], }, ), ]), @@ -226,30 +251,48 @@ fn strategic_campaign() -> ghostlight_dungeon::domain::Campaign { ("player".into(), player), ( "runner".into(), - actor("runner", "Depot runner", "depot", "warn the workers"), + actor( + "runner", + "Ilyra Quill", + "depot", + "find who sold the rain seal", + ), + ), + ]), + institutions: BTreeMap::from([ + ( + "board".into(), + InstitutionState { + id: "board".into(), + name: "Mossglass Regency".into(), + resources: vec!["empty rain-seal reliquary".into()], + goals: vec!["survive the seal scandal without surrendering the throne".into()], + posture: "blaming unnamed caravan clerks".into(), + }, + ), + ( + "synod".into(), + InstitutionState { + id: "synod".into(), + name: "Copper Synod".into(), + resources: vec!["tithe ledgers".into(), "three armed auditors".into()], + goals: vec!["make the regency pay for the vanished caravans".into()], + posture: "quietly pricing a replacement monarch".into(), + }, ), ]), - institutions: BTreeMap::from([( - "board".into(), - InstitutionState { - id: "board".into(), - name: "Station board".into(), - resources: vec!["reserve shipment".into()], - goals: vec!["contain the supply dispute".into()], - posture: "deliberating".into(), - }, - )]), clocks: BTreeMap::from([( "shortage".into(), WorldClock { id: "shortage".into(), - label: "Supply shortage".into(), + label: "White Root succession crisis".into(), progress: 1, threshold: 4, - consequence: "the yard stops work".into(), + consequence: "the charcoal guilds declare the regent ritually rainless".into(), }, )]), facts: BTreeMap::new(), + civic_systems: BTreeMap::new(), transcript: vec![], last_player_activity: now - Duration::hours(2), pending_ticks: 1, @@ -262,20 +305,50 @@ fn strategic_campaign() -> ghostlight_dungeon::domain::Campaign { GestaltPersonaState { schema: "ghostlight.gestalt_persona_state.v1".into(), id: "workers".into(), - name: "Yard workers".into(), + name: "Thornweald Charcoal Guilds".into(), version: 0, home_location_id: "yard".into(), - shared_capabilities: BTreeSet::from(["operate loading cranes".into()]), - shared_knowledge: BTreeSet::from(["two deliveries are missing".into()]), - resources: BTreeSet::from(["union hall".into()]), - goals: vec!["secure the missing supplies".into()], - pressures: vec!["the next shift may refuse work".into()], + shared_capabilities: BTreeSet::from(["close every forest kiln at once".into()]), + shared_knowledge: BTreeSet::from([ + "two tithe caravans vanished after the aquifer diversion".into(), + "the regent's rain seal is missing".into(), + ]), + resources: BTreeSet::from(["assembly grove".into()]), + goals: vec!["replace tithe tribute with an elected water compact".into()], + pressures: vec!["three guilds have already painted secession banners".into()], }, )]), gestalt_members: BTreeMap::new(), pending_world_proposals: vec![], agency_profiles: BTreeMap::new(), - agency_relations: BTreeMap::new(), + agency_relations: BTreeMap::from([ + ( + "regency-synod-rivalry".into(), + AgencyRelation { + schema: "ghostlight.agency_relation.v1".into(), + id: "regency-synod-rivalry".into(), + from_subject_id: "board".into(), + to_subject_id: "synod".into(), + kind: AgencyRelationKind::Rivalry, + strength: 86, + active: true, + evidence_receipt_ids: vec![], + }, + ), + ( + "synod-guild-command".into(), + AgencyRelation { + schema: "ghostlight.agency_relation.v1".into(), + id: "synod-guild-command".into(), + from_subject_id: "synod".into(), + to_subject_id: "workers".into(), + kind: AgencyRelationKind::Command, + strength: 63, + active: true, + evidence_receipt_ids: vec![], + }, + ), + ]), gestalt_lineages: BTreeMap::new(), resolution_policy: Default::default(), resolution_pins: BTreeMap::new(), @@ -284,11 +357,17 @@ fn strategic_campaign() -> ghostlight_dungeon::domain::Campaign { }; ghostlight_dungeon::resolution::ensure_agency_profiles(&mut campaign); for profile in campaign.agency_profiles.values_mut() { - profile.information_channels.insert("station radio".into()); + profile + .information_channels + .insert("root-wire broadsheet".into()); } - if let Some(board) = campaign.agency_profiles.get_mut("board") { - board.location_ids.extend(["depot".into(), "yard".into()]); - board + for institution_id in ["board", "synod"] { + let profile = campaign + .agency_profiles + .get_mut(institution_id) + .expect("fixture institution has a profile"); + profile.location_ids.extend(["depot".into(), "yard".into()]); + profile .facets .entry(AgencyAxis::Geography) .or_default() diff --git a/crates/ghostlight-dungeon/src/compiler.rs b/crates/ghostlight-dungeon/src/compiler.rs index c8a6105..1ede6fe 100644 --- a/crates/ghostlight-dungeon/src/compiler.rs +++ b/crates/ghostlight-dungeon/src/compiler.rs @@ -1,9 +1,11 @@ use crate::{ domain::{ ActorState, AgencyAxis, AgencyProfile, AgencyRelation, AgencyRelationKind, - AgencySubjectKind, BranchOrigin, Campaign, EvidenceCoverage, EvidenceUseLane, FactScope, - GestaltMemberDelta, GestaltPersonaState, InstitutionState, Location, Route, - VaultEvidenceReceipt, WorldClock, WorldCompilePreview, WorldFact, + AgencySubjectKind, BranchOrigin, Campaign, CivicSystemManifest, + DestinationCompilationPreview, EvidenceCoverage, EvidenceUseLane, FactScope, + GestaltMemberDelta, GestaltPersonaState, InstitutionState, LocalityElaboration, + LocalityElaborationPreview, Location, Route, VaultEvidenceReceipt, WorldClock, + WorldCompilePreview, WorldFact, }, model::{ ModelPort, ModelStageReceipt, ModelStageRequest, run_validated_stage, @@ -573,6 +575,14 @@ struct CompiledExpansionSeed { #[schemars(length(max = 8))] populations: Vec, #[serde(default)] + #[schemars(length(max = 12))] + institutions: Vec, + #[serde(default)] + #[schemars(length(max = 48))] + local_relations: Vec, + #[serde(default)] + civic_system: Option, + #[serde(default)] #[schemars(length(max = 32))] migration_relations: Vec, #[serde(default)] @@ -606,6 +616,29 @@ struct CompiledDestinationPopulation { information_channels: BTreeSet, } +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +struct CompiledDestinationInstitution { + id: String, + name: String, + resources: Vec, + goals: Vec, + posture: String, + location_ids: BTreeSet, + facets: CompiledAgencyFacets, + information_channels: BTreeSet, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +struct CivicSystemVerification { + authority_legible: bool, + selection_or_succession_legible: bool, + public_resources_legible: bool, + redress_legible: bool, + institutional_relations_coherent: bool, + resident_answer_grounded: bool, + rationale: String, +} + #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] struct CompiledDestinationMigrationRelation { id: String, @@ -1639,10 +1672,7 @@ impl WorldCompiler { campaign: &Campaign, origin_location_id: &str, destination_request: &str, - ) -> Result<( - crate::domain::RegionExpansionPreview, - Vec, - )> { + ) -> Result<(DestinationCompilationPreview, Vec)> { validate_user_text("destination request", destination_request, 500)?; let origin = campaign .locations @@ -1652,13 +1682,13 @@ impl WorldCompiler { let (existing_destination_id, identity_receipts) = self .resolve_destination_identity(campaign, destination_request, &snapshot) .await?; - if let Some(existing_destination_id) = existing_destination_id { + if let Some(existing_destination_id) = existing_destination_id.as_deref() { let destination = campaign .locations - .get(&existing_destination_id) + .get(existing_destination_id) .expect("destination identity resolver was locally validated"); - let Some((path, travel_minutes)) = - shortest_location_path(campaign, origin_location_id, &existing_destination_id) + let Some((_path, _travel_minutes)) = + shortest_location_path(campaign, origin_location_id, existing_destination_id) else { return Err(anyhow!( "{} already exists in canonical campaign topology, but no committed route currently reaches it from {}. No substitute location or route preview was created; request a genuinely new intermediary place or resolve the missing topology explicitly.", @@ -1666,26 +1696,22 @@ impl WorldCompiler { origin.name, )); }; - let path = path - .iter() - .filter_map(|location_id| campaign.locations.get(location_id)) - .map(|location| location.name.as_str()) - .collect::>() - .join(" → "); - return Err(anyhow!( - "{} already exists in canonical campaign topology and is reachable from {} via {} ({} minutes). Use the projected travel controls; no new destination preview was created.", - destination.name, - origin.name, - path, - travel_minutes, - )); } + let expansion_origin_location_id = existing_destination_id + .as_deref() + .unwrap_or(origin_location_id); + let expansion_origin = campaign + .locations + .get(expansion_origin_location_id) + .expect("expansion origin is either the validated origin or destination"); let (queries, retrieval_receipt) = self .plan_queries( "destination_retrieval_plan", &format!("campaign:{}:revision:{}", campaign.id, campaign.revision), &serde_json::to_string(&serde_json::json!({ "origin": origin, + "elaboration_anchor": expansion_origin, + "existing_destination_id": existing_destination_id, "destination": destination_request, "canon_cutoff": campaign.branch_origin.canon_cutoff, }))?, @@ -1699,7 +1725,7 @@ impl WorldCompiler { .gestalts .values() .filter(|gestalt| { - gestalt.home_location_id == origin_location_id + gestalt.home_location_id == expansion_origin_location_id && campaign .agency_profiles .get(&gestalt.id) @@ -1721,7 +1747,7 @@ impl WorldCompiler { "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) + && member.last_location_id.as_deref().unwrap_or(&gestalt.home_location_id) == expansion_origin_location_id) .map(|member| serde_json::json!({ "id":member.id, "name":member.name, @@ -1733,10 +1759,36 @@ impl WorldCompiler { }) }) .collect::>(); + let current_civic_context = campaign + .civic_systems + .get(expansion_origin_location_id) + .map(|system| { + serde_json::json!({ + "manifest":system, + "institutions":system.governing_institution_ids.iter().filter_map(|id|campaign.institutions.get(id)).collect::>(), + "institution_profiles":system.governing_institution_ids.iter().filter_map(|id|campaign.agency_profiles.get(id)).collect::>(), + "residents":system.resident_population_ids.iter().filter_map(|id|campaign.gestalts.get(id)).collect::>(), + "resident_profiles":system.resident_population_ids.iter().filter_map(|id|campaign.agency_profiles.get(id)).collect::>(), + "public_facts":system.public_authority_fact_ids.iter() + .chain(system.public_selection_fact_ids.iter()) + .chain(system.public_resource_fact_ids.iter()) + .chain(system.public_redress_fact_ids.iter()) + .filter_map(|id|campaign.facts.get(id)).collect::>(), + "political_relations":system.political_relation_ids.iter().filter_map(|id|campaign.agency_relations.get(id)).collect::>(), + }) + }); + let scope_instruction = if let Some(target_id) = existing_destination_id.as_deref() { + format!( + "The primary destination already exists as exact canonical location {target_id}. Elaborate it in place. Never emit that location again, rename it, replace it, or alter its existing routes or container. Every new location must be a bounded child whose containment chain reaches {target_id}; origin_routes are new local routes owned by {target_id}." + ) + } else { + "The primary destination is genuinely new. Admit it and its bounded child detail from the supplied origin without rewriting any existing place.".into() + }; 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.\n\nUse evidence as canon constraints, not as an exhaustive game map. Missing game-scale routes, geometry, people, ordinary procedures, supplies, local responsibilities, capacity choices, and operating doctrine require the smallest coherent playable elaboration. Mark the resulting facts branch_local or provisional_local and disclose consequential inventions in branch_assumptions. Variation between campaigns is permitted; if a detail must not vary, it belongs in the Vault. Never put a compatible elaboration in gaps merely because the Vault is silent.\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. 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\nThe gaps array is legal only when no compatible elaboration can preserve an exact clause of REQUEST without choosing between contradictory canon baselines, inventing an unanchored canon baseline explicitly required by the request, or exceeding an approved capability. Every gap must name that exact premise clause and the exact table choice blocking compilation. `The Vault does not specify X` is never sufficient. Use an empty gaps array when branch-local invention preserves the request.\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 explicit without misclassifying them as canon gaps.\n\nCAMPAIGN LOCATIONS:\n{}\nCO-LOCATED SOURCE POPULATIONS AND NAMED MEMBER DELTAS:\n{}\nREQUEST:\n{}\nEVIDENCE:\n{}", - origin_location_id, + "Compile only the requested bounded destination region. {scope_instruction} Every new location id must be new. Return explicit origin_routes records owned by expansion anchor id {} into the new region or child locality, and give every such destination a reciprocal route record back to the anchor 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\nUse evidence as canon constraints, not as an exhaustive game map. Missing game-scale routes, geometry, people, ordinary procedures, supplies, local responsibilities, capacity choices, and operating doctrine require the smallest coherent playable elaboration. Mark the resulting facts branch_local or provisional_local and disclose consequential inventions in branch_assumptions. Variation between campaigns is permitted; if a detail must not vary, it belongs in the Vault. Never put a compatible elaboration in gaps merely because the Vault is silent.\n\nWhen CURRENT CIVIC APPARATUS is null, a playable inhabited destination needs one to eight non-overlapping population leaves and two to twelve distinct institutions. When it is present, preserve it and add only genuinely new detail needed by the request; population and institution arrays may be empty. New local relations may join new subjects to exact subjects in the current apparatus. Never duplicate a resident body, office, fact, or relation under a fresh name. Each new population home_location_id must be one new location. Each new institution location_ids set may name the jurisdiction or its new children. shared_fact_ids may contain exact fact IDs from the current apparatus or this 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\nReturn one complete civic_system manifest for every inhabited candidate. On an existing apparatus it is the next version and must retain every existing governing institution, resident population, public fact, and political relation while adding any new IDs. It must identify the exact jurisdiction, its governing institutions and resident populations, at least one committed public fact in each of four domains—current authority, selection or succession, public resources or revenue, and redress or appeal—and the political relations that make implementation, hierarchy, or contestation legible. Every named resident population must share those public civic facts. If REQUEST presupposes a mayor, election, throne, council, or other office that this locality does not use, commit facts that let a resident correct the premise; never manufacture the requested institution merely to agree with the question. The question selects the missing domain, not its answer.\n\nThe gaps array is legal only when no compatible elaboration can preserve an exact clause of REQUEST without choosing between contradictory canon baselines, inventing an unanchored canon baseline explicitly required by the request, or exceeding an approved capability. Every gap must name that exact premise clause and the exact table choice blocking compilation. `The Vault does not specify X` is never sufficient. Use an empty gaps array when branch-local invention preserves the request.\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 explicit without misclassifying them as canon gaps.\n\nCAMPAIGN LOCATIONS:\n{}\nCURRENT CIVIC APPARATUS:\n{}\nCO-LOCATED SOURCE POPULATIONS AND NAMED MEMBER DELTAS:\n{}\nREQUEST:\n{}\nEVIDENCE:\n{}", + expansion_origin_location_id, serde_json::to_string(&campaign.locations)?, + serde_json::to_string(¤t_civic_context)?, serde_json::to_string(&origin_population_context)?, destination_request, evidence_text(&receipts) @@ -1746,7 +1798,7 @@ impl WorldCompiler { let sources = receipt_ids(&receipts); let mut compiler_receipts = Vec::new(); let mut correction = String::new(); - let (seed, expansion) = loop { + let (seed, mut expansion) = loop { let output = self .structured( "destination_compile", @@ -1777,9 +1829,10 @@ impl WorldCompiler { "destination compiler failed local validation after one correction: {error}" )); } - let fact_statements = seed + let fact_statements = campaign .facts - .iter() + .values() + .chain(seed.facts.iter()) .map(|fact| (fact.id.as_str(), fact.statement.as_str())) .collect::>(); let populations = seed @@ -1829,6 +1882,52 @@ impl WorldCompiler { evidence_receipt_ids: sources.clone(), }) .collect::>(); + let institutions = seed + .institutions + .iter() + .map(|institution| InstitutionState { + id: institution.id.clone(), + name: institution.name.clone(), + resources: institution.resources.clone(), + goals: institution.goals.clone(), + posture: institution.posture.clone(), + }) + .collect::>(); + let institution_profiles = seed + .institutions + .iter() + .map(|institution| AgencyProfile { + schema: "ghostlight.agency_profile.v1".into(), + id: format!("agency:{}", institution.id), + subject_id: institution.id.clone(), + subject_kind: AgencySubjectKind::Institution, + profile_version: 0, + collective_authority_id: None, + parent_subject_id: None, + active_leaf: true, + simulation_eligible: true, + facets: institution.facets.clone().into_map(), + location_ids: institution.location_ids.clone(), + information_channels: institution.information_channels.clone(), + detail_debt: 0, + last_detail_tick: campaign.strategic_tick_count, + evidence_receipt_ids: sources.clone(), + }) + .collect::>(); + let local_relations = seed + .local_relations + .iter() + .map(|relation| AgencyRelation { + schema: "ghostlight.agency_relation.v1".into(), + id: relation.id.clone(), + from_subject_id: relation.from_subject_id.clone(), + to_subject_id: relation.to_subject_id.clone(), + kind: relation.kind.clone(), + strength: relation.strength, + active: true, + evidence_receipt_ids: sources.clone(), + }) + .collect::>(); let migration_relations = seed .migration_relations .iter() @@ -1843,9 +1942,21 @@ impl WorldCompiler { evidence_receipt_ids: sources.clone(), }) .collect::>(); + let mut civic_system = seed.civic_system.clone(); + if let Some(system) = &mut civic_system { + system.version = campaign + .civic_systems + .get(&system.jurisdiction_location_id) + .map(|current| current.version.saturating_add(1)) + .unwrap_or(0); + system.semantic_verification_receipt_id.clear(); + } let expansion = crate::domain::RegionExpansion { - origin_location_id: origin_location_id.into(), - origin_routes: compiled_route_map(seed.origin_routes.clone(), origin_location_id)?, + origin_location_id: expansion_origin_location_id.into(), + origin_routes: compiled_route_map( + seed.origin_routes.clone(), + expansion_origin_location_id, + )?, locations: seed .locations .clone() @@ -1856,8 +1967,28 @@ impl WorldCompiler { populations, population_profiles, migration_relations, + institutions, + institution_profiles, + local_relations, + civic_system, }; - match validate_region_expansion(campaign, &expansion) { + let validation = + if !expansion.populations.is_empty() && expansion.civic_system.is_none() { + Err(anyhow!( + "compiled inhabited destination omitted its civic system manifest" + )) + } else if let Some(target_location_id) = existing_destination_id.as_deref() { + validate_locality_elaboration( + campaign, + &LocalityElaboration { + target_location_id: target_location_id.into(), + expansion: expansion.clone(), + }, + ) + } else { + validate_new_destination_expansion(campaign, &expansion) + }; + match validation { Ok(()) => break (seed, expansion), Err(error) if compiler_receipts.len() == 1 => { mark_semantic_invalid( @@ -1877,6 +2008,60 @@ impl WorldCompiler { } } }; + if let Some(civic_system) = &expansion.civic_system { + let verification_prompt = format!( + "Independently verify the admitted civic apparatus. Judge meaning, not JSON shape. The public facts must actually explain current authority, selection or succession, public resources or revenue, and redress or appeal. The institutions and political relations must form a coherent local apparatus, and every resident population's exact shared_fact_ids must ground an ordinary answer about local government. A question may select a civic domain but must not have forced its presupposed office, election, or answer into the candidate. Do not rewrite or complete the candidate; return verdicts only.\n\nREQUEST:\n{}\nEVIDENCE:\n{}\nCANDIDATE:\n{}", + destination_request, + evidence_text(&receipts), + serde_json::to_string(&serde_json::json!({ + "previous_civic_apparatus":¤t_civic_context, + "civic_system":civic_system, + "new_facts":&seed.facts, + "new_institutions":&seed.institutions, + "new_local_relations":&seed.local_relations, + "new_resident_populations":seed.populations.iter().map(|population| serde_json::json!({ + "id":population.id, + "shared_fact_ids":population.shared_fact_ids, + })).collect::>(), + }))?, + ); + let (value, mut verification_receipt) = self + .structured( + "destination_civic_verification", + &snapshot, + &verification_prompt, + serde_json::to_value(schema_for!(CivicSystemVerification))?, + sources.clone(), + ) + .await?; + let verdict = serde_json::from_value::(value)?; + let rationale_chars = verdict.rationale.trim().chars().count(); + if rationale_chars == 0 + || rationale_chars > 1_000 + || !verdict.authority_legible + || !verdict.selection_or_succession_legible + || !verdict.public_resources_legible + || !verdict.redress_legible + || !verdict.institutional_relations_coherent + || !verdict.resident_answer_grounded + { + let error = anyhow!( + "destination civic verifier rejected the candidate: {}", + verdict.rationale.trim() + ); + mark_semantic_invalid(&mut verification_receipt, &error); + return Err(error); + } + let candidate_digest = civic_candidate_digest(&expansion)?; + verification_receipt + .rebind_snapshot(civic_verifier_binding(campaign, &candidate_digest)); + expansion + .civic_system + .as_mut() + .expect("verified civic system remains present") + .semantic_verification_receipt_id = verification_receipt.storage_key().to_owned(); + compiler_receipts.push(verification_receipt); + } let evidence_ids = receipt_ids(&receipts); let affected_sources: Vec = receipts .iter() @@ -1905,8 +2090,23 @@ impl WorldCompiler { status: "review".into(), }) .collect(); - Ok(( - crate::domain::RegionExpansionPreview { + let preview = if let Some(target_location_id) = existing_destination_id { + DestinationCompilationPreview::LocalityElaboration(LocalityElaborationPreview { + schema: "ghostlight.locality_elaboration_preview.v1".into(), + campaign_id: campaign.id, + expected_revision: campaign.revision, + elaboration: LocalityElaboration { + target_location_id, + expansion, + }, + evidence_receipts: receipts, + branch_assumptions: seed.branch_assumptions, + gaps: gap_texts, + canon_candidates: candidates, + requires_approval: true, + }) + } else { + DestinationCompilationPreview::RegionExpansion(crate::domain::RegionExpansionPreview { schema: "ghostlight.region_expansion_preview.v1".into(), campaign_id: campaign.id, expected_revision: campaign.revision, @@ -1916,7 +2116,10 @@ impl WorldCompiler { gaps: gap_texts, canon_candidates: candidates, requires_approval: true, - }, + }) + }; + Ok(( + preview, identity_receipts .into_iter() .chain(std::iter::once(retrieval_receipt)) @@ -3507,6 +3710,24 @@ fn mark_semantic_invalid(receipt: &mut ModelStageReceipt, error: &impl std::fmt: receipt.local_validation_error = Some(error.to_string().chars().take(1_000).collect()); } +pub(crate) fn civic_candidate_digest(expansion: &crate::domain::RegionExpansion) -> Result { + let mut candidate = expansion.clone(); + if let Some(system) = &mut candidate.civic_system { + system.semantic_verification_receipt_id.clear(); + } + Ok(format!( + "sha256:{:x}", + Sha256::digest(rmp_serde::to_vec_named(&candidate)?) + )) +} + +pub(crate) fn civic_verifier_binding(campaign: &Campaign, candidate_digest: &str) -> String { + format!( + "campaign:{}:revision:{}:destination_civic:{}", + campaign.id, campaign.revision, candidate_digest + ) +} + pub fn validate_region_expansion( campaign: &Campaign, expansion: &crate::domain::RegionExpansion, @@ -3765,7 +3986,277 @@ pub fn validate_region_expansion( )); } } - let mut relation_ids = BTreeSet::new(); + let institution_ids = expansion + .institutions + .iter() + .map(|institution| institution.id.as_str()) + .collect::>(); + if expansion.institutions.len() > 12 + || institution_ids.len() != expansion.institutions.len() + || institution_ids.iter().any(|id| { + id.trim().is_empty() + || population_ids.contains(id) + || campaign.gestalts.contains_key(*id) + || campaign.actors.contains_key(*id) + || campaign.institutions.contains_key(*id) + }) + { + return Err(anyhow!( + "destination institutions need at most twelve unique new canonical subject IDs" + )); + } + let institution_profile_ids = expansion + .institution_profiles + .iter() + .map(|profile| profile.subject_id.as_str()) + .collect::>(); + if institution_profile_ids != institution_ids + || expansion.institution_profiles.len() != expansion.institutions.len() + { + return Err(anyhow!( + "destination institution profiles must cover every new institution exactly once" + )); + } + for institution in &expansion.institutions { + if institution.name.trim().is_empty() + || institution.posture.trim().is_empty() + || institution.goals.is_empty() + || institution + .resources + .iter() + .chain(institution.goals.iter()) + .any(|value| value.trim().is_empty()) + { + return Err(anyhow!( + "destination institution {} has malformed canonical state", + institution.id + )); + } + let profile = expansion + .institution_profiles + .iter() + .find(|profile| profile.subject_id == institution.id) + .expect("institution profile coverage was checked above"); + let profile_axes = profile.facets.keys().cloned().collect::>(); + if profile.schema != "ghostlight.agency_profile.v1" + || profile.id != format!("agency:{}", institution.id) + || profile.subject_kind != AgencySubjectKind::Institution + || profile.profile_version != 0 + || profile.collective_authority_id.is_some() + || profile.parent_subject_id.is_some() + || !profile.active_leaf + || !profile.simulation_eligible + || profile.location_ids.is_empty() + || profile.location_ids.iter().any(|id| !known(id)) + || profile_axes != axes + || profile + .information_channels + .iter() + .any(|channel| !crate::resolution::information_channel_is_concrete(channel)) + { + return Err(anyhow!( + "destination institution {} has a malformed agency profile", + institution.id + )); + } + } + let existing_civic = expansion + .civic_system + .as_ref() + .and_then(|system| campaign.civic_systems.get(&system.jurisdiction_location_id)); + let existing_civic_subject_ids = existing_civic + .into_iter() + .flat_map(|system| { + system + .governing_institution_ids + .iter() + .chain(system.resident_population_ids.iter()) + }) + .map(String::as_str) + .collect::>(); + let local_subject_ids = population_ids + .iter() + .copied() + .chain(institution_ids.iter().copied()) + .chain(existing_civic_subject_ids.iter().copied()) + .collect::>(); + let mut local_relation_ids = BTreeSet::new(); + for relation in &expansion.local_relations { + if expansion.local_relations.len() > 48 + || relation.schema != "ghostlight.agency_relation.v1" + || relation.id.trim().is_empty() + || !local_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 + || !local_subject_ids.contains(relation.from_subject_id.as_str()) + || !local_subject_ids.contains(relation.to_subject_id.as_str()) + { + return Err(anyhow!( + "destination local relation {} is not an exact new local-subject edge", + relation.id + )); + } + } + if let Some(civic) = expansion.civic_system.as_ref() { + let civic_fact_ids = civic + .public_authority_fact_ids + .iter() + .chain(civic.public_selection_fact_ids.iter()) + .chain(civic.public_resource_fact_ids.iter()) + .chain(civic.public_redress_fact_ids.iter()) + .collect::>(); + let previous = campaign.civic_systems.get(&civic.jurisdiction_location_id); + let expected_version = previous + .map(|system| system.version.saturating_add(1)) + .unwrap_or(0); + let previous_institution_ids = previous + .into_iter() + .flat_map(|system| system.governing_institution_ids.iter()) + .collect::>(); + let previous_resident_ids = previous + .into_iter() + .flat_map(|system| system.resident_population_ids.iter()) + .collect::>(); + let previous_relation_ids = previous + .into_iter() + .flat_map(|system| system.political_relation_ids.iter()) + .collect::>(); + let allowed_institution_ids = institution_ids + .iter() + .map(|id| (*id).to_owned()) + .chain(previous_institution_ids.iter().map(|id| (*id).clone())) + .collect::>(); + let expected_resident_ids = population_ids + .iter() + .map(|id| (*id).to_owned()) + .chain(previous_resident_ids.iter().map(|id| (*id).clone())) + .collect::>(); + let allowed_relation_ids = local_relation_ids + .iter() + .map(|id| (*id).to_owned()) + .chain(previous_relation_ids.iter().map(|id| (*id).clone())) + .collect::>(); + let allowed_fact_ids = new_fact_ids + .iter() + .cloned() + .chain(previous.into_iter().flat_map(|system| { + system + .public_authority_fact_ids + .iter() + .chain(system.public_selection_fact_ids.iter()) + .chain(system.public_resource_fact_ids.iter()) + .chain(system.public_redress_fact_ids.iter()) + .cloned() + })) + .collect::>(); + if civic.schema != "ghostlight.civic_system_manifest.v1" + || civic.version != expected_version + || !known(&civic.jurisdiction_location_id) + || allowed_institution_ids.len() < 2 + || expected_resident_ids.is_empty() + || civic.governing_institution_ids.is_empty() + || civic + .governing_institution_ids + .iter() + .any(|id| !allowed_institution_ids.contains(id)) + || previous_institution_ids + .iter() + .any(|id| !civic.governing_institution_ids.contains(*id)) + || civic.resident_population_ids != expected_resident_ids + || civic.public_authority_fact_ids.is_empty() + || civic.public_selection_fact_ids.is_empty() + || civic.public_resource_fact_ids.is_empty() + || civic.public_redress_fact_ids.is_empty() + || civic_fact_ids + .iter() + .any(|id| !allowed_fact_ids.contains(*id)) + || civic.political_relation_ids.is_empty() + || civic + .political_relation_ids + .iter() + .any(|id| !allowed_relation_ids.contains(id)) + || previous_relation_ids + .iter() + .any(|id| !civic.political_relation_ids.contains(*id)) + || previous.is_some_and(|previous| { + !previous + .public_authority_fact_ids + .is_subset(&civic.public_authority_fact_ids) + || !previous + .public_selection_fact_ids + .is_subset(&civic.public_selection_fact_ids) + || !previous + .public_resource_fact_ids + .is_subset(&civic.public_resource_fact_ids) + || !previous + .public_redress_fact_ids + .is_subset(&civic.public_redress_fact_ids) + }) + { + return Err(anyhow!( + "inhabited destination civic manifest does not close authority, selection, resources, redress, populations, and political relations" + )); + } + let public_statements = civic_fact_ids + .iter() + .map(|fact_id| { + expansion + .facts + .iter() + .find(|fact| fact.id.as_str() == fact_id.as_str()) + .or_else(|| campaign.facts.get(*fact_id)) + .map(|fact| fact.statement.as_str()) + .ok_or_else(|| anyhow!("civic manifest references a missing public fact")) + }) + .collect::>>()?; + if expansion.populations.iter().any(|population| { + public_statements + .iter() + .any(|statement| !population.shared_knowledge.contains(*statement)) + }) { + return Err(anyhow!( + "every resident population must know the committed public civic facts" + )); + } + if expansion.facts.iter().any(|fact| { + civic_fact_ids.contains(&fact.id) + && fact.scope == FactScope::CanonBaseline + && fact.evidence_receipt_ids.is_empty() + }) { + return Err(anyhow!( + "an invented public civic fact cannot claim canon-baseline scope without evidence" + )); + } + if !civic.political_relation_ids.iter().any(|id| { + expansion + .local_relations + .iter() + .find(|relation| relation.id == *id) + .or_else(|| campaign.agency_relations.get(id)) + .is_some_and(|relation| { + matches!( + relation.kind, + AgencyRelationKind::Command + | AgencyRelationKind::Rivalry + | AgencyRelationKind::Coercion + ) && (civic + .governing_institution_ids + .contains(&relation.from_subject_id) + || civic + .governing_institution_ids + .contains(&relation.to_subject_id)) + }) + }) { + return Err(anyhow!( + "civic system needs a command, rivalry, or coercion edge that makes political authority or contestation legible" + )); + } + } + let mut relation_ids = local_relation_ids; for relation in &expansion.migration_relations { let source_is_exact_origin_leaf = campaign .gestalts @@ -3847,6 +4338,159 @@ pub fn validate_region_expansion( Ok(()) } +pub fn validate_new_destination_expansion( + campaign: &Campaign, + expansion: &crate::domain::RegionExpansion, +) -> Result<()> { + validate_region_expansion(campaign, expansion)?; + if let Some(civic) = &expansion.civic_system { + if !expansion + .locations + .iter() + .any(|location| location.id == civic.jurisdiction_location_id) + { + return Err(anyhow!( + "new destination civic jurisdiction must be one newly admitted location" + )); + } + validate_civic_locality_scope(campaign, expansion, &civic.jurisdiction_location_id)?; + } + Ok(()) +} + +pub fn validate_locality_elaboration( + campaign: &Campaign, + elaboration: &LocalityElaboration, +) -> Result<()> { + validate_region_expansion(campaign, &elaboration.expansion)?; + if !campaign + .locations + .contains_key(&elaboration.target_location_id) + || elaboration.expansion.origin_location_id != elaboration.target_location_id + { + return Err(anyhow!( + "locality elaboration must preserve one exact canonical target as its expansion anchor" + )); + } + if elaboration.expansion.locations.iter().any(|location| { + !expansion_location_is_within( + campaign, + &elaboration.expansion, + &location.id, + &elaboration.target_location_id, + ) + }) { + return Err(anyhow!( + "locality elaboration may admit only child places beneath its exact target" + )); + } + let civic = elaboration + .expansion + .civic_system + .as_ref() + .ok_or_else(|| anyhow!("locality elaboration requires a civic system manifest"))?; + if civic.jurisdiction_location_id != elaboration.target_location_id { + return Err(anyhow!( + "locality civic jurisdiction must remain the exact canonical target" + )); + } + validate_civic_locality_scope( + campaign, + &elaboration.expansion, + &elaboration.target_location_id, + )?; + Ok(()) +} + +fn validate_civic_locality_scope( + campaign: &Campaign, + expansion: &crate::domain::RegionExpansion, + jurisdiction_location_id: &str, +) -> Result<()> { + if expansion.populations.iter().any(|population| { + !expansion_location_is_within( + campaign, + expansion, + &population.home_location_id, + jurisdiction_location_id, + ) + }) || expansion.institution_profiles.iter().any(|profile| { + profile.location_ids.iter().any(|location_id| { + !expansion_location_is_within( + campaign, + expansion, + location_id, + jurisdiction_location_id, + ) + }) + }) { + return Err(anyhow!( + "civic populations and institutions must be located within their exact jurisdiction" + )); + } + let civic = expansion + .civic_system + .as_ref() + .expect("civic scope validation follows civic manifest validation"); + let public_fact_ids = civic + .public_authority_fact_ids + .iter() + .chain(civic.public_selection_fact_ids.iter()) + .chain(civic.public_resource_fact_ids.iter()) + .chain(civic.public_redress_fact_ids.iter()) + .collect::>(); + if expansion.facts.iter().any(|fact| { + public_fact_ids.contains(&fact.id) + && (fact.discoverable_at_location_ids.is_empty() + || fact.discoverable_at_location_ids.iter().any(|location_id| { + !expansion_location_is_within( + campaign, + expansion, + location_id, + jurisdiction_location_id, + ) + })) + }) { + return Err(anyhow!( + "public civic facts must be discoverable only within their exact jurisdiction" + )); + } + Ok(()) +} + +fn expansion_location_is_within( + campaign: &Campaign, + expansion: &crate::domain::RegionExpansion, + location_id: &str, + ancestor_id: &str, +) -> bool { + let new_locations = expansion + .locations + .iter() + .map(|location| (location.id.as_str(), location)) + .collect::>(); + let mut cursor = Some(location_id); + let mut seen = BTreeSet::new(); + while let Some(id) = cursor { + if id == ancestor_id { + return true; + } + if !seen.insert(id) { + return false; + } + cursor = new_locations + .get(id) + .and_then(|location| location.container_id.as_deref()) + .or_else(|| { + campaign + .locations + .get(id) + .and_then(|location| location.container_id.as_deref()) + }); + } + false +} + fn evidence_text(receipts: &[VaultEvidenceReceipt]) -> String { let mut seen = BTreeSet::new(); receipts @@ -4233,6 +4877,7 @@ fn seed_to_campaign(mut seed: CompiledSeed, receipts: &[VaultEvidenceReceipt]) - (x.id.clone(), x) }) .collect(), + civic_systems: BTreeMap::new(), transcript: vec![crate::domain::NarrativeTurn { revision: 0, at: now, @@ -4524,6 +5169,14 @@ fn apply_compiled_agency_skeleton( } pub fn validate_campaign_seed(c: &Campaign) -> Result<()> { + validate_campaign(c, true) +} + +pub(crate) fn validate_campaign_runtime(c: &Campaign) -> Result<()> { + validate_campaign(c, false) +} + +fn validate_campaign(c: &Campaign, require_dematerialized_members: bool) -> Result<()> { if c.tick_hours == 0 { return Err(anyhow!("strategic tick duration must be positive")); } @@ -4618,7 +5271,7 @@ pub fn validate_campaign_seed(c: &Campaign) -> Result<()> { member.gestalt_id )); } - if member.materialized_actor_id.is_some() { + if require_dematerialized_members && member.materialized_actor_id.is_some() { return Err(anyhow!( "compiled gestalt member {} must begin dematerialized", member.id @@ -4683,6 +5336,65 @@ pub fn validate_campaign_seed(c: &Campaign) -> Result<()> { return Err(anyhow!("clock {} is invalid", clock.id)); } } + validate_campaign_civic_systems(c)?; + Ok(()) +} + +fn validate_campaign_civic_systems(campaign: &Campaign) -> Result<()> { + for (jurisdiction_id, system) in &campaign.civic_systems { + let public_fact_ids = system + .public_authority_fact_ids + .iter() + .chain(system.public_selection_fact_ids.iter()) + .chain(system.public_resource_fact_ids.iter()) + .chain(system.public_redress_fact_ids.iter()) + .collect::>(); + if system.schema != "ghostlight.civic_system_manifest.v1" + || system.jurisdiction_location_id != *jurisdiction_id + || !campaign.locations.contains_key(jurisdiction_id) + || system.semantic_verification_receipt_id.trim().is_empty() + || system.governing_institution_ids.len() < 2 + || system + .governing_institution_ids + .iter() + .any(|id| !campaign.institutions.contains_key(id)) + || system.resident_population_ids.is_empty() + || system + .resident_population_ids + .iter() + .any(|id| !campaign.gestalts.contains_key(id)) + || system.public_authority_fact_ids.is_empty() + || system.public_selection_fact_ids.is_empty() + || system.public_resource_fact_ids.is_empty() + || system.public_redress_fact_ids.is_empty() + || public_fact_ids + .iter() + .any(|id| !campaign.facts.contains_key(*id)) + || system.political_relation_ids.is_empty() + || system.political_relation_ids.iter().any(|id| { + !campaign + .agency_relations + .get(id) + .is_some_and(|edge| edge.active) + }) + { + return Err(anyhow!( + "campaign civic system for {jurisdiction_id} has broken canonical references" + )); + } + for resident_id in &system.resident_population_ids { + let resident = &campaign.gestalts[resident_id]; + if public_fact_ids.iter().any(|fact_id| { + !resident + .shared_knowledge + .contains(&campaign.facts[*fact_id].statement) + }) { + return Err(anyhow!( + "campaign civic resident {resident_id} lost a public civic fact" + )); + } + } + } Ok(()) } @@ -4983,6 +5695,7 @@ mod tests { struct DestinationElaborationModel { saw_branch_assumption_boundary: AtomicBool, + reject_civic_verification: bool, } struct OversizedQueryModel; @@ -5437,19 +6150,42 @@ mod tests { }], "persistent_features":["braced roof","witnessed stores ledger"] }], - "facts":[{ - "id":"fact:refuge_operating_leaf", - "statement":"The refuge uses a witnessed operating leaf for repair and admission duty.", - "scope":"branch_local", - "evidence_receipt_ids":[], - "discoverable_at_location_ids":["refuge"] - }], + "facts":[ + { + "id":"fact:refuge_authority", + "statement":"The refuge duty council currently authorizes admissions and storm closure.", + "scope":"branch_local", + "evidence_receipt_ids":[], + "discoverable_at_location_ids":["refuge"] + }, + { + "id":"fact:refuge_selection", + "statement":"Wardens select two duty councillors by witnessed lot after each storm season.", + "scope":"branch_local", + "evidence_receipt_ids":[], + "discoverable_at_location_ids":["refuge"] + }, + { + "id":"fact:refuge_resources", + "statement":"The stores office receives repair boards through disclosed convoy levies.", + "scope":"branch_local", + "evidence_receipt_ids":[], + "discoverable_at_location_ids":["refuge"] + }, + { + "id":"fact:refuge_redress", + "statement":"A warden may appeal a duty ruling before the next witnessed stores count.", + "scope":"branch_local", + "evidence_receipt_ids":[], + "discoverable_at_location_ids":["refuge"] + } + ], "populations":[{ "id":"refuge-wardens", "name":"Refuge wardens", "home_location_id":"refuge", "shared_capabilities":["brace ordinary storm damage"], - "shared_fact_ids":["fact:refuge_operating_leaf"], + "shared_fact_ids":["fact:refuge_authority","fact:refuge_selection","fact:refuge_resources","fact:refuge_redress"], "resources":["repair boards"], "goals":["keep the refuge usable"], "pressures":["capacity is finite"], @@ -5464,6 +6200,60 @@ mod tests { }, "information_channels":["witnessed operating leaf"] }], + "institutions":[ + { + "id":"refuge-duty-council", + "name":"Refuge Duty Council", + "resources":["closure seal"], + "goals":["keep admissions within storm capacity"], + "posture":"admit by witnessed capacity ruling", + "location_ids":["refuge"], + "facets":{ + "geography":["storm refuge"], + "ideology":["witnessed duty"], + "authority":["admission rulings"], + "economy_role":["capacity allocation"], + "species_body":["mixed households"], + "information":["public duty leaf"] + }, + "information_channels":["public duty leaf"] + }, + { + "id":"refuge-stores-office", + "name":"Refuge Stores Office", + "resources":["stores ledger"], + "goals":["preserve disclosed emergency stores"], + "posture":"publish every levy and count", + "location_ids":["refuge"], + "facets":{ + "geography":["storm refuge"], + "ideology":["disclosed accounting"], + "authority":["stores custody"], + "economy_role":["repair supply"], + "species_body":["mixed households"], + "information":["witnessed stores count"] + }, + "information_channels":["witnessed stores count"] + } + ], + "local_relations":[{ + "id":"relation:refuge-council-stores", + "from_subject_id":"refuge-duty-council", + "to_subject_id":"refuge-stores-office", + "kind":"command", + "strength":60 + }], + "civic_system":{ + "schema":"ghostlight.civic_system_manifest.v1", + "jurisdiction_location_id":"refuge", + "governing_institution_ids":["refuge-duty-council"], + "resident_population_ids":["refuge-wardens"], + "public_authority_fact_ids":["fact:refuge_authority"], + "public_selection_fact_ids":["fact:refuge_selection"], + "public_resource_fact_ids":["fact:refuge_resources"], + "public_redress_fact_ids":["fact:refuge_redress"], + "political_relation_ids":["relation:refuge-council-stores"] + }, "migration_relations":[], "branch_assumptions":[ "The storm-path geometry and witnessed repair procedure are compatible campaign-local elaboration." @@ -5472,6 +6262,23 @@ mod tests { }) .to_string()) } + "destination_civic_verification" => { + let accepted = !self.reject_civic_verification; + Ok(serde_json::json!({ + "authority_legible":accepted, + "selection_or_succession_legible":accepted, + "public_resources_legible":accepted, + "redress_legible":accepted, + "institutional_relations_coherent":accepted, + "resident_answer_grounded":accepted, + "rationale":if accepted { + "The refuge facts and institutions form a legible civic apparatus grounded in every resident population." + } else { + "The candidate's labels do not form a meaningful civic apparatus." + } + }) + .to_string()) + } _ => Err(anyhow!("unexpected destination elaboration stage")), } } @@ -5483,26 +6290,256 @@ mod tests { struct ExistingDestinationModel { calls: AtomicUsize, + saw_current_civic_context: AtomicBool, } #[async_trait] impl ModelPort for ExistingDestinationModel { async fn run(&self, request: &ModelStageRequest) -> Result { self.calls.fetch_add(1, Ordering::SeqCst); - if request.stage != "destination_identity_resolution" { - return Err(anyhow!( - "existing destination resolution must stop before stage {}", + match request.stage.as_str() { + "destination_identity_resolution" => { + assert!(request.lived_stream.contains("Harrow Station")); + assert!(request.lived_stream.contains("loc:harrow_station")); + Ok(serde_json::json!({ + "decision":"existing", + "existing_location_id":"loc:harrow_station", + "rationale":"The request's primary destination is the supplied Harrow Station." + }) + .to_string()) + } + "destination_retrieval_plan" => Ok(serde_json::json!({ + "queries":["Harrow Station civic institutions","Harrow Station public offices"] + }) + .to_string()), + "destination_compile" => { + assert!( + request + .lived_stream + .contains("Elaborate it in place. Never emit that location again") + ); + assert!( + request + .lived_stream + .contains("The question selects the missing domain, not its answer") + ); + if !request + .lived_stream + .contains("CURRENT CIVIC APPARATUS:\nnull") + { + self.saw_current_civic_context.store(true, Ordering::SeqCst); + return Ok(serde_json::json!({ + "origin_routes":[{ + "route_id":"route:station_to_audit_chamber", + "destination_id":"loc:harrow_audit_chamber", + "distance":"behind the petitions bench", + "travel_minutes":4 + }], + "locations":[{ + "id":"loc:harrow_audit_chamber", + "name":"Harrow Audit Chamber", + "container_id":"loc:harrow_station", + "routes":[{ + "route_id":"route:audit_chamber_to_station", + "destination_id":"loc:harrow_station", + "distance":"back through the petitions bench", + "travel_minutes":4 + }], + "persistent_features":["sealed berth-dues duplicate ledger"] + }], + "facts":[{ + "id":"fact:harrow_hidden_levy", + "statement":"The audit chamber found that Mayor Selka Vey diverted one season of published berth dues into an unvoted emergency courier fund.", + "scope":"branch_local", + "evidence_receipt_ids":[], + "discoverable_at_location_ids":["loc:harrow_station","loc:harrow_audit_chamber"] + }], + "populations":[], + "institutions":[{ + "id":"harrow-audit-chamber", + "name":"Harrow Audit Chamber", + "resources":["duplicate berth-dues ledger"], + "goals":["force a public vote on the diverted dues"], + "posture":"prepare contempt findings against the mayoral office", + "location_ids":["loc:harrow_audit_chamber"], + "facets":{ + "geography":["Harrow civic quarter"], + "ideology":["adversarial public accounting"], + "authority":["compulsory civic audit"], + "economy_role":["treasury inspection"], + "species_body":["mixed civil service"], + "information":["open audit findings"] + }, + "information_channels":["open audit findings"] + }], + "local_relations":[{ + "id":"relation:harrow-audit-mayor", + "from_subject_id":"harrow-audit-chamber", + "to_subject_id":"harrow-mayoral-office", + "kind":"rivalry", + "strength":81 + }], + "civic_system":{ + "schema":"ghostlight.civic_system_manifest.v1", + "jurisdiction_location_id":"loc:harrow_station", + "governing_institution_ids":["harrow-mayoral-office","harrow-ward-assembly","harrow-audit-chamber"], + "resident_population_ids":["harrow-residents"], + "public_authority_fact_ids":["fact:harrow_authority"], + "public_selection_fact_ids":["fact:harrow_selection"], + "public_resource_fact_ids":["fact:harrow_resources","fact:harrow_hidden_levy"], + "public_redress_fact_ids":["fact:harrow_redress"], + "political_relation_ids":["relation:harrow-mayor-assembly","relation:harrow-audit-mayor"] + }, + "migration_relations":[], + "branch_assumptions":["The audit chamber and diverted-dues finding are a second bounded campaign-local elaboration of Harrow's persisted civic apparatus."], + "gaps":[] + }) + .to_string()); + } + Ok(serde_json::json!({ + "origin_routes":[{ + "route_id":"route:station_to_civic_quarter", + "destination_id":"loc:harrow_civic_quarter", + "distance":"through the public arcade", + "travel_minutes":6 + }], + "locations":[{ + "id":"loc:harrow_civic_quarter", + "name":"Harrow Civic Quarter", + "container_id":"loc:harrow_station", + "routes":[{ + "route_id":"route:civic_quarter_to_station", + "destination_id":"loc:harrow_station", + "distance":"back through the public arcade", + "travel_minutes":6 + }], + "persistent_features":["ward notice boards","sealed ballot archive"] + }], + "facts":[ + { + "id":"fact:harrow_authority", + "statement":"Mayor Selka Vey currently holds Harrow Station's civic seal while the ward assembly controls appropriations.", + "scope":"branch_local", + "evidence_receipt_ids":[], + "discoverable_at_location_ids":["loc:harrow_station","loc:harrow_civic_quarter"] + }, + { + "id":"fact:harrow_selection", + "statement":"Harrow residents elected Selka Vey over Oren Vale at the last five-year mayoral ballot.", + "scope":"branch_local", + "evidence_receipt_ids":[], + "discoverable_at_location_ids":["loc:harrow_station","loc:harrow_civic_quarter"] + }, + { + "id":"fact:harrow_resources", + "statement":"The civic treasury is funded by berth dues published before each ward appropriation session.", + "scope":"branch_local", + "evidence_receipt_ids":[], + "discoverable_at_location_ids":["loc:harrow_station","loc:harrow_civic_quarter"] + }, + { + "id":"fact:harrow_redress", + "statement":"Residents may contest a mayoral order before the ward assembly's open petitions bench.", + "scope":"branch_local", + "evidence_receipt_ids":[], + "discoverable_at_location_ids":["loc:harrow_station","loc:harrow_civic_quarter"] + } + ], + "populations":[{ + "id":"harrow-residents", + "name":"Harrow residents", + "home_location_id":"loc:harrow_civic_quarter", + "shared_capabilities":["participate in ward ballots"], + "shared_fact_ids":["fact:harrow_authority","fact:harrow_selection","fact:harrow_resources","fact:harrow_redress"], + "resources":["ward meeting rooms"], + "goals":["keep berth dues answerable to residents"], + "pressures":["the mayor and assembly dispute emergency appropriations"], + "collective_authority_id":"harrow-residents", + "facets":{ + "geography":["Harrow Station"], + "ideology":["ward representation"], + "authority":["resident franchise"], + "economy_role":["station households and berth workers"], + "species_body":["mixed residents"], + "information":["ward notice boards"] + }, + "information_channels":["ward notice boards"] + }], + "institutions":[ + { + "id":"harrow-mayoral-office", + "name":"Harrow Mayoral Office", + "resources":["civic seal","emergency clerks"], + "goals":["retain emergency spending discretion"], + "posture":"press the ward assembly for immediate appropriation", + "location_ids":["loc:harrow_station"], + "facets":{ + "geography":["Harrow Station"], + "ideology":["executive dispatch"], + "authority":["mayoral orders"], + "economy_role":["emergency administration"], + "species_body":["mixed civil service"], + "information":["sealed civic notices"] + }, + "information_channels":["sealed civic notices"] + }, + { + "id":"harrow-ward-assembly", + "name":"Harrow Ward Assembly", + "resources":["appropriations ledger","petitions bench"], + "goals":["bind emergency spending to public accounts"], + "posture":"withhold appropriation pending an open audit", + "location_ids":["loc:harrow_civic_quarter"], + "facets":{ + "geography":["Harrow wards"], + "ideology":["public accounting"], + "authority":["appropriations and petitions"], + "economy_role":["budget oversight"], + "species_body":["mixed ward delegates"], + "information":["open session record"] + }, + "information_channels":["open session record"] + } + ], + "local_relations":[{ + "id":"relation:harrow-mayor-assembly", + "from_subject_id":"harrow-mayoral-office", + "to_subject_id":"harrow-ward-assembly", + "kind":"rivalry", + "strength":72 + }], + "civic_system":{ + "schema":"ghostlight.civic_system_manifest.v1", + "jurisdiction_location_id":"loc:harrow_station", + "governing_institution_ids":["harrow-mayoral-office","harrow-ward-assembly"], + "resident_population_ids":["harrow-residents"], + "public_authority_fact_ids":["fact:harrow_authority"], + "public_selection_fact_ids":["fact:harrow_selection"], + "public_resource_fact_ids":["fact:harrow_resources"], + "public_redress_fact_ids":["fact:harrow_redress"], + "political_relation_ids":["relation:harrow-mayor-assembly"] + }, + "migration_relations":[], + "branch_assumptions":["Harrow's mayoral ballot, ward appropriations split, officeholders, and current dispute are bounded campaign-local elaboration."], + "gaps":[] + }) + .to_string()) + } + "destination_civic_verification" => Ok(serde_json::json!({ + "authority_legible":true, + "selection_or_succession_legible":true, + "public_resources_legible":true, + "redress_legible":true, + "institutional_relations_coherent":true, + "resident_answer_grounded":true, + "rationale":"Harrow's exact public facts explain its divided authority, ballot, revenue, and appeal path to every resident population." + }) + .to_string()), + _ => Err(anyhow!( + "unexpected existing destination stage {}", request.stage - )); + )), } - assert!(request.lived_stream.contains("Harrow Station")); - assert!(request.lived_stream.contains("loc:harrow_station")); - Ok(serde_json::json!({ - "decision":"existing", - "existing_location_id":"loc:harrow_station", - "rationale":"The request's primary destination is the supplied Harrow Station." - }) - .to_string()) } fn provider(&self) -> &'static str { @@ -6550,6 +7587,7 @@ mod tests { { let model = Arc::new(DestinationElaborationModel { saw_branch_assumption_boundary: AtomicBool::new(false), + reject_civic_verification: false, }); let compiler = WorldCompiler::new(vault(), model.clone(), "flash", "pro"); let mut seed = private_actor_test_seed(); @@ -6565,6 +7603,9 @@ mod tests { ) .await .unwrap(); + let DestinationCompilationPreview::RegionExpansion(preview) = preview else { + panic!("new destination must produce a region expansion preview") + }; assert!(model.saw_branch_assumption_boundary.load(Ordering::SeqCst)); assert!(preview.requires_approval); @@ -6583,17 +7624,41 @@ mod tests { vec![ "destination_identity_resolution", "destination_retrieval_plan", - "destination_compile" + "destination_compile", + "destination_civic_verification" ] ); } #[tokio::test] - async fn destination_compiler_refuses_to_duplicate_a_reachable_canonical_place() { - let model = Arc::new(ExistingDestinationModel { - calls: AtomicUsize::new(0), + async fn destination_compiler_rejects_semantically_empty_civic_machinery() { + let model = Arc::new(DestinationElaborationModel { + saw_branch_assumption_boundary: AtomicBool::new(false), + reject_civic_verification: true, }); - let compiler = WorldCompiler::new(vault(), model.clone(), "flash", "pro"); + let compiler = WorldCompiler::new(vault(), model, "flash", "pro"); + let mut seed = private_actor_test_seed(); + seed.player.location_id = "convoy-staging".into(); + seed.opening_narration = "The convoy waits in the rain.".into(); + let campaign = seed_to_campaign(seed, &[]).unwrap(); + + let error = compiler + .compile_destination( + &campaign, + "convoy-staging", + "a playable storm refuge with ordinary repair and admission procedure", + ) + .await + .unwrap_err(); + + assert!( + error + .to_string() + .contains("destination civic verifier rejected the candidate") + ); + } + + fn harrow_campaign() -> Campaign { let mut seed = private_actor_test_seed(); seed.player.location_id = "convoy-staging".into(); seed.locations[0].routes.push(CompiledRoute { @@ -6634,22 +7699,206 @@ mod tests { }], persistent_features: vec!["abandoned road office".into()], }); - let campaign = seed_to_campaign(seed, &[]).unwrap(); + seed_to_campaign(seed, &[]).unwrap() + } - let error = compiler + #[tokio::test] + async fn destination_compiler_elaborates_a_reachable_canonical_city_in_place() { + let model = Arc::new(ExistingDestinationModel { + calls: AtomicUsize::new(0), + saw_current_civic_context: AtomicBool::new(false), + }); + let compiler = WorldCompiler::new(vault(), model.clone(), "flash", "pro"); + let campaign = harrow_campaign(); + + let (preview, receipts) = compiler .compile_destination( &campaign, "convoy-staging", - "Harrow Station via the lower Veyr Run; compile its playable approach", + "Visit Harrow Station and ask a local who they voted for Mayor.", ) .await - .unwrap_err() - .to_string(); + .unwrap(); + let DestinationCompilationPreview::LocalityElaboration(preview) = preview else { + panic!("existing destination must produce a locality elaboration preview") + }; + let expansion = &preview.elaboration.expansion; + assert_eq!(preview.elaboration.target_location_id, "loc:harrow_station"); + assert_eq!(expansion.origin_location_id, "loc:harrow_station"); + assert!( + expansion + .locations + .iter() + .all(|location| location.id != "loc:harrow_station") + ); + assert_eq!(expansion.institutions.len(), 2); + assert_eq!(expansion.civic_system.as_ref().unwrap().version, 0); + assert!( + !expansion + .civic_system + .as_ref() + .unwrap() + .semantic_verification_receipt_id + .is_empty() + ); + assert_eq!( + expansion.local_relations[0].kind, + AgencyRelationKind::Rivalry + ); + let selection = &expansion + .facts + .iter() + .find(|fact| fact.id == "fact:harrow_selection") + .unwrap() + .statement; + assert!(selection.contains("Selka Vey")); + assert!(selection.contains("Oren Vale")); + assert!( + expansion.populations[0] + .shared_knowledge + .contains(selection) + ); + assert_eq!( + receipts + .iter() + .map(|receipt| receipt.stage.as_str()) + .collect::>(), + vec![ + "destination_identity_resolution", + "destination_retrieval_plan", + "destination_compile", + "destination_civic_verification" + ] + ); + assert_eq!(model.calls.load(Ordering::SeqCst), 4); + } - assert!(error.contains("already exists in canonical campaign topology")); - assert!(error.contains("Convoy Staging → Lower Veyr Run → Harrow Station (110 minutes)")); - assert!(error.contains("no new destination preview was created")); - assert_eq!(model.calls.load(Ordering::SeqCst), 1); + #[tokio::test] + async fn locality_elaboration_reuses_and_deepens_its_persisted_civic_apparatus() { + let model = Arc::new(ExistingDestinationModel { + calls: AtomicUsize::new(0), + saw_current_civic_context: AtomicBool::new(false), + }); + let compiler = WorldCompiler::new(vault(), model.clone(), "flash", "pro"); + let initial = harrow_campaign(); + let (first, first_receipts) = compiler + .compile_destination( + &initial, + "convoy-staging", + "Visit Harrow Station and ask a local who they voted for Mayor.", + ) + .await + .unwrap(); + let DestinationCompilationPreview::LocalityElaboration(first) = first else { + panic!("first pass must elaborate Harrow in place") + }; + let first_evidence_queries = first + .evidence_receipts + .iter() + .map(|receipt| receipt.query_hash.clone()) + .collect::>(); + let dir = tempfile::tempdir().unwrap(); + let store = + crate::persistence::CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); + let kernel = crate::kernel::WorldKernel::start(store); + kernel + .command(crate::domain::WorldCommand::CreateCampaign { + campaign: initial, + evidence_receipts: vec![], + model_stage_receipts: vec![], + }) + .await + .unwrap(); + let first_commit = kernel + .command(crate::domain::WorldCommand::ElaborateLocality { + expected_revision: first.expected_revision, + elaboration: first.elaboration, + evidence_receipts: first.evidence_receipts, + canon_candidates: first.canon_candidates, + model_stage_receipts: first_receipts, + }) + .await + .unwrap(); + let crate::kernel::CommandResult::Committed { + campaign: first_campaign, + .. + } = first_commit + else { + panic!("first civic pass must commit") + }; + + let (second, second_receipts) = compiler + .compile_destination( + &first_campaign, + "convoy-staging", + "Investigate the fight over Harrow's berth dues and who is hiding the ledger.", + ) + .await + .unwrap(); + let DestinationCompilationPreview::LocalityElaboration(second) = second else { + panic!("second pass must deepen Harrow in place") + }; + assert!( + second + .evidence_receipts + .iter() + .any(|receipt| first_evidence_queries.contains(&receipt.query_hash)) + ); + assert_eq!(second.elaboration.expansion.populations.len(), 0); + assert_eq!(second.elaboration.expansion.institutions.len(), 1); + let manifest = second.elaboration.expansion.civic_system.as_ref().unwrap(); + assert_eq!(manifest.version, 1); + assert!( + manifest + .governing_institution_ids + .contains("harrow-mayoral-office") + ); + assert!( + manifest + .governing_institution_ids + .contains("harrow-audit-chamber") + ); + assert!( + manifest + .public_resource_fact_ids + .contains("fact:harrow_resources") + ); + assert!( + manifest + .public_resource_fact_ids + .contains("fact:harrow_hidden_levy") + ); + + let second_commit = kernel + .command(crate::domain::WorldCommand::ElaborateLocality { + expected_revision: second.expected_revision, + elaboration: second.elaboration, + evidence_receipts: second.evidence_receipts, + canon_candidates: second.canon_candidates, + model_stage_receipts: second_receipts, + }) + .await + .unwrap(); + let crate::kernel::CommandResult::Committed { + campaign: second_campaign, + .. + } = second_commit + else { + panic!("second civic pass must commit") + }; + assert_eq!( + second_campaign.civic_systems["loc:harrow_station"].version, + 1 + ); + assert_eq!(second_campaign.institutions.len(), 3); + assert!( + second_campaign.gestalts["harrow-residents"] + .shared_knowledge + .iter() + .any(|fact| fact.contains("unvoted emergency courier fund")) + ); + assert!(model.saw_current_civic_context.load(Ordering::SeqCst)); + assert_eq!(model.calls.load(Ordering::SeqCst), 8); } #[tokio::test] @@ -7279,6 +8528,10 @@ mod tests { populations: vec![], population_profiles: vec![], migration_relations: vec![], + institutions: vec![], + institution_profiles: vec![], + local_relations: vec![], + civic_system: None, } } diff --git a/crates/ghostlight-dungeon/src/consumer.rs b/crates/ghostlight-dungeon/src/consumer.rs index d0142ff..9485466 100644 --- a/crates/ghostlight-dungeon/src/consumer.rs +++ b/crates/ghostlight-dungeon/src/consumer.rs @@ -17,6 +17,7 @@ pub const APPLY_EXTERNAL_SNAPSHOT_OPERATION: &str = "ghostlight.world.external.s pub const LIST_EXTERNAL_PROPOSALS_OPERATION: &str = "ghostlight.world.external.proposals.list"; pub const ACKNOWLEDGE_EXTERNAL_PROPOSAL_OPERATION: &str = "ghostlight.world.external.proposal.acknowledge"; +pub const COMPOSE_NEWSPAPER_OPERATION: &str = "ghostlight.world.newspaper.compose"; #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] #[serde(rename_all = "snake_case")] @@ -65,6 +66,7 @@ impl WorldSeed { || !campaign.transcript.is_empty() || !campaign.events.is_empty() || !campaign.news.is_empty() + || !campaign.civic_systems.is_empty() || !campaign.pending_world_proposals.is_empty() || campaign.pending_ticks != 0 || campaign.away_ticks_processed != 0 @@ -73,7 +75,7 @@ impl WorldSeed { || campaign.strategic_tick_count != 0 { return Err(anyhow!( - "world seed cannot contain already-authoritative runtime state" + "world seed cannot contain already-authoritative runtime or civic state" )); } Ok(Self { @@ -114,6 +116,7 @@ impl WorldSeed { institutions: self.institutions, clocks: self.clocks, facts: self.facts, + civic_systems: BTreeMap::new(), transcript: Vec::new(), last_player_activity: self.world_time, pending_ticks: 0, @@ -309,6 +312,18 @@ pub struct ExternalProposalReceipt { pub acknowledged_at: DateTime, } +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +pub struct WorldNewspaperRequest { + pub schema: String, + pub campaign_id: Uuid, + pub authority_id: String, + pub owner_id: String, + pub authority_key: String, + pub title: String, + #[schemars(range(min = 1, max = 64))] + pub max_articles: u16, +} + pub fn authority_key_digest(value: &str) -> String { format!("sha256:{:x}", Sha256::digest(value.as_bytes())) } diff --git a/crates/ghostlight-dungeon/src/domain.rs b/crates/ghostlight-dungeon/src/domain.rs index 49a7786..568e504 100644 --- a/crates/ghostlight-dungeon/src/domain.rs +++ b/crates/ghostlight-dungeon/src/domain.rs @@ -19,6 +19,8 @@ pub struct Campaign { pub institutions: BTreeMap, pub clocks: BTreeMap, pub facts: BTreeMap, + #[serde(default)] + pub civic_systems: BTreeMap, pub transcript: Vec, pub last_player_activity: DateTime, pub pending_ticks: u8, @@ -1089,6 +1091,14 @@ pub enum WorldCommand { #[serde(default)] model_stage_receipts: Vec, }, + ElaborateLocality { + expected_revision: u64, + elaboration: LocalityElaboration, + evidence_receipts: Vec, + canon_candidates: Vec, + #[serde(default)] + model_stage_receipts: Vec, + }, MaterializeGestaltMember { expected_revision: u64, gestalt_id: String, @@ -1154,6 +1164,53 @@ pub struct RegionExpansion { /// relations and the physical topology. #[serde(default)] pub migration_relations: Vec, + /// Institutions admitted with the region or locality. Institutions remain + /// distinct strategic subjects; population leaves may know public civic + /// facts without inheriting an institution's goals, resources, or voice. + #[serde(default)] + pub institutions: Vec, + /// Exact agency inputs for `institutions`. + #[serde(default)] + pub institution_profiles: Vec, + /// Political and administrative relations among newly admitted local + /// institutions and populations. Migration remains in its separate lane. + #[serde(default)] + pub local_relations: Vec, + /// Structural receipt proving that an inhabited locality exposes enough + /// committed public state for ordinary civic questions. The facts may say + /// that no mayor or election exists; a player's presupposition never gets + /// to choose the answer. + #[serde(default)] + pub civic_system: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +pub struct CivicSystemManifest { + pub schema: String, + #[serde(default)] + pub version: u64, + pub jurisdiction_location_id: String, + pub governing_institution_ids: BTreeSet, + pub resident_population_ids: BTreeSet, + pub public_authority_fact_ids: BTreeSet, + pub public_selection_fact_ids: BTreeSet, + pub public_resource_fact_ids: BTreeSet, + pub public_redress_fact_ids: BTreeSet, + pub political_relation_ids: BTreeSet, + /// Exact locally rebound verifier receipt that covers this complete civic + /// candidate. The compiler supplies it after inference; models never own + /// this binding. + #[serde(default)] + pub semantic_verification_receipt_id: String, +} + +/// Admission of bounded child detail beneath one exact canonical coarse place. +/// The target identity is immutable; the nested expansion contains only new +/// subjects, facts, child places, and edges admitted beneath it. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct LocalityElaboration { + pub target_location_id: String, + pub expansion: RegionExpansion, } #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] @@ -1174,6 +1231,27 @@ pub struct RegionExpansionPreview { pub requires_approval: bool, } +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct LocalityElaborationPreview { + pub schema: String, + pub campaign_id: Uuid, + pub expected_revision: u64, + pub elaboration: LocalityElaboration, + pub evidence_receipts: Vec, + #[serde(default)] + pub branch_assumptions: Vec, + pub gaps: Vec, + pub canon_candidates: Vec, + pub requires_approval: bool, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +#[serde(tag = "kind", content = "preview", rename_all = "snake_case")] +pub enum DestinationCompilationPreview { + RegionExpansion(RegionExpansionPreview), + LocalityElaboration(LocalityElaborationPreview), +} + #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] #[serde(rename_all = "snake_case")] pub enum TickSource { diff --git a/crates/ghostlight-dungeon/src/kernel.rs b/crates/ghostlight-dungeon/src/kernel.rs index 18bb1f3..92e9df5 100644 --- a/crates/ghostlight-dungeon/src/kernel.rs +++ b/crates/ghostlight-dungeon/src/kernel.rs @@ -324,6 +324,8 @@ fn execute( } } } + crate::compiler::validate_campaign_runtime(&campaign) + .map_err(|error| KernelError::Invalid(error.to_string()))?; let previous_world_revision = campaign.revision; campaign.revision = campaign.revision.saturating_add(1); let now = Utc::now(); @@ -1275,6 +1277,21 @@ fn execute( apply_individuation(&mut campaign, &proposal.individuation)?; } } + let individuation_public_channels = resolved_plan + .as_ref() + .or(plan.as_ref()) + .map(|plan| { + plan.selected_actions + .iter() + .map(|action| { + crate::resolution::cell_action_digest(action) + .map(|digest| (digest, action.public_channels.clone())) + .map_err(|error| KernelError::Invalid(error.to_string())) + }) + .collect::, _>>() + }) + .transpose()? + .unwrap_or_default(); let applied_tick = match resolved_plan.or(plan) { Some(plan) => apply_strategic_tick_plan(&mut campaign, plan)?, None => { @@ -1305,7 +1322,10 @@ fn execute( institution_ids: vec![], gestalt_ids: vec![proposal.individuation.gestalt_id.clone()], location_ids: vec![proposal.individuation.location_id.clone()], - public_channels: vec![], + public_channels: individuation_public_channels + .get(&proposal.action_digest) + .cloned() + .unwrap_or_default(), }); } } @@ -1322,7 +1342,7 @@ fn execute( channel: channel.clone(), headline: event.summary.clone(), event_ids: vec![event.id.clone()], - reliability: "direct institutional channel".into(), + reliability: "committed public channel".into(), }); } } @@ -1356,36 +1376,10 @@ fn execute( model_stage_receipts, } => { require_revision(&campaign, expected_revision)?; - let supplied_evidence = evidence_receipts - .iter() - .map(|receipt| receipt.id.as_str()) - .collect::>(); - if expansion.facts.iter().any(|fact| { - 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 - .iter() - .any(|id| !supplied_evidence.contains(id.as_str())) - }) { - return Err(KernelError::Invalid( - "region expansion evidence receipts were not supplied".into(), - )); - } - crate::compiler::validate_region_expansion(&campaign, &expansion) + validate_region_admission_evidence(&expansion, &evidence_receipts, &canon_candidates)?; + crate::compiler::validate_new_destination_expansion(&campaign, &expansion) .map_err(|error| KernelError::Invalid(error.to_string()))?; + validate_civic_admission_receipt(&campaign, &expansion, &model_stage_receipts)?; let transition = crate::legacy_transition::lower_region_expansion( &campaign, &expansion, @@ -1415,6 +1409,55 @@ fn execute( Some((transition, mutation_receipt)), ) } + WorldCommand::ElaborateLocality { + expected_revision, + elaboration, + evidence_receipts, + canon_candidates, + model_stage_receipts, + } => { + require_revision(&campaign, expected_revision)?; + validate_region_admission_evidence( + &elaboration.expansion, + &evidence_receipts, + &canon_candidates, + )?; + crate::compiler::validate_locality_elaboration(&campaign, &elaboration) + .map_err(|error| KernelError::Invalid(error.to_string()))?; + validate_civic_admission_receipt( + &campaign, + &elaboration.expansion, + &model_stage_receipts, + )?; + let transition = crate::legacy_transition::lower_region_expansion( + &campaign, + &elaboration.expansion, + Utc::now() + Duration::minutes(5), + ) + .map_err(|error| KernelError::Invalid(error.to_string()))?; + let mutation_receipt = crate::legacy_transition::apply_lowered_region_expansion( + &mut campaign, + &elaboration.expansion, + &transition, + Utc::now(), + ) + .map_err(|error| KernelError::Invalid(error.to_string()))?; + for candidate in &canon_candidates { + campaign + .canon_candidates + .insert(candidate.id.clone(), candidate.clone()); + } + commit_with_records( + store, + row, + campaign, + "elaborate_locality", + evidence_receipts, + canon_candidates, + model_stage_receipts, + Some((transition, mutation_receipt)), + ) + } WorldCommand::MaterializeGestaltMember { expected_revision, gestalt_id, @@ -2328,6 +2371,88 @@ fn require_revision(c: &Campaign, expected: u64) -> Result<(), KernelError> { } } +fn validate_region_admission_evidence( + expansion: &RegionExpansion, + evidence_receipts: &[VaultEvidenceReceipt], + canon_candidates: &[CanonCandidate], +) -> Result<(), KernelError> { + let supplied_evidence = evidence_receipts + .iter() + .map(|receipt| receipt.id.as_str()) + .collect::>(); + let missing_profile_evidence = expansion + .population_profiles + .iter() + .chain(expansion.institution_profiles.iter()) + .any(|profile| { + profile + .evidence_receipt_ids + .iter() + .any(|id| !supplied_evidence.contains(id.as_str())) + }); + let missing_relation_evidence = expansion + .migration_relations + .iter() + .chain(expansion.local_relations.iter()) + .any(|relation| { + relation + .evidence_receipt_ids + .iter() + .any(|id| !supplied_evidence.contains(id.as_str())) + }); + if expansion.facts.iter().any(|fact| { + fact.evidence_receipt_ids + .iter() + .any(|id| !supplied_evidence.contains(id.as_str())) + }) || missing_profile_evidence + || missing_relation_evidence + || canon_candidates.iter().any(|candidate| { + candidate + .evidence_receipt_ids + .iter() + .any(|id| !supplied_evidence.contains(id.as_str())) + }) + { + return Err(KernelError::Invalid( + "region admission evidence receipts were not supplied".into(), + )); + } + Ok(()) +} + +fn validate_civic_admission_receipt( + campaign: &Campaign, + expansion: &RegionExpansion, + model_stage_receipts: &[crate::model::ModelStageReceipt], +) -> Result<(), KernelError> { + let Some(system) = &expansion.civic_system else { + return Ok(()); + }; + let candidate_digest = crate::compiler::civic_candidate_digest(expansion) + .map_err(|error| KernelError::Invalid(error.to_string()))?; + let expected_binding = crate::compiler::civic_verifier_binding(campaign, &candidate_digest); + let receipt = model_stage_receipts + .iter() + .find(|receipt| receipt.storage_key() == system.semantic_verification_receipt_id) + .ok_or_else(|| { + KernelError::Invalid("civic admission lacks its exact semantic verifier receipt".into()) + })?; + let mut rebound = receipt.clone(); + rebound.rebind_snapshot(receipt.snapshot_binding.clone()); + if receipt.schema != "ghostlight.persona_stage_receipt.v1" + || receipt.stage != "destination_civic_verification" + || receipt.validation_result != "valid" + || receipt.local_validation_error.is_some() + || receipt.snapshot_binding != expected_binding + || rebound.storage_key() != receipt.storage_key() + { + return Err(KernelError::Invalid( + "civic admission semantic verifier receipt is invalid or candidate-mismatched".into(), + )); + } + Ok(()) +} + fn is_human_controlled_actor(campaign: &Campaign, actor_id: &str) -> bool { actor_id == campaign.player_actor_id || campaign @@ -4106,7 +4231,7 @@ fn persist(e: anyhow::Error) -> KernelError { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet}; @@ -4174,7 +4299,7 @@ mod tests { assert_eq!(after, &expected); } - fn campaign() -> Campaign { + pub(crate) fn campaign() -> Campaign { let id = uuid::Uuid::new_v4(); let actor = ActorState { id: "player".into(), @@ -4215,6 +4340,7 @@ mod tests { institutions: BTreeMap::new(), clocks: BTreeMap::new(), facts: BTreeMap::new(), + civic_systems: BTreeMap::new(), transcript: vec![], last_player_activity: Utc::now(), pending_ticks: 0, @@ -4235,6 +4361,237 @@ mod tests { } } + fn civic_locality_elaboration() -> LocalityElaboration { + let public_facts = [ + ( + "fact:room-authority", + "Mayor Selka Vey holds the civic seal while the ward assembly controls appropriations.", + ), + ( + "fact:room-selection", + "Residents elected Selka Vey over Oren Vale at the last mayoral ballot.", + ), + ( + "fact:room-resources", + "Published berth dues fund the civic treasury.", + ), + ( + "fact:room-redress", + "Residents may appeal a mayoral order to the ward petitions bench.", + ), + ]; + let facts = public_facts + .iter() + .map(|(id, statement)| WorldFact { + id: (*id).into(), + statement: (*statement).into(), + scope: FactScope::BranchLocal, + evidence_receipt_ids: vec![], + discoverable_at_location_ids: BTreeSet::from([ + "room".into(), + "civic-quarter".into(), + ]), + }) + .collect::>(); + let institution_profile = |id: &str, authority: &str| AgencyProfile { + schema: "ghostlight.agency_profile.v1".into(), + id: format!("agency:{id}"), + subject_id: id.into(), + subject_kind: AgencySubjectKind::Institution, + profile_version: 0, + collective_authority_id: None, + parent_subject_id: None, + active_leaf: true, + simulation_eligible: true, + facets: BTreeMap::from([ + (AgencyAxis::Geography, BTreeSet::from(["room".into()])), + ( + AgencyAxis::Ideology, + BTreeSet::from(["public mandate".into()]), + ), + (AgencyAxis::Authority, BTreeSet::from([authority.into()])), + ( + AgencyAxis::EconomyRole, + BTreeSet::from(["civic administration".into()]), + ), + ( + AgencyAxis::SpeciesBody, + BTreeSet::from(["mixed residents".into()]), + ), + ( + AgencyAxis::Information, + BTreeSet::from(["ward notices".into()]), + ), + ]), + location_ids: BTreeSet::from(["civic-quarter".into()]), + information_channels: BTreeSet::from(["ward notice board".into()]), + detail_debt: 0, + last_detail_tick: 0, + evidence_receipt_ids: vec![], + }; + LocalityElaboration { + target_location_id: "room".into(), + expansion: RegionExpansion { + origin_location_id: "room".into(), + origin_routes: BTreeMap::from([( + "to-civic-quarter".into(), + Route { + destination_id: "civic-quarter".into(), + distance: "through the public arcade".into(), + travel_minutes: 5, + }, + )]), + locations: vec![Location { + id: "civic-quarter".into(), + name: "Civic Quarter".into(), + container_id: Some("room".into()), + routes: BTreeMap::from([( + "to-room".into(), + Route { + destination_id: "room".into(), + distance: "back through the public arcade".into(), + travel_minutes: 5, + }, + )]), + persistent_features: vec!["sealed ballot archive".into()], + }], + facts, + populations: vec![GestaltPersonaState { + schema: "ghostlight.gestalt_persona_state.v1".into(), + id: "room-residents".into(), + name: "Room residents".into(), + version: 0, + home_location_id: "civic-quarter".into(), + shared_capabilities: BTreeSet::from(["participate in ward ballots".into()]), + shared_knowledge: public_facts + .iter() + .map(|(_, statement)| (*statement).into()) + .collect(), + resources: BTreeSet::from(["ward hall".into()]), + goals: vec!["keep the treasury answerable".into()], + pressures: vec!["the mayor and assembly dispute appropriations".into()], + }], + population_profiles: vec![AgencyProfile { + schema: "ghostlight.agency_profile.v1".into(), + id: "agency:room-residents".into(), + subject_id: "room-residents".into(), + subject_kind: AgencySubjectKind::Gestalt, + profile_version: 0, + collective_authority_id: Some("room-residents".into()), + parent_subject_id: None, + active_leaf: true, + simulation_eligible: true, + facets: BTreeMap::from([ + (AgencyAxis::Geography, BTreeSet::from(["room".into()])), + ( + AgencyAxis::Ideology, + BTreeSet::from(["ward representation".into()]), + ), + ( + AgencyAxis::Authority, + BTreeSet::from(["resident franchise".into()]), + ), + ( + AgencyAxis::EconomyRole, + BTreeSet::from(["berth work".into()]), + ), + ( + AgencyAxis::SpeciesBody, + BTreeSet::from(["mixed residents".into()]), + ), + ( + AgencyAxis::Information, + BTreeSet::from(["ward notices".into()]), + ), + ]), + location_ids: BTreeSet::from(["civic-quarter".into()]), + information_channels: BTreeSet::from(["ward notice board".into()]), + detail_debt: 0, + last_detail_tick: 0, + evidence_receipt_ids: vec![], + }], + migration_relations: vec![], + institutions: vec![ + InstitutionState { + id: "mayoral-office".into(), + name: "Mayoral Office".into(), + resources: vec!["civic seal".into()], + goals: vec!["retain emergency spending discretion".into()], + posture: "press for immediate appropriation".into(), + }, + InstitutionState { + id: "ward-assembly".into(), + name: "Ward Assembly".into(), + resources: vec!["appropriations ledger".into()], + goals: vec!["bind spending to public accounts".into()], + posture: "withhold funds pending audit".into(), + }, + ], + institution_profiles: vec![ + institution_profile("mayoral-office", "mayoral orders"), + institution_profile("ward-assembly", "appropriations"), + ], + local_relations: vec![AgencyRelation { + schema: "ghostlight.agency_relation.v1".into(), + id: "relation:mayor-assembly".into(), + from_subject_id: "mayoral-office".into(), + to_subject_id: "ward-assembly".into(), + kind: AgencyRelationKind::Rivalry, + strength: 72, + active: true, + evidence_receipt_ids: vec![], + }], + civic_system: Some(CivicSystemManifest { + schema: "ghostlight.civic_system_manifest.v1".into(), + version: 0, + jurisdiction_location_id: "room".into(), + governing_institution_ids: BTreeSet::from([ + "mayoral-office".into(), + "ward-assembly".into(), + ]), + resident_population_ids: BTreeSet::from(["room-residents".into()]), + public_authority_fact_ids: BTreeSet::from(["fact:room-authority".into()]), + public_selection_fact_ids: BTreeSet::from(["fact:room-selection".into()]), + public_resource_fact_ids: BTreeSet::from(["fact:room-resources".into()]), + public_redress_fact_ids: BTreeSet::from(["fact:room-redress".into()]), + political_relation_ids: BTreeSet::from(["relation:mayor-assembly".into()]), + semantic_verification_receipt_id: String::new(), + }), + }, + } + } + + fn civic_verifier_receipt( + campaign: &Campaign, + expansion: &mut RegionExpansion, + ) -> crate::model::ModelStageReceipt { + let digest = crate::compiler::civic_candidate_digest(expansion).unwrap(); + let mut receipt = crate::model::ModelStageReceipt { + schema: "ghostlight.persona_stage_receipt.v1".into(), + receipt_hash: String::new(), + provider: "fixture".into(), + model: "fixture".into(), + stage: "destination_civic_verification".into(), + snapshot_binding: String::new(), + request_hash: test_action_digest("civic-verifier-request"), + output_hash: test_action_digest("civic-verifier-output"), + source_receipt_ids: vec![], + latency_ms: 1, + validation_result: "valid".into(), + local_validation_error: None, + input_chars: 1, + output_chars: 1, + provider_attempts: vec![], + }; + receipt.rebind_snapshot(crate::compiler::civic_verifier_binding(campaign, &digest)); + expansion + .civic_system + .as_mut() + .unwrap() + .semantic_verification_receipt_id = receipt.storage_key().to_owned(); + receipt + } + #[tokio::test] async fn resolved_outcome_cannot_admit_an_unrequested_gestalt_member() { let dir = tempfile::tempdir().unwrap(); @@ -4562,6 +4919,7 @@ mod tests { place_profiles: BTreeMap::new(), propositions: BTreeMap::new(), topology: BTreeMap::new(), + civic_systems: BTreeMap::new(), }; let initial_world_time = state.world_time; store.create_component_world_state(&state).unwrap(); @@ -6679,6 +7037,10 @@ mod tests { populations: vec![], population_profiles: vec![], migration_relations: vec![], + institutions: vec![], + institution_profiles: vec![], + local_relations: vec![], + civic_system: None, }, evidence_receipts: vec![evidence], canon_candidates: vec![candidate], @@ -6878,6 +7240,10 @@ mod tests { populations: vec![population], population_profiles: vec![profile], migration_relations: vec![relation], + institutions: vec![], + institution_profiles: vec![], + local_relations: vec![], + civic_system: None, }, evidence_receipts: vec![evidence], canon_candidates: vec![], @@ -6909,6 +7275,200 @@ mod tests { ); } + #[tokio::test] + async fn locality_elaboration_preserves_the_city_and_grounds_a_named_residents_vote() { + let dir = tempfile::tempdir().unwrap(); + let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); + let kernel = WorldKernel::start(store); + let seed = campaign(); + let original = seed.locations["room"].clone(); + let mut elaboration = civic_locality_elaboration(); + let verifier_receipt = civic_verifier_receipt(&seed, &mut elaboration.expansion); + kernel + .command(WorldCommand::CreateCampaign { + campaign: seed, + evidence_receipts: vec![], + model_stage_receipts: vec![], + }) + .await + .unwrap(); + + let committed = kernel + .command(WorldCommand::ElaborateLocality { + expected_revision: 0, + elaboration, + evidence_receipts: vec![], + canon_candidates: vec![], + model_stage_receipts: vec![verifier_receipt], + }) + .await + .unwrap(); + let CommandResult::Committed { + campaign: elaborated, + .. + } = committed + else { + panic!("expected committed locality elaboration") + }; + assert_eq!(elaborated.locations["room"].id, original.id); + assert_eq!(elaborated.locations["room"].name, original.name); + assert_eq!( + elaborated.locations["room"].persistent_features, + original.persistent_features + ); + assert_eq!( + elaborated.locations["civic-quarter"] + .container_id + .as_deref(), + Some("room") + ); + assert_eq!(elaborated.institutions.len(), 2); + assert_eq!(elaborated.civic_systems["room"].version, 0); + assert!( + !elaborated.civic_systems["room"] + .semantic_verification_receipt_id + .is_empty() + ); + assert_eq!( + elaborated.agency_relations["relation:mayor-assembly"].kind, + AgencyRelationKind::Rivalry + ); + let selection = elaborated.facts["fact:room-selection"].statement.clone(); + assert!( + elaborated.gestalts["room-residents"] + .shared_knowledge + .contains(&selection) + ); + + let named = kernel + .command(WorldCommand::IndividuateGestaltMember { + expected_revision: 1, + individuation: GestaltIndividuation { + gestalt_id: "room-residents".into(), + expected_gestalt_version: 0, + member: GestaltMemberDelta { + schema: "ghostlight.gestalt_member_delta.v1".into(), + id: "iren-vale".into(), + gestalt_id: "room-residents".into(), + version: 0, + name: "Iren Vale".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!["make berth dues transparent".into()], + memories: vec![ + "I voted for Oren Vale because he promised a public berth audit." + .into(), + ], + last_location_id: Some("civic-quarter".into()), + materialized_actor_id: None, + last_relevant_revision: 0, + relevance_lease_until_revision: 0, + }, + location_id: "civic-quarter".into(), + }, + }) + .await + .unwrap(); + let CommandResult::Committed { + campaign: individuated, + .. + } = named + else { + panic!("expected committed resident individuation") + }; + let resident = &individuated.actors["member:iren-vale"]; + assert!(resident.knowledge.contains(&selection)); + assert!(resident.memories[0].contains("Oren Vale")); + } + + #[tokio::test] + async fn invalid_civic_locality_leaves_the_coarse_city_untouched() { + let dir = tempfile::tempdir().unwrap(); + let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); + let kernel = WorldKernel::start(store.clone()); + let seed = campaign(); + let campaign_id = seed.id; + kernel + .command(WorldCommand::CreateCampaign { + campaign: seed, + evidence_receipts: vec![], + model_stage_receipts: vec![], + }) + .await + .unwrap(); + let mut elaboration = civic_locality_elaboration(); + elaboration.expansion.populations[0] + .shared_knowledge + .remove("Residents elected Selka Vey over Oren Vale at the last mayoral ballot."); + + let error = kernel + .command(WorldCommand::ElaborateLocality { + expected_revision: 0, + elaboration, + evidence_receipts: vec![], + canon_candidates: vec![], + model_stage_receipts: vec![], + }) + .await + .unwrap_err(); + assert!(error.to_string().contains("public civic facts")); + let stored = store + .load::("campaign.v1", &campaign_id.to_string()) + .unwrap() + .unwrap() + .1; + assert_eq!(stored.revision, 0); + assert_eq!(stored.locations.len(), 1); + assert!(stored.institutions.is_empty()); + assert!(stored.gestalts.is_empty()); + } + + #[tokio::test] + async fn structurally_valid_civic_locality_requires_its_bound_semantic_receipt() { + let dir = tempfile::tempdir().unwrap(); + let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); + let kernel = WorldKernel::start(store.clone()); + let seed = campaign(); + let campaign_id = seed.id; + kernel + .command(WorldCommand::CreateCampaign { + campaign: seed, + evidence_receipts: vec![], + model_stage_receipts: vec![], + }) + .await + .unwrap(); + + let error = kernel + .command(WorldCommand::ElaborateLocality { + expected_revision: 0, + elaboration: civic_locality_elaboration(), + evidence_receipts: vec![], + canon_candidates: vec![], + model_stage_receipts: vec![], + }) + .await + .unwrap_err(); + assert!( + error.to_string().contains("semantic verifier receipt"), + "{error}" + ); + let stored = store + .load::("campaign.v1", &campaign_id.to_string()) + .unwrap() + .unwrap() + .1; + assert_eq!(stored.revision, 0); + assert!(stored.civic_systems.is_empty()); + assert!(stored.institutions.is_empty()); + } + #[tokio::test] async fn gestalt_member_dematerializes_to_delta_and_returns_as_same_person() { let dir = tempfile::tempdir().unwrap(); @@ -8038,7 +8598,10 @@ mod tests { stage: &str, marker: char, ) -> crate::model::ModelStageReceipt { - let hash = format!("sha256:{}", marker.to_string().repeat(64)); + let hash = test_action_digest(&format!( + "resolution-stage:{}:{}:{}:{}:{}", + campaign.id, campaign.revision, cell_id, stage, marker + )); crate::model::ModelStageReceipt { schema: "ghostlight.persona_stage_receipt.v1".into(), receipt_hash: hash.clone(), @@ -8680,7 +9243,12 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); let kernel = WorldKernel::start(store.clone()); - let seed = hierarchical_refugee_campaign(); + let mut seed = hierarchical_refugee_campaign(); + seed.agency_profiles + .get_mut("refugees-east") + .unwrap() + .information_channels + .insert("storm-camp broadsheet".into()); kernel .command(WorldCommand::CreateCampaign { campaign: seed.clone(), @@ -8712,13 +9280,15 @@ mod tests { let action = CellActionProposal { subject_id: "refugees-east".into(), intent: "appoint a named storm delegation broker".into(), - intended_effect: "make one person accountable for the camp negotiation".into(), + intended_effect: "make one accuser answer for the camp negotiation".into(), priority: 80, state_references: vec!["subject:refugees-east".into(), "location:camp".into()], - public_channels: vec![], + public_channels: vec!["storm-camp broadsheet".into()], effects: vec![StrategicCellEffect::Gestalt { gestalt_id: "refugees-east".into(), - pressure_additions: vec!["the storm delegation needs an accountable broker".into()], + pressure_additions: vec![ + "Veska Rill says the east quartermasters sold the lower road twice".into(), + ], pressure_resolutions: vec![], }], }; @@ -8728,7 +9298,8 @@ mod tests { wave.strategic_individuations = vec![StrategicGestaltIndividuation { schema: "ghostlight.strategic_gestalt_individuation.v1".into(), action_digest: action_digest.clone(), - rationale: "The camp needs one accountable storm broker.".into(), + rationale: + "She accused the east quartermasters of selling the broken lower road twice.".into(), individuation: GestaltIndividuation { gestalt_id: "refugees-east".into(), expected_gestalt_version: 0, @@ -8809,7 +9380,10 @@ mod tests { }) .await .unwrap_err(); - assert!(error.to_string().contains("payload-bound selector receipt")); + assert!( + error.to_string().contains("payload-bound selector receipt"), + "{error}" + ); let unchanged = store .load::("campaign.v1", &seed.id.to_string()) .unwrap() @@ -8843,11 +9417,103 @@ mod tests { .iter() .any(|event| event.kind == "gestalt_individuation") ); + assert!(campaign.news.iter().any(|issue| { + issue.channel == "storm-camp broadsheet" && issue.headline.contains("Veska Rill") + })); + let newspaper = + crate::newspaper::compose_world_newspaper(&campaign, "The Underdeep Clarion", 8) + .unwrap(); + let rendered = crate::newspaper::render_world_newspaper_markdown(&newspaper); + assert!(rendered.contains("Names to Know")); + assert!(rendered.contains("Veska Rill")); + assert!( + rendered.contains("selling the broken lower road twice"), + "{rendered}" + ); let proposals = store .load_all::("strategic_gestalt_individuation.v1") .unwrap(); assert_eq!(proposals.len(), 1); assert_eq!(proposals[0].action_digest, action_digest); + + let mut second_wave = inaction_wave(&campaign, &store); + let second_cell_id = second_wave + .cover + .cells + .iter() + .find(|cell| cell.subject_ids.contains("member:veska-rill")) + .unwrap() + .id + .clone(); + let second_appraisal = second_wave + .appraisals + .iter_mut() + .find(|appraisal| appraisal.cell_id == second_cell_id) + .unwrap(); + second_appraisal.considered_subject_ids = BTreeSet::from(["member:veska-rill".into()]); + let second_action = CellActionProposal { + subject_id: "member:veska-rill".into(), + intent: "cross the bay to confront the quartermasters".into(), + intended_effect: "arrive at the south docks without resolving the accusation".into(), + priority: 91, + state_references: vec![], + public_channels: vec![], + effects: vec![StrategicCellEffect::ActorMove { + actor_id: "member:veska-rill".into(), + destination_id: "docks".into(), + }], + }; + second_appraisal.actions = vec![second_action.clone()]; + second_appraisal.inactions.clear(); + let second_base_binding = format!( + "campaign:{}:revision:{}:resolution:{}:cell:{}", + campaign.id, + campaign.revision, + campaign.resolution_policy.resolution_epoch, + second_cell_id + ); + let mut second_verifier = + resolution_stage(&second_cell_id, &campaign, "cell_effect_verifier", 'v'); + second_verifier.snapshot_binding = crate::persona::cell_effect_verification_binding( + &second_base_binding, + std::slice::from_ref(&second_action), + ) + .unwrap(); + store + .insert( + "persona_stage_receipt.v1", + "ghostlight.persona_stage_receipt.v1", + second_verifier.storage_key(), + &second_verifier, + ) + .unwrap(); + second_wave + .model_receipt_hashes + .push(second_verifier.storage_key().to_owned()); + let result = kernel + .command(WorldCommand::AdvanceStrategicTick { + expected_revision: campaign.revision, + source: TickSource::Scheduler, + plan: None, + model_receipt_hash: Some(test_action_digest("second-veska-wave")), + resolution_wave: Some(second_wave), + }) + .await + .unwrap(); + let CommandResult::Committed { + campaign: campaign_after_second_wave, + .. + } = result + else { + panic!() + }; + assert_eq!( + campaign_after_second_wave.actors["member:veska-rill"].location_id, + "docks" + ); + assert!(campaign_after_second_wave.events.iter().any(|event| { + event.kind == "actor_movement" && event.actor_ids.contains(&"member:veska-rill".into()) + })); } #[tokio::test] diff --git a/crates/ghostlight-dungeon/src/legacy_transition.rs b/crates/ghostlight-dungeon/src/legacy_transition.rs index 61967b4..6f703c6 100644 --- a/crates/ghostlight-dungeon/src/legacy_transition.rs +++ b/crates/ghostlight-dungeon/src/legacy_transition.rs @@ -383,6 +383,54 @@ pub fn lower_region_expansion( }); } } + for institution in &expansion.institutions { + let subject = institution_subject(&institution.id); + mutations.push(WorldMutation::AdmitEntity { + subject: subject.clone(), + initial_components: BTreeSet::from([ + WorldComponentKind::Identity, + WorldComponentKind::Posture, + WorldComponentKind::Commitment, + ]), + initial_place: None, + 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:{}", institution.id), + handle_value: Some(institution.name.clone()), + audience: Vec::new(), + }); + mutations.push(WorldMutation::ChangePosture { + subject: subject.clone(), + posture: institution.posture.clone(), + }); + for (index, goal) in institution.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 resource in &institution.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("institution_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 { @@ -416,6 +464,59 @@ pub fn lower_region_expansion( strength_delta: Some(i64::from(relation.strength)), }); } + for relation in &expansion.local_relations { + mutations.push(WorldMutation::ChangeRelationship { + source: expansion_agency_subject(campaign, expansion, &relation.from_subject_id)?, + target: expansion_agency_subject(campaign, expansion, &relation.to_subject_id)?, + operation: RelationshipMutationOperation::Create, + relationship_id: relation.id.clone(), + description: Some(agency_relation_kind_label(&relation.kind).into()), + strength_delta: Some(i64::from(relation.strength)), + }); + } + if let Some(system) = &expansion.civic_system { + let new_population_ids = expansion + .populations + .iter() + .map(|population| population.id.as_str()) + .collect::>(); + for resident_id in &system.resident_population_ids { + if new_population_ids.contains(resident_id.as_str()) { + continue; + } + let resident = campaign.gestalts.get(resident_id).ok_or_else(|| { + anyhow!("civic manifest references an unknown existing resident population") + })?; + for fact_id in system + .public_authority_fact_ids + .iter() + .chain(system.public_selection_fact_ids.iter()) + .chain(system.public_resource_fact_ids.iter()) + .chain(system.public_redress_fact_ids.iter()) + { + let fact = expansion + .facts + .iter() + .find(|fact| fact.id == *fact_id) + .or_else(|| campaign.facts.get(fact_id)) + .ok_or_else(|| anyhow!("civic manifest references an unknown fact"))?; + if !resident.shared_knowledge.contains(&fact.statement) { + mutations.push(WorldMutation::ChangeKnowledge { + operation: KnowledgeMutationOperation::Acquire, + proposition: proposition_subject(fact_id), + knower: Some(population_subject(resident_id)), + speaker: None, + recipients: Vec::new(), + channel: None, + }); + } + } + } + mutations.push(WorldMutation::SetCivicSystem { + jurisdiction: place_subject(&system.jurisdiction_location_id), + system: system.clone(), + }); + } lower_exact_mutations( campaign, mutations, @@ -423,7 +524,7 @@ pub fn lower_region_expansion( None, MutationOutcomeBinding::Deterministic, None, - "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.", + "Admit only the approved place profiles, proposition contents, population leaves, institutions, agency inputs, and exact local or 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", @@ -566,6 +667,90 @@ fn project_accepted_region_expansion( .agency_profiles .insert(profile.subject_id.clone(), profile); } + for requested in &expansion.institutions { + let subject = institution_subject(&requested.id); + let identity = next + .identities + .get(&format!("identity:canonical:{}", requested.id)) + .filter(|identity| identity.subject == subject && identity.active) + .ok_or_else(|| anyhow!("accepted destination institution lost identity"))?; + let posture = next + .postures + .get(&subject) + .ok_or_else(|| anyhow!("accepted destination institution lost posture"))?; + let mut institution = requested.clone(); + institution.name = identity.value.clone(); + institution.posture = posture.clone(); + campaign + .institutions + .insert(institution.id.clone(), institution); + } + for requested in &expansion.institution_profiles { + campaign + .agency_profiles + .insert(requested.subject_id.clone(), requested.clone()); + } + for requested in &expansion.local_relations { + let source = expansion_agency_subject(campaign, expansion, &requested.from_subject_id)?; + let target = expansion_agency_subject(campaign, expansion, &requested.to_subject_id)?; + let value = next + .relationships + .get(&requested.id) + .filter(|value| value.source == source && value.target == target) + .ok_or_else(|| anyhow!("accepted destination local 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 let Some(requested) = &expansion.civic_system { + let jurisdiction = place_subject(&requested.jurisdiction_location_id); + let accepted = next + .civic_systems + .get(&jurisdiction) + .filter(|system| *system == requested) + .ok_or_else(|| anyhow!("accepted destination civic system vanished"))?; + campaign + .civic_systems + .insert(accepted.jurisdiction_location_id.clone(), accepted.clone()); + for resident_id in &accepted.resident_population_ids { + let resident = campaign + .gestalts + .get_mut(resident_id) + .ok_or_else(|| anyhow!("accepted civic resident population vanished"))?; + for fact_id in accepted + .public_authority_fact_ids + .iter() + .chain(accepted.public_selection_fact_ids.iter()) + .chain(accepted.public_resource_fact_ids.iter()) + .chain(accepted.public_redress_fact_ids.iter()) + { + let proposition = proposition_subject(fact_id); + if !next + .knowledge + .contains_key(&crate::transition::KnowledgeKey { + knower: population_subject(resident_id), + proposition: proposition.clone(), + }) + { + return Err(anyhow!("accepted civic resident lost public knowledge")); + } + resident.shared_knowledge.insert( + next.propositions + .get(&proposition) + .ok_or_else(|| anyhow!("accepted civic fact lost proposition content"))? + .statement + .clone(), + ); + } + } + } for requested in &expansion.migration_relations { let value = next .relationships @@ -586,7 +771,7 @@ fn project_accepted_region_expansion( .agency_relations .insert(relation.id.clone(), relation); } - if !expansion.populations.is_empty() { + if !expansion.populations.is_empty() || !expansion.institutions.is_empty() { campaign.resolution_cover = None; campaign.resolution_policy.resolution_epoch = campaign .resolution_policy @@ -1618,6 +1803,16 @@ fn component_snapshot(campaign: &Campaign) -> Result { place_profiles: BTreeMap::new(), propositions: BTreeMap::new(), topology: BTreeMap::new(), + civic_systems: campaign + .civic_systems + .values() + .map(|system| { + ( + place_subject(&system.jurisdiction_location_id), + system.clone(), + ) + }) + .collect(), }; admit( &mut state, @@ -2840,6 +3035,53 @@ fn resolve_subject(campaign: &Campaign, id: &str) -> Option { } } +fn expansion_agency_subject( + campaign: &Campaign, + expansion: &crate::domain::RegionExpansion, + id: &str, +) -> Result { + if expansion + .institutions + .iter() + .any(|institution| institution.id == id) + { + Ok(institution_subject(id)) + } else if expansion + .populations + .iter() + .any(|population| population.id == id) + { + Ok(population_subject(id)) + } else if let Some(subject) = resolve_subject(campaign, id) + && matches!( + subject.kind, + SubjectKind::Institution | SubjectKind::Population + ) + { + Ok(subject) + } else { + Err(anyhow!( + "local relation references a subject outside the expansion" + )) + } +} + +fn agency_relation_kind_label(kind: &crate::domain::AgencyRelationKind) -> &'static str { + use crate::domain::AgencyRelationKind::*; + match kind { + Containment => "containment", + Command => "command", + Membership => "membership", + Alliance => "alliance", + Rivalry => "rivalry", + Trade => "trade", + Migration => "migration", + Communication => "communication", + Coercion => "coercion", + SharedLocation => "shared_location", + } +} + fn ensure_member<'a>( campaign: &'a Campaign, member_id: &str, @@ -3127,6 +3369,7 @@ mod tests { discoverable_at_location_ids: BTreeSet::from(["room".into()]), }, )]), + civic_systems: BTreeMap::new(), transcript: vec![], last_player_activity: Utc::now(), pending_ticks: 0, diff --git a/crates/ghostlight-dungeon/src/lib.rs b/crates/ghostlight-dungeon/src/lib.rs index a2d6bdb..80293a3 100644 --- a/crates/ghostlight-dungeon/src/lib.rs +++ b/crates/ghostlight-dungeon/src/lib.rs @@ -14,6 +14,7 @@ pub mod legacy_transition; pub mod mesh; pub mod model; pub mod model_connector; +pub mod newspaper; pub mod outcome; pub mod persistence; pub mod persona; diff --git a/crates/ghostlight-dungeon/src/main.rs b/crates/ghostlight-dungeon/src/main.rs index 6731338..b6bb86a 100644 --- a/crates/ghostlight-dungeon/src/main.rs +++ b/crates/ghostlight-dungeon/src/main.rs @@ -17,7 +17,7 @@ use ghostlight_dungeon::{ assessor::ActionAssessor, compiler::{GestaltFissionRequest, OpeningRequest, OpeningSuggestion, WorldCompiler}, domain::{ - ActionIntent, Campaign, GestaltFissionPreview, RegionExpansionPreview, + ActionIntent, Campaign, DestinationCompilationPreview, GestaltFissionPreview, RejectedProposalReceipt, WorldCommand, }, gestalt::{GestaltPresencePlanner, required_addressed_promotions}, @@ -80,7 +80,7 @@ struct AppState { compiler: Option>, assessor: Option>, model: Option>, - expansion_previews: Arc>>>, + expansion_previews: Arc>>>, fission_previews: Arc>>, live_turns: Arc, live_turn_started: Arc, @@ -4071,7 +4071,7 @@ async fn compile_destination( ); Json(serde_json::json!({ "preview_id":id, - "preview":region_expansion_preview_projection(&preview), + "preview":destination_compilation_preview_projection(&preview), })) .into_response() } @@ -4108,17 +4108,25 @@ async fn approve_destination( return (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(); } }; - match runtime - .kernel - .command(WorldCommand::ExpandRegion { + let command = match preview { + DestinationCompilationPreview::RegionExpansion(preview) => WorldCommand::ExpandRegion { expected_revision: preview.expected_revision, expansion: preview.expansion, evidence_receipts: preview.evidence_receipts, canon_candidates: preview.canon_candidates, model_stage_receipts: model_receipts, - }) - .await - { + }, + DestinationCompilationPreview::LocalityElaboration(preview) => { + WorldCommand::ElaborateLocality { + expected_revision: preview.expected_revision, + elaboration: preview.elaboration, + evidence_receipts: preview.evidence_receipts, + canon_candidates: preview.canon_candidates, + model_stage_receipts: model_receipts, + } + } + }; + match runtime.kernel.command(command).await { Ok(value) => Json(player_command_projection(&value)).into_response(), Err(error) => (StatusCode::CONFLICT, error.to_string()).into_response(), } @@ -5379,19 +5387,49 @@ fn world_compile_preview_projection(preview: &WorldCompilePreview) -> serde_json }) } -fn region_expansion_preview_projection(preview: &RegionExpansionPreview) -> serde_json::Value { - serde_json::json!({ - "origin_location_id":preview.expansion.origin_location_id, - "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, - "branch_assumptions":preview.branch_assumptions, - "gaps":preview.gaps, - "requires_approval":preview.requires_approval, - }) +fn destination_compilation_preview_projection( + preview: &DestinationCompilationPreview, +) -> serde_json::Value { + match preview { + DestinationCompilationPreview::RegionExpansion(preview) => serde_json::json!({ + "kind":"region_expansion", + "target_location_id":null, + "origin_location_id":preview.expansion.origin_location_id, + "origin_routes":preview.expansion.origin_routes, + "locations":preview.expansion.locations, + "facts":preview.expansion.facts, + "populations":preview.expansion.populations, + "population_profiles":preview.expansion.population_profiles, + "institutions":preview.expansion.institutions, + "institution_profiles":preview.expansion.institution_profiles, + "local_relations":preview.expansion.local_relations, + "migration_relations":preview.expansion.migration_relations, + "civic_system":preview.expansion.civic_system, + "branch_assumptions":preview.branch_assumptions, + "gaps":preview.gaps, + "requires_approval":preview.requires_approval, + }), + DestinationCompilationPreview::LocalityElaboration(preview) => { + serde_json::json!({ + "kind":"locality_elaboration", + "target_location_id":preview.elaboration.target_location_id, + "origin_location_id":preview.elaboration.expansion.origin_location_id, + "origin_routes":preview.elaboration.expansion.origin_routes, + "locations":preview.elaboration.expansion.locations, + "facts":preview.elaboration.expansion.facts, + "populations":preview.elaboration.expansion.populations, + "population_profiles":preview.elaboration.expansion.population_profiles, + "institutions":preview.elaboration.expansion.institutions, + "institution_profiles":preview.elaboration.expansion.institution_profiles, + "local_relations":preview.elaboration.expansion.local_relations, + "migration_relations":preview.elaboration.expansion.migration_relations, + "civic_system":preview.elaboration.expansion.civic_system, + "branch_assumptions":preview.branch_assumptions, + "gaps":preview.gaps, + "requires_approval":preview.requires_approval, + }) + } + } } fn gestalt_fission_preview_projection(preview: &GestaltFissionPreview) -> serde_json::Value { @@ -5489,6 +5527,7 @@ fn player_http_command_allowed(command: &WorldCommand, player_actor_id: &str) -> | WorldCommand::ApproveResolutionBudget { .. } | WorldCommand::AdvanceStrategicTick { .. } | WorldCommand::ExpandRegion { .. } + | WorldCommand::ElaborateLocality { .. } | WorldCommand::MaterializeGestaltMember { .. } | WorldCommand::DematerializeGestaltMember { .. } | WorldCommand::IndividuateGestaltMember { .. } @@ -6503,6 +6542,7 @@ mod tests { institutions: BTreeMap::new(), clocks: BTreeMap::new(), facts: BTreeMap::new(), + civic_systems: BTreeMap::new(), transcript: vec![], last_player_activity: chrono::Utc::now(), pending_ticks: 0, @@ -7248,11 +7288,13 @@ mod tests { .strip_prefix("/ghostlight") .expect("public resource URI must stay below the Ghostlight mount"); let token = uri.rsplit('/').next().unwrap(); - let app_session_bytes = std::fs::read(dir.path().join("app-sessions.cc")).unwrap(); assert!( - !app_session_bytes - .windows(token.len()) - .any(|window| window == token.as_bytes()) + !state + .auth + .lock() + .await + .persisted_bytes_contain(token) + .unwrap() ); let intruder = app @@ -7454,7 +7496,8 @@ mod tests { validate_player_http_command(&WorldCommand::SetResolutionBudget { expected_revision: 0, expected_resolution_epoch: 0, - active_cell_budget: 129, + active_cell_budget: ghostlight_dungeon::resolution::MAX_ACTIVE_CELL_BUDGET + .saturating_add(1), }) .is_err() ); diff --git a/crates/ghostlight-dungeon/src/mesh.rs b/crates/ghostlight-dungeon/src/mesh.rs index 0b0824d..18d0e84 100644 --- a/crates/ghostlight-dungeon/src/mesh.rs +++ b/crates/ghostlight-dungeon/src/mesh.rs @@ -213,7 +213,8 @@ impl MeshPublisher { "ghostlight.world.seed.admit", "ghostlight.world.external.snapshot.apply", "ghostlight.world.external.proposals.list", - "ghostlight.world.external.proposal.acknowledge" + "ghostlight.world.external.proposal.acknowledge", + "ghostlight.world.newspaper.compose" ], "ownership":"Consumers own declared external subjects; Ghostlight owns all simulated world subjects and emits proposals across that boundary." }, @@ -592,7 +593,9 @@ fn schema_catalog() -> Value { "ghostlight.external_proposal_list_request.v1": schemars::schema_for!(crate::consumer::ExternalProposalListRequest), "ghostlight.external_proposal_list.v1": schemars::schema_for!(crate::consumer::ExternalProposalList), "ghostlight.external_proposal_acknowledgement.v1": schemars::schema_for!(crate::consumer::ExternalProposalAcknowledgement), - "ghostlight.external_proposal_receipt.v1": schemars::schema_for!(crate::consumer::ExternalProposalReceipt) + "ghostlight.external_proposal_receipt.v1": schemars::schema_for!(crate::consumer::ExternalProposalReceipt), + "ghostlight.world_newspaper_request.v1": schemars::schema_for!(crate::consumer::WorldNewspaperRequest), + "ghostlight.world_newspaper_issue.v1": schemars::schema_for!(crate::newspaper::WorldNewspaperIssue) }) } @@ -620,10 +623,12 @@ mod tests { .get_required::("ghostlight:schema-catalog") .unwrap(); let schemas = catalog.value["schemas"].as_object().unwrap(); - assert_eq!(schemas.len(), 14); + assert_eq!(schemas.len(), 16); assert!(schemas["ghostlight.campaign.v1"]["$schema"].is_string()); assert!(schemas["ghostlight.session_zero.v1"]["$schema"].is_string()); assert!(schemas["ghostlight.vault_source_manifest.v1"]["$schema"].is_string()); + assert!(schemas["ghostlight.world_newspaper_request.v1"]["$schema"].is_string()); + assert!(schemas["ghostlight.world_newspaper_issue.v1"]["$schema"].is_string()); assert!(!schemas.contains_key("ghostlight.persona_stage_receipt.v1")); assert!(!schemas.contains_key("ghostlight.world_mutation.v1")); drop(catalog); diff --git a/crates/ghostlight-dungeon/src/native_cultmesh.rs b/crates/ghostlight-dungeon/src/native_cultmesh.rs index 0c7a636..df38107 100644 --- a/crates/ghostlight-dungeon/src/native_cultmesh.rs +++ b/crates/ghostlight-dungeon/src/native_cultmesh.rs @@ -303,6 +303,14 @@ async fn handle_operation_inner( .await?; success_response(request, "ghostlight.external_proposal_receipt.v1", &receipt) } + ghostlight_dungeon::consumer::COMPOSE_NEWSPAPER_OPERATION => { + require_schema(payload_schema, "ghostlight.world_newspaper_request.v1")?; + let command: ghostlight_dungeon::consumer::WorldNewspaperRequest = + decode_request(request)?; + require_schema(&command.schema, "ghostlight.world_newspaper_request.v1")?; + let issue = state.registry.compose_world_newspaper(command).await?; + success_response(request, "ghostlight.world_newspaper_issue.v1", &issue) + } _ => bail!("world consumer operation is not advertised by Ghostlight"), }; } diff --git a/crates/ghostlight-dungeon/src/newspaper.rs b/crates/ghostlight-dungeon/src/newspaper.rs new file mode 100644 index 0000000..79244fe --- /dev/null +++ b/crates/ghostlight-dungeon/src/newspaper.rs @@ -0,0 +1,221 @@ +use crate::domain::{Campaign, Event}; +use anyhow::{Result, anyhow}; +use chrono::{DateTime, Utc}; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +pub struct WorldNewspaperIssue { + pub schema: String, + pub id: String, + pub title: String, + pub at: DateTime, + pub source_world_revision: u64, + pub articles: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +pub struct WorldNewspaperArticle { + pub id: String, + pub section: String, + pub headline: String, + pub dateline: Option, + pub body: String, + pub channel: String, + pub reliability: String, + pub event_ids: Vec, +} + +pub fn compose_world_newspaper( + campaign: &Campaign, + title: impl Into, + max_articles: usize, +) -> Result { + if max_articles == 0 { + return Err(anyhow!("newspaper article budget must be positive")); + } + let title = title.into(); + if title.trim().is_empty() { + return Err(anyhow!("newspaper title is empty")); + } + let events = campaign + .events + .iter() + .map(|event| (event.id.as_str(), event)) + .collect::>(); + let mut news = campaign.news.iter().collect::>(); + news.sort_by(|left, right| right.at.cmp(&left.at).then_with(|| left.id.cmp(&right.id))); + + let mut articles = Vec::new(); + for issue in news.into_iter().take(max_articles) { + if issue.event_ids.is_empty() { + return Err(anyhow!("news item {} has no committed event", issue.id)); + } + let source_events = issue + .event_ids + .iter() + .map(|event_id| { + let event = events.get(event_id.as_str()).copied().ok_or_else(|| { + anyhow!("news item {} cites unknown event {event_id}", issue.id) + })?; + if !event.public_channels.contains(&issue.channel) { + return Err(anyhow!( + "news item {} uses channel absent from event {event_id}", + issue.id + )); + } + Ok(event) + }) + .collect::>>()?; + let primary = source_events[0]; + let dateline = event_dateline(campaign, primary); + let body = source_events + .iter() + .map(|event| event.summary.trim()) + .collect::>() + .join(" "); + if body.is_empty() { + return Err(anyhow!("news item {} cites an empty event", issue.id)); + } + articles.push(WorldNewspaperArticle { + id: format!("article:{}", issue.id), + section: section_for(primary).into(), + headline: issue.headline.clone(), + dateline, + body, + channel: issue.channel.clone(), + reliability: issue.reliability.clone(), + event_ids: issue.event_ids.clone(), + }); + } + let at = articles + .first() + .and_then(|article| { + article + .event_ids + .first() + .and_then(|event_id| events.get(event_id.as_str())) + .map(|event| event.at) + }) + .unwrap_or(campaign.world_time); + let identity = rmp_serde::to_vec_named(&( + campaign.id, + campaign.revision, + &title, + articles + .iter() + .map(|article| &article.id) + .collect::>(), + ))?; + Ok(WorldNewspaperIssue { + schema: "ghostlight.world_newspaper_issue.v1".into(), + id: format!("newspaper:sha256:{:x}", Sha256::digest(identity)), + title, + at, + source_world_revision: campaign.revision, + articles, + }) +} + +pub fn render_world_newspaper_markdown(issue: &WorldNewspaperIssue) -> String { + let mut rendered = format!( + "# {}\n\n*World revision {} · {}*\n", + issue.title, + issue.source_world_revision, + issue.at.format("%Y-%m-%d %H:%M UTC") + ); + for article in &issue.articles { + rendered.push_str(&format!( + "\n## {} — {}\n\n", + article.section, article.headline + )); + if let Some(dateline) = &article.dateline { + rendered.push_str(&format!("**{dateline}** — ")); + } + rendered.push_str(&article.body); + rendered.push_str(&format!( + "\n\n*Via {} · {} · events: {}*\n", + article.channel, + article.reliability, + article.event_ids.join(", ") + )); + } + rendered +} + +fn event_dateline(campaign: &Campaign, event: &Event) -> Option { + event.location_ids.first().map(|location_id| { + campaign + .locations + .get(location_id) + .map(|location| location.name.clone()) + .unwrap_or_else(|| location_id.clone()) + }) +} + +fn section_for(event: &Event) -> &'static str { + match event.kind.as_str() { + "institution_action" => "Courts & Councils", + "gestalt_individuation" => "Names to Know", + "strategic_activity_outcome" => "Dispatches", + "gestalt_action" | "gestalt_activity" | "gestalt_migration" => "Realms", + _ => "World", + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::{Event, NewsIssue}; + + #[test] + fn newspaper_is_a_projection_of_public_committed_events() { + let mut campaign = crate::kernel::tests::campaign(); + campaign.revision = 3; + campaign.events.push(Event { + id: "event:seal-scandal".into(), + at: campaign.world_time, + kind: "institution_action".into(), + summary: + "The Thorn Court admits its royal seal was pawned to pay a dragon's gambling debt." + .into(), + actor_ids: vec![], + institution_ids: vec![], + gestalt_ids: vec![], + location_ids: vec!["room".into()], + public_channels: vec!["court broadsheet".into()], + }); + campaign.news.push(NewsIssue { + id: "news:seal-scandal".into(), + at: campaign.world_time, + channel: "court broadsheet".into(), + headline: "CROWN SEAL PAWNED; DRAGON REFUSES COMMENT".into(), + event_ids: vec!["event:seal-scandal".into()], + reliability: "committed public channel".into(), + }); + + let issue = compose_world_newspaper(&campaign, "The Underdeep Clarion", 8).unwrap(); + let markdown = render_world_newspaper_markdown(&issue); + assert_eq!(issue.articles[0].event_ids, ["event:seal-scandal"]); + assert!(markdown.contains("CROWN SEAL PAWNED")); + assert!(markdown.contains("dragon's gambling debt")); + assert!(markdown.contains("event:seal-scandal")); + } + + #[test] + fn newspaper_rejects_a_headline_without_a_committed_event() { + let mut campaign = crate::kernel::tests::campaign(); + campaign.news.push(NewsIssue { + id: "news:invented".into(), + at: campaign.world_time, + channel: "whisper wire".into(), + headline: "UNFOUNDED NONSENSE".into(), + event_ids: vec!["event:missing".into()], + reliability: "rumor".into(), + }); + let error = compose_world_newspaper(&campaign, "The Clarion", 8).unwrap_err(); + assert!(error.to_string().contains("unknown event")); + } +} diff --git a/crates/ghostlight-dungeon/src/outcome.rs b/crates/ghostlight-dungeon/src/outcome.rs index cb29ce7..bad8632 100644 --- a/crates/ghostlight-dungeon/src/outcome.rs +++ b/crates/ghostlight-dungeon/src/outcome.rs @@ -2687,6 +2687,7 @@ mod tests { discoverable_at_location_ids: BTreeSet::from(["dock".into()]), }, )]), + civic_systems: BTreeMap::new(), transcript: vec![], last_player_activity: Utc::now(), pending_ticks: 0, diff --git a/crates/ghostlight-dungeon/src/persistence.rs b/crates/ghostlight-dungeon/src/persistence.rs index bbe4d1c..761a25f 100644 --- a/crates/ghostlight-dungeon/src/persistence.rs +++ b/crates/ghostlight-dungeon/src/persistence.rs @@ -831,43 +831,75 @@ impl CampaignStore { &expected.key, &manifest, )?); - for item in evidence { - rows.push(envelope( - "vault_evidence_receipt.v1", - "ghostlight.vault_evidence_receipt.v1", - &item.id, - item, - )?); - } - for item in candidates { - rows.push(envelope( - "canon_candidate.v1", - "ghostlight.canon_candidate.v1", - &item.id, - item, - )?); - } - for item in model_receipts { - rows.push(envelope( - "persona_stage_receipt.v1", - "ghostlight.persona_stage_receipt.v1", - item.storage_key(), - item, - )?); - } - if let Some(mutation) = mutation { - append_mutation_proof(&mut rows, receipt, mutation)?; - } let mut expected_rows = vec![expected.clone()]; if let Some((row, _)) = existing_manifest { expected_rows.push(row); } + for item in evidence { + self.append_idempotent_companion( + &mut expected_rows, + &mut rows, + envelope( + "vault_evidence_receipt.v1", + "ghostlight.vault_evidence_receipt.v1", + &item.id, + item, + )?, + )?; + } + for item in candidates { + self.append_idempotent_companion( + &mut expected_rows, + &mut rows, + envelope( + "canon_candidate.v1", + "ghostlight.canon_candidate.v1", + &item.id, + item, + )?, + )?; + } + for item in model_receipts { + self.append_idempotent_companion( + &mut expected_rows, + &mut rows, + envelope( + "persona_stage_receipt.v1", + "ghostlight.persona_stage_receipt.v1", + item.storage_key(), + item, + )?, + )?; + } + if let Some(mutation) = mutation { + append_mutation_proof(&mut rows, receipt, mutation)?; + } if !self.inner.compare_and_swap_batch(&expected_rows, rows)? { return Err(anyhow!("stale CultCache snapshot")); } Ok(next_row) } + fn append_idempotent_companion( + &self, + expected: &mut Vec, + replacements: &mut Vec, + row: CultCacheEnvelope, + ) -> Result<()> { + if let Some(existing) = self.load_envelope(&row.r#type, &row.key)? { + if existing != row { + return Err(anyhow!( + "immutable world-commit companion conflict: {}/{}", + row.r#type, + row.key + )); + } + expected.push(existing); + } + replacements.push(row); + Ok(()) + } + pub fn append_strategic_tick( &self, expected: &CultCacheEnvelope, diff --git a/crates/ghostlight-dungeon/src/registry.rs b/crates/ghostlight-dungeon/src/registry.rs index 0b7bf35..e3d503b 100644 --- a/crates/ghostlight-dungeon/src/registry.rs +++ b/crates/ghostlight-dungeon/src/registry.rs @@ -2,9 +2,9 @@ use crate::{ consumer::{ ExternalProposalAcknowledgement, ExternalProposalList, ExternalProposalListRequest, ExternalProposalReceipt, ExternalProposalStatus, ExternalSubjectAuthority, - ExternalWorldProposal, WorldSeed, WorldSeedAdmission, WorldSeedAdmissionReceipt, - WorldSeedAdmissionRequest, WorldSeedProducerKind, validate_authority_key, - validate_seed_admission, + ExternalWorldProposal, WorldNewspaperRequest, WorldSeed, WorldSeedAdmission, + WorldSeedAdmissionReceipt, WorldSeedAdmissionRequest, WorldSeedProducerKind, + validate_authority_key, validate_seed_admission, }, domain::{Campaign, CampaignLifecycleReceipt, VaultEvidenceReceipt}, kernel::WorldKernel, @@ -376,6 +376,42 @@ impl CampaignRegistry { }) } + pub async fn compose_world_newspaper( + &self, + request: WorldNewspaperRequest, + ) -> Result { + if request.schema != "ghostlight.world_newspaper_request.v1" + || request.max_articles == 0 + || request.max_articles > 64 + { + return Err(anyhow!("world newspaper request is invalid")); + } + let runtime = self.runtime(request.campaign_id).await?; + let (_, authority) = runtime + .store + .load::( + "external_subject_authority.v1", + &request.authority_id, + )? + .ok_or_else(|| anyhow!("external subject authority is unknown"))?; + if authority.campaign_id != request.campaign_id || authority.owner_id != request.owner_id { + return Err(anyhow!( + "world newspaper request does not match its authority" + )); + } + validate_authority_key(&authority, &request.authority_key)?; + let campaign = runtime + .store + .load::("campaign.v1", &request.campaign_id.to_string())? + .ok_or_else(|| anyhow!("campaign is missing"))? + .1; + crate::newspaper::compose_world_newspaper( + &campaign, + request.title, + usize::from(request.max_articles), + ) + } + pub async fn acknowledge_external_proposal( &self, acknowledgement: ExternalProposalAcknowledgement, @@ -674,6 +710,7 @@ mod tests { institutions: BTreeMap::new(), clocks: BTreeMap::new(), facts: BTreeMap::new(), + civic_systems: BTreeMap::new(), transcript: vec![], last_player_activity: Utc::now(), pending_ticks: 0, @@ -1145,6 +1182,16 @@ mod tests { posture: "watchful".into(), }, ); + campaign.institutions.insert( + "inner-court".into(), + crate::domain::InstitutionState { + id: "inner-court".into(), + name: "The Inner Court".into(), + resources: vec!["sealed minutes".into()], + goals: vec!["control the grain audit".into()], + posture: "denying that the missing grain has political significance".into(), + }, + ); campaign.gestalts.insert( "external-population".into(), crate::domain::GestaltPersonaState { @@ -1218,6 +1265,29 @@ mod tests { ); let (_, repeated) = registry.admit_world_seed(request).await.unwrap(); assert_eq!(repeated.seed_digest, receipt.seed_digest); + let newspaper_request = crate::consumer::WorldNewspaperRequest { + schema: "ghostlight.world_newspaper_request.v1".into(), + campaign_id: campaign.id, + authority_id: "authority:external-hold".into(), + owner_id: "fixture-consumer".into(), + authority_key: authority_key.into(), + title: "The Consumer Gazette".into(), + max_articles: 12, + }; + let mut denied_newspaper = newspaper_request.clone(); + denied_newspaper.authority_key = "wrong-key".into(); + assert!( + registry + .compose_world_newspaper(denied_newspaper) + .await + .is_err() + ); + let newspaper = registry + .compose_world_newspaper(newspaper_request.clone()) + .await + .unwrap(); + assert_eq!(newspaper.source_world_revision, 0); + assert!(newspaper.articles.is_empty()); let mut snapshot = crate::consumer::ExternalSubjectSnapshot { schema: "ghostlight.external_subject_snapshot.v1".into(), @@ -1318,6 +1388,51 @@ mod tests { .revision, 1 ); + let mut invalid_gestalt_snapshot = crate::consumer::ExternalSubjectSnapshot { + schema: "ghostlight.external_subject_snapshot.v1".into(), + campaign_id: campaign.id, + expected_world_revision: 1, + authority_id: "authority:external-population".into(), + owner_id: "fixture-consumer".into(), + authority_key: authority_key.into(), + source_revision: 1, + idempotency_key: "population-invalid-home".into(), + payload_digest: String::new(), + projection: crate::consumer::ExternalSubjectProjection::Gestalt( + crate::domain::GestaltPersonaState { + schema: "ghostlight.gestalt_persona_state.v1".into(), + id: "external-population".into(), + name: "External Population".into(), + version: 2, + home_location_id: "invented-place".into(), + shared_capabilities: BTreeSet::from(["farming".into()]), + shared_knowledge: BTreeSet::from(["old road".into()]), + resources: BTreeSet::new(), + goals: vec!["endure".into()], + pressures: Vec::new(), + }, + ), + }; + invalid_gestalt_snapshot.payload_digest = + crate::consumer::snapshot_payload_digest(&invalid_gestalt_snapshot).unwrap(); + let error = registry + .apply_external_subject_snapshot(invalid_gestalt_snapshot) + .await + .unwrap_err(); + assert!( + error.to_string().contains("unknown home location"), + "{error}" + ); + assert_eq!( + runtime + .store + .load::("campaign.v1", &campaign.id.to_string()) + .unwrap() + .unwrap() + .1 + .revision, + 1 + ); let mut gestalt_snapshot = crate::consumer::ExternalSubjectSnapshot { schema: "ghostlight.external_subject_snapshot.v1".into(), campaign_id: campaign.id, @@ -1363,6 +1478,42 @@ mod tests { [&crate::domain::AgencyAxis::EconomyRole] .contains("milling") ); + runtime + .kernel + .command(crate::domain::WorldCommand::AdvanceStrategicTick { + expected_revision: 2, + source: crate::domain::TickSource::Scheduler, + plan: Some(crate::domain::StrategicTickPlan { + institution_actions: vec![crate::domain::StrategicInstitutionAction { + institution_id: "inner-court".into(), + posture: + "accusing three granary auditors of being one witch in a long coat" + .into(), + location_ids: vec!["room".into()], + public_channels: vec!["court broadsheet".into()], + }], + ..Default::default() + }), + model_receipt_hash: Some(format!("sha256:{}", "a".repeat(64))), + resolution_wave: None, + }) + .await + .unwrap(); + let newspaper = registry + .compose_world_newspaper(newspaper_request) + .await + .unwrap(); + assert_eq!(newspaper.source_world_revision, 3); + assert_eq!(newspaper.articles.len(), 1); + assert_eq!( + newspaper.articles[0].event_ids, + ["strategic:3:institution:inner-court"] + ); + assert!( + newspaper.articles[0] + .body + .contains("one witch in a long coat") + ); let proposal = ExternalWorldProposal { schema: "ghostlight.external_world_proposal.v1".into(), id: "external-proposal:test".into(), diff --git a/crates/ghostlight-dungeon/src/resolution.rs b/crates/ghostlight-dungeon/src/resolution.rs index a3b5612..5643c61 100644 --- a/crates/ghostlight-dungeon/src/resolution.rs +++ b/crates/ghostlight-dungeon/src/resolution.rs @@ -3419,6 +3419,7 @@ pub(crate) mod tests { institutions, clocks: BTreeMap::new(), facts: BTreeMap::new(), + civic_systems: BTreeMap::new(), transcript: vec![], last_player_activity: Utc::now(), pending_ticks: 0, diff --git a/crates/ghostlight-dungeon/src/surface.rs b/crates/ghostlight-dungeon/src/surface.rs index 45bd833..56bbb8c 100644 --- a/crates/ghostlight-dungeon/src/surface.rs +++ b/crates/ghostlight-dungeon/src/surface.rs @@ -617,7 +617,7 @@ mod tests { channel: "public bulletin".into(), headline: "The public ferry is delayed.".into(), event_ids: vec!["event:public".into()], - reliability: "direct institutional channel".into(), + reliability: "committed public channel".into(), }); campaign .agency_profiles @@ -658,7 +658,7 @@ mod tests { channel: "sealed command wire".into(), headline: "SECRET_COMMAND_MOVEMENT".into(), event_ids: vec!["event:sealed".into()], - reliability: "direct institutional channel".into(), + reliability: "committed public channel".into(), }); campaign .actors diff --git a/crates/ghostlight-dungeon/src/transition.rs b/crates/ghostlight-dungeon/src/transition.rs index 457578a..0974c39 100644 --- a/crates/ghostlight-dungeon/src/transition.rs +++ b/crates/ghostlight-dungeon/src/transition.rs @@ -1,4 +1,4 @@ -use crate::domain::{FactScope, OutcomeBand, StrategicOutcomeBand}; +use crate::domain::{CivicSystemManifest, FactScope, OutcomeBand, StrategicOutcomeBand}; use anyhow::{Result, anyhow}; use chrono::{DateTime, Utc}; use schemars::{JsonSchema, schema_for}; @@ -53,6 +53,7 @@ pub enum WorldComponentKind { PlaceProfile, PropositionContent, Topology, + CivicSystem, Lifecycle, WorldTime, } @@ -183,6 +184,7 @@ pub enum WorldMutationOperation { TopologyOpen, TopologyClose, TopologyRetire, + CivicSystemSet, AdmitEntity, RetireEntity, AdvanceWorldTime, @@ -574,6 +576,10 @@ pub enum WorldMutation { distance: Option, travel_minutes: Option, }, + SetCivicSystem { + jurisdiction: SubjectRef, + system: CivicSystemManifest, + }, AdmitEntity { subject: SubjectRef, initial_components: BTreeSet, @@ -838,6 +844,8 @@ pub struct ComponentWorldState { #[serde(default)] pub propositions: BTreeMap, pub topology: BTreeMap, + #[serde(default)] + pub civic_systems: BTreeMap, } fn default_route_distance() -> String { @@ -1310,6 +1318,10 @@ fn apply_component_mutation( distance.as_deref(), *travel_minutes, )?, + SetCivicSystem { + jurisdiction, + system, + } => apply_civic_system(state, jurisdiction, system)?, AdmitEntity { subject, initial_components, @@ -1387,6 +1399,80 @@ fn apply_component_mutation( Ok(()) } +fn apply_civic_system( + state: &mut ComponentWorldState, + jurisdiction: &SubjectRef, + system: &CivicSystemManifest, +) -> Result<()> { + active_subject(state, jurisdiction)?; + require_kind(jurisdiction, SubjectKind::Place)?; + if system.schema != "ghostlight.civic_system_manifest.v1" + || system.jurisdiction_location_id != jurisdiction.id + || system.semantic_verification_receipt_id.trim().is_empty() + { + return Err(anyhow!( + "civic system is not bound to its exact jurisdiction and verifier" + )); + } + let expected_version = state + .civic_systems + .get(jurisdiction) + .map(|current| current.version.saturating_add(1)) + .unwrap_or(0); + if system.version != expected_version { + return Err(anyhow!( + "civic system version is stale: expected {expected_version}, got {}", + system.version + )); + } + for id in &system.governing_institution_ids { + let subject = SubjectRef { + kind: SubjectKind::Institution, + id: id.clone(), + }; + active_subject(state, &subject)?; + } + for id in &system.resident_population_ids { + let resident = SubjectRef { + kind: SubjectKind::Population, + id: id.clone(), + }; + active_subject(state, &resident)?; + for fact_id in system + .public_authority_fact_ids + .iter() + .chain(system.public_selection_fact_ids.iter()) + .chain(system.public_resource_fact_ids.iter()) + .chain(system.public_redress_fact_ids.iter()) + { + let proposition = SubjectRef { + kind: SubjectKind::Proposition, + id: fact_id.clone(), + }; + active_subject(state, &proposition)?; + if !state.knowledge.contains_key(&KnowledgeKey { + knower: resident.clone(), + proposition, + }) { + return Err(anyhow!( + "resident population lacks a civic proposition bound by the manifest" + )); + } + } + } + for id in &system.political_relation_ids { + if !state.relationships.contains_key(id) { + return Err(anyhow!( + "civic system references a missing political relation" + )); + } + } + state + .civic_systems + .insert(jurisdiction.clone(), system.clone()); + Ok(()) +} + #[allow(clippy::too_many_arguments)] fn apply_resource_mutation( state: &mut ComponentWorldState, @@ -2545,6 +2631,7 @@ fn retire_entity(state: &mut ComponentWorldState, subject: &SubjectRef) -> Resul record.version = version; state.place_profiles.remove(subject); state.propositions.remove(subject); + state.civic_systems.remove(subject); Ok(()) } @@ -2747,6 +2834,85 @@ pub fn validate_component_world(state: &ComponentWorldState) -> Result<()> { return Err(anyhow!("topology edge is malformed")); } } + for (jurisdiction, system) in &state.civic_systems { + active_subject(state, jurisdiction)?; + require_kind(jurisdiction, SubjectKind::Place)?; + if system.schema != "ghostlight.civic_system_manifest.v1" + || system.jurisdiction_location_id != jurisdiction.id + || system.semantic_verification_receipt_id.trim().is_empty() + { + return Err(anyhow!("canonical civic system is malformed")); + } + for id in &system.governing_institution_ids { + active_subject( + state, + &SubjectRef { + kind: SubjectKind::Institution, + id: id.clone(), + }, + )?; + } + for id in &system.resident_population_ids { + active_subject( + state, + &SubjectRef { + kind: SubjectKind::Population, + id: id.clone(), + }, + )?; + } + for id in system + .public_authority_fact_ids + .iter() + .chain(system.public_selection_fact_ids.iter()) + .chain(system.public_resource_fact_ids.iter()) + .chain(system.public_redress_fact_ids.iter()) + { + active_subject( + state, + &SubjectRef { + kind: SubjectKind::Proposition, + id: id.clone(), + }, + )?; + } + for resident_id in &system.resident_population_ids { + for proposition_id in system + .public_authority_fact_ids + .iter() + .chain(system.public_selection_fact_ids.iter()) + .chain(system.public_resource_fact_ids.iter()) + .chain(system.public_redress_fact_ids.iter()) + { + let key = KnowledgeKey { + knower: SubjectRef { + kind: SubjectKind::Population, + id: resident_id.clone(), + }, + proposition: SubjectRef { + kind: SubjectKind::Proposition, + id: proposition_id.clone(), + }, + }; + if !state + .knowledge + .get(&key) + .is_some_and(|knowledge| knowledge.status == "known") + { + return Err(anyhow!( + "canonical civic resident lost a public proposition" + )); + } + } + } + if system + .political_relation_ids + .iter() + .any(|id| !state.relationships.contains_key(id)) + { + return Err(anyhow!("canonical civic system lost a political relation")); + } + } Ok(()) } @@ -2851,6 +3017,9 @@ fn mutation_component_refs( Component::Topology, Some(edge_id.clone()), )], + SetCivicSystem { jurisdiction, .. } => { + vec![(jurisdiction.clone(), Component::CivicSystem, None)] + } AdmitEntity { subject, initial_place, @@ -3209,6 +3378,7 @@ fn subject_schema_fields( (TopologyOrigin, "from_place", Required), (TopologyDestination, "to_place", Required), ], + CivicSystemSet => vec![(Subject, "jurisdiction", Required)], AdmitEntity => vec![ (Entity, "subject", Required), (InitialPlace, "initial_place", Optional), @@ -3288,7 +3458,8 @@ fn string_schema_fields( RetireEntity => vec![(RetirementReason, "reason", Required)], TransferCustody | KnowledgeAcquire | KnowledgeCommunicate | KnowledgeConceal | KnowledgeCorrect | KnowledgeInvalidate | PopulationJoin | PopulationLeave - | PopulationTransfer | PopulationSplit | PopulationMerge | AdvanceWorldTime => vec![], + | PopulationTransfer | PopulationSplit | PopulationMerge | CivicSystemSet + | AdvanceWorldTime => vec![], } } @@ -3332,8 +3503,8 @@ fn integer_schema_fields( | KnowledgeCommunicate | KnowledgeConceal | KnowledgeCorrect | KnowledgeInvalidate | MemoryRecord | MemoryRevise | MemoryRetire | PostureChange | PopulationJoin | PopulationLeave | PopulationTransfer | PopulationSplit | PopulationMerge - | IdentityAdopt | IdentityDisclose | IdentityRestrict | IdentityRetire | AdmitEntity - | RetireEntity => vec![], + | IdentityAdopt | IdentityDisclose | IdentityRestrict | IdentityRetire | CivicSystemSet + | AdmitEntity | RetireEntity => vec![], } } @@ -3392,6 +3563,7 @@ fn mutation_schema_tags(operation: WorldMutationOperation) -> (&'static str, Opt TopologyOpen => ("change_topology", Some("open")), TopologyClose => ("change_topology", Some("close")), TopologyRetire => ("change_topology", Some("retire")), + CivicSystemSet => ("set_civic_system", None), AdmitEntity => ("admit_entity", None), RetireEntity => ("retire_entity", None), AdvanceWorldTime => ("advance_world_time", None), @@ -3560,6 +3732,7 @@ impl WorldMutation { TopologyMutationOperation::Close => WorldMutationOperation::TopologyClose, TopologyMutationOperation::Retire => WorldMutationOperation::TopologyRetire, }, + SetCivicSystem { .. } => WorldMutationOperation::CivicSystemSet, AdmitEntity { .. } => WorldMutationOperation::AdmitEntity, RetireEntity { .. } => WorldMutationOperation::RetireEntity, AdvanceWorldTime { .. } => WorldMutationOperation::AdvanceWorldTime, @@ -3698,6 +3871,7 @@ impl WorldMutation { add(MutationSubjectRole::TopologyOrigin, from_place); add(MutationSubjectRole::TopologyDestination, to_place); } + SetCivicSystem { jurisdiction, .. } => add(MutationSubjectRole::Subject, jurisdiction), AdmitEntity { subject, initial_place, @@ -3831,6 +4005,7 @@ impl WorldMutation { | ChangeKnowledge { .. } | ChangePopulationMembership { .. } | ChangePopulationLineage { .. } + | SetCivicSystem { .. } | AdvanceWorldTime { .. } => {} } values @@ -3885,6 +4060,7 @@ impl WorldMutation { | ChangePopulationMembership { .. } | ChangePopulationLineage { .. } | ChangeIdentity { .. } + | SetCivicSystem { .. } | AdmitEntity { .. } | RetireEntity { .. } => {} } @@ -4104,6 +4280,28 @@ impl WorldMutation { )); } } + SetCivicSystem { + jurisdiction, + system, + } => { + require_kind(jurisdiction, SubjectKind::Place)?; + if system.schema != "ghostlight.civic_system_manifest.v1" + || system.jurisdiction_location_id != jurisdiction.id + || system.governing_institution_ids.is_empty() + || system.resident_population_ids.is_empty() + || system.public_authority_fact_ids.is_empty() + || system.public_selection_fact_ids.is_empty() + || system.public_resource_fact_ids.is_empty() + || system.public_redress_fact_ids.is_empty() + || system.political_relation_ids.is_empty() + { + return Err(anyhow!("civic system mutation is incomplete")); + } + nonempty( + "civic semantic verifier receipt", + &system.semantic_verification_receipt_id, + )?; + } AdmitEntity { subject, initial_components, @@ -4690,9 +4888,69 @@ mod tests { version: 4, }, )]), + civic_systems: BTreeMap::new(), } } + #[test] + fn public_civic_knowledge_is_a_continuing_component_invariant() { + let mut state = component_world(); + let jurisdiction = subject(SubjectKind::Place, "place:camp"); + let institution = subject(SubjectKind::Institution, "institution:clinic"); + let resident = subject(SubjectKind::Population, "population:refugees"); + let proposition = subject(SubjectKind::Proposition, "proposition:east-trail"); + state.relationships.insert( + "relation:clinic-refugees".into(), + RelationshipComponentState { + source: institution, + target: resident.clone(), + description: "administers the camp under public challenge".into(), + strength: Some(55), + version: state.revision, + }, + ); + let resident_knowledge = KnowledgeKey { + knower: resident, + proposition: proposition.clone(), + }; + state.knowledge.insert( + resident_knowledge.clone(), + KnowledgeComponentState { + status: "known".into(), + source: None, + channel: None, + concealed_from: BTreeSet::new(), + version: state.revision, + }, + ); + state.civic_systems.insert( + jurisdiction, + CivicSystemManifest { + schema: "ghostlight.civic_system_manifest.v1".into(), + version: 0, + jurisdiction_location_id: "place:camp".into(), + governing_institution_ids: BTreeSet::from(["institution:clinic".into()]), + resident_population_ids: BTreeSet::from(["population:refugees".into()]), + public_authority_fact_ids: BTreeSet::from(["proposition:east-trail".into()]), + public_selection_fact_ids: BTreeSet::from(["proposition:east-trail".into()]), + public_resource_fact_ids: BTreeSet::from(["proposition:east-trail".into()]), + public_redress_fact_ids: BTreeSet::from(["proposition:east-trail".into()]), + political_relation_ids: BTreeSet::from(["relation:clinic-refugees".into()]), + semantic_verification_receipt_id: "receipt:civic".into(), + }, + ); + validate_component_world(&state).unwrap(); + + state.knowledge.remove(&resident_knowledge); + let error = validate_component_world(&state).unwrap_err(); + assert!( + error + .to_string() + .contains("civic resident lost a public proposition"), + "{error}" + ); + } + fn permit( id: &str, operation: WorldMutationOperation, diff --git a/crates/ghostlight-dungeon/src/vault.rs b/crates/ghostlight-dungeon/src/vault.rs index 9ec9e44..5acdc94 100644 --- a/crates/ghostlight-dungeon/src/vault.rs +++ b/crates/ghostlight-dungeon/src/vault.rs @@ -735,12 +735,16 @@ fn receipt( ) -> VaultEvidenceReceipt { let query_bytes = rmp_serde::to_vec_named(query).expect("query serializes"); let query_hash = format!("sha256:{:x}", Sha256::digest(query_bytes)); + let retrieved_at = Utc::now(); + let receipt_bytes = + rmp_serde::to_vec_named(&(provider, &query_hash, &witnesses, &retrieved_at)) + .expect("vault receipt identity serializes"); VaultEvidenceReceipt { schema: "ghostlight.vault_evidence_receipt.v1".into(), - id: format!("vault:{query_hash}"), + id: format!("vault:sha256:{:x}", Sha256::digest(receipt_bytes)), provider: provider.into(), query_hash, witnesses, - retrieved_at: Utc::now(), + retrieved_at, } } diff --git a/docs/architecture/ghostlight-transition-algebra.md b/docs/architecture/ghostlight-transition-algebra.md index 429e36f..c067dc9 100644 --- a/docs/architecture/ghostlight-transition-algebra.md +++ b/docs/architecture/ghostlight-transition-algebra.md @@ -1,7 +1,8 @@ # Ghostlight World Transition Algebra Status: adopted architecture; foreground, reaction, strategic, time, travel, -approval-gated fission, and bounded region expansion use the mutation reducer. +approval-gated fission, bounded region expansion, and in-place locality +elaboration use the mutation reducer. Initial compiler publication is classified as a one-time creation transaction, and named-person materialisation is classified as a resolution transaction. Aggregate-storage removal remains migration work. @@ -101,10 +102,13 @@ The migration is not complete while any of these can decide canonical state: - model output, browser payloads, story rendering, news generation, retrieval, or a derived simulation cell. -Bounded region expansion now lowers to the same batch primitive through typed -place and proposition admission plus exact topology changes. It may possess a -broader administrative authority envelope, but not another state-writing -mechanism. Approval-gated population fission likewise lowers to entity +Bounded region expansion and in-place locality elaboration lower to the same +batch primitive through typed place, proposition, population, and institution +admission plus exact topology and political-relation changes. Locality +elaboration owns only additions beneath one exact canonical place; it cannot +replace that place or bypass approval. Either path may possess a broader +administrative authority envelope, but not another state-writing mechanism. +Approval-gated population fission likewise lowers to entity admission, lineage, custody, and membership mutations; the fission projector owns only the derived resolution profiles and cover epoch. Initial compiler publication is not a transition over an existing world; its separate creation @@ -125,8 +129,8 @@ All of these lower to `WorldMutationBatch` before state changes: - population migration and approval-gated fission; - contract amendments that are permitted to change forward-looking world state; -- compiler-admitted entities added after publication and later bounded region - expansion. +- compiler-admitted entities added after publication, bounded region expansion, + and in-place locality elaboration. ### Cut line @@ -275,6 +279,7 @@ component family and names the invariants that family can enforce. There is no | `ChangePopulationLineage` | Records an admitted split, merge, or remainder relation. | Fission preview and approval exist; leaves remain non-overlapping and complete. | | `ChangeIdentity` | Adopts, discloses, restricts, or retires an exact identity handle. | Self-authority or explicit custody exists; disclosure is separate from renaming. | | `ChangeTopology` | Adds, alters, opens, closes, or retires a containment or route edge. | Evidence/branch admission, endpoint existence, reciprocal rules, and geometry invariants hold. | +| `CivicSystemSet` | Publishes the complete versioned civic apparatus for one jurisdiction. | The jurisdiction, institutions, resident populations, public civic propositions, political relations, version, and exact semantic-verifier receipt all exist in the accepted component overlay. | | `AdmitEntity` | Creates an explicitly permitted non-resource subject and initial components. | Admission class, evidence or branch-local authority, collision freedom, and required components hold. | | `RetireEntity` | Retires an exact subject without erasing history. | No dangling custody, occupancy, membership, topology, or active obligation remains. | | `AdvanceWorldTime` | Advances campaign time by an exact duration. | Monotonicity, governance, no-puppeting, tick budget, and scheduled obligations hold. | diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 07fd95e..63efa51 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -187,11 +187,17 @@ messages. Component-only mutation ingress rejects aggregate campaign rows. Initial publication is separately bounded to a fresh empty store plus atomic discoverability rename; it cannot mutate a published campaign. -- Region expansion admits typed place and proposition profiles, validates - evidence and containment, and requires an exact reciprocal route between the - stable origin and every newly compiled destination. Aggregate locations, - routes, and facts are rebuilt from accepted component state; the direct - insertion loops have been deleted. +- Destination compilation resolves identity before generation. A genuinely new + place uses bounded region expansion; an exact reachable canonical place uses + in-place locality elaboration and cannot be re-emitted, renamed, or replaced. + Both paths admit typed places, propositions, populations, institutions, + political relations, topology, and the civic manifest through the same + mutation reducer. Compiler-validated agency profiles remain a companion + projection outside that reducer and are a named component-migration frontier. + Inhabited proposals bind current authority, selection or succession, + public resources, and redress facts to every resident population through a + civic manifest, then pass an independent semantic civic verifier before + approval. Aggregate state is rebuilt from accepted components. - Named Gestalt members now change foreground resolution without gaining a second effect vocabulary. Promotion/folding advances world revision and `resolution_epoch`, clears the prior cover, preserves the exact individual @@ -427,7 +433,12 @@ The generic world-consumer boundary is implemented. Session Zero and external producers share one admitted `WorldSeed` transaction; externally authoritative institutions or Gestalts enter through revisioned WorldKernel snapshots; and strategic actions aimed at them persist typed proposals for consumer acknowledgement over -the existing loopback CultNet RUDP operation server. +the existing loopback CultNet RUDP operation server. Consumers can request an + authority-gated `ghostlight.world.newspaper.compose` projection. It renders + committed `NewsIssue` rows only when every cited committed `Event` exposes the + same public channel. Headline, channel, and reliability remain news-owned; + body, dateline, event IDs, and source revision remain event-grounded + provenance. The scale and emergence gate is implemented and locally proven. Delvehold is a consumer of Ghostlight's generic authored-world API, not a @@ -441,14 +452,29 @@ atomic commit authority. The active budget ceiling is 240, independent of the 32-call provider gate. A fixture proves 1,000 subjects across 200 cells and all 200 membrane pipelines under a seven-call gate. -1. Have the game-side adapter lower its authored hierarchy into the published +Sparse inhabited destinations now compile a versioned civic apparatus in place. +The first pass establishes institutions, resident populations, political edges, +and public authority, succession, resource, and redress facts. A later pass is +given that exact persisted apparatus and must deepen it without duplicating its +government or population. The independent civic verdict is rebound to the exact +candidate and checked again by `WorldKernel`; structurally plausible politics +without that receipt cannot mutate the world. A two-wave fixture proves an +action-bound named person can emerge publicly, retain identity, enter the next +resolution cover, and act from her own authority. The generated newspaper +contains her public appointment but does not expose her later private movement. + +1. Restore provider credit and rerun the provider-backed fantasy strategic + smoke. The 2026-08-26 run reached the first real cell pipeline and stopped at + DeepSeek with HTTP 402 before committing any event or newspaper; retain no + fabricated substitute for that missing live witness. +2. Have the game-side adapter lower its authored hierarchy into the published generic schemas; keep projection and economy translation consumer-owned. -2. Prove one consumer-owned effect crosses that public API, changes two foreign +3. Prove one consumer-owned effect crosses that public API, changes two foreign political layers, causes one durable named figure to emerge and later act, and returns attributed news or intent without mutating Delvehold-owned truth. -3. Leave the unpublished Mars seed and Kalsa refuge expansion unapproved unless +4. Leave the unpublished Mars seed and Kalsa refuge expansion unapproved unless the operator explicitly admits either; retain Kalsa as regression evidence. -4. Keep `gamecult-ops` synchronized with every executable deployment and model +5. Keep `gamecult-ops` synchronized with every executable deployment and model transport change. Use Idunn on Yggdrasil for all builds and deployments. Do not weaken actor custody, private projection, unanimous approval, diff --git a/notes/ghostlight-current-system-map.md b/notes/ghostlight-current-system-map.md index 1a5a5c1..888179e 100644 --- a/notes/ghostlight-current-system-map.md +++ b/notes/ghostlight-current-system-map.md @@ -900,15 +900,40 @@ provenance, retrieval, exact receipts, and player projection preserve those lanes without copying Kalsa into the read-only Aetheria recovery index or creating a Ghostlight-owned semantic index. -Bounded region expansion treats Vault evidence as canon constraints rather than -an exhaustive game map. The compiler must synthesize the smallest compatible -branch-local routes, geometry, people, supplies, procedures, capacity, -responsibility, and doctrine needed for play. Those choices remain visible as -`branch_assumptions`; they may vary between campaigns unless the Vault pins -them. A `gap` is reserved for contradictory canon baselines, an explicitly -requested exact canon baseline that cannot be anchored, or conflict with an -approved capability. Ordinary source silence is not a gap. Preview approval -remains the only path from this proposal into canonical world state. +Destination compilation treats Vault evidence as canon constraints rather than +an exhaustive game map. Identity resolution sends a genuinely new place to +bounded region expansion and an exact reachable canonical place to locality +elaboration. Locality elaboration preserves the existing place identity while +adding only contained places and locally scoped subjects, public facts, and +relations. A player's question can select the missing domain but cannot dictate +the office, procedure, or answer. Inhabited proposals must expose current +authority, selection or succession, public resources, and redress through a +typed civic manifest whose exact fact references are shared by each resident +population. A separate model stage verifies their semantic legibility; it may +reject but cannot rewrite or commit the proposal. The kernel rebinds that +verdict to the exact candidate before mutation admission. Accepted civic +systems persist as versioned component state, so a later pass receives the +current institutions, populations, facts, and relations and must extend that +apparatus instead of inventing a parallel government. + +Both destination paths synthesize the smallest compatible branch-local routes, +geometry, people, supplies, procedures, capacity, responsibility, and doctrine +needed for play. Those choices remain visible as `branch_assumptions`; they may +vary between campaigns unless the Vault pins them. A `gap` is reserved for +contradictory canon baselines, an explicitly requested exact canon baseline that +cannot be anchored, or conflict with an approved capability. Ordinary source +silence is not a gap. Preview approval remains the only path from this proposal +into canonical world state. + +Autonomous strategic waves run the same admitted agency state through parallel +cell membranes under a provider concurrency gate. Action-bound individuation +may create one consequential named person through the existing Gestalt member +commit primitive; that person enters later covers as the same canonical actor. +Public action channels produce committed `NewsIssue` records. The world- +consumer boundary can compose those records into a typed newspaper issue whose +articles retain exact event IDs, channels, reliability, and source revision. +Newspaper prose is derived from committed event summaries and cannot introduce +an event the kernel did not commit. Session Zero compilation, expansion, and fission follow the same projection rule. Review projections expose topology, pressures, source-use coverage, gaps, @@ -1120,15 +1145,27 @@ wrote campaign state has been removed. Its surviving projector updates only agency profiles, facets, cover invalidation, and `resolution_epoch` after the canonical mutation batch succeeds. -Bounded region expansion now composes typed place admission, typed proposition -admission, and exact topology changes against one authority snapshot. Every -new destination carries an explicit outbound route from the stable origin and -a reciprocal return route with the same positive travel time. Place profiles, -proposition content, evidence references, discovery locations, containment, -route identity, distance, and topology are validated on the component overlay; -the aggregate `Location`, `Route`, and `WorldFact` rows are reconstructed only -from accepted component state. The previous direct location/fact insertion -loops are gone. A route map key is local to its exact origin. The component +Region expansion and in-place locality elaboration compose typed place, +proposition, population, and institution admission plus exact topology and +political-relation changes against one authority snapshot. Locality elaboration +anchors every added place beneath one existing canonical jurisdiction and +forbids the compiler from duplicating that target. Civic manifests cross-bind +governing institutions, resident populations, public civic facts, and local +political relations before lowering. `CivicSystemSet` is the versioned component +owner; aggregate `Campaign.civic_systems` is reconstructed from its accepted +state. The mutation reducer owns those canonical component changes; the +compiler-validated agency-profile map is still a companion projection and must +not be described as component-owned until its migration is complete. Approval +commits the complete addition atomically or leaves the coarse place untouched. Repeated +Vault retrievals have distinct retrieval receipt identities, while an exact +immutable receipt replay is admitted idempotently under the same CultCache CAS. + +Every new destination carries an explicit outbound route from the stable origin +and a reciprocal return route with the same positive travel time. Place +profiles, proposition content, evidence references, discovery locations, +containment, route identity, distance, and topology are validated on the +component overlay; aggregate rows are reconstructed only from accepted +component state. A route map key is local to its exact origin. The component overlay derives its edge identity from `(origin_location_id, local_route_id)`; the player surface uses the route's exact destination field, and accepted region expansion restores the original local key. Reusing `road`, `harbor`, or diff --git a/notes/ghostlight-implementation-plan.md b/notes/ghostlight-implementation-plan.md index 84517ec..687c567 100644 --- a/notes/ghostlight-implementation-plan.md +++ b/notes/ghostlight-implementation-plan.md @@ -160,14 +160,25 @@ separate from this response-delivery boundary. World transition authority is now a closed semantic mutation algebra rather than four empirical effect universes. Foreground attempts, NPC initiative, reaction appraisal, strategic actor/institution/Gestalt outcomes, waits, -unanimous group travel, approval-gated population fission, and bounded region -expansion lower through one revision-bound batch reducer and persist its +unanimous group travel, approval-gated population fission, bounded region +expansion, and in-place locality elaboration lower through one revision-bound +batch reducer and persist its authority, batch, and receipt with the aggregate campaign projection. Fission inherits non-scarce population baseline through typed lineage while partitioning every exact resource and named member once; the resolution organ -only changes profiles and cover epoch. Region expansion admits exact place and -proposition profiles and a reciprocal origin/destination topology before -reconstructing compatibility rows. Initial compiler publication is now +only changes profiles and cover epoch. Destination identity resolution sends a +new place to region expansion and an exact reachable canonical place to +locality elaboration. Inhabited proposals admit populations, institutions, +political relations, and resident-shared civic facts for authority, selection +or succession, resources, and redress; deterministic cross-reference checks and +an independent semantic verifier run before approval and is rebound and checked +again at kernel admission. Accepted civic manifests are versioned component +state. Later destination passes receive that exact apparatus and may only retain +and deepen it; they cannot publish a duplicate resident body or government. +Public strategic events lower to `NewsIssue` records, and the generic CultNet +world-consumer boundary projects those committed records as an authority-gated +typed newspaper with exact event provenance. +Initial compiler publication is explicitly bounded as an empty-store creation transaction owned by the CampaignRegistry, not a runtime mutation. Named-person presence is a resolution transaction: it preserves the member delta, invalidates the prior cover and diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 9367e0b..08076bc 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -140,4 +140,8 @@ {"note": "The generic external authority/snapshot contract admits both institution and Gestalt subjects. This closes the Delvehold sovereign-gestalt requirement without adding a Delvehold-specific type: one tagged ExternalSubjectProjection carries either canonical shape, WorldKernel validates exact authority kind and subject ID, refreshes derived agency facets, and keeps the subject non-simulation-eligible while still targetable by foreign proposals.", "status": "ok", "ts": "2026-08-26T17:12:55+00:00", "type": "architecture"} {"note": "Strategic/offscreen named-person emergence now reuses WorldKernel apply_individuation: one selected Gestalt action may carry one action-bound model identity proposal, while the kernel revalidates revision, simulation authority, location, lineage, version, bounded payload, uniqueness, and atomically materializes the person with the strategic wave. This supersedes the earlier claim that all new-person individuation requires immediate player speech; that gate applies only to automatic foreground presence.", "status": "ok", "ts": "2026-08-26T17:53:55+00:00", "type": "implementation"} {"note": "Hundreds-class scale proof: the active cell ceiling is 240; a 1,000-subject fixture produced complete unique 200-cell coverage and dispatched all 200 three-stage membrane pipelines in one wave under a seven-call provider semaphore. Wave width remains independent of the provider parallelism ceiling of 32.", "status": "ok", "ts": "2026-08-26T17:53:55+00:00", "type": "verification"} -{"ts": "2026-08-26T18:08:11+00:00", "type": "verification", "status": "ok", "note": "Modeling audit closed four emergence authority holes before commit: the selector now rechecks the execution permit before and after inference; scheduler and kernel share one eligible-Gestalt candidate-digest function for mixed waves; the locally validated selector receipt is content-addressed again against the exact proposal digest; and the exact StrategicGestaltIndividuation row persists in the same CultCache strategic CAS. A substituted caller payload is rejected while campaign revision and member state remain unchanged. Duplicate public names, materialized actor-ID collisions, and relationships to unknown canonical subjects are rejected."} +{"note": "Modeling audit closed four emergence authority holes before commit: the selector now rechecks the execution permit before and after inference; scheduler and kernel share one eligible-Gestalt candidate-digest function for mixed waves; the locally validated selector receipt is content-addressed again against the exact proposal digest; and the exact StrategicGestaltIndividuation row persists in the same CultCache strategic CAS. A substituted caller payload is rejected while campaign revision and member state remain unchanged. Duplicate public names, materialized actor-ID collisions, and relationships to unknown canonical subjects are rejected.", "status": "ok", "ts": "2026-08-26T18:08:11+00:00", "type": "verification"} +{"note": "Destination identity resolution now routes a genuinely new place to RegionExpansion and an exact reachable canonical place to LocalityElaboration. Inhabited proposals bind institutions, resident populations, local political relations, and public authority, selection or succession, resource, and redress facts through a typed civic manifest; deterministic validation and an independent semantic verifier run before approval. WorldKernel lowers approved locality additions through the shared mutation reducer atomically, preserving the canonical place identity. Acceptance proves that a materialized Harrow resident inherits the exact public election fact while retaining a personal named vote memory; invalid civic admission leaves the coarse city untouched.", "status": "ok", "ts": "2026-08-26T19:31:56+00:00", "type": "implementation"} +{"branch": "codex/ghostlight-dungeon-mvp", "note": "Supersedes the final sentence of the 2026-08-26T19:31:56 implementation evidence: acceptance proves that the materialized Harrow resident inherited the exact public election fact. Her personal named vote memory was supplied by the fixture and does not prove automatic personal-memory generation.", "status": "ok", "ts": "2026-08-26T21:00:41+00:00", "type": "correction"} +{"branch": "codex/ghostlight-dungeon-mvp", "note": "Generic sparse-world acceptance passes locally. Iterative locality elaboration retains and versions one civic apparatus; WorldKernel requires the exact semantic civic receipt; civic public knowledge is a continuing component invariant; external subject snapshots cannot introduce an unknown home; a consumer-authorized nonempty newspaper cites the exact committed strategic event; and Veska Rill emerges publicly, persists into a later resolution cover, and acts from her own authority without leaking her private movement into news. cargo test -p ghostlight-dungeon --all-targets passed 376 library, 43 main-binary, 4 agency-corpus, and 1 scale-smoke tests; the scale fixture covers 1,000 subjects in 200 concurrently dispatched cells.", "status": "ok", "ts": "2026-08-26T21:00:53+00:00", "type": "verification"} +{"ts": "2026-08-26T21:01:00+00:00", "type": "verification", "status": "blocked", "note": "The provider-backed Rainless Marches fantasy-world smoke at F:\\GameCult\\GhostlightDungeon\\acceptance\\delvehold-world-newspaper-20260826-223723 reached the first real cell projector after a successful build, then DeepSeek returned HTTP 402 Payment Required on both same-snapshot attempts. No result.json or newspaper.md was produced, and no substitute should be treated as a live autonomous-world witness.", "branch": "codex/ghostlight-dungeon-mvp"} diff --git a/state/ghostlight-state.cultcache.jsonl b/state/ghostlight-state.cultcache.jsonl index c66eabf..bd0541b 100644 --- a/state/ghostlight-state.cultcache.jsonl +++ b/state/ghostlight-state.cultcache.jsonl @@ -142,3 +142,7 @@ {"key": "2026-08-26T175355Z0000-0140-9d8d9efc8fb7", "payload": "eyJub3RlIjogIlN0cmF0ZWdpYy9vZmZzY3JlZW4gbmFtZWQtcGVyc29uIGVtZXJnZW5jZSBub3cgcmV1c2VzIFdvcmxkS2VybmVsIGFwcGx5X2luZGl2aWR1YXRpb246IG9uZSBzZWxlY3RlZCBHZXN0YWx0IGFjdGlvbiBtYXkgY2Fycnkgb25lIGFjdGlvbi1ib3VuZCBtb2RlbCBpZGVudGl0eSBwcm9wb3NhbCwgd2hpbGUgdGhlIGtlcm5lbCByZXZhbGlkYXRlcyByZXZpc2lvbiwgc2ltdWxhdGlvbiBhdXRob3JpdHksIGxvY2F0aW9uLCBsaW5lYWdlLCB2ZXJzaW9uLCBib3VuZGVkIHBheWxvYWQsIHVuaXF1ZW5lc3MsIGFuZCBhdG9taWNhbGx5IG1hdGVyaWFsaXplcyB0aGUgcGVyc29uIHdpdGggdGhlIHN0cmF0ZWdpYyB3YXZlLiBUaGlzIHN1cGVyc2VkZXMgdGhlIGVhcmxpZXIgY2xhaW0gdGhhdCBhbGwgbmV3LXBlcnNvbiBpbmRpdmlkdWF0aW9uIHJlcXVpcmVzIGltbWVkaWF0ZSBwbGF5ZXIgc3BlZWNoOyB0aGF0IGdhdGUgYXBwbGllcyBvbmx5IHRvIGF1dG9tYXRpYyBmb3JlZ3JvdW5kIHByZXNlbmNlLiIsICJzdGF0dXMiOiAib2siLCAidHMiOiAiMjAyNi0wOC0yNlQxNzo1Mzo1NSswMDowMCIsICJ0eXBlIjogImltcGxlbWVudGF0aW9uIn0=", "stored_at": "2026-08-26T17:53:55.470514+00:00", "type": "ghostlight.evidence_record.v0"} {"key": "2026-08-26T175355Z0000-0141-5d422df0eb1c", "payload": "eyJub3RlIjogIkh1bmRyZWRzLWNsYXNzIHNjYWxlIHByb29mOiB0aGUgYWN0aXZlIGNlbGwgY2VpbGluZyBpcyAyNDA7IGEgMSwwMDAtc3ViamVjdCBmaXh0dXJlIHByb2R1Y2VkIGNvbXBsZXRlIHVuaXF1ZSAyMDAtY2VsbCBjb3ZlcmFnZSBhbmQgZGlzcGF0Y2hlZCBhbGwgMjAwIHRocmVlLXN0YWdlIG1lbWJyYW5lIHBpcGVsaW5lcyBpbiBvbmUgd2F2ZSB1bmRlciBhIHNldmVuLWNhbGwgcHJvdmlkZXIgc2VtYXBob3JlLiBXYXZlIHdpZHRoIHJlbWFpbnMgaW5kZXBlbmRlbnQgb2YgdGhlIHByb3ZpZGVyIHBhcmFsbGVsaXNtIGNlaWxpbmcgb2YgMzIuIiwgInN0YXR1cyI6ICJvayIsICJ0cyI6ICIyMDI2LTA4LTI2VDE3OjUzOjU1KzAwOjAwIiwgInR5cGUiOiAidmVyaWZpY2F0aW9uIn0=", "stored_at": "2026-08-26T17:53:55.641566+00:00", "type": "ghostlight.evidence_record.v0"} {"key": "2026-08-26T180811Z0000-0142-4552563edb4f", "payload": "eyJub3RlIjogIk1vZGVsaW5nIGF1ZGl0IGNsb3NlZCBmb3VyIGVtZXJnZW5jZSBhdXRob3JpdHkgaG9sZXMgYmVmb3JlIGNvbW1pdDogdGhlIHNlbGVjdG9yIG5vdyByZWNoZWNrcyB0aGUgZXhlY3V0aW9uIHBlcm1pdCBiZWZvcmUgYW5kIGFmdGVyIGluZmVyZW5jZTsgc2NoZWR1bGVyIGFuZCBrZXJuZWwgc2hhcmUgb25lIGVsaWdpYmxlLUdlc3RhbHQgY2FuZGlkYXRlLWRpZ2VzdCBmdW5jdGlvbiBmb3IgbWl4ZWQgd2F2ZXM7IHRoZSBsb2NhbGx5IHZhbGlkYXRlZCBzZWxlY3RvciByZWNlaXB0IGlzIGNvbnRlbnQtYWRkcmVzc2VkIGFnYWluIGFnYWluc3QgdGhlIGV4YWN0IHByb3Bvc2FsIGRpZ2VzdDsgYW5kIHRoZSBleGFjdCBTdHJhdGVnaWNHZXN0YWx0SW5kaXZpZHVhdGlvbiByb3cgcGVyc2lzdHMgaW4gdGhlIHNhbWUgQ3VsdENhY2hlIHN0cmF0ZWdpYyBDQVMuIEEgc3Vic3RpdHV0ZWQgY2FsbGVyIHBheWxvYWQgaXMgcmVqZWN0ZWQgd2hpbGUgY2FtcGFpZ24gcmV2aXNpb24gYW5kIG1lbWJlciBzdGF0ZSByZW1haW4gdW5jaGFuZ2VkLiBEdXBsaWNhdGUgcHVibGljIG5hbWVzLCBtYXRlcmlhbGl6ZWQgYWN0b3ItSUQgY29sbGlzaW9ucywgYW5kIHJlbGF0aW9uc2hpcHMgdG8gdW5rbm93biBjYW5vbmljYWwgc3ViamVjdHMgYXJlIHJlamVjdGVkLiIsICJzdGF0dXMiOiAib2siLCAidHMiOiAiMjAyNi0wOC0yNlQxODowODoxMSswMDowMCIsICJ0eXBlIjogInZlcmlmaWNhdGlvbiJ9", "stored_at": "2026-08-26T18:08:11.091051+00:00", "type": "ghostlight.evidence_record.v0"} +{"key": "2026-08-26T193156Z0000-0143-238f7895b452", "payload": "eyJub3RlIjogIkRlc3RpbmF0aW9uIGlkZW50aXR5IHJlc29sdXRpb24gbm93IHJvdXRlcyBhIGdlbnVpbmVseSBuZXcgcGxhY2UgdG8gUmVnaW9uRXhwYW5zaW9uIGFuZCBhbiBleGFjdCByZWFjaGFibGUgY2Fub25pY2FsIHBsYWNlIHRvIExvY2FsaXR5RWxhYm9yYXRpb24uIEluaGFiaXRlZCBwcm9wb3NhbHMgYmluZCBpbnN0aXR1dGlvbnMsIHJlc2lkZW50IHBvcHVsYXRpb25zLCBsb2NhbCBwb2xpdGljYWwgcmVsYXRpb25zLCBhbmQgcHVibGljIGF1dGhvcml0eSwgc2VsZWN0aW9uIG9yIHN1Y2Nlc3Npb24sIHJlc291cmNlLCBhbmQgcmVkcmVzcyBmYWN0cyB0aHJvdWdoIGEgdHlwZWQgY2l2aWMgbWFuaWZlc3Q7IGRldGVybWluaXN0aWMgdmFsaWRhdGlvbiBhbmQgYW4gaW5kZXBlbmRlbnQgc2VtYW50aWMgdmVyaWZpZXIgcnVuIGJlZm9yZSBhcHByb3ZhbC4gV29ybGRLZXJuZWwgbG93ZXJzIGFwcHJvdmVkIGxvY2FsaXR5IGFkZGl0aW9ucyB0aHJvdWdoIHRoZSBzaGFyZWQgbXV0YXRpb24gcmVkdWNlciBhdG9taWNhbGx5LCBwcmVzZXJ2aW5nIHRoZSBjYW5vbmljYWwgcGxhY2UgaWRlbnRpdHkuIEFjY2VwdGFuY2UgcHJvdmVzIHRoYXQgYSBtYXRlcmlhbGl6ZWQgSGFycm93IHJlc2lkZW50IGluaGVyaXRzIHRoZSBleGFjdCBwdWJsaWMgZWxlY3Rpb24gZmFjdCB3aGlsZSByZXRhaW5pbmcgYSBwZXJzb25hbCBuYW1lZCB2b3RlIG1lbW9yeTsgaW52YWxpZCBjaXZpYyBhZG1pc3Npb24gbGVhdmVzIHRoZSBjb2Fyc2UgY2l0eSB1bnRvdWNoZWQuIiwgInN0YXR1cyI6ICJvayIsICJ0cyI6ICIyMDI2LTA4LTI2VDE5OjMxOjU2KzAwOjAwIiwgInR5cGUiOiAiaW1wbGVtZW50YXRpb24ifQ==", "stored_at": "2026-08-26T19:31:56.391626+00:00", "type": "ghostlight.evidence_record.v0"} +{"key": "2026-08-26T210041Z0000-0144-fd3f3362b0d8", "payload": "eyJicmFuY2giOiAiY29kZXgvZ2hvc3RsaWdodC1kdW5nZW9uLW12cCIsICJub3RlIjogIlN1cGVyc2VkZXMgdGhlIGZpbmFsIHNlbnRlbmNlIG9mIHRoZSAyMDI2LTA4LTI2VDE5OjMxOjU2IGltcGxlbWVudGF0aW9uIGV2aWRlbmNlOiBhY2NlcHRhbmNlIHByb3ZlcyB0aGF0IHRoZSBtYXRlcmlhbGl6ZWQgSGFycm93IHJlc2lkZW50IGluaGVyaXRlZCB0aGUgZXhhY3QgcHVibGljIGVsZWN0aW9uIGZhY3QuIEhlciBwZXJzb25hbCBuYW1lZCB2b3RlIG1lbW9yeSB3YXMgc3VwcGxpZWQgYnkgdGhlIGZpeHR1cmUgYW5kIGRvZXMgbm90IHByb3ZlIGF1dG9tYXRpYyBwZXJzb25hbC1tZW1vcnkgZ2VuZXJhdGlvbi4iLCAic3RhdHVzIjogIm9rIiwgInRzIjogIjIwMjYtMDgtMjZUMjE6MDA6NDErMDA6MDAiLCAidHlwZSI6ICJjb3JyZWN0aW9uIn0=", "stored_at": "2026-08-26T21:00:41.591938+00:00", "type": "ghostlight.evidence_record.v0"} +{"key": "2026-08-26T210053Z0000-0145-c3f040a14674", "payload": "eyJicmFuY2giOiAiY29kZXgvZ2hvc3RsaWdodC1kdW5nZW9uLW12cCIsICJub3RlIjogIkdlbmVyaWMgc3BhcnNlLXdvcmxkIGFjY2VwdGFuY2UgcGFzc2VzIGxvY2FsbHkuIEl0ZXJhdGl2ZSBsb2NhbGl0eSBlbGFib3JhdGlvbiByZXRhaW5zIGFuZCB2ZXJzaW9ucyBvbmUgY2l2aWMgYXBwYXJhdHVzOyBXb3JsZEtlcm5lbCByZXF1aXJlcyB0aGUgZXhhY3Qgc2VtYW50aWMgY2l2aWMgcmVjZWlwdDsgY2l2aWMgcHVibGljIGtub3dsZWRnZSBpcyBhIGNvbnRpbnVpbmcgY29tcG9uZW50IGludmFyaWFudDsgZXh0ZXJuYWwgc3ViamVjdCBzbmFwc2hvdHMgY2Fubm90IGludHJvZHVjZSBhbiB1bmtub3duIGhvbWU7IGEgY29uc3VtZXItYXV0aG9yaXplZCBub25lbXB0eSBuZXdzcGFwZXIgY2l0ZXMgdGhlIGV4YWN0IGNvbW1pdHRlZCBzdHJhdGVnaWMgZXZlbnQ7IGFuZCBWZXNrYSBSaWxsIGVtZXJnZXMgcHVibGljbHksIHBlcnNpc3RzIGludG8gYSBsYXRlciByZXNvbHV0aW9uIGNvdmVyLCBhbmQgYWN0cyBmcm9tIGhlciBvd24gYXV0aG9yaXR5IHdpdGhvdXQgbGVha2luZyBoZXIgcHJpdmF0ZSBtb3ZlbWVudCBpbnRvIG5ld3MuIGNhcmdvIHRlc3QgLXAgZ2hvc3RsaWdodC1kdW5nZW9uIC0tYWxsLXRhcmdldHMgcGFzc2VkIDM3NiBsaWJyYXJ5LCA0MyBtYWluLWJpbmFyeSwgNCBhZ2VuY3ktY29ycHVzLCBhbmQgMSBzY2FsZS1zbW9rZSB0ZXN0czsgdGhlIHNjYWxlIGZpeHR1cmUgY292ZXJzIDEsMDAwIHN1YmplY3RzIGluIDIwMCBjb25jdXJyZW50bHkgZGlzcGF0Y2hlZCBjZWxscy4iLCAic3RhdHVzIjogIm9rIiwgInRzIjogIjIwMjYtMDgtMjZUMjE6MDA6NTMrMDA6MDAiLCAidHlwZSI6ICJ2ZXJpZmljYXRpb24ifQ==", "stored_at": "2026-08-26T21:00:53.693935+00:00", "type": "ghostlight.evidence_record.v0"} +{"key": "2026-08-26T210100Z0000-0146-4104b475cc53", "payload": "eyJicmFuY2giOiAiY29kZXgvZ2hvc3RsaWdodC1kdW5nZW9uLW12cCIsICJub3RlIjogIlRoZSBwcm92aWRlci1iYWNrZWQgUmFpbmxlc3MgTWFyY2hlcyBmYW50YXN5LXdvcmxkIHNtb2tlIGF0IEY6XFxHYW1lQ3VsdFxcR2hvc3RsaWdodER1bmdlb25cXGFjY2VwdGFuY2VcXGRlbHZlaG9sZC13b3JsZC1uZXdzcGFwZXItMjAyNjA4MjYtMjIzNzIzIHJlYWNoZWQgdGhlIGZpcnN0IHJlYWwgY2VsbCBwcm9qZWN0b3IgYWZ0ZXIgYSBzdWNjZXNzZnVsIGJ1aWxkLCB0aGVuIERlZXBTZWVrIHJldHVybmVkIEhUVFAgNDAyIFBheW1lbnQgUmVxdWlyZWQgb24gYm90aCBzYW1lLXNuYXBzaG90IGF0dGVtcHRzLiBObyByZXN1bHQuanNvbiBvciBuZXdzcGFwZXIubWQgd2FzIHByb2R1Y2VkLCBhbmQgbm8gc3Vic3RpdHV0ZSBzaG91bGQgYmUgdHJlYXRlZCBhcyBhIGxpdmUgYXV0b25vbW91cy13b3JsZCB3aXRuZXNzLiIsICJzdGF0dXMiOiAiYmxvY2tlZCIsICJ0cyI6ICIyMDI2LTA4LTI2VDIxOjAxOjAwKzAwOjAwIiwgInR5cGUiOiAidmVyaWZpY2F0aW9uIn0=", "stored_at": "2026-08-26T21:01:00.680991+00:00", "type": "ghostlight.evidence_record.v0"} diff --git a/state/map.yaml b/state/map.yaml index e8af503..338022a 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -81,7 +81,7 @@ live_architecture: - Every player, NPC, institution, scheduler, import, and reload transition uses the same typed WorldCommand validation and atomic CultCache commit path. - Foreground attempts, NPC reactions, strategic cell outcomes, waits, travel, and approval-gated population fission lower into one closed semantic WorldMutationBatch vocabulary. Means and intended effects remain proposals; only the WorldKernel reducer can change canonical components. - The mutation reducer validates a complete batch against an exact authority envelope on an isolated component overlay, advances each touched subject version once, and persists component state, authority, batch, mutation receipt, causal receipt, events, and aggregate compatibility projection atomically. Aggregate campaign rows are rejected by component-only mutation ingress. - - WorldEffectDelta, ActorStateDelta, and StrategicOutcomeEffect are model-boundary migration inputs, not independent writers. Bounded region expansion lowers through typed place/proposition admission and topology mutations. Initial publication is a fresh-store creation transaction; named-person materialisation/folding is a resolution transaction that advances revision and resolution epoch, clears the cover, preserves the individual delta, and cannot rewrite Gestalt-wide knowledge, custody, pressure, or fictional time. + - WorldEffectDelta, ActorStateDelta, and StrategicOutcomeEffect are model-boundary migration inputs, not independent writers. Destination identity resolution routes a genuinely new place to bounded region expansion and an exact reachable canonical place to in-place locality elaboration. Both lower places, propositions, populations, institutions, political relations, topology, and the civic manifest through the same typed mutation reducer. Compiler-validated agency profiles remain a companion projection outside the reducer and are an explicit component-migration frontier. Inhabited destination proposals require a civic manifest whose public authority, selection or succession, resources, and redress facts are structurally cross-bound and independently checked for semantic legibility before approval. Initial publication is a fresh-store creation transaction; named-person materialisation/folding is a resolution transaction that advances revision and resolution epoch, clears the cover, preserves the individual delta, and cannot rewrite Gestalt-wide knowledge, custody, pressure, or fictional time. - Ghostlight owns generalized Projector to Persona to Interpreter machinery; consuming Personas retain their own canonical minds and commit authority. - Player speech address is a bounded proposal over exact co-present simulation-eligible actor IDs. WorldKernel commits the selected Persona response set with the speech turn; every present actor still appraises, while direct addressees receive explicit response duty and observers retain optional agency. A direct addressee must speak or select typed deliberate silence, which lowers deterministically rather than opening a free-text reaction-effect lane. - Foreground action assessment derives a closed structural schema from exact current authority. A compact private scope projection receives only the exact attempt and the structurally available lane names; local validation permits it only to subtract. Causally unselected lanes disappear from the assessor schema and information facts stay out of the prompt when knowledge mutation is unselected. Canonical dynamic effect maps cross the strict model boundary as bounded authority-enumerated entry arrays and lower once into WorldEffectDelta after validation. The admission-bound schema gives required strong/ordinary-success lanes minItems 1 only on the admissible branch and forces every inadmissible effect array empty; local validation repeats both rules after lowering. A separate compact semantic verifier then compares the complete four-band effect bundle with the player's exact means and intended effect. Neither stage can reassess difficulty, choose committed effects, expand authority, or commit. One mismatch produces a private semantic-invalid receipt and bounded same-snapshot assessor correction; a second mismatch aborts. Only structurally and semantically verified proposals enter the cache. @@ -193,14 +193,14 @@ live_architecture: - Institution, faction, and consumer decision models active_subgoals: - - Prove the admitted generic world-consumer contract with a game-side fixture: shared compiler/consumer WorldSeed admission, externally authoritative institution-or-Gestalt snapshots, and attributed proposal acknowledgement over typed CultNet, without consumer-specific IDs or schemas in Ghostlight. - - Exercise strategic/offscreen named-person individuation across sustained political waves so emerged people plot, acquire relationships, fold, and return without granting a cell, arena, or model commit authority. + - Connect a Delvehold-owned adapter to the admitted generic consumer contract: shared compiler/consumer WorldSeed admission, externally authoritative institution-or-Gestalt snapshots, attributed proposal acknowledgement, and committed-event newspaper composition over typed CultNet, without consumer-specific IDs or schemas in Ghostlight. + - Extend strategic/offscreen named-person individuation beyond the proven emerge-then-act path so people plot across sustained political waves, acquire relationships, fold, and return without granting a cell, arena, or model commit authority. - Pressure the proven 200-cell dispatcher with authored consumer hierarchies and measure provider cost; the active budget ceiling is 240 while provider concurrency remains separately capped at 32. - Finish the semantic mutation migration: delete or demote remaining legacy model effect schemas and move aggregate campaign fields toward projection-only state. Seed publication and named-person presence now have explicit non-effect authority classifications. - Keep the selectable Kalsa Vault's Public player-safe and Spoilers GM-only evidence lanes intact through Git/Obsidian sync, retrieval, exact receipts, and player projection. Do not import it into the read-only Aetheria recovery index or create a rival Ghostlight semantic index. - Grow the 36-case candidate agency corpus toward 300 reviewed, behaviorally distinct attempts that either compose from existing primitives, produce an explicit bargain, or falsify the algebra. - Pressure live campaign compilation and play from exact Vault evidence; reject honest gaps instead of borrowing a nearby fixture, cast, or geography. - - Make large consumer-authored political hierarchies produce meaningful attributed activity while rivals retain separate knowledge, speech, resources, and authority and named people retain continuity through materialization, folding, migration, and return. Delvehold is the first proving fixture, not a special execution path. + - Run the provider-backed sparse-world acceptance through iterative civic elaboration and sustained strategic waves. Retain a typed newspaper witness whose committed NewsIssue rows cite exact committed public Events on the same public channel. Delvehold is the first proving fixture, not a special execution path. - Optimize stable-prefix cache reuse and work per token without removing context needed for goals, promises, relationships, knowledge, or exact permissions. - Keep every model stage proposal-only; malformed, stale, cross-slice, or semantically invalid waves must leave campaign state and fictional time unchanged. - Complete separate-account co-op privacy, actor-binding, unanimity, and restart proof when suitable testers or controlled account fixtures are available. @@ -323,6 +323,6 @@ data_flow: - If state grows faster than understanding, cut it back. current_status: - summary: Yggdrasil serves immutable Ghostlight release fdb6352e0dfdd0eeb129020ea9dea0b6225eccf9 with Eve 672c0c1e9fc828b63752345385727b06c50491d0, daemon SHA-256 d4c57cc6df0e2743f2f444bbdf4c2c90961a41b74e2c92cf45fa52b4e63f5714, native-client SHA-256 0d54f75ce7fe66b876ae720cdf9d6314778972f2193410fe2979ec51b8d25aba, artifact sha256-feadb845bf999afb09e781f3e81a36fe5bc5b2d1d9eec06c028bbd81680a548a, and independent CodexConnector release 2f29b90eebd8fc1bbdc07cdd22ac4883f16849a5 using gpt-5.6-luna. Idunn passed 347 tests and left both services healthy with zero restarts. Kalsa campaign e99e8794-281f-4a82-8b2c-5e6954bd6b16 is at world revision 21, resolution epoch 3, and configured budget 1. Startup migration repaired Cal Rusk to exact canonical member:cal_rusk without advancing fiction; his learned knowledge and personal delta survived folding, travel, and rematerialisation. A budget-1 strategic wave advanced remote actors without puppeting Asha. Destination preview 9fa863a0-e1fc-4115-bb18-74d523a3c6de synthesized eight source-compatible branch assumptions and returned zero material gaps; it remains unapproved and the world is unchanged. The unpublished Mars preview also remains unapproved. Existing mutation, Gestalt, topology, knowledge, privacy, approval, no-puppeting, and atomicity invariants remain authoritative. Starfire remains retired as a writer and build host. - next_action: Keep Dungeon adversarial single-player play as regression pressure while the game-side adapter prepares its first generic WorldSeed. Run one consumer fixture through seed admission, authoritative institution snapshot, two simulated political layers, strategic action-bound named-person emergence, a later action by that durable person, and attributed proposal acknowledgement without mutating consumer-owned truth. + summary: Ghostlight's generic consumer boundary admits sparse WorldSeeds without forged civic runtime state, validates externally owned subject snapshots against the resulting world, runs the same hundreds-class parallel cell machinery used by Dungeon, and exposes an authority-gated newspaper projection over committed NewsIssue rows whose exact cited Events expose the same public channel. Headlines, channel, and reliability come from committed news state; article bodies, datelines, and event provenance come from the cited committed events. Sparse inhabited places compile a versioned civic apparatus and later passes deepen that exact apparatus. Local acceptance proves 1,000 subjects across 200 concurrently dispatched cells, two-wave durable named-person emergence and action, nonempty consumer newspaper provenance, semantic civic receipt binding, and continuing public civic knowledge. The provider-backed Rainless Marches run reached the live cell pipeline on 2026-08-26 but DeepSeek returned HTTP 402 before any event or newspaper committed. Yggdrasil still serves immutable Ghostlight release fdb6352e0dfdd0eeb129020ea9dea0b6225eccf9; Dungeon play remains regression pressure, and unpublished Mars and Kalsa destination previews remain unapproved. + next_action: Restore provider credit and rerun the sparse fantasy-world smoke to obtain a real sustained newspaper witness, then let the Delvehold-owned adapter lower its authored hierarchy and Greathold boundary through the published generic schemas. Continue adversarial single-player Dungeon play as regression pressure; do not invent a local newspaper in place of the failed provider run. gestalt_population: Gestalt Personas own shared population baselines; persistent member deltas own named individuality; WorldKernel materialization and approval-gated fission preserve lineage and identity. Materialisation/folding changes only representation and the exact member delta, advances resolution epoch, and retires the old cover; it has no Gestalt-wide effect authority. Selected actionable member exceptions are mandatory Projector perspective owners, so aggregation cannot silently erase their decision. Presence projection is limited to nearby active leaves and exact-location dormant members, includes reciprocal player relationship evidence, and may propose an earned cast without committing it. Simulation cells are derived covers only.