From fbbaf453b8c0233d8988c6beca6691c932c3ba5f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 31 Aug 2026 20:10:26 +0200 Subject: [PATCH] Add resumable world complexity elaboration --- .../src/bin/ghostlight-strategic-smoke.rs | 711 +++++++++++- crates/ghostlight-dungeon/src/elaboration.rs | 1027 +++++++++++++++++ crates/ghostlight-dungeon/src/kernel.rs | 35 +- crates/ghostlight-dungeon/src/resolution.rs | 136 ++- .../ghostlight-multiresolution-agency.md | 18 +- .../Agents and model stages.md | 10 + docs/public-architecture/Runtime pipelines.md | 23 +- notes/fresh-workspace-handoff.md | 24 +- notes/ghostlight-current-system-map.md | 115 +- state/map.yaml | 4 +- 10 files changed, 1999 insertions(+), 104 deletions(-) diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs index 3016a83..c10fc5d 100644 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs @@ -453,6 +453,76 @@ struct TitledCommitCheckpoint { legacy_inferred: bool, } +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(deny_unknown_fields)] +struct ComplexityPreviewInvocation { + dispatch: ghostlight_dungeon::elaboration::ElaborationDispatch, + parent_binding: String, + proposal: ghostlight_dungeon::elaboration::WorldComplexityProposal, + model_receipt_hashes: Vec, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(deny_unknown_fields)] +struct ComplexityRoundPreviewCheckpoint { + schema: String, + round: u32, + demand: ghostlight_dungeon::elaboration::WorldElaborationDemand, + frozen_world_revision: u64, + wave: ghostlight_dungeon::elaboration::ElaborationWaveBinding, + schedule: ghostlight_dungeon::elaboration::ElaborationScheduleReceipt, + invocations: Vec, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(deny_unknown_fields)] +struct ComplexityFailedInvocation { + dispatch: Option, + diagnostic: String, + model_receipt_hashes: Vec, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(deny_unknown_fields)] +struct ComplexityRoundFailureCheckpoint { + schema: String, + round: u32, + demand: ghostlight_dungeon::elaboration::WorldElaborationDemand, + parent_gestalt_ids: Vec, + wave: Option, + schedule: Option, + completed_invocations: Vec, + invocation_failures: Vec, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(deny_unknown_fields)] +struct ComplexityMutationCheckpoint { + schema: String, + round: u32, + dispatch: ghostlight_dungeon::elaboration::ElaborationDispatch, + parent_gestalt_id: String, + mutation_kind: String, + affected_subject_ids: Vec, + model_receipt_hashes: Vec, + commit_receipt: ghostlight_dungeon::domain::WorldCommitReceipt, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(deny_unknown_fields)] +struct ComplexityRoundCheckpoint { + schema: String, + round: u32, + demand_before: ghostlight_dungeon::elaboration::WorldElaborationDemand, + actionable_subjects_after: u32, + schedule: ghostlight_dungeon::elaboration::ElaborationScheduleReceipt, + mutation_checkpoints: Vec, + session_checkpoints: std::collections::BTreeMap< + ghostlight_dungeon::elaboration::ElaboratorTitle, + ghostlight_dungeon::elaboration::ElaboratorSessionCheckpoint, + >, +} + fn read_checkpoint(path: &std::path::Path) -> anyhow::Result { let bytes = std::fs::read(path) .map_err(|error| anyhow::anyhow!("cannot read checkpoint {}: {error}", path.display()))?; @@ -694,6 +764,88 @@ fn rehydrate_titled_failure( }) } +fn complexity_failure_checkpoint_paths( + root: &std::path::Path, + round: u32, +) -> anyhow::Result> { + let original = root.join(format!("complexity-round-{round:03}-terminal-failure.json")); + let prefix = format!("complexity-round-{round:03}-resume-"); + let mut paths = original + .is_file() + .then_some(original) + .into_iter() + .collect::>(); + let mut resumed = std::fs::read_dir(root)? + .filter_map(|entry| entry.ok()) + .filter_map(|entry| { + let name = entry.file_name(); + let generation = name + .to_str()? + .strip_prefix(&prefix)? + .strip_suffix("-terminal-failure.json")? + .parse::() + .ok()?; + Some((generation, entry.path())) + }) + .collect::>(); + resumed.sort_by_key(|(generation, _)| *generation); + paths.extend(resumed.into_iter().map(|(_, path)| path)); + Ok(paths) +} + +fn rehydrate_complexity_failure( + checkpoint: ComplexityRoundFailureCheckpoint, + store: &ghostlight_dungeon::persistence::CampaignStore, +) -> anyhow::Result< + ghostlight_dungeon::elaboration::ElaborationWaveFailure< + ghostlight_dungeon::elaboration::WorldComplexityProposal, + >, +> { + if checkpoint.schema != "ghostlight.complexity_round_failure.v1" { + anyhow::bail!("complexity failure checkpoint schema is unsupported") + } + let wave = checkpoint.wave.clone(); + let completed_invocations = checkpoint + .completed_invocations + .into_iter() + .map(|invocation| { + Ok(ghostlight_dungeon::elaboration::ElaborationInvocation { + wave: wave + .clone() + .ok_or_else(|| anyhow::anyhow!("complexity checkpoint has no wave"))?, + dispatch: invocation.dispatch, + proposal: invocation.proposal, + model_stage_receipts: load_checkpoint_receipts( + store, + &invocation.model_receipt_hashes, + )?, + }) + }) + .collect::>>()?; + let invocation_failures = checkpoint + .invocation_failures + .into_iter() + .map(|failure| { + Ok( + ghostlight_dungeon::elaboration::ElaborationInvocationFailure { + dispatch: failure.dispatch, + diagnostic: failure.diagnostic, + model_stage_receipts: load_checkpoint_receipts( + store, + &failure.model_receipt_hashes, + )?, + }, + ) + }) + .collect::>>()?; + Ok(ghostlight_dungeon::elaboration::ElaborationWaveFailure { + wave, + schedule: checkpoint.schedule, + completed_invocations, + invocation_failures, + }) +} + fn civic_manifest_preserves( current: &ghostlight_dungeon::domain::CivicSystemManifest, checkpoint: &ghostlight_dungeon::domain::CivicSystemManifest, @@ -870,9 +1022,13 @@ async fn main() -> anyhow::Result<()> { compiler::DestinationCompilationFailure, domain::{TickSource, WorldCommand}, elaboration::{ - ElaborationScheduler, ElaboratorTitle, ModelWorldElaborationWorker, - admit_world_elaboration_wave, dispatch_elaboration_wave, finalize_world_elaboration, - resume_elaboration_wave, world_elaboration_wave_binding, + ElaborationScheduler, ElaboratorSessionCheckpoint, ElaboratorSessionJournalEntry, + ElaboratorTitle, ModelWorldComplexityWorker, ModelWorldElaborationWorker, + WorldComplexityProposal, WorldScaleIntent, admit_world_elaboration_wave, + canonical_actionable_subject_count, compact_elaborator_session, + derive_world_elaboration_demand, dispatch_elaboration_wave, finalize_world_elaboration, + rebase_world_complexity_proposal, resume_elaboration_wave, + world_complexity_parent_binding, world_elaboration_wave_binding, }, kernel::{CommandResult, WorldKernel}, model_runtime::ModelRuntimeSelection, @@ -883,7 +1039,12 @@ async fn main() -> anyhow::Result<()> { }, turn::SnapshotPermit, }; - use std::{path::PathBuf, sync::Arc, time::Instant}; + use std::{ + collections::{BTreeMap, BTreeSet}, + path::PathBuf, + sync::Arc, + time::Instant, + }; let runtime_root = std::env::var_os("GHOSTLIGHT_DUNGEON_ROOT") .map(PathBuf::from) @@ -1944,6 +2105,456 @@ async fn main() -> anyhow::Result<()> { serde_json::Value::Array(elaboration_reports), ); } + let target_cover_basis_points = + bounded_environment_usize("GHOSTLIGHT_WORLD_TARGET_COVER_BASIS_POINTS", 0, 0, 10_000)? + as u16; + let mut complexity_reports = Vec::new(); + if target_cover_basis_points > 0 { + if initial_location_ids.is_empty() { + anyhow::bail!("world complexity scaling requires admitted elaboration jurisdictions") + } + let complexity_parallelism = + bounded_environment_usize("GHOSTLIGHT_WORLD_COMPLEXITY_PARALLELISM", 8, 1, 32)?; + let maximum_complexity_rounds = + bounded_environment_usize("GHOSTLIGHT_WORLD_COMPLEXITY_MAX_ROUNDS", 32, 1, 128)?; + let scale_intent = WorldScaleIntent { + schema: "ghostlight.world_scale_intent.v1".into(), + target_active_cover_basis_points: target_cover_basis_points, + }; + let realm_weights = initial_location_ids + .iter() + .cloned() + .map(|location_id| (location_id, 1_u32)) + .collect::>(); + let complexity_profile = strategic_world_elaboration_profile(); + let eligible_titles = ElaboratorTitle::ALL.into_iter().collect::>(); + let mut complexity_scheduler = ElaborationScheduler::new(&complexity_profile)?; + let mut session_checkpoints = + BTreeMap::::new(); + let session_location_id = initial_location_ids[0].clone(); + let mut completed_complexity_rounds = 0_u32; + if resume { + for round in 1..=maximum_complexity_rounds as u32 { + let path = root.join(format!("complexity-round-{round:03}-checkpoint.json")); + if !path.is_file() { + break; + } + let checkpoint: ComplexityRoundCheckpoint = read_checkpoint(&path)?; + if checkpoint.schema != "ghostlight.complexity_round_checkpoint.v1" + || checkpoint.round != round + || checkpoint.actionable_subjects_after + > canonical_actionable_subject_count(&campaign) + { + anyhow::bail!("complexity round checkpoint is stale or malformed") + } + complexity_scheduler = ElaborationScheduler::from_state( + &complexity_profile, + checkpoint.schedule.final_state.clone(), + )?; + for (title, session) in &checkpoint.session_checkpoints { + session.validate_for(&campaign, &session_location_id, *title)?; + } + session_checkpoints = checkpoint.session_checkpoints.clone(); + completed_complexity_rounds = round; + complexity_reports.push(serde_json::to_value(checkpoint)?); + } + } + for round in completed_complexity_rounds + 1..=maximum_complexity_rounds as u32 { + let preview_path = root.join(format!("complexity-round-{round:03}-preview.json")); + let resumed_preview = if resume && preview_path.is_file() { + Some(read_checkpoint::( + &preview_path, + )?) + } else { + None + }; + let demand = if let Some(checkpoint) = resumed_preview.as_ref() { + checkpoint.demand.clone() + } else { + derive_world_elaboration_demand( + u16::from(campaign.resolution_policy.active_cell_budget), + canonical_actionable_subject_count(&campaign), + &scale_intent, + realm_weights.clone(), + )? + }; + let actionable_before = demand.current_actionable_subjects; + if demand.actionable_subject_deficit == 0 { + break; + } + let preview = if let Some(checkpoint) = resumed_preview { + if checkpoint.schema != "ghostlight.complexity_round_preview.v1" + || checkpoint.round != round + || checkpoint.invocations.is_empty() + { + anyhow::bail!("complexity round preview checkpoint is stale or malformed") + } + complexity_scheduler = ElaborationScheduler::from_state( + &complexity_profile, + checkpoint.schedule.final_state.clone(), + )?; + checkpoint + } else { + let parents = complexity_parent_candidates( + &campaign, + &demand, + usize::try_from(demand.round_mutation_budget).unwrap_or(usize::MAX), + ); + if parents.is_empty() { + anyhow::bail!( + "world complexity remains {} subjects short but no active Gestalt can be subdivided", + demand.actionable_subject_deficit + ) + } + let failure_paths = complexity_failure_checkpoint_paths(&root, round)?; + let latest_failure = failure_paths.last().cloned(); + let first_dispatch_ordinal = if let Some(path) = latest_failure.as_ref() { + let checkpoint: ComplexityRoundFailureCheckpoint = read_checkpoint(path)?; + if checkpoint.round != round + || checkpoint.demand != demand + || checkpoint.parent_gestalt_ids != parents + { + anyhow::bail!("complexity failure checkpoint is stale or malformed") + } + checkpoint + .schedule + .as_ref() + .and_then(|schedule| schedule.dispatches.first()) + .map(|dispatch| dispatch.ordinal) + .ok_or_else(|| anyhow::anyhow!("complexity failure has no dispatches"))? + } else { + complexity_scheduler + .state() + .total_dispatches + .saturating_add(1) + }; + let worker = Arc::new(ModelWorldComplexityWorker::new( + model.clone(), + Arc::new(campaign.clone()), + first_dispatch_ordinal, + parents.clone(), + session_checkpoints.clone(), + )?); + let result = if let Some(path) = latest_failure.as_ref() { + let checkpoint: ComplexityRoundFailureCheckpoint = read_checkpoint(path)?; + let scheduler_state = checkpoint + .schedule + .as_ref() + .ok_or_else(|| anyhow::anyhow!("complexity failure has no schedule"))? + .final_state + .clone(); + complexity_scheduler = + ElaborationScheduler::from_state(&complexity_profile, scheduler_state)?; + resume_elaboration_wave( + rehydrate_complexity_failure(checkpoint, &store)?, + complexity_parallelism, + worker, + ) + .await + } else { + dispatch_elaboration_wave( + &mut complexity_scheduler, + worker.wave().clone(), + &eligible_titles, + u32::try_from(parents.len()).unwrap_or(u32::MAX), + complexity_parallelism, + worker, + ) + .await + }; + let run = match result { + Ok(run) => run, + Err(failure) => { + let receipts = failure + .completed_invocations + .iter() + .flat_map(|invocation| invocation.model_stage_receipts.iter()) + .chain( + failure + .invocation_failures + .iter() + .flat_map(|failure| failure.model_stage_receipts.iter()), + ) + .cloned() + .collect::>(); + if !receipts.is_empty() { + store.persist_model_stage_receipts(&receipts)?; + } + let failure_path = if latest_failure.is_some() { + root.join(format!( + "complexity-round-{round:03}-resume-{:02}-terminal-failure.json", + failure_paths.len() + )) + } else { + root.join(format!("complexity-round-{round:03}-terminal-failure.json")) + }; + let checkpoint = ComplexityRoundFailureCheckpoint { + schema: "ghostlight.complexity_round_failure.v1".into(), + round, + demand: demand.clone(), + parent_gestalt_ids: parents.clone(), + wave: failure.wave, + schedule: failure.schedule, + completed_invocations: failure + .completed_invocations + .iter() + .map(|invocation| { + Ok(ComplexityPreviewInvocation { + dispatch: invocation.dispatch.clone(), + parent_binding: world_complexity_parent_binding( + &campaign, + invocation.proposal.parent_gestalt_id(), + )?, + proposal: invocation.proposal.clone(), + model_receipt_hashes: invocation + .model_stage_receipts + .iter() + .map(|receipt| receipt.storage_key().to_owned()) + .collect(), + }) + }) + .collect::>>()?, + invocation_failures: failure + .invocation_failures + .iter() + .map(|failure| ComplexityFailedInvocation { + dispatch: failure.dispatch.clone(), + diagnostic: failure.diagnostic.clone(), + model_receipt_hashes: failure + .model_stage_receipts + .iter() + .map(|receipt| receipt.storage_key().to_owned()) + .collect(), + }) + .collect(), + }; + publish_immutable_checkpoint(&failure_path, &checkpoint)?; + anyhow::bail!( + "world complexity round {round} failed; exact checkpoint at {}", + failure_path.display() + ) + } + }; + let receipts = run + .invocations() + .iter() + .flat_map(|invocation| invocation.model_stage_receipts.iter()) + .cloned() + .collect::>(); + store.persist_model_stage_receipts(&receipts)?; + let checkpoint = ComplexityRoundPreviewCheckpoint { + schema: "ghostlight.complexity_round_preview.v1".into(), + round, + demand: demand.clone(), + frozen_world_revision: campaign.revision, + wave: run.wave().clone(), + schedule: run.schedule().clone(), + invocations: run + .invocations() + .iter() + .map(|invocation| { + Ok(ComplexityPreviewInvocation { + dispatch: invocation.dispatch.clone(), + parent_binding: world_complexity_parent_binding( + &campaign, + invocation.proposal.parent_gestalt_id(), + )?, + proposal: invocation.proposal.clone(), + model_receipt_hashes: invocation + .model_stage_receipts + .iter() + .map(|receipt| receipt.storage_key().to_owned()) + .collect(), + }) + }) + .collect::>>()?, + }; + publish_immutable_checkpoint(&preview_path, &checkpoint)?; + checkpoint + }; + let mut mutation_paths = Vec::new(); + let mut journals = + BTreeMap::>::new(); + for invocation in &preview.invocations { + let commit_path = root.join(format!( + "complexity-round-{round:03}-commit-{:04}.json", + invocation.dispatch.ordinal + )); + let checkpoint = if commit_path.is_file() { + read_checkpoint::(&commit_path)? + } else { + let proposal = rebase_world_complexity_proposal( + &invocation.parent_binding, + &campaign, + invocation.proposal.clone(), + )?; + let parent_gestalt_id = proposal.parent_gestalt_id().to_owned(); + let mutation_kind = proposal.mutation_kind().to_owned(); + let affected_subject_ids = match &proposal { + WorldComplexityProposal::Fission { preview } => { + std::iter::once(preview.parent_gestalt_id.clone()) + .chain(preview.children.iter().map(|child| child.id.clone())) + .collect::>() + } + WorldComplexityProposal::Individuate { individuation } => vec![ + individuation.gestalt_id.clone(), + ghostlight_dungeon::domain::gestalt_member_subject_id( + &individuation.member.id, + ), + ], + }; + let model_receipts = + load_checkpoint_receipts(&store, &invocation.model_receipt_hashes)?; + let committed = match proposal { + WorldComplexityProposal::Fission { preview } => { + kernel + .command(WorldCommand::FissionGestalt { + expected_revision: campaign.revision, + preview, + evidence_receipts: Vec::new(), + model_stage_receipts: model_receipts, + }) + .await? + } + WorldComplexityProposal::Individuate { individuation } => { + if model_receipts.is_empty() { + anyhow::bail!("complexity individuation has no model receipt") + } + kernel + .command(WorldCommand::IndividuateGestaltMember { + expected_revision: campaign.revision, + individuation, + }) + .await? + } + }; + let CommandResult::Committed { + campaign: advanced, + receipt, + } = committed + else { + anyhow::bail!("complexity mutation did not commit") + }; + let checkpoint = ComplexityMutationCheckpoint { + schema: "ghostlight.complexity_mutation_checkpoint.v1".into(), + round, + dispatch: invocation.dispatch.clone(), + parent_gestalt_id, + mutation_kind, + affected_subject_ids, + model_receipt_hashes: invocation.model_receipt_hashes.clone(), + commit_receipt: receipt, + }; + publish_immutable_checkpoint(&commit_path, &checkpoint)?; + campaign = advanced; + checkpoint + }; + if checkpoint.schema != "ghostlight.complexity_mutation_checkpoint.v1" + || checkpoint.round != round + || checkpoint.dispatch != invocation.dispatch + || checkpoint.parent_gestalt_id != invocation.proposal.parent_gestalt_id() + || checkpoint.model_receipt_hashes != invocation.model_receipt_hashes + || checkpoint.mutation_kind != invocation.proposal.mutation_kind() + || checkpoint.commit_receipt.command_kind != checkpoint.mutation_kind + { + anyhow::bail!("complexity mutation checkpoint is inconsistent") + } + journals.entry(checkpoint.dispatch.title).or_default().push( + ElaboratorSessionJournalEntry { + world_revision: checkpoint.commit_receipt.revision, + commit_receipt_id: format!( + "{}-{}", + checkpoint.commit_receipt.campaign_id, + checkpoint.commit_receipt.revision + ), + mutation_kind: checkpoint.mutation_kind.clone(), + affected_subject_ids: checkpoint.affected_subject_ids.clone(), + summary: format!( + "Applied {} to {} and admitted {}.", + checkpoint.mutation_kind, + checkpoint.parent_gestalt_id, + checkpoint.affected_subject_ids.join(", ") + ), + }, + ); + mutation_paths.push(commit_path); + } + for (title, journal) in journals { + let path = root.join(format!( + "complexity-round-{round:03}-session-{}.json", + title.display_name().to_ascii_lowercase() + )); + let checkpoint = if path.is_file() { + read_checkpoint::(&path)? + } else { + let (checkpoint, receipts) = compact_elaborator_session( + model.as_ref(), + &campaign, + &session_location_id, + title, + &format!( + "{}:{}", + title.display_name().to_ascii_lowercase(), + session_location_id + ), + session_checkpoints.get(&title), + &journal, + Vec::new(), + ) + .await?; + store.persist_model_stage_receipts(&receipts)?; + publish_immutable_checkpoint(&path, &checkpoint)?; + checkpoint + }; + checkpoint.validate_for(&campaign, &session_location_id, title)?; + session_checkpoints.insert(title, checkpoint); + } + let actionable_after = canonical_actionable_subject_count(&campaign); + if actionable_after <= actionable_before { + anyhow::bail!( + "world complexity round {round} committed without increasing admitted complexity" + ) + } + let checkpoint = ComplexityRoundCheckpoint { + schema: "ghostlight.complexity_round_checkpoint.v1".into(), + round, + demand_before: demand, + actionable_subjects_after: actionable_after, + schedule: preview.schedule, + mutation_checkpoints: mutation_paths, + session_checkpoints: session_checkpoints.clone(), + }; + let path = root.join(format!("complexity-round-{round:03}-checkpoint.json")); + publish_immutable_checkpoint(&path, &checkpoint)?; + complexity_reports.push(serde_json::to_value(&checkpoint)?); + } + let final_count = canonical_actionable_subject_count(&campaign); + let final_demand = derive_world_elaboration_demand( + u16::from(campaign.resolution_policy.active_cell_budget), + final_count, + &scale_intent, + realm_weights, + )?; + if final_demand.actionable_subject_deficit != 0 { + anyhow::bail!( + "world complexity stopped at {final_count} of {} admitted subjects after {maximum_complexity_rounds} rounds", + final_demand.target_actionable_subjects + ) + } + if let Some(metadata) = world_compile + .as_mut() + .and_then(serde_json::Value::as_object_mut) + { + metadata.insert( + "complexity_rounds".into(), + serde_json::Value::Array(complexity_reports.clone()), + ); + metadata.insert( + "actionable_subject_count".into(), + serde_json::json!(final_count), + ); + } + } let newspaper_title = std::env::var("GHOSTLIGHT_STRATEGIC_NEWSPAPER_TITLE") .unwrap_or_else(|_| "The Underdeep Clarion".into()); let newspaper_voice = std::env::var("GHOSTLIGHT_STRATEGIC_NEWSPAPER_VOICE") @@ -2693,6 +3304,97 @@ fn strategic_world_elaboration_profile() -> ghostlight_dungeon::elaboration::Wor } } +fn complexity_parent_candidates( + campaign: &ghostlight_dungeon::domain::Campaign, + demand: &ghostlight_dungeon::elaboration::WorldElaborationDemand, + limit: usize, +) -> Vec { + let realm_for = |profile: &ghostlight_dungeon::domain::AgencyProfile| { + profile + .location_ids + .iter() + .find(|location_id| demand.realm_subject_targets.contains_key(*location_id)) + .cloned() + }; + let mut current_by_realm = demand + .realm_subject_targets + .keys() + .cloned() + .map(|realm| (realm, 0_u32)) + .collect::>(); + for profile in campaign + .agency_profiles + .values() + .filter(|profile| profile.active_leaf && profile.simulation_eligible) + { + if let Some(realm) = realm_for(profile) { + *current_by_realm.entry(realm).or_default() += 1; + } + } + let realm_pressure = demand + .realm_subject_targets + .iter() + .map(|(realm, target)| { + ( + realm.clone(), + target.saturating_sub(current_by_realm.get(realm).copied().unwrap_or(0)), + ) + }) + .collect::>(); + let mut by_realm = BTreeMap::, String)>>::new(); + for (id, profile) in campaign.gestalts.keys().filter_map(|id| { + let profile = campaign.agency_profiles.get(id)?; + (profile.active_leaf + && profile.simulation_eligible + && !campaign + .gestalt_members + .values() + .any(|member| member.gestalt_id == *id && member.materialized_actor_id.is_some())) + .then_some((id, profile)) + }) { + if let Some(realm) = realm_for(profile) + && realm_pressure.get(&realm).copied().unwrap_or(0) > 0 + { + by_realm + .entry(realm) + .or_default() + .push((std::cmp::Reverse(profile.detail_debt), id.clone())); + } + } + for candidates in by_realm.values_mut() { + candidates.sort(); + candidates.reverse(); + } + let mut selected_per_realm = BTreeMap::::new(); + let mut selected = Vec::new(); + while selected.len() < limit { + let next_realm = by_realm + .iter() + .filter(|(_, candidates)| !candidates.is_empty()) + .min_by(|(left, _), (right, _)| { + let left_selected = selected_per_realm.get(*left).copied().unwrap_or(0); + let right_selected = selected_per_realm.get(*right).copied().unwrap_or(0); + let left_pressure = realm_pressure.get(*left).copied().unwrap_or(1).max(1); + let right_pressure = realm_pressure.get(*right).copied().unwrap_or(1).max(1); + left_selected + .saturating_mul(right_pressure) + .cmp(&right_selected.saturating_mul(left_pressure)) + .then_with(|| left.cmp(right)) + }) + .map(|(realm, _)| realm.clone()); + let Some(realm) = next_realm else { + break; + }; + let (_, id) = by_realm + .get_mut(&realm) + .and_then(Vec::pop) + .expect("selected realm has a candidate"); + *selected_per_realm.entry(realm).or_default() += 1; + selected.push(id); + } + selected +} + fn admitted_public_channel(value: &str) -> anyhow::Result { let channel = value.trim(); if !ghostlight_dungeon::resolution::information_channel_is_concrete(channel) { @@ -3768,3 +4470,4 @@ mod tests { ); } } +use std::collections::BTreeMap; diff --git a/crates/ghostlight-dungeon/src/elaboration.rs b/crates/ghostlight-dungeon/src/elaboration.rs index 0966a0a..0d4e58c 100644 --- a/crates/ghostlight-dungeon/src/elaboration.rs +++ b/crates/ghostlight-dungeon/src/elaboration.rs @@ -284,6 +284,311 @@ impl WorldElaborationProfile { } } +/// Compacted working memory for one titled elaborator. Narrative fields steer +/// later proposals but own no world truth; exact commit receipts and the +/// canonical campaign remain authoritative. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct ElaboratorSessionCheckpoint { + pub schema: String, + pub session_id: String, + pub title: ElaboratorTitle, + pub generation: u32, + pub campaign_id: Uuid, + pub through_world_revision: u64, + pub target_location_id: String, + pub frontier_summary: String, + pub unresolved_leads: Vec, + pub recent_commit_receipt_ids: Vec, + pub recent_rejection_findings: Vec, + pub prior_checkpoint_digest: Option, + pub digest: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct ElaboratorSessionCompactionDraft { + pub schema: String, + pub frontier_summary: String, + pub unresolved_leads: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct ElaboratorSessionJournalEntry { + pub world_revision: u64, + pub commit_receipt_id: String, + pub mutation_kind: String, + pub affected_subject_ids: Vec, + pub summary: String, +} + +impl ElaboratorSessionCheckpoint { + #[allow(clippy::too_many_arguments)] + pub fn bind_compaction( + session_id: impl Into, + title: ElaboratorTitle, + generation: u32, + campaign_id: Uuid, + through_world_revision: u64, + target_location_id: impl Into, + draft: ElaboratorSessionCompactionDraft, + recent_commit_receipt_ids: Vec, + recent_rejection_findings: Vec, + prior_checkpoint_digest: Option, + ) -> Result { + if draft.schema != "ghostlight.elaborator_session_compaction_draft.v1" { + return Err(anyhow!( + "elaborator session compaction draft schema is unsupported" + )); + } + let mut checkpoint = Self { + schema: "ghostlight.elaborator_session_checkpoint.v1".into(), + session_id: session_id.into(), + title, + generation, + campaign_id, + through_world_revision, + target_location_id: target_location_id.into(), + frontier_summary: draft.frontier_summary, + unresolved_leads: draft.unresolved_leads, + recent_commit_receipt_ids, + recent_rejection_findings, + prior_checkpoint_digest, + digest: String::new(), + }; + checkpoint.validate_shape()?; + checkpoint.digest = checkpoint.recompute_digest()?; + Ok(checkpoint) + } + + pub fn validate_for( + &self, + campaign: &crate::domain::Campaign, + target_location_id: &str, + title: ElaboratorTitle, + ) -> Result<()> { + self.validate_shape()?; + if self.campaign_id != campaign.id + || self.through_world_revision > campaign.revision + || self.target_location_id != target_location_id + || self.title != title + || self.digest != self.recompute_digest()? + { + return Err(anyhow!( + "elaborator session checkpoint is stale, cross-session, or malformed" + )); + } + Ok(()) + } + + fn validate_shape(&self) -> Result<()> { + let bounded = |value: &str, maximum: usize| { + !value.trim().is_empty() && value.chars().count() <= maximum + }; + if self.schema != "ghostlight.elaborator_session_checkpoint.v1" + || !bounded(&self.session_id, 160) + || !bounded(&self.target_location_id, 240) + || !bounded(&self.frontier_summary, 4_000) + || self.unresolved_leads.len() > 32 + || self.unresolved_leads.iter().any(|lead| !bounded(lead, 600)) + || self.recent_commit_receipt_ids.len() > 64 + || self + .recent_commit_receipt_ids + .iter() + .any(|id| !bounded(id, 240)) + || self.recent_rejection_findings.len() > 32 + || self + .recent_rejection_findings + .iter() + .any(|finding| !bounded(finding, 800)) + || self + .prior_checkpoint_digest + .as_deref() + .is_some_and(|digest| !bounded(digest, 160)) + { + return Err(anyhow!( + "elaborator session checkpoint exceeds its bounded memory contract" + )); + } + Ok(()) + } + + fn recompute_digest(&self) -> Result { + crate::legacy_transition::digest_serializable(&( + "ghostlight.elaborator_session_checkpoint.v1", + &self.session_id, + self.title, + self.generation, + self.campaign_id, + self.through_world_revision, + &self.target_location_id, + &self.frontier_summary, + &self.unresolved_leads, + &self.recent_commit_receipt_ids, + &self.recent_rejection_findings, + &self.prior_checkpoint_digest, + )) + } +} + +#[derive(Clone, Debug, Serialize)] +#[serde(deny_unknown_fields)] +struct ElaboratorSessionCompactionFinding { + diagnostic: String, +} + +struct ElaboratorSessionCompactionTool { + workbench: serde_json::Value, +} + +#[async_trait] +impl crate::agent::ModelAgentTool for ElaboratorSessionCompactionTool { + type Action = ElaboratorSessionCompactionDraft; + type Output = ElaboratorSessionCompactionDraft; + type Finding = ElaboratorSessionCompactionFinding; + + fn action_schema(&self) -> std::result::Result { + let mut schema = serde_json::to_value(schema_for!(ElaboratorSessionCompactionDraft)) + .map_err(|error| error.to_string())?; + schema["properties"]["schema"] = + exact_schema("ghostlight.elaborator_session_compaction_draft.v1"); + schema["properties"]["frontier_summary"]["minLength"] = serde_json::json!(1); + schema["properties"]["frontier_summary"]["maxLength"] = serde_json::json!(4000); + schema["properties"]["unresolved_leads"]["maxItems"] = serde_json::json!(32); + Ok(schema) + } + + fn initial_context_snapshot(&self) -> Option { + Some(self.workbench.clone()) + } + + async fn invoke( + &mut self, + action: Self::Action, + _context: &crate::agent::ModelAgentToolContext, + ) -> crate::agent::ModelAgentToolOutcome { + let bounded = |value: &str, maximum: usize| { + !value.trim().is_empty() && value.chars().count() <= maximum + }; + if action.schema != "ghostlight.elaborator_session_compaction_draft.v1" + || !bounded(&action.frontier_summary, 4_000) + || action.unresolved_leads.len() > 32 + || action + .unresolved_leads + .iter() + .any(|lead| !bounded(lead, 600)) + { + return crate::agent::ModelAgentToolOutcome::Rejected { + finding: ElaboratorSessionCompactionFinding { + diagnostic: + "compaction must preserve one bounded frontier and at most 32 concrete unresolved leads" + .into(), + }, + receipts: Vec::new(), + }; + } + crate::agent::ModelAgentToolOutcome::Accepted { + output: action, + receipts: Vec::new(), + } + } +} + +#[allow(clippy::too_many_arguments)] +pub async fn compact_elaborator_session( + model: &dyn crate::model::ModelPort, + campaign: &crate::domain::Campaign, + target_location_id: &str, + title: ElaboratorTitle, + session_id: &str, + prior: Option<&ElaboratorSessionCheckpoint>, + journal: &[ElaboratorSessionJournalEntry], + recent_rejection_findings: Vec, +) -> Result<( + ElaboratorSessionCheckpoint, + Vec, +)> { + if !campaign.locations.contains_key(target_location_id) + || journal.is_empty() + || journal.len() > 64 + || journal.iter().any(|entry| { + entry.world_revision > campaign.revision + || entry.commit_receipt_id.trim().is_empty() + || entry.mutation_kind.trim().is_empty() + || entry.summary.trim().is_empty() + || entry.summary.chars().count() > 1_000 + || entry.affected_subject_ids.len() > 32 + }) + { + return Err(anyhow!( + "elaborator session compaction journal is empty, stale, or unbounded" + )); + } + if let Some(prior) = prior { + prior.validate_for(campaign, target_location_id, title)?; + } + let generation = prior.map_or(0, |checkpoint| checkpoint.generation.saturating_add(1)); + let snapshot_binding = crate::legacy_transition::digest_serializable(&( + "ghostlight.elaborator_session_compaction_snapshot.v1", + campaign.id, + campaign.revision, + target_location_id, + title, + session_id, + prior.map(|checkpoint| checkpoint.digest.as_str()), + journal, + &recent_rejection_findings, + ))?; + let instructions = format!( + "You compact working memory for the {} elaborator. {} Preserve the causal frontier, unfinished structural leads, and useful rejected paths. Do not invent commits, subjects, facts, or completed work. The canonical world and exact journal remain authoritative; your summary only steers the next turn.", + title.display_name(), + title.mandate(), + ); + let spec = crate::agent::ModelAgentSpec { + stage: format!( + "world-elaboration-{}-session-compaction", + title.display_name().to_ascii_lowercase() + ), + model: crate::model::MODEL_FAST.into(), + snapshot_binding, + instructions, + source_receipt_ids: Vec::new(), + temperature: Some(0.1), + max_output_tokens: Some(1_400), + max_steps: 2, + }; + let mut tool = ElaboratorSessionCompactionTool { + workbench: serde_json::json!({ + "schema":"ghostlight.elaborator_session_compaction_workbench.v1", + "prior_checkpoint":prior, + "recent_admitted_journal":journal, + "recent_rejection_findings":recent_rejection_findings, + "through_world_revision":campaign.revision, + "target_location_id":target_location_id, + }), + }; + let run = crate::agent::run_model_agent(model, &spec, &mut tool) + .await + .map_err(|failure| anyhow!(failure.message))?; + let checkpoint = ElaboratorSessionCheckpoint::bind_compaction( + session_id, + title, + generation, + campaign.id, + campaign.revision, + target_location_id, + run.output, + journal + .iter() + .map(|entry| entry.commit_receipt_id.clone()) + .collect(), + recent_rejection_findings, + prior.map(|checkpoint| checkpoint.digest.clone()), + )?; + Ok((checkpoint, run.receipts)) +} + #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] #[serde(deny_unknown_fields)] pub struct ElaborationDispatchState { @@ -838,6 +1143,7 @@ pub struct ModelWorldElaborationWorker { campaign: Arc, target_location_id: String, request: String, + session_checkpoints: BTreeMap, } impl ModelWorldElaborationWorker { @@ -861,9 +1167,21 @@ impl ModelWorldElaborationWorker { campaign, target_location_id, request: request.into(), + session_checkpoints: BTreeMap::new(), }) } + pub fn with_session_checkpoints( + mut self, + checkpoints: BTreeMap, + ) -> Result { + for (title, checkpoint) in &checkpoints { + checkpoint.validate_for(&self.campaign, &self.target_location_id, *title)?; + } + self.session_checkpoints = checkpoints; + Ok(self) + } + /// The exact semantic task shared by the worker wave, its artifacts, and /// the independent verifier. Callers should read this value from the /// prepared worker instead of retaining a second request owner. @@ -903,6 +1221,418 @@ impl ModelWorldElaborationWorker { } } +/// Provider-backed worker for one causally meaningful Gestalt subdivision. +/// A round assigns distinct active parents against one frozen campaign. The +/// worker proposes only; callers must revalidate and commit each preview +/// through `WorldKernel::FissionGestalt`. +pub struct ModelWorldComplexityWorker { + model: Arc, + campaign: Arc, + wave: ElaborationWaveBinding, + first_dispatch_ordinal: u64, + parent_gestalt_ids: Vec, + session_checkpoints: BTreeMap, +} + +impl ModelWorldComplexityWorker { + pub fn new( + model: Arc, + campaign: Arc, + first_dispatch_ordinal: u64, + parent_gestalt_ids: Vec, + session_checkpoints: BTreeMap, + ) -> Result { + if parent_gestalt_ids.is_empty() + || parent_gestalt_ids.iter().collect::>().len() != parent_gestalt_ids.len() + { + return Err(anyhow!( + "complexity round requires distinct assigned parent Gestalts" + )); + } + for parent_id in &parent_gestalt_ids { + let profile = campaign.agency_profiles.get(parent_id); + if !campaign.gestalts.contains_key(parent_id) + || profile.is_none_or(|profile| { + !profile.active_leaf + || !profile.simulation_eligible + || profile.subject_kind != crate::domain::AgencySubjectKind::Gestalt + }) + || campaign.gestalt_members.values().any(|member| { + member.gestalt_id == *parent_id && member.materialized_actor_id.is_some() + }) + { + return Err(anyhow!( + "complexity round parent is not an unresolved active Gestalt" + )); + } + } + for (title, checkpoint) in &session_checkpoints { + if checkpoint.campaign_id != campaign.id + || checkpoint.through_world_revision > campaign.revision + || checkpoint.title != *title + { + return Err(anyhow!( + "complexity worker received a stale or cross-title session checkpoint" + )); + } + } + let wave = ElaborationWaveBinding { + schema: "ghostlight.elaboration_wave_binding.v1".into(), + snapshot_binding: crate::legacy_transition::digest_serializable(&( + "ghostlight.world_complexity_round.v1", + campaign.id, + campaign.revision, + first_dispatch_ordinal, + &parent_gestalt_ids, + ))?, + }; + Ok(Self { + model, + campaign, + wave, + first_dispatch_ordinal, + parent_gestalt_ids, + session_checkpoints, + }) + } + + pub fn wave(&self) -> &ElaborationWaveBinding { + &self.wave + } + + fn parent_for(&self, dispatch: &ElaborationDispatch) -> Result<&str> { + let offset = dispatch + .ordinal + .checked_sub(self.first_dispatch_ordinal) + .ok_or_else(|| anyhow!("complexity dispatch predates its assigned round"))?; + self.parent_gestalt_ids + .get(usize::try_from(offset).unwrap_or(usize::MAX)) + .map(String::as_str) + .ok_or_else(|| anyhow!("complexity dispatch exceeds its assigned parent set")) + } +} + +fn complexity_partition_axis(title: ElaboratorTitle) -> crate::domain::AgencyAxis { + use crate::domain::AgencyAxis; + match title { + ElaboratorTitle::Patina | ElaboratorTitle::Hearth | ElaboratorTitle::Ember => { + AgencyAxis::Geography + } + ElaboratorTitle::Charter => AgencyAxis::Authority, + ElaboratorTitle::Ledger => AgencyAxis::EconomyRole, + ElaboratorTitle::Tangle | ElaboratorTitle::Numen => AgencyAxis::Ideology, + ElaboratorTitle::Veil => AgencyAxis::Information, + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum WorldComplexityOperation { + Fission, + Individuate, +} + +fn complexity_operation(title: ElaboratorTitle) -> WorldComplexityOperation { + match title { + ElaboratorTitle::Hearth | ElaboratorTitle::Veil => WorldComplexityOperation::Individuate, + _ => WorldComplexityOperation::Fission, + } +} + +/// One proposed increase in causally meaningful world resolution. This is +/// deliberately the same command algebra the kernel already owns: elaborators +/// may either split a population into distinct active leaves or promote one +/// consequential person from it. They do not own a parallel subject store. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +#[serde(tag = "operation", rename_all = "snake_case", deny_unknown_fields)] +pub enum WorldComplexityProposal { + Fission { + preview: crate::domain::GestaltFissionPreview, + }, + Individuate { + individuation: crate::domain::GestaltIndividuation, + }, +} + +impl WorldComplexityProposal { + pub fn parent_gestalt_id(&self) -> &str { + match self { + Self::Fission { preview } => &preview.parent_gestalt_id, + Self::Individuate { individuation } => &individuation.gestalt_id, + } + } + + pub fn mutation_kind(&self) -> &'static str { + match self { + Self::Fission { .. } => "fission_gestalt", + Self::Individuate { .. } => "individuate_gestalt_member", + } + } +} + +/// Rebinds only the optimistic revision of a proposal produced in a frozen +/// parallel round. The assigned parent, its active profile, and all of its +/// member state must remain byte-identical; unrelated earlier commits may not +/// force an expensive proposal replay. +pub fn world_complexity_parent_binding( + campaign: &crate::domain::Campaign, + parent_gestalt_id: &str, +) -> Result { + let members = campaign + .gestalt_members + .values() + .filter(|member| member.gestalt_id == parent_gestalt_id) + .collect::>(); + crate::legacy_transition::digest_serializable(&( + "ghostlight.world_complexity_parent.v1", + campaign.id, + campaign.gestalts.get(parent_gestalt_id), + campaign.agency_profiles.get(parent_gestalt_id), + members, + )) +} + +pub fn rebase_world_complexity_proposal( + frozen_parent_binding: &str, + current: &crate::domain::Campaign, + mut proposal: WorldComplexityProposal, +) -> Result { + let parent_id = proposal.parent_gestalt_id().to_owned(); + if world_complexity_parent_binding(current, &parent_id)? != frozen_parent_binding { + return Err(anyhow!( + "complexity mutation parent changed after its frozen proposal" + )); + } + match &mut proposal { + WorldComplexityProposal::Fission { preview } => { + if preview.campaign_id != current.id { + return Err(anyhow!("complexity fission belongs to another campaign")); + } + preview.expected_world_revision = current.revision; + crate::resolution::validate_fission(current, preview)?; + } + WorldComplexityProposal::Individuate { individuation } => { + crate::resolution::validate_gestalt_individuation(current, individuation)?; + } + } + Ok(proposal) +} + +#[derive(Clone, Debug, Serialize)] +#[serde(deny_unknown_fields)] +struct WorldComplexityFinding { + diagnostic: String, +} + +struct WorldComplexityTool<'a> { + campaign: &'a crate::domain::Campaign, + parent_gestalt_id: &'a str, + operation: WorldComplexityOperation, + partition_axis: crate::domain::AgencyAxis, + workbench: serde_json::Value, +} + +#[async_trait] +impl crate::agent::ModelAgentTool for WorldComplexityTool<'_> { + type Action = WorldComplexityProposal; + type Output = WorldComplexityProposal; + type Finding = WorldComplexityFinding; + + fn action_schema(&self) -> std::result::Result { + serde_json::to_value(schema_for!(WorldComplexityProposal)) + .map_err(|error| error.to_string()) + } + + fn initial_context_snapshot(&self) -> Option { + Some(self.workbench.clone()) + } + + async fn invoke( + &mut self, + action: Self::Action, + _context: &crate::agent::ModelAgentToolContext, + ) -> crate::agent::ModelAgentToolOutcome { + if action.parent_gestalt_id() != self.parent_gestalt_id + || !matches!( + (&self.operation, &action), + ( + WorldComplexityOperation::Fission, + WorldComplexityProposal::Fission { .. } + ) | ( + WorldComplexityOperation::Individuate, + WorldComplexityProposal::Individuate { .. } + ) + ) + { + return crate::agent::ModelAgentToolOutcome::Rejected { + finding: WorldComplexityFinding { + diagnostic: "complexity proposal changed its assigned parent or operation" + .into(), + }, + receipts: Vec::new(), + }; + } + let validation = match &action { + WorldComplexityProposal::Fission { preview } => { + if preview.partition_axis != self.partition_axis { + Err(anyhow!("fission changed its assigned partition axis")) + } else { + crate::resolution::validate_fission(self.campaign, preview) + } + } + WorldComplexityProposal::Individuate { individuation } => { + crate::resolution::validate_gestalt_individuation(self.campaign, individuation) + } + }; + match validation { + Ok(()) => crate::agent::ModelAgentToolOutcome::Accepted { + output: action, + receipts: Vec::new(), + }, + Err(error) => crate::agent::ModelAgentToolOutcome::Rejected { + finding: WorldComplexityFinding { + diagnostic: error.to_string(), + }, + receipts: Vec::new(), + }, + } + } +} + +#[async_trait] +impl ElaborationSubAgentPort for ModelWorldComplexityWorker { + async fn invoke( + &self, + invocation: ElaborationSubAgentInvocation, + ) -> std::result::Result< + ElaborationSubAgentOutput, + ElaborationSubAgentFailure, + > { + if invocation.wave != self.wave { + return Err(ElaborationSubAgentFailure { + diagnostic: "complexity invocation does not match its frozen round".into(), + model_stage_receipts: Vec::new(), + }); + } + let parent_id = + self.parent_for(&invocation.dispatch) + .map_err(|error| ElaborationSubAgentFailure { + diagnostic: error.to_string(), + model_stage_receipts: Vec::new(), + })?; + let parent = &self.campaign.gestalts[parent_id]; + let profile = &self.campaign.agency_profiles[parent_id]; + let axis = complexity_partition_axis(invocation.dispatch.title); + let operation = complexity_operation(invocation.dispatch.title); + let location_id = + profile + .location_ids + .iter() + .next() + .ok_or_else(|| ElaborationSubAgentFailure { + diagnostic: "complexity parent has no exact location".into(), + model_stage_receipts: Vec::new(), + })?; + let assignment = match operation { + WorldComplexityOperation::Fission => serde_json::json!({ + "operation":"fission_gestalt", + "parent_gestalt_id":parent_id, + "partition_axis":axis, + "requirements":[ + "Return operation=fission with a ghostlight.gestalt_fission_preview.v1 preview.", + "Bind campaign_id and expected_world_revision exactly to the frozen world.", + "Create 2 through 8 non-overlapping children with distinct partition values.", + "Exactly one residual child must have partition value other/unknown.", + "Children inherit capabilities, knowledge, goals, and pressures exactly.", + "Assign every scarce resource and dormant named member exactly once.", + "Use no evidence receipts or canon candidates and require approval." + ] + }), + WorldComplexityOperation::Individuate => serde_json::json!({ + "operation":"individuate_gestalt_member", + "parent_gestalt_id":parent_id, + "location_id":location_id, + "requirements":[ + "Return operation=individuate with one GestaltIndividuation.", + "Use the exact parent id, parent version, and assigned location.", + "Create one consequential named person whose goals, knowledge, relationships, and memories are grounded in the parent state.", + "Use a new local member id without the member: prefix; version zero; no materialized actor id.", + "Do not create quota names, unsupported relationships, or decorative biography." + ] + }), + }; + let instructions = format!( + "You are {}, one titled elaborator in an iterative world-complexity session. {} Perform exactly the assigned structural mutation where the frozen world supports consequential agency. Prefer one strong change over quota padding. Your proposal cannot commit, approve itself, or invent evidence.", + invocation.dispatch.title.display_name(), + invocation.dispatch.title.mandate(), + ); + let workbench = serde_json::json!({ + "schema":"ghostlight.world_complexity_workbench.v1", + "assignment":assignment, + "parent":parent, + "parent_profile":profile, + "parent_members":self.campaign.gestalt_members.values() + .filter(|member|member.gestalt_id == parent_id).collect::>(), + "local_relations":self.campaign.agency_relations.values() + .filter(|relation|relation.from_subject_id == parent_id || relation.to_subject_id == parent_id) + .collect::>(), + "compacted_session":self.session_checkpoints.get(&invocation.dispatch.title), + }); + let mut tool = WorldComplexityTool { + campaign: &self.campaign, + parent_gestalt_id: parent_id, + operation, + partition_axis: axis, + workbench, + }; + let spec = crate::agent::ModelAgentSpec { + stage: format!( + "world-complexity-{}-{}", + invocation + .dispatch + .title + .display_name() + .to_ascii_lowercase(), + match operation { + WorldComplexityOperation::Fission => "fission", + WorldComplexityOperation::Individuate => "individuate", + } + ), + model: match invocation.dispatch.title { + ElaboratorTitle::Charter | ElaboratorTitle::Tangle => { + crate::model::MODEL_BALANCED.into() + } + ElaboratorTitle::Numen => crate::model::MODEL_CAPABLE.into(), + _ => crate::model::MODEL_FAST.into(), + }, + snapshot_binding: crate::legacy_transition::digest_serializable(&( + "ghostlight.world_complexity_invocation.v1", + &self.wave, + &invocation.dispatch, + parent_id, + )) + .map_err(|error| ElaborationSubAgentFailure { + diagnostic: error.to_string(), + model_stage_receipts: Vec::new(), + })?, + instructions, + source_receipt_ids: Vec::new(), + temperature: Some(0.35), + max_output_tokens: Some(4_000), + max_steps: 3, + }; + match crate::agent::run_model_agent(self.model.as_ref(), &spec, &mut tool).await { + Ok(run) => Ok(ElaborationSubAgentOutput { + proposal: run.output, + model_stage_receipts: run.receipts, + }), + Err(error) => Err(ElaborationSubAgentFailure { + diagnostic: error.message, + model_stage_receipts: error.receipts, + }), + } + } +} + #[derive(Clone, Debug)] enum WorldElaborationAssignment { PatinaPlace { @@ -1452,6 +2182,7 @@ impl ElaborationSubAgentPort for ModelWorldElaboration workbench: serde_json::json!({ "schema":"ghostlight.elaborator_workbench.v1", "assignment":assignment_instruction, + "compacted_session":self.session_checkpoints.get(&invocation.dispatch.title), "frozen_public_world_projection":serde_json::from_str::(&projection) .unwrap_or_else(|_| serde_json::Value::String(projection)), }), @@ -2441,6 +3172,47 @@ mod tests { assert!(!campaign.agency_profiles[&campaign.player_actor_id].simulation_eligible); } + #[test] + fn elaborator_session_compaction_binds_narrative_memory_to_exact_commits() { + let campaign = campaign_with_civic_room(); + let checkpoint = ElaboratorSessionCheckpoint::bind_compaction( + "charter:room", + ElaboratorTitle::Charter, + 2, + campaign.id, + campaign.revision, + "room", + ElaboratorSessionCompactionDraft { + schema: "ghostlight.elaborator_session_compaction_draft.v1".into(), + frontier_summary: + "The threshold witness office lacks an acknowledged succession rule.".into(), + unresolved_leads: vec![ + "Split the resident body by who can challenge a witness count.".into(), + ], + }, + vec!["world-commit:12".into()], + vec!["A proposed office duplicated an admitted institution.".into()], + Some("sha256:prior".into()), + ) + .unwrap(); + checkpoint + .validate_for(&campaign, "room", ElaboratorTitle::Charter) + .unwrap(); + + let mut tampered = checkpoint.clone(); + tampered.frontier_summary = "Invent an unrelated monarchy.".into(); + assert!( + tampered + .validate_for(&campaign, "room", ElaboratorTitle::Charter) + .is_err() + ); + assert!( + checkpoint + .validate_for(&campaign, "room", ElaboratorTitle::Patina) + .is_err() + ); + } + fn campaign_with_civic_room() -> crate::domain::Campaign { let mut campaign = crate::kernel::tests::campaign(); campaign.civic_systems.insert( @@ -2462,6 +3234,210 @@ mod tests { campaign } + fn campaign_with_fission_parent() -> crate::domain::Campaign { + let mut campaign = campaign_with_civic_room(); + campaign.gestalts.insert( + "river-households".into(), + crate::domain::GestaltPersonaState { + schema: "ghostlight.gestalt_persona_state.v1".into(), + id: "river-households".into(), + name: "River Households".into(), + version: 0, + home_location_id: "room".into(), + shared_capabilities: BTreeSet::from(["river tending".into()]), + shared_knowledge: BTreeSet::from(["seasonal ford marks".into()]), + resources: BTreeSet::new(), + goals: vec!["keep the river habitable".into()], + pressures: vec!["the banks are narrowing".into()], + }, + ); + crate::resolution::ensure_agency_profiles(&mut campaign); + campaign + .agency_profiles + .get_mut("river-households") + .unwrap() + .location_ids = BTreeSet::from(["room".into()]); + campaign + } + + fn valid_river_fission( + campaign: &crate::domain::Campaign, + ) -> crate::domain::GestaltFissionPreview { + let parent = &campaign.gestalts["river-households"]; + let child = |id: &str, name: &str| crate::domain::GestaltPersonaState { + schema: parent.schema.clone(), + id: id.into(), + name: name.into(), + version: 0, + home_location_id: parent.home_location_id.clone(), + shared_capabilities: parent.shared_capabilities.clone(), + shared_knowledge: parent.shared_knowledge.clone(), + resources: BTreeSet::new(), + goals: parent.goals.clone(), + pressures: parent.pressures.clone(), + }; + crate::domain::GestaltFissionPreview { + schema: "ghostlight.gestalt_fission_preview.v1".into(), + campaign_id: campaign.id, + expected_world_revision: campaign.revision, + parent_gestalt_id: parent.id.clone(), + partition_axis: crate::domain::AgencyAxis::Authority, + children: vec![ + child("licensed-river-households", "Licensed River Households"), + child("unrecorded-river-households", "Unrecorded River Households"), + ], + child_partition_values: BTreeMap::from([ + ( + "licensed-river-households".into(), + "licensed tenders".into(), + ), + ("unrecorded-river-households".into(), "other/unknown".into()), + ]), + residual_child_id: "unrecorded-river-households".into(), + member_child_assignments: BTreeMap::new(), + resource_child_assignments: BTreeMap::new(), + evidence_receipt_ids: Vec::new(), + gaps: Vec::new(), + canon_candidates: Vec::new(), + requires_approval: true, + } + } + + #[tokio::test] + async fn complexity_tool_admits_only_the_assigned_meaningful_fission() { + let campaign = campaign_with_fission_parent(); + let preview = valid_river_fission(&campaign); + let mut tool = WorldComplexityTool { + campaign: &campaign, + parent_gestalt_id: "river-households", + operation: WorldComplexityOperation::Fission, + partition_axis: crate::domain::AgencyAxis::Authority, + workbench: serde_json::json!({"schema":"test.workbench.v1"}), + }; + let context = crate::agent::ModelAgentToolContext { + source_receipt_ids: Vec::new(), + current_model_receipt: None, + }; + + let admitted = crate::agent::ModelAgentTool::invoke( + &mut tool, + WorldComplexityProposal::Fission { + preview: preview.clone(), + }, + &context, + ) + .await; + assert!(matches!( + admitted, + crate::agent::ModelAgentToolOutcome::Accepted { .. } + )); + + let mut wrong_axis = preview; + wrong_axis.partition_axis = crate::domain::AgencyAxis::Ideology; + let rejected = crate::agent::ModelAgentTool::invoke( + &mut tool, + WorldComplexityProposal::Fission { + preview: wrong_axis, + }, + &context, + ) + .await; + assert!(matches!( + rejected, + crate::agent::ModelAgentToolOutcome::Rejected { .. } + )); + } + + #[tokio::test] + async fn complexity_tool_promotes_one_grounded_person_without_a_roster() { + let campaign = campaign_with_fission_parent(); + let individuation = crate::domain::GestaltIndividuation { + gestalt_id: "river-households".into(), + expected_gestalt_version: campaign.gestalts["river-households"].version, + location_id: "room".into(), + member: crate::domain::GestaltMemberDelta { + schema: "ghostlight.gestalt_member_delta.v1".into(), + id: "orin-weirkeeper".into(), + gestalt_id: "river-households".into(), + version: 0, + name: "Orin Weirkeeper".into(), + capability_additions: BTreeSet::from(["read narrowing banks".into()]), + capability_removals: BTreeSet::new(), + knowledge_additions: BTreeSet::from(["which ford marks were moved".into()]), + knowledge_removals: BTreeSet::new(), + equipment: BTreeSet::from(["notched sounding pole".into()]), + conditions: BTreeSet::new(), + obligations: BTreeSet::from(["keep the river habitable".into()]), + relationships: BTreeMap::new(), + goals: vec!["force a public reckoning over the narrowing banks".into()], + memories: vec!["found three seasonal ford marks reset upstream".into()], + last_location_id: None, + materialized_actor_id: None, + last_relevant_revision: 0, + relevance_lease_until_revision: 0, + }, + }; + let mut tool = WorldComplexityTool { + campaign: &campaign, + parent_gestalt_id: "river-households", + operation: WorldComplexityOperation::Individuate, + partition_axis: crate::domain::AgencyAxis::Information, + workbench: serde_json::json!({"schema":"test.workbench.v1"}), + }; + let context = crate::agent::ModelAgentToolContext { + source_receipt_ids: Vec::new(), + current_model_receipt: None, + }; + + let admitted = crate::agent::ModelAgentTool::invoke( + &mut tool, + WorldComplexityProposal::Individuate { individuation }, + &context, + ) + .await; + assert!(matches!( + admitted, + crate::agent::ModelAgentToolOutcome::Accepted { .. } + )); + } + + #[test] + fn complexity_fission_rebases_only_across_unchanged_parent_state() { + let frozen = campaign_with_fission_parent(); + let preview = valid_river_fission(&frozen); + let mut current = frozen.clone(); + current.revision = current.revision.saturating_add(1); + + let binding = world_complexity_parent_binding(&frozen, "river-households").unwrap(); + let rebased = rebase_world_complexity_proposal( + &binding, + ¤t, + WorldComplexityProposal::Fission { + preview: preview.clone(), + }, + ) + .unwrap(); + let WorldComplexityProposal::Fission { preview: rebased } = rebased else { + panic!("rebased mutation changed kind") + }; + assert_eq!(rebased.expected_world_revision, current.revision); + + current + .gestalts + .get_mut("river-households") + .unwrap() + .pressures + .push("an intervening flood changed the parent".into()); + assert!( + rebase_world_complexity_proposal( + &binding, + ¤t, + WorldComplexityProposal::Fission { preview }, + ) + .is_err() + ); + } + fn profile(weights: &[(ElaboratorTitle, u16)]) -> WorldElaborationProfile { WorldElaborationProfile { schema: "ghostlight.world_elaboration_profile.v1".into(), @@ -2858,6 +3834,8 @@ mod tests { struct ExactAssignmentSchemaModel; + struct ExactSessionCompactionModel; + struct ReceiptlessWorldWorker; #[async_trait] @@ -2955,6 +3933,55 @@ mod tests { } } + #[async_trait] + impl crate::model::ModelPort for ExactSessionCompactionModel { + async fn run(&self, request: &crate::model::ModelStageRequest) -> Result { + assert!(request.stage.ends_with("session-compaction")); + assert!(request.lived_stream.contains("world-commit:12")); + assert!(request.lived_stream.contains("threshold witness")); + Ok(serde_json::json!({ + "schema":"ghostlight.elaborator_session_compaction_draft.v1", + "frontier_summary":"The threshold witness office still lacks a succession rule.", + "unresolved_leads":["Fission the electorate by access to public count challenges."] + }) + .to_string()) + } + + fn provider(&self) -> &'static str { + "session-compaction-fixture" + } + } + + #[tokio::test] + async fn session_compactor_preserves_exact_journal_ancestry() { + let campaign = campaign_with_civic_room(); + let (checkpoint, receipts) = compact_elaborator_session( + &ExactSessionCompactionModel, + &campaign, + "room", + ElaboratorTitle::Charter, + "charter:room", + None, + &[ElaboratorSessionJournalEntry { + world_revision: campaign.revision, + commit_receipt_id: "world-commit:12".into(), + mutation_kind: "fission_gestalt".into(), + affected_subject_ids: vec!["threshold-witnesses".into()], + summary: "The threshold witness electorate split over public challenges.".into(), + }], + vec!["A duplicate office proposal was rejected.".into()], + ) + .await + .unwrap(); + + assert_eq!(checkpoint.recent_commit_receipt_ids, ["world-commit:12"]); + assert_eq!(checkpoint.generation, 0); + assert_eq!(receipts.len(), 1); + checkpoint + .validate_for(&campaign, "room", ElaboratorTitle::Charter) + .unwrap(); + } + #[tokio::test] async fn provider_worker_rejects_a_wave_from_a_newer_world_before_model_inference() { let frozen = campaign_with_civic_room(); diff --git a/crates/ghostlight-dungeon/src/kernel.rs b/crates/ghostlight-dungeon/src/kernel.rs index 379b704..852e54b 100644 --- a/crates/ghostlight-dungeon/src/kernel.rs +++ b/crates/ghostlight-dungeon/src/kernel.rs @@ -2152,28 +2152,12 @@ fn apply_individuation( ) -> Result<(), KernelError> { let mut member = individuation.member.clone(); member.id = crate::domain::canonical_gestalt_member_local_id(&member.id); - let gestalt = campaign - .gestalts - .get(&individuation.gestalt_id) - .ok_or_else(|| KernelError::Invalid("gestalt is unknown".into()))?; - crate::resolution::validate_active_gestalt_presence_location( - campaign, - &individuation.gestalt_id, - &individuation.location_id, - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - if gestalt.version != individuation.expected_gestalt_version - || member.gestalt_id != individuation.gestalt_id - || member.version != 0 - || member.materialized_actor_id.is_some() - || member.id.trim().is_empty() - || member.name.trim().is_empty() - || campaign.gestalt_members.contains_key(&member.id) - { - return Err(KernelError::Invalid( - "gestalt individuation is stale or malformed".into(), - )); - } + let canonical = GestaltIndividuation { + member: member.clone(), + ..individuation.clone() + }; + crate::resolution::validate_gestalt_individuation(campaign, &canonical) + .map_err(|error| KernelError::Invalid(error.to_string()))?; campaign .gestalt_members .insert(member.id.clone(), member.clone()); @@ -8413,6 +8397,13 @@ pub(crate) mod tests { let resident = &individuated.actors["member:iren-vale"]; assert!(resident.knowledge.contains(&selection)); assert!(resident.memories[0].contains("Oren Vale")); + let resident_profile = &individuated.agency_profiles["member:iren-vale"]; + assert!(resident_profile.active_leaf); + assert!(resident_profile.simulation_eligible); + assert_eq!( + crate::elaboration::canonical_actionable_subject_count(&individuated), + crate::elaboration::canonical_actionable_subject_count(&elaborated) + 1 + ); } #[tokio::test] diff --git a/crates/ghostlight-dungeon/src/resolution.rs b/crates/ghostlight-dungeon/src/resolution.rs index 3b517d7..52677fa 100644 --- a/crates/ghostlight-dungeon/src/resolution.rs +++ b/crates/ghostlight-dungeon/src/resolution.rs @@ -2204,6 +2204,71 @@ fn validate_strategic_individuations( ) } +pub fn validate_gestalt_individuation( + campaign: &Campaign, + individuation: &GestaltIndividuation, +) -> Result<()> { + let member = &individuation.member; + let profile = campaign + .agency_profiles + .get(&individuation.gestalt_id) + .ok_or_else(|| anyhow!("individuation Gestalt has no agency profile"))?; + validate_active_gestalt_presence_location( + campaign, + &individuation.gestalt_id, + &individuation.location_id, + )?; + if !campaign.gestalts.contains_key(&individuation.gestalt_id) + || !profile.active_leaf + || !profile.simulation_eligible + || individuation.expected_gestalt_version + != campaign.gestalts[&individuation.gestalt_id].version + || member.schema != "ghostlight.gestalt_member_delta.v1" + || member.gestalt_id != individuation.gestalt_id + || member.version != 0 + || member.materialized_actor_id.is_some() + || member.id.trim().is_empty() + || member.id.chars().count() > 80 + || member.name.trim().is_empty() + || member.name.chars().count() > 160 + || member.goals.len() > 8 + || member.memories.len() > 8 + || member.obligations.len() > 8 + || serde_json::to_vec(member).is_ok_and(|encoded| encoded.len() > 16_384) + || campaign + .gestalt_members + .contains_key(&crate::domain::canonical_gestalt_member_local_id( + &member.id, + )) + || campaign + .actors + .contains_key(&crate::domain::gestalt_member_subject_id(&member.id)) + || campaign + .actors + .values() + .any(|actor| actor.name.trim().eq_ignore_ascii_case(member.name.trim())) + || campaign.gestalt_members.values().any(|existing| { + existing + .name + .trim() + .eq_ignore_ascii_case(member.name.trim()) + }) + || member.relationships.keys().any(|subject_id| { + !campaign.actors.contains_key(subject_id) + && !campaign.institutions.contains_key(subject_id) + && !campaign.gestalts.contains_key(subject_id) + && subject_id + .strip_prefix("member:") + .is_none_or(|member_id| !campaign.gestalt_members.contains_key(member_id)) + }) + { + return Err(anyhow!( + "gestalt individuation exceeds its exact population authority" + )); + } + Ok(()) +} + pub(crate) fn validate_strategic_individuation_proposals( campaign: &Campaign, proposals: &[StrategicGestaltIndividuation], @@ -2223,57 +2288,11 @@ pub(crate) fn validate_strategic_individuation_proposals( .get(&proposal.action_digest) .ok_or_else(|| anyhow!("strategic individuation is not bound to a selected action"))?; let individuation = &proposal.individuation; - let member = &individuation.member; - let profile = campaign - .agency_profiles - .get(&individuation.gestalt_id) - .ok_or_else(|| anyhow!("strategic individuation Gestalt has no agency profile"))?; if proposal.schema != "ghostlight.strategic_gestalt_individuation.v1" || proposal.rationale.trim().is_empty() || proposal.rationale.chars().count() > 460 || action.subject_id != individuation.gestalt_id - || !campaign.gestalts.contains_key(&individuation.gestalt_id) - || !profile.active_leaf - || !profile.simulation_eligible - || !profile.location_ids.contains(&individuation.location_id) - || individuation.expected_gestalt_version - != campaign.gestalts[&individuation.gestalt_id].version - || member.schema != "ghostlight.gestalt_member_delta.v1" - || member.gestalt_id != individuation.gestalt_id - || member.version != 0 - || member.materialized_actor_id.is_some() - || member.id.trim().is_empty() - || member.id.chars().count() > 80 - || member.name.trim().is_empty() - || member.name.chars().count() > 160 - || member.goals.len() > 8 - || member.memories.len() > 8 - || member.obligations.len() > 8 - || serde_json::to_vec(member).is_ok_and(|encoded| encoded.len() > 16_384) - || campaign.gestalt_members.contains_key( - &crate::domain::canonical_gestalt_member_local_id(&member.id), - ) - || campaign - .actors - .contains_key(&crate::domain::gestalt_member_subject_id(&member.id)) - || campaign - .actors - .values() - .any(|actor| actor.name.trim().eq_ignore_ascii_case(member.name.trim())) - || campaign.gestalt_members.values().any(|existing| { - existing - .name - .trim() - .eq_ignore_ascii_case(member.name.trim()) - }) - || member.relationships.keys().any(|subject_id| { - !campaign.actors.contains_key(subject_id) - && !campaign.institutions.contains_key(subject_id) - && !campaign.gestalts.contains_key(subject_id) - && subject_id - .strip_prefix("member:") - .is_none_or(|member_id| !campaign.gestalt_members.contains_key(member_id)) - }) + || validate_gestalt_individuation(campaign, individuation).is_err() { return Err(anyhow!( "strategic individuation exceeds its exact Gestalt action authority" @@ -4210,6 +4229,29 @@ pub(crate) mod tests { assert_eq!(represented.len(), 1_000); } + #[test] + fn partitions_twenty_four_hundred_subjects_into_a_two_hundred_forty_cell_cover() { + let value = campaign(2_400, 240); + let started = Instant::now(); + let cover = plan_cover( + &value, + default_demand(&value, "ten-percent expanded-world cover"), + ) + .unwrap(); + assert_eq!(cover.configured_budget, 240); + assert_eq!(cover.effective_budget, 240); + assert_eq!(cover.cells.len(), 240); + let represented = cover + .cells + .iter() + .flat_map(|cell| cell.subject_ids.iter()) + .collect::>(); + assert_eq!(represented.len(), 2_400); + if cfg!(debug_assertions) { + assert!(started.elapsed().as_secs_f32() < 20.0); + } + } + #[test] fn arena_cannot_act_as_a_collective_or_borrow_a_constituents_secret() { let mut value = campaign(2, 1); diff --git a/docs/architecture/ghostlight-multiresolution-agency.md b/docs/architecture/ghostlight-multiresolution-agency.md index 88c399d..16e7cab 100644 --- a/docs/architecture/ghostlight-multiresolution-agency.md +++ b/docs/architecture/ghostlight-multiresolution-agency.md @@ -61,9 +61,10 @@ typed partition inputs. `SimulationCell` is always disposable and rebuildable. elaboration, and later consumer-requested scale changes use the same demand derivation and canonical actionability count. Each titled worker proposes at most one structural operation at a time; deterministic admission and kernel - commit remain unchanged. Complexity rises through grounded Gestalt fission, - institution creation, or promotion of an individual into an active Actor - leaf, never through unelaborated census or roster rows. + commit remain unchanged. The current scale loop raises complexity through + grounded Gestalt fission or promotion of an individual into an active Actor + leaf, never through unelaborated census or roster rows. Institution admission + remains compiler-owned rather than being smuggled into this loop. - **Cut line:** fixed elaboration-pass count is not a world-scale owner. It may bound which jurisdictions are being worked in one run, but it cannot declare the latent world sufficiently populated. Provider concurrency controls only @@ -83,11 +84,12 @@ The mutation budget is not a cold-prompt budget. Each titled elaborator owns a resumable working session containing its current frontier, unresolved leads, recent admitted mutations, exact rejection findings, and title mandate. The canonical world remains long-term memory. Bounded retrieval supplies older -relevant state. When a session exceeds its context threshold, an agentic -compaction pass emits a typed checkpoint bound to exact world commits; the raw -conversation is discarded as authority and the next turn appends from the -checkpoint. Scheduler frequency remains proportional to slider share across -these sequential turns. +relevant state. After each round, every title that committed work receives one +agentic compaction turn. It emits a typed checkpoint bound to the exact admitted +commit ancestry; raw conversation is never authority, and the next turn appends +from the checkpoint. This round boundary is the current bounded context policy. +Scheduler frequency remains proportional to slider share across sequential +turns. Round effort is proportional to unresolved pressure rather than presumed model yield: `ceil(active_cell_budget * deficit / target)`, zero when the target is diff --git a/docs/public-architecture/Agents and model stages.md b/docs/public-architecture/Agents and model stages.md index 3540cd1..e1dcab9 100644 --- a/docs/public-architecture/Agents and model stages.md +++ b/docs/public-architecture/Agents and model stages.md @@ -73,6 +73,16 @@ exact assignment and frozen namespace. Wave admission resolves conflicts; an independent semantic verifier reviews the inhabited candidate; `WorldKernel` alone commits it. +At latent-world scale, the same titled sessions also receive +`world-complexity--fission` or +`world-complexity-<title>-individuate` assignments. Each call may subdivide one +active Gestalt or promote one grounded consequential person. Deterministic +fission/individuation validation and the existing kernel commands remain the +only admission owners. After every productive round, +`world-elaborator-<title>-session-compaction` distills that title's frontier and +unresolved leads while the harness reattaches exact commit ancestry. Compacted +memory can guide later proposals but cannot create subjects or facts. + ## Foreground perception, response, and action | Stage | Tier | Purpose | Output and downstream gate | diff --git a/docs/public-architecture/Runtime pipelines.md b/docs/public-architecture/Runtime pipelines.md index a557cc5..dc0b837 100644 --- a/docs/public-architecture/Runtime pipelines.md +++ b/docs/public-architecture/Runtime pipelines.md @@ -68,15 +68,19 @@ description: End-to-end Ghostlight flows from campaign negotiation to newspapers provider concurrency remain separate controls. 3. The elaboration scheduler dispatches titled workers in proportion to their user-controlled slider shares. -4. Each worker proposes exactly one additive place, route, fact, population, - institution, relation, migration edge, or civic-system operation. -5. Deterministic validation resolves write conflicts and verifies the complete - candidate. An independent civic verifier reviews inhabited apparatus. -6. `WorldKernel` alone admits the finalized operation set. - -The fixed-pass full-world driver is currently being replaced by the scale -demand described above. The derivation is implemented; subject-producing, -resumable budget expenditure remains active work and is not claimed complete. +4. Locality passes propose exactly one additive place, route, fact, + institution, relation, or civic operation. Complexity passes propose one + Gestalt fission or one grounded individual promotion against a distinct + frozen parent. +5. Complexity proposals run concurrently, then rebase only when their exact + parent state is unchanged and serialize through `WorldKernel`. Successful + commits are checkpointed individually; a retry replays only failed calls. +6. Every title that committed work receives one bounded agentic compaction + turn. Its narrative frontier is checkpointed beside deterministic commit + ancestry, so provider-session eviction cannot erase or rewrite history. +7. The driver recounts canonical active agency leaves and derives another + round until the target cover ratio is met. Resolution then builds its + disposable cell cover independently. ## Newspaper @@ -92,4 +96,3 @@ resumable budget expenditure remains active work and is not claimed complete. 5. Deterministic provenance binds every factual assertion to exact committed sources. Errors found after close become correction memory for a later edition rather than an infinite rewrite loop. - diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 9beac0a..357a5cc 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -1679,9 +1679,10 @@ materializing a `NewsIssue`. 2. Preserve the delivered Run 60 PDF and its frozen-copy verification as the earlier baseline, plus the final Run 61 style/flow artifact, v2 manifest, grammar, hashes, frozen copy, and art assets recorded above. -3. Do not resume stopped Run 75. Revise the current local scale derivation - before integrating it. `WorldScaleIntent` and `WorldElaborationDemand` now - derive a numeric 2,400-subject target from 240 cells at ten-percent cover, +3. Do not resume stopped Run 75. Exact pushed + `df66ec989c1e44a7a8b21ed159e9589778426238` defines `WorldScaleIntent` and + `WorldElaborationDemand`, deriving a numeric 2,400-subject target from 240 + cells at ten-percent cover, but this is not yet the required complexity proof: a flat population roster cannot satisfy the target. `round_mutation_budget` is `ceil(active_cell_budget * deficit / target)`: 240 cells with a @@ -1689,13 +1690,16 @@ materializing a `NewsIssue`. bounded round pressure, not a model-call or session count and not an assumption that one mutation yields one subject. Elaborator context now keeps stable identity and mandate in a prefix separate from the bounded - dynamic workbench snapshot, but persistent elaboration checkpointing and - compaction are not implemented. Define a deterministic measure of admitted - causal complexity and an iterative loop that fissions Gestalts, promotes - meaningful individuals and institutions, remeasures after admission, and - continues until the target is met. Do not assume a fixed batch yield or one - model call per useful subject. Add persistence, resume binding, compaction, - and a product-scale fixture around that loop. Keep Resolution as cover owner. Nemesis receives + dynamic workbench snapshot. The current uncommitted cut now persists + digest-chained per-title compacted sessions, proposes both meaningful Gestalt + fission and grounded named-person promotion, admits only through existing + WorldKernel commands, remeasures canonical complexity after each round, and + resumes only failed dispatches from the exact frozen schedule. Focused + complexity, session, and resume checks pass. Do not assume a fixed batch + yield or one model call per useful subject. Finish independent architecture + review and the full package/strategic gates, commit and push the exact cut, + then launch a fresh provider-backed product-scale acceptance without + resuming Run 75. Keep Resolution as cover owner. Nemesis receives that cover and assigns causal decision windows inside it; it does not choose cover membership. Preserve Runs 64 through 75 and both live services. This work does not wait for the Delvehold adapter because the Greathold remains an diff --git a/notes/ghostlight-current-system-map.md b/notes/ghostlight-current-system-map.md index 65b0b7b..f14ad90 100644 --- a/notes/ghostlight-current-system-map.md +++ b/notes/ghostlight-current-system-map.md @@ -1270,11 +1270,124 @@ outside this authority. no second region generator or event authority. - **Verification layer:** destination validation and reconciliation bind each candidate before kernel revalidation and commit. End-to-end acceptance also - requires all requested realms to enter locality elaboration, the bounded + requires all requested realms to enter locality elaboration, iterative + complexity rounds to satisfy the consumer scale intent, the bounded multiresolution cover, strategic waves, and grounded newspaper projection. Runs 64 and 65 stopped before that claim was established and remain failure evidence rather than accepted full-world runs. +#### Iterative latent-world complexity and elaborator continuity + +- **Owner:** the strategic acceptance driver owns round orchestration, + deterministic titled-elaborator scheduling, checkpoint publication, and + bounded termination. `WorldScaleIntent` is consumer-authored; + `derive_world_elaboration_demand` deterministically owns the target, deficit, + realm shares, and per-round mutation pressure. Each titled elaborator owns + only its compact working frontier. `WorldKernel` remains the sole canonical + mutation owner, and Resolution remains the owner of the later active cover. +- **Inputs:** the admitted campaign after region and locality elaboration; its + active-cell entitlement; a target cover ratio; equal acceptance-driver realm + weights; a weighted titled-elaborator profile; bounded parallelism and round + limits; active, simulation-eligible Gestalt leaves without a currently + materialized member; the prior per-title session checkpoint; and the exact + frozen parent state, members, profile, and local relations for each assigned + mutation. Scheduler title deterministically selects the proposal lane: + Hearth and Veil individuate one consequential member; the other six titles + fission the assigned population along their fixed agency axis. +- **Outputs:** each round publishes an immutable frozen preview with demand, + wave and schedule receipts, exact parent bindings, proposals, and model + receipt hashes; then one immutable mutation checkpoint per sequentially + admitted fission or individuation; one compacted checkpoint for each title + that obtained an admitted mutation in that round; and a terminal round + checkpoint carrying the scheduler state, mutation paths, the accumulated + per-title session checkpoints, and remeasured + actionable-subject count. The final count and round reports are acceptance + metadata, not canonical world state. +- **Derived state:** actionable complexity is the count of canonical active, + simulation-eligible agency leaves. Dormant member rows, census texture, + model calls, dispatches, mutation budget, and compacted prose do not satisfy + the target. A session checkpoint's frontier summary, unresolved leads, + rejection findings, digest chain, and recent commit IDs are bounded steering + memory; the campaign and kernel commit receipts remain truth. Resolution + cover membership and Nemesis decision windows are downstream derivations and + do not feed back into complexity admission authority. +- **Forbidden writers:** elaborators, session compaction, the scheduler, + demand derivation, preview files, round files, and acceptance metadata cannot + write campaign state, declare a target satisfied, allocate the Resolution + cover, or turn narrative memory into facts. A fission proposal cannot approve + or commit itself, invent evidence, promote raw roster rows, or rewrite a + parent. An individuation cannot invent a population, duplicate an existing + actor or member identity, materialize itself, or acquire relationships to + nonexistent subjects. Sequential commits may update only the optimistic + revision of a frozen fission proposal after the exact parent binding remains + unchanged; individuation instead revalidates its exact Gestalt version and + location against current state. +- **Shared paths:** all round workers use the existing generic elaborator + dispatcher and weighted schedule. Every proposal passes the existing + fission or individuation validator and the existing + `WorldCommand::FissionGestalt` or `WorldCommand::IndividuateGestaltMember` + mailbox. `resolution::validate_gestalt_individuation` is the single local + authority for member identity, parent version, exact location, bounds, and + relationship targets; strategic action-bound selection and direct kernel + admission both reuse it. Direct individuation then follows the ordinary + presence path: `apply_individuation` inserts the canonical member delta and + promotes it into an Actor, `commit_gestalt_presence` calls + `ensure_agency_profiles`, and the new active simulation-eligible actor profile + becomes visible to `canonical_actionable_subject_count`. Parallel workers + read one frozen campaign; commits serialize through WorldKernel. Unrelated + earlier fissions may be rebased, + while any change to the assigned parent, its profile, or its members rejects + the later proposal instead of silently reconciling it. + Compaction consumes only admitted commit journals plus bounded rejection + findings, then the resulting title-bound checkpoint is supplied as context + to the next round. +- **Cut line:** this cut reuses Gestalt fission, strategic Gestalt + individuation, WorldKernel admission, model receipts, the generic scheduler, + and immutable acceptance checkpoints. It adds no second population or member + insertion path, campaign store, parallel commit owner, cover allocator, or + transcript-shaped session log. The prior partial-wave + checkpoint remains recovery for one frozen dispatch partition; it is not + elaborator memory. Compact checkpoints replace accumulated working history + without replacing canonical commits. +- **Verification layer:** checkpoint shape and digest bind title, session, + campaign, target location, generation, world revision, prior checkpoint, and + bounded narrative fields. Frozen parent digests make conflicting parallel + mutations uncommittable. Existing fission validation proves lineage, child + partitioning, resource custody, and member transfer; shared individuation + validation proves active parent and location, exact version, unique bounded + identity, valid relationships, and non-materialized member state. WorldKernel + revalidates either lane before atomic mutation. Each round must strictly + increase the canonical actionable count; completion requires a freshly + derived zero deficit rather than exhaustion of calls or rounds. Focused tests cover scale + arithmetic, checkpoint tampering and cross-title rejection, exact compaction + ancestry, assigned-parent validation, and safe revision rebasing. +- **Failure and resume:** a provider failure publishes an immutable + round-failure generation with the exact completed and failed dispatches and + receipts, then stops that run. Explicit resume rehydrates the latest failure, + preserves completed invocations, and invokes only the failed original + dispatches through `resume_elaboration_wave`; repeated failures publish + numbered generations without changing the frozen schedule. A published + successful round preview may also be reused on explicit resume. Existing + mutation checkpoints suppress replay, per-title compaction checkpoints + suppress recompaction, and consecutive completed round checkpoints restore scheduler + fairness and session memory before the first unfinished round. Missing + eligible parents, stale or malformed checkpoints, changed parent bindings, + zero-growth rounds, and a nonzero deficit at the configured round ceiling are + terminal failures. Canonical CultCache state, not the checkpoint prose, + decides whether already admitted mutations exist after interruption. + +Two boundaries remain intentionally narrow in this acceptance-driver cut. One +session checkpoint exists per title but is currently anchored to the first +admitted jurisdiction, while assignments may mutate parents elsewhere; it is +not yet a per-realm memory topology. Fission and named-member individuation are +live, but institution promotion is not. Dormant member rows still do not count; +the individuation lane earns its increment by atomically promoting the admitted +member into an Actor and deriving that Actor's active agency profile through the +shared presence-commit path. +Architecture claims that complexity has no production caller, no durable +elaborator compaction owner, no partial-failure resume, or only a fission +proposal lane are stale. + The strategic acceptance runner exercises this path as a deliberate hybrid. The existing destination compiler first commits the complete civic foundation for one canonical locality. A second revision-bound titled wave then adds one diff --git a/state/map.yaml b/state/map.yaml index ed7b587..ec04e05 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -329,8 +329,8 @@ current_status: provider_acceptance_checkpoint: Exact pushed commit `139b8a6` completed Run 60 under `character-newsroom.v10` without world or per-wave replay. Its acceptance witness and terminal status bind the completed page and exact resume lineage. The independently dispatched blind reviewer, shown only the reader-facing fantasy newspaper, read it as a real left-populist civic broadsheet and did not immediately identify procedural generation, so the narrative reverse-Turing criterion passes. The review's substantive criticism is that the three stories feel like three rewrites of one briefing; accepted Run 60 remains immutable. The run used 96,902 prompt tokens and reported zero cache hits. Its delivered typeset artifact is `output/pdf/canopy-ledger-run-60-front-page.pdf`; frozen-source and visual verification remain accepted. Exact pushed `bc2ca39` then produced frozen-fact newsroom-only Run 61 Issues 13, 15, 16, 17, and 18 without world or wave model replay. Provider output proves `special_issue` convergence in Issues 13 and 15, independent `general_issue` beats in Issues 16 through 18, and assignment-selector cache hits. Blind review of Issues 13, 15, 16, and 17 passes both distinct recurring voices and issue-shape diversity, recognizing Ossan, Mera, Corin, and Lysa's biases plus modest cross-issue evolution. Run 62 exercised v12 without world or wave replay and failed only because two lead articles proposed invalid datelines; recurring reporter calls still recorded zero cache hits. Run 63 used exact pushed v13 `a52d57b`; Issues 17 and 18 completed before root stopped the final weekly recomposition, both repeated bylines again recorded zero cache hits, and live services remained unchanged. Preserve Runs 61 through 63 as stopped or completed immutable evidence. Copy defects remain later deadline-correction work rather than a reason to reopen accepted issue artifacts. implementation_checkpoint: Exact pushed v13 `a52d57b` keeps one stable reporter action schema, places a common stable house charter before recurring identity and dynamic assignment, and projects deterministic `allowed_datelines` from cited records while retaining copy-desk factual authority and deterministic cited-place admission; 480 library tests and the all-target check pass. Run 63 falsifies reporter-cache pursuit as a useful acceptance target for sporadic independent filings. The proposed v14 cache-floor prompt growth was removed. Append-only agent contexts remain the natural cache beneficiary; accepted Run 60 remains immutable. The strategic cut extracts one shared `validate_strategic_individuation_proposals` owner used by resolution validation and by the scheduler before it returns an optional proposal. An invalid optional identity emits a semantic-invalid receipt and produces no individuation instead of aborting the recoverable wave. Focused valid and invalid regressions pass, and exact-source Run 68 exercises the corrected provider path through twelve committed waves; no further validator implementation is pending. The newsroom-only cut adds a navigation-only directory of completed public changes grouped by period and exact source timestamps to new v14 audit citations. The directory derives context from canonical records and gains no fact or world authority. Legacy empty source times are omitted from both rendering and serialization, preserving inherited v13 receipt bytes and digests; new v14 nonempty source times remain rendered and serialized. Exact-source Run 73 proves that compatibility path and final recomposition mechanically. Current source gives the assignment editor bounded full-ledger queries and explicitly asks it to search sideways for opposition and countermoves; Run 73 falsifies the stronger assumption that this access and instruction alone guarantee balanced selection. Exact pushed v15 source `b6787d909bd79b68ed3a4d143b7f6dd438e00fa2` binds accountability, opposition, and counter-narrative pitches to two distinct named parties and selected citations through a typed conflict axis, and preserves canonical ledger order. Run 74 falsifies the stronger v15 assumption: its lone accountability pitch used the same transfer citation for cultivators and a passive Tribunal, while four of five pitches avoided the adversarial axis through lead or consequence functions. Two cited names did not prove two moves. Exact pushed v16 `86fe6ed89d51da26b65ab6a031608075840b1527` binds each adversarial axis to two distinct cited public moves or positions and rejects one record presented as both sides; it adds no event writer, judge, process, dependency, or persistent authority. Formatting, 27 focused newspaper tests, 484 full library tests, and 16 strategic-smoke tests pass. full_world_acceptance_checkpoint: Run 68 at exact source `69c811a2669fc38f19f9199bf57088dc250bfc3e` is mechanically complete at world revision 27 with 12/12 strategic waves, 240 events, 514 public news rows, and a final newspaper. Independent editorial and grounding reviews both fail. Earlier per-wave papers prove the immutable record already contains dramatic completed facts, including an organ breaching the rail capital, a dead pump, and families crossing borders; the final paper failed to make that committed change legible. Preserve Run 68 unchanged. Run 69 at source `84b31e57a462710eb939c4559e0437eb5d6a7a28` failed before any model call when immutable recomposition verification encountered an empty rendered `Source time:` line in inherited v13 per-wave issues. Run 70 at source `ec45952b843e102dc2ebddda3a3bbb4058687175` also failed before any model call because v14 serialization changed the legacy recomposition digest. Exact-source Run 73 `b827d897b9579c2091a67c363d35b8695288ba2f` is terminal complete at `/var/lib/gamecult/ghostlight-dungeon/acceptance/full-world-delvehold-b827d89-73`: world revision 27, 12/12 waves, 240 events, 514 news rows, inherited artifacts byte-identical to Run 68, manifest valid, and archive SHA-256 `090d05f304c8f3d33c9dccd728bffbf3e5dc2969a7aeeffc2f9d7bafe701ac8a`. Exact-source Run 74 `b6787d909bd79b68ed3a4d143b7f6dd438e00fa2` is mechanically complete at `/var/lib/gamecult/ghostlight-dungeon/acceptance/full-world-delvehold-b6787d9-74`: revision 27, 12/12 waves, 240 events, 514 news rows, Run 68 inherited artifacts byte-identical, manifest valid, unchanged live services, and archive SHA-256 `957b11a5d584d27d23bf4d50ed1fbc8d067faf67953b03f80705bfb9587c496d`. Independent editorial review fails: the page has a coherent throughline and sharp prose but no sustained adversarial narrative; opposing decision-makers, motives, responses, and countermoves are largely absent, scandal and public reaction are missing, lived costs remain abstract, and the result reads as polished minutes with conclusions. Its post-press correction notice has two items: `The corridor had begun closing hours earlier` overstates a source that says the prolonged oath-route closure was diverting arrivals six hours before the breach; `no relief or assignment of liability has followed` must narrow to `no tribunal remedy is recorded yet`. Run 75 launched at exact source `86fe6ed89d51da26b65ab6a031608075840b1527` under the superseded 240-cell-only acceptance shape and was stopped cleanly at the operator's scale correction. Preserve `/var/lib/gamecult/ghostlight-dungeon/acceptance/full-world-delvehold-86fe6ed-75` as stopped non-acceptance evidence: preflight, world-region and titled-elaboration checkpoints, a wave-one cell terminal checkpoint, partial pulses 01/02, and two rejected pulse receipts exist. `ghostlight-full-world-run75.service` invocation `86bfe6a3ef504a7d99f579b3d67710ab` is inactive/dead after explicit stop; live services remain unchanged. Do not claim terminal success or failure. Preserve Runs 64 through 75. Mechanical completion of the earlier world is proven, but final newspaper acceptance under the corrected scale target is not. - scale_checkpoint: The active 240-cell entitlement is an attention budget, not the world-size claim. The approximately 2,400 potentially acting entities are a target for causally meaningful latent complexity, not a raw population or roster count. Multiresolution Gestalts compress the unresolved population; repeated admitted elaboration must fission them and promote individuals and institutions whose agency, relationships, resources, pressures, or authority can actually participate in consequences, then remeasure the deficit. The current uncommitted Body defines consumer-authored `WorldScaleIntent` and deterministic `WorldElaborationDemand`; at 240 cells and 1,000 cover basis points it derives a numeric 2,400-subject target, current-subject deficit, and weighted per-realm shares. Its `round_mutation_budget` is `ceil(active_cell_budget * deficit / target)`: a 2,320/2,400 deficit under 240 cells yields 232 demanded mutations for the next round. This is bounded round pressure, not model-call/session count and not an assumption that one mutation yields one subject. The elaborator context also separates a stable identity-and-mandate prefix from the bounded dynamic workbench snapshot. The cut is not integrated or resumable: no production caller, persistent elaboration checkpoint or compaction owner, or product-scale fixture proves that the counted subjects are meaningful. Resolution owns derived cover membership. Nemesis receives an existing cover and assigns bounded causal decision windows among eligible responders; it does not allocate that cover. + scale_checkpoint: The active 240-cell entitlement is an attention budget, not the world-size claim. The approximately 2,400 potentially acting entities are a target for causally meaningful latent complexity, not a raw population or roster count. Multiresolution Gestalts compress the unresolved population; repeated admitted elaboration must fission them and promote individuals and institutions whose agency, relationships, resources, pressures, or authority can actually participate in consequences, then remeasure the deficit. Exact pushed `df66ec989c1e44a7a8b21ed159e9589778426238` defines consumer-authored `WorldScaleIntent` and deterministic `WorldElaborationDemand`; at 240 cells and 1,000 cover basis points it derives a numeric 2,400-subject target, current-subject deficit, and weighted per-realm shares. Its `round_mutation_budget` is `ceil(active_cell_budget * deficit / target)`: a 2,320/2,400 deficit under 240 cells yields 232 demanded mutations for the next round. This is bounded round pressure, not model-call/session count and not an assumption that one mutation yields one subject. The current uncommitted scale-loop cut gives titled elaborators stable identity-and-mandate prefixes plus bounded dynamic workbench snapshots, proposes both Gestalt fission and grounded named-person promotion, commits only through existing WorldKernel commands, remeasures canonical complexity after each round, resumes only failed dispatches from an exact frozen schedule, and compacts admitted journals into digest-chained per-title session checkpoints. Focused complexity, session, and resume checks pass. Full package verification, independent architecture review, commit/push, and provider-scale acceptance remain pending. Resolution owns derived cover membership. Nemesis receives an existing cover and assigns bounded causal decision windows among eligible responders; it does not allocate that cover. presentation_checkpoint: The historical press-layout and seed-ownership split are complete. `notes/historical-newspaper-layout-grammar.md` remains the durable grammar. Manifest v2 at `output/tex/canopy-ledger-run-61-style-1847-flow-723.manifest.toml` independently binds `style_seed=1847`, `flow_seed=723`, frozen source SHA-256 `8f195140f52a40ba705d6a66987146a1500ae89668e5d82b01d1792eb3afb882`, and the final artifact `output/pdf/canopy-ledger-run-61-style-1847-flow-723.pdf`, SHA-256 `a457f4b1702a7a52480e42fce0039f0dbe677ff32958e98f1c412b346237190c`. An identical seed pair produces byte-identical TeX and PDF; changing only flow preserves the exact style section while materially changing a plausible layout, and changing only style preserves flow topology. Cut-first and cut-midstory templates pass visual inspection; the failed split-card template is deleted. Frozen copy/assets, actual PDF `/BM /Multiply`, and economic-layer advertising authority remain invariant. public_reference_checkpoint: Public architecture reference is complete. Canonical Ghostlight commit `15ea0f0` owns five pages under `docs/public-architecture` covering overview, authority, pipelines, 43 named production stages, and eight titled elaborators. Site commit `ea0b026` publishes exact projections under `F:\Projects\GhostlightDungeon-site\content\Documentation`, adds the sync/check script, explorer and table-of-contents navigation, scoped documentation layout, and homepage Architecture link. Local Quartz build and visual browser QA pass. GitHub Pages workflow `33408004480` succeeded. `https://ghostlight.gamecult.org/Documentation/` and the extensionless `Documentation/Agents-and-model-stages` route are live; the stage page exposes seven tables and 51 rows. Ghostlight remains technical authority; the site repository owns public composition and deployment. - next_action: Do not resume Run 75. Revise the current local `WorldScaleIntent` / `WorldElaborationDemand` cut before integration so the target measures causally meaningful world complexity rather than population rows. Define the deterministic admitted-complexity measure, the iterative loop that fissions Gestalts and promotes meaningful individuals or institutions, and the remeasurement boundary after each admitted round. Keep `round_mutation_budget` as bounded round pressure separate from model-call/session count and assumed yield; no roster insertion or fixed batch yield may satisfy the deficit. Preserve the stable elaborator identity-and-mandate prefix and bounded dynamic workbench snapshot, then add the missing persistent checkpoint and compaction owner. Keep the 2,400-complexity target separate from the 240-cell attention entitlement, keep Resolution as cover owner, and let Nemesis assign causal decision windows only inside admitted cover. Bind the iterative plan to resume and a product-scale fixture proving roughly ten-percent active cover while the latent world continues to elaborate. Run focused and full verification, update the Body map and Mind, commit, and push before any fresh full-world run. Preserve stopped Run 75, immutable Runs 64 through 74, both live services, the completed public reference, the two-seed press checkpoint, and the economic-layer advertising boundary. + next_action: Do not resume Run 75. Review the uncommitted iterative complexity cut against the ownership map, run the full focused/package/strategic gates, and correct any findings without weakening failed-dispatch-only resume, digest-chained per-title compaction, WorldKernel-only commit, or post-round canonical remeasurement. Then commit and push the exact source and launch a fresh provider-backed product-scale acceptance; prove meaningful Gestalt fission and grounded individual promotion progress toward the 2,400-complexity target under the 240-cell entitlement without roster padding, assumed batch yield, or replay of Run 75. Preserve Resolution cover ownership, Nemesis's bounded causal-window role, immutable Runs 64 through 75, both live services, the completed public reference, the two-seed press checkpoint, and the economic-layer advertising boundary. 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.