Compile sparse worlds into living politics

This commit is contained in:
Meta Vens 2026-08-26 23:03:43 +02:00
commit a266933ed9
30 changed files with 3422 additions and 261 deletions

View file

@ -114,6 +114,17 @@ pub struct AppSessionOwner {
}
impl AppSessionOwner {
#[cfg(test)]
pub fn persisted_bytes_contain(&self, needle: &str) -> anyhow::Result<bool> {
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<Path>,
wrapping_key_path: impl AsRef<Path>,

View file

@ -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,

View file

@ -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,

View file

@ -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,

View file

@ -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,

View file

@ -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()

File diff suppressed because it is too large Load diff

View file

@ -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<Utc>,
}
#[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()))
}

View file

@ -19,6 +19,8 @@ pub struct Campaign {
pub institutions: BTreeMap<String, InstitutionState>,
pub clocks: BTreeMap<String, WorldClock>,
pub facts: BTreeMap<String, WorldFact>,
#[serde(default)]
pub civic_systems: BTreeMap<String, CivicSystemManifest>,
pub transcript: Vec<NarrativeTurn>,
pub last_player_activity: DateTime<Utc>,
pub pending_ticks: u8,
@ -1089,6 +1091,14 @@ pub enum WorldCommand {
#[serde(default)]
model_stage_receipts: Vec<crate::model::ModelStageReceipt>,
},
ElaborateLocality {
expected_revision: u64,
elaboration: LocalityElaboration,
evidence_receipts: Vec<VaultEvidenceReceipt>,
canon_candidates: Vec<CanonCandidate>,
#[serde(default)]
model_stage_receipts: Vec<crate::model::ModelStageReceipt>,
},
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<AgencyRelation>,
/// 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<InstitutionState>,
/// Exact agency inputs for `institutions`.
#[serde(default)]
pub institution_profiles: Vec<AgencyProfile>,
/// Political and administrative relations among newly admitted local
/// institutions and populations. Migration remains in its separate lane.
#[serde(default)]
pub local_relations: Vec<AgencyRelation>,
/// 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<CivicSystemManifest>,
}
#[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<String>,
pub resident_population_ids: BTreeSet<String>,
pub public_authority_fact_ids: BTreeSet<String>,
pub public_selection_fact_ids: BTreeSet<String>,
pub public_resource_fact_ids: BTreeSet<String>,
pub public_redress_fact_ids: BTreeSet<String>,
pub political_relation_ids: BTreeSet<String>,
/// 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<VaultEvidenceReceipt>,
#[serde(default)]
pub branch_assumptions: Vec<String>,
pub gaps: Vec<String>,
pub canon_candidates: Vec<CanonCandidate>,
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 {

View file

@ -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::<Result<BTreeMap<_, _>, _>>()
})
.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::<BTreeSet<_>>();
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::<BTreeSet<_>>();
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::<Vec<_>>();
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>("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>("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>("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::<StrategicGestaltIndividuation>("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]

View file

@ -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::<BTreeSet<_>>();
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<ComponentWorldState> {
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<SubjectRef> {
}
}
fn expansion_agency_subject(
campaign: &Campaign,
expansion: &crate::domain::RegionExpansion,
id: &str,
) -> Result<SubjectRef> {
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,

View file

@ -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;

View file

@ -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<Arc<WorldCompiler>>,
assessor: Option<Arc<ActionAssessor>>,
model: Option<Arc<dyn ModelPort>>,
expansion_previews: Arc<Mutex<BTreeMap<String, OwnedPreview<RegionExpansionPreview>>>>,
expansion_previews: Arc<Mutex<BTreeMap<String, OwnedPreview<DestinationCompilationPreview>>>>,
fission_previews: Arc<Mutex<BTreeMap<String, OwnedFissionPreview>>>,
live_turns: Arc<AtomicUsize>,
live_turn_started: Arc<Notify>,
@ -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()
);

View file

@ -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::<SchemaCatalogRecord>("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);

View file

@ -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"),
};
}

View file

@ -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<Utc>,
pub source_world_revision: u64,
pub articles: Vec<WorldNewspaperArticle>,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct WorldNewspaperArticle {
pub id: String,
pub section: String,
pub headline: String,
pub dateline: Option<String>,
pub body: String,
pub channel: String,
pub reliability: String,
pub event_ids: Vec<String>,
}
pub fn compose_world_newspaper(
campaign: &Campaign,
title: impl Into<String>,
max_articles: usize,
) -> Result<WorldNewspaperIssue> {
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::<BTreeMap<_, _>>();
let mut news = campaign.news.iter().collect::<Vec<_>>();
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::<Result<Vec<_>>>()?;
let primary = source_events[0];
let dateline = event_dateline(campaign, primary);
let body = source_events
.iter()
.map(|event| event.summary.trim())
.collect::<Vec<_>>()
.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::<Vec<_>>(),
))?;
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<String> {
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"));
}
}

View file

@ -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,

View file

@ -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<CultCacheEnvelope>,
replacements: &mut Vec<CultCacheEnvelope>,
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,

View file

@ -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<crate::newspaper::WorldNewspaperIssue> {
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::<ExternalSubjectAuthority>(
"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>("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>("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(),

View file

@ -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,

View file

@ -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

View file

@ -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<String>,
travel_minutes: Option<i64>,
},
SetCivicSystem {
jurisdiction: SubjectRef,
system: CivicSystemManifest,
},
AdmitEntity {
subject: SubjectRef,
initial_components: BTreeSet<WorldComponentKind>,
@ -838,6 +844,8 @@ pub struct ComponentWorldState {
#[serde(default)]
pub propositions: BTreeMap<SubjectRef, PropositionComponentState>,
pub topology: BTreeMap<String, TopologyComponentState>,
#[serde(default)]
pub civic_systems: BTreeMap<SubjectRef, CivicSystemManifest>,
}
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,

View file

@ -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,
}
}

View file

@ -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. |

View file

@ -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,

View file

@ -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

View file

@ -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

View file

@ -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"}

View file

@ -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"}

View file

@ -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.