diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-action-smoke.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-action-smoke.rs index cfc8222..50fa69e 100644 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-action-smoke.rs +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-action-smoke.rs @@ -33,7 +33,7 @@ async fn main() -> anyhow::Result<()> { std::fs::create_dir_all(&root)?; let campaign = action_campaign(); let store = CampaignStore::open(root.join("campaign.cc"))?; - store.create_campaign(&campaign, &[], &[])?; + store.create_unadmitted_fixture_campaign(&campaign, &[], &[])?; let model: Arc = Arc::new(DeepSeekPort::from_runtime_secret(secret)?); let assessor = ActionAssessor::new(model.clone(), "deepseek-v4-pro"); let kernel = WorldKernel::start(store.clone()); 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 79868c1..8e2d9d0 100644 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-dynamics-smoke.rs +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-dynamics-smoke.rs @@ -200,7 +200,7 @@ async fn main() -> anyhow::Result<()> { (base_campaign, None) }; let store = CampaignStore::open(root.join("campaign.cc"))?; - store.create_campaign(&campaign, &[], &[])?; + store.create_unadmitted_fixture_campaign(&campaign, &[], &[])?; let kernel = WorldKernel::start(store.clone()); let model_calls = Arc::new(std::sync::Mutex::new(Vec::new())); let model: Arc = Arc::new(LiveFireModelRecorder { 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 148cb9f..e2c12ae 100644 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-scale-smoke.rs +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-gestalt-scale-smoke.rs @@ -51,7 +51,7 @@ async fn main() -> anyhow::Result<()> { .location_id .clone(); let store = CampaignStore::open(root.join("campaign.cc"))?; - store.create_campaign(&campaign, &[], &[])?; + store.create_unadmitted_fixture_campaign(&campaign, &[], &[])?; let model: Arc = Arc::new(DeepSeekPort::from_runtime_secret(secret)?); let started = Instant::now(); let output = propose_resolution_wave( 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 b501e52..00916dc 100644 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-live-turn-smoke.rs +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-live-turn-smoke.rs @@ -44,7 +44,7 @@ async fn main() -> anyhow::Result<()> { persona_response_actor_ids: Default::default(), }); let store = CampaignStore::open(root.join("campaign.cc"))?; - store.create_campaign(&campaign, &[], &[])?; + store.create_unadmitted_fixture_campaign(&campaign, &[], &[])?; let model: Arc = Arc::new(DeepSeekPort::from_runtime_secret(secret)?); let engine = PersonaProjectionEngine { model, diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs index a35eb0c..5fb118d 100644 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs @@ -51,7 +51,7 @@ async fn main() -> anyhow::Result<()> { .location_id .clone(); let store = CampaignStore::open(root.join("campaign.cc"))?; - store.create_campaign(&campaign, &[], &[])?; + store.create_unadmitted_fixture_campaign(&campaign, &[], &[])?; let model: Arc = Arc::new(DeepSeekPort::from_runtime_secret(secret)?); let started = Instant::now(); let output = propose_resolution_wave( diff --git a/crates/ghostlight-dungeon/src/compiler.rs b/crates/ghostlight-dungeon/src/compiler.rs index e09c9aa..c8a6105 100644 --- a/crates/ghostlight-dungeon/src/compiler.rs +++ b/crates/ghostlight-dungeon/src/compiler.rs @@ -4527,8 +4527,11 @@ pub fn validate_campaign_seed(c: &Campaign) -> Result<()> { if c.tick_hours == 0 { return Err(anyhow!("strategic tick duration must be positive")); } - if !c.actors.contains_key(&c.player_actor_id) { - return Err(anyhow!("player actor is missing")); + if !c.actors.contains_key(&c.player_actor_id) + && !c.institutions.contains_key(&c.player_actor_id) + && !c.gestalts.contains_key(&c.player_actor_id) + { + return Err(anyhow!("primary controlled subject is missing")); } crate::resolution::validate_policy(&c.resolution_policy)?; crate::resolution::validate_pins(c, &c.resolution_pins)?; diff --git a/crates/ghostlight-dungeon/src/consumer.rs b/crates/ghostlight-dungeon/src/consumer.rs new file mode 100644 index 0000000..6a78ce1 --- /dev/null +++ b/crates/ghostlight-dungeon/src/consumer.rs @@ -0,0 +1,398 @@ +use crate::domain::{ + ActorState, AgencyProfile, AgencyRelation, AgencySubjectKind, BranchOrigin, Campaign, + CanonCandidate, CellActionProposal, GestaltLineage, GestaltMemberDelta, GestaltPersonaState, + InstitutionState, Location, ResolutionPolicy, StrategicCellEffect, WorldClock, WorldFact, +}; +use anyhow::{Result, anyhow}; +use chrono::{DateTime, Utc}; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use uuid::Uuid; + +pub const WORLD_CONSUMER_SERVICE_ID: &str = "ghostlight.world.consumer"; +pub const ADMIT_WORLD_OPERATION: &str = "ghostlight.world.seed.admit"; +pub const APPLY_EXTERNAL_SNAPSHOT_OPERATION: &str = "ghostlight.world.external.snapshot.apply"; +pub const LIST_EXTERNAL_PROPOSALS_OPERATION: &str = "ghostlight.world.external.proposals.list"; +pub const ACKNOWLEDGE_EXTERNAL_PROPOSAL_OPERATION: &str = + "ghostlight.world.external.proposal.acknowledge"; + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum WorldSeedProducerKind { + Compiler, + Consumer, +} + +/// Initial canonical world state before runtime-only revision, transcript, +/// scheduling, and cover state exist. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct WorldSeed { + pub schema: String, + pub id: Uuid, + pub name: String, + pub branch_origin: BranchOrigin, + pub world_time: DateTime, + pub tick_hours: u32, + /// One subject protected from Ghostlight agency. Dungeon supplies its host + /// actor. A world consumer may supply an externally owned institution. + pub primary_controlled_subject_id: String, + pub locations: BTreeMap, + pub actors: BTreeMap, + pub institutions: BTreeMap, + pub clocks: BTreeMap, + pub facts: BTreeMap, + #[serde(default)] + pub canon_candidates: BTreeMap, + #[serde(default)] + pub gestalts: BTreeMap, + #[serde(default)] + pub gestalt_members: BTreeMap, + #[serde(default)] + pub agency_profiles: BTreeMap, + #[serde(default)] + pub agency_relations: BTreeMap, + #[serde(default)] + pub gestalt_lineages: BTreeMap, + #[serde(default)] + pub resolution_policy: ResolutionPolicy, +} + +impl WorldSeed { + pub fn from_campaign(campaign: &Campaign) -> Result { + if campaign.revision != 0 + || !campaign.transcript.is_empty() + || !campaign.events.is_empty() + || !campaign.news.is_empty() + || !campaign.pending_world_proposals.is_empty() + || campaign.pending_ticks != 0 + || campaign.away_ticks_processed != 0 + || !campaign.resolution_pins.is_empty() + || campaign.resolution_cover.is_some() + || campaign.strategic_tick_count != 0 + { + return Err(anyhow!( + "world seed cannot contain already-authoritative runtime state" + )); + } + Ok(Self { + schema: "ghostlight.world_seed.v1".into(), + id: campaign.id, + name: campaign.name.clone(), + branch_origin: campaign.branch_origin.clone(), + world_time: campaign.world_time, + tick_hours: campaign.tick_hours, + primary_controlled_subject_id: campaign.player_actor_id.clone(), + locations: campaign.locations.clone(), + actors: campaign.actors.clone(), + institutions: campaign.institutions.clone(), + clocks: campaign.clocks.clone(), + facts: campaign.facts.clone(), + canon_candidates: campaign.canon_candidates.clone(), + gestalts: campaign.gestalts.clone(), + gestalt_members: campaign.gestalt_members.clone(), + agency_profiles: campaign.agency_profiles.clone(), + agency_relations: campaign.agency_relations.clone(), + gestalt_lineages: campaign.gestalt_lineages.clone(), + resolution_policy: campaign.resolution_policy.clone(), + }) + } + + pub fn into_campaign(self) -> Campaign { + Campaign { + schema: "ghostlight.campaign.v1".into(), + id: self.id, + name: self.name, + revision: 0, + branch_origin: self.branch_origin, + world_time: self.world_time, + tick_hours: self.tick_hours, + player_actor_id: self.primary_controlled_subject_id, + locations: self.locations, + actors: self.actors, + institutions: self.institutions, + clocks: self.clocks, + facts: self.facts, + transcript: Vec::new(), + last_player_activity: self.world_time, + pending_ticks: 0, + away_ticks_processed: 0, + events: Vec::new(), + news: Vec::new(), + canon_candidates: self.canon_candidates, + gestalts: self.gestalts, + gestalt_members: self.gestalt_members, + pending_world_proposals: Vec::new(), + agency_profiles: self.agency_profiles, + agency_relations: self.agency_relations, + gestalt_lineages: self.gestalt_lineages, + resolution_policy: self.resolution_policy, + resolution_pins: BTreeMap::new(), + resolution_cover: None, + strategic_tick_count: 0, + } + } + + pub fn digest(&self) -> Result { + crate::legacy_transition::digest_serializable(self) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +pub struct ExternalSubjectAuthority { + pub schema: String, + pub id: String, + pub campaign_id: Uuid, + pub subject_id: String, + pub subject_kind: AgencySubjectKind, + pub owner_id: String, + pub authority_key_sha256: String, + #[serde(default)] + pub last_source_revision: Option, + #[serde(default)] + pub last_payload_digest: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct WorldSeedAdmission { + pub schema: String, + pub campaign_id: Uuid, + pub producer_id: String, + pub producer_kind: WorldSeedProducerKind, + pub seed_digest: String, + pub idempotency_key: String, + #[serde(default)] + pub external_subjects: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +pub struct WorldSeedAdmissionReceipt { + pub schema: String, + pub campaign_id: Uuid, + pub producer_id: String, + pub seed_digest: String, + pub idempotency_key: String, + pub admitted_subject_ids: Vec, + pub admitted_at: DateTime, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct WorldSeedAdmissionRequest { + pub schema: String, + pub seed: WorldSeed, + pub admission: WorldSeedAdmission, + /// Proves possession of every external authority declared in this request. + /// The raw value is never persisted. + pub authority_key: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct ExternalInstitutionSnapshot { + pub schema: String, + pub campaign_id: Uuid, + pub expected_world_revision: u64, + pub authority_id: String, + pub owner_id: String, + pub authority_key: String, + pub source_revision: u64, + pub idempotency_key: String, + pub payload_digest: String, + pub projection: InstitutionState, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +pub struct ExternalSnapshotReceipt { + pub schema: String, + pub id: String, + pub campaign_id: Uuid, + pub authority_id: String, + pub subject_id: String, + pub owner_id: String, + pub source_revision: u64, + pub payload_digest: String, + pub previous_world_revision: u64, + pub world_revision: u64, + pub committed_at: DateTime, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum ExternalProposalStatus { + Pending, + Accepted, + PartiallyAccepted, + Rejected, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct ExternalWorldProposal { + pub schema: String, + pub id: String, + pub campaign_id: Uuid, + pub world_revision: u64, + pub authority_id: String, + pub external_subject_id: String, + pub source_subject_id: String, + pub intent: String, + pub intended_effect: String, + pub action_digest: String, + pub public_channels: Vec, + pub state_references: Vec, + pub status: ExternalProposalStatus, + pub created_at: DateTime, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct ExternalProposalListRequest { + pub schema: String, + pub campaign_id: Uuid, + pub authority_id: String, + pub owner_id: String, + pub authority_key: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct ExternalProposalList { + pub schema: String, + pub campaign_id: Uuid, + pub authority_id: String, + pub proposals: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct ExternalProposalAcknowledgement { + pub schema: String, + pub campaign_id: Uuid, + pub authority_id: String, + pub owner_id: String, + pub authority_key: String, + pub proposal_id: String, + pub idempotency_key: String, + pub status: ExternalProposalStatus, + pub result_summary: String, + pub acknowledged_at: DateTime, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +pub struct ExternalProposalReceipt { + pub schema: String, + pub campaign_id: Uuid, + pub authority_id: String, + pub proposal_id: String, + pub idempotency_key: String, + pub status: ExternalProposalStatus, + pub result_summary: String, + pub acknowledged_at: DateTime, +} + +pub fn authority_key_digest(value: &str) -> String { + format!("sha256:{:x}", Sha256::digest(value.as_bytes())) +} + +pub fn validate_authority_key(authority: &ExternalSubjectAuthority, supplied: &str) -> Result<()> { + if supplied.is_empty() || authority_key_digest(supplied) != authority.authority_key_sha256 { + return Err(anyhow!("external subject authority proof is invalid")); + } + Ok(()) +} + +pub fn snapshot_payload_digest(snapshot: &ExternalInstitutionSnapshot) -> Result { + crate::legacy_transition::digest_serializable(&( + snapshot.campaign_id, + &snapshot.authority_id, + &snapshot.owner_id, + snapshot.source_revision, + &snapshot.idempotency_key, + &snapshot.projection, + )) +} + +pub fn validate_seed_admission( + seed: &WorldSeed, + admission: &WorldSeedAdmission, + authority_key: &str, +) -> Result { + if seed.schema != "ghostlight.world_seed.v1" + || admission.schema != "ghostlight.world_seed_admission.v1" + || seed.id != admission.campaign_id + || admission.seed_digest != seed.digest()? + || admission.producer_id.trim().is_empty() + || admission.idempotency_key.trim().is_empty() + { + return Err(anyhow!("world seed admission envelope is inconsistent")); + } + let mut campaign = seed.clone().into_campaign(); + crate::resolution::ensure_agency_profiles(&mut campaign); + crate::compiler::validate_campaign_seed(&campaign)?; + let mut seen = std::collections::BTreeSet::new(); + let mut seen_subjects = std::collections::BTreeSet::new(); + for authority in &admission.external_subjects { + if authority.schema != "ghostlight.external_subject_authority.v1" + || authority.campaign_id != campaign.id + || authority.owner_id != admission.producer_id + || !seen.insert(authority.id.as_str()) + || !seen_subjects.insert(authority.subject_id.as_str()) + || authority.last_source_revision.is_some() + || authority.last_payload_digest.is_some() + { + return Err(anyhow!( + "external subject authority envelope is inconsistent" + )); + } + validate_authority_key(authority, authority_key)?; + let profile = campaign + .agency_profiles + .get_mut(&authority.subject_id) + .filter(|profile| profile.subject_kind == authority.subject_kind) + .ok_or_else(|| anyhow!("external authority subject or kind is unknown"))?; + if authority.subject_kind != AgencySubjectKind::Institution + || !campaign.institutions.contains_key(&authority.subject_id) + { + return Err(anyhow!( + "the first consumer API slice admits institution-shaped external subjects only" + )); + } + profile.simulation_eligible = false; + } + let primary = &campaign.player_actor_id; + if !campaign.actors.contains_key(primary) + && !campaign.institutions.contains_key(primary) + && !campaign.gestalts.contains_key(primary) + { + return Err(anyhow!("primary controlled subject is missing")); + } + if admission.producer_kind == WorldSeedProducerKind::Consumer + && !admission + .external_subjects + .iter() + .any(|authority| authority.subject_id == *primary) + { + return Err(anyhow!( + "consumer seed primary controlled subject lacks external authority" + )); + } + Ok(campaign) +} + +pub fn proposal_targets(action: &CellActionProposal) -> Vec<&str> { + action + .effects + .iter() + .flat_map(|effect| match effect { + StrategicCellEffect::GestaltActivity { + target_subject_ids, .. + } + | StrategicCellEffect::ActorActivity { + target_subject_ids, .. + } + | StrategicCellEffect::MemberActivity { + target_subject_ids, .. + } => target_subject_ids + .iter() + .map(String::as_str) + .collect::>(), + _ => Vec::new(), + }) + .collect() +} diff --git a/crates/ghostlight-dungeon/src/domain.rs b/crates/ghostlight-dungeon/src/domain.rs index 0250c05..1687686 100644 --- a/crates/ghostlight-dungeon/src/domain.rs +++ b/crates/ghostlight-dungeon/src/domain.rs @@ -978,6 +978,9 @@ pub enum WorldCommand { #[serde(default)] model_stage_receipts: Vec, }, + ApplyExternalInstitutionSnapshot { + snapshot: crate::consumer::ExternalInstitutionSnapshot, + }, Speak { expected_revision: u64, actor_id: String, diff --git a/crates/ghostlight-dungeon/src/kernel.rs b/crates/ghostlight-dungeon/src/kernel.rs index 9a45d1c..66298d4 100644 --- a/crates/ghostlight-dungeon/src/kernel.rs +++ b/crates/ghostlight-dungeon/src/kernel.rs @@ -47,6 +47,10 @@ pub enum CommandResult { campaign: Campaign, receipt: WorldCommitReceipt, }, + ExternalSnapshotCommitted { + campaign: Campaign, + receipt: crate::consumer::ExternalSnapshotReceipt, + }, ResolutionUpdated { campaign: Campaign, receipt: ResolutionControlReceipt, @@ -88,7 +92,7 @@ pub struct WorldKernel { } impl WorldKernel { - pub fn initialize_campaign( + pub(crate) fn initialize_campaign( store: &CampaignStore, command: WorldCommand, ) -> Result { @@ -204,7 +208,11 @@ fn execute( crate::compiler::validate_campaign_seed(&campaign) .map_err(|error| KernelError::Invalid(error.to_string()))?; store - .create_campaign(&campaign, &evidence_receipts, &model_stage_receipts) + .create_unadmitted_fixture_campaign( + &campaign, + &evidence_receipts, + &model_stage_receipts, + ) .map_err(persist)?; return Ok(CommandResult::Created { campaign }); } @@ -214,6 +222,130 @@ fn execute( .map_err(persist)? .ok_or(KernelError::NotFound)?; match command { + WorldCommand::ApplyExternalInstitutionSnapshot { snapshot } => { + if snapshot.schema != "ghostlight.external_institution_snapshot.v1" + || snapshot.campaign_id != campaign.id + { + return Err(KernelError::Invalid( + "external snapshot targets another campaign".into(), + )); + } + let receipt_key = format!("{}:{}", snapshot.authority_id, snapshot.source_revision); + if let Some((_, receipt)) = store + .load::( + "external_snapshot_receipt.v1", + &receipt_key, + ) + .map_err(persist)? + { + return if receipt.payload_digest == snapshot.payload_digest + && receipt.owner_id == snapshot.owner_id + { + Ok(CommandResult::ExternalSnapshotCommitted { campaign, receipt }) + } else { + Err(KernelError::Invalid( + "external snapshot idempotency conflict".into(), + )) + }; + } + let (authority_row, authority) = store + .load::( + "external_subject_authority.v1", + &snapshot.authority_id, + ) + .map_err(persist)? + .ok_or_else(|| { + KernelError::Invalid("external subject authority is unknown".into()) + })?; + if authority.campaign_id != snapshot.campaign_id + || authority.owner_id != snapshot.owner_id + || authority.subject_id != snapshot.projection.id + { + return Err(KernelError::Invalid( + "external snapshot does not match its authority".into(), + )); + } + crate::consumer::validate_authority_key(&authority, &snapshot.authority_key) + .map_err(|error| KernelError::Invalid(error.to_string()))?; + let actual_digest = crate::consumer::snapshot_payload_digest(&snapshot) + .map_err(|error| KernelError::Invalid(error.to_string()))?; + if actual_digest != snapshot.payload_digest { + return Err(KernelError::Invalid( + "external snapshot payload digest is invalid".into(), + )); + } + if authority + .last_source_revision + .is_some_and(|revision| snapshot.source_revision <= revision) + { + return Err(KernelError::Invalid( + "external snapshot source revision is stale".into(), + )); + } + require_revision(&campaign, snapshot.expected_world_revision)?; + campaign + .institutions + .insert(snapshot.projection.id.clone(), snapshot.projection.clone()); + if let Some(profile) = campaign.agency_profiles.get_mut(&snapshot.projection.id) { + profile.facets.insert( + AgencyAxis::Authority, + BTreeSet::from([ + snapshot.projection.id.clone(), + snapshot.projection.posture.clone(), + ]), + ); + profile.facets.insert( + AgencyAxis::EconomyRole, + snapshot.projection.resources.iter().cloned().collect(), + ); + } + let previous_world_revision = campaign.revision; + campaign.revision = campaign.revision.saturating_add(1); + let now = Utc::now(); + campaign.events.push(Event { + id: format!( + "external-snapshot:{}:{}", + snapshot.authority_id, snapshot.source_revision + ), + at: now, + kind: "external_institution_snapshot".into(), + summary: format!( + "{} supplied an authoritative external institution snapshot.", + snapshot.owner_id + ), + actor_ids: Vec::new(), + institution_ids: vec![snapshot.projection.id.clone()], + gestalt_ids: Vec::new(), + location_ids: Vec::new(), + public_channels: Vec::new(), + }); + let mut next_authority = authority; + next_authority.last_source_revision = Some(snapshot.source_revision); + next_authority.last_payload_digest = Some(snapshot.payload_digest.clone()); + let receipt = crate::consumer::ExternalSnapshotReceipt { + schema: "ghostlight.external_snapshot_receipt.v1".into(), + id: receipt_key, + campaign_id: snapshot.campaign_id, + authority_id: snapshot.authority_id, + subject_id: snapshot.projection.id, + owner_id: snapshot.owner_id, + source_revision: snapshot.source_revision, + payload_digest: snapshot.payload_digest, + previous_world_revision, + world_revision: campaign.revision, + committed_at: now, + }; + store + .append_external_snapshot( + &row, + &authority_row, + &campaign, + &next_authority, + &receipt, + ) + .map_err(persist)?; + Ok(CommandResult::ExternalSnapshotCommitted { campaign, receipt }) + } WorldCommand::Assess { expected_revision, intent, @@ -955,6 +1087,25 @@ fn execute( .map(|wave| crate::resolution::validate_and_resolve_wave(&campaign, wave)) .transpose() .map_err(|error| KernelError::Invalid(error.to_string()))?; + let external_subject_ids = store + .load_all::( + "external_subject_authority.v1", + ) + .map_err(persist)? + .into_iter() + .map(|authority| authority.subject_id) + .collect::>(); + if resolved_plan + .as_ref() + .or(plan.as_ref()) + .is_some_and(|plan| { + strategic_plan_writes_external_subject(plan, &external_subject_ids) + }) + { + return Err(KernelError::Invalid( + "strategic resolution cannot mutate an external subject or bypass its proposal boundary".into(), + )); + } if (plan.is_some() || resolution_wave.is_some()) && model_receipt_hash .as_deref() @@ -1648,6 +1799,58 @@ fn execute( } } +fn external_outcome_writes_subject( + effect: &StrategicOutcomeEffect, + external_subject_ids: &BTreeSet, +) -> bool { + match effect { + StrategicOutcomeEffect::ResourceCreated { + owner_subject_id, .. + } + | StrategicOutcomeEffect::ResourceConsumed { + owner_subject_id, .. + } + | StrategicOutcomeEffect::KnowledgeLearned { + owner_subject_id, .. + } => external_subject_ids.contains(owner_subject_id), + StrategicOutcomeEffect::ResourceTransferred { + from_subject_id, + to_subject_id, + .. + } => { + external_subject_ids.contains(from_subject_id) + || external_subject_ids.contains(to_subject_id) + } + StrategicOutcomeEffect::KnowledgeCommunicated { to_subject_ids, .. } => to_subject_ids + .iter() + .any(|subject_id| external_subject_ids.contains(subject_id)), + StrategicOutcomeEffect::NoMaterialChange { .. } + | StrategicOutcomeEffect::GestaltPressure { .. } + | StrategicOutcomeEffect::AgencyRelationShift { .. } + | StrategicOutcomeEffect::MemberMemory { .. } + | StrategicOutcomeEffect::MemberObligation { .. } + | StrategicOutcomeEffect::MemberRelationship { .. } => false, + } +} + +fn strategic_plan_writes_external_subject( + plan: &StrategicTickPlan, + external_subject_ids: &BTreeSet, +) -> bool { + plan.selected_actions.iter().any(|action| { + crate::consumer::proposal_targets(action) + .iter() + .any(|target| external_subject_ids.contains(*target)) + }) || plan + .institution_actions + .iter() + .any(|action| external_subject_ids.contains(&action.institution_id)) + || plan + .activity_outcomes + .iter() + .any(|outcome| external_outcome_writes_subject(&outcome.effect, external_subject_ids)) +} + fn expected_activity_outcome_bindings( campaign: &Campaign, action_digests: &[String], @@ -3256,6 +3459,23 @@ fn commit_strategic_tick( let previous_revision = campaign.revision; campaign.revision += 1; let committed_at = Utc::now(); + let external_authorities = store + .load_all::("external_subject_authority.v1") + .map_err(persist)?; + let external_proposals = resolution_wave + .as_ref() + .map(|wave| { + external_proposals_for_wave( + campaign.id, + campaign.revision, + committed_at, + wave, + &external_authorities, + ) + }) + .transpose() + .map_err(|error| KernelError::Invalid(error.to_string()))? + .unwrap_or_default(); let receipt = WorldCommitReceipt { schema: "ghostlight.world_commit_receipt.v1".into(), campaign_id: campaign.id, @@ -3295,6 +3515,7 @@ fn commit_strategic_tick( &receipt, &strategic, resolution_wave.as_ref(), + &external_proposals, mutation .as_ref() .map(|(transition, receipt)| (&transition.authority, &transition.batch, receipt)), @@ -3303,6 +3524,50 @@ fn commit_strategic_tick( Ok(CommandResult::Committed { campaign, receipt }) } +fn external_proposals_for_wave( + campaign_id: uuid::Uuid, + world_revision: u64, + created_at: chrono::DateTime, + wave: &ResolutionWaveCommit, + authorities: &[crate::consumer::ExternalSubjectAuthority], +) -> anyhow::Result> { + let mut proposals = Vec::new(); + for appraisal in &wave.appraisals { + for action in &appraisal.actions { + let action_digest = crate::resolution::cell_action_digest(action)?; + for authority in authorities { + if crate::consumer::proposal_targets(action) + .contains(&authority.subject_id.as_str()) + { + let id = crate::legacy_transition::digest_serializable(&( + campaign_id, + world_revision, + &authority.id, + &action_digest, + ))?; + proposals.push(crate::consumer::ExternalWorldProposal { + schema: "ghostlight.external_world_proposal.v1".into(), + id: format!("external-proposal:{id}"), + campaign_id, + world_revision, + authority_id: authority.id.clone(), + external_subject_id: authority.subject_id.clone(), + source_subject_id: action.subject_id.clone(), + intent: action.intent.clone(), + intended_effect: action.intended_effect.clone(), + action_digest: action_digest.clone(), + public_channels: action.public_channels.clone(), + state_references: action.state_references.clone(), + status: crate::consumer::ExternalProposalStatus::Pending, + created_at, + }); + } + } + } + } + Ok(proposals) +} + fn commit_resolution_control( store: &CampaignStore, row: cultcache_legacy::CultCacheEnvelope, @@ -4304,7 +4569,9 @@ mod tests { let mut aggregate = campaign(); aggregate.id = campaign_id; - store.create_campaign(&aggregate, &[], &[]).unwrap(); + store + .create_unadmitted_fixture_campaign(&aggregate, &[], &[]) + .unwrap(); let error = kernel .commit_mutation_batch(authority, batch) .await @@ -7780,6 +8047,93 @@ mod tests { } } + #[test] + fn direct_strategic_plan_cannot_write_external_subject_state() { + let external = BTreeSet::from(["external-hold".to_string()]); + let mut plan = StrategicTickPlan::default(); + plan.institution_actions.push(StrategicInstitutionAction { + institution_id: "external-hold".into(), + posture: "overwritten".into(), + location_ids: Vec::new(), + public_channels: Vec::new(), + }); + assert!(strategic_plan_writes_external_subject(&plan, &external)); + + plan.institution_actions.clear(); + plan.activity_outcomes.push(StrategicActivityOutcome { + schema: "ghostlight.strategic_activity_outcome.v1".into(), + action_digest: format!("sha256:{}", "a".repeat(64)), + source_subject_id: "foreign-court".into(), + band: StrategicOutcomeBand::Success, + summary: "Attempted cross-boundary resource mutation.".into(), + supporting_state_references: Vec::new(), + effect: StrategicOutcomeEffect::ResourceConsumed { + owner_subject_id: "external-hold".into(), + resource: "ore".into(), + }, + }); + assert!(strategic_plan_writes_external_subject(&plan, &external)); + + plan.activity_outcomes.clear(); + plan.selected_actions.push(CellActionProposal { + subject_id: "foreign-court".into(), + intent: "Contact the hold.".into(), + intended_effect: "Request negotiation.".into(), + priority: 1, + state_references: Vec::new(), + public_channels: Vec::new(), + effects: vec![StrategicCellEffect::ActorActivity { + actor_id: "foreign-court".into(), + activity: StrategicActivityKind::Communicate, + target_subject_ids: vec!["external-hold".into()], + location_ids: Vec::new(), + }], + }); + assert!(strategic_plan_writes_external_subject(&plan, &external)); + } + + #[test] + fn strategic_wave_derives_attributed_external_proposal() { + let dir = tempfile::tempdir().unwrap(); + let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); + let campaign = crate::resolution::tests::campaign(2, 2); + let mut wave = inaction_wave(&campaign, &store); + let appraisal = wave.appraisals.first_mut().unwrap(); + let source_subject_id = appraisal.inactions[0].subject_id.clone(); + appraisal.inactions.clear(); + appraisal.actions.push(CellActionProposal { + subject_id: source_subject_id.clone(), + intent: "Open talks with the external hold.".into(), + intended_effect: "Establish a negotiating channel.".into(), + priority: 1, + state_references: Vec::new(), + public_channels: vec!["diplomatic".into()], + effects: vec![StrategicCellEffect::ActorActivity { + actor_id: source_subject_id.clone(), + activity: StrategicActivityKind::Communicate, + target_subject_ids: vec!["external-hold".into()], + location_ids: Vec::new(), + }], + }); + let authorities = vec![crate::consumer::ExternalSubjectAuthority { + schema: "ghostlight.external_subject_authority.v1".into(), + id: "authority:external-hold".into(), + campaign_id: campaign.id, + subject_id: "external-hold".into(), + subject_kind: AgencySubjectKind::Institution, + owner_id: "fixture-consumer".into(), + authority_key_sha256: crate::consumer::authority_key_digest("secret"), + last_source_revision: None, + last_payload_digest: None, + }]; + let proposals = + external_proposals_for_wave(campaign.id, 1, Utc::now(), &wave, &authorities).unwrap(); + assert_eq!(proposals.len(), 1); + assert_eq!(proposals[0].source_subject_id, source_subject_id); + assert_eq!(proposals[0].external_subject_id, "external-hold"); + assert_eq!(proposals[0].authority_id, "authority:external-hold"); + } + #[tokio::test] async fn resolution_budget_commits_without_advancing_fictional_state() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/ghostlight-dungeon/src/lib.rs b/crates/ghostlight-dungeon/src/lib.rs index 708c301..a2d6bdb 100644 --- a/crates/ghostlight-dungeon/src/lib.rs +++ b/crates/ghostlight-dungeon/src/lib.rs @@ -3,6 +3,7 @@ pub mod agency_corpus; pub mod assessor; pub mod compiler; +pub mod consumer; pub mod d20; pub mod domain; pub mod gestalt; diff --git a/crates/ghostlight-dungeon/src/main.rs b/crates/ghostlight-dungeon/src/main.rs index 68202b0..8a5e1a9 100644 --- a/crates/ghostlight-dungeon/src/main.rs +++ b/crates/ghostlight-dungeon/src/main.rs @@ -5427,6 +5427,11 @@ fn player_command_projection(result: &CommandResult) -> serde_json::Value { "revision":receipt.revision, "receipt":receipt, }), + CommandResult::ExternalSnapshotCommitted { receipt, .. } => serde_json::json!({ + "kind":"external_snapshot_committed", + "revision":receipt.world_revision, + "receipt":receipt, + }), CommandResult::ResolutionUpdated { receipt, .. } => serde_json::json!({ "kind":"resolution_updated", "receipt":receipt, @@ -5475,6 +5480,7 @@ fn player_http_command_allowed(command: &WorldCommand, player_actor_id: &str) -> WorldCommand::Attempt { .. } => false, WorldCommand::Wait { .. } | WorldCommand::SetResolutionBudget { .. } => true, WorldCommand::CreateCampaign { .. } + | WorldCommand::ApplyExternalInstitutionSnapshot { .. } | WorldCommand::ProposeTimeAdvance { .. } | WorldCommand::ApproveTimeAdvance { .. } | WorldCommand::ProposeGroupTravel { .. } @@ -6993,7 +6999,7 @@ mod tests { ); let runtime = state .registry - .create(campaign.clone(), vec![], vec![]) + .create_unadmitted_fixture(campaign.clone(), vec![], vec![]) .await .unwrap(); process_due_ticks( @@ -7045,7 +7051,7 @@ mod tests { ); let runtime = state .registry - .create(campaign.clone(), vec![], vec![]) + .create_unadmitted_fixture(campaign.clone(), vec![], vec![]) .await .unwrap(); @@ -7080,7 +7086,7 @@ mod tests { let campaign = seed("Membership-bound"); let runtime = state .registry - .create(campaign.clone(), vec![], vec![]) + .create_unadmitted_fixture(campaign.clone(), vec![], vec![]) .await .unwrap(); runtime @@ -7157,7 +7163,7 @@ mod tests { let campaign = seed("Export witness"); let runtime = state .registry - .create(campaign.clone(), vec![], vec![]) + .create_unadmitted_fixture(campaign.clone(), vec![], vec![]) .await .unwrap(); let expected_export = load_campaign(&runtime.store).unwrap(); diff --git a/crates/ghostlight-dungeon/src/mesh.rs b/crates/ghostlight-dungeon/src/mesh.rs index dfbcb6c..0b6e417 100644 --- a/crates/ghostlight-dungeon/src/mesh.rs +++ b/crates/ghostlight-dungeon/src/mesh.rs @@ -204,6 +204,19 @@ impl MeshPublisher { "heimdall.access_gate_state.v1" ], "witnesses":[{"kind":"source-commit","ref":option_env!("GHOSTLIGHT_BUILD_COMMIT").unwrap_or("development")}], + "worldConsumerBoundary":{ + "serviceId":"ghostlight.world.consumer", + "transport":"cultnet.transport.rudp.v0", + "endpoint":"127.0.0.1:4102", + "exposure":"loopback-only", + "operations":[ + "ghostlight.world.seed.admit", + "ghostlight.world.external.snapshot.apply", + "ghostlight.world.external.proposals.list", + "ghostlight.world.external.proposal.acknowledge" + ], + "ownership":"Consumers own declared external subjects; Ghostlight owns all simulated world subjects and emits proposals across that boundary." + }, "surfaces":[{ "surfaceId":SURFACE_ID, "schema":"gamecult.eve.surface.v1", @@ -237,7 +250,8 @@ impl MeshPublisher { }], "commands":[ {"command":COMMAND_BOUNDARY,"transport":"https-json","summary":"Canonical Ghostlight Eve command boundary."}, - {"command":"ghostlight.native.player","transport":"cultnet.transport.rudp.v0","summary":"Loopback native access to the same actor-filtered surface and Eve command authority."} + {"command":"ghostlight.native.player","transport":"cultnet.transport.rudp.v0","summary":"Loopback native access to the same actor-filtered surface and Eve command authority."}, + {"command":"ghostlight.world.consumer","transport":"cultnet.transport.rudp.v0","summary":"Typed world-seed admission, external snapshots, and proposal exchange for game consumers."} ] }) } @@ -567,7 +581,18 @@ fn schema_catalog() -> Value { json!({ "ghostlight.campaign.v1": schemars::schema_for!(Campaign), "ghostlight.session_zero.v1": schemars::schema_for!(SessionZeroState), - "ghostlight.vault_source_manifest.v1": schemars::schema_for!(VaultSourceManifest) + "ghostlight.vault_source_manifest.v1": schemars::schema_for!(VaultSourceManifest), + "ghostlight.world_seed.v1": schemars::schema_for!(crate::consumer::WorldSeed), + "ghostlight.world_seed_admission_request.v1": schemars::schema_for!(crate::consumer::WorldSeedAdmissionRequest), + "ghostlight.world_seed_admission_receipt.v1": schemars::schema_for!(crate::consumer::WorldSeedAdmissionReceipt), + "ghostlight.external_subject_authority.v1": schemars::schema_for!(crate::consumer::ExternalSubjectAuthority), + "ghostlight.external_institution_snapshot.v1": schemars::schema_for!(crate::consumer::ExternalInstitutionSnapshot), + "ghostlight.external_snapshot_receipt.v1": schemars::schema_for!(crate::consumer::ExternalSnapshotReceipt), + "ghostlight.external_world_proposal.v1": schemars::schema_for!(crate::consumer::ExternalWorldProposal), + "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) }) } @@ -595,7 +620,7 @@ mod tests { .get_required::("ghostlight:schema-catalog") .unwrap(); let schemas = catalog.value["schemas"].as_object().unwrap(); - assert_eq!(schemas.len(), 3); + assert_eq!(schemas.len(), 14); 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()); diff --git a/crates/ghostlight-dungeon/src/native_cultmesh.rs b/crates/ghostlight-dungeon/src/native_cultmesh.rs index f8ca08f..89153a8 100644 --- a/crates/ghostlight-dungeon/src/native_cultmesh.rs +++ b/crates/ghostlight-dungeon/src/native_cultmesh.rs @@ -232,7 +232,10 @@ async fn handle_operation_inner( else { bail!("native boundary accepts only operation requests"); }; - if service_id != NATIVE_SERVICE_ID || payload_encoding != "messagepack-base64" { + if payload_encoding != "messagepack-base64" + || (service_id != NATIVE_SERVICE_ID + && service_id != ghostlight_dungeon::consumer::WORLD_CONSUMER_SERVICE_ID) + { bail!("native request does not match the advertised service contract"); } if target_runtime_id @@ -241,6 +244,74 @@ async fn handle_operation_inner( { bail!("native request targets another runtime"); } + if service_id == ghostlight_dungeon::consumer::WORLD_CONSUMER_SERVICE_ID { + return match operation.as_str() { + ghostlight_dungeon::consumer::ADMIT_WORLD_OPERATION => { + require_schema(payload_schema, "ghostlight.world_seed_admission_request.v1")?; + let command: ghostlight_dungeon::consumer::WorldSeedAdmissionRequest = + decode_request(request)?; + require_schema( + &command.schema, + "ghostlight.world_seed_admission_request.v1", + )?; + let (_, receipt) = state.registry.admit_world_seed(command).await?; + success_response( + request, + "ghostlight.world_seed_admission_receipt.v1", + &receipt, + ) + } + ghostlight_dungeon::consumer::APPLY_EXTERNAL_SNAPSHOT_OPERATION => { + require_schema( + payload_schema, + "ghostlight.external_institution_snapshot.v1", + )?; + let command: ghostlight_dungeon::consumer::ExternalInstitutionSnapshot = + decode_request(request)?; + require_schema( + &command.schema, + "ghostlight.external_institution_snapshot.v1", + )?; + let receipt = state + .registry + .apply_external_institution_snapshot(command) + .await?; + success_response(request, "ghostlight.external_snapshot_receipt.v1", &receipt) + } + ghostlight_dungeon::consumer::LIST_EXTERNAL_PROPOSALS_OPERATION => { + require_schema( + payload_schema, + "ghostlight.external_proposal_list_request.v1", + )?; + let command: ghostlight_dungeon::consumer::ExternalProposalListRequest = + decode_request(request)?; + require_schema( + &command.schema, + "ghostlight.external_proposal_list_request.v1", + )?; + let proposals = state.registry.list_external_proposals(command).await?; + success_response(request, "ghostlight.external_proposal_list.v1", &proposals) + } + ghostlight_dungeon::consumer::ACKNOWLEDGE_EXTERNAL_PROPOSAL_OPERATION => { + require_schema( + payload_schema, + "ghostlight.external_proposal_acknowledgement.v1", + )?; + let command: ghostlight_dungeon::consumer::ExternalProposalAcknowledgement = + decode_request(request)?; + require_schema( + &command.schema, + "ghostlight.external_proposal_acknowledgement.v1", + )?; + let receipt = state + .registry + .acknowledge_external_proposal(command) + .await?; + success_response(request, "ghostlight.external_proposal_receipt.v1", &receipt) + } + _ => bail!("world consumer operation is not advertised by Ghostlight"), + }; + } match operation.as_str() { NATIVE_AUTH_BEGIN => { require_schema(payload_schema, "ghostlight.native_auth_begin.v1")?; @@ -346,17 +417,22 @@ fn failure_response(request: &CultNetMessage, code: &str, message: &str) -> Resu } fn bare_failure_response(request: &CultNetMessage) -> CultNetMessage { - let (message_id, operation) = match request { + let (message_id, service_id, operation) = match request { CultNetMessage::OperationRequest { message_id, + service_id, operation, .. - } => (message_id.clone(), operation.clone()), - _ => (uuid::Uuid::new_v4().to_string(), "unknown".into()), + } => (message_id.clone(), service_id.clone(), operation.clone()), + _ => ( + uuid::Uuid::new_v4().to_string(), + NATIVE_SERVICE_ID.into(), + "unknown".into(), + ), }; CultNetMessage::OperationResponse { message_id, - service_id: NATIVE_SERVICE_ID.into(), + service_id, operation, status: "denied".into(), payload_schema: "ghostlight.native_failure.v1".into(), diff --git a/crates/ghostlight-dungeon/src/persistence.rs b/crates/ghostlight-dungeon/src/persistence.rs index d747fba..3aab56e 100644 --- a/crates/ghostlight-dungeon/src/persistence.rs +++ b/crates/ghostlight-dungeon/src/persistence.rs @@ -1,3 +1,7 @@ +use crate::consumer::{ + ExternalProposalReceipt, ExternalSnapshotReceipt, ExternalSubjectAuthority, + ExternalWorldProposal, WorldSeedAdmission, WorldSeedAdmissionReceipt, +}; use crate::domain::{ Campaign, CampaignLifecycleReceipt, GestaltMaterializationReceipt, ResolutionControlReceipt, ResolutionWaveCommit, StrategicTickReceipt, VaultEvidenceReceipt, VaultManifest, @@ -152,16 +156,46 @@ impl CampaignStore { Ok(next_row) } - pub fn create_campaign( + #[doc(hidden)] + pub fn create_unadmitted_fixture_campaign( &self, campaign: &Campaign, receipts: &[VaultEvidenceReceipt], model_receipts: &[crate::model::ModelStageReceipt], ) -> Result { - self.create_campaign_rows(campaign, receipts, model_receipts, None) + self.create_campaign_rows(campaign, receipts, model_receipts, None, None) } - pub fn create_session_zero_campaign( + pub fn create_admitted_campaign( + &self, + campaign: &Campaign, + receipts: &[VaultEvidenceReceipt], + model_receipts: &[crate::model::ModelStageReceipt], + admission: &WorldSeedAdmission, + admission_receipt: &WorldSeedAdmissionReceipt, + session_zero_publication: Option<&PublishedSessionZeroSeed>, + ) -> Result { + if admission.campaign_id != campaign.id + || admission_receipt.campaign_id != campaign.id + || admission.seed_digest != admission_receipt.seed_digest + || admission.producer_id != admission_receipt.producer_id + || admission.idempotency_key != admission_receipt.idempotency_key + { + return Err(anyhow!( + "world seed admission persistence bundle is inconsistent" + )); + } + self.create_campaign_rows( + campaign, + receipts, + model_receipts, + Some((admission, admission_receipt)), + session_zero_publication, + ) + } + + #[cfg(test)] + pub(crate) fn create_session_zero_campaign( &self, campaign: &Campaign, receipts: &[VaultEvidenceReceipt], @@ -173,7 +207,7 @@ impl CampaignStore { { return Err(anyhow!("Session Zero publication targets another campaign")); } - self.create_campaign_rows(campaign, receipts, model_receipts, Some(publication)) + self.create_campaign_rows(campaign, receipts, model_receipts, None, Some(publication)) } fn create_campaign_rows( @@ -181,6 +215,7 @@ impl CampaignStore { campaign: &Campaign, receipts: &[VaultEvidenceReceipt], model_receipts: &[crate::model::ModelStageReceipt], + admission: Option<(&WorldSeedAdmission, &WorldSeedAdmissionReceipt)>, publication: Option<&PublishedSessionZeroSeed>, ) -> Result { let campaign_row = envelope( @@ -196,6 +231,28 @@ impl CampaignStore { &campaign.id.to_string(), campaign, )?); + if let Some((admission, receipt)) = admission { + rows.push(envelope( + "world_seed_admission.v1", + "ghostlight.world_seed_admission.v1", + &campaign.id.to_string(), + admission, + )?); + rows.push(envelope( + "world_seed_admission_receipt.v1", + "ghostlight.world_seed_admission_receipt.v1", + &campaign.id.to_string(), + receipt, + )?); + for authority in &admission.external_subjects { + rows.push(envelope( + "external_subject_authority.v1", + "ghostlight.external_subject_authority.v1", + &authority.id, + authority, + )?); + } + } let manifest = merge_vault_manifest(None, receipts); rows.push(envelope( "vault_manifest.v1", @@ -300,6 +357,95 @@ impl CampaignStore { Ok(campaign_row) } + pub fn append_external_snapshot( + &self, + expected_campaign: &CultCacheEnvelope, + expected_authority: &CultCacheEnvelope, + next_campaign: &Campaign, + next_authority: &ExternalSubjectAuthority, + receipt: &ExternalSnapshotReceipt, + ) -> Result { + if expected_campaign.key != next_campaign.id.to_string() + || expected_authority.key != next_authority.id + || receipt.campaign_id != next_campaign.id + || receipt.authority_id != next_authority.id + || receipt.subject_id != next_authority.subject_id + || receipt.world_revision != next_campaign.revision + || receipt.previous_world_revision.saturating_add(1) != next_campaign.revision + { + return Err(anyhow!( + "external snapshot persistence bundle is inconsistent" + )); + } + let next_campaign_row = envelope( + "campaign.v1", + "ghostlight.campaign.v1", + &next_campaign.id.to_string(), + next_campaign, + )?; + let rows = vec![ + next_campaign_row.clone(), + envelope( + "external_subject_authority.v1", + "ghostlight.external_subject_authority.v1", + &next_authority.id, + next_authority, + )?, + envelope( + "external_snapshot_receipt.v1", + "ghostlight.external_snapshot_receipt.v1", + &format!("{}:{}", receipt.authority_id, receipt.source_revision), + receipt, + )?, + ]; + if !self.inner.compare_and_swap_batch( + &[expected_campaign.clone(), expected_authority.clone()], + rows, + )? { + return Err(anyhow!("stale external snapshot or authority watermark")); + } + Ok(next_campaign_row) + } + + pub fn append_external_proposals( + &self, + rows: &mut Vec, + proposals: &[ExternalWorldProposal], + ) -> Result<()> { + for proposal in proposals { + rows.push(envelope( + "external_world_proposal.v1", + "ghostlight.external_world_proposal.v1", + &proposal.id, + proposal, + )?); + } + Ok(()) + } + + pub fn record_external_proposal_receipt( + &self, + receipt: &ExternalProposalReceipt, + ) -> Result { + let key = receipt.proposal_id.clone(); + if let Some((_, existing)) = + self.load::("external_proposal_receipt.v1", &key)? + { + return if existing == *receipt { + Ok(existing) + } else { + Err(anyhow!("external proposal receipt idempotency conflict")) + }; + } + self.insert( + "external_proposal_receipt.v1", + "ghostlight.external_proposal_receipt.v1", + &key, + receipt, + )?; + Ok(receipt.clone()) + } + pub fn snapshot_to(&self, path: impl AsRef) -> Result<()> { let rows = self.inner.pull_all()?; let target = OwnedRedbMessagePackBackingStore::new(path.as_ref())?; @@ -730,6 +876,7 @@ impl CampaignStore { world_receipt: &WorldCommitReceipt, strategic_receipt: &StrategicTickReceipt, resolution_wave: Option<&ResolutionWaveCommit>, + external_proposals: &[ExternalWorldProposal], mutation: Option<( &MutationAuthorityEnvelope, &WorldMutationBatch, @@ -797,6 +944,7 @@ impl CampaignStore { )?); } } + self.append_external_proposals(&mut rows, external_proposals)?; if let Some((authority, batch, mutation_receipt)) = mutation { if mutation_receipt.previous_world_revision != world_receipt.previous_revision || mutation_receipt.world_revision != world_receipt.revision diff --git a/crates/ghostlight-dungeon/src/registry.rs b/crates/ghostlight-dungeon/src/registry.rs index 7ed6bf9..1e9c1e3 100644 --- a/crates/ghostlight-dungeon/src/registry.rs +++ b/crates/ghostlight-dungeon/src/registry.rs @@ -1,4 +1,11 @@ use crate::{ + consumer::{ + ExternalProposalAcknowledgement, ExternalProposalList, ExternalProposalListRequest, + ExternalProposalReceipt, ExternalProposalStatus, ExternalSubjectAuthority, + ExternalWorldProposal, WorldSeed, WorldSeedAdmission, WorldSeedAdmissionReceipt, + WorldSeedAdmissionRequest, WorldSeedProducerKind, validate_authority_key, + validate_seed_admission, + }, domain::{Campaign, CampaignLifecycleReceipt, VaultEvidenceReceipt}, kernel::WorldKernel, model::ModelStageReceipt, @@ -117,7 +124,8 @@ impl CampaignRegistry { self.runtimes.read().await.keys().copied().collect() } - pub async fn create( + #[doc(hidden)] + pub async fn create_unadmitted_fixture( &self, campaign: Campaign, evidence: Vec, @@ -152,46 +160,77 @@ impl CampaignRegistry { "every campaign member must bind an existing human-protected actor" )); } - if let Ok(existing) = self.runtime(campaign.id).await { - let stored = existing - .store - .load::( - "session_zero_publication.v1", - &campaign.id.to_string(), - )? - .map(|(_, value)| value); - return match stored { - Some(stored) if stored.approved_seed_digest == publication.approved_seed_digest => { - Ok(existing) - } - _ => Err(anyhow!( - "campaign id is already published from another seed" - )), - }; + let seed = WorldSeed::from_campaign(&campaign)?; + let admission = WorldSeedAdmission { + schema: "ghostlight.world_seed_admission.v1".into(), + campaign_id: campaign.id, + producer_id: format!("session-zero:{}", publication.session_zero_id), + producer_kind: WorldSeedProducerKind::Compiler, + seed_digest: seed.digest()?, + idempotency_key: publication.approved_seed_digest.clone(), + external_subjects: Vec::new(), + }; + self.admit_seed( + seed, + admission, + "", + evidence, + model_receipts, + Some(publication), + ) + .await + .map(|(runtime, _)| runtime) + } + + pub async fn admit_world_seed( + &self, + request: WorldSeedAdmissionRequest, + ) -> Result<(CampaignRuntime, WorldSeedAdmissionReceipt)> { + if request.schema != "ghostlight.world_seed_admission_request.v1" { + return Err(anyhow!("world seed admission request schema is invalid")); + } + self.admit_seed( + request.seed, + request.admission, + &request.authority_key, + Vec::new(), + Vec::new(), + None, + ) + .await + } + + async fn admit_seed( + &self, + seed: WorldSeed, + admission: WorldSeedAdmission, + authority_key: &str, + evidence: Vec, + model_receipts: Vec, + publication: Option, + ) -> Result<(CampaignRuntime, WorldSeedAdmissionReceipt)> { + let campaign = validate_seed_admission(&seed, &admission, authority_key)?; + let receipt = WorldSeedAdmissionReceipt { + schema: "ghostlight.world_seed_admission_receipt.v1".into(), + campaign_id: campaign.id, + producer_id: admission.producer_id.clone(), + seed_digest: admission.seed_digest.clone(), + idempotency_key: admission.idempotency_key.clone(), + admitted_subject_ids: admission + .external_subjects + .iter() + .map(|item| item.subject_id.clone()) + .collect(), + admitted_at: Utc::now(), + }; + if let Some(existing) = self.open_existing_admission(&admission).await? { + return Ok(existing); } let directory = self.root.join(campaign.id.to_string()); if directory.exists() { - let store = CampaignStore::open(directory.join("campaign.cc"))?; - let stored = store - .load::( - "session_zero_publication.v1", - &campaign.id.to_string(), - )? - .map(|(_, value)| value); - if stored.as_ref().is_some_and(|stored| { - stored.approved_seed_digest == publication.approved_seed_digest - }) { - let runtime = CampaignRuntime { - kernel: WorldKernel::start(store.clone()), - store, - }; - self.runtimes - .write() - .await - .insert(campaign.id, runtime.clone()); - return Ok(runtime); - } - return Err(anyhow!("campaign directory belongs to another seed")); + return Err(anyhow!( + "campaign directory belongs to another admitted seed" + )); } let staging = self .root @@ -199,11 +238,13 @@ impl CampaignRegistry { fs::create_dir(&staging)?; let prepared = (|| -> Result<()> { let store = CampaignStore::open(staging.join("campaign.cc"))?; - store.create_session_zero_campaign( + store.create_admitted_campaign( &campaign, &evidence, &model_receipts, - &publication, + &admission, + &receipt, + publication.as_ref(), )?; drop(store); fs::rename(&staging, &directory)?; @@ -222,7 +263,169 @@ impl CampaignRegistry { .write() .await .insert(campaign.id, runtime.clone()); - Ok(runtime) + Ok((runtime, receipt)) + } + + async fn open_existing_admission( + &self, + admission: &WorldSeedAdmission, + ) -> Result> { + let runtime = if let Ok(runtime) = self.runtime(admission.campaign_id).await { + Some(runtime) + } else { + let directory = self.root.join(admission.campaign_id.to_string()); + if !directory.exists() { + None + } else { + let store = CampaignStore::open(directory.join("campaign.cc"))?; + Some(CampaignRuntime { + kernel: WorldKernel::start(store.clone()), + store, + }) + } + }; + let Some(runtime) = runtime else { + return Ok(None); + }; + let stored = runtime + .store + .load::( + "world_seed_admission.v1", + &admission.campaign_id.to_string(), + )? + .map(|(_, value)| value); + let stored_receipt = runtime + .store + .load::( + "world_seed_admission_receipt.v1", + &admission.campaign_id.to_string(), + )? + .map(|(_, value)| value); + match (stored, stored_receipt) { + (Some(stored), Some(receipt)) if stored == *admission => { + self.runtimes + .write() + .await + .insert(admission.campaign_id, runtime.clone()); + Ok(Some((runtime, receipt))) + } + _ => Err(anyhow!("campaign id is already admitted from another seed")), + } + } + + pub async fn apply_external_institution_snapshot( + &self, + snapshot: crate::consumer::ExternalInstitutionSnapshot, + ) -> Result { + let runtime = self.runtime(snapshot.campaign_id).await?; + match runtime + .kernel + .command(crate::domain::WorldCommand::ApplyExternalInstitutionSnapshot { snapshot }) + .await + .map_err(|error| anyhow!(error.to_string()))? + { + crate::kernel::CommandResult::ExternalSnapshotCommitted { receipt, .. } => Ok(receipt), + _ => Err(anyhow!( + "kernel returned the wrong external snapshot result" + )), + } + } + + pub async fn list_external_proposals( + &self, + request: ExternalProposalListRequest, + ) -> Result { + if request.schema != "ghostlight.external_proposal_list_request.v1" { + return Err(anyhow!("external proposal list request schema 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!( + "external proposal request does not match its authority" + )); + } + validate_authority_key(&authority, &request.authority_key)?; + let receipts = runtime + .store + .load_all::("external_proposal_receipt.v1")?; + let acknowledged: std::collections::BTreeSet<_> = receipts + .into_iter() + .map(|receipt| receipt.proposal_id) + .collect(); + let proposals = runtime + .store + .load_all::("external_world_proposal.v1")? + .into_iter() + .filter(|proposal| { + proposal.authority_id == request.authority_id + && !acknowledged.contains(&proposal.id) + }) + .collect(); + Ok(ExternalProposalList { + schema: "ghostlight.external_proposal_list.v1".into(), + campaign_id: request.campaign_id, + authority_id: request.authority_id, + proposals, + }) + } + + pub async fn acknowledge_external_proposal( + &self, + acknowledgement: ExternalProposalAcknowledgement, + ) -> Result { + if acknowledgement.schema != "ghostlight.external_proposal_acknowledgement.v1" + || acknowledgement.status == ExternalProposalStatus::Pending + || acknowledgement.idempotency_key.trim().is_empty() + || acknowledgement.result_summary.trim().is_empty() + || acknowledgement.result_summary.chars().count() > 1000 + { + return Err(anyhow!("external proposal acknowledgement is invalid")); + } + let runtime = self.runtime(acknowledgement.campaign_id).await?; + let (_, authority) = runtime + .store + .load::( + "external_subject_authority.v1", + &acknowledgement.authority_id, + )? + .ok_or_else(|| anyhow!("external subject authority is unknown"))?; + if authority.owner_id != acknowledgement.owner_id { + return Err(anyhow!( + "external acknowledgement does not match its authority" + )); + } + validate_authority_key(&authority, &acknowledgement.authority_key)?; + let (_, proposal) = runtime + .store + .load::( + "external_world_proposal.v1", + &acknowledgement.proposal_id, + )? + .ok_or_else(|| anyhow!("external proposal is unknown"))?; + if proposal.authority_id != acknowledgement.authority_id + || proposal.campaign_id != acknowledgement.campaign_id + { + return Err(anyhow!("external proposal belongs to another authority")); + } + runtime + .store + .record_external_proposal_receipt(&ExternalProposalReceipt { + schema: "ghostlight.external_proposal_receipt.v1".into(), + campaign_id: acknowledgement.campaign_id, + authority_id: acknowledgement.authority_id, + proposal_id: acknowledgement.proposal_id, + idempotency_key: acknowledgement.idempotency_key, + status: acknowledgement.status, + result_summary: acknowledgement.result_summary, + acknowledged_at: acknowledgement.acknowledged_at, + }) } async fn create_with_lifecycle( @@ -587,7 +790,7 @@ mod tests { provider_attempts: vec![], }; registry - .create(original.clone(), vec![], vec![model_receipt.clone()]) + .create_unadmitted_fixture(original.clone(), vec![], vec![model_receipt.clone()]) .await .unwrap(); let fork = registry.fork(original.id, "Fork".into()).await.unwrap(); @@ -655,7 +858,7 @@ mod tests { let registry = CampaignRegistry::new(dir.path().join("campaigns")).unwrap(); let original = seed("Original"); registry - .create(original.clone(), vec![], vec![]) + .create_unadmitted_fixture(original.clone(), vec![], vec![]) .await .unwrap(); @@ -694,13 +897,18 @@ mod tests { .unwrap() .location_id = "missing".into(); - assert!(registry.create(invalid, vec![], vec![]).await.is_err()); + assert!( + registry + .create_unadmitted_fixture(invalid, vec![], vec![]) + .await + .is_err() + ); assert!(registry.list().await.is_empty()); assert_eq!(std::fs::read_dir(&root).unwrap().count(), 0); let valid = seed("Valid"); let runtime = registry - .create(valid.clone(), vec![], vec![]) + .create_unadmitted_fixture(valid.clone(), vec![], vec![]) .await .unwrap(); assert_eq!( @@ -751,6 +959,8 @@ mod tests { .unwrap(); for document_type in [ "campaign.v1", + "world_seed_admission.v1", + "world_seed_admission_receipt.v1", "session_zero_publication.v1", "campaign_membership.v1", "campaign_contract.v1", @@ -893,7 +1103,9 @@ mod tests { let campaign_root = root.join(flat.id.to_string()); std::fs::create_dir_all(&campaign_root).unwrap(); let store = CampaignStore::open(campaign_root.join("campaign.cc")).unwrap(); - store.create_campaign(&flat, &[], &[]).unwrap(); + store + .create_unadmitted_fixture_campaign(&flat, &[], &[]) + .unwrap(); drop(store); let registry = CampaignRegistry::new(&root).unwrap(); registry.load_existing().await.unwrap(); @@ -917,4 +1129,232 @@ mod tests { 1 ); } + + #[tokio::test] + async fn consumer_seed_admission_and_external_snapshot_share_one_authoritative_path() { + let dir = tempfile::tempdir().unwrap(); + let registry = CampaignRegistry::new(dir.path()).unwrap(); + let mut campaign = seed("Consumer world"); + campaign.institutions.insert( + "external-hold".into(), + crate::domain::InstitutionState { + id: "external-hold".into(), + name: "External Hold".into(), + resources: vec!["ore".into()], + goals: vec!["remain sovereign".into()], + posture: "watchful".into(), + }, + ); + campaign.player_actor_id = "external-hold".into(); + let seed = WorldSeed::from_campaign(&campaign).unwrap(); + let authority_key = "test-authority-key"; + let admission = WorldSeedAdmission { + schema: "ghostlight.world_seed_admission.v1".into(), + campaign_id: campaign.id, + producer_id: "fixture-consumer".into(), + producer_kind: WorldSeedProducerKind::Consumer, + seed_digest: seed.digest().unwrap(), + idempotency_key: "admit-once".into(), + external_subjects: vec![ExternalSubjectAuthority { + schema: "ghostlight.external_subject_authority.v1".into(), + id: "authority:external-hold".into(), + campaign_id: campaign.id, + subject_id: "external-hold".into(), + subject_kind: crate::domain::AgencySubjectKind::Institution, + owner_id: "fixture-consumer".into(), + authority_key_sha256: crate::consumer::authority_key_digest(authority_key), + last_source_revision: None, + last_payload_digest: None, + }], + }; + let request = WorldSeedAdmissionRequest { + schema: "ghostlight.world_seed_admission_request.v1".into(), + seed, + admission, + authority_key: authority_key.into(), + }; + let (runtime, receipt) = registry.admit_world_seed(request.clone()).await.unwrap(); + assert_eq!(receipt.admitted_subject_ids, vec!["external-hold"]); + assert!( + !runtime + .store + .load::("campaign.v1", &campaign.id.to_string()) + .unwrap() + .unwrap() + .1 + .agency_profiles["external-hold"] + .simulation_eligible + ); + let (_, repeated) = registry.admit_world_seed(request).await.unwrap(); + assert_eq!(repeated.seed_digest, receipt.seed_digest); + + let mut snapshot = crate::consumer::ExternalInstitutionSnapshot { + schema: "ghostlight.external_institution_snapshot.v1".into(), + campaign_id: campaign.id, + expected_world_revision: 0, + authority_id: "authority:external-hold".into(), + owner_id: "fixture-consumer".into(), + authority_key: authority_key.into(), + source_revision: 7, + idempotency_key: "snapshot-seven".into(), + payload_digest: String::new(), + projection: crate::domain::InstitutionState { + id: "external-hold".into(), + name: "External Hold".into(), + resources: vec!["ore".into(), "grain".into()], + goals: vec!["remain sovereign".into()], + posture: "mobilized".into(), + }, + }; + snapshot.payload_digest = crate::consumer::snapshot_payload_digest(&snapshot).unwrap(); + let mut denied = snapshot.clone(); + denied.authority_key = "wrong-key".into(); + assert!( + registry + .apply_external_institution_snapshot(denied) + .await + .is_err() + ); + assert_eq!( + runtime + .store + .load::("campaign.v1", &campaign.id.to_string()) + .unwrap() + .unwrap() + .1 + .revision, + 0 + ); + let snapshot_receipt = registry + .apply_external_institution_snapshot(snapshot.clone()) + .await + .unwrap(); + assert_eq!(snapshot_receipt.world_revision, 1); + let updated = runtime + .store + .load::("campaign.v1", &campaign.id.to_string()) + .unwrap() + .unwrap() + .1; + assert_eq!(updated.institutions["external-hold"].posture, "mobilized"); + assert!( + updated.agency_profiles["external-hold"].facets[&crate::domain::AgencyAxis::Authority] + .contains("mobilized") + ); + assert!( + updated.agency_profiles["external-hold"].facets + [&crate::domain::AgencyAxis::EconomyRole] + .contains("grain") + ); + assert_eq!( + registry + .apply_external_institution_snapshot(snapshot) + .await + .unwrap(), + snapshot_receipt + ); + let mut stale_snapshot = crate::consumer::ExternalInstitutionSnapshot { + schema: "ghostlight.external_institution_snapshot.v1".into(), + campaign_id: campaign.id, + expected_world_revision: 1, + authority_id: "authority:external-hold".into(), + owner_id: "fixture-consumer".into(), + authority_key: authority_key.into(), + source_revision: 6, + idempotency_key: "snapshot-six".into(), + payload_digest: String::new(), + projection: campaign.institutions["external-hold"].clone(), + }; + stale_snapshot.payload_digest = + crate::consumer::snapshot_payload_digest(&stale_snapshot).unwrap(); + assert!( + registry + .apply_external_institution_snapshot(stale_snapshot) + .await + .is_err() + ); + assert_eq!( + runtime + .store + .load::("campaign.v1", &campaign.id.to_string()) + .unwrap() + .unwrap() + .1 + .revision, + 1 + ); + let proposal = ExternalWorldProposal { + schema: "ghostlight.external_world_proposal.v1".into(), + id: "external-proposal:test".into(), + campaign_id: campaign.id, + world_revision: 1, + authority_id: "authority:external-hold".into(), + external_subject_id: "external-hold".into(), + source_subject_id: "foreign-court".into(), + intent: "Offer a treaty.".into(), + intended_effect: "Open negotiations.".into(), + action_digest: format!("sha256:{}", "a".repeat(64)), + public_channels: vec!["diplomatic".into()], + state_references: Vec::new(), + status: ExternalProposalStatus::Pending, + created_at: Utc::now(), + }; + runtime + .store + .insert( + "external_world_proposal.v1", + "ghostlight.external_world_proposal.v1", + &proposal.id, + &proposal, + ) + .unwrap(); + let proposals = registry + .list_external_proposals(ExternalProposalListRequest { + schema: "ghostlight.external_proposal_list_request.v1".into(), + campaign_id: campaign.id, + authority_id: "authority:external-hold".into(), + owner_id: "fixture-consumer".into(), + authority_key: authority_key.into(), + }) + .await + .unwrap(); + assert_eq!(proposals.proposals, vec![proposal.clone()]); + let acknowledgement = ExternalProposalAcknowledgement { + schema: "ghostlight.external_proposal_acknowledgement.v1".into(), + campaign_id: campaign.id, + authority_id: "authority:external-hold".into(), + owner_id: "fixture-consumer".into(), + authority_key: authority_key.into(), + proposal_id: proposal.id, + idempotency_key: "ack-treaty".into(), + status: ExternalProposalStatus::Rejected, + result_summary: "The hold declined.".into(), + acknowledged_at: Utc::now(), + }; + let acknowledgement_receipt = registry + .acknowledge_external_proposal(acknowledgement.clone()) + .await + .unwrap(); + assert_eq!( + registry + .acknowledge_external_proposal(acknowledgement) + .await + .unwrap(), + acknowledgement_receipt + ); + assert!( + registry + .list_external_proposals(ExternalProposalListRequest { + schema: "ghostlight.external_proposal_list_request.v1".into(), + campaign_id: campaign.id, + authority_id: "authority:external-hold".into(), + owner_id: "fixture-consumer".into(), + authority_key: authority_key.into(), + }) + .await + .unwrap() + .proposals + .is_empty() + ); + } } diff --git a/docs/architecture/ghostlight-world-consumer-api.md b/docs/architecture/ghostlight-world-consumer-api.md new file mode 100644 index 0000000..d14bf48 --- /dev/null +++ b/docs/architecture/ghostlight-world-consumer-api.md @@ -0,0 +1,109 @@ +# Ghostlight World Consumer API + +## Objective + +Let a consumer supply and observe one persistent Ghostlight world without +becoming part of Ghostlight's runtime. Session Zero compilation and external +world authoring are two producers of the same admitted seed. Delvehold is the +first demanding consumer; no Delvehold identifier, schema, or policy is core +authority. + +## Authority map + +- **Seed admission owner:** `CampaignRegistry` validates one `WorldSeed` and + commits it with one `WorldSeedAdmission` and receipt. Producer-specific + documents may join that transaction but cannot create another publication + path. +- **World owner:** `WorldKernel` owns every admitted campaign revision and all + simulation state. +- **External-subject owner:** `ExternalSubjectAuthority` binds one exact + consumer owner to one exact subject. The subject remains a visible target but + receives no Ghostlight Persona turn and cannot act through a strategic cell. +- **Consumer owner:** the consumer decides whether a Ghostlight proposal changes + its own domain. Its acknowledgement records admission or refusal but cannot + rewrite Ghostlight state. +- **Inputs:** a consumer-neutral seed, producer and payload digests, exact + authority descriptors, normalized external-institution snapshots, and + proposal acknowledgements. +- **Outputs:** seed-admission receipts, revisioned snapshot receipts, attributed + external proposals, and immutable proposal acknowledgements. +- **Derived state:** Session Zero publication documents, consumer bindings, + network messages, schema catalogs, and UI projections own no canonical world + state. +- **Forbidden writers:** seed producers, adapters, models, arenas, transport, + and acknowledgements cannot write a campaign row directly. +- **Shared paths:** compiler and consumer seeds lower to one registry/store + transaction. Strategic waves continue through the existing WorldKernel + command and atomic commit path. +- **Cut line:** `publish_session_zero` no longer owns campaign creation. It is a + producer-specific wrapper around generic seed admission. Ghostlight never + switches on `greathold` or a `delvehold.*` schema. + +## Typed flow + +```text +producer seed + -> WorldSeed + WorldSeedAdmission + -> CampaignRegistry validation + -> one empty-store CultCache transaction + -> WorldKernel runtime + +consumer-owned state + -> consumer adapter + -> ExternalInstitutionSnapshot + -> authority, digest, revision, and idempotency validation + -> WorldKernel atomic campaign commit + -> ExternalSnapshotReceipt + +strategic action directed at an external subject + -> WorldKernel strategic-wave validation + -> attributed ExternalWorldProposal persisted with the wave + -> consumer reads proposal and decides locally + -> ExternalProposalReceipt records accept, partial accept, or reject + -> any realized consumer change returns later as a fresh snapshot +``` + +## Transport + +The API uses typed CultNet operation requests over Ghostlight's existing RUDP +server. Seed admission, external snapshots, proposal reads, and proposal +acknowledgements use MessagePack payloads and typed receipts. The service is +loopback-only until CultMesh authority leases and secure remote admission are +implemented. HTTP and Eve remain player/product projections, not the world +consumer boundary. + +## Invariants + +- The public seed shape excludes runtime revision, transcript, pending work, + cover state, and other already-authoritative campaign fields. +- The seed digest binds the exact normalized seed. A campaign ID cannot be + republished from another digest. +- An external authority names one existing institution-shaped subject and one + owner. Its secret is persisted only as SHA-256. +- External subjects are active graph targets but never simulation-eligible. +- A snapshot replaces only the exact externally owned institution projection. + It cannot create subjects, routes, actors, Gestalts, relations, or private + knowledge. +- Source revisions increase monotonically. Exact idempotent replay returns the + original receipt; conflicting replay changes nothing. +- Outbound proposals remain attributed to an exact Ghostlight subject and exact + target. An arena never becomes the proposer. +- Proposal acknowledgement is not a Ghostlight world mutation. Realized effects + return through a later snapshot. +- Dungeon campaigns keep their player actor, membership, contract, and Session + Zero documents. Their adversarial play path does not depend on a consumer. + +## First acceptance + +1. Session Zero and a consumer-authored fixture persist the same generic seed + admission and receipt types. +2. A configured external institution never receives a strategic cell or + Persona action. +3. Wrong owner, wrong secret, stale source revision, digest conflict, and stale + world revision leave campaign state unchanged. +4. A valid snapshot advances the campaign once and returns an idempotent typed + receipt. +5. A strategic action aimed at the external institution emits one attributed + proposal in the same atomic wave commit. +6. Consumer acknowledgement cannot mutate the campaign and can be replayed + idempotently. diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 8d33470..f1d250b 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -424,7 +424,13 @@ approved capability. ## Next action -The immediate gate is a Delvehold external-world architecture and scale pass. +The generic world-consumer boundary is implemented. Session Zero and external +producers share one admitted `WorldSeed` transaction; externally authoritative +institutions 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 immediate gate is now the scale and emergence pass. Delvehold is a consumer of Ghostlight's generic authored-world API, not a Ghostlight-owned organ or special runtime. Ghostlight owns the world beyond the Greathold as a persistent multiresolution political simulation, while Delvehold @@ -435,24 +441,20 @@ Do not begin by multiplying prompts or raising a constant; map resolution ownership, emergence triggers, causal propagation, folding, and provider-call amortization first. -1. Map Delvehold's authored realm, institution, population, and person hierarchy - and identify the missing lore required for a whole-world seed. -2. Specify a WorldKernel-owned offscreen individuation path that lets causal +1. Specify a WorldKernel-owned offscreen individuation path that lets causal political pressure produce durable named figures without granting entity creation authority to a cell, arena, or model. -3. Measure the existing parallel wave dispatcher at the current 128-cell ceiling +2. Measure the existing parallel wave dispatcher at the current 128-cell ceiling and design the hundreds-cell budget around bounded provider concurrency, outcome resolution, atomic commit, fairness, and cost. -4. Define and implement generic authored-seed, externally controlled subject, - inbound effect, outbound intent/news, and receipt operations in Ghostlight's - public API. Keep Delvehold projection and economy translation in a - Delvehold-owned adapter. -5. Prove one Greathold effect crosses that public API, changes two foreign +3. Have the game-side adapter lower its authored hierarchy into the published + generic schemas; keep projection and economy translation consumer-owned. +4. Prove one consumer-owned effect crosses that public API, changes two foreign political layers, and returns attributed news or intent without mutating Delvehold-owned truth. -6. Leave the unpublished Mars seed and Kalsa refuge expansion unapproved unless +5. Leave the unpublished Mars seed and Kalsa refuge expansion unapproved unless the operator explicitly admits either; retain Kalsa as regression evidence. -7. Keep `gamecult-ops` synchronized with every executable deployment and model +6. 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 d2926a8..f1fd360 100644 --- a/notes/ghostlight-current-system-map.md +++ b/notes/ghostlight-current-system-map.md @@ -98,22 +98,21 @@ own their canonical Persona state and consequence commits. ## DELVE/HOLD consumer profile -DELVE/HOLD is admitted as a consumer of Ghostlight's generic API for one -canonical world outside the Greathold. Its target contract supplies an authored +Delvehold is the first proving consumer for Ghostlight's generic API for one +canonical world beyond a consumer-owned boundary. Its target contract supplies an authored ontology and fixed seed rather than invoking Session Zero world generation. That bypass ends at generation: publication and every later transition must still enter `WorldKernel` through typed validation and atomic CultCache commit. Delvehold owns players, workshops, dungeons, civic state, contracts, and its quantitative economy. Ghostlight owns external actors, institutions, Gestalts, -relationships, knowledge, pressures, and strategic decisions. The admitted -consumer configuration contains one externally owned boundary subject, -`greathold`, projecting only committed macro effects into Ghostlight and -receiving no Persona or strategic turn. Ghostlight currently lacks the generic -subject-authority contract and shared consumer-seed admission primitive; -ordinary institution selection is not enforcement. External consequences -return as generic attributed proposals for Delvehold admission, not direct -mutations. +relationships, knowledge, pressures, and strategic decisions. Consumer +configurations may bind institution subjects through `ExternalSubjectAuthority`. +Those institutions project committed revisioned snapshots into Ghostlight, +receive no Persona or strategic turn, and remain targets of foreign action. +Such actions persist as attributed proposals in the same strategic-wave commit +and return for consumer admission, not direct mutation. Compiler and consumer +producers share one `WorldSeed` admission transaction. The Delvehold adapter remains Delvehold-owned. It lowers committed Greathold projections and realized effects into generic Ghostlight operations, then raises diff --git a/state/evidence.jsonl b/state/evidence.jsonl index e41aee3..5d4e8c8 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -135,4 +135,5 @@ {"branch": "codex/ghostlight-dungeon-mvp", "note": "Idunn deployed exact Ghostlight bd4758894c1f81df13a048fa82ca4511fe6d4245 after 312 locked Linux tests; daemon and native-client hashes are 0fb4e27c56a1d331d77335ce959ed5937040636da081e4c016602bc073a8c3de and 13ddda694161be9a81b914421b54a3405027f6c389f34080dee95f1acbf1b07d. Nightwing/VoidBot retrieval was live. Session Zero e7f2f947-25fa-4e1b-82e3-4a3e07dc4497 reached revision 55 and retained approval preview sha256:01f07d0f5bc453151743dab77821d64a28d0505e82bd905aa335d45525e51d83: four strongly connected locations, no First Exodus/Blackbox/Kesh/Maela borrowing, nine unique active receipts, valid world and agency stages, and an unsupported Pan-Solar doctrine isolated as an evidence gap. No campaign was approved or published.", "status": "ok", "ts": "2026-08-25T03:34:25+00:00", "type": "live_acceptance"} {"note": "DELVE/HOLD boundary: live Ghostlight WorldKernel, multiresolution agency, typed transitions, persistence, and receipts are reusable, but current InstitutionState and strategic resource handles do not implement HOLD quantities, prices, recipes, capacity, inventories, orders, contracts, or conservation. Delvehold therefore retains quantitative economy authority; a forced ontology may bypass world generation but never WorldKernel validation. Owner witnesses: crates/ghostlight-dungeon/src/domain.rs and F:\\Projects\\Delvehold\\Delvehold\\Game Design\\Shared World\\World State Model.md.", "status": "ok", "ts": "2026-08-26T00:50:11+00:00", "type": "architecture"} {"note": "Operator redirected Ghostlight's near-term objective from Kalsa adversarial play to Delvehold's full external-world simulation. Delvehold owns the Greathold, players, dungeons, civic state, and quantitative economy; Ghostlight owns foreign regions, institutions, populations, people, relationships, knowledge, politics, events, and news. The target requires a cell budget in the hundreds, durable offscreen named-person emergence, nested political hierarchies, and causal response to committed Greathold effects. Current runtime caps cells at 128, dispatches cell pipelines concurrently under independently bounded provider parallelism up to 32, and only admits new-person individuation from immediate player speech, so scale proof and offscreen emergence are explicit architecture gaps. Kalsa remains regression evidence.", "status": "ok", "ts": "2026-08-26T15:51:04+00:00", "type": "research"} -{"ts": "2026-08-26T15:55:05+00:00", "type": "architecture", "status": "ok", "note": "Delvehold is a proving consumer of Ghostlight's generic world-simulation API, not a Ghostlight integration organ. Ghostlight may add only generic capabilities: one seed admission primitive shared by compiler and consumer producers, generic externally owned subject authority, consumer-supplied effect schemas, and typed proposals and receipts. The greathold ID, all delvehold.* bindings, and detailed projection/economy translation remain Delvehold-owned. Cells and WorldKernel never switch on consumer-specific names."} +{"note": "Delvehold is a proving consumer of Ghostlight's generic world-simulation API, not a Ghostlight integration organ. Ghostlight may add only generic capabilities: one seed admission primitive shared by compiler and consumer producers, generic externally owned subject authority, consumer-supplied effect schemas, and typed proposals and receipts. The greathold ID, all delvehold.* bindings, and detailed projection/economy translation remain Delvehold-owned. Cells and WorldKernel never switch on consumer-specific names.", "status": "ok", "ts": "2026-08-26T15:55:05+00:00", "type": "architecture"} +{"ts": "2026-08-26T16:46:55+00:00", "type": "architecture", "status": "ok", "note": "Supersedes the 2026-08-26T15:51 research note only where it called Delvehold the redirected primary play target: Delvehold is the first proving consumer of the generic world API, while adversarial single-player Dungeon play remains an active regression and context-discovery path. Implemented one compiler/consumer WorldSeed admission transaction, institution-scoped ExternalSubjectAuthority, WorldKernel-owned revisioned snapshots, atomic strategic-wave proposals, acknowledgement receipts, and typed loopback CultNet RUDP operations. Consumer-specific IDs and quantitative economy semantics remain outside Ghostlight."} diff --git a/state/ghostlight-state.cultcache.jsonl b/state/ghostlight-state.cultcache.jsonl index fdd1b0c..e433621 100644 --- a/state/ghostlight-state.cultcache.jsonl +++ b/state/ghostlight-state.cultcache.jsonl @@ -137,3 +137,4 @@ {"key": "2026-08-26T005011Z0000-0135-2d1c23496415", "payload": "eyJub3RlIjogIkRFTFZFL0hPTEQgYm91bmRhcnk6IGxpdmUgR2hvc3RsaWdodCBXb3JsZEtlcm5lbCwgbXVsdGlyZXNvbHV0aW9uIGFnZW5jeSwgdHlwZWQgdHJhbnNpdGlvbnMsIHBlcnNpc3RlbmNlLCBhbmQgcmVjZWlwdHMgYXJlIHJldXNhYmxlLCBidXQgY3VycmVudCBJbnN0aXR1dGlvblN0YXRlIGFuZCBzdHJhdGVnaWMgcmVzb3VyY2UgaGFuZGxlcyBkbyBub3QgaW1wbGVtZW50IEhPTEQgcXVhbnRpdGllcywgcHJpY2VzLCByZWNpcGVzLCBjYXBhY2l0eSwgaW52ZW50b3JpZXMsIG9yZGVycywgY29udHJhY3RzLCBvciBjb25zZXJ2YXRpb24uIERlbHZlaG9sZCB0aGVyZWZvcmUgcmV0YWlucyBxdWFudGl0YXRpdmUgZWNvbm9teSBhdXRob3JpdHk7IGEgZm9yY2VkIG9udG9sb2d5IG1heSBieXBhc3Mgd29ybGQgZ2VuZXJhdGlvbiBidXQgbmV2ZXIgV29ybGRLZXJuZWwgdmFsaWRhdGlvbi4gT3duZXIgd2l0bmVzc2VzOiBjcmF0ZXMvZ2hvc3RsaWdodC1kdW5nZW9uL3NyYy9kb21haW4ucnMgYW5kIEY6XFxQcm9qZWN0c1xcRGVsdmVob2xkXFxEZWx2ZWhvbGRcXEdhbWUgRGVzaWduXFxTaGFyZWQgV29ybGRcXFdvcmxkIFN0YXRlIE1vZGVsLm1kLiIsICJzdGF0dXMiOiAib2siLCAidHMiOiAiMjAyNi0wOC0yNlQwMDo1MDoxMSswMDowMCIsICJ0eXBlIjogImFyY2hpdGVjdHVyZSJ9", "stored_at": "2026-08-26T00:50:11.582781+00:00", "type": "ghostlight.evidence_record.v0"} {"key": "2026-08-26T155104Z0000-0136-f1e48d3fe47f", "payload": "eyJub3RlIjogIk9wZXJhdG9yIHJlZGlyZWN0ZWQgR2hvc3RsaWdodCdzIG5lYXItdGVybSBvYmplY3RpdmUgZnJvbSBLYWxzYSBhZHZlcnNhcmlhbCBwbGF5IHRvIERlbHZlaG9sZCdzIGZ1bGwgZXh0ZXJuYWwtd29ybGQgc2ltdWxhdGlvbi4gRGVsdmVob2xkIG93bnMgdGhlIEdyZWF0aG9sZCwgcGxheWVycywgZHVuZ2VvbnMsIGNpdmljIHN0YXRlLCBhbmQgcXVhbnRpdGF0aXZlIGVjb25vbXk7IEdob3N0bGlnaHQgb3ducyBmb3JlaWduIHJlZ2lvbnMsIGluc3RpdHV0aW9ucywgcG9wdWxhdGlvbnMsIHBlb3BsZSwgcmVsYXRpb25zaGlwcywga25vd2xlZGdlLCBwb2xpdGljcywgZXZlbnRzLCBhbmQgbmV3cy4gVGhlIHRhcmdldCByZXF1aXJlcyBhIGNlbGwgYnVkZ2V0IGluIHRoZSBodW5kcmVkcywgZHVyYWJsZSBvZmZzY3JlZW4gbmFtZWQtcGVyc29uIGVtZXJnZW5jZSwgbmVzdGVkIHBvbGl0aWNhbCBoaWVyYXJjaGllcywgYW5kIGNhdXNhbCByZXNwb25zZSB0byBjb21taXR0ZWQgR3JlYXRob2xkIGVmZmVjdHMuIEN1cnJlbnQgcnVudGltZSBjYXBzIGNlbGxzIGF0IDEyOCwgZGlzcGF0Y2hlcyBjZWxsIHBpcGVsaW5lcyBjb25jdXJyZW50bHkgdW5kZXIgaW5kZXBlbmRlbnRseSBib3VuZGVkIHByb3ZpZGVyIHBhcmFsbGVsaXNtIHVwIHRvIDMyLCBhbmQgb25seSBhZG1pdHMgbmV3LXBlcnNvbiBpbmRpdmlkdWF0aW9uIGZyb20gaW1tZWRpYXRlIHBsYXllciBzcGVlY2gsIHNvIHNjYWxlIHByb29mIGFuZCBvZmZzY3JlZW4gZW1lcmdlbmNlIGFyZSBleHBsaWNpdCBhcmNoaXRlY3R1cmUgZ2Fwcy4gS2Fsc2EgcmVtYWlucyByZWdyZXNzaW9uIGV2aWRlbmNlLiIsICJzdGF0dXMiOiAib2siLCAidHMiOiAiMjAyNi0wOC0yNlQxNTo1MTowNCswMDowMCIsICJ0eXBlIjogInJlc2VhcmNoIn0=", "stored_at": "2026-08-26T15:51:04.158942+00:00", "type": "ghostlight.evidence_record.v0"} {"key": "2026-08-26T155505Z0000-0137-59ce136e84c9", "payload": "eyJub3RlIjogIkRlbHZlaG9sZCBpcyBhIHByb3ZpbmcgY29uc3VtZXIgb2YgR2hvc3RsaWdodCdzIGdlbmVyaWMgd29ybGQtc2ltdWxhdGlvbiBBUEksIG5vdCBhIEdob3N0bGlnaHQgaW50ZWdyYXRpb24gb3JnYW4uIEdob3N0bGlnaHQgbWF5IGFkZCBvbmx5IGdlbmVyaWMgY2FwYWJpbGl0aWVzOiBvbmUgc2VlZCBhZG1pc3Npb24gcHJpbWl0aXZlIHNoYXJlZCBieSBjb21waWxlciBhbmQgY29uc3VtZXIgcHJvZHVjZXJzLCBnZW5lcmljIGV4dGVybmFsbHkgb3duZWQgc3ViamVjdCBhdXRob3JpdHksIGNvbnN1bWVyLXN1cHBsaWVkIGVmZmVjdCBzY2hlbWFzLCBhbmQgdHlwZWQgcHJvcG9zYWxzIGFuZCByZWNlaXB0cy4gVGhlIGdyZWF0aG9sZCBJRCwgYWxsIGRlbHZlaG9sZC4qIGJpbmRpbmdzLCBhbmQgZGV0YWlsZWQgcHJvamVjdGlvbi9lY29ub215IHRyYW5zbGF0aW9uIHJlbWFpbiBEZWx2ZWhvbGQtb3duZWQuIENlbGxzIGFuZCBXb3JsZEtlcm5lbCBuZXZlciBzd2l0Y2ggb24gY29uc3VtZXItc3BlY2lmaWMgbmFtZXMuIiwgInN0YXR1cyI6ICJvayIsICJ0cyI6ICIyMDI2LTA4LTI2VDE1OjU1OjA1KzAwOjAwIiwgInR5cGUiOiAiYXJjaGl0ZWN0dXJlIn0=", "stored_at": "2026-08-26T15:55:05.625298+00:00", "type": "ghostlight.evidence_record.v0"} +{"key": "2026-08-26T164655Z0000-0138-849e5de32fc5", "payload": "eyJub3RlIjogIlN1cGVyc2VkZXMgdGhlIDIwMjYtMDgtMjZUMTU6NTEgcmVzZWFyY2ggbm90ZSBvbmx5IHdoZXJlIGl0IGNhbGxlZCBEZWx2ZWhvbGQgdGhlIHJlZGlyZWN0ZWQgcHJpbWFyeSBwbGF5IHRhcmdldDogRGVsdmVob2xkIGlzIHRoZSBmaXJzdCBwcm92aW5nIGNvbnN1bWVyIG9mIHRoZSBnZW5lcmljIHdvcmxkIEFQSSwgd2hpbGUgYWR2ZXJzYXJpYWwgc2luZ2xlLXBsYXllciBEdW5nZW9uIHBsYXkgcmVtYWlucyBhbiBhY3RpdmUgcmVncmVzc2lvbiBhbmQgY29udGV4dC1kaXNjb3ZlcnkgcGF0aC4gSW1wbGVtZW50ZWQgb25lIGNvbXBpbGVyL2NvbnN1bWVyIFdvcmxkU2VlZCBhZG1pc3Npb24gdHJhbnNhY3Rpb24sIGluc3RpdHV0aW9uLXNjb3BlZCBFeHRlcm5hbFN1YmplY3RBdXRob3JpdHksIFdvcmxkS2VybmVsLW93bmVkIHJldmlzaW9uZWQgc25hcHNob3RzLCBhdG9taWMgc3RyYXRlZ2ljLXdhdmUgcHJvcG9zYWxzLCBhY2tub3dsZWRnZW1lbnQgcmVjZWlwdHMsIGFuZCB0eXBlZCBsb29wYmFjayBDdWx0TmV0IFJVRFAgb3BlcmF0aW9ucy4gQ29uc3VtZXItc3BlY2lmaWMgSURzIGFuZCBxdWFudGl0YXRpdmUgZWNvbm9teSBzZW1hbnRpY3MgcmVtYWluIG91dHNpZGUgR2hvc3RsaWdodC4iLCAic3RhdHVzIjogIm9rIiwgInRzIjogIjIwMjYtMDgtMjZUMTY6NDY6NTUrMDA6MDAiLCAidHlwZSI6ICJhcmNoaXRlY3R1cmUifQ==", "stored_at": "2026-08-26T16:46:55.684556+00:00", "type": "ghostlight.evidence_record.v0"} diff --git a/state/map.yaml b/state/map.yaml index dd9eba6..a383429 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -193,7 +193,7 @@ live_architecture: - Institution, faction, and consumer decision models active_subgoals: - - Define and admit the generic consumer-authored world contract: one seed publication primitive shared with compiler output, generic externally owned boundary-subject descriptors, consumer-supplied effect schemas, and typed CultMesh proposals and receipts. Prove it with Delvehold's authored world and configured `greathold` subject without hard-coding either into Ghostlight. + - Prove the admitted generic world-consumer contract with a game-side fixture: shared compiler/consumer WorldSeed admission, externally authoritative institution snapshots, and attributed proposal acknowledgement over typed CultNet, without consumer-specific IDs or schemas in Ghostlight. - Specify strategic/offscreen named-person individuation, plotting, durable identity, and folding under WorldKernel authority; remote causal pressure must be able to make a person matter without granting a cell, arena, or model entity-creation authority. - Prove the hundreds-class wave target using the existing parallel cell dispatcher and separately bounded provider concurrency. Measure the current 128-cell ceiling first; widen it only if the authored outside-world cover requires more, and only with an explicit scheduling, atomicity, and cost model. - 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. @@ -324,5 +324,5 @@ data_flow: 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: Map the generic Ghostlight API gaps exposed by Delvehold before implementation. Define the admitted seed contract shared by compiler and consumer producers; generic externally owned boundary-subject authority; realm-to-institution-to-population-to-person resolution; strategic and offscreen individuation and folding; and a separately scheduled hundreds-class cell budget. Then prove the API with a Delvehold consumer fixture: one admitted consumer event changes at least two simulated political layers, creates or advances an independently acting named figure, and returns an attributed generic proposal and receipt without mutating consumer-owned truth. Delvehold-specific IDs and document lowering remain in Delvehold. + next_action: Keep Dungeon adversarial single-player play as regression pressure while the game-side adapter prepares its first generic WorldSeed. In Ghostlight, specify and prove WorldKernel-owned offscreen named-person emergence and benchmark the parallel dispatcher at the current 128-cell ceiling before widening toward hundreds. Then run one consumer fixture through seed admission, authoritative institution snapshot, two simulated political layers, durable named-person action, and attributed proposal acknowledgement without mutating consumer-owned truth. 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.