diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-live-turn-smoke.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-live-turn-smoke.rs index 1b83a92..6d7a0e9 100644 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-live-turn-smoke.rs +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-live-turn-smoke.rs @@ -53,7 +53,7 @@ async fn main() -> anyhow::Result<()> { store.insert( "persona_stage_receipt.v1", "ghostlight.persona_stage_receipt.v1", - &receipt.output_hash, + receipt.storage_key(), receipt, )?; } @@ -187,5 +187,12 @@ fn four_actor_campaign() -> ghostlight_dungeon::domain::Campaign { gestalts: BTreeMap::new(), gestalt_members: BTreeMap::new(), pending_world_proposals: vec![], + agency_profiles: BTreeMap::new(), + agency_relations: BTreeMap::new(), + gestalt_lineages: BTreeMap::new(), + resolution_policy: Default::default(), + resolution_pins: BTreeMap::new(), + resolution_cover: None, + strategic_tick_count: 0, } } diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs index b352391..838ed79 100644 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs @@ -12,7 +12,8 @@ async fn main() -> anyhow::Result<()> { kernel::{CommandResult, WorldKernel}, model::{DeepSeekPort, ModelPort}, persistence::CampaignStore, - scheduler::propose_strategic_tick, + scheduler::propose_resolution_wave, + turn::SnapshotPermit, }; use std::{path::PathBuf, sync::Arc, time::Instant}; @@ -30,29 +31,43 @@ async fn main() -> anyhow::Result<()> { store.create_campaign(&campaign, &[], &[])?; let model: Arc = Arc::new(DeepSeekPort::from_machine_dpapi(secret)?); let started = Instant::now(); - let (plan, output) = propose_strategic_tick(model.as_ref(), &campaign).await?; + let output = propose_resolution_wave( + model, + Arc::new(SnapshotPermit::new_resolution( + store.clone(), + campaign.id, + campaign.revision, + campaign.resolution_policy.resolution_epoch, + )), + &campaign, + ) + .await?; + let plan = ghostlight_dungeon::resolution::validate_and_resolve_wave(&campaign, &output.wave)?; if plan.institution_actions.is_empty() && plan.gestalt_actions.is_empty() && plan.actor_moves.is_empty() { anyhow::bail!( "strategic model proposed no material offscreen change: {}", - output.narrative + "all cells explicitly chose inaction" ); } - store.insert( - "persona_stage_receipt.v1", - "ghostlight.persona_stage_receipt.v1", - &output.receipt.output_hash, - &output.receipt, - )?; + for stage in &output.stages { + store.insert( + "persona_stage_receipt.v1", + "ghostlight.persona_stage_receipt.v1", + stage.receipt.storage_key(), + &stage.receipt, + )?; + } let kernel = WorldKernel::start(store.clone()); let committed = kernel .command(WorldCommand::AdvanceStrategicTick { expected_revision: 0, source: TickSource::Scheduler, - plan: Some(plan.clone()), - model_receipt_hash: Some(output.receipt.output_hash.clone()), + plan: None, + model_receipt_hash: Some(output.aggregate_receipt_hash.clone()), + resolution_wave: Some(output.wave.clone()), }) .await?; let CommandResult::Committed { @@ -71,7 +86,7 @@ async fn main() -> anyhow::Result<()> { "schema":"ghostlight.live_strategic_smoke.v1", "campaign_id":campaign.id, "elapsed_seconds":started.elapsed().as_secs_f64(), - "model_receipt_hash":output.receipt.output_hash, + "model_receipt_hash":output.aggregate_receipt_hash, "plan":plan, "event_count":advanced.events.len(), "news_count":advanced.news.len(), @@ -111,7 +126,7 @@ fn strategic_campaign() -> ghostlight_dungeon::domain::Campaign { let now = Utc::now(); let mut player = actor("player", "Mediator", "room", "rest"); player.knowledge.insert("station radio".into()); - Campaign { + let mut campaign = Campaign { schema: "ghostlight.campaign.v1".into(), id: uuid::Uuid::new_v4(), name: "Strategic live acceptance".into(), @@ -221,5 +236,25 @@ fn strategic_campaign() -> ghostlight_dungeon::domain::Campaign { )]), gestalt_members: BTreeMap::new(), pending_world_proposals: vec![], + agency_profiles: BTreeMap::new(), + agency_relations: BTreeMap::new(), + gestalt_lineages: BTreeMap::new(), + resolution_policy: Default::default(), + resolution_pins: BTreeMap::new(), + resolution_cover: None, + strategic_tick_count: 0, + }; + ghostlight_dungeon::resolution::ensure_agency_profiles(&mut campaign); + for profile in campaign.agency_profiles.values_mut() { + profile.information_channels.insert("station radio".into()); } + if let Some(board) = campaign.agency_profiles.get_mut("board") { + board.location_ids.extend(["depot".into(), "yard".into()]); + board + .facets + .entry(AgencyAxis::Geography) + .or_default() + .extend(["depot".into(), "yard".into()]); + } + campaign } diff --git a/crates/ghostlight-dungeon/src/compiler.rs b/crates/ghostlight-dungeon/src/compiler.rs index d6d4403..bc81bce 100644 --- a/crates/ghostlight-dungeon/src/compiler.rs +++ b/crates/ghostlight-dungeon/src/compiler.rs @@ -1,6 +1,7 @@ use crate::{ domain::{ - ActorState, BranchOrigin, Campaign, FactScope, GestaltMemberDelta, GestaltPersonaState, + ActorState, AgencyAxis, AgencyRelation, AgencyRelationKind, AgencySubjectKind, + BranchOrigin, Campaign, FactScope, GestaltMemberDelta, GestaltPersonaState, InstitutionState, Location, VaultEvidenceReceipt, WorldClock, WorldCompilePreview, WorldFact, }, @@ -60,6 +61,14 @@ pub struct SelectedStart { pub role: RoleSuggestion, } +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct GestaltFissionRequest { + pub parent_gestalt_id: String, + pub partition_axis: AgencyAxis, + pub requested_partition_values: Vec, + pub reason: String, +} + #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct SuggestedOpenings { pub openings: Vec, @@ -110,6 +119,29 @@ struct CompiledSeed { gaps: Vec, branch_assumptions: Vec, opening_narration: String, + #[serde(default)] + agency_profiles: Vec, + #[serde(default)] + agency_relations: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +struct CompiledAgencyProfile { + subject_id: String, + subject_kind: AgencySubjectKind, + collective_authority_id: Option, + facets: BTreeMap>, + location_ids: BTreeSet, + information_channels: BTreeSet, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +struct CompiledAgencyRelation { + id: String, + from_subject_id: String, + to_subject_id: String, + kind: AgencyRelationKind, + strength: u8, } #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] @@ -119,6 +151,15 @@ struct CompiledExpansionSeed { gaps: Vec, } +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +struct CompiledFissionSeed { + children: Vec, + child_partition_values: BTreeMap, + #[serde(default)] + member_child_assignments: BTreeMap, + gaps: Vec, +} + pub struct WorldCompiler { vault: Arc, model: Arc, @@ -201,9 +242,9 @@ impl WorldCompiler { 3, ) .await?; - let receipts = self.retrieve_all(&queries, &start.when, 10).await?; + let receipts = self.retrieve_all(&queries, &start.when, 18).await?; let base_prompt = format!( - "Compile a bounded playable region and institutional pressure graph. Emit only supported canon facts; mark reversible texture provisional_local and list material gaps. The player location and every actor location must exist. Every route destination must exist, travel time must be positive, clocks need positive thresholds, and the player id must be unique. Represent populations that can act collectively (villages, crews, crowds, departments, corporations) as gestalt Personas. Seed a small roster of plausible durable member identities for people the player may encounter; member deltas contain only departures from their gestalt baseline and begin dematerialized. Do not duplicate a gestalt member in actors. Keep named plot-critical people as ordinary actors. Every gestalt home location and member gestalt reference must exist. START:\n{}\nEVIDENCE:\n{}", + "Compile two deliberately different scales. First, compile a bounded playable region with stable topology, local actors, populations, and clocks. Second, compile a global agency skeleton covering every source-supported major power, coarse region, institution, important relation, information channel, and strategic pressure relevant to this era. Major remote powers belong in institutions and agency profiles; do not eagerly invent their settlements, routes, or people. Agency profile facets use exactly geography, ideology, authority, economy_role, species_body, and information. Agency relations use exact supplied subject IDs. Emit only supported canon facts; mark reversible texture provisional_local and list material gaps. The player location and every actor location must exist. Every route destination must exist, travel time must be positive, clocks need positive thresholds, and the player id must be unique. Represent populations that can act collectively (villages, crews, crowds, departments, corporations) as gestalt Personas. Seed a small roster of plausible durable member identities for people the player may encounter; member deltas contain only departures from their gestalt baseline and begin dematerialized. Do not duplicate a gestalt member in actors. Keep named plot-critical people as ordinary actors. Every gestalt home location and member gestalt reference must exist. Every non-player actor, institution, and gestalt must have exactly one agency profile; location IDs must already exist. Cross-faction relations never imply shared authority. START:\n{}\nEVIDENCE:\n{}", serde_json::to_string(&start)?, evidence_text(&receipts) ); @@ -269,6 +310,165 @@ impl WorldCompiler { .await } + pub async fn compile_fission( + &self, + campaign: &Campaign, + request: GestaltFissionRequest, + ) -> Result<( + crate::domain::GestaltFissionPreview, + Vec, + Vec, + )> { + let parent = campaign + .gestalts + .get(&request.parent_gestalt_id) + .ok_or_else(|| anyhow!("fission parent is unknown"))?; + let requested: BTreeSet<_> = request + .requested_partition_values + .iter() + .map(|value| value.trim().to_ascii_lowercase()) + .collect(); + if request.reason.trim().is_empty() + || requested.is_empty() + || requested.len() != request.requested_partition_values.len() + || requested.contains("other/unknown") + || request + .requested_partition_values + .iter() + .any(|value| value.trim().is_empty()) + { + return Err(anyhow!( + "fission request needs distinct named cuts and a reason" + )); + } + let subject = serde_json::json!({ + "request":request, + "parent":parent, + "member_deltas":campaign.gestalt_members.values().filter(|member| member.gestalt_id == parent.id).collect::>(), + "campaign_time":campaign.world_time, + "canon_cutoff":campaign.branch_origin.canon_cutoff + }); + let (queries, retrieval_receipt) = self + .plan_queries( + "gestalt_fission_retrieval_plan", + &format!("fission:{}:{}", campaign.id, parent.id), + &serde_json::to_string(&subject)?, + 3, + ) + .await?; + let receipts = self + .retrieve_all(&queries, &campaign.branch_origin.canon_cutoff, 12) + .await?; + let base_prompt = format!( + "Refine one canonical leaf gestalt along exactly the requested facet. Produce one child per requested value plus one mandatory child whose value is exactly 'other/unknown'. Children inherit the parent baseline and contain only justified refinements; every child starts at version 0 and uses an existing campaign location. Do not erase or rewrite member deltas. Assign a member only when evidence or durable existing delta supports the cut; unassigned members will remain in other/unknown. List every material lore gap. This is an approval preview, not a commit. SUBJECT:\n{}\nEVIDENCE:\n{}", + serde_json::to_string(&subject)?, + evidence_text(&receipts), + ); + let schema = serde_json::to_value(schema_for!(CompiledFissionSeed))?; + let mut stages = vec![retrieval_receipt]; + let mut correction = String::new(); + for attempt in 0..2 { + let (value, stage) = self + .structured( + "gestalt_fission_compile", + &format!( + "campaign:{}:revision:{}:fission:{}", + campaign.id, campaign.revision, parent.id + ), + &format!("{base_prompt}{correction}"), + schema.clone(), + receipt_ids(&receipts), + ) + .await?; + stages.push(stage); + let compiled: CompiledFissionSeed = serde_json::from_value(value)?; + let residual_child_id = compiled + .child_partition_values + .iter() + .find(|(_, value)| value.trim().eq_ignore_ascii_case("other/unknown")) + .map(|(id, _)| id.clone()); + let gaps = compiled.gaps.clone(); + let evidence_receipt_ids = receipt_ids(&receipts); + let affected_sources: Vec<_> = receipts + .iter() + .flat_map(|receipt| { + receipt + .witnesses + .iter() + .map(|witness| witness.source_id.clone()) + }) + .collect::>() + .into_iter() + .collect(); + let canon_candidates = gaps + .iter() + .enumerate() + .map(|(index, gap)| crate::domain::CanonCandidate { + schema: "ghostlight.canon_candidate.v1".into(), + id: format!( + "canon-candidate:{}:fission:{}:{}", + campaign.id, + parent.id, + index + 1 + ), + originating_campaign_id: campaign.id, + gap: gap.clone(), + evidence_receipt_ids: evidence_receipt_ids.clone(), + conflicts: vec![], + proposed_wording: format!( + "Clarify population division for {}: {gap}", + parent.name + ), + affected_vault_sources: affected_sources.clone(), + status: "review".into(), + }) + .collect(); + let preview = 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: request.partition_axis.clone(), + children: compiled.children, + child_partition_values: compiled.child_partition_values, + residual_child_id: residual_child_id.unwrap_or_default(), + member_child_assignments: compiled.member_child_assignments, + evidence_receipt_ids, + gaps, + canon_candidates, + requires_approval: true, + }; + let returned_values: BTreeSet<_> = preview + .child_partition_values + .values() + .map(|value| value.trim().to_ascii_lowercase()) + .filter(|value| value != "other/unknown") + .collect(); + match crate::resolution::validate_fission(campaign, &preview).and_then(|_| { + if returned_values == requested { + Ok(()) + } else { + Err(anyhow!( + "fission did not preserve the requested enumerated cut" + )) + } + }) { + Ok(()) => return Ok((preview, receipts, stages)), + Err(error) if attempt == 0 => { + correction = format!( + "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS FISSION: {error}\nReturn one corrected complete preview against the same subject and evidence." + ); + } + Err(error) => { + return Err(anyhow!( + "gestalt fission failed local validation after one correction: {error}" + )); + } + } + } + unreachable!() + } + pub async fn compile_destination( &self, campaign: &Campaign, @@ -613,6 +813,8 @@ fn ensure_distinct_openings(items: &[OpeningSuggestion]) -> Result<()> { fn seed_to_campaign(seed: CompiledSeed, receipts: &[VaultEvidenceReceipt]) -> Result { let id = Uuid::new_v4(); + let compiled_agency_profiles = seed.agency_profiles.clone(); + let compiled_agency_relations = seed.agency_relations.clone(); let player_id = seed.player.id.clone(); let now = Utc::now(); let mut actors: BTreeMap<_, _> = seed.actors.into_iter().map(|x| (x.id.clone(), x)).collect(); @@ -645,7 +847,7 @@ fn seed_to_campaign(seed: CompiledSeed, receipts: &[VaultEvidenceReceipt]) -> Re (candidate.id.clone(), candidate) }) .collect(); - Ok(Campaign { + let mut campaign = Campaign { schema: "ghostlight.campaign.v1".into(), id, name: seed.title, @@ -702,7 +904,107 @@ fn seed_to_campaign(seed: CompiledSeed, receipts: &[VaultEvidenceReceipt]) -> Re .map(|x| (x.id.clone(), x)) .collect(), pending_world_proposals: vec![], - }) + agency_profiles: BTreeMap::new(), + agency_relations: BTreeMap::new(), + gestalt_lineages: BTreeMap::new(), + resolution_policy: Default::default(), + resolution_pins: BTreeMap::new(), + resolution_cover: None, + strategic_tick_count: 0, + }; + crate::resolution::ensure_agency_profiles(&mut campaign); + apply_compiled_agency_skeleton( + &mut campaign, + compiled_agency_profiles, + compiled_agency_relations, + )?; + Ok(campaign) +} + +fn apply_compiled_agency_skeleton( + campaign: &mut Campaign, + profiles: Vec, + relations: Vec, +) -> Result<()> { + let expected: BTreeSet<_> = campaign + .agency_profiles + .values() + .filter(|profile| profile.active_leaf && profile.simulation_eligible) + .map(|profile| profile.subject_id.clone()) + .collect(); + if expected.is_empty() && profiles.is_empty() && relations.is_empty() { + return Ok(()); + } + let supplied: BTreeSet<_> = profiles + .iter() + .map(|profile| profile.subject_id.clone()) + .collect(); + let axes = BTreeSet::from([ + AgencyAxis::Geography, + AgencyAxis::Ideology, + AgencyAxis::Authority, + AgencyAxis::EconomyRole, + AgencyAxis::SpeciesBody, + AgencyAxis::Information, + ]); + if supplied != expected || supplied.len() != profiles.len() { + return Err(anyhow!( + "global agency skeleton must profile every non-player actor, institution, and gestalt exactly once" + )); + } + for input in profiles { + let authority_known = input + .collective_authority_id + .as_ref() + .is_none_or(|id| campaign.agency_profiles.contains_key(id)); + let profile = campaign + .agency_profiles + .get_mut(&input.subject_id) + .ok_or_else(|| anyhow!("agency profile references an unknown subject"))?; + let input_axes: BTreeSet<_> = input.facets.keys().cloned().collect(); + if profile.subject_kind != input.subject_kind + || input_axes != axes + || input + .location_ids + .iter() + .any(|id| !campaign.locations.contains_key(id)) + || !authority_known + { + return Err(anyhow!("compiled agency profile is malformed")); + } + profile.collective_authority_id = input.collective_authority_id; + profile.facets = input.facets; + profile.location_ids = input.location_ids; + profile.information_channels = input.information_channels; + profile.evidence_receipt_ids = campaign.branch_origin.evidence_receipt_ids.clone(); + } + let mut relation_ids = BTreeSet::new(); + for input in relations { + if !relation_ids.insert(input.id.clone()) + || input.id.trim().is_empty() + || input.from_subject_id == input.to_subject_id + || !expected.contains(&input.from_subject_id) + || !expected.contains(&input.to_subject_id) + || input.strength == 0 + || input.strength > 100 + { + return Err(anyhow!("compiled agency relation is malformed")); + } + campaign.agency_relations.insert( + input.id.clone(), + AgencyRelation { + schema: "ghostlight.agency_relation.v1".into(), + id: input.id, + from_subject_id: input.from_subject_id, + to_subject_id: input.to_subject_id, + kind: input.kind, + strength: input.strength, + active: true, + evidence_receipt_ids: campaign.branch_origin.evidence_receipt_ids.clone(), + }, + ); + } + Ok(()) } pub fn validate_campaign_seed(c: &Campaign) -> Result<()> { @@ -712,6 +1014,27 @@ pub fn validate_campaign_seed(c: &Campaign) -> Result<()> { if !c.actors.contains_key(&c.player_actor_id) { return Err(anyhow!("player actor is missing")); } + crate::resolution::validate_policy(&c.resolution_policy)?; + crate::resolution::validate_pins(c, &c.resolution_pins)?; + let expected_profiles: BTreeSet<_> = c + .actors + .keys() + .filter(|id| *id != &c.player_actor_id) + .chain(c.institutions.keys()) + .chain(c.gestalts.keys()) + .cloned() + .collect(); + let actual_profiles: BTreeSet<_> = c + .agency_profiles + .values() + .filter(|profile| profile.active_leaf && profile.simulation_eligible) + .map(|profile| profile.subject_id.clone()) + .collect(); + if expected_profiles != actual_profiles { + return Err(anyhow!( + "campaign agency skeleton has incomplete subject coverage" + )); + } for actor in c.actors.values() { if !c.locations.contains_key(&actor.location_id) { return Err(anyhow!( @@ -746,10 +1069,10 @@ pub fn validate_campaign_seed(c: &Campaign) -> Result<()> { } } for location in c.locations.values() { - if let Some(parent) = &location.container_id { - if parent == &location.id || !c.locations.contains_key(parent) { - return Err(anyhow!("location {} has invalid container", location.id)); - } + if let Some(parent) = &location.container_id + && (parent == &location.id || !c.locations.contains_key(parent)) + { + return Err(anyhow!("location {} has invalid container", location.id)); } for route in location.routes.values() { if route.travel_minutes == 0 || !c.locations.contains_key(&route.destination_id) { @@ -816,7 +1139,9 @@ mod tests { "gestalt_members":[{"schema":"ghostlight.gestalt_member_delta.v1","id":"john","gestalt_id":"yard-workers","version":0,"name":"John the smith","capability_additions":["forge hinges"],"capability_removals":[],"knowledge_additions":[],"knowledge_removals":[],"equipment":["hammer"],"conditions":[],"obligations":[],"relationships":{},"goals":[],"memories":[],"last_location_id":"yard","materialized_actor_id":null}], "institutions":[],"clocks":[{"id":"shift","label":"Shift ends","progress":0,"threshold":4,"consequence":"night"}], "facts":[{"id":"f","statement":"A witnessed fact","scope":"canon_baseline","evidence_receipt_ids":["fixture"]}], - "gaps":["Who owns the outer gate?"],"branch_assumptions":[],"opening_narration":"The yard persists." + "gaps":["Who owns the outer gate?"],"branch_assumptions":[],"opening_narration":"The yard persists.", + "agency_profiles":[{"subject_id":"yard-workers","subject_kind":"gestalt","collective_authority_id":"yard-workers","facets":{"geography":["yard"],"ideology":["mutual aid"],"authority":["yard-workers"],"economy_role":["maintenance"],"species_body":["human"],"information":["yard routines"]},"location_ids":["yard"],"information_channels":["yard routines"]}], + "agency_relations":[] }).to_string() } _ => return Err(anyhow!("unexpected stage")), @@ -958,6 +1283,11 @@ mod tests { assert_eq!(preview.campaign.locations.len(), 1); assert_eq!(preview.campaign.canon_candidates.len(), 1); assert_eq!(preview.campaign.gestalts.len(), 1); + assert_eq!(preview.campaign.agency_profiles.len(), 2); + assert_eq!( + preview.campaign.agency_profiles["yard-workers"].facets[&AgencyAxis::Ideology], + BTreeSet::from(["mutual aid".into()]) + ); assert_eq!( preview.campaign.gestalt_members["john"].name, "John the smith" diff --git a/crates/ghostlight-dungeon/src/domain.rs b/crates/ghostlight-dungeon/src/domain.rs index 3a24404..c246ecf 100644 --- a/crates/ghostlight-dungeon/src/domain.rs +++ b/crates/ghostlight-dungeon/src/domain.rs @@ -36,6 +36,20 @@ pub struct Campaign { pub gestalt_members: BTreeMap, #[serde(default)] pub pending_world_proposals: Vec, + #[serde(default)] + pub agency_profiles: BTreeMap, + #[serde(default)] + pub agency_relations: BTreeMap, + #[serde(default)] + pub gestalt_lineages: BTreeMap, + #[serde(default)] + pub resolution_policy: ResolutionPolicy, + #[serde(default)] + pub resolution_pins: BTreeMap, + #[serde(default)] + pub resolution_cover: Option, + #[serde(default)] + pub strategic_tick_count: u64, } #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] @@ -193,6 +207,284 @@ pub struct GestaltPresenceChange { pub member_version: u64, } +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum AgencySubjectKind { + Actor, + Institution, + Gestalt, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum AgencyAxis { + Geography, + Ideology, + Authority, + EconomyRole, + SpeciesBody, + Information, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct AgencyProfile { + pub schema: String, + pub id: String, + pub subject_id: String, + pub subject_kind: AgencySubjectKind, + pub profile_version: u64, + pub collective_authority_id: Option, + pub parent_subject_id: Option, + pub active_leaf: bool, + #[serde(default = "default_true")] + pub simulation_eligible: bool, + pub facets: BTreeMap>, + pub location_ids: BTreeSet, + pub information_channels: BTreeSet, + pub detail_debt: u64, + pub last_detail_tick: u64, + pub evidence_receipt_ids: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum AgencyRelationKind { + Containment, + Command, + Membership, + Alliance, + Rivalry, + Trade, + Migration, + Communication, + Coercion, + SharedLocation, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct AgencyRelation { + pub schema: String, + pub id: String, + pub from_subject_id: String, + pub to_subject_id: String, + pub kind: AgencyRelationKind, + pub strength: u8, + pub active: bool, + pub evidence_receipt_ids: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct GestaltLineage { + pub schema: String, + pub parent_gestalt_id: String, + pub child_gestalt_ids: Vec, + pub partition_axis: AgencyAxis, + pub partition_values: BTreeMap, + pub residual_child_id: String, + pub source_revision: u64, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct ResolutionPolicy { + pub schema: String, + pub resolution_epoch: u64, + #[serde(default)] + pub provider_configuration_epoch: u64, + pub active_cell_budget: u8, + pub pending_active_cell_budget: Option, + pub provider_parallelism: u8, +} + +impl Default for ResolutionPolicy { + fn default() -> Self { + Self { + schema: "ghostlight.resolution_policy.v1".into(), + resolution_epoch: 0, + provider_configuration_epoch: 0, + active_cell_budget: 8, + pending_active_cell_budget: None, + provider_parallelism: 8, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum ResolutionPinKind { + KeepTogether, + KeepSeparate, + MinimumIndividualDetail, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct ResolutionPin { + pub schema: String, + pub id: String, + pub kind: ResolutionPinKind, + pub subject_ids: BTreeSet, + pub reason: String, + pub created_world_revision: u64, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct ResolutionDemand { + pub schema: String, + pub campaign_id: Uuid, + pub world_revision: u64, + pub resolution_epoch: u64, + pub axis_weights: BTreeMap, + pub focal_subject_ids: BTreeSet, + pub horizon_minutes: u32, + pub rationale: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum SimulationCellMode { + Cohesive, + Arena, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Default)] +pub struct MergeLoss { + pub facet_divergence: f32, + pub hidden_boundary_mass: f32, + pub information_divergence: f32, + pub spatial_divergence: f32, + pub clock_obligation_divergence: f32, + pub salience_burial: f32, + pub partition_churn: f32, + pub total: f32, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct SimulationCell { + pub schema: String, + pub id: String, + pub mode: SimulationCellMode, + pub subject_ids: BTreeSet, + pub merge_loss: MergeLoss, + pub rationale: String, + pub lease_until_world_revision: u64, + pub lease_until_strategic_tick: u64, + pub detail_focus_subject_id: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct ResolutionCover { + pub schema: String, + pub campaign_id: Uuid, + pub world_revision: u64, + pub resolution_epoch: u64, + pub configured_budget: u8, + pub effective_budget: u8, + pub mandatory_overage: u8, + pub cells: Vec, + pub demand: ResolutionDemand, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct ResolutionPlanReceipt { + pub schema: String, + pub campaign_id: Uuid, + pub world_revision: u64, + pub resolution_epoch: u64, + pub configured_budget: u8, + pub effective_budget: u8, + pub cell_ids: Vec, + pub mandatory_overage: u8, + pub preserved_cell_ids: Vec, + pub collapsed_boundaries: Vec, + pub merge_losses: BTreeMap, + pub rationale: String, + pub created_at: DateTime, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct ResolutionControlReceipt { + pub schema: String, + pub campaign_id: Uuid, + pub world_revision: u64, + pub previous_resolution_epoch: u64, + pub resolution_epoch: u64, + #[serde(default)] + pub provider_configuration_epoch: u64, + pub operation: String, + pub active_cell_budget: u8, + pub pin_ids: Vec, + pub committed_at: DateTime, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum StrategicCellEffect { + Institution { + institution_id: String, + posture: String, + location_ids: Vec, + }, + Gestalt { + gestalt_id: String, + pressure_additions: Vec, + }, + ActorMove { + actor_id: String, + destination_id: String, + }, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct CellActionProposal { + pub subject_id: String, + pub intent: String, + pub intended_effect: String, + pub priority: i16, + pub state_references: Vec, + pub public_channels: Vec, + pub effect: StrategicCellEffect, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct CellAppraisal { + pub schema: String, + pub cell_id: String, + pub world_revision: u64, + pub resolution_epoch: u64, + pub considered_subject_ids: BTreeSet, + pub actions: Vec, + pub inaction_reason: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct ResolutionWaveCommit { + pub schema: String, + pub world_revision: u64, + pub resolution_epoch: u64, + pub cover: ResolutionCover, + pub plan_receipt: ResolutionPlanReceipt, + pub appraisals: Vec, + pub model_receipt_hashes: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct GestaltFissionPreview { + pub schema: String, + pub campaign_id: Uuid, + pub expected_world_revision: u64, + pub parent_gestalt_id: String, + pub partition_axis: AgencyAxis, + pub children: Vec, + pub child_partition_values: BTreeMap, + pub residual_child_id: String, + #[serde(default)] + pub member_child_assignments: BTreeMap, + pub evidence_receipt_ids: Vec, + pub gaps: Vec, + #[serde(default)] + pub canon_candidates: Vec, + pub requires_approval: bool, +} + #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Default)] pub struct ActorStateDelta { pub memories_add: Vec, @@ -307,6 +599,12 @@ pub struct StrategicTickReceipt { pub revision: u64, pub source: TickSource, pub model_receipt_hash: Option, + #[serde(default)] + pub model_receipt_hashes: Vec, + #[serde(default)] + pub resolution_epoch: Option, + #[serde(default)] + pub resolution_cover_id: Option, pub event_ids: Vec, pub committed_at: DateTime, } @@ -415,6 +713,30 @@ pub enum WorldCommand { plan: Option, #[serde(default)] model_receipt_hash: Option, + #[serde(default)] + resolution_wave: Option, + }, + SetResolutionBudget { + expected_revision: u64, + expected_resolution_epoch: u64, + active_cell_budget: u8, + }, + SetProviderParallelism { + expected_revision: u64, + expected_provider_configuration_epoch: u64, + provider_parallelism: u8, + }, + ReplaceResolutionPins { + expected_revision: u64, + expected_resolution_epoch: u64, + pins: Vec, + }, + FissionGestalt { + expected_revision: u64, + preview: GestaltFissionPreview, + evidence_receipts: Vec, + #[serde(default)] + model_stage_receipts: Vec, }, ExpandRegion { expected_revision: u64, @@ -458,6 +780,10 @@ pub enum WorldCommand { }, } +fn default_true() -> bool { + true +} + #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] pub struct RegionExpansion { pub origin_location_id: String, diff --git a/crates/ghostlight-dungeon/src/kernel.rs b/crates/ghostlight-dungeon/src/kernel.rs index 48dcee6..8fca19a 100644 --- a/crates/ghostlight-dungeon/src/kernel.rs +++ b/crates/ghostlight-dungeon/src/kernel.rs @@ -44,6 +44,10 @@ pub enum CommandResult { campaign: Campaign, receipt: WorldCommitReceipt, }, + ResolutionUpdated { + campaign: Campaign, + receipt: ResolutionControlReceipt, + }, } struct Request { @@ -86,7 +90,7 @@ fn execute( command: WorldCommand, ) -> Result { if let WorldCommand::CreateCampaign { - campaign, + mut campaign, evidence_receipts, model_stage_receipts, } = command @@ -94,6 +98,7 @@ fn execute( if !store.keys("campaign.v1").map_err(persist)?.is_empty() { return Err(KernelError::Invalid("campaign already exists".into())); } + crate::resolution::ensure_agency_profiles(&mut campaign); crate::compiler::validate_campaign_seed(&campaign) .map_err(|error| KernelError::Invalid(error.to_string()))?; store @@ -249,14 +254,141 @@ fn execute( campaign.pending_ticks = 0; commit(store, row, campaign, "wait", None) } + WorldCommand::SetResolutionBudget { + expected_revision, + expected_resolution_epoch, + active_cell_budget, + } => { + require_revision(&campaign, expected_revision)?; + require_resolution_epoch(&campaign, expected_resolution_epoch)?; + let previous_epoch = campaign.resolution_policy.resolution_epoch; + campaign.resolution_policy.active_cell_budget = active_cell_budget; + campaign.resolution_policy.pending_active_cell_budget = None; + crate::resolution::validate_policy(&campaign.resolution_policy) + .map_err(|error| KernelError::Invalid(error.to_string()))?; + campaign.resolution_policy.resolution_epoch = previous_epoch.saturating_add(1); + campaign.resolution_cover = None; + commit_resolution_control( + store, + row, + campaign, + previous_epoch, + "set_active_cell_budget", + ) + } + WorldCommand::SetProviderParallelism { + expected_revision, + expected_provider_configuration_epoch, + provider_parallelism, + } => { + require_revision(&campaign, expected_revision)?; + if campaign.resolution_policy.provider_configuration_epoch + != expected_provider_configuration_epoch + { + return Err(KernelError::Stale { + expected: expected_provider_configuration_epoch, + actual: campaign.resolution_policy.provider_configuration_epoch, + }); + } + campaign.resolution_policy.provider_parallelism = provider_parallelism; + crate::resolution::validate_policy(&campaign.resolution_policy) + .map_err(|error| KernelError::Invalid(error.to_string()))?; + let previous_epoch = campaign.resolution_policy.resolution_epoch; + campaign.resolution_policy.provider_configuration_epoch = campaign + .resolution_policy + .provider_configuration_epoch + .saturating_add(1); + commit_resolution_control( + store, + row, + campaign, + previous_epoch, + "set_provider_parallelism", + ) + } + WorldCommand::ReplaceResolutionPins { + expected_revision, + expected_resolution_epoch, + pins, + } => { + require_revision(&campaign, expected_revision)?; + require_resolution_epoch(&campaign, expected_resolution_epoch)?; + let mut replacement = BTreeMap::new(); + for pin in pins { + if replacement.insert(pin.id.clone(), pin).is_some() { + return Err(KernelError::Invalid("duplicate resolution pin id".into())); + } + } + crate::resolution::validate_pins(&campaign, &replacement) + .map_err(|error| KernelError::Invalid(error.to_string()))?; + let previous_epoch = campaign.resolution_policy.resolution_epoch; + campaign.resolution_pins = replacement; + campaign.resolution_policy.resolution_epoch = previous_epoch.saturating_add(1); + campaign.resolution_cover = None; + commit_resolution_control( + store, + row, + campaign, + previous_epoch, + "replace_resolution_pins", + ) + } + WorldCommand::FissionGestalt { + expected_revision, + preview, + evidence_receipts, + model_stage_receipts, + } => { + require_revision(&campaign, expected_revision)?; + let supplied_evidence: BTreeSet<_> = evidence_receipts + .iter() + .map(|receipt| receipt.id.clone()) + .collect(); + if preview + .evidence_receipt_ids + .iter() + .any(|id| !supplied_evidence.contains(id)) + { + return Err(KernelError::Invalid( + "fission preview evidence receipts were not supplied".into(), + )); + } + crate::resolution::apply_fission(&mut campaign, &preview) + .map_err(|error| KernelError::Invalid(error.to_string()))?; + for candidate in &preview.canon_candidates { + campaign + .canon_candidates + .insert(candidate.id.clone(), candidate.clone()); + } + commit_with_records( + store, + row, + campaign, + "fission_gestalt", + evidence_receipts, + preview.canon_candidates, + model_stage_receipts, + ) + } WorldCommand::AdvanceStrategicTick { expected_revision, source, plan, model_receipt_hash, + resolution_wave, } => { require_revision(&campaign, expected_revision)?; - if plan.is_some() + if plan.is_some() && resolution_wave.is_some() { + return Err(KernelError::Invalid( + "strategic tick has two competing plan authorities".into(), + )); + } + let resolved_plan = resolution_wave + .as_ref() + .map(|wave| crate::resolution::validate_and_resolve_wave(&campaign, wave)) + .transpose() + .map_err(|error| KernelError::Invalid(error.to_string()))?; + if (plan.is_some() || resolution_wave.is_some()) && model_receipt_hash .as_deref() .is_none_or(|hash| !valid_sha256(hash)) @@ -265,15 +397,66 @@ fn execute( "model-driven strategic tick lacks an exact model receipt hash".into(), )); } + if let Some(wave) = &resolution_wave { + let unique_hashes: BTreeSet<_> = wave.model_receipt_hashes.iter().collect(); + if unique_hashes.len() != wave.model_receipt_hashes.len() + || wave.model_receipt_hashes.len() < wave.cover.cells.len().saturating_mul(3) + { + return Err(KernelError::Invalid( + "resolution wave does not carry one distinct stage receipt per cell stage" + .into(), + )); + } + let mut stage_bindings = BTreeSet::new(); + for hash in &wave.model_receipt_hashes { + let Some((_, receipt)) = store + .load::("persona_stage_receipt.v1", hash) + .map_err(persist)? + else { + return Err(KernelError::Invalid( + "resolution wave references an unknown model receipt".into(), + )); + }; + if receipt.storage_key() != hash { + return Err(KernelError::Invalid( + "resolution wave contains a mismatched model receipt".into(), + )); + } + stage_bindings + .insert((receipt.stage.clone(), receipt.snapshot_binding.clone())); + } + for cell in &wave.cover.cells { + let binding = format!( + "campaign:{}:revision:{}:resolution:{}:cell:{}", + campaign.id, + campaign.revision, + campaign.resolution_policy.resolution_epoch, + cell.id + ); + for stage in ["cell_projector", "cell_persona", "cell_interpreter"] { + if !stage_bindings.contains(&(stage.into(), binding.clone())) { + return Err(KernelError::Invalid(format!( + "resolution wave lacks {stage} receipt for {}", + cell.id + ))); + } + } + } + } campaign.world_time += Duration::hours(i64::from(campaign.tick_hours)); for clock in campaign.clocks.values_mut() { clock.progress = clock.progress.saturating_add(1).min(clock.threshold); } let tick_number = campaign.away_ticks_processed.saturating_add(1); - let tick_events = match plan { + let tick_events = match resolved_plan.or(plan) { Some(plan) => apply_strategic_tick_plan(&mut campaign, plan)?, None => deterministic_strategic_tick(&mut campaign, tick_number), }; + if let Some(wave) = &resolution_wave { + crate::resolution::advance_detail_debt(&mut campaign, &wave.cover); + campaign.resolution_cover = Some(wave.cover.clone()); + } + campaign.strategic_tick_count = campaign.strategic_tick_count.saturating_add(1); let player = campaign.actors.get(&campaign.player_actor_id); for event in &tick_events { let accessible = event @@ -295,7 +478,15 @@ fn execute( campaign.events.extend(tick_events); campaign.away_ticks_processed = tick_number.min(8); campaign.pending_ticks = campaign.pending_ticks.saturating_sub(1); - commit_strategic_tick(store, row, campaign, source, model_receipt_hash, event_ids) + commit_strategic_tick( + store, + row, + campaign, + source, + model_receipt_hash, + event_ids, + resolution_wave, + ) } WorldCommand::ExpandRegion { expected_revision, @@ -926,6 +1117,16 @@ fn require_revision(c: &Campaign, expected: u64) -> Result<(), KernelError> { } } +fn require_resolution_epoch(c: &Campaign, expected: u64) -> Result<(), KernelError> { + if c.resolution_policy.resolution_epoch != expected { + return Err(KernelError::Invalid(format!( + "stale resolution epoch: expected {expected}, actual {}", + c.resolution_policy.resolution_epoch + ))); + } + Ok(()) +} + fn assess(c: &Campaign, intent: ActionIntent) -> ActionAssessment { let actor = c.actors.get(&intent.actor_id); let admissible = actor.is_some() && !intent.description.trim().is_empty(); @@ -1190,6 +1391,7 @@ fn commit_gestalt_presence( kind: &str, reason: &str, ) -> Result { + crate::resolution::ensure_agency_profiles(&mut campaign); let mut changes = Vec::new(); for (member_id, member) in &campaign.gestalt_members { let previous_actor = before @@ -1259,7 +1461,9 @@ fn commit_strategic_tick( source: TickSource, model_receipt_hash: Option, event_ids: Vec, + resolution_wave: Option, ) -> Result { + crate::resolution::ensure_agency_profiles(&mut campaign); let previous_revision = campaign.revision; campaign.revision += 1; let committed_at = Utc::now(); @@ -1279,16 +1483,59 @@ fn commit_strategic_tick( revision: campaign.revision, source, model_receipt_hash, + model_receipt_hashes: resolution_wave + .as_ref() + .map(|wave| wave.model_receipt_hashes.clone()) + .unwrap_or_default(), + resolution_epoch: resolution_wave.as_ref().map(|wave| wave.resolution_epoch), + resolution_cover_id: resolution_wave.as_ref().map(|wave| { + format!( + "{}:{}:{}", + campaign.id, wave.world_revision, wave.resolution_epoch + ) + }), event_ids, committed_at, }; let key = format!("{}-{}", campaign.id, campaign.revision); store - .append_strategic_tick(&row, &campaign, &key, &receipt, &strategic) + .append_strategic_tick( + &row, + &campaign, + &key, + &receipt, + &strategic, + resolution_wave.as_ref(), + ) .map_err(persist)?; Ok(CommandResult::Committed { campaign, receipt }) } +fn commit_resolution_control( + store: &CampaignStore, + row: cultcache_legacy::CultCacheEnvelope, + campaign: Campaign, + previous_resolution_epoch: u64, + operation: &str, +) -> Result { + let receipt = ResolutionControlReceipt { + schema: "ghostlight.resolution_control_receipt.v1".into(), + campaign_id: campaign.id, + world_revision: campaign.revision, + previous_resolution_epoch, + resolution_epoch: campaign.resolution_policy.resolution_epoch, + provider_configuration_epoch: campaign.resolution_policy.provider_configuration_epoch, + operation: operation.into(), + active_cell_budget: campaign.resolution_policy.active_cell_budget, + pin_ids: campaign.resolution_pins.keys().cloned().collect(), + committed_at: Utc::now(), + }; + store + .append_resolution_control(&row, &campaign, &receipt) + .map_err(persist)?; + Ok(CommandResult::ResolutionUpdated { campaign, receipt }) +} + fn commit( store: &CampaignStore, row: cultcache_legacy::CultCacheEnvelope, @@ -1296,6 +1543,7 @@ fn commit( kind: &str, roll: Option, ) -> Result { + crate::resolution::ensure_agency_profiles(&mut campaign); let previous_revision = campaign.revision; campaign.revision += 1; let receipt = WorldCommitReceipt { @@ -1328,6 +1576,7 @@ fn commit_with_records( candidates: Vec, model_receipts: Vec, ) -> Result { + crate::resolution::ensure_agency_profiles(&mut campaign); let previous_revision = campaign.revision; campaign.revision += 1; let receipt = WorldCommitReceipt { @@ -1413,6 +1662,13 @@ mod tests { gestalts: BTreeMap::new(), gestalt_members: BTreeMap::new(), pending_world_proposals: vec![], + agency_profiles: BTreeMap::new(), + agency_relations: BTreeMap::new(), + gestalt_lineages: BTreeMap::new(), + resolution_policy: Default::default(), + resolution_pins: BTreeMap::new(), + resolution_cover: None, + strategic_tick_count: 0, } } @@ -1624,6 +1880,7 @@ mod tests { source: TickSource::Scheduler, plan: None, model_receipt_hash: None, + resolution_wave: None, }) .await .unwrap(); @@ -1696,6 +1953,7 @@ mod tests { source: TickSource::Scheduler, plan: Some(puppet), model_receipt_hash: Some(format!("sha256:{}", "a".repeat(64))), + resolution_wave: None, }) .await, Err(KernelError::Invalid(_)) @@ -1722,6 +1980,7 @@ mod tests { source: TickSource::Scheduler, plan: Some(valid), model_receipt_hash: Some(format!("sha256:{}", "b".repeat(64))), + resolution_wave: None, }) .await .unwrap(); @@ -2330,4 +2589,279 @@ mod tests { assert_eq!(persisted.revision, 1); assert!(persisted.actors["player"].conditions.contains("braced")); } + + fn resolution_stage( + cell_id: &str, + campaign: &Campaign, + stage: &str, + marker: char, + ) -> crate::model::ModelStageReceipt { + let hash = format!("sha256:{}", marker.to_string().repeat(64)); + crate::model::ModelStageReceipt { + schema: "ghostlight.persona_stage_receipt.v1".into(), + receipt_hash: hash.clone(), + provider: "fixture".into(), + model: "fixture".into(), + stage: stage.into(), + snapshot_binding: format!( + "campaign:{}:revision:{}:resolution:{}:cell:{}", + campaign.id, + campaign.revision, + campaign.resolution_policy.resolution_epoch, + cell_id + ), + request_hash: format!("sha256:{}", "e".repeat(64)), + output_hash: format!("sha256:{}", "f".repeat(64)), + source_receipt_ids: vec![], + latency_ms: 1, + validation_result: "valid".into(), + } + } + + fn inaction_wave( + campaign: &Campaign, + store: &CampaignStore, + ) -> crate::domain::ResolutionWaveCommit { + let cover = crate::resolution::plan_cover( + campaign, + crate::resolution::default_demand(campaign, "kernel fixture"), + ) + .unwrap(); + let mut hashes = Vec::new(); + for (cell_index, cell) in cover.cells.iter().enumerate() { + for (stage_index, stage) in ["cell_projector", "cell_persona", "cell_interpreter"] + .into_iter() + .enumerate() + { + let marker = + char::from_u32(u32::from(b'a') + (cell_index * 3 + stage_index) as u32) + .unwrap(); + let receipt = resolution_stage(&cell.id, campaign, stage, marker); + store + .insert( + "persona_stage_receipt.v1", + "ghostlight.persona_stage_receipt.v1", + receipt.storage_key(), + &receipt, + ) + .unwrap(); + hashes.push(receipt.storage_key().to_owned()); + } + } + crate::domain::ResolutionWaveCommit { + schema: "ghostlight.resolution_wave_commit.v1".into(), + world_revision: campaign.revision, + resolution_epoch: campaign.resolution_policy.resolution_epoch, + plan_receipt: crate::resolution::plan_receipt(campaign, &cover), + appraisals: cover + .cells + .iter() + .map(|cell| CellAppraisal { + schema: "ghostlight.cell_appraisal.v1".into(), + cell_id: cell.id.clone(), + world_revision: campaign.revision, + resolution_epoch: campaign.resolution_policy.resolution_epoch, + considered_subject_ids: cell.subject_ids.clone(), + actions: vec![], + inaction_reason: Some("No justified move.".into()), + }) + .collect(), + cover, + model_receipt_hashes: hashes, + } + } + + #[tokio::test] + async fn resolution_budget_commits_without_advancing_fictional_state() { + let dir = tempfile::tempdir().unwrap(); + let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); + let kernel = WorldKernel::start(store.clone()); + let seed = crate::resolution::tests::campaign(6, 8); + let world_time = seed.world_time; + kernel + .command(WorldCommand::CreateCampaign { + campaign: seed.clone(), + evidence_receipts: vec![], + model_stage_receipts: vec![], + }) + .await + .unwrap(); + let result = kernel + .command(WorldCommand::SetResolutionBudget { + expected_revision: 0, + expected_resolution_epoch: 0, + active_cell_budget: 3, + }) + .await + .unwrap(); + let CommandResult::ResolutionUpdated { campaign, receipt } = result else { + panic!("resolution command used the world commit path") + }; + assert_eq!(campaign.revision, 0); + assert_eq!(campaign.world_time, world_time); + assert_eq!(campaign.resolution_policy.active_cell_budget, 3); + assert_eq!(campaign.resolution_policy.resolution_epoch, 1); + assert_eq!(receipt.previous_resolution_epoch, 0); + assert!( + kernel + .command(WorldCommand::SetResolutionBudget { + expected_revision: 0, + expected_resolution_epoch: 0, + active_cell_budget: 4, + }) + .await + .is_err() + ); + assert_eq!( + store.keys("resolution_control_receipt.v1").unwrap().len(), + 1 + ); + } + + #[tokio::test] + async fn provider_parallelism_changes_without_repartitioning_the_world() { + let dir = tempfile::tempdir().unwrap(); + let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); + let kernel = WorldKernel::start(store); + let mut seed = crate::resolution::tests::campaign(6, 3); + let cover = crate::resolution::plan_cover( + &seed, + crate::resolution::default_demand(&seed, "existing cover"), + ) + .unwrap(); + seed.resolution_cover = Some(cover.clone()); + let world_time = seed.world_time; + kernel + .command(WorldCommand::CreateCampaign { + campaign: seed, + evidence_receipts: vec![], + model_stage_receipts: vec![], + }) + .await + .unwrap(); + let result = kernel + .command(WorldCommand::SetProviderParallelism { + expected_revision: 0, + expected_provider_configuration_epoch: 0, + provider_parallelism: 4, + }) + .await + .unwrap(); + let CommandResult::ResolutionUpdated { campaign, receipt } = result else { + panic!("operator control used the fictional world commit path") + }; + assert_eq!(campaign.revision, 0); + assert_eq!(campaign.world_time, world_time); + assert_eq!(campaign.resolution_policy.resolution_epoch, 0); + assert_eq!(campaign.resolution_policy.provider_configuration_epoch, 1); + assert_eq!(campaign.resolution_policy.provider_parallelism, 4); + assert_eq!(campaign.resolution_cover, Some(cover)); + assert_eq!(receipt.operation, "set_provider_parallelism"); + assert!( + kernel + .command(WorldCommand::SetProviderParallelism { + expected_revision: 0, + expected_provider_configuration_epoch: 0, + provider_parallelism: 2, + }) + .await + .is_err() + ); + } + + #[tokio::test] + async fn strategic_resolution_wave_commits_cover_and_all_appraisals_atomically() { + let dir = tempfile::tempdir().unwrap(); + let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); + let kernel = WorldKernel::start(store.clone()); + let seed = crate::resolution::tests::campaign(6, 2); + kernel + .command(WorldCommand::CreateCampaign { + campaign: seed.clone(), + evidence_receipts: vec![], + model_stage_receipts: vec![], + }) + .await + .unwrap(); + let persisted = store + .load::("campaign.v1", &seed.id.to_string()) + .unwrap() + .unwrap() + .1; + let wave = inaction_wave(&persisted, &store); + let cell_count = wave.cover.cells.len(); + let result = kernel + .command(WorldCommand::AdvanceStrategicTick { + expected_revision: 0, + source: TickSource::Scheduler, + plan: None, + model_receipt_hash: Some(format!("sha256:{}", "9".repeat(64))), + resolution_wave: Some(wave), + }) + .await + .unwrap(); + let CommandResult::Committed { campaign, .. } = result else { + panic!() + }; + assert_eq!(campaign.revision, 1); + assert_eq!(campaign.strategic_tick_count, 1); + assert!(campaign.resolution_cover.is_some()); + assert_eq!(store.keys("cell_appraisal.v1").unwrap().len(), cell_count); + assert_eq!(store.keys("resolution_plan_receipt.v1").unwrap().len(), 1); + assert_eq!(store.keys("strategic_tick.v1").unwrap().len(), 1); + } + + #[tokio::test] + async fn stale_resolution_wave_leaves_time_clocks_and_campaign_unmutated() { + let dir = tempfile::tempdir().unwrap(); + let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); + let kernel = WorldKernel::start(store.clone()); + let seed = crate::resolution::tests::campaign(4, 2); + kernel + .command(WorldCommand::CreateCampaign { + campaign: seed.clone(), + evidence_receipts: vec![], + model_stage_receipts: vec![], + }) + .await + .unwrap(); + let persisted = store + .load::("campaign.v1", &seed.id.to_string()) + .unwrap() + .unwrap() + .1; + let wave = inaction_wave(&persisted, &store); + kernel + .command(WorldCommand::SetResolutionBudget { + expected_revision: 0, + expected_resolution_epoch: 0, + active_cell_budget: 1, + }) + .await + .unwrap(); + let before = store + .load::("campaign.v1", &seed.id.to_string()) + .unwrap() + .unwrap() + .1; + assert!( + kernel + .command(WorldCommand::AdvanceStrategicTick { + expected_revision: 0, + source: TickSource::Scheduler, + plan: None, + model_receipt_hash: Some(format!("sha256:{}", "8".repeat(64))), + resolution_wave: Some(wave), + }) + .await + .is_err() + ); + let after = store + .load::("campaign.v1", &seed.id.to_string()) + .unwrap() + .unwrap() + .1; + assert_eq!(after, before); + assert!(store.keys("strategic_tick.v1").unwrap().is_empty()); + } } diff --git a/crates/ghostlight-dungeon/src/lib.rs b/crates/ghostlight-dungeon/src/lib.rs index 9f1f689..0da350d 100644 --- a/crates/ghostlight-dungeon/src/lib.rs +++ b/crates/ghostlight-dungeon/src/lib.rs @@ -11,6 +11,7 @@ pub mod narrator; pub mod persistence; pub mod persona; pub mod registry; +pub mod resolution; pub mod scheduler; pub mod surface; pub mod turn; diff --git a/crates/ghostlight-dungeon/src/main.rs b/crates/ghostlight-dungeon/src/main.rs index 7d6c566..462ecde 100644 --- a/crates/ghostlight-dungeon/src/main.rs +++ b/crates/ghostlight-dungeon/src/main.rs @@ -9,9 +9,12 @@ use axum::{ use ghostlight_dungeon::windows_secret::unprotect_machine_utf8; use ghostlight_dungeon::{ assessor::ActionAssessor, - compiler::{CustomStart, OpeningRequest, OpeningSuggestion, SelectedStart, WorldCompiler}, + compiler::{ + CustomStart, GestaltFissionRequest, OpeningRequest, OpeningSuggestion, SelectedStart, + WorldCompiler, + }, domain::{ - ActionIntent, Campaign, NarrationProjection, RegionExpansionPreview, + ActionIntent, Campaign, GestaltFissionPreview, NarrationProjection, RegionExpansionPreview, RejectedProposalReceipt, WorldCommand, WorldCompilePreview, }, gestalt::GestaltPresencePlanner, @@ -51,6 +54,7 @@ struct AppState { model: Option>, compile_previews: Arc>>>, expansion_previews: Arc>>>, + fission_previews: Arc>>, live_turns: Arc, mesh: MeshPublisher, } @@ -75,6 +79,20 @@ struct OwnedPreview { model_receipts: Vec, } +#[derive(Clone)] +struct OwnedFissionPreview { + session_hash: String, + value: GestaltFissionPreview, + evidence_receipts: Vec, + model_receipts: Vec, +} + +#[derive(Deserialize)] +struct ProviderParallelismRequest { + expected_provider_configuration_epoch: u64, + provider_parallelism: u8, +} + #[derive(Clone, Serialize, Deserialize)] struct AuthState { schema: String, @@ -204,6 +222,7 @@ async fn main() -> anyhow::Result<()> { model: shared_model, compile_previews: Arc::new(Mutex::new(BTreeMap::new())), expansion_previews: Arc::new(Mutex::new(BTreeMap::new())), + fission_previews: Arc::new(Mutex::new(BTreeMap::new())), live_turns: Arc::new(AtomicUsize::new(0)), mesh, }; @@ -229,6 +248,11 @@ async fn main() -> anyhow::Result<()> { "/api/compiler/destination/approve/{preview_id}", post(approve_destination), ) + .route("/api/compiler/gestalt/fission", post(compile_fission)) + .route( + "/api/compiler/gestalt/fission/approve/{preview_id}", + post(approve_fission), + ) .route("/api/command", post(command)) .route("/api/campaigns", get(campaigns)) .route( @@ -243,6 +267,10 @@ async fn main() -> anyhow::Result<()> { get(export_canon_candidates_markdown), ) .route("/api/operator", get(operator_inspector)) + .route( + "/api/operator/provider-parallelism", + post(set_provider_parallelism), + ) .fallback_service(ServeDir::new(web_root).append_index_html_on_directories(true)) .with_state(state); let address: SocketAddr = std::env::var("GHOSTLIGHT_DUNGEON_BIND") @@ -620,6 +648,107 @@ async fn approve_destination( } } +async fn compile_fission( + headers: HeaderMap, + State(state): State, + Json(request): Json, +) -> Response { + let session = match authenticated_session(&headers, &state).await { + Some(value) => value, + None => return StatusCode::UNAUTHORIZED.into_response(), + }; + let _live = LiveTurnGuard::enter(&state.live_turns); + let runtime = match session_runtime(&state, &session).await { + Ok(Some(value)) => value, + Ok(None) => { + return (StatusCode::NOT_FOUND, "session has no selected campaign").into_response(); + } + Err(error) => { + return (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(); + } + }; + let campaign = match load_campaign(&runtime.store) { + Ok(value) => value, + Err(error) => return (StatusCode::NOT_FOUND, error.to_string()).into_response(), + }; + let Some(compiler) = &state.compiler else { + return ( + StatusCode::SERVICE_UNAVAILABLE, + "DeepSeek credential is unavailable", + ) + .into_response(); + }; + match compiler.compile_fission(&campaign, request).await { + Ok((preview, evidence_receipts, model_receipts)) => { + let id = uuid::Uuid::new_v4().to_string(); + state.fission_previews.lock().await.insert( + id.clone(), + OwnedFissionPreview { + session_hash: session, + value: preview.clone(), + evidence_receipts, + model_receipts: model_receipts.clone(), + }, + ); + Json(serde_json::json!({ + "preview_id":id, + "preview":preview, + "model_receipts":model_receipts + })) + .into_response() + } + Err(error) => (StatusCode::UNPROCESSABLE_ENTITY, error.to_string()).into_response(), + } +} + +async fn approve_fission( + Path(preview_id): Path, + headers: HeaderMap, + State(state): State, +) -> Response { + let session = match authenticated_session(&headers, &state).await { + Some(value) => value, + None => return StatusCode::UNAUTHORIZED.into_response(), + }; + let _live = LiveTurnGuard::enter(&state.live_turns); + let mut previews = state.fission_previews.lock().await; + let Some(owned) = previews.get(&preview_id).cloned() else { + return (StatusCode::NOT_FOUND, "preview missing or already consumed").into_response(); + }; + if owned.session_hash != session { + return StatusCode::FORBIDDEN.into_response(); + } + previews.remove(&preview_id); + drop(previews); + let runtime = match session_runtime(&state, &session).await { + Ok(Some(value)) => value, + Ok(None) => { + return (StatusCode::NOT_FOUND, "session has no selected campaign").into_response(); + } + Err(error) => { + return (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(); + } + }; + match runtime + .kernel + .command(WorldCommand::FissionGestalt { + expected_revision: owned.value.expected_world_revision, + preview: owned.value, + evidence_receipts: owned.evidence_receipts, + model_stage_receipts: owned.model_receipts, + }) + .await + { + Ok(value) => { + if let Err(error) = refresh_mesh(&state).await { + tracing::warn!(%error, "gestalt fission CultMesh publication failed"); + } + Json(value).into_response() + } + Err(error) => (StatusCode::CONFLICT, error.to_string()).into_response(), + } +} + async fn resolve_npc_initiative( state: &AppState, runtime: &CampaignRuntime, @@ -645,7 +774,7 @@ async fn resolve_npc_initiative( let _ = runtime.store.insert( "persona_stage_receipt.v1", "ghostlight.persona_stage_receipt.v1", - &receipt.output_hash, + receipt.storage_key(), &receipt, ); let resolved = runtime @@ -689,7 +818,7 @@ async fn publish_latest_narration( let _ = runtime.store.insert( "persona_stage_receipt.v1", "ghostlight.persona_stage_receipt.v1", - &receipt.output_hash, + receipt.storage_key(), &receipt, ); Ok(Some(projection)) @@ -794,7 +923,7 @@ async fn command( let _ = runtime.store.insert( "persona_stage_receipt.v1", "ghostlight.persona_stage_receipt.v1", - &receipt.output_hash, + receipt.storage_key(), &receipt, ); *proposal = Some(assessment); @@ -848,7 +977,7 @@ async fn command( let _ = runtime.store.insert( "persona_stage_receipt.v1", "ghostlight.persona_stage_receipt.v1", - &receipt.output_hash, + receipt.storage_key(), &receipt, ); if !plan.individuations.is_empty() @@ -900,7 +1029,7 @@ async fn command( let _ = runtime.store.insert( "persona_stage_receipt.v1", "ghostlight.persona_stage_receipt.v1", - &receipt.output_hash, + receipt.storage_key(), &receipt, ); } @@ -1023,7 +1152,7 @@ async fn command( let _ = runtime.store.insert( "persona_stage_receipt.v1", "ghostlight.persona_stage_receipt.v1", - &receipt.output_hash, + receipt.storage_key(), &receipt, ); return match runtime @@ -1090,7 +1219,10 @@ fn player_http_command_allowed(command: &WorldCommand, player_actor_id: &str) -> WorldCommand::Assess { intent, proposal, .. } => intent.actor_id == player_actor_id && proposal.is_none(), - WorldCommand::Attempt { .. } | WorldCommand::Wait { .. } => true, + WorldCommand::Attempt { .. } + | WorldCommand::Wait { .. } + | WorldCommand::SetResolutionBudget { .. } + | WorldCommand::ReplaceResolutionPins { .. } => true, WorldCommand::CreateCampaign { .. } | WorldCommand::AdvanceStrategicTick { .. } | WorldCommand::ExpandRegion { .. } @@ -1099,7 +1231,9 @@ fn player_http_command_allowed(command: &WorldCommand, player_actor_id: &str) -> | WorldCommand::IndividuateGestaltMember { .. } | WorldCommand::ReconcileGestaltPresence { .. } | WorldCommand::ResolveReactionWave { .. } - | WorldCommand::ResolveNpcAction { .. } => false, + | WorldCommand::ResolveNpcAction { .. } + | WorldCommand::SetProviderParallelism { .. } + | WorldCommand::FissionGestalt { .. } => false, } } @@ -1168,6 +1302,9 @@ async fn refresh_mesh(state: &AppState) -> anyhow::Result { .store .load_all("gestalt_materialization_receipt.v1")?, rejected: runtime.store.load_all("rejected_proposal_receipt.v1")?, + resolution_plans: runtime.store.load_all("resolution_plan_receipt.v1")?, + cell_appraisals: runtime.store.load_all("cell_appraisal.v1")?, + resolution_controls: runtime.store.load_all("resolution_control_receipt.v1")?, }); } let publisher = state.mesh.clone(); @@ -1431,6 +1568,47 @@ async fn export_canon_candidates_markdown( response } +async fn set_provider_parallelism( + headers: HeaderMap, + State(state): State, + Json(request): Json, +) -> Response { + let session = match authenticated_session(&headers, &state).await { + Some(value) => value, + None => return StatusCode::UNAUTHORIZED.into_response(), + }; + let runtime = match session_runtime(&state, &session).await { + Ok(Some(value)) => value, + Ok(None) => { + return (StatusCode::NOT_FOUND, "session has no selected campaign").into_response(); + } + Err(error) => { + return (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(); + } + }; + let campaign = match load_campaign(&runtime.store) { + Ok(value) => value, + Err(error) => return (StatusCode::NOT_FOUND, error.to_string()).into_response(), + }; + match runtime + .kernel + .command(WorldCommand::SetProviderParallelism { + expected_revision: campaign.revision, + expected_provider_configuration_epoch: request.expected_provider_configuration_epoch, + provider_parallelism: request.provider_parallelism, + }) + .await + { + Ok(value) => { + if let Err(error) = refresh_mesh(&state).await { + tracing::warn!(%error, "provider concurrency CultMesh publication failed"); + } + Json(value).into_response() + } + Err(error) => (StatusCode::CONFLICT, error.to_string()).into_response(), + } +} + async fn operator_inspector(headers: HeaderMap, State(state): State) -> Response { let session = match authenticated_session(&headers, &state).await { Some(value) => value, @@ -1478,15 +1656,27 @@ async fn process_due_ticks( if campaign.away_ticks_processed >= target { return Ok(()); } - let (plan, model_receipt_hash) = if let Some(model) = &state.model { - let (plan, stage) = - ghostlight_dungeon::scheduler::propose_strategic_tick(model.as_ref(), &campaign) - .await?; + let Some(model) = &state.model else { + return Ok(()); + }; + let permit = Arc::new(SnapshotPermit::new_resolution( + runtime.store.clone(), + campaign.id, + campaign.revision, + campaign.resolution_policy.resolution_epoch, + )); + let output = ghostlight_dungeon::scheduler::propose_resolution_wave( + model.clone(), + permit, + &campaign, + ) + .await?; + for stage in &output.stages { match runtime .store .load::( "persona_stage_receipt.v1", - &stage.receipt.output_hash, + stage.receipt.storage_key(), )? { Some((_, existing)) if existing == stage.receipt => {} Some(_) => anyhow::bail!("strategic model receipt hash collision"), @@ -1494,15 +1684,12 @@ async fn process_due_ticks( runtime.store.insert( "persona_stage_receipt.v1", "ghostlight.persona_stage_receipt.v1", - &stage.receipt.output_hash, + stage.receipt.storage_key(), &stage.receipt, )?; } } - (Some(plan), Some(stage.receipt.output_hash)) - } else { - (None, None) - }; + } if yield_to_live_turns && state.live_turns.load(Ordering::SeqCst) > 0 { return Ok(()); } @@ -1511,8 +1698,9 @@ async fn process_due_ticks( .command(WorldCommand::AdvanceStrategicTick { expected_revision: campaign.revision, source: source.clone(), - plan, - model_receipt_hash, + plan: None, + model_receipt_hash: Some(output.aggregate_receipt_hash), + resolution_wave: Some(output.wave), }) .await?; } @@ -1688,6 +1876,13 @@ mod tests { gestalts: BTreeMap::new(), gestalt_members: BTreeMap::new(), pending_world_proposals: vec![], + agency_profiles: BTreeMap::new(), + agency_relations: BTreeMap::new(), + gestalt_lineages: BTreeMap::new(), + resolution_policy: Default::default(), + resolution_pins: BTreeMap::new(), + resolution_cover: None, + strategic_tick_count: 0, } } @@ -1738,6 +1933,7 @@ mod tests { model: None, compile_previews: Arc::new(Mutex::new(BTreeMap::new())), expansion_previews: Arc::new(Mutex::new(BTreeMap::new())), + fission_previews: Arc::new(Mutex::new(BTreeMap::new())), live_turns: Arc::new(AtomicUsize::new(0)), mesh: MeshPublisher::open(dir.path().join("mesh.cc"), None).unwrap(), }; @@ -1785,6 +1981,7 @@ mod tests { source: ghostlight_dungeon::domain::TickSource::Scheduler, plan: None, model_receipt_hash: None, + resolution_wave: None, }, "player", )); diff --git a/crates/ghostlight-dungeon/src/mesh.rs b/crates/ghostlight-dungeon/src/mesh.rs index 73a66a5..ef372a2 100644 --- a/crates/ghostlight-dungeon/src/mesh.rs +++ b/crates/ghostlight-dungeon/src/mesh.rs @@ -1,11 +1,14 @@ use crate::{ domain::{ - ActionAssessment, ActorState, ActorStateDelta, Campaign, CampaignLifecycleReceipt, - CanonCandidate, Event, GestaltMaterializationReceipt, GestaltMemberDelta, + ActionAssessment, ActorState, ActorStateDelta, AgencyProfile, AgencyRelation, Campaign, + CampaignLifecycleReceipt, CanonCandidate, CellActionProposal, CellAppraisal, Event, + GestaltFissionPreview, GestaltLineage, GestaltMaterializationReceipt, GestaltMemberDelta, GestaltPersonaState, InstitutionState, Location, NarrationProjection, NewsIssue, - RegionExpansionPreview, RejectedProposalReceipt, RelationshipState, RollReceipt, - StrategicTickPlan, StrategicTickReceipt, VaultEvidenceReceipt, VaultManifest, - WorldActionProposal, WorldClock, WorldCommitReceipt, WorldCompilePreview, WorldFact, + RegionExpansionPreview, RejectedProposalReceipt, RelationshipState, + ResolutionControlReceipt, ResolutionCover, ResolutionDemand, ResolutionPin, + ResolutionPlanReceipt, ResolutionPolicy, RollReceipt, SimulationCell, StrategicTickPlan, + StrategicTickReceipt, VaultEvidenceReceipt, VaultManifest, WorldActionProposal, WorldClock, + WorldCommitReceipt, WorldCompilePreview, WorldFact, }, model::ModelStageReceipt, surface::{operator_surface, player_surface}, @@ -37,6 +40,9 @@ pub struct CampaignMeshSnapshot { pub strategic_ticks: Vec, pub gestalt_receipts: Vec, pub rejected: Vec, + pub resolution_plans: Vec, + pub cell_appraisals: Vec, + pub resolution_controls: Vec, } #[derive(Clone, Debug, PartialEq, DatabaseEntry)] @@ -240,6 +246,17 @@ impl MeshPublisher { )?; for snapshot in campaigns { let campaign = &snapshot.campaign; + let interface_version = campaign + .revision + .saturating_mul(1_000_000_000_000) + .saturating_add( + campaign + .resolution_policy + .resolution_epoch + .saturating_mul(1_000_000), + ) + .saturating_add(campaign.resolution_policy.provider_configuration_epoch) + as i64; let surface = player_surface(campaign, &snapshot.narrations); let key = format!("eve:surface:ghostlight.campaign.{}", campaign.id); self.put_and_publish( @@ -257,6 +274,9 @@ impl MeshPublisher { &snapshot.strategic_ticks, &snapshot.gestalt_receipts, &snapshot.rejected, + &snapshot.resolution_plans, + &snapshot.cell_appraisals, + &snapshot.resolution_controls, live_turn_pressure, ); self.put_and_publish( @@ -272,7 +292,7 @@ impl MeshPublisher { &EveSurfaceStateRecord { provider_id: PROVIDER_ID.into(), title: format!("{} operator", campaign.name), - version: campaign.revision as i64, + version: interface_version, updated_at: updated_at.clone(), surface: operator, }, @@ -283,7 +303,7 @@ impl MeshPublisher { &EveSurfaceStateRecord { provider_id: PROVIDER_ID.into(), title: campaign.name.clone(), - version: campaign.revision as i64, + version: interface_version, updated_at: updated_at.clone(), surface, }, @@ -364,7 +384,20 @@ fn schema_catalog() -> Value { "ghostlight.canon_candidate.v1": schemars::schema_for!(CanonCandidate), "ghostlight.gestalt_persona_state.v1": schemars::schema_for!(GestaltPersonaState), "ghostlight.gestalt_member_delta.v1": schemars::schema_for!(GestaltMemberDelta) - ,"ghostlight.gestalt_materialization_receipt.v1": schemars::schema_for!(GestaltMaterializationReceipt) + ,"ghostlight.gestalt_materialization_receipt.v1": schemars::schema_for!(GestaltMaterializationReceipt), + "ghostlight.agency_profile.v1": schemars::schema_for!(AgencyProfile), + "ghostlight.agency_relation.v1": schemars::schema_for!(AgencyRelation), + "ghostlight.gestalt_lineage.v1": schemars::schema_for!(GestaltLineage), + "ghostlight.resolution_policy.v1": schemars::schema_for!(ResolutionPolicy), + "ghostlight.resolution_pin.v1": schemars::schema_for!(ResolutionPin), + "ghostlight.resolution_demand.v1": schemars::schema_for!(ResolutionDemand), + "ghostlight.simulation_cell.v1": schemars::schema_for!(SimulationCell), + "ghostlight.resolution_cover.v1": schemars::schema_for!(ResolutionCover), + "ghostlight.resolution_plan_receipt.v1": schemars::schema_for!(ResolutionPlanReceipt), + "ghostlight.resolution_control_receipt.v1": schemars::schema_for!(ResolutionControlReceipt), + "ghostlight.cell_appraisal.v1": schemars::schema_for!(CellAppraisal), + "ghostlight.cell_action_proposal.v1": schemars::schema_for!(CellActionProposal), + "ghostlight.gestalt_fission_preview.v1": schemars::schema_for!(GestaltFissionPreview) }) } @@ -392,6 +425,10 @@ mod tests { "ghostlight.relationship_state.v1", "ghostlight.strategic_tick.v1", "ghostlight.gestalt_materialization_receipt.v1", + "ghostlight.agency_profile.v1", + "ghostlight.resolution_cover.v1", + "ghostlight.cell_appraisal.v1", + "ghostlight.gestalt_fission_preview.v1", ] { assert!(catalog.value["schemas"][schema]["$schema"].is_string()); } diff --git a/crates/ghostlight-dungeon/src/model.rs b/crates/ghostlight-dungeon/src/model.rs index 346bdee..bdfa1fa 100644 --- a/crates/ghostlight-dungeon/src/model.rs +++ b/crates/ghostlight-dungeon/src/model.rs @@ -19,6 +19,8 @@ pub struct ModelStageRequest { #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] pub struct ModelStageReceipt { pub schema: String, + #[serde(default)] + pub receipt_hash: String, pub provider: String, pub model: String, pub stage: String, @@ -30,6 +32,16 @@ pub struct ModelStageReceipt { pub validation_result: String, } +impl ModelStageReceipt { + pub fn storage_key(&self) -> &str { + if self.receipt_hash.is_empty() { + &self.output_hash + } else { + &self.receipt_hash + } + } +} + #[derive(Clone, Debug, PartialEq)] pub struct ModelStageOutput { pub narrative: String, @@ -102,17 +114,36 @@ pub async fn run_validated_stage_with_timeout( None => None, }; let request_bytes = serde_json::to_vec(&attempt_request)?; + let provider = port.provider().to_owned(); + let request_hash = format!("sha256:{:x}", Sha256::digest(&request_bytes)); + let output_hash = format!("sha256:{:x}", Sha256::digest(output.as_bytes())); + let receipt_hash = format!( + "sha256:{:x}", + Sha256::digest( + format!( + "{}|{}|{}|{}|{}|{}", + provider, + request.model, + request.stage, + request.snapshot_binding, + request_hash, + output_hash + ) + .as_bytes() + ) + ); return Ok(ModelStageOutput { narrative: output.clone(), structured, receipt: ModelStageReceipt { schema: "ghostlight.persona_stage_receipt.v1".into(), - provider: port.provider().into(), + receipt_hash, + provider, model: request.model.clone(), stage: request.stage.clone(), snapshot_binding: request.snapshot_binding.clone(), - request_hash: format!("sha256:{:x}", Sha256::digest(&request_bytes)), - output_hash: format!("sha256:{:x}", Sha256::digest(output.as_bytes())), + request_hash, + output_hash, source_receipt_ids: request.source_receipt_ids.clone(), latency_ms: started.elapsed().as_millis() as u64, validation_result: "valid".into(), @@ -256,7 +287,7 @@ impl ModelPort for FixtureModel { Ok(if request.output_schema.is_some() { r#"{"private_delta":{"memories_add":[],"conditions_add":[],"conditions_remove":[],"goals_add":[],"relationship_updates":{}},"speech":null,"reaction_priority":0,"world_actions":[]}"#.into() } else { - format!("{}", request.lived_stream) + request.lived_stream.to_string() }) } fn provider(&self) -> &'static str { diff --git a/crates/ghostlight-dungeon/src/narrator.rs b/crates/ghostlight-dungeon/src/narrator.rs index bdfe896..d46ad6b 100644 --- a/crates/ghostlight-dungeon/src/narrator.rs +++ b/crates/ghostlight-dungeon/src/narrator.rs @@ -78,7 +78,7 @@ impl Narrator { source_revision: campaign.revision, text: text.into(), event_ids: recent_events.into_iter().map(|event| event.id).collect(), - model_receipt_hash: output.receipt.output_hash.clone(), + model_receipt_hash: output.receipt.storage_key().to_owned(), published_at: Utc::now(), }; Ok((projection, output.receipt)) @@ -144,6 +144,13 @@ mod tests { gestalts: BTreeMap::new(), gestalt_members: BTreeMap::new(), pending_world_proposals: vec![], + agency_profiles: BTreeMap::new(), + agency_relations: BTreeMap::new(), + gestalt_lineages: BTreeMap::new(), + resolution_policy: Default::default(), + resolution_pins: BTreeMap::new(), + resolution_cover: None, + strategic_tick_count: 0, } } diff --git a/crates/ghostlight-dungeon/src/persistence.rs b/crates/ghostlight-dungeon/src/persistence.rs index 2304ab1..24fa880 100644 --- a/crates/ghostlight-dungeon/src/persistence.rs +++ b/crates/ghostlight-dungeon/src/persistence.rs @@ -1,6 +1,6 @@ use crate::domain::{ - Campaign, GestaltMaterializationReceipt, StrategicTickReceipt, VaultEvidenceReceipt, - VaultManifest, WorldCommitReceipt, + Campaign, GestaltMaterializationReceipt, ResolutionControlReceipt, ResolutionWaveCommit, + StrategicTickReceipt, VaultEvidenceReceipt, VaultManifest, WorldCommitReceipt, }; use anyhow::{Context, Result, anyhow}; use chrono::Utc; @@ -111,7 +111,7 @@ impl CampaignStore { rows.push(envelope( "persona_stage_receipt.v1", "ghostlight.persona_stage_receipt.v1", - &receipt.output_hash, + receipt.storage_key(), receipt, )?); } @@ -240,7 +240,7 @@ impl CampaignStore { rows.push(envelope( "persona_stage_receipt.v1", "ghostlight.persona_stage_receipt.v1", - &item.output_hash, + item.storage_key(), item, )?); } @@ -261,6 +261,7 @@ impl CampaignStore { receipt_key: &str, world_receipt: &WorldCommitReceipt, strategic_receipt: &StrategicTickReceipt, + resolution_wave: Option<&ResolutionWaveCommit>, ) -> Result { let next_row = envelope( &expected.r#type, @@ -268,7 +269,7 @@ impl CampaignStore { &expected.key, next, )?; - let rows = vec![ + let mut rows = vec![ next_row.clone(), envelope( "world_commit_receipt.v1", @@ -283,6 +284,65 @@ impl CampaignStore { strategic_receipt, )?, ]; + if let Some(wave) = resolution_wave { + let key = format!( + "{}:{}:{}", + next.id, wave.world_revision, wave.resolution_epoch + ); + rows.push(envelope( + "resolution_cover.v1", + "ghostlight.resolution_cover.v1", + &key, + &wave.cover, + )?); + rows.push(envelope( + "resolution_plan_receipt.v1", + "ghostlight.resolution_plan_receipt.v1", + &key, + &wave.plan_receipt, + )?); + for appraisal in &wave.appraisals { + rows.push(envelope( + "cell_appraisal.v1", + "ghostlight.cell_appraisal.v1", + &format!( + "{}:{}:{}", + next.revision, wave.resolution_epoch, appraisal.cell_id + ), + appraisal, + )?); + } + } + if !self + .inner + .compare_and_swap_batch(std::slice::from_ref(expected), rows)? + { + return Err(anyhow!("stale CultCache snapshot")); + } + Ok(next_row) + } + + pub fn append_resolution_control( + &self, + expected: &CultCacheEnvelope, + next: &Campaign, + receipt: &ResolutionControlReceipt, + ) -> Result { + let next_row = envelope( + &expected.r#type, + "ghostlight.campaign.v1", + &expected.key, + next, + )?; + let rows = vec![ + next_row.clone(), + envelope( + "resolution_control_receipt.v1", + "ghostlight.resolution_control_receipt.v1", + &format!("{}:{}", next.id, receipt.resolution_epoch), + receipt, + )?, + ]; if !self .inner .compare_and_swap_batch(std::slice::from_ref(expected), rows)? diff --git a/crates/ghostlight-dungeon/src/persona.rs b/crates/ghostlight-dungeon/src/persona.rs index 9706db7..7e881be 100644 --- a/crates/ghostlight-dungeon/src/persona.rs +++ b/crates/ghostlight-dungeon/src/persona.rs @@ -7,6 +7,7 @@ use ghostlight_persona_projection::{ }; use schemars::{JsonSchema, schema_for}; use serde::{Deserialize, Serialize}; +use std::collections::BTreeSet; use std::sync::Arc; #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] @@ -50,6 +51,48 @@ pub struct PersonaTerminalBundle { pub stage_receipts: Vec, } +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct CellConstituentSlice { + pub subject_id: String, + pub subject_kind: crate::domain::AgencySubjectKind, + pub name: String, + pub collective_authority_id: Option, + pub location_ids: BTreeSet, + pub knowledge: BTreeSet, + pub capabilities: BTreeSet, + pub resources: BTreeSet, + pub information_channels: BTreeSet, + pub permitted_state_references: BTreeSet, + pub reachable_destination_ids: BTreeSet, + pub goals: Vec, + pub pressures: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct PermittedCellSlice { + pub cell_id: String, + pub mode: crate::domain::SimulationCellMode, + pub world_revision: u64, + pub resolution_epoch: u64, + pub snapshot_binding: String, + pub constituents: Vec, + pub shared_knowledge: BTreeSet, + pub shared_capabilities: BTreeSet, + pub perceived_events: Vec, + pub world_clock_pressure: Vec, + pub detail_focus_subject_id: Option, + pub max_actions: usize, + pub source_receipt_ids: Vec, +} + +#[derive(Clone, Debug)] +pub struct CellTerminalBundle { + pub lived_stream: LivedNarrativeStream, + pub persona_output: String, + pub appraisal: crate::domain::CellAppraisal, + pub stage_receipts: Vec, +} + #[async_trait] pub trait ExecutionPermit: Send + Sync { async fn require(&self, actor_id: &str, snapshot_binding: &str, stage: &str) -> Result<()>; @@ -170,6 +213,262 @@ impl PersonaProjectionEngine { } } +#[derive(Clone)] +pub struct CellProjectionEngine { + pub model: Arc, + pub permit: Arc, + pub projector_model: String, + pub persona_model: String, + pub interpreter_model: String, +} + +impl CellProjectionEngine { + pub async fn execute(&self, slice: PermittedCellSlice) -> Result { + self.permit + .require(&slice.cell_id, &slice.snapshot_binding, "cell_projector") + .await?; + let typed_context = serde_json::to_string(&slice)?; + let visible_stimulus = slice.perceived_events.join("\n"); + let mode_guidance = match slice.mode { + crate::domain::SimulationCellMode::Cohesive => { + "This cell has real collective authority. Render a plural lived perspective from genuinely shared knowledge and capability only; describe constituent exceptions as exceptions." + } + crate::domain::SimulationCellMode::Arena => { + "This cell is an arena, never a person or faction. Render an attributed polyphonic situation. Never union secrets, knowledge, resources, intentions, authority, or voice between constituents." + } + }; + let projected = run_validated_stage( + self.model.as_ref(), + &ModelStageRequest { + stage: "cell_projector".into(), + model: self.projector_model.clone(), + snapshot_binding: slice.snapshot_binding.clone(), + lived_stream: build_projector_prompt(&ProjectorPrompt { + identity: &slice.cell_id, + typed_context: &typed_context, + visible_stimulus: &visible_stimulus, + domain_guidance: mode_guidance, + }), + output_schema: None, + source_receipt_ids: slice.source_receipt_ids.clone(), + }, + ) + .await?; + if !narrative_stream_is_clean(&projected.narrative) { + return Err(anyhow!("cell projector violated lived-narrative membrane")); + } + let lived = LivedNarrativeStream { + text: projected.narrative.clone(), + snapshot_binding: slice.snapshot_binding.clone(), + projector_receipt: projected.receipt.clone(), + }; + self.permit + .require(&slice.cell_id, &slice.snapshot_binding, "cell_persona") + .await?; + let persona = run_validated_stage( + self.model.as_ref(), + &ModelStageRequest { + stage: "cell_persona".into(), + model: self.persona_model.clone(), + snapshot_binding: slice.snapshot_binding.clone(), + lived_stream: build_persona_prompt(&PersonaPrompt { + identity: &slice.cell_id, + lived_stream: &lived.text, + domain_guidance: match slice.mode { + crate::domain::SimulationCellMode::Cohesive => { + "Appraise the strategic horizon as a real collective. Action is optional, but inaction must be intentional. Do not invent completed consequences." + } + crate::domain::SimulationCellMode::Arena => { + "Appraise the strategic horizon polyphonically. Attribute every intention to a constituent. The arena itself cannot speak, know, decide, or act. Action is optional, but inaction must be explicit." + } + }, + }), + output_schema: None, + source_receipt_ids: vec![], + }, + ) + .await?; + self.permit + .require(&slice.cell_id, &slice.snapshot_binding, "cell_interpreter") + .await?; + let mut schema = serde_json::to_value(schema_for!(crate::domain::CellAppraisal))?; + constrain_cell_schema(&mut schema, &slice)?; + let mut request = ModelStageRequest { + stage: "cell_interpreter".into(), + model: self.interpreter_model.clone(), + snapshot_binding: slice.snapshot_binding.clone(), + lived_stream: build_interpreter_prompt(&InterpreterPrompt { + identity: &slice.cell_id, + typed_context: &typed_context, + lived_stream: &lived.text, + persona_output: &persona.narrative, + output_schema: &serde_json::to_string_pretty(&schema)?, + domain_guidance: "Emit only exact constituent-attributed attempts supported by that constituent's typed state. The cell id is not an actor id. Use an empty actions array plus a concrete inaction_reason when nobody acts.", + }), + output_schema: Some(schema), + source_receipt_ids: slice.source_receipt_ids.clone(), + }; + let mut stage_receipts = vec![projected.receipt, persona.receipt]; + for attempt in 0..2 { + let mut interpreted = run_validated_stage(self.model.as_ref(), &request).await?; + let appraisal = interpreted + .structured + .clone() + .ok_or_else(|| anyhow!("cell interpreter produced no typed appraisal")) + .and_then(|value| serde_json::from_value(value).map_err(Into::into)); + match appraisal.and_then(|appraisal| { + validate_cell_appraisal(&slice, &appraisal)?; + Ok(appraisal) + }) { + Ok(appraisal) => { + stage_receipts.push(interpreted.receipt); + self.permit + .require(&slice.cell_id, &slice.snapshot_binding, "cell_terminal") + .await?; + return Ok(CellTerminalBundle { + lived_stream: lived, + persona_output: persona.narrative, + appraisal, + stage_receipts, + }); + } + Err(error) if attempt == 0 => { + interpreted.receipt.validation_result = "semantic_invalid".into(); + stage_receipts.push(interpreted.receipt); + request.lived_stream.push_str(&format!( + "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS APPRAISAL: {error}\nReturn one corrected complete appraisal against the same snapshot, lived stream, and Persona turn." + )); + } + Err(error) => { + return Err(anyhow!( + "cell interpreter failed semantic validation after one correction: {error}" + )); + } + } + } + unreachable!() + } +} + +fn validate_cell_appraisal( + slice: &PermittedCellSlice, + appraisal: &crate::domain::CellAppraisal, +) -> Result<()> { + let expected: BTreeSet<_> = slice + .constituents + .iter() + .map(|value| value.subject_id.clone()) + .collect(); + if appraisal.schema != "ghostlight.cell_appraisal.v1" + || appraisal.cell_id != slice.cell_id + || appraisal.world_revision != slice.world_revision + || appraisal.resolution_epoch != slice.resolution_epoch + || appraisal.considered_subject_ids != expected + || appraisal.actions.len() > slice.max_actions + || (appraisal.actions.is_empty() + && appraisal + .inaction_reason + .as_deref() + .is_none_or(str::is_empty)) + { + return Err(anyhow!( + "appraisal does not bind the complete permitted cell" + )); + } + for action in &appraisal.actions { + let subject = slice + .constituents + .iter() + .find(|value| value.subject_id == action.subject_id) + .ok_or_else(|| anyhow!("action is attributed outside the cell"))?; + if action.intent.trim().is_empty() + || action.intended_effect.trim().is_empty() + || action + .state_references + .iter() + .any(|reference| !subject.permitted_state_references.contains(reference)) + || action + .public_channels + .iter() + .any(|channel| !subject.information_channels.contains(channel)) + { + return Err(anyhow!( + "action borrows state or information across constituents" + )); + } + match &action.effect { + crate::domain::StrategicCellEffect::Institution { + institution_id, + location_ids, + .. + } if subject.subject_kind == crate::domain::AgencySubjectKind::Institution + && institution_id == &subject.subject_id + && location_ids + .iter() + .all(|location| subject.location_ids.contains(location)) => {} + crate::domain::StrategicCellEffect::Gestalt { gestalt_id, .. } + if subject.subject_kind == crate::domain::AgencySubjectKind::Gestalt + && gestalt_id == &subject.subject_id => {} + crate::domain::StrategicCellEffect::ActorMove { + actor_id, + destination_id, + } if subject.subject_kind == crate::domain::AgencySubjectKind::Actor + && actor_id == &subject.subject_id + && subject.reachable_destination_ids.contains(destination_id) => {} + _ => { + return Err(anyhow!( + "action effect exceeds its exact constituent authority" + )); + } + } + } + Ok(()) +} + +fn constrain_cell_schema(schema: &mut serde_json::Value, slice: &PermittedCellSlice) -> Result<()> { + let properties = schema + .pointer_mut("/properties") + .and_then(serde_json::Value::as_object_mut) + .ok_or_else(|| anyhow!("cell appraisal schema has no properties"))?; + properties.insert( + "schema".into(), + serde_json::json!({"const":"ghostlight.cell_appraisal.v1"}), + ); + properties.insert("cell_id".into(), serde_json::json!({"const":slice.cell_id})); + properties.insert( + "world_revision".into(), + serde_json::json!({"const":slice.world_revision}), + ); + properties.insert( + "resolution_epoch".into(), + serde_json::json!({"const":slice.resolution_epoch}), + ); + properties.insert( + "considered_subject_ids".into(), + serde_json::json!({ + "type":"array", + "uniqueItems":true, + "minItems":slice.constituents.len(), + "maxItems":slice.constituents.len(), + "items":{"type":"string","enum":slice.constituents.iter().map(|value| &value.subject_id).collect::>()} + }), + ); + let actions = properties + .get_mut("actions") + .and_then(serde_json::Value::as_object_mut) + .ok_or_else(|| anyhow!("cell appraisal schema has no action array"))?; + actions.insert("maxItems".into(), slice.max_actions.into()); + let proposal = schema + .pointer_mut("/$defs/CellActionProposal/properties") + .and_then(serde_json::Value::as_object_mut) + .ok_or_else(|| anyhow!("cell appraisal schema has no proposal properties"))?; + proposal.insert( + "subject_id".into(), + serde_json::json!({"type":"string","enum":slice.constituents.iter().map(|value| &value.subject_id).collect::>() }), + ); + Ok(()) +} + fn constrain_interpreter_schema( schema: &mut serde_json::Value, slice: &PermittedActorSlice, diff --git a/crates/ghostlight-dungeon/src/registry.rs b/crates/ghostlight-dungeon/src/registry.rs index 1727fe1..68d9f62 100644 --- a/crates/ghostlight-dungeon/src/registry.rs +++ b/crates/ghostlight-dungeon/src/registry.rs @@ -56,6 +56,35 @@ impl CampaignRegistry { if keys[0] != id.to_string() { return Err(anyhow!("campaign directory and stored id disagree")); } + let (row, mut campaign) = store + .load::("campaign.v1", &keys[0])? + .ok_or_else(|| anyhow!("campaign row vanished during migration"))?; + let before = campaign.clone(); + crate::resolution::ensure_agency_profiles(&mut campaign); + if campaign != before { + let previous_resolution_epoch = campaign.resolution_policy.resolution_epoch; + campaign.resolution_policy.resolution_epoch = + previous_resolution_epoch.saturating_add(1); + campaign.resolution_cover = None; + store.append_resolution_control( + &row, + &campaign, + &crate::domain::ResolutionControlReceipt { + schema: "ghostlight.resolution_control_receipt.v1".into(), + campaign_id: campaign.id, + world_revision: campaign.revision, + previous_resolution_epoch, + resolution_epoch: campaign.resolution_policy.resolution_epoch, + provider_configuration_epoch: campaign + .resolution_policy + .provider_configuration_epoch, + operation: "migrate_flat_agency_state".into(), + active_cell_budget: campaign.resolution_policy.active_cell_budget, + pin_ids: campaign.resolution_pins.keys().cloned().collect(), + committed_at: Utc::now(), + }, + )?; + } found.insert( id, CampaignRuntime { @@ -83,10 +112,11 @@ impl CampaignRegistry { pub async fn create( &self, - campaign: Campaign, + mut campaign: Campaign, evidence: Vec, model_receipts: Vec, ) -> Result { + crate::resolution::ensure_agency_profiles(&mut campaign); if self.runtimes.read().await.contains_key(&campaign.id) { return Err(anyhow!("campaign already exists")); } @@ -147,6 +177,9 @@ impl CampaignRegistry { fork.name = name; fork.revision = 0; fork.pending_world_proposals.clear(); + fork.resolution_policy.resolution_epoch = + fork.resolution_policy.resolution_epoch.saturating_add(1); + fork.resolution_cover = None; let runtime = self.create(fork.clone(), evidence, model_receipts).await?; runtime.store.insert( "campaign_lifecycle_receipt.v1", @@ -282,6 +315,13 @@ mod tests { gestalts: BTreeMap::new(), gestalt_members: BTreeMap::new(), pending_world_proposals: vec![], + agency_profiles: BTreeMap::new(), + agency_relations: BTreeMap::new(), + gestalt_lineages: BTreeMap::new(), + resolution_policy: Default::default(), + resolution_pins: BTreeMap::new(), + resolution_cover: None, + strategic_tick_count: 0, } } @@ -292,6 +332,7 @@ mod tests { let original = seed("Original"); let model_receipt = ModelStageReceipt { schema: "ghostlight.persona_stage_receipt.v1".into(), + receipt_hash: "sha256:receipt".into(), provider: "fixture".into(), model: "fixture".into(), stage: "world_compile".into(), @@ -343,4 +384,37 @@ mod tests { vec![original.id.to_string()] ); } + + #[tokio::test] + async fn load_existing_migrates_flat_campaign_without_advancing_world_revision() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("campaigns"); + let flat = seed("Flat legacy"); + let campaign_root = root.join(flat.id.to_string()); + std::fs::create_dir_all(&campaign_root).unwrap(); + let store = CampaignStore::open(campaign_root.join("campaign.cc")).unwrap(); + store.create_campaign(&flat, &[], &[]).unwrap(); + drop(store); + let registry = CampaignRegistry::new(&root).unwrap(); + registry.load_existing().await.unwrap(); + let runtime = registry.runtime(flat.id).await.unwrap(); + let migrated = runtime + .store + .load::("campaign.v1", &flat.id.to_string()) + .unwrap() + .unwrap() + .1; + assert_eq!(migrated.revision, flat.revision); + assert_eq!(migrated.world_time, flat.world_time); + assert!(migrated.agency_profiles.contains_key(&flat.player_actor_id)); + assert_eq!(migrated.resolution_policy.resolution_epoch, 1); + assert_eq!( + runtime + .store + .keys("resolution_control_receipt.v1") + .unwrap() + .len(), + 1 + ); + } } diff --git a/crates/ghostlight-dungeon/src/resolution.rs b/crates/ghostlight-dungeon/src/resolution.rs new file mode 100644 index 0000000..3c40f89 --- /dev/null +++ b/crates/ghostlight-dungeon/src/resolution.rs @@ -0,0 +1,2454 @@ +use crate::domain::*; +use anyhow::{Result, anyhow}; +use sha2::{Digest, Sha256}; +use std::cmp::Ordering; +use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, VecDeque}; + +pub const MIN_ACTIVE_CELL_BUDGET: u8 = 1; +pub const MAX_ACTIVE_CELL_BUDGET: u8 = 32; +pub const MAX_PROVIDER_PARALLELISM: u8 = 32; + +#[derive(Clone, Debug)] +struct Candidate { + left: String, + right: String, + loss: MergeLoss, +} + +impl PartialEq for Candidate { + fn eq(&self, other: &Self) -> bool { + self.loss.total.to_bits() == other.loss.total.to_bits() + && self.left == other.left + && self.right == other.right + } +} +impl Eq for Candidate {} +impl PartialOrd for Candidate { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} +impl Ord for Candidate { + fn cmp(&self, other: &Self) -> Ordering { + other + .loss + .total + .total_cmp(&self.loss.total) + .then_with(|| other.left.cmp(&self.left)) + .then_with(|| other.right.cmp(&self.right)) + } +} + +pub fn default_demand(campaign: &Campaign, rationale: impl Into) -> ResolutionDemand { + ResolutionDemand { + schema: "ghostlight.resolution_demand.v1".into(), + campaign_id: campaign.id, + world_revision: campaign.revision, + resolution_epoch: campaign.resolution_policy.resolution_epoch, + axis_weights: BTreeMap::from([ + (AgencyAxis::Geography, 0.25), + (AgencyAxis::Ideology, 0.20), + (AgencyAxis::Authority, 0.25), + (AgencyAxis::EconomyRole, 0.15), + (AgencyAxis::SpeciesBody, 0.05), + (AgencyAxis::Information, 0.10), + ]), + focal_subject_ids: BTreeSet::new(), + horizon_minutes: campaign.tick_hours.saturating_mul(60), + rationale: rationale.into(), + } +} + +pub fn ensure_agency_profiles(campaign: &mut Campaign) { + let evidence = campaign.branch_origin.evidence_receipt_ids.clone(); + for actor in campaign.actors.values() { + campaign + .agency_profiles + .entry(actor.id.clone()) + .or_insert_with(|| profile_for_actor(actor, &evidence)); + } + for institution in campaign.institutions.values() { + campaign + .agency_profiles + .entry(institution.id.clone()) + .or_insert_with(|| profile_for_institution(institution, &evidence)); + } + for gestalt in campaign.gestalts.values() { + campaign + .agency_profiles + .entry(gestalt.id.clone()) + .or_insert_with(|| profile_for_gestalt(gestalt, &evidence)); + } + for actor in campaign.actors.values() { + if let Some(profile) = campaign.agency_profiles.get_mut(&actor.id) { + profile.location_ids = BTreeSet::from([actor.location_id.clone()]); + profile + .information_channels + .extend(actor.knowledge.iter().cloned()); + } + } + let live: BTreeSet<_> = campaign + .actors + .keys() + .chain(campaign.institutions.keys()) + .chain(campaign.gestalts.keys()) + .cloned() + .collect(); + campaign + .agency_profiles + .retain(|id, profile| live.contains(id) || !profile.active_leaf); + if let Some(player) = campaign.agency_profiles.get_mut(&campaign.player_actor_id) { + player.simulation_eligible = false; + } + ensure_structural_relations(campaign); +} + +fn base_profile( + subject_id: &str, + kind: AgencySubjectKind, + authority: Option, + evidence: &[String], +) -> AgencyProfile { + AgencyProfile { + schema: "ghostlight.agency_profile.v1".into(), + id: format!("agency-profile:{subject_id}"), + subject_id: subject_id.into(), + subject_kind: kind, + profile_version: 0, + collective_authority_id: authority, + parent_subject_id: None, + active_leaf: true, + simulation_eligible: true, + facets: BTreeMap::new(), + location_ids: BTreeSet::new(), + information_channels: BTreeSet::new(), + detail_debt: 0, + last_detail_tick: 0, + evidence_receipt_ids: evidence.to_vec(), + } +} + +fn profile_for_actor(actor: &ActorState, evidence: &[String]) -> AgencyProfile { + let mut profile = base_profile(&actor.id, AgencySubjectKind::Actor, None, evidence); + profile.location_ids.insert(actor.location_id.clone()); + profile.facets.insert( + AgencyAxis::Geography, + BTreeSet::from([actor.location_id.clone()]), + ); + profile.facets.insert( + AgencyAxis::EconomyRole, + actor.capabilities.iter().cloned().collect(), + ); + profile.facets.insert( + AgencyAxis::Information, + actor.knowledge.iter().cloned().collect(), + ); + profile.information_channels = actor.knowledge.iter().cloned().collect(); + profile +} + +fn profile_for_institution(value: &InstitutionState, evidence: &[String]) -> AgencyProfile { + let mut profile = base_profile( + &value.id, + AgencySubjectKind::Institution, + Some(value.id.clone()), + evidence, + ); + profile.facets.insert( + AgencyAxis::Authority, + BTreeSet::from([value.id.clone(), value.posture.clone()]), + ); + profile.facets.insert( + AgencyAxis::EconomyRole, + value.resources.iter().cloned().collect(), + ); + profile +} + +fn profile_for_gestalt(value: &GestaltPersonaState, evidence: &[String]) -> AgencyProfile { + let mut profile = base_profile( + &value.id, + AgencySubjectKind::Gestalt, + Some(value.id.clone()), + evidence, + ); + profile.location_ids.insert(value.home_location_id.clone()); + profile.facets.insert( + AgencyAxis::Geography, + BTreeSet::from([value.home_location_id.clone()]), + ); + profile.facets.insert( + AgencyAxis::EconomyRole, + value.shared_capabilities.iter().cloned().collect(), + ); + profile.facets.insert( + AgencyAxis::Information, + value.shared_knowledge.iter().cloned().collect(), + ); + profile.information_channels = value.shared_knowledge.iter().cloned().collect(); + profile +} + +fn ensure_structural_relations(campaign: &mut Campaign) { + let live: BTreeSet<_> = campaign + .agency_profiles + .values() + .filter(|profile| profile.active_leaf) + .map(|profile| profile.subject_id.as_str()) + .collect(); + campaign.agency_relations.retain(|_, relation| { + live.contains(relation.from_subject_id.as_str()) + && live.contains(relation.to_subject_id.as_str()) + }); +} + +#[derive(Clone, Debug)] +struct DerivedAgencyGraph { + neighbors: BTreeMap>, +} + +#[derive(Debug)] +struct ScoringCache { + pressure_tokens: BTreeMap>, + salience: BTreeMap, +} + +impl ScoringCache { + fn new(campaign: &Campaign, profiles: &BTreeMap) -> Self { + Self { + pressure_tokens: profiles + .keys() + .map(|id| (id.clone(), pressure_tokens(campaign, id))) + .collect(), + salience: profiles + .iter() + .map(|(id, profile)| (id.clone(), subject_salience(campaign, profile))) + .collect(), + } + } +} + +impl DerivedAgencyGraph { + fn build(campaign: &Campaign, subjects: BTreeSet) -> Self { + let mut neighbors: BTreeMap<_, _> = subjects + .iter() + .map(|id| (id.clone(), BTreeSet::new())) + .collect(); + { + let mut connect = |left: &str, right: &str| { + if left != right && subjects.contains(left) && subjects.contains(right) { + neighbors + .entry(left.to_owned()) + .or_default() + .insert(right.to_owned()); + neighbors + .entry(right.to_owned()) + .or_default() + .insert(left.to_owned()); + } + }; + for relation in campaign + .agency_relations + .values() + .filter(|relation| relation.active) + { + connect(&relation.from_subject_id, &relation.to_subject_id); + } + let mut by_location: BTreeMap<&str, Vec<&str>> = BTreeMap::new(); + for profile in campaign + .agency_profiles + .values() + .filter(|profile| subjects.contains(&profile.subject_id)) + { + for location in &profile.location_ids { + by_location + .entry(location.as_str()) + .or_default() + .push(profile.subject_id.as_str()); + } + } + for values in by_location.values_mut() { + values.sort_unstable(); + values.dedup(); + for pair in values.windows(2) { + connect(pair[0], pair[1]); + } + } + } + + // A campaign root is a resolution-only Steiner vertex. Linking component + // representatives through it keeps the cover coarsenable without claiming + // that distant or opposed subjects share containment, knowledge, or authority. + let mut seen = BTreeSet::new(); + let mut representatives = Vec::new(); + for start in &subjects { + if !seen.insert(start.clone()) { + continue; + } + representatives.push(start.clone()); + let mut queue = VecDeque::from([start.clone()]); + while let Some(current) = queue.pop_front() { + for next in neighbors.get(¤t).into_iter().flatten() { + if seen.insert(next.clone()) { + queue.push_back(next.clone()); + } + } + } + } + for pair in representatives.windows(2) { + neighbors + .entry(pair[0].clone()) + .or_default() + .insert(pair[1].clone()); + neighbors + .entry(pair[1].clone()) + .or_default() + .insert(pair[0].clone()); + } + Self { neighbors } + } +} + +pub fn validate_policy(policy: &ResolutionPolicy) -> Result<()> { + if !(MIN_ACTIVE_CELL_BUDGET..=MAX_ACTIVE_CELL_BUDGET).contains(&policy.active_cell_budget) + || policy.pending_active_cell_budget.is_some_and(|value| { + !(MIN_ACTIVE_CELL_BUDGET..=MAX_ACTIVE_CELL_BUDGET).contains(&value) + }) + || !(1..=MAX_PROVIDER_PARALLELISM).contains(&policy.provider_parallelism) + { + return Err(anyhow!("resolution policy is outside supported bounds")); + } + Ok(()) +} + +pub fn validate_pins(campaign: &Campaign, pins: &BTreeMap) -> Result<()> { + let subjects: BTreeSet<_> = campaign + .agency_profiles + .values() + .filter(|profile| profile.active_leaf && profile.simulation_eligible) + .map(|profile| profile.subject_id.as_str()) + .collect(); + for pin in pins.values() { + if pin.id.trim().is_empty() + || pin.reason.trim().is_empty() + || pin.subject_ids.is_empty() + || pin + .subject_ids + .iter() + .any(|id| !subjects.contains(id.as_str())) + { + return Err(anyhow!( + "resolution pin is malformed or references an unknown subject" + )); + } + match pin.kind { + ResolutionPinKind::MinimumIndividualDetail if pin.subject_ids.len() != 1 => { + return Err(anyhow!( + "minimum-individual pin must name exactly one subject" + )); + } + ResolutionPinKind::KeepTogether | ResolutionPinKind::KeepSeparate + if pin.subject_ids.len() < 2 => + { + return Err(anyhow!( + "group resolution pin must name at least two subjects" + )); + } + _ => {} + } + } + for together in pins + .values() + .filter(|pin| pin.kind == ResolutionPinKind::KeepTogether) + { + if pins + .values() + .filter(|pin| pin.kind == ResolutionPinKind::KeepSeparate) + .any(|separate| { + together + .subject_ids + .intersection(&separate.subject_ids) + .count() + >= 2 + }) + || pins + .values() + .filter(|pin| pin.kind == ResolutionPinKind::MinimumIndividualDetail) + .any(|individual| !individual.subject_ids.is_disjoint(&together.subject_ids)) + { + return Err(anyhow!( + "resolution pins require the same subjects together and apart" + )); + } + } + Ok(()) +} + +pub fn plan_cover(campaign: &Campaign, demand: ResolutionDemand) -> Result { + let trace = std::env::var_os("GHOSTLIGHT_PARTITION_TRACE").is_some(); + let trace_started = std::time::Instant::now(); + validate_policy(&campaign.resolution_policy)?; + validate_pins(campaign, &campaign.resolution_pins)?; + validate_demand(campaign, &demand)?; + let profiles: BTreeMap<_, _> = campaign + .agency_profiles + .iter() + .filter(|(_, profile)| profile.active_leaf && profile.simulation_eligible) + .map(|(id, profile)| (id.clone(), profile.clone())) + .collect(); + if profiles.is_empty() { + return Err(anyhow!("agency graph has no active subjects")); + } + let scoring = ScoringCache::new(campaign, &profiles); + let mandatory = mandatory_subjects(campaign, &demand); + let graph = DerivedAgencyGraph::build(campaign, profiles.keys().cloned().collect()); + if trace { + eprintln!("partition graph: {:?}", trace_started.elapsed()); + } + let mut groups: HashMap> = profiles + .keys() + .map(|id| (id.clone(), BTreeSet::from([id.clone()]))) + .collect(); + contract_together_pins(&mut groups, &campaign.resolution_pins, &mandatory); + let mut group_samples: HashMap> = groups + .iter() + .map(|(id, subjects)| (id.clone(), representative_sample(subjects.iter()))) + .collect(); + let mandatory_cells = groups + .values() + .filter(|subjects| !subjects.is_disjoint(&mandatory)) + .count(); + let configured = campaign.resolution_policy.active_cell_budget as usize; + let target = configured.max(mandatory_cells); + let active_subjects: BTreeSet<_> = profiles.keys().cloned().collect(); + let separate_floor = campaign + .resolution_pins + .values() + .filter(|pin| pin.kind == ResolutionPinKind::KeepSeparate) + .map(|pin| pin.subject_ids.intersection(&active_subjects).count()) + .max() + .unwrap_or(0); + let target = target.max(separate_floor); + let mut neighbors = group_neighbors(&groups, &graph); + let mut heap = candidates( + campaign, + &profiles, + &groups, + &group_samples, + &neighbors, + &scoring, + &demand, + &mandatory, + ); + if trace { + eprintln!("partition heap: {:?}", trace_started.elapsed()); + } + let mut merge_serial = 0u64; + let mut candidate_elapsed = std::time::Duration::ZERO; + let mut heap_pops = 0usize; + while groups.len() > target { + let Some(best) = heap.pop() else { break }; + heap_pops += 1; + if !groups.contains_key(&best.left) + || !groups.contains_key(&best.right) + || !neighbors + .get(&best.left) + .is_some_and(|ids| ids.contains(&best.right)) + { + continue; + } + let left_group = groups + .remove(&best.left) + .ok_or_else(|| anyhow!("partition candidate vanished"))?; + let right_group = groups + .remove(&best.right) + .ok_or_else(|| anyhow!("partition candidate vanished"))?; + let (mut joined, smaller) = if left_group.len() >= right_group.len() { + (left_group, right_group) + } else { + (right_group, left_group) + }; + joined.extend(smaller); + let left_sample = group_samples.remove(&best.left).unwrap_or_default(); + let right_sample = group_samples.remove(&best.right).unwrap_or_default(); + let joined_sample = representative_sample(left_sample.iter().chain(right_sample.iter())); + let new_id = format!("merge-group:{merge_serial:016}"); + merge_serial = merge_serial.saturating_add(1); + let joined_neighbors: BTreeSet<_> = neighbors + .remove(&best.left) + .unwrap_or_default() + .union(&neighbors.remove(&best.right).unwrap_or_default()) + .filter(|id| *id != &best.left && *id != &best.right && groups.contains_key(*id)) + .cloned() + .collect(); + for other in &joined_neighbors { + if let Some(values) = neighbors.get_mut(other) { + values.remove(&best.left); + values.remove(&best.right); + values.insert(new_id.clone()); + } + } + groups.insert(new_id.clone(), joined); + group_samples.insert(new_id.clone(), joined_sample); + neighbors.insert(new_id.clone(), joined_neighbors.clone()); + for other in joined_neighbors { + let candidate = if trace { + let candidate_started = std::time::Instant::now(); + let candidate = candidate_for( + campaign, + &profiles, + &groups, + &group_samples, + &new_id, + &other, + &scoring, + &demand, + &mandatory, + ); + candidate_elapsed += candidate_started.elapsed(); + candidate + } else { + candidate_for( + campaign, + &profiles, + &groups, + &group_samples, + &new_id, + &other, + &scoring, + &demand, + &mandatory, + ) + }; + if let Some(candidate) = candidate { + heap.push(candidate); + } + } + } + if trace { + eprintln!( + "partition merge: {:?}; candidates {:?}; heap pops {}", + trace_started.elapsed(), + candidate_elapsed, + heap_pops + ); + } + refine_boundaries( + campaign, + &profiles, + &graph, + &scoring, + &demand, + &mandatory, + &mut groups, + ); + if trace { + eprintln!("partition refine: {:?}", trace_started.elapsed()); + } + let highest_debt = profiles + .values() + .max_by(|left, right| { + left.detail_debt + .cmp(&right.detail_debt) + .then_with(|| right.subject_id.cmp(&left.subject_id)) + }) + .map(|profile| profile.subject_id.clone()); + let mut cells = Vec::new(); + for subjects in groups.values() { + let (mode, loss) = classify_and_score(campaign, &profiles, &scoring, subjects, &demand); + cells.push(SimulationCell { + schema: "ghostlight.simulation_cell.v1".into(), + id: cell_id(subjects, &mode), + mode, + subject_ids: subjects.clone(), + merge_loss: loss, + rationale: cut_rationale(subjects, &demand), + lease_until_world_revision: campaign.revision.saturating_add(5), + lease_until_strategic_tick: campaign.strategic_tick_count.saturating_add(2), + detail_focus_subject_id: highest_debt + .as_ref() + .filter(|id| subjects.contains(*id)) + .cloned(), + }); + } + cells.sort_by(|left, right| left.id.cmp(&right.id)); + if trace { + eprintln!("partition cells: {:?}", trace_started.elapsed()); + } + cells = preserve_previous_cover( + campaign, &profiles, &scoring, &demand, &mandatory, target, cells, + ); + validate_cover_with_graph(campaign, &demand, &cells, &graph)?; + if trace { + eprintln!("partition validate: {:?}", trace_started.elapsed()); + } + let effective_budget = cells.len().min(u8::MAX as usize) as u8; + Ok(ResolutionCover { + schema: "ghostlight.resolution_cover.v1".into(), + campaign_id: campaign.id, + world_revision: campaign.revision, + resolution_epoch: campaign.resolution_policy.resolution_epoch, + configured_budget: campaign.resolution_policy.active_cell_budget, + effective_budget, + mandatory_overage: effective_budget + .saturating_sub(campaign.resolution_policy.active_cell_budget), + cells, + demand, + }) +} + +fn refine_boundaries( + campaign: &Campaign, + profiles: &BTreeMap, + graph: &DerivedAgencyGraph, + scoring: &ScoringCache, + demand: &ResolutionDemand, + mandatory: &BTreeSet, + groups: &mut HashMap>, +) { + let mut subject_group = HashMap::new(); + for (group_id, subjects) in groups.iter() { + for subject in subjects { + subject_group.insert(subject.clone(), group_id.clone()); + } + } + let subjects: Vec<_> = profiles.keys().cloned().collect(); + for subject in subjects { + if mandatory.contains(&subject) { + continue; + } + let Some(source_id) = subject_group.get(&subject).cloned() else { + continue; + }; + if groups + .get(&source_id) + .is_none_or(|values| values.len() <= 1) + { + continue; + } + let adjacent_groups: BTreeSet<_> = graph + .neighbors + .get(&subject) + .into_iter() + .flatten() + .filter_map(|neighbor| subject_group.get(neighbor).cloned()) + .filter(|id| id != &source_id) + .collect(); + if adjacent_groups.is_empty() { + continue; + } + let Some(source) = groups.get(&source_id).cloned() else { + continue; + }; + for destination_id in adjacent_groups { + let Some(destination) = groups.get(&destination_id).cloned() else { + continue; + }; + let mut next_source = source.clone(); + next_source.remove(&subject); + let mut next_destination = destination.clone(); + next_destination.insert(subject.clone()); + if !connected(graph, &next_source) + || !connected(graph, &next_destination) + || violates_separate_pin( + &BTreeSet::from([subject.clone()]), + &destination, + &campaign.resolution_pins, + ) + || breaks_together_pin( + &source_id, + &destination_id, + &subject, + groups, + &campaign.resolution_pins, + ) + { + continue; + } + let old_loss = compression_cost( + &classify_and_score(campaign, profiles, scoring, &source, demand).1, + source.len(), + ) + compression_cost( + &classify_and_score(campaign, profiles, scoring, &destination, demand).1, + destination.len(), + ); + let new_loss = compression_cost( + &classify_and_score(campaign, profiles, scoring, &next_source, demand).1, + next_source.len(), + ) + compression_cost( + &classify_and_score(campaign, profiles, scoring, &next_destination, demand).1, + next_destination.len(), + ); + if old_loss > f32::EPSILON && new_loss <= old_loss * 0.95 { + groups.insert(source_id.clone(), next_source); + groups.insert(destination_id.clone(), next_destination); + subject_group.insert(subject.clone(), destination_id); + break; + } + } + } +} + +fn breaks_together_pin( + source_id: &str, + destination_id: &str, + subject: &str, + groups: &HashMap>, + pins: &BTreeMap, +) -> bool { + pins.values() + .filter(|pin| { + pin.kind == ResolutionPinKind::KeepTogether && pin.subject_ids.contains(subject) + }) + .any(|pin| { + pin.subject_ids.iter().any(|other| { + other != subject + && groups + .get(source_id) + .is_some_and(|values| values.contains(other)) + && !groups + .get(destination_id) + .is_some_and(|values| values.contains(other)) + }) + }) +} + +fn preserve_previous_cover( + campaign: &Campaign, + profiles: &BTreeMap, + scoring: &ScoringCache, + demand: &ResolutionDemand, + mandatory: &BTreeSet, + target: usize, + candidate: Vec, +) -> Vec { + let Some(previous) = campaign.resolution_cover.as_ref().filter(|cover| { + cover.resolution_epoch == campaign.resolution_policy.resolution_epoch + && cover.configured_budget == campaign.resolution_policy.active_cell_budget + && cover.cells.len() == target + }) else { + return candidate; + }; + if previous + .cells + .iter() + .any(|cell| cell.subject_ids.len() > 1 && !cell.subject_ids.is_disjoint(mandatory)) + { + return candidate; + } + let expected: BTreeSet<_> = profiles.keys().cloned().collect(); + let actual: BTreeSet<_> = previous + .cells + .iter() + .flat_map(|cell| cell.subject_ids.iter().cloned()) + .collect(); + if actual != expected { + return candidate; + } + let old_total: f32 = previous + .cells + .iter() + .map(|cell| { + compression_cost( + &classify_and_score(campaign, profiles, scoring, &cell.subject_ids, demand).1, + cell.subject_ids.len(), + ) + }) + .sum(); + let new_total: f32 = candidate + .iter() + .map(|cell| compression_cost(&cell.merge_loss, cell.subject_ids.len())) + .sum(); + let improvement = if old_total <= f32::EPSILON { + 0.0 + } else { + ((old_total - new_total) / old_total).max(0.0) + }; + let lease_active = previous.cells.iter().any(|cell| { + campaign.revision < cell.lease_until_world_revision + && campaign.strategic_tick_count < cell.lease_until_strategic_tick + }); + if !lease_active && improvement >= 0.10 { + return candidate; + } + let mut preserved: Vec<_> = previous + .cells + .iter() + .map(|cell| { + let (mode, merge_loss) = + classify_and_score(campaign, profiles, scoring, &cell.subject_ids, demand); + SimulationCell { + schema: "ghostlight.simulation_cell.v1".into(), + id: cell_id(&cell.subject_ids, &mode), + mode, + subject_ids: cell.subject_ids.clone(), + merge_loss, + rationale: format!("preserved partition: {}", cell.rationale), + lease_until_world_revision: cell.lease_until_world_revision, + lease_until_strategic_tick: cell.lease_until_strategic_tick, + detail_focus_subject_id: None, + } + }) + .collect(); + if let Some(highest_debt) = profiles + .values() + .max_by(|left, right| { + left.detail_debt + .cmp(&right.detail_debt) + .then_with(|| right.subject_id.cmp(&left.subject_id)) + }) + .map(|profile| profile.subject_id.as_str()) + && let Some(cell) = preserved + .iter_mut() + .find(|cell| cell.subject_ids.contains(highest_debt)) + { + cell.detail_focus_subject_id = Some(highest_debt.to_owned()); + } + preserved.sort_by(|left, right| left.id.cmp(&right.id)); + preserved +} + +fn compression_cost(loss: &MergeLoss, constituent_count: usize) -> f32 { + loss.total * constituent_count.saturating_sub(1) as f32 +} + +pub fn validate_demand(campaign: &Campaign, demand: &ResolutionDemand) -> Result<()> { + let axes = [ + AgencyAxis::Geography, + AgencyAxis::Ideology, + AgencyAxis::Authority, + AgencyAxis::EconomyRole, + AgencyAxis::SpeciesBody, + AgencyAxis::Information, + ]; + if demand.campaign_id != campaign.id + || demand.world_revision != campaign.revision + || demand.resolution_epoch != campaign.resolution_policy.resolution_epoch + || demand.horizon_minutes == 0 + || demand.rationale.trim().is_empty() + || axes.iter().any(|axis| { + demand + .axis_weights + .get(axis) + .is_none_or(|weight| !weight.is_finite() || !(0.0..=1.0).contains(weight)) + }) + || demand + .focal_subject_ids + .iter() + .any(|id| !campaign.agency_profiles.contains_key(id)) + { + return Err(anyhow!("resolution demand is stale or malformed")); + } + let sum: f32 = demand.axis_weights.values().sum(); + if (sum - 1.0).abs() > 0.02 { + return Err(anyhow!("resolution demand axis weights must sum to one")); + } + Ok(()) +} + +pub fn cell_action_limit(cell: &SimulationCell) -> usize { + match cell.mode { + SimulationCellMode::Cohesive => 1, + SimulationCellMode::Arena => { + let count = cell.subject_ids.len().max(1); + let ceil_log = if count <= 1 { + 0 + } else { + usize::BITS - (count - 1).leading_zeros() + }; + 4usize.min(1 + ceil_log as usize) + } + } +} + +fn mandatory_subjects(campaign: &Campaign, demand: &ResolutionDemand) -> BTreeSet { + let mut mandatory = demand.focal_subject_ids.clone(); + for pin in campaign.resolution_pins.values() { + if pin.kind == ResolutionPinKind::MinimumIndividualDetail { + mandatory.extend(pin.subject_ids.iter().cloned()); + } + } + for member in campaign.gestalt_members.values() { + if member.relevance_lease_until_revision > campaign.revision + && let Some(actor_id) = &member.materialized_actor_id + { + mandatory.insert(actor_id.clone()); + } + } + mandatory +} + +fn contract_together_pins( + groups: &mut HashMap>, + pins: &BTreeMap, + mandatory: &BTreeSet, +) { + for pin in pins + .values() + .filter(|pin| pin.kind == ResolutionPinKind::KeepTogether) + { + if !pin.subject_ids.is_disjoint(mandatory) { + continue; + } + let keys: Vec<_> = groups + .iter() + .filter(|(_, subjects)| !subjects.is_disjoint(&pin.subject_ids)) + .map(|(key, _)| key.clone()) + .collect(); + let mut joined = BTreeSet::new(); + for key in keys { + if let Some(subjects) = groups.remove(&key) { + joined.extend(subjects); + } + } + if !joined.is_empty() { + groups.insert(cell_id(&joined, &SimulationCellMode::Arena), joined); + } + } +} + +fn candidates( + campaign: &Campaign, + profiles: &BTreeMap, + groups: &HashMap>, + group_samples: &HashMap>, + neighbors: &HashMap>, + scoring: &ScoringCache, + demand: &ResolutionDemand, + mandatory: &BTreeSet, +) -> BinaryHeap { + let mut heap = BinaryHeap::new(); + for (left, adjacent) in neighbors { + for right in adjacent.iter().filter(|right| left < *right) { + if let Some(candidate) = candidate_for( + campaign, + profiles, + groups, + group_samples, + left, + right, + scoring, + demand, + mandatory, + ) { + heap.push(candidate); + } + } + } + heap +} + +fn candidate_for( + campaign: &Campaign, + profiles: &BTreeMap, + groups: &HashMap>, + group_samples: &HashMap>, + left_id: &str, + right_id: &str, + scoring: &ScoringCache, + demand: &ResolutionDemand, + mandatory: &BTreeSet, +) -> Option { + let left = groups.get(left_id)?; + let right = groups.get(right_id)?; + if !left.is_disjoint(mandatory) + || !right.is_disjoint(mandatory) + || violates_separate_pin(left, right, &campaign.resolution_pins) + { + return None; + } + let sample = representative_sample( + group_samples + .get(left_id)? + .iter() + .chain(group_samples.get(right_id)?.iter()), + ); + let loss = score_merge(campaign, profiles, scoring, left, right, &sample, demand); + let (left, right) = if left_id <= right_id { + (left_id.to_owned(), right_id.to_owned()) + } else { + (right_id.to_owned(), left_id.to_owned()) + }; + Some(Candidate { left, right, loss }) +} + +fn group_neighbors( + groups: &HashMap>, + graph: &DerivedAgencyGraph, +) -> HashMap> { + let mut subject_group = HashMap::new(); + for (group_id, subjects) in groups { + for subject in subjects { + subject_group.insert(subject.clone(), group_id.clone()); + } + } + let mut result: HashMap<_, _> = groups + .keys() + .map(|id| (id.clone(), BTreeSet::new())) + .collect(); + for (subject, adjacent) in &graph.neighbors { + let Some(left) = subject_group.get(subject) else { + continue; + }; + for other in adjacent { + let Some(right) = subject_group.get(other) else { + continue; + }; + if left != right { + result + .entry(left.clone()) + .or_default() + .insert(right.clone()); + result + .entry(right.clone()) + .or_default() + .insert(left.clone()); + } + } + } + result +} + +fn violates_separate_pin( + left: &BTreeSet, + right: &BTreeSet, + pins: &BTreeMap, +) -> bool { + pins.values() + .filter(|pin| pin.kind == ResolutionPinKind::KeepSeparate) + .any(|pin| !left.is_disjoint(&pin.subject_ids) && !right.is_disjoint(&pin.subject_ids)) +} + +fn classify_and_score( + campaign: &Campaign, + profiles: &BTreeMap, + scoring: &ScoringCache, + subjects: &BTreeSet, + demand: &ResolutionDemand, +) -> (SimulationCellMode, MergeLoss) { + if subjects.len() <= 1 { + return (SimulationCellMode::Cohesive, MergeLoss::default()); + } + let sampled = bounded_profiles(profiles, subjects); + classify_selection( + campaign, + profiles, + scoring, + sampled, + subjects.iter(), + |id| subjects.contains(id), + subjects.len(), + demand, + ) +} + +fn score_merge( + campaign: &Campaign, + profiles: &BTreeMap, + scoring: &ScoringCache, + left: &BTreeSet, + right: &BTreeSet, + sample_subject_ids: &[String], + demand: &ResolutionDemand, +) -> MergeLoss { + let constituent_count = left.len() + right.len(); + let sampled = sample_subject_ids + .iter() + .filter_map(|id| profiles.get(id)) + .collect(); + classify_selection( + campaign, + profiles, + scoring, + sampled, + std::iter::empty::<&String>(), + |id| left.contains(id) || right.contains(id), + constituent_count, + demand, + ) + .1 +} + +fn classify_selection<'a, I, F>( + campaign: &Campaign, + profiles: &BTreeMap, + scoring: &ScoringCache, + sampled: Vec<&AgencyProfile>, + authority_subjects: I, + contains: F, + constituent_count: usize, + demand: &ResolutionDemand, +) -> (SimulationCellMode, MergeLoss) +where + I: IntoIterator, + F: Fn(&str) -> bool, +{ + let facet = weighted_facet_divergence(&sampled, demand); + let information = set_divergence( + &sampled + .iter() + .map(|profile| &profile.information_channels) + .collect::>(), + ); + let spatial = spatial_divergence(campaign, &sampled, demand.horizon_minutes); + let obligation_sets: Vec<_> = sampled + .iter() + .filter_map(|profile| scoring.pressure_tokens.get(&profile.subject_id)) + .collect(); + let clock_obligation = set_divergence(&obligation_sets); + let mut authorities = BTreeSet::new(); + for subject in authority_subjects { + if let Some(authority) = profiles + .get(subject) + .and_then(|profile| profile.collective_authority_id.as_deref()) + { + authorities.insert(authority); + if authorities.len() > 1 { + break; + } + } + } + let hostile = campaign.agency_relations.values().any(|relation| { + relation.active + && matches!( + relation.kind, + AgencyRelationKind::Rivalry | AgencyRelationKind::Coercion + ) + && contains(&relation.from_subject_id) + && contains(&relation.to_subject_id) + }); + let boundary = hidden_boundary_mass_where(campaign, &contains); + let salience = sampled + .iter() + .filter_map(|profile| scoring.salience.get(&profile.subject_id).copied()) + .fold(0.0_f32, f32::max); + let churn = campaign.resolution_cover.as_ref().is_some_and(|cover| { + !cover.cells.iter().any(|cell| { + cell.subject_ids.len() == constituent_count + && cell.subject_ids.iter().all(|id| contains(id)) + }) + }) as u8 as f32; + let total = 0.25 * facet + + 0.20 * boundary + + 0.15 * information + + 0.15 * spatial + + 0.10 * clock_obligation + + 0.10 * salience + + 0.05 * churn; + let loss = MergeLoss { + facet_divergence: facet, + hidden_boundary_mass: boundary, + information_divergence: information, + spatial_divergence: spatial, + clock_obligation_divergence: clock_obligation, + salience_burial: salience, + partition_churn: churn, + total, + }; + let cohesive = authorities.len() == 1 + && !hostile + && information <= 0.20 + && facet <= 0.25 + && clock_obligation <= 0.25; + ( + if cohesive { + SimulationCellMode::Cohesive + } else { + SimulationCellMode::Arena + }, + loss, + ) +} + +fn bounded_profiles<'a>( + profiles: &'a BTreeMap, + subjects: &BTreeSet, +) -> Vec<&'a AgencyProfile> { + let stride = subjects.len().div_ceil(PROFILE_SAMPLE_LIMIT).max(1); + subjects + .iter() + .step_by(stride) + .take(PROFILE_SAMPLE_LIMIT) + .filter_map(|id| profiles.get(id)) + .collect() +} + +const PROFILE_SAMPLE_LIMIT: usize = 8; + +fn representative_sample<'a>(subjects: impl Iterator) -> Vec { + let mut ranked = subjects + .map(|id| (sample_rank(id), id.clone())) + .collect::>(); + ranked.sort_unstable(); + ranked.dedup_by(|left, right| left.1 == right.1); + ranked.truncate(PROFILE_SAMPLE_LIMIT); + ranked.into_iter().map(|(_, id)| id).collect() +} + +fn sample_rank(id: &str) -> u64 { + id.as_bytes().iter().fold(0xcbf29ce484222325, |hash, byte| { + (hash ^ u64::from(*byte)).wrapping_mul(0x100000001b3) + }) +} + +fn pressure_tokens(campaign: &Campaign, subject_id: &str) -> BTreeSet { + if let Some(actor) = campaign.actors.get(subject_id) { + return actor + .obligations + .iter() + .cloned() + .chain(actor.goals.iter().map(|value| format!("goal:{value}"))) + .chain( + actor + .conditions + .iter() + .map(|value| format!("condition:{value}")), + ) + .collect(); + } + if let Some(institution) = campaign.institutions.get(subject_id) { + return institution + .goals + .iter() + .map(|value| format!("goal:{value}")) + .chain(std::iter::once(format!("posture:{}", institution.posture))) + .collect(); + } + campaign + .gestalts + .get(subject_id) + .map(|gestalt| { + gestalt + .goals + .iter() + .map(|value| format!("goal:{value}")) + .chain( + gestalt + .pressures + .iter() + .map(|value| format!("pressure:{value}")), + ) + .collect() + }) + .unwrap_or_default() +} + +fn subject_salience(campaign: &Campaign, profile: &AgencyProfile) -> f32 { + let debt = profile.detail_debt.min(64) as f32 / 64.0; + let event = campaign.events.iter().rev().take(16).any(|event| { + event.actor_ids.contains(&profile.subject_id) + || event.institution_ids.contains(&profile.subject_id) + }) as u8 as f32; + let conflict = campaign.agency_relations.values().any(|relation| { + relation.active + && matches!( + relation.kind, + AgencyRelationKind::Rivalry | AgencyRelationKind::Coercion + ) + && (relation.from_subject_id == profile.subject_id + || relation.to_subject_id == profile.subject_id) + }) as u8 as f32; + (0.45 * debt + 0.30 * event + 0.25 * conflict).clamp(0.0, 1.0) +} + +fn spatial_divergence( + campaign: &Campaign, + profiles: &[&AgencyProfile], + horizon_minutes: u32, +) -> f32 { + if profiles.len() <= 1 { + return 0.0; + } + let mut total = 0.0; + let mut pairs = 0u32; + for (index, left) in profiles.iter().enumerate() { + for right in profiles.iter().skip(index + 1) { + let distance = if !left.location_ids.is_disjoint(&right.location_ids) { + 0.0 + } else { + let minutes = left + .location_ids + .iter() + .flat_map(|location| { + campaign + .locations + .get(location) + .into_iter() + .flat_map(|value| value.routes.values()) + }) + .filter(|route| right.location_ids.contains(&route.destination_id)) + .map(|route| route.travel_minutes) + .min(); + minutes + .map(|minutes| minutes as f32 / horizon_minutes.max(1) as f32) + .unwrap_or(1.0) + .clamp(0.0, 1.0) + }; + total += distance; + pairs += 1; + } + } + total / pairs.max(1) as f32 +} + +fn weighted_facet_divergence(profiles: &[&AgencyProfile], demand: &ResolutionDemand) -> f32 { + demand + .axis_weights + .iter() + .map(|(axis, weight)| { + let empty = BTreeSet::new(); + let sets: Vec<_> = profiles + .iter() + .map(|profile| profile.facets.get(axis).unwrap_or(&empty)) + .collect(); + weight * set_divergence(&sets) + }) + .sum::() + .clamp(0.0, 1.0) +} + +fn set_divergence(sets: &[&BTreeSet]) -> f32 { + if sets.len() <= 1 { + return 0.0; + } + let mut total = 0.0; + let mut pairs = 0; + for (index, left) in sets.iter().enumerate() { + for right in sets.iter().skip(index + 1) { + let union = left.union(right).count(); + let similarity = if union == 0 { + 1.0 + } else { + left.intersection(right).count() as f32 / union as f32 + }; + total += 1.0 - similarity; + pairs += 1; + } + } + if pairs == 0 { + 0.0 + } else { + total / pairs as f32 + } +} + +fn hidden_boundary_mass_where(campaign: &Campaign, contains: &F) -> f32 +where + F: Fn(&str) -> bool, +{ + let mut mass = 0u32; + let mut possible = 0u32; + for relation in campaign + .agency_relations + .values() + .filter(|relation| relation.active) + { + if contains(&relation.from_subject_id) && contains(&relation.to_subject_id) { + possible += 100; + if !matches!( + relation.kind, + AgencyRelationKind::Containment | AgencyRelationKind::SharedLocation + ) { + mass += u32::from(relation.strength); + } + } + } + if possible == 0 { + 0.0 + } else { + mass as f32 / possible as f32 + } +} + +fn cut_rationale(subjects: &BTreeSet, demand: &ResolutionDemand) -> String { + let axis = demand + .axis_weights + .iter() + .max_by(|left, right| left.1.total_cmp(right.1).then_with(|| left.0.cmp(right.0))) + .map(|(axis, _)| format!("{axis:?}").to_lowercase()) + .unwrap_or_else(|| "mixed".into()); + format!( + "{} subjects grouped under {axis}-weighted demand", + subjects.len() + ) +} + +fn cell_id(subjects: &BTreeSet, mode: &SimulationCellMode) -> String { + let material = format!( + "{mode:?}:{}", + subjects.iter().cloned().collect::>().join("|") + ); + format!("cell:{:x}", Sha256::digest(material.as_bytes())) +} + +pub fn validate_cover( + campaign: &Campaign, + demand: &ResolutionDemand, + cells: &[SimulationCell], +) -> Result<()> { + let graph = DerivedAgencyGraph::build( + campaign, + campaign + .agency_profiles + .values() + .filter(|profile| profile.active_leaf && profile.simulation_eligible) + .map(|profile| profile.subject_id.clone()) + .collect(), + ); + validate_cover_with_graph(campaign, demand, cells, &graph) +} + +fn validate_cover_with_graph( + campaign: &Campaign, + demand: &ResolutionDemand, + cells: &[SimulationCell], + graph: &DerivedAgencyGraph, +) -> Result<()> { + let scoring = ScoringCache::new(campaign, &campaign.agency_profiles); + let expected: BTreeSet<_> = campaign + .agency_profiles + .values() + .filter(|profile| profile.active_leaf && profile.simulation_eligible) + .map(|profile| profile.subject_id.clone()) + .collect(); + let mut actual = BTreeSet::new(); + for cell in cells { + if cell.subject_ids.is_empty() + || cell.subject_ids.iter().any(|id| !actual.insert(id.clone())) + || (cell.subject_ids.len() > 1 && !connected(graph, &cell.subject_ids)) + || cell.id != cell_id(&cell.subject_ids, &cell.mode) + || (cell.mode == SimulationCellMode::Cohesive + && classify_and_score( + campaign, + &campaign.agency_profiles, + &scoring, + &cell.subject_ids, + demand, + ) + .0 != SimulationCellMode::Cohesive) + { + return Err(anyhow!("resolution cover contains an invalid cell")); + } + } + if actual != expected { + return Err(anyhow!( + "resolution cover does not cover every active subject exactly once" + )); + } + Ok(()) +} + +fn connected(graph: &DerivedAgencyGraph, subjects: &BTreeSet) -> bool { + let Some(start) = subjects.iter().next() else { + return false; + }; + let mut seen = BTreeSet::from([start.clone()]); + let mut queue = VecDeque::from([start.clone()]); + while let Some(current) = queue.pop_front() { + for next in graph.neighbors.get(¤t).into_iter().flatten() { + if subjects.contains(next) && seen.insert(next.clone()) { + queue.push_back(next.clone()); + } + } + } + seen == *subjects +} + +pub fn advance_detail_debt(campaign: &mut Campaign, cover: &ResolutionCover) { + let focused: BTreeSet<_> = cover + .cells + .iter() + .filter_map(|cell| cell.detail_focus_subject_id.clone()) + .chain( + cover + .cells + .iter() + .filter(|cell| cell.subject_ids.len() == 1) + .flat_map(|cell| cell.subject_ids.iter().cloned()), + ) + .collect(); + for profile in campaign + .agency_profiles + .values_mut() + .filter(|profile| profile.active_leaf) + { + if focused.contains(&profile.subject_id) { + profile.detail_debt = 0; + profile.last_detail_tick = campaign.strategic_tick_count.saturating_add(1); + } else { + profile.detail_debt = profile.detail_debt.saturating_add(1); + } + profile.profile_version = profile.profile_version.saturating_add(1); + } +} + +pub fn plan_receipt(campaign: &Campaign, cover: &ResolutionCover) -> ResolutionPlanReceipt { + let previous: BTreeSet<_> = campaign + .resolution_cover + .as_ref() + .map(|value| value.cells.iter().map(|cell| cell.id.clone()).collect()) + .unwrap_or_default(); + let current: BTreeSet<_> = cover.cells.iter().map(|cell| cell.id.clone()).collect(); + let preserved_cell_ids = current.intersection(&previous).cloned().collect::>(); + let collapsed_boundaries = cover + .cells + .iter() + .filter(|cell| cell.subject_ids.len() > 1) + .map(|cell| { + format!( + "{}:{}", + match cell.mode { + SimulationCellMode::Cohesive => "cohesive", + SimulationCellMode::Arena => "arena", + }, + cell.subject_ids + .iter() + .cloned() + .collect::>() + .join("|") + ) + }) + .collect(); + ResolutionPlanReceipt { + schema: "ghostlight.resolution_plan_receipt.v1".into(), + campaign_id: campaign.id, + world_revision: campaign.revision, + resolution_epoch: campaign.resolution_policy.resolution_epoch, + configured_budget: cover.configured_budget, + effective_budget: cover.effective_budget, + cell_ids: cover.cells.iter().map(|cell| cell.id.clone()).collect(), + mandatory_overage: cover.mandatory_overage, + preserved_cell_ids, + collapsed_boundaries, + merge_losses: cover + .cells + .iter() + .map(|cell| (cell.id.clone(), cell.merge_loss.clone())) + .collect(), + rationale: format!( + "{} active cells under {:?}-weighted pressure; {} mandatory overage", + cover.effective_budget, + cover + .demand + .axis_weights + .iter() + .max_by(|left, right| left.1.total_cmp(right.1)) + .map(|(axis, _)| axis), + cover.mandatory_overage + ), + created_at: chrono::Utc::now(), + } +} + +pub fn validate_and_resolve_wave( + campaign: &Campaign, + wave: &ResolutionWaveCommit, +) -> Result { + if wave.world_revision != campaign.revision + || wave.resolution_epoch != campaign.resolution_policy.resolution_epoch + || wave.cover.world_revision != campaign.revision + || wave.cover.resolution_epoch != campaign.resolution_policy.resolution_epoch + || wave.plan_receipt.world_revision != campaign.revision + || wave.plan_receipt.resolution_epoch != campaign.resolution_policy.resolution_epoch + || wave + .model_receipt_hashes + .iter() + .any(|hash| !is_sha256(hash)) + { + return Err(anyhow!("resolution wave is stale or malformed")); + } + validate_demand(campaign, &wave.cover.demand)?; + validate_cover(campaign, &wave.cover.demand, &wave.cover.cells)?; + if wave.plan_receipt.cell_ids + != wave + .cover + .cells + .iter() + .map(|cell| cell.id.clone()) + .collect::>() + { + return Err(anyhow!("resolution receipt does not bind the active cover")); + } + let cells: BTreeMap<_, _> = wave + .cover + .cells + .iter() + .map(|cell| (cell.id.as_str(), cell)) + .collect(); + if wave.appraisals.len() != cells.len() { + return Err(anyhow!( + "every active cell must appraise the wave exactly once" + )); + } + let mut seen_cells = BTreeSet::new(); + let mut proposals = Vec::new(); + for appraisal in &wave.appraisals { + let cell = cells + .get(appraisal.cell_id.as_str()) + .ok_or_else(|| anyhow!("cell appraisal references an inactive cell"))?; + if !seen_cells.insert(appraisal.cell_id.as_str()) + || appraisal.world_revision != campaign.revision + || appraisal.resolution_epoch != campaign.resolution_policy.resolution_epoch + || appraisal.considered_subject_ids != cell.subject_ids + || (appraisal.actions.is_empty() + && appraisal + .inaction_reason + .as_deref() + .is_none_or(str::is_empty)) + { + return Err(anyhow!("cell appraisal is incomplete or stale")); + } + let quota = cell_action_limit(cell); + if appraisal.actions.len() > quota { + return Err(anyhow!("cell appraisal exceeds its action quota")); + } + for proposal in &appraisal.actions { + validate_cell_proposal(campaign, cell, proposal)?; + proposals.push(proposal.clone()); + } + } + proposals.sort_by(|left, right| { + right + .priority + .cmp(&left.priority) + .then_with(|| left.subject_id.cmp(&right.subject_id)) + .then_with(|| left.intent.cmp(&right.intent)) + }); + let consequence_limit = 16usize.min(usize::from(wave.cover.effective_budget) * 2); + let mut used = BTreeSet::new(); + let mut plan = StrategicTickPlan::default(); + for proposal in proposals { + let key = proposal_target_key(&proposal.effect); + if !used.insert(key) { + continue; + } + match proposal.effect { + StrategicCellEffect::Institution { + institution_id, + posture, + location_ids, + } => plan.institution_actions.push(StrategicInstitutionAction { + institution_id, + posture, + summary: proposal.intended_effect, + location_ids, + public_channels: proposal.public_channels, + }), + StrategicCellEffect::Gestalt { + gestalt_id, + pressure_additions, + } => plan.gestalt_actions.push(StrategicGestaltAction { + gestalt_id, + summary: proposal.intended_effect, + pressure_additions, + public_channels: proposal.public_channels, + }), + StrategicCellEffect::ActorMove { + actor_id, + destination_id, + } => plan.actor_moves.push(StrategicActorMove { + actor_id, + destination_id, + summary: proposal.intended_effect, + public_channels: proposal.public_channels, + }), + } + if plan.institution_actions.len() + plan.gestalt_actions.len() + plan.actor_moves.len() + >= consequence_limit + { + break; + } + } + Ok(plan) +} + +fn validate_cell_proposal( + campaign: &Campaign, + cell: &SimulationCell, + proposal: &CellActionProposal, +) -> Result<()> { + if !cell.subject_ids.contains(&proposal.subject_id) + || proposal.subject_id == campaign.player_actor_id + || proposal.intent.trim().is_empty() + || proposal.intended_effect.trim().is_empty() + { + return Err(anyhow!("cell proposal has no exact constituent authority")); + } + let profile = campaign + .agency_profiles + .get(&proposal.subject_id) + .ok_or_else(|| anyhow!("cell proposal constituent lacks an agency profile"))?; + let permitted_references = subject_state_references(campaign, &proposal.subject_id)?; + if proposal + .state_references + .iter() + .any(|reference| !permitted_references.contains(reference)) + || proposal + .public_channels + .iter() + .any(|channel| !profile.information_channels.contains(channel)) + { + return Err(anyhow!( + "cell proposal exceeds constituent knowledge, resources, or information scope" + )); + } + match &proposal.effect { + StrategicCellEffect::Institution { + institution_id, + location_ids, + .. + } => { + if institution_id != &proposal.subject_id + || !campaign.institutions.contains_key(institution_id) + || location_ids + .iter() + .any(|id| !campaign.locations.contains_key(id)) + || location_ids + .iter() + .any(|id| !profile.location_ids.contains(id)) + { + return Err(anyhow!("institution proposal exceeds constituent state")); + } + } + StrategicCellEffect::Gestalt { gestalt_id, .. } => { + if gestalt_id != &proposal.subject_id || !campaign.gestalts.contains_key(gestalt_id) { + return Err(anyhow!("gestalt proposal exceeds constituent state")); + } + } + StrategicCellEffect::ActorMove { + actor_id, + destination_id, + } => { + let actor = campaign + .actors + .get(actor_id) + .filter(|_| actor_id == &proposal.subject_id) + .ok_or_else(|| anyhow!("actor proposal exceeds constituent state"))?; + let reachable = campaign + .locations + .get(&actor.location_id) + .is_some_and(|location| { + location.routes.values().any(|route| { + route.destination_id == *destination_id + && route.travel_minutes <= campaign.tick_hours.saturating_mul(60) + }) + }); + if !reachable { + return Err(anyhow!("actor proposal exceeds spatial reach")); + } + } + } + Ok(()) +} + +pub fn subject_state_references(campaign: &Campaign, subject_id: &str) -> Result> { + let profile = campaign + .agency_profiles + .get(subject_id) + .ok_or_else(|| anyhow!("agency subject is unknown"))?; + let mut references = BTreeSet::from([format!("subject:{subject_id}")]); + references.extend( + profile + .location_ids + .iter() + .map(|value| format!("location:{value}")), + ); + references.extend(profile.facets.iter().flat_map(|(axis, values)| { + values + .iter() + .map(move |value| format!("facet:{axis:?}:{value}")) + })); + if let Some(actor) = campaign.actors.get(subject_id) { + references.extend( + actor + .capabilities + .iter() + .map(|value| format!("capability:{value}")) + .chain( + actor + .knowledge + .iter() + .map(|value| format!("knowledge:{value}")), + ) + .chain( + actor + .equipment + .iter() + .map(|value| format!("equipment:{value}")), + ) + .chain( + actor + .obligations + .iter() + .map(|value| format!("obligation:{value}")), + ), + ); + } + if let Some(institution) = campaign.institutions.get(subject_id) { + references.extend( + institution + .resources + .iter() + .map(|value| format!("resource:{value}")) + .chain( + institution + .goals + .iter() + .map(|value| format!("goal:{value}")), + ), + ); + } + if let Some(gestalt) = campaign.gestalts.get(subject_id) { + references.extend( + gestalt + .shared_capabilities + .iter() + .map(|value| format!("capability:{value}")) + .chain( + gestalt + .shared_knowledge + .iter() + .map(|value| format!("knowledge:{value}")), + ) + .chain( + gestalt + .resources + .iter() + .map(|value| format!("resource:{value}")), + ), + ); + } + Ok(references) +} + +fn proposal_target_key(effect: &StrategicCellEffect) -> String { + match effect { + StrategicCellEffect::Institution { institution_id, .. } => { + format!("institution:{institution_id}") + } + StrategicCellEffect::Gestalt { gestalt_id, .. } => format!("gestalt:{gestalt_id}"), + StrategicCellEffect::ActorMove { actor_id, .. } => format!("actor:{actor_id}"), + } +} + +fn is_sha256(value: &str) -> bool { + value + .strip_prefix("sha256:") + .is_some_and(|hex| hex.len() == 64 && hex.bytes().all(|byte| byte.is_ascii_hexdigit())) +} + +pub fn apply_fission(campaign: &mut Campaign, preview: &GestaltFissionPreview) -> Result<()> { + validate_fission(campaign, preview)?; + let parent = campaign + .gestalts + .get_mut(&preview.parent_gestalt_id) + .ok_or_else(|| anyhow!("fission parent vanished"))?; + parent.version = parent.version.saturating_add(1); + let parent_profile = campaign + .agency_profiles + .get_mut(&preview.parent_gestalt_id) + .ok_or_else(|| anyhow!("fission parent lacks an agency profile"))?; + parent_profile.active_leaf = false; + parent_profile.simulation_eligible = false; + parent_profile.profile_version = parent_profile.profile_version.saturating_add(1); + let inherited = parent_profile.clone(); + for child in &preview.children { + campaign.gestalts.insert(child.id.clone(), child.clone()); + let mut profile = profile_for_gestalt(child, &preview.evidence_receipt_ids); + profile.parent_subject_id = Some(preview.parent_gestalt_id.clone()); + profile.facets = inherited.facets.clone(); + profile + .facets + .entry(preview.partition_axis.clone()) + .or_default() + .insert( + preview + .child_partition_values + .get(&child.id) + .expect("validated child partition value") + .clone(), + ); + for receipt_id in &inherited.evidence_receipt_ids { + if !profile.evidence_receipt_ids.contains(receipt_id) { + profile.evidence_receipt_ids.push(receipt_id.clone()); + } + } + campaign.agency_profiles.insert(child.id.clone(), profile); + } + for member in campaign + .gestalt_members + .values_mut() + .filter(|member| member.gestalt_id == preview.parent_gestalt_id) + { + member.gestalt_id = preview + .member_child_assignments + .get(&member.id) + .cloned() + .unwrap_or_else(|| preview.residual_child_id.clone()); + member.version = member.version.saturating_add(1); + } + let inherited_relations: Vec<_> = campaign + .agency_relations + .values() + .filter(|relation| { + relation.active + && (relation.from_subject_id == preview.parent_gestalt_id + || relation.to_subject_id == preview.parent_gestalt_id) + }) + .cloned() + .collect(); + for relation in inherited_relations { + for child in &preview.children { + let mut inherited_relation = relation.clone(); + inherited_relation.id = format!("{}:fission:{}", relation.id, child.id); + if inherited_relation.from_subject_id == preview.parent_gestalt_id { + inherited_relation.from_subject_id = child.id.clone(); + } + if inherited_relation.to_subject_id == preview.parent_gestalt_id { + inherited_relation.to_subject_id = child.id.clone(); + } + campaign + .agency_relations + .insert(inherited_relation.id.clone(), inherited_relation); + } + } + campaign.gestalt_lineages.insert( + preview.parent_gestalt_id.clone(), + GestaltLineage { + schema: "ghostlight.gestalt_lineage.v1".into(), + parent_gestalt_id: preview.parent_gestalt_id.clone(), + child_gestalt_ids: preview + .children + .iter() + .map(|child| child.id.clone()) + .collect(), + partition_axis: preview.partition_axis.clone(), + partition_values: preview.child_partition_values.clone(), + residual_child_id: preview.residual_child_id.clone(), + source_revision: campaign.revision, + }, + ); + campaign.resolution_cover = None; + campaign.resolution_policy.resolution_epoch = campaign + .resolution_policy + .resolution_epoch + .saturating_add(1); + Ok(()) +} + +pub fn validate_fission(campaign: &Campaign, preview: &GestaltFissionPreview) -> Result<()> { + let parent = campaign + .gestalts + .get(&preview.parent_gestalt_id) + .ok_or_else(|| anyhow!("fission parent is unknown"))?; + let parent_profile = campaign + .agency_profiles + .get(&preview.parent_gestalt_id) + .filter(|profile| profile.active_leaf) + .ok_or_else(|| anyhow!("fission parent is not an active leaf gestalt"))?; + let child_ids: BTreeSet<_> = preview + .children + .iter() + .map(|child| child.id.as_str()) + .collect(); + let residual_value = preview + .child_partition_values + .get(&preview.residual_child_id) + .map(|value| value.trim().to_ascii_lowercase()); + if preview.campaign_id != campaign.id + || preview.expected_world_revision != campaign.revision + || !preview.requires_approval + || preview.children.len() < 2 + || child_ids.len() != preview.children.len() + || !child_ids.contains(preview.residual_child_id.as_str()) + || residual_value.as_deref() != Some("other/unknown") + || preview.child_partition_values.len() != preview.children.len() + || preview.children.iter().any(|child| { + child.id.trim().is_empty() + || child.name.trim().is_empty() + || child.version != 0 + || campaign.gestalts.contains_key(&child.id) + || !campaign.locations.contains_key(&child.home_location_id) + || (preview.partition_axis != AgencyAxis::Geography + && child.home_location_id != parent.home_location_id) + || !preview.child_partition_values.contains_key(&child.id) + }) + || preview + .member_child_assignments + .iter() + .any(|(member, child)| { + campaign + .gestalt_members + .get(member) + .is_none_or(|value| value.gestalt_id != parent.id) + || !child_ids.contains(child.as_str()) + }) + || parent_profile.subject_kind != AgencySubjectKind::Gestalt + { + return Err(anyhow!("gestalt fission preview is stale or malformed")); + } + Ok(()) +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use chrono::Utc; + use std::time::Instant; + use uuid::Uuid; + + pub(crate) fn campaign(subjects: usize, budget: u8) -> Campaign { + let player_id = "player".to_owned(); + let actors = BTreeMap::from([( + player_id.clone(), + ActorState { + id: player_id.clone(), + name: "Player".into(), + location_id: "center".into(), + capabilities: BTreeSet::new(), + knowledge: BTreeSet::new(), + equipment: BTreeSet::new(), + conditions: BTreeSet::new(), + obligations: BTreeSet::new(), + relationships: BTreeMap::new(), + goals: vec![], + memories: vec![], + }, + )]); + let institutions = (0..subjects) + .map(|index| { + let id = format!("faction-{index:04}"); + ( + id.clone(), + InstitutionState { + id, + name: format!("Faction {index}"), + resources: vec![format!("resource-{}", index % 7)], + goals: vec![format!("goal-{}", index % 5)], + posture: format!("posture-{}", index % 3), + }, + ) + }) + .collect(); + let mut value = Campaign { + schema: "ghostlight.campaign.v1".into(), + id: Uuid::new_v4(), + name: "Resolution fixture".into(), + revision: 0, + branch_origin: BranchOrigin { + canon_cutoff: "fixture".into(), + evidence_receipt_ids: vec![], + }, + world_time: Utc::now(), + tick_hours: 6, + player_actor_id: player_id, + locations: BTreeMap::from([( + "center".into(), + Location { + id: "center".into(), + name: "Center".into(), + container_id: None, + routes: BTreeMap::new(), + persistent_features: vec![], + }, + )]), + actors, + institutions, + clocks: BTreeMap::new(), + facts: BTreeMap::new(), + transcript: vec![], + last_player_activity: Utc::now(), + pending_ticks: 0, + away_ticks_processed: 0, + events: vec![], + news: vec![], + canon_candidates: BTreeMap::new(), + gestalts: BTreeMap::new(), + gestalt_members: BTreeMap::new(), + pending_world_proposals: vec![], + agency_profiles: BTreeMap::new(), + agency_relations: BTreeMap::new(), + gestalt_lineages: BTreeMap::new(), + resolution_policy: ResolutionPolicy { + active_cell_budget: budget, + ..ResolutionPolicy::default() + }, + resolution_pins: BTreeMap::new(), + resolution_cover: None, + strategic_tick_count: 0, + }; + ensure_agency_profiles(&mut value); + for (index, profile) in value + .agency_profiles + .values_mut() + .filter(|profile| profile.simulation_eligible) + .enumerate() + { + profile.facets.insert( + AgencyAxis::Geography, + BTreeSet::from([format!("region-{}", index % 4)]), + ); + profile.facets.insert( + AgencyAxis::Ideology, + BTreeSet::from([format!("ideology-{}", index % 6)]), + ); + profile.facets.insert( + AgencyAxis::SpeciesBody, + BTreeSet::from([format!("body-{}", index % 2)]), + ); + } + value + } + + #[test] + fn aetheria_scale_cover_is_complete_unique_and_budgeted() { + for budget in [1, 4, 8, 32] { + let value = campaign(24, budget); + let cover = plan_cover(&value, default_demand(&value, "test pressure")).unwrap(); + assert_eq!(cover.cells.len(), usize::from(budget).min(24)); + let covered: Vec<_> = cover + .cells + .iter() + .flat_map(|cell| cell.subject_ids.iter()) + .collect(); + assert_eq!(covered.len(), 24); + assert_eq!(covered.iter().copied().collect::>().len(), 24); + validate_cover(&value, &cover.demand, &cover.cells).unwrap(); + } + } + + #[test] + fn results_and_tie_breaking_are_deterministic() { + let value = campaign(24, 8); + let demand = default_demand(&value, "same pressure"); + assert_eq!( + plan_cover(&value, demand.clone()).unwrap(), + plan_cover(&value, demand).unwrap() + ); + } + + #[test] + fn rivals_at_budget_one_form_an_arena_not_a_false_collective() { + let mut value = campaign(2, 1); + value.agency_relations.insert( + "rivalry".into(), + AgencyRelation { + schema: "ghostlight.agency_relation.v1".into(), + id: "rivalry".into(), + from_subject_id: "faction-0000".into(), + to_subject_id: "faction-0001".into(), + kind: AgencyRelationKind::Rivalry, + strength: 100, + active: true, + evidence_receipt_ids: vec![], + }, + ); + let cover = plan_cover(&value, default_demand(&value, "war")).unwrap(); + assert_eq!(cover.cells.len(), 1); + assert_eq!(cover.cells[0].mode, SimulationCellMode::Arena); + } + + #[test] + fn foreground_subjects_create_reported_temporary_overage() { + let value = campaign(5, 1); + let mut demand = default_demand(&value, "foreground"); + demand.focal_subject_ids = BTreeSet::from([ + "faction-0000".into(), + "faction-0001".into(), + "faction-0002".into(), + ]); + let cover = plan_cover(&value, demand).unwrap(); + assert_eq!(cover.effective_budget, 4); + assert_eq!(cover.mandatory_overage, 3); + for id in ["faction-0000", "faction-0001", "faction-0002"] { + assert!( + cover + .cells + .iter() + .any(|cell| { cell.subject_ids == BTreeSet::from([id.to_owned()]) }) + ); + } + } + + #[test] + fn contradictory_pins_are_rejected() { + let mut value = campaign(3, 2); + value.resolution_pins.insert( + "together".into(), + ResolutionPin { + schema: "ghostlight.resolution_pin.v1".into(), + id: "together".into(), + kind: ResolutionPinKind::KeepTogether, + subject_ids: BTreeSet::from(["faction-0000".into(), "faction-0001".into()]), + reason: "test".into(), + created_world_revision: 0, + }, + ); + value.resolution_pins.insert( + "apart".into(), + ResolutionPin { + schema: "ghostlight.resolution_pin.v1".into(), + id: "apart".into(), + kind: ResolutionPinKind::KeepSeparate, + subject_ids: BTreeSet::from(["faction-0000".into(), "faction-0001".into()]), + reason: "test".into(), + created_world_revision: 0, + }, + ); + assert!(plan_cover(&value, default_demand(&value, "pins")).is_err()); + } + + #[test] + fn detail_debt_rotates_low_budget_attention() { + let mut value = campaign(6, 1); + let mut focused = BTreeSet::new(); + for _ in 0..6 { + let cover = plan_cover(&value, default_demand(&value, "quiet world")).unwrap(); + focused.insert( + cover.cells[0] + .detail_focus_subject_id + .clone() + .expect("aggregate must have a detail focus"), + ); + advance_detail_debt(&mut value, &cover); + value.resolution_cover = Some(cover); + value.strategic_tick_count += 1; + value.revision += 1; + } + assert_eq!(focused.len(), 6); + } + + #[test] + fn planning_never_mutates_canonical_state() { + let value = campaign(24, 4); + let before = value.clone(); + let _ = plan_cover(&value, default_demand(&value, "read only")).unwrap(); + assert_eq!(value, before); + } + + #[test] + fn partitions_one_thousand_subjects_with_bounded_local_work() { + let value = campaign(1_000, 8); + let started = Instant::now(); + let cover = plan_cover(&value, default_demand(&value, "large skeleton")).unwrap(); + assert_eq!(cover.cells.len(), 8); + if cfg!(debug_assertions) { + assert!(started.elapsed().as_secs_f32() < 6.0); + } else { + assert!(started.elapsed().as_millis() < 100); + } + } + + #[test] + fn arena_cannot_act_as_a_collective_or_borrow_a_constituents_secret() { + let mut value = campaign(2, 1); + value.agency_relations.insert( + "rivalry".into(), + AgencyRelation { + schema: "ghostlight.agency_relation.v1".into(), + id: "rivalry".into(), + from_subject_id: "faction-0000".into(), + to_subject_id: "faction-0001".into(), + kind: AgencyRelationKind::Rivalry, + strength: 100, + active: true, + evidence_receipt_ids: vec![], + }, + ); + value + .agency_profiles + .get_mut("faction-0001") + .unwrap() + .information_channels + .insert("secret-courier".into()); + let cover = plan_cover(&value, default_demand(&value, "espionage")).unwrap(); + let cell = cover.cells[0].clone(); + assert_eq!(cell.mode, SimulationCellMode::Arena); + let make_wave = |proposal: CellActionProposal| ResolutionWaveCommit { + schema: "ghostlight.resolution_wave_commit.v1".into(), + world_revision: value.revision, + resolution_epoch: value.resolution_policy.resolution_epoch, + plan_receipt: plan_receipt(&value, &cover), + appraisals: vec![CellAppraisal { + schema: "ghostlight.cell_appraisal.v1".into(), + cell_id: cell.id.clone(), + world_revision: value.revision, + resolution_epoch: value.resolution_policy.resolution_epoch, + considered_subject_ids: cell.subject_ids.clone(), + actions: vec![proposal], + inaction_reason: None, + }], + cover: cover.clone(), + model_receipt_hashes: vec![], + }; + let collective = CellActionProposal { + subject_id: cell.id.clone(), + intent: "speak for everyone".into(), + intended_effect: "declare consensus".into(), + priority: 1, + state_references: vec![], + public_channels: vec![], + effect: StrategicCellEffect::Institution { + institution_id: "faction-0000".into(), + posture: "unified".into(), + location_ids: vec![], + }, + }; + assert!(validate_and_resolve_wave(&value, &make_wave(collective)).is_err()); + let borrowed_secret = CellActionProposal { + subject_id: "faction-0000".into(), + intent: "publish through a rival's courier".into(), + intended_effect: "send a message".into(), + priority: 1, + state_references: vec![], + public_channels: vec!["secret-courier".into()], + effect: StrategicCellEffect::Institution { + institution_id: "faction-0000".into(), + posture: "messaging".into(), + location_ids: vec![], + }, + }; + assert!(validate_and_resolve_wave(&value, &make_wave(borrowed_secret)).is_err()); + } + + #[test] + fn fission_preserves_parent_and_member_delta_while_activating_child_leaves() { + let mut value = campaign(1, 1); + value.gestalts.insert( + "villagers".into(), + GestaltPersonaState { + schema: "ghostlight.gestalt_persona_state.v1".into(), + id: "villagers".into(), + name: "Villagers".into(), + version: 0, + home_location_id: "center".into(), + shared_capabilities: BTreeSet::from(["farm".into()]), + shared_knowledge: BTreeSet::from(["local roads".into()]), + resources: BTreeSet::from(["granary".into()]), + goals: vec!["survive winter".into()], + pressures: vec![], + }, + ); + value.gestalt_members.insert( + "john".into(), + GestaltMemberDelta { + schema: "ghostlight.gestalt_member_delta.v1".into(), + id: "john".into(), + gestalt_id: "villagers".into(), + version: 3, + name: "John".into(), + capability_additions: BTreeSet::from(["smith".into()]), + capability_removals: BTreeSet::new(), + knowledge_additions: BTreeSet::new(), + knowledge_removals: BTreeSet::new(), + equipment: BTreeSet::from(["hammer".into()]), + conditions: BTreeSet::new(), + obligations: BTreeSet::new(), + relationships: BTreeMap::new(), + goals: vec![], + memories: vec!["met the traveler".into()], + last_location_id: Some("center".into()), + materialized_actor_id: None, + last_relevant_revision: 0, + relevance_lease_until_revision: 0, + }, + ); + ensure_agency_profiles(&mut value); + let child = |id: &str, name: &str| GestaltPersonaState { + schema: "ghostlight.gestalt_persona_state.v1".into(), + id: id.into(), + name: name.into(), + version: 0, + home_location_id: "center".into(), + shared_capabilities: BTreeSet::from(["farm".into()]), + shared_knowledge: BTreeSet::from(["local roads".into()]), + resources: BTreeSet::from(["granary".into()]), + goals: vec!["survive winter".into()], + pressures: vec![], + }; + let preview = GestaltFissionPreview { + schema: "ghostlight.gestalt_fission_preview.v1".into(), + campaign_id: value.id, + expected_world_revision: value.revision, + parent_gestalt_id: "villagers".into(), + partition_axis: AgencyAxis::Ideology, + children: vec![ + child("traditionalists", "Traditionalists"), + child("other", "Other villagers"), + ], + child_partition_values: BTreeMap::from([ + ("traditionalists".into(), "traditionalist".into()), + ("other".into(), "other/unknown".into()), + ]), + residual_child_id: "other".into(), + member_child_assignments: BTreeMap::new(), + evidence_receipt_ids: vec![], + gaps: vec![], + canon_candidates: vec![], + requires_approval: true, + }; + apply_fission(&mut value, &preview).unwrap(); + assert!(value.gestalts.contains_key("villagers")); + assert!(!value.agency_profiles["villagers"].active_leaf); + assert!(value.agency_profiles["traditionalists"].active_leaf); + assert!(value.agency_profiles["other"].active_leaf); + assert_eq!(value.gestalt_members["john"].gestalt_id, "other"); + assert_eq!(value.gestalt_members["john"].version, 4); + assert!( + value.gestalt_members["john"] + .memories + .contains(&"met the traveler".into()) + ); + assert_eq!( + value.gestalt_lineages["villagers"].residual_child_id, + "other" + ); + } + + #[test] + fn golden_pressures_preserve_the_behavioral_boundary_they_weight() { + for axis in [ + AgencyAxis::Geography, + AgencyAxis::Ideology, + AgencyAxis::EconomyRole, + AgencyAxis::SpeciesBody, + AgencyAxis::Information, + ] { + let mut value = campaign(4, 2); + for (index, id) in (0..4).map(|index| (index, format!("faction-{index:04}"))) { + let profile = value.agency_profiles.get_mut(&id).unwrap(); + for current in [ + AgencyAxis::Geography, + AgencyAxis::Ideology, + AgencyAxis::Authority, + AgencyAxis::EconomyRole, + AgencyAxis::SpeciesBody, + AgencyAxis::Information, + ] { + profile + .facets + .insert(current, BTreeSet::from(["shared".into()])); + } + profile.facets.insert( + axis.clone(), + BTreeSet::from([format!("side-{}", index / 2)]), + ); + } + let mut demand = default_demand(&value, format!("golden {axis:?}")); + for weight in demand.axis_weights.values_mut() { + *weight = 0.02; + } + demand.axis_weights.insert(axis.clone(), 0.90); + let cover = plan_cover(&value, demand).unwrap(); + assert_eq!(cover.cells.len(), 2); + for cell in cover.cells { + let preserved_values: BTreeSet<_> = cell + .subject_ids + .iter() + .flat_map(|id| value.agency_profiles[id].facets[&axis].iter().cloned()) + .collect(); + assert_eq!(preserved_values.len(), 1, "failed golden pressure {axis:?}"); + } + } + } +} diff --git a/crates/ghostlight-dungeon/src/scheduler.rs b/crates/ghostlight-dungeon/src/scheduler.rs index 9c16332..7e51e88 100644 --- a/crates/ghostlight-dungeon/src/scheduler.rs +++ b/crates/ghostlight-dungeon/src/scheduler.rs @@ -1,70 +1,333 @@ use crate::{ - domain::{Campaign, StrategicTickPlan}, + domain::{ + AgencyAxis, AgencySubjectKind, Campaign, ResolutionDemand, ResolutionWaveCommit, + SimulationCell, + }, model::{ModelPort, ModelStageOutput, ModelStageRequest, run_validated_stage}, + persona::{CellConstituentSlice, CellProjectionEngine, ExecutionPermit, PermittedCellSlice}, + resolution::{ + cell_action_limit, default_demand, plan_cover, plan_receipt, validate_and_resolve_wave, + validate_demand, + }, }; -use anyhow::{Context, Result}; +use anyhow::{Context, Result, anyhow}; use chrono::{DateTime, Utc}; -use schemars::schema_for; +use schemars::{JsonSchema, schema_for}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; -pub async fn propose_strategic_tick( +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +struct DemandProjection { + axis_weights: BTreeMap, + focal_subject_ids: BTreeSet, + rationale: String, +} + +pub struct StrategicResolutionOutput { + pub wave: ResolutionWaveCommit, + pub stages: Vec, + pub aggregate_receipt_hash: String, +} + +pub async fn propose_resolution_wave( + model: Arc, + permit: Arc, + campaign: &Campaign, +) -> Result { + let (demand, mut stages) = project_resolution_demand(model.as_ref(), campaign).await; + let cover = plan_cover(campaign, demand)?; + let receipt = plan_receipt(campaign, &cover); + let engine = CellProjectionEngine { + model, + permit, + projector_model: "deepseek-v4-flash".into(), + persona_model: "deepseek-v4-flash".into(), + interpreter_model: "deepseek-v4-flash".into(), + }; + let semaphore = Arc::new(tokio::sync::Semaphore::new(usize::from( + campaign.resolution_policy.provider_parallelism.max(1), + ))); + let mut jobs = tokio::task::JoinSet::new(); + for cell in cover.cells.clone() { + let engine = engine.clone(); + let semaphore = semaphore.clone(); + let slice = cell_slice(campaign, &cell)?; + jobs.spawn(async move { + let _permit = semaphore + .acquire_owned() + .await + .map_err(|_| anyhow!("provider concurrency gate closed"))?; + let terminal = engine.execute(slice).await?; + Ok::<_, anyhow::Error>((cell.id, terminal)) + }); + } + let mut terminals = Vec::new(); + while let Some(result) = jobs.join_next().await { + terminals.push(result.map_err(|error| anyhow!("cell Persona task failed: {error}"))??); + } + terminals.sort_by(|left, right| left.0.cmp(&right.0)); + let appraisals = terminals + .iter() + .map(|(_, terminal)| terminal.appraisal.clone()) + .collect(); + for (_, terminal) in terminals { + stages.extend( + terminal + .stage_receipts + .into_iter() + .map(|receipt| ModelStageOutput { + narrative: String::new(), + structured: None, + receipt, + }), + ); + } + let model_receipt_hashes = stages + .iter() + .map(|stage| stage.receipt.storage_key().to_owned()) + .collect::>(); + let aggregate_receipt_hash = format!( + "sha256:{:x}", + Sha256::digest(model_receipt_hashes.join("|").as_bytes()) + ); + let wave = ResolutionWaveCommit { + schema: "ghostlight.resolution_wave_commit.v1".into(), + world_revision: campaign.revision, + resolution_epoch: campaign.resolution_policy.resolution_epoch, + cover, + plan_receipt: receipt, + appraisals, + model_receipt_hashes, + }; + validate_and_resolve_wave(campaign, &wave)?; + Ok(StrategicResolutionOutput { + wave, + stages, + aggregate_receipt_hash, + }) +} + +async fn project_resolution_demand( model: &dyn ModelPort, campaign: &Campaign, -) -> Result<(StrategicTickPlan, ModelStageOutput)> { - let player_id = &campaign.player_actor_id; - let actors = campaign - .actors - .iter() - .filter(|(id, _)| *id != player_id) - .map(|(id, actor)| { - serde_json::json!({ - "id":id, - "location_id":actor.location_id, - "goals":actor.goals, - "conditions":actor.conditions, - "obligations":actor.obligations +) -> (ResolutionDemand, Vec) { + let fallback = || { + campaign + .resolution_cover + .as_ref() + .map(|cover| { + let mut demand = cover.demand.clone(); + demand.world_revision = campaign.revision; + demand.resolution_epoch = campaign.resolution_policy.resolution_epoch; + demand.rationale = format!("last accepted demand: {}", demand.rationale); + demand }) - }) - .collect::>(); + .unwrap_or_else(|| default_demand(campaign, "default geography/authority demand")) + }; + let active_ids: Vec<_> = campaign + .agency_profiles + .values() + .filter(|profile| profile.active_leaf && profile.simulation_eligible) + .map(|profile| profile.subject_id.clone()) + .collect(); let context = serde_json::json!({ - "campaign_id":campaign.id, - "revision":campaign.revision, - "world_time":campaign.world_time, - "tick_hours":campaign.tick_hours, - "locations":campaign.locations, - "player_information_access": campaign.actors.get(player_id).map(|actor| serde_json::json!({ - "knowledge_channels": actor.knowledge, - "equipment": actor.equipment - })), - "remote_actors":actors, - "institutions":campaign.institutions, - "gestalts":campaign.gestalts, - "clocks":campaign.clocks, - "recent_events":campaign.events.iter().rev().take(12).collect::>() + "campaign_id": campaign.id, + "world_revision": campaign.revision, + "resolution_epoch": campaign.resolution_policy.resolution_epoch, + "horizon_minutes": campaign.tick_hours.saturating_mul(60), + "allowed_subject_ids": active_ids, + "clocks": campaign.clocks, + "recent_events": campaign.events.iter().rev().take(12).collect::>(), + "relations": campaign.agency_relations.values().filter(|relation| relation.active).collect::>(), + "profiles": campaign.agency_profiles.values().filter(|profile| profile.active_leaf && profile.simulation_eligible).collect::>() }); - let schema = serde_json::to_value(schema_for!(StrategicTickPlan))?; - let output = run_validated_stage( - model, - &ModelStageRequest { - stage: "strategic_tick".into(), - model: "deepseek-v4-flash".into(), - snapshot_binding: format!("campaign:{}:revision:{}", campaign.id, campaign.revision), - lived_stream: format!( - "Propose one bounded offscreen strategic tick. Institutions, remote actors, and gestalt populations act in their own interests. At least one supplied non-player power with a credible goal, pressure, resource, or reachable movement must act; use empty arrays only when the supplied state genuinely affords no action. Do not control, move, injure, or directly target the absent player. Use only supplied IDs. Actor movement must use a direct listed route whose travel time fits inside tick_hours. Keep summaries concrete. Pressure additions are branch-local population pressure, not new canon knowledge. For each action, public_channels names concrete information mechanisms through which that event can later become known (radio, newspaper, courier, rumor network); leave it empty only for a genuinely secret event. When a public event credibly travels through one of player_information_access.knowledge_channels, copy that channel string exactly. The kernel independently gates news by exact channel access. Return only one JSON object matching the supplied schema.\nSTATE:\n{}\nOUTPUT JSON SCHEMA:\n{}", - serde_json::to_string(&context)?, - serde_json::to_string_pretty(&schema)? - ), - output_schema: Some(schema), - source_receipt_ids: campaign.branch_origin.evidence_receipt_ids.clone(), - }, - ) - .await?; - let plan = serde_json::from_value( - output + let mut schema = match serde_json::to_value(schema_for!(DemandProjection)) { + Ok(value) => value, + Err(_) => return (fallback(), vec![]), + }; + if let Some(items) = schema.pointer_mut("/properties/focal_subject_ids/items") { + *items = serde_json::json!({"type":"string","enum":active_ids}); + } + let base_prompt = format!( + "Project which boundaries best predict different strategic behavior for the next horizon. Return all six axis weights (geography, ideology, authority, economy_role, species_body, information), each from 0 to 1 and summing to 1. Focal subjects may only use supplied IDs. This stage proposes relevance and cannot change world state. Return one JSON object matching the schema.\nSTATE:\n{}\nOUTPUT JSON SCHEMA:\n{}", + serde_json::to_string(&context).unwrap_or_default(), + serde_json::to_string_pretty(&schema).unwrap_or_default(), + ); + let mut request = ModelStageRequest { + stage: "resolution_demand".into(), + model: "deepseek-v4-flash".into(), + snapshot_binding: format!( + "campaign:{}:revision:{}:resolution:{}", + campaign.id, campaign.revision, campaign.resolution_policy.resolution_epoch + ), + lived_stream: base_prompt, + output_schema: Some(schema), + source_receipt_ids: campaign.branch_origin.evidence_receipt_ids.clone(), + }; + let mut outputs = Vec::new(); + for attempt in 0..2 { + let Ok(mut output) = run_validated_stage(model, &request).await else { + return (fallback(), outputs); + }; + let projection = output .structured .clone() - .context("strategic tick stage returned no structured plan")?, - )?; - Ok((plan, output)) + .and_then(|value| serde_json::from_value::(value).ok()); + if let Some(projection) = projection { + let demand = ResolutionDemand { + schema: "ghostlight.resolution_demand.v1".into(), + campaign_id: campaign.id, + world_revision: campaign.revision, + resolution_epoch: campaign.resolution_policy.resolution_epoch, + axis_weights: projection.axis_weights, + focal_subject_ids: projection.focal_subject_ids, + horizon_minutes: campaign.tick_hours.saturating_mul(60), + rationale: projection.rationale, + }; + if validate_demand(campaign, &demand).is_ok() { + outputs.push(output); + return (demand, outputs); + } + } + output.receipt.validation_result = "semantic_invalid".into(); + outputs.push(output); + if attempt == 0 { + request.lived_stream.push_str( + "\n\nLOCAL VALIDATOR: The prior projection omitted an axis, used an unknown subject, had invalid weights, failed to sum to one, or had no rationale. Return one corrected object against the same snapshot.", + ); + } + } + (fallback(), outputs) +} + +fn cell_slice(campaign: &Campaign, cell: &SimulationCell) -> Result { + let constituents = cell + .subject_ids + .iter() + .map(|id| constituent_slice(campaign, id)) + .collect::>>()?; + let shared_knowledge = intersection( + constituents + .iter() + .map(|subject| &subject.knowledge) + .collect(), + ); + let shared_capabilities = intersection( + constituents + .iter() + .map(|subject| &subject.capabilities) + .collect(), + ); + Ok(PermittedCellSlice { + cell_id: cell.id.clone(), + mode: cell.mode.clone(), + world_revision: campaign.revision, + resolution_epoch: campaign.resolution_policy.resolution_epoch, + snapshot_binding: format!( + "campaign:{}:revision:{}:resolution:{}:cell:{}", + campaign.id, campaign.revision, campaign.resolution_policy.resolution_epoch, cell.id + ), + constituents, + shared_knowledge, + shared_capabilities, + perceived_events: campaign + .events + .iter() + .rev() + .take(12) + .map(|event| event.summary.clone()) + .collect(), + world_clock_pressure: campaign + .clocks + .values() + .map(|clock| { + format!( + "{}: {}/{}; consequence {}", + clock.label, clock.progress, clock.threshold, clock.consequence + ) + }) + .collect(), + detail_focus_subject_id: cell.detail_focus_subject_id.clone(), + max_actions: cell_action_limit(cell), + source_receipt_ids: campaign.branch_origin.evidence_receipt_ids.clone(), + }) +} + +fn constituent_slice(campaign: &Campaign, id: &str) -> Result { + let profile = campaign + .agency_profiles + .get(id) + .ok_or_else(|| anyhow!("simulation cell subject lacks an agency profile"))?; + let mut value = CellConstituentSlice { + subject_id: id.into(), + subject_kind: profile.subject_kind.clone(), + name: id.into(), + collective_authority_id: profile.collective_authority_id.clone(), + location_ids: profile.location_ids.clone(), + knowledge: BTreeSet::new(), + capabilities: BTreeSet::new(), + resources: BTreeSet::new(), + information_channels: profile.information_channels.clone(), + permitted_state_references: crate::resolution::subject_state_references(campaign, id)?, + reachable_destination_ids: BTreeSet::new(), + goals: vec![], + pressures: vec![], + }; + match profile.subject_kind { + AgencySubjectKind::Actor => { + let actor = campaign.actors.get(id).context("cell actor vanished")?; + value.name = actor.name.clone(); + value.knowledge = actor.knowledge.clone(); + value.capabilities = actor.capabilities.clone(); + value.resources = actor.equipment.clone(); + value.goals = actor.goals.clone(); + value.pressures = actor + .conditions + .iter() + .chain(&actor.obligations) + .cloned() + .collect(); + value.reachable_destination_ids = campaign + .locations + .get(&actor.location_id) + .into_iter() + .flat_map(|location| location.routes.values()) + .filter(|route| route.travel_minutes <= campaign.tick_hours.saturating_mul(60)) + .map(|route| route.destination_id.clone()) + .collect(); + } + AgencySubjectKind::Institution => { + let institution = campaign + .institutions + .get(id) + .context("cell institution vanished")?; + value.name = institution.name.clone(); + value.resources = institution.resources.iter().cloned().collect(); + value.goals = institution.goals.clone(); + value.pressures = vec![institution.posture.clone()]; + } + AgencySubjectKind::Gestalt => { + let gestalt = campaign.gestalts.get(id).context("cell gestalt vanished")?; + value.name = gestalt.name.clone(); + value.knowledge = gestalt.shared_knowledge.clone(); + value.capabilities = gestalt.shared_capabilities.clone(); + value.resources = gestalt.resources.clone(); + value.goals = gestalt.goals.clone(); + value.pressures = gestalt.pressures.clone(); + } + } + Ok(value) +} + +fn intersection(sets: Vec<&BTreeSet>) -> BTreeSet { + let Some(first) = sets.first() else { + return BTreeSet::new(); + }; + sets.iter().skip(1).fold((*first).clone(), |current, next| { + current.intersection(next).cloned().collect() + }) } pub fn due_tick_target(now: DateTime, last_player_activity: DateTime) -> u8 { @@ -79,6 +342,86 @@ pub fn due_tick_target(now: DateTime, last_player_activity: DateTime) #[cfg(test)] mod tests { use super::*; + use crate::model::ModelPort; + use crate::persona::AllowAllPermit; + use async_trait::async_trait; + use std::sync::atomic::{AtomicUsize, Ordering}; + + struct CellFixtureModel { + active: AtomicUsize, + maximum: AtomicUsize, + malformed_cell: bool, + } + + impl CellFixtureModel { + fn enter(&self) -> ActiveCall<'_> { + let active = self.active.fetch_add(1, Ordering::SeqCst) + 1; + self.maximum.fetch_max(active, Ordering::SeqCst); + ActiveCall(self) + } + } + + struct ActiveCall<'a>(&'a CellFixtureModel); + impl Drop for ActiveCall<'_> { + fn drop(&mut self) { + self.0.active.fetch_sub(1, Ordering::SeqCst); + } + } + + #[async_trait] + impl ModelPort for CellFixtureModel { + async fn run(&self, request: &ModelStageRequest) -> Result { + let _active = self.enter(); + tokio::time::sleep(std::time::Duration::from_millis(2)).await; + match request.stage.as_str() { + "resolution_demand" => Ok(serde_json::json!({ + "axis_weights": { + "geography":0.25, + "ideology":0.20, + "authority":0.25, + "economy_role":0.15, + "species_body":0.05, + "information":0.10 + }, + "focal_subject_ids":[], + "rationale":"fixture pressure" + }) + .to_string()), + "cell_projector" => Ok("Several powers feel the horizon tightening.".into()), + "cell_persona" => Ok("Each constituent watches and deliberately holds.".into()), + "cell_interpreter" if self.malformed_cell => Ok("not-json".into()), + "cell_interpreter" => { + let context = request + .lived_stream + .split("Permissioned typed context:\n") + .nth(1) + .and_then(|value| value.split("\n\nLived stream:").next()) + .context("fixture could not locate typed cell context")?; + let slice: PermittedCellSlice = serde_json::from_str(context)?; + Ok(serde_json::to_string(&crate::domain::CellAppraisal { + schema: "ghostlight.cell_appraisal.v1".into(), + cell_id: slice.cell_id, + world_revision: slice.world_revision, + resolution_epoch: slice.resolution_epoch, + considered_subject_ids: slice + .constituents + .into_iter() + .map(|value| value.subject_id) + .collect(), + actions: vec![], + inaction_reason: Some( + "No constituent has a justified move this horizon.".into(), + ), + })?) + } + stage => Err(anyhow!("unexpected fixture stage {stage}")), + } + } + + fn provider(&self) -> &'static str { + "fixture" + } + } #[test] fn away_budget_waits_and_caps_at_eight() { @@ -88,4 +431,40 @@ mod tests { assert_eq!(due_tick_target(now, now - chrono::Duration::hours(1)), 1); assert_eq!(due_tick_target(now, now - chrono::Duration::hours(30)), 8); } + + #[tokio::test] + async fn every_selected_cell_runs_one_membrane_pipeline() { + let mut campaign = crate::resolution::tests::campaign(6, 2); + campaign.resolution_policy.provider_parallelism = 2; + let model = Arc::new(CellFixtureModel { + active: AtomicUsize::new(0), + maximum: AtomicUsize::new(0), + malformed_cell: false, + }); + let output = propose_resolution_wave(model.clone(), Arc::new(AllowAllPermit), &campaign) + .await + .unwrap(); + assert_eq!(output.wave.cover.cells.len(), 2); + assert_eq!(output.wave.appraisals.len(), 2); + assert_eq!(output.stages.len(), 7); + assert!(model.maximum.load(Ordering::SeqCst) <= 2); + validate_and_resolve_wave(&campaign, &output.wave).unwrap(); + } + + #[tokio::test] + async fn one_malformed_cell_aborts_the_whole_wave() { + let campaign = crate::resolution::tests::campaign(6, 2); + let before = campaign.clone(); + let model = Arc::new(CellFixtureModel { + active: AtomicUsize::new(0), + maximum: AtomicUsize::new(0), + malformed_cell: true, + }); + assert!( + propose_resolution_wave(model, Arc::new(AllowAllPermit), &campaign) + .await + .is_err() + ); + assert_eq!(campaign, before); + } } diff --git a/crates/ghostlight-dungeon/src/surface.rs b/crates/ghostlight-dungeon/src/surface.rs index c32293b..fe93a81 100644 --- a/crates/ghostlight-dungeon/src/surface.rs +++ b/crates/ghostlight-dungeon/src/surface.rs @@ -8,6 +8,16 @@ use crate::{ use serde_json::{Value, json}; pub fn player_surface(campaign: &Campaign, narrations: &[NarrationProjection]) -> Value { + let interface_version = campaign + .revision + .saturating_mul(1_000_000_000_000) + .saturating_add( + campaign + .resolution_policy + .resolution_epoch + .saturating_mul(1_000_000), + ) + .saturating_add(campaign.resolution_policy.provider_configuration_epoch); let mut story = narrations.iter().map(|n| json!({"id":format!("narration-{}",n.source_revision),"kind":"text","props":{"value":n.text},"children":[]})).collect::>(); story.extend(campaign.transcript.iter().map(|t| json!({"id":format!("turn-{}-{}",t.revision,t.speaker),"kind":"text","props":{"value":format!("{}: {}",t.speaker,t.text)},"children":[]}))); let player = &campaign.actors[&campaign.player_actor_id]; @@ -38,13 +48,27 @@ pub fn player_surface(campaign: &Campaign, narrations: &[NarrationProjection]) - .collect::>() .join("\n"); let news=campaign.news.iter().map(|item|json!({"id":item.id,"kind":"text","props":{"value":format!("[{}] {}",item.channel,item.headline)},"children":[]})).collect::>(); + let effective_budget = campaign + .resolution_cover + .as_ref() + .map(|cover| cover.effective_budget) + .unwrap_or(campaign.resolution_policy.active_cell_budget); json!({ "type":"surface-state", "schema":"gamecult.eve.surface.v1", "providerId":"gamecult.ghostlight.dungeon", - "providerKind":"narrative.simulation", "title":campaign.name, "version":campaign.revision, + "providerKind":"narrative.simulation", "title":campaign.name, "version":interface_version, + "world_revision":campaign.revision, + "resolution":{ + "policy":campaign.resolution_policy, + "effective_budget":effective_budget, + "mandatory_overage":campaign.resolution_cover.as_ref().map(|cover| cover.mandatory_overage).unwrap_or(0), + "pins":campaign.resolution_pins.values().collect::>(), + "fission_targets":campaign.agency_profiles.values().filter(|profile| profile.active_leaf && profile.subject_kind == crate::domain::AgencySubjectKind::Gestalt).filter_map(|profile| campaign.gestalts.get(&profile.subject_id).map(|gestalt| json!({"id":gestalt.id,"name":gestalt.name}))).collect::>() + }, "surface":{"id":format!("ghostlight.campaign.{}",campaign.id),"root":{"id":"dungeon.root","kind":"surface","props":{},"children":[ {"id":"dungeon.status","kind":"card","props":{"title":format!("{} · revision {} · {}",campaign.name,campaign.revision,campaign.world_time)},"children":[]}, {"id":"dungeon.location","kind":"card","props":{"title":format!("{} · {}",location.name,player.name)},"children":[{"id":"dungeon.pressures","kind":"text","props":{"value":pressures},"children":[]}]}, {"id":"dungeon.ledger","kind":"card","props":{"title":"Character ledger"},"children":[{"id":"dungeon.ledger.text","kind":"text","props":{"value":ledger},"children":[]}]}, + {"id":"dungeon.resolution","kind":"card","props":{"title":format!("World resolution · {} configured / {} effective",campaign.resolution_policy.active_cell_budget,effective_budget)},"children":[{"id":"dungeon.resolution.text","kind":"text","props":{"value":format!("Resolution epoch {} · {} pins · {} temporary overage",campaign.resolution_policy.resolution_epoch,campaign.resolution_pins.len(),campaign.resolution_cover.as_ref().map(|cover| cover.mandatory_overage).unwrap_or(0))},"children":[]}]}, {"id":"dungeon.news","kind":"card","props":{"title":"Accessible news and rumors"},"children":news}, {"id":"dungeon.transcript","kind":"card","props":{"title":"Story"},"children":story}, {"id":"dungeon.composer","kind":"text-input","props":{"label":"What do you attempt?","commandId":"attempt.assess"},"children":[]} @@ -61,8 +85,59 @@ pub fn operator_surface( strategic_ticks: &[StrategicTickReceipt], gestalt_receipts: &[GestaltMaterializationReceipt], rejected: &[RejectedProposalReceipt], + resolution_plans: &[crate::domain::ResolutionPlanReceipt], + cell_appraisals: &[crate::domain::CellAppraisal], + resolution_controls: &[crate::domain::ResolutionControlReceipt], live_turn_pressure: usize, ) -> Value { + let interface_version = campaign + .revision + .saturating_mul(1_000_000_000_000) + .saturating_add( + campaign + .resolution_policy + .resolution_epoch + .saturating_mul(1_000_000), + ) + .saturating_add(campaign.resolution_policy.provider_configuration_epoch); + let cover_text = campaign + .resolution_cover + .as_ref() + .map(|cover| { + cover + .cells + .iter() + .map(|cell| { + format!( + "{} {:?} [{}] loss {:.3} debt focus {} — {}", + cell.id, + cell.mode, + cell.subject_ids + .iter() + .cloned() + .collect::>() + .join(", "), + cell.merge_loss.total, + cell.detail_focus_subject_id.as_deref().unwrap_or("none"), + cell.rationale + ) + }) + .collect::>() + .join("\n") + }) + .unwrap_or_else(|| "No cover has committed yet.".into()); + let graph_text = campaign + .agency_relations + .values() + .filter(|relation| relation.active) + .map(|relation| { + format!( + "{} --{:?}/{}--> {}", + relation.from_subject_id, relation.kind, relation.strength, relation.to_subject_id + ) + }) + .collect::>() + .join("\n"); let typed = json!({ "campaign": campaign, "evidence": evidence, @@ -71,13 +146,18 @@ pub fn operator_surface( "strategic_ticks": strategic_ticks, "gestalt_materialization_receipts": gestalt_receipts, "rejected_proposals": rejected, + "resolution_plan_receipts": resolution_plans, + "cell_appraisals": cell_appraisals, + "resolution_control_receipts": resolution_controls, "scheduler": {"live_turn_pressure": live_turn_pressure} }); json!({ "type":"surface-state", "schema":"gamecult.eve.surface.v1", "providerId":"gamecult.ghostlight.dungeon", - "providerKind":"narrative.simulation.operator", "title":format!("{} operator",campaign.name), "version":campaign.revision, + "providerKind":"narrative.simulation.operator", "title":format!("{} operator",campaign.name), "version":interface_version, "surface":{"id":format!("ghostlight.operator.{}",campaign.id),"root":{"id":"dungeon.operator.root","kind":"surface","props":{},"children":[ {"id":"dungeon.operator.status","kind":"card","props":{"title":format!("Revision {} · {} model stages · {} rejected proposals",campaign.revision,stages.len(),rejected.len())},"children":[]}, + {"id":"dungeon.operator.cover","kind":"card","props":{"title":format!("Agency cover · epoch {} · budget {}",campaign.resolution_policy.resolution_epoch,campaign.resolution_policy.active_cell_budget)},"children":[{"id":"dungeon.operator.cover.text","kind":"text","props":{"value":cover_text},"children":[]}]}, + {"id":"dungeon.operator.graph","kind":"card","props":{"title":format!("Agency graph · {} profiles · {} relations",campaign.agency_profiles.len(),campaign.agency_relations.len())},"children":[{"id":"dungeon.operator.graph.text","kind":"text","props":{"value":graph_text},"children":[]}]}, {"id":"dungeon.operator.typed","kind":"code","props":{"language":"json","value":serde_json::to_string_pretty(&typed).unwrap_or_else(|_| "operator projection failed".into())},"children":[]} ]},"styles":{"tokens":{"colorBackground":"#0c1110","colorPanel":"#17201d","colorText":"#e8e1cf","colorMuted":"#9aa69f","colorAccent":"#d49b58"}}}, "commands":[] diff --git a/crates/ghostlight-dungeon/src/turn.rs b/crates/ghostlight-dungeon/src/turn.rs index b4e0ad7..d6ff2c4 100644 --- a/crates/ghostlight-dungeon/src/turn.rs +++ b/crates/ghostlight-dungeon/src/turn.rs @@ -11,6 +11,7 @@ pub struct SnapshotPermit { store: CampaignStore, campaign_id: uuid::Uuid, revision: u64, + resolution_epoch: Option, } impl SnapshotPermit { pub fn new(store: CampaignStore, campaign_id: uuid::Uuid, revision: u64) -> Self { @@ -18,6 +19,20 @@ impl SnapshotPermit { store, campaign_id, revision, + resolution_epoch: None, + } + } + pub fn new_resolution( + store: CampaignStore, + campaign_id: uuid::Uuid, + revision: u64, + resolution_epoch: u64, + ) -> Self { + Self { + store, + campaign_id, + revision, + resolution_epoch: Some(resolution_epoch), } } } @@ -29,7 +44,11 @@ impl ExecutionPermit for SnapshotPermit { .load::("campaign.v1", &self.campaign_id.to_string())? .map(|(_, c)| c) .ok_or_else(|| anyhow!("campaign vanished during Persona wave"))?; - if value.revision != self.revision { + if value.revision != self.revision + || self + .resolution_epoch + .is_some_and(|epoch| value.resolution_policy.resolution_epoch != epoch) + { return Err(anyhow!("Persona projection snapshot is stale")); } Ok(()) @@ -64,6 +83,9 @@ pub async fn appraise_present( .filter(|actor| actor.location_id == player.location_id) .map(|actor| (actor.id.clone(), actor.name.clone())) .collect::>(); + let semaphore = std::sync::Arc::new(tokio::sync::Semaphore::new(usize::from( + campaign.resolution_policy.provider_parallelism.max(1), + ))); let mut jobs = tokio::task::JoinSet::new(); for actor in actors { let engine = engine.clone(); @@ -71,7 +93,12 @@ pub async fn appraise_present( let event = event_summary.to_owned(); let receipts = campaign.branch_origin.evidence_receipt_ids.clone(); let perceived_actors = perceived_actors.clone(); + let semaphore = semaphore.clone(); jobs.spawn(async move { + let _provider_slot = semaphore + .acquire_owned() + .await + .map_err(|_| anyhow!("provider concurrency gate closed"))?; let slice = PermittedActorSlice { actor_id: actor.id.clone(), location_id: actor.location_id.clone(), diff --git a/docs/architecture/ghostlight-dungeon-mvp.md b/docs/architecture/ghostlight-dungeon-mvp.md index 0c870dc..9b6447d 100644 --- a/docs/architecture/ghostlight-dungeon-mvp.md +++ b/docs/architecture/ghostlight-dungeon-mvp.md @@ -225,6 +225,11 @@ implementation to make competing decisions after migration. ## Persona projection ownership +The population-scale partition and cell-wave authority is specified in +`ghostlight-multiresolution-agency.md`. It replaces a flat list of strategic +gestalts with a dynamic, budget-aware connected cover while preserving the +materialization rules below for named people. + ### Gestalt population materialization Large low-focus populations use a gestalt Persona without sacrificing durable @@ -584,7 +589,10 @@ Live play prevents new background model calls from launching. The absent player is not puppeted or directly harmed. Remote actors and institutions may move, prepare, recruit, investigate, bargain, obstruct, spend resources, and advance clocks. Information-channel-aware news is projected only if the player -character can access its channel. +character can access its channel. Each tick first projects current pressure, +builds a connected budgeted agency cover, and runs one private Persona membrane +per cell. Every appraisal and stage receipt must validate before the kernel +commits the strategic wave atomically. ### Eve/CultMesh and browser @@ -678,6 +686,19 @@ Ghostlight publishes JSON Schema for: - `ghostlight.strategic_tick.v1` - `ghostlight.news_issue.v1` - `ghostlight.canon_candidate.v1` +- `ghostlight.agency_profile.v1` +- `ghostlight.agency_relation.v1` +- `ghostlight.gestalt_lineage.v1` +- `ghostlight.resolution_policy.v1` +- `ghostlight.resolution_pin.v1` +- `ghostlight.resolution_demand.v1` +- `ghostlight.simulation_cell.v1` +- `ghostlight.resolution_cover.v1` +- `ghostlight.resolution_plan_receipt.v1` +- `ghostlight.resolution_control_receipt.v1` +- `ghostlight.cell_appraisal.v1` +- `ghostlight.cell_action_proposal.v1` +- `ghostlight.gestalt_fission_preview.v1` The UI consumes existing `gamecult.eve.surface.v1` and `gamecult.eve.command.v1` contracts. diff --git a/docs/architecture/ghostlight-multiresolution-agency.md b/docs/architecture/ghostlight-multiresolution-agency.md new file mode 100644 index 0000000..8c97648 --- /dev/null +++ b/docs/architecture/ghostlight-multiresolution-agency.md @@ -0,0 +1,215 @@ +# Ghostlight Multiresolution Agency Graph + +## Objective + +Let a campaign contain the whole strategic setting without pretending every +person, faction, institution, and population can receive a separate model turn. +Ghostlight preserves canonical fine state and changes only the resolution at +which that state is simulated during a wave. + +This document is the authority map for the implemented multiresolution organ. +The wider runtime map remains `ghostlight-dungeon-mvp.md`. + +## Authority map + +- **Owner:** `WorldKernel` owns canonical subjects, world revision, resolution + controls, accepted fission, and atomic strategic-wave commits. +- **Inputs:** canonical actors, institutions, gestalt leaves, typed agency + profiles and relations, resolution pins, current pressure demand, committed + clocks/events, and the previous accepted cover. +- **Outputs:** a revision-bound `ResolutionCover`, its plan receipt, one + appraisal per selected cell, exact constituent-attributed proposals, and one + atomic strategic transition. +- **Derived state:** simulation cells, merge losses, content-addressed cell IDs, + detail focus, and the active cover. None owns a person, population, secret, + relationship, possession, or fictional fact. +- **Forbidden writers:** demand projection, graph construction, the partitioner, + Projectors, Personas, Interpreters, scheduler, browser, and operator inspector + cannot mutate canonical world state. +- **Shared paths:** scheduled ticks and return catch-up both compile the same + `AdvanceStrategicTick` command. Budget and pin changes use the campaign + mailbox at safe boundaries. Provider parallelism uses a separate + configuration epoch and does not repartition or advance fiction. +- **Cut line:** the old flat strategic-plan proposer is gone. No active runtime + path may tick a hand-picked list of factions outside the selected cover or + union arena knowledge into a synthetic actor. + +`ActorState`, `InstitutionState`, `GestaltPersonaState`, and durable gestalt +member deltas remain canonical owners. `AgencyProfile` and `AgencyRelation` are +typed partition inputs. `SimulationCell` is always disposable and rebuildable. + +## Canonical population resolution + +Known population detail is represented by non-overlapping active gestalt +leaves. A material split uses approval-gated `FissionGestalt`: + +1. the compiler retrieves exact Vault evidence and produces a fission preview; +2. every requested enumerated facet gets a child and one `other/unknown` + remainder is mandatory; +3. children inherit the parent baseline and own only later deltas; +4. member deltas are assigned to one child without rewriting identity; +5. the parent remains as inactive lineage rather than being destroyed; +6. the kernel validates the preview, evidence, versions, assignments, and + residual child before one atomic commit. + +Reversible simulation aggregation never invokes fission and never deletes or +reverses this lineage. + +## Demand projection + +A flash-model structured stage converts the committed event or strategic +horizon into weights for geography, ideology, authority, economy role, +species/body, and information. Focal subjects must be chosen from supplied IDs. +Local semantic validation permits one same-snapshot correction. Failure falls +back to the last accepted demand; the initial fallback favors geography and +authority. + +Demand is relevance evidence. It cannot create profiles, pins, cells, or facts. + +## Agency graph + +Vertices are active canonical actors, institutions, and gestalt leaves. Edges +carry containment, command, membership, alliance, rivalry, trade, migration, +communication, coercion, and shared-location meaning. Subjects sharing a +location receive derived adjacency. Disconnected components receive a +resolution-only Steiner chain so the graph remains coarsenable; those bridge +edges assert no lore relation, common authority, proximity, or shared +knowledge. + +The compiler must profile every non-player actor, institution, and gestalt +exactly once across all six axes. It compiles a bounded local play region and a +global skeleton of major powers, coarse regions, institutions, information +channels, and strategic pressures. Runtime migration derives profiles for old +flat campaigns without changing their world revision, actors, institutions, +gestalts, or fictional time. + +## Budgeted connected cover + +The player selects an active Persona-cell budget from 1 through 32, default 8. +The partitioner: + +1. contracts valid `keep_together` pins; +2. forces focal, directly engaged, leased, initiative, targeted, and + `minimum_individual_detail` subjects into singleton cells; +3. respects `keep_separate` pins and reports mandatory effective-budget + overage rather than hiding a foreground subject; +4. starts at fine resolution and repeatedly merges the lowest-loss legal + graph-adjacent pair with deterministic tie-breaking; +5. performs one connected boundary-refinement pass and accepts a move only + when compression cost improves by at least five percent; +6. preserves a previous cover during its lease, or until a replacement improves + the weighted objective by at least ten percent, unless a forced split or + budget change applies; +7. validates complete unique coverage, connectedness, cell identity, mode, and + epoch before the cover can enter a wave. + +Compression cost is merge loss multiplied by the number of collapsed +trajectories. This prevents the objective from favoring one overloaded arena +merely because a singleton has zero local loss. + +The normalized merge loss is: + +```text +0.25 facet divergence ++ 0.20 hidden causal-boundary mass ++ 0.15 information-scope divergence ++ 0.15 spatial divergence ++ 0.10 clock/obligation divergence ++ 0.10 salience burial ++ 0.05 partition churn +``` + +Facet divergence is demand-weighted Jaccard distance. Spatial divergence uses +known locations, direct travel time, and the current strategic horizon. +Candidate scoring uses a deterministic mergeable representative sample for +bounded local work; exact authority, hostile relation, coverage, connectivity, +pins, and knowledge validation remain unsampled. + +Union-by-size owns constituent-set merges. This is not merely an optimization: +it keeps the 1,000-subject path from degenerating into quadratic copying while +leaving stable merge ordering unchanged. The release property test completes +the 1,000-subject, budget-8 partition in approximately 50 ms on the development +host, under the 100 ms contract. Setting `GHOSTLIGHT_PARTITION_TRACE` enables a +development-only phase timing probe. + +## Cell modes + +- **Cohesive:** all constituents share one actual collective authority, contain + no active hostile edge, and remain within information and behavioral + divergence thresholds. The cell may speak and act plurally. +- **Arena:** constituents remain distinct or opposed. The cell receives an + attributed polyphonic situation and may simulate interaction, but it has no + actor ID and cannot speak, know, decide, or act as a collective. + +Cross-faction aggregation is therefore an arena. Arena interpreters may emit at +most `min(4, 1 + ceil(log2(constituent_count)))` actions, each attributed to an +exact constituent. The kernel validates that subject's knowledge, information +channel, resources, authority, relationships, location, and reachable +destinations. Secrets are never unioned. + +## Fairness and quiet-world agency + +Every active profile carries persistent non-fictional `detail_debt`. Aggregate +representation increases debt; singleton or explicit detail focus clears it. +Each strategic wave reserves focus for the highest-debt subject. At budget 1, +the root arena retains the global situation while explicitly appraising that +subject. Deterministic clocks and obligations advance regardless of focus, and +every cell must emit explicit action or inaction. + +With N subjects, deterministic debt rotation gives every subject direct +resolution attention within at most N strategic waves, absent a mandatory +foreground override. + +## Persona-cell wave + +Each selected cell runs one Ghostlight-owned +Projector → Persona → Interpreter membrane: + +- cohesive Projectors expose genuinely shared lived state plus attributed + exceptions; +- arena Projectors expose attributed constituent slices and no synthetic actor; +- Personas receive only the private lived narrative stream; +- Interpreters emit a typed appraisal and exact constituent effects; +- malformed or semantically invalid output gets one same-snapshot correction. + +Physical provider concurrency batches these pipelines behind a separate +operator limit, default 8. Changing that limit increments only +`provider_configuration_epoch`; it preserves the selected cover, resolution +epoch, world revision, clocks, and fictional time. + +All cell results must bind the same campaign revision and resolution epoch. +The kernel requires a Projector, Persona, and Interpreter receipt for every +cell, validates every proposal, resolves incompatibilities deterministically, +caps committed consequences at `min(16, 2 × effective_budget)`, and commits the +entire wave once. One missing appraisal, stale receipt, malformed stage, +invalid cover, or invalid effect aborts the wave without partial mutation. + +## Public state and controls + +The schema catalog and CultCache stores publish: + +- `agency_profile.v1`, `agency_relation.v1`, `gestalt_lineage.v1`; +- `resolution_policy.v1`, `resolution_pin.v1`, `resolution_demand.v1`; +- `simulation_cell.v1`, `resolution_cover.v1`, + `resolution_plan_receipt.v1`, and `resolution_control_receipt.v1`; +- `cell_appraisal.v1`, `cell_action_proposal.v1`, and the internal atomic + `resolution_wave_commit.v1` bundle; +- `gestalt_fission_preview.v1` and approval-gated `FissionGestalt`. + +The authenticated campaign laboratory exposes budget, effective overage, pins, +fission preview/approval, and a separate operator provider-parallelism control. +The Eve operator projection carries the agency graph, active cover, cell modes, +loss components, debt focus, pins, plan receipts, cell appraisals, and control +receipts. Browser and Eve surfaces use a composite interface version so +resolution-only and provider-only changes refresh without impersonating a world +revision. + +## Verification + +Property and golden tests cover budgets 1/4/8/32, complete unique connected +coverage, deterministic ties, mandatory overage, contradictory pins, fairness, +arena isolation, fission identity preservation, stale epochs, atomic waves, and +the 1,000-subject target. Pressure goldens preserve geography under blockade, +ideology under schism, workplace/economic role under strike, species/body and +transport under epidemic, and information boundaries under espionage. + diff --git a/notes/documentation-inventory.md b/notes/documentation-inventory.md index 3747055..4a4d966 100644 --- a/notes/documentation-inventory.md +++ b/notes/documentation-inventory.md @@ -15,6 +15,11 @@ not slowly melt into one cursed binder. ## Core Architecture Contracts +- `docs/architecture/ghostlight-dungeon-mvp.md`: hosted dungeon authority and + runtime map. +- `docs/architecture/ghostlight-multiresolution-agency.md`: dynamic agency + graph, connected cohesive/arena covers, detail fairness, cell waves, fission, + controls, and atomicity. - `docs/architecture/canonical-agent-state-schema.md`: canonical state model. - `docs/architecture/agent-state-variable-glossary.md`: meanings for state axes, voice style, overlays, and emergent behaviors. diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index d73d7f3..b6e3bf0 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -38,7 +38,8 @@ generalized projection membrane; Epiphany consumes its pinned crate while retaining her own Mind and consequence authority. The Rust daemon now owns VoidBot-grounded compilation and approval, stable topology, campaign mailboxes, fiction-first d20 receipts, parallel Persona waves, automatic gestalt -individuation and folding, model-driven strategic ticks, exact-channel news, +individuation and folding, a multiresolution global agency graph, connected +cohesive/arena cell covers, model-driven strategic cell waves, exact-channel news, CultMesh/Eve publication, invite-isolated campaigns, and `.cc` export. Live acceptance has proved two invite sessions, Vault compilation, three concurrent NPC reactions, a 13.57-second four-actor wave, and material offscreen agency @@ -47,6 +48,12 @@ the latest exact deployment evidence; do not resume the superseded compiler foundation checklist below. Existing Ghostlight fixtures remain regression evidence. +The multiresolution authority map is +`docs/architecture/ghostlight-multiresolution-agency.md`. Canonical people and +populations never merge; only the derived simulation cover does. Budget/pin +changes use `resolution_epoch`, provider parallelism uses its own configuration +epoch, and neither advances fictional time. + ## Prior research pipeline focus The active path is a source-grounded branching-scene data loop: diff --git a/notes/ghostlight-current-system-map.md b/notes/ghostlight-current-system-map.md index d9983c3..106b6a6 100644 --- a/notes/ghostlight-current-system-map.md +++ b/notes/ghostlight-current-system-map.md @@ -27,10 +27,14 @@ Away-time agency follows a separate proposal/commit seam: ```text exact campaign revision - -> flash-model StrategicTickPlan proposal - -> WorldKernel validates IDs, non-player scope, topology, duration, and bounds + -> flash-model six-axis resolution demand + -> connected agency graph + budget/pins/leases/detail debt + -> cohesive or arena simulation-cell cover + -> one private Projector/Persona/Interpreter membrane per cell + -> exact constituent-attributed appraisals and proposals + -> WorldKernel validates cover, receipts, knowledge, scope, topology, and bounds -> AdvanceStrategicTick through the campaign mailbox - -> atomic campaign/event/news commit + -> one atomic campaign/event/news/cover/appraisal commit ``` The model owns no tick mutation. A provider failure or invalid proposal leaves @@ -53,6 +57,12 @@ gestalt baseline + existing member delta, or a first-relevance identity proposal The temporary actor slot is derived. It never owns identity, relationship, memory, equipment, injury, or obligation state. +The active cell budget and provider concurrency limit are separate controls. +Budget and pins increment `resolution_epoch` without advancing world revision or +fictional time. Provider concurrency increments only +`provider_configuration_epoch`; it batches the same cover and cannot repartition +the world. See `docs/architecture/ghostlight-multiresolution-agency.md`. + The browser command boundary is deliberately smaller than `WorldCommand`. Authenticated HTTP admits only player-owned Speak, unfilled Assess, Attempt, and Wait requests. Actor identity must match the campaign player. Compiler diff --git a/notes/ghostlight-dungeon.md b/notes/ghostlight-dungeon.md index bba8bd5..7283718 100644 --- a/notes/ghostlight-dungeon.md +++ b/notes/ghostlight-dungeon.md @@ -6,6 +6,12 @@ Build `GhostlightDungeon` inside `GameCult/Ghostlight`: a persistent, Vault-grou The runtime will be a Rust daemon on Starfire. It will own world compilation, typed CultCache state, d20 resolution, NPC Persona loops, offscreen simulation, narration, and Eve/CultUI publication. A thin TypeScript browser client will lower the Eve surface and submit typed commands. +Population-scale agency is implemented by the dynamic connected cover in +`docs/architecture/ghostlight-multiresolution-agency.md`. That authority map +supersedes any reading of the gestalt materialization notes below as a flat +strategic Persona list: materialization preserves named identity, while the +agency graph decides the current simulation resolution. + Ghostlight’s existing v0 schemas and training fixtures remain evidence and regression material; they do not become runtime authorities. ## Authority and invariants @@ -163,6 +169,34 @@ stake prose alone never impersonates world mutation. - Live play has inference priority; background work stops launching new calls while a player turn is active. - Offscreen events generate information-channel-aware news leads. On return, the player may receive newspapers, reports, messages, or rumors only when the character has access to them; the news layer cannot reveal omniscient state. +### Multiresolution gestalt and institution agency + +- Campaign creation compiles a global agency skeleton across every non-player + actor, institution, and active gestalt leaf. All six partition facets are + explicit; remote powers do not require eager local geography. +- `ActorState`, `InstitutionState`, gestalt baselines, member deltas, + relationships, possessions, and knowledge remain canonical. A + `simulation_cell.v1` is a derived connected cover and may be discarded. +- The player chooses 1–32 active Persona cells, default 8. Foreground subjects, + active leases, initiative holders, explicit targets, and individual-detail + pins may create a reported temporary overage. +- Adjacent cells merge by the weighted loss specified in + `ghostlight-multiresolution-agency.md`; cohesive cells require real common + authority, while opposed or cross-faction cells are arenas with no synthetic + actor or shared knowledge. +- Every active cell receives one private Projector → Persona → Interpreter + pipeline. Arena output is constituent-attributed. All cells, receipts, and + effects validate against one world revision and resolution epoch before one + atomic strategic commit. +- Persistent detail debt rotates direct attention through quiet subjects. All + clocks and deterministic obligations advance regardless of selected detail. +- Population fission is a separate approval-gated canonical operation. It + creates enumerated child leaves plus `other/unknown`, preserves the parent as + lineage, and reassigns durable member deltas without rewriting identity. +- Provider request parallelism is an operator control with its own epoch. It + batches the selected cell pipelines and cannot change the cover or fictional + state. + ### Web laboratory and hosting - Build the interface as a Ghostlight-owned `gamecult.eve.surface.v1` document and lower it with Eve’s pinned browser renderer. diff --git a/notes/ghostlight-implementation-plan.md b/notes/ghostlight-implementation-plan.md index dacd28d..70e2997 100644 --- a/notes/ghostlight-implementation-plan.md +++ b/notes/ghostlight-implementation-plan.md @@ -18,9 +18,16 @@ consequence authority. The hosted runtime owns compiler approval, exact VoidBot evidence, campaign mailboxes, fiction-first d20 resolution, parallel Persona appraisal, narration, reversible gestalt materialization, isolated sessions/campaigns, CultMesh/Eve -publication, and away-time scheduling. Strategic ticks now use a flash-model -typed proposal; the WorldKernel forbids player puppeting, invented IDs, -unreachable movement, and unbounded information or population-pressure edits. +publication, and away-time scheduling. Strategic ticks now project six-axis +pressure, select a connected budgeted cover over the global agency skeleton, +and run one private Ghostlight Persona membrane per cohesive or arena cell. The +WorldKernel admits the whole cell wave atomically and forbids player puppeting, +synthetic arena actors, borrowed secrets, invented IDs, unreachable movement, +and unbounded information or population-pressure edits. The laboratory exposes +a 1–32 player budget, persistent pins, approval-gated gestalt fission, graph and +cover receipts, and a separate operator provider-concurrency limit. The +specific authority map is +`docs/architecture/ghostlight-multiresolution-agency.md`. The implementation cut is closed. Final acceptance evidence covers hosted VoidBot compilation, invite isolation, automatic gestalt presence, three NPC reactions, a 13.57-second four-actor parallel wave, model-driven institutional, diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 969d7a3..ae76995 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -79,3 +79,4 @@ {"ts":"2026-08-16T21:56:08+00:00","type":"verification","status":"ok","branch":"codex/ghostlight-dungeon-mvp","note":"Final hosted acceptance against deployed commit 3eba32a4e8774956e63ed4727349b924a9d3f6f8 passed: unauthenticated and consumed-invite requests returned 401, the second session saw zero campaigns, live VoidBot/DeepSeek compilation produced stable topology plus an institution, three clocks, and a gestalt, three NPC proposals survived the reaction wave, and the Eve operator surface lowered successfully. Witness: F:\\GameCult\\GhostlightDungeon\\acceptance\\20260816-215443\\acceptance-result.json."} {"ts":"2026-08-16T21:57:56+00:00","type":"verification","status":"ok","branch":"codex/ghostlight-dungeon-mvp","note":"Exact final source completed a four-actor Projector-Persona-Interpreter wave with three reactions and nine model-stage receipts in 13.57 seconds, below the 20-second target. A live model-driven strategic tick completed in 3.04 seconds, changed an institution, gestalt pressure, remote actor location, and clock, preserved the absent player's location, and published only the player's exact station-radio channel. Witnesses: F:\\GameCult\\GhostlightDungeon\\acceptance\\four-actor-20260816-215743\\result.json and F:\\GameCult\\GhostlightDungeon\\acceptance\\strategic-20260816-215734\\result.json."} {"ts":"2026-08-16T21:58:30+00:00","type":"architecture","status":"accepted","branch":"codex/ghostlight-dungeon-mvp","note":"Live acceptance falsified split NPC initiative ownership: the old begin commit could survive a later malformed assessment. ResolveNpcAction now validates the selected proposal and same-revision assessment, obtains the server d20, applies the typed effect, consumes sibling proposals, and persists receipts in one WorldKernel commit. The assessor now receives exact present-actor IDs and gets one same-snapshot local-semantic correction; tests prove an invented actor leaves revision and pending proposals unchanged."} +{"ts":"2026-08-17T09:30:12+02:00","type":"implementation","status":"ok","branch":"codex/ghostlight-dungeon-mvp","note":"The flat strategic proposer is removed. Ghostlight now compiles a complete global agency skeleton, derives deterministic connected cohesive/arena covers under player budget and pins, runs one Ghostlight-owned Projector-Persona-Interpreter membrane per cell, validates exact constituent knowledge/authority/topology and all model receipts, and commits the whole strategic wave atomically. Approval-gated fission preserves parent lineage and member deltas; detail debt provides quiet-world fairness. Fifty-two dungeon tests and all workspace tests pass; the optimized 1,000-subject budget-8 partition completes in about 50 ms, below the 100 ms contract. Provider concurrency has a separate operator epoch and cannot repartition or advance fiction."} diff --git a/state/map.yaml b/state/map.yaml index c0915dd..24e9954 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -69,7 +69,10 @@ live_architecture: - Ghostlight owns generalized Projector to Persona to Interpreter machinery; consuming Personas retain their own canonical minds and commit authority. - Epiphany consumes the extracted Ghostlight projection crate at an exact Git revision while retaining her canonical Mind, effect admission, and consequence authority. - Gestalt Personas own shared population state; first-relevance individuation and later folding are revisioned WorldKernel commits, and durable member deltas preserve specific people between appearances. - - Model-driven strategic ticks can change remote actors, institutions, gestalts, clocks, and exact-channel news while the absent player remains outside their write authority. + - The multiresolution agency graph derives a connected cohesive/arena cell cover from canonical actors, institutions, and gestalt leaves under a player-selected 1–32 budget. + - Model-driven strategic cell waves can change remote actors, institutions, gestalts, clocks, and exact-channel news while the absent player remains outside their write authority; the entire wave validates and commits atomically. + - Budget and pins own `resolution_epoch`; provider concurrency owns a separate configuration epoch and cannot repartition or advance fiction. + - Approval-gated gestalt fission creates explicit child leaves plus `other/unknown`, preserves inactive parent lineage, and never erases member deltas. - Existing v0 training fixtures are regression evidence and have no runtime write authority. persistence_spine: - The hosted runtime uses Rust CultCache/redb `.cc` stores: one store per campaign plus service auth and CultMesh stores. @@ -254,6 +257,6 @@ data_flow: - If state grows faster than understanding, cut it back. current_status: - summary: GhostlightDungeon is the active MVP program. The approval-gated compiler persists exact VoidBot evidence, canon candidates, bounded topology, gestalt baselines, and durable member deltas. Fiction-first player and NPC attempts use deterministic initiative, model assessment, server-side d20, and prevalidated typed outcome deltas. Present NPCs appraise events in parallel; gestalt populations materialize durable individuals and fold them back without losing identity. Ghostlight owns the generalized Persona projection membrane and Epiphany consumes it at an exact Git revision. CampaignRegistry isolates per-campaign stores/mailboxes and sessions. CultMesh/Eve publication owns hosted state sight. Away-time ticks now use revision-bound flash-model strategic proposals validated by WorldKernel; invalid plans, player puppeting, invented IDs, and unreachable movement cannot mutate state. - next_action: Preserve the final deployed release and acceptance receipts, then treat additional rulesets, Vault adapters, multiplayer, and richer Persona projections as post-MVP work requiring a new authority map. - gestalt_population: Gestalt Personas own shared population baselines; persistent member deltas own named individuality; WorldKernel materialization commands compose and demote active actors without deleting member identity. + summary: GhostlightDungeon is the active MVP program. The approval-gated compiler persists exact VoidBot evidence, canon candidates, bounded topology, a global agency skeleton, gestalt baselines, and durable member deltas. Fiction-first player and NPC attempts use deterministic initiative, model assessment, server-side d20, and prevalidated typed outcome deltas. Present NPCs appraise events in parallel; gestalt populations materialize durable individuals and fold them back without losing identity. Ghostlight owns the generalized Persona projection membrane and Epiphany consumes it at an exact Git revision. CampaignRegistry isolates per-campaign stores/mailboxes and sessions. CultMesh/Eve publication owns hosted state sight. Away-time ticks now project demand, select a connected budgeted cohesive/arena cover, run one private Persona membrane per cell, validate exact constituent knowledge and authority, and commit the whole strategic wave atomically. Invalid covers, malformed cells, stale epochs, player puppeting, borrowed secrets, invented IDs, and unreachable movement cannot mutate state. + next_action: Deploy the exact multiresolution release to Starfire and capture live demand/cover/cell-wave acceptance, then treat additional rulesets, Vault adapters, multiplayer, and richer Persona projections as post-MVP work requiring a new authority map. + gestalt_population: Gestalt Personas own shared population baselines; persistent member deltas own named individuality; WorldKernel materialization and approval-gated fission preserve lineage and identity. Simulation cells are derived covers only. diff --git a/web/dist/assets/index-BINdyAeG.js b/web/dist/assets/index-BINdyAeG.js deleted file mode 100644 index b25ebc6..0000000 --- a/web/dist/assets/index-BINdyAeG.js +++ /dev/null @@ -1,153 +0,0 @@ -(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))i(o);new MutationObserver(o=>{for(const a of o)if(a.type==="childList")for(const s of a.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&i(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const a={};return o.integrity&&(a.integrity=o.integrity),o.referrerPolicy&&(a.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?a.credentials="include":o.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function i(o){if(o.ep)return;o.ep=!0;const a=n(o);fetch(o.href,a)}})();const j=new WeakMap,be=20;function at(e,t,n,i,o,a,s,l){const f=dt(e.canvas);if(!f)return!1;const c=f.gl;if(!ut(f,a,s))return j.set(e.canvas,null),!1;const r=ct(t,n,i,o,l);c.bindFramebuffer(c.FRAMEBUFFER,f.framebuffer),c.viewport(0,0,a,s),c.disable(c.DEPTH_TEST),c.disable(c.CULL_FACE),c.enable(c.BLEND),c.blendFunc(c.ONE,c.ONE),c.clearColor(0,0,0,1),c.clear(c.COLOR_BUFFER_BIT),r.gravity.length>0&&(c.useProgram(f.splatProgram),c.uniform4f(c.getUniformLocation(f.splatProgram,"u_viewport"),o.minX,o.minY,o.maxX,o.maxY),c.uniform1f(c.getUniformLocation(f.splatProgram,"u_time"),I(t.simulationTimeSeconds,0)),c.bindBuffer(c.ARRAY_BUFFER,f.splatBuffer),c.bufferData(c.ARRAY_BUFFER,r.gravity,c.DYNAMIC_DRAW),Me(c,f.splatProgram),c.drawArrays(c.TRIANGLES,0,r.gravity.length/be)),c.bindFramebuffer(c.FRAMEBUFFER,f.tintFramebuffer),c.clearColor(0,0,0,0),c.clear(c.COLOR_BUFFER_BIT),r.tint.length>0&&(c.useProgram(f.splatProgram),c.uniform4f(c.getUniformLocation(f.splatProgram,"u_viewport"),o.minX,o.minY,o.maxX,o.maxY),c.uniform1f(c.getUniformLocation(f.splatProgram,"u_time"),I(t.simulationTimeSeconds,0)),c.bindBuffer(c.ARRAY_BUFFER,f.splatBuffer),c.bufferData(c.ARRAY_BUFFER,r.tint,c.DYNAMIC_DRAW),Me(c,f.splatProgram),c.drawArrays(c.TRIANGLES,0,r.tint.length/be)),c.disable(c.BLEND),c.bindFramebuffer(c.FRAMEBUFFER,null),c.viewport(0,0,a,s),c.useProgram(f.shadeProgram),c.activeTexture(c.TEXTURE0),c.bindTexture(c.TEXTURE_2D,f.fieldTexture),c.uniform1i(c.getUniformLocation(f.shadeProgram,"u_field"),0),c.activeTexture(c.TEXTURE1),c.bindTexture(c.TEXTURE_2D,f.tintTexture),c.uniform1i(c.getUniformLocation(f.shadeProgram,"u_tint"),1),c.uniform2f(c.getUniformLocation(f.shadeProgram,"u_resolution"),a,s),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_time"),I(n.simulationTimeSeconds,I(t.simulationTimeSeconds,0))),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_lineInterval"),I(t.lineInterval,I(t.scalarFieldLineInterval,I(t.depthRange,228.79605)/20))),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_lineOffset"),I(t.lineOffset,I(t.startDepth,2.310401))),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_lineWidth"),I(t.lineWidth,.3)),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_lineFade"),I(t.lineFade,5)),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_angleWidth"),I(t.angleWidth,.05)),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_angleFade"),I(t.angleFade,1.15)),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_dangerSteepness"),I(t.dangerSteepness,1.5)),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_scale"),I(t.isolineScale,2.6924083)),Q(c,f.shadeProgram,"u_baseColor",Z(t.scalarFieldBaseColor,[.002,.006,.012])),Q(c,f.shadeProgram,"u_fieldGlowColor",Z(t.scalarFieldGlowColor,[.018,.05,.075])),Q(c,f.shadeProgram,"u_lineLowColor",Z(t.scalarFieldLowLineColor,[0,.34,.52])),Q(c,f.shadeProgram,"u_lineHighColor",Z(t.scalarFieldHighLineColor,[1.45,.3,.05])),Q(c,f.shadeProgram,"u_angleLowColor",Z(t.scalarFieldLowAngleColor,[.06,.16,.24])),Q(c,f.shadeProgram,"u_angleHighColor",Z(t.scalarFieldHighAngleColor,[1.1,.24,.04])),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_tintScale"),I(t.vectorFieldTintScale,.45)),c.bindBuffer(c.ARRAY_BUFFER,f.quadBuffer);const d=c.getAttribLocation(f.shadeProgram,"a_position");return c.enableVertexAttribArray(d),c.vertexAttribPointer(d,2,c.FLOAT,!1,0,0),c.drawArrays(c.TRIANGLES,0,6),e.drawImage(f.canvas,0,0,a,s),!0}function ct(e,t,n,i,o){const a=[],s=[];return st(a,e,t,n),lt(s,e,o),{gravity:new Float32Array(a),tint:new Float32Array(s)}}function st(e,t,n,i,o){const a=I(n.terrainRadius,I(t.terrainRadius,1200)),s=I(n.terrainDepth,I(t.terrainDepth,-8));s!==0&&le(e,0,0,Math.max(1,a*2),Math.max(1,a*2),-s,0,0,1,Math.max(1e-4,I(n.terrainDepthExponent,I(t.terrainDepthExponent,1.2))),0,1,0,0);for(const l of i)le(e,l.x,l.y,Math.max(1,l.radius),Math.max(1,l.radius),-l.depth,0,0,1,Math.max(1e-4,l.exponent),0,1,0,0),l.waveRadius>0&&l.waveDepth!==0&&le(e,l.x,l.y,l.waveRadius,l.waveRadius,-l.waveDepth,0,0,1,8,4,I(n.terrainWaveFrequency,I(t.terrainWaveFrequency,.6)),l.waveSpeed,0)}function lt(e,t,n){const i=ft(n?.splats),o=Array.isArray(n?.layers)?n.layers:[],a=new Set,s=pt(t.vectorFieldLayer,t.tintFieldLayer,"fog.tint");o.forEach((_,J)=>{const ie=mt(_?.layerKey,"");I(_?.channel,-1)===4&&ie===s&&a.add(J)});const l=Math.max(0,ht(i.count,0));if(l<=0||a.size===0)return;const f=L(i.centerX),c=L(i.centerY),r=L(i.halfExtentX),d=L(i.halfExtentY),u=L(i.rotationCos),h=L(i.rotationSin),y=L(i.channel),b=L(i.falloff),v=L(i.valueR),C=L(i.valueG),A=L(i.valueB),N=L(i.valueA),Y=L(i.sourceKind),z=L(i.frequencyX),H=L(i.animationSpeed),V=L(i.sourceFlags),K=L(i.layerIndex);for(let _=0;_Number(i));if(n.length>=3&&n.slice(0,3).every(Number.isFinite))return[n[0],n[1],n[2]]}if(typeof e=="string"){const n=e.split(/[,\s]+/).map(i=>Number(i)).filter(Number.isFinite);if(n.length>=3)return[n[0],n[1],n[2]]}return t}function Q(e,t,n,i){e.uniform3f(e.getUniformLocation(t,n),i[0],i[1],i[2])}function L(e){return Array.isArray(e)?e.map(t=>I(t,0)):[]}function ft(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function mt(e,t){return e==null?t:String(e)}function pt(...e){for(const t of e){if(typeof t=="string"&&t.trim())return t;if(typeof t=="number"&&Number.isFinite(t))return String(t)}return""}function ht(e,t){const n=Number(e);return Number.isFinite(n)?Math.max(0,Math.floor(n)):t}const gt=`#version 300 es -in vec2 a_corner; -in vec2 a_center; -in vec2 a_half; -in vec2 a_rot; -in vec4 a_meta; -in vec4 a_source; -in vec4 a_value; -uniform vec4 u_viewport; -out vec2 v_local; -out vec4 v_meta; -out vec4 v_source; -out vec4 v_value; -void main() { - vec2 scaled = a_corner * a_half; - vec2 world = a_center + vec2( - scaled.x * a_rot.x - scaled.y * a_rot.y, - scaled.x * a_rot.y + scaled.y * a_rot.x - ); - vec2 clip = vec2( - ((world.x - u_viewport.x) / max(0.0001, u_viewport.z - u_viewport.x)) * 2.0 - 1.0, - ((world.y - u_viewport.y) / max(0.0001, u_viewport.w - u_viewport.y)) * 2.0 - 1.0 - ); - gl_Position = vec4(clip, 0.0, 1.0); - v_local = a_corner; - v_meta = a_meta; - v_source = a_source; - v_value = a_value; -}`,yt=`#version 300 es -precision highp float; -in vec2 v_local; -in vec4 v_meta; -in vec4 v_source; -in vec4 v_value; -uniform float u_time; -out vec4 outColor; -float hash21(vec2 p) { - p = fract(p * vec2(123.34, 456.21)); - p += dot(p, p + 45.32); - return fract(p.x * p.y); -} -float valueNoise(vec2 p) { - vec2 i = floor(p); - vec2 f = fract(p); - float a = hash21(i); - float b = hash21(i + vec2(1.0, 0.0)); - float c = hash21(i + vec2(0.0, 1.0)); - float d = hash21(i + vec2(1.0, 1.0)); - vec2 u = f * f * (3.0 - 2.0 * f); - return mix(mix(a, b, u.x), mix(c, d, u.x), u.y) * 2.0 - 1.0; -} -float powerPulse(float x, float power) { - x = clamp(abs(x), 0.0, 1.0); - return pow((x + 1.0) * (1.0 - x), max(0.0001, power)); -} -void main() { - float d = length(v_local); - if (d > 1.0) discard; - float alpha = powerPulse(d, v_meta.x); - if (alpha <= 0.0001) discard; - float source = 1.0; - if (v_source.x > 0.5 && v_source.x < 2.5) { - float timeOffset = v_source.x > 1.5 ? u_time * v_source.z : 0.0; - source = valueNoise(v_local * v_source.y + timeOffset); - if (v_source.w != 0.0) source = abs(source); - } else if (v_source.x > 3.5) { - source = cos(pow(d * 2.0, 1.25) * v_source.y + u_time * v_source.z); - } - outColor = v_value * alpha * source; -}`,bt=`#version 300 es -in vec2 a_position; -out vec2 v_uv; -void main() { - v_uv = a_position * 0.5 + 0.5; - gl_Position = vec4(a_position, 0.0, 1.0); -}`,vt=`#version 300 es -precision highp float; -uniform sampler2D u_field; -uniform sampler2D u_tint; -uniform vec2 u_resolution; -uniform float u_time; -uniform float u_lineInterval; -uniform float u_lineOffset; -uniform float u_lineWidth; -uniform float u_lineFade; -uniform float u_angleWidth; -uniform float u_angleFade; -uniform float u_dangerSteepness; -uniform float u_scale; -uniform vec3 u_baseColor; -uniform vec3 u_fieldGlowColor; -uniform vec3 u_lineLowColor; -uniform vec3 u_lineHighColor; -uniform vec3 u_angleLowColor; -uniform vec3 u_angleHighColor; -uniform float u_tintScale; -in vec2 v_uv; -out vec4 outColor; -vec2 calcGrad(vec2 uv, float me) { - vec2 texel = 1.0 / max(vec2(1.0), u_resolution); - float n = -texture(u_field, vec2(uv.x, uv.y + texel.y)).r; - float e = -texture(u_field, vec2(uv.x + texel.x, uv.y)).r; - return vec2(e - me, n - me); -} -void main() { - float height = -texture(u_field, v_uv).r; - vec4 tint = texture(u_tint, v_uv); - vec2 plan = calcGrad(v_uv, height); - float slope = max(length(plan), 0.00001); - vec3 color = u_baseColor; - float fieldGlow = smoothstep(0.0, u_lineInterval * 7.0, abs(height)); - color += u_fieldGlowColor * fieldGlow; - color += tint.rgb * clamp(tint.a, 0.0, 1.0) * u_tintScale; - - float dangerBlend = smoothstep(0.0, u_dangerSteepness, pow(slope / max(0.0001, u_scale), 2.0)); - vec3 baseLine = mix(u_lineLowColor, u_lineHighColor, dangerBlend); - vec3 angleLine = mix(u_angleLowColor, u_angleHighColor, dangerBlend) * clamp(slope / max(0.0001, u_scale), 0.0, 1.0); - - vec3 lines = vec3(0.0); - float interval = max(0.0001, abs(u_lineInterval)); - float nearestLine = abs(fract((height + u_lineOffset) / interval) - 0.5) * interval; - float lineDistance = nearestLine / slope; - float line = 1.0 - smoothstep(u_lineWidth, u_lineWidth * u_lineFade, lineDistance); - lines += line * baseLine; - - float angle = atan(plan.y, plan.x) / 3.1415926536 + 1.0; - float nearestAngle = abs(fract(angle * 6.0) - 0.5) / 6.0; - float angleMask = smoothstep(interval * 0.25, interval * 1.5, abs(height)); - float angleLineAmount = 1.0 - smoothstep(u_angleWidth, u_angleWidth * u_angleFade, nearestAngle); - lines += angleLineAmount * angleMask * angleLine; - - color += clamp(lines, 0.0, 1.7); - outColor = vec4(color, 1.0); -}`,qe=new Set(["gamecult.fields.splats.v1","gamecult.fields.gravity.v1","gamecult.fields.objects.v1"]),xt={pluginId:"fields.surface",capabilities:["field.surface2d","gravity.surface","field.scalar","field.vector","field.objects"],componentKinds:["field.surface2d","gravity.surface"],schemas:[...qe],normalizeDocument:ve,renderComponent:wt};function wt(e,t,n,i,o,a){const s=document.createElement("canvas");s.className="cultui-gravity-surface",e.id&&(s.id=e.id),s.setAttribute("role","img"),s.setAttribute("aria-label",jt(t.label,"gravity surface")),s.style.display="block",s.style.width="100%",s.style.height="100%",s.style.pointerEvents="none",a.applyGeneratedLayout(s,n,i);let l=!1;const f={},c=()=>At(s,t,f,a.resolveAssetUrl),r=()=>{!s.isConnected||l||(l=!0,requestAnimationFrame(()=>{l=!1,s.isConnected&&c()}))};s.addEventListener("cultui:asset-loaded",r);let d=0,u;const h=()=>{d&&window.clearInterval(d),u?.disconnect(),s.removeEventListener("cultui:asset-loaded",r)},y=()=>{if(!s.isConnected){h();return}St(e,t,o,a.providerId,f).then(v=>{v&&s.isConnected&&r()}).catch(v=>{f.lastError=v instanceof Error?v.message:String(v)})};typeof ResizeObserver<"u"&&(u=new ResizeObserver(r),u.observe(s)),r();const b=Math.max(33,Math.min(1e3,Xt(t.stateRefreshMs,100)));return d=window.setInterval(y,b),queueMicrotask(y),window.setTimeout(r,300),window.setTimeout(r,1e3),s}async function St(e,t,n,i,o){if(o.loading)return!1;const a=[ge(e,t,"renderSplats","renderSplatsDocumentId","renderSplatsSchemaId"),ge(e,t,"gravity","gravityDocumentId","gravitySchemaId"),ge(e,t,"objects","objectsDocumentId","objectsSchemaId")].filter(s=>!!s?.documentId);if(a.length===0)return!1;o.loading=!0;try{let s=!1;for(const l of a){const f=await n.documentResolver?.(l,e);let c=me(ve(f?.schemaId||l.schemaId,f?.document));if(Object.keys(c).length===0&&(c=me(ve(l.schemaId,await Et(l,i||n.provider?.providerId)))),Object.keys(c).length===0)continue;const r=l.slotId==="renderSplats"?"renderSplats":l.slotId==="gravity"?"gravity":"objects",d=we(o[r]?.frameId,-1),u=we(c.frameId,d);o[r]=c,s||=u!==d}return o.lastLoadedAt=Date.now(),s}finally{o.loading=!1}}async function Et(e,t){if(typeof fetch!="function"||typeof window>"u"||!t)return;const n=new URLSearchParams({documentId:e.documentId});e.schemaId&&n.set("schemaId",e.schemaId),e.slotId&&n.set("slotId",e.slotId);const i=await fetch(`/eir/document/${encodeURIComponent(t)}?${n.toString()}`,{cache:"no-store",headers:{Accept:"application/json"}});if(i.ok)return me(await i.json()).document}function ge(e,t,n,i,o){const a=(e.embeddedDocuments||[]).find(l=>String(l?.slotId||"")===n),s=T(t[i],a?.documentId);if(s)return{documentId:s,schemaId:T(t[o],a?.schemaId),presentationKind:T(a?.presentationKind)||"data",slotId:n}}function ve(e,t){const n=Array.isArray(t)?t:void 0,i=n?n[0]:t?.schema,o=String(e||i||"");return!n||!qe.has(o)?t:o==="gamecult.fields.splats.v1"?Bt(n):o==="gamecult.fields.gravity.v1"?Dt(n):$t(n)}function At(e,t,n,i){const o=e.getBoundingClientRect(),a=Math.max(1,Math.floor(o.width||e.clientWidth||1)),s=Math.max(1,Math.floor(o.height||e.clientHeight||1)),l=Math.max(1,Math.min(2,window.devicePixelRatio||1)),f=Math.max(1,Math.floor(a*l)),c=Math.max(1,Math.floor(s*l));(e.width!==f||e.height!==c)&&(e.width=f,e.height=c);const r=e.getContext("2d");if(!r)return;r.setTransform(l,0,0,l,0,0),r.clearRect(0,0,a,s);const d=Nt(Mt(t),a,s),u=Ve(n?.gravity),h=Lt(n?.gravity)||kt(T(t.bodies,"")),y=Pt(n?.objects)||Ft(T(t.objects,""));at(r,t,u,h,d,a,s,n?.renderSplats)||It(r,t,a,s,"field.surface2d requires WebGL2 float render targets"),_t(r,h,t,d,a,s,i),Tt(r,y,t,d,a,s,i)}function It(e,t,n,i,o){e.save(),e.fillStyle=T(t.failureBackground,"rgba(0, 0, 0, 0.72)"),e.fillRect(0,0,n,i),e.font=T(t.failureFont,"700 13px Cascadia Mono, Consolas, monospace"),e.fillStyle=T(t.failureColor,"rgba(255, 184, 79, 0.95)"),e.fillText(o,16,28),e.restore()}function _t(e,t,n,i,o,a,s){for(const l of t){const f=He(i,l.x,l.y,o,a),c=Math.max(18,Math.min(190,l.radius/Math.max(1,i.maxX-i.minX)*o*.32)),r=s(l.icon),d=l.kind.toLowerCase().includes("sun")?Math.max(E(n.sunIconMinPx,34),c*E(n.sunIconScale,.72)):Math.max(E(n.bodyIconMinPx,24),c*E(n.bodyIconScale,.48)),u=l.iconSize>0?l.iconSize:d;r&&Ct(e,r,f.x,f.y,u,.92),l.key&&Ye(e,n,l.key.replace(/^local\./,""),f.x+c*.44,f.y-c*.48,T(n.bodyLabelColor,"rgba(226, 244, 255, 0.82)"))}}const fe=new Map;function Ct(e,t,n,i,o,a){let s=fe.get(t);s||(s=new Image,s.decoding="async",s.onload=()=>requestAnimationFrame(()=>{e.canvas.dispatchEvent(new CustomEvent("cultui:asset-loaded"))}),s.src=t,fe.set(t,s)),!(!s.complete||s.naturalWidth===0)&&(e.save(),e.globalAlpha=a,e.drawImage(s,n-o/2,i-o/2,o,o),e.restore())}function Tt(e,t,n,i,o,a,s){for(const l of t){const f=He(i,l.x,l.y,o,a);if(f.x<-40||f.x>o+40||f.y<-40||f.y>a+40)continue;const c=l.kind.toLowerCase().includes("station")?E(n.stationIconSizePx,34):l.controlled?E(n.shipIconSizePx,22):E(n.remoteShipIconSizePx,18),r=Rt(n,l.faction,l.controlled,l.visibility),d=s(l.icon);e.save(),e.globalAlpha=Math.max(.25,Math.min(1,l.visibility)),e.translate(f.x,f.y);const u=Math.atan2(l.directionY,l.directionX)+Math.PI/2;if(l.kind.toLowerCase().includes("ship")&&e.rotate(u),d){const h=fe.get(d);if(h)h.complete&&h.naturalWidth>0&&e.drawImage(h,-c/2,-c/2,c,c);else{const y=new Image;y.decoding="async",y.onload=()=>e.canvas.dispatchEvent(new CustomEvent("cultui:asset-loaded")),y.src=d,fe.set(d,y)}}e.restore(),Ye(e,n,l.label,f.x+c*.55,f.y-c*.45,r)}}function Ye(e,t,n,i,o,a){n&&(e.save(),e.font=T(t.objectLabelFont,"700 12px Ubuntu, system-ui, sans-serif"),e.textBaseline="middle",e.lineWidth=E(t.objectLabelStrokeWidth,3),e.strokeStyle=T(t.objectLabelStroke,"rgba(0, 0, 0, 0.72)"),e.fillStyle=a,e.strokeText(n,i,o),e.fillText(n,i,o),e.restore())}function Rt(e,t,n,i){const o=Math.max(.25,Math.min(1,i));if(n)return re(T(e.objectControlledColor,"rgba(122, 240, 255, {alpha})"),o);const a=t.toLowerCase();return a.includes("raider")?re(T(e.objectRaiderColor,"rgba(255, 143, 74, {alpha})"),o):a.includes("neutral")?re(T(e.objectNeutralColor,"rgba(232, 232, 224, {alpha})"),o):re(T(e.objectDefaultColor,"rgba(214, 244, 255, {alpha})"),o)}function re(e,t){return e.replaceAll("{alpha}",String(t))}function kt(e){return e.split(";").map(t=>t.trim()).filter(Boolean).map(t=>{const n=t.split("|");return{key:n[0]??"",kind:n[1]??"",x:Number(n[2])||0,y:Number(n[3])||0,radius:Math.max(1,Number(n[4])||1),depth:Number(n[5])||0,exponent:Number(n[6])||1,waveRadius:Number(n[7])||0,waveDepth:Number(n[8])||0,waveSpeed:Number(n[9])||0,icon:n[10]??"",iconSize:Number(n[12])||0,tint:n[11]??""}})}function Ft(e){return e.split(";").map(t=>t.trim()).filter(Boolean).map(t=>{const n=t.split("|");return{key:n[0]??"",kind:n[1]??"",label:n[2]??"",x:Number(n[3])||0,y:Number(n[4])||0,directionX:Number(n[5])||0,directionY:Number(n[6])||1,faction:n[7]??"",controlled:n[8]==="1"||n[8]==="true",visibility:Number(n[9])||1,icon:n[10]??""}})}function Lt(e){const t=Array.isArray(e?.gravityInfluences)?e.gravityInfluences:[],n=Array.isArray(e?.bodies)?e.bodies:[];if(t.length===0&&n.length===0)return;const i=new Map;for(const o of n){const a=T(o.bodyKey,o.name,"");a&&i.set(a,o)}return(t.length>0?t:n).map(o=>{const a=T(o.bodyKey,o.name,"body"),s=i.get(a),l=T(o.kind,"Body");return{key:a,kind:l,x:E(o.x,0),y:E(o.y,0),radius:Math.max(1,E(o.radius,80)),depth:E(o.gravityDepth,0),exponent:E(o.gravityDepthExponent,1),waveRadius:E(o.waveRadius,0),waveDepth:E(o.waveDepth,0),waveSpeed:E(o.waveSpeed,0),icon:xe(o.iconAsset)||xe(s?.iconAsset),iconSize:E(s?.iconSize,E(o.iconSize,0)),tint:""}})}function Pt(e){const t=Array.isArray(e?.objects)?e.objects:[];if(t.length!==0)return t.map(n=>{const i=T(n.kind,"object");return{key:T(n.entityKey,String(n.entityIndex??""),"object"),kind:i,label:T(n.displayName,n.entityKey,"object"),x:E(n.x,0),y:E(n.y,0),directionX:E(n.directionX,1),directionY:E(n.directionY,0),faction:T(n.factionKey,""),controlled:qt(n.controlled),visibility:E(n.visibility,1),icon:xe(n.iconAsset)}})}function xe(e){const t=Ve(e);return T(t.uri,"")}function Mt(e){const t=Math.max(1,E(e.viewRadius,Math.max(1200,E(e.terrainRadius,1200))));return{minX:E(e.minX,-t),minY:E(e.minY,-t),maxX:E(e.maxX,t),maxY:E(e.maxY,t)}}function Nt(e,t,n){const i=Math.max(1e-4,e.maxX-e.minX),o=Math.max(1e-4,e.maxY-e.minY),a=Math.max(1e-4,t/Math.max(1,n)),s=i/o,l=(e.minX+e.maxX)*.5,f=(e.minY+e.maxY)*.5;if(a>s){const r=o*a;return{minX:l-r*.5,maxX:l+r*.5,minY:e.minY,maxY:e.maxY}}const c=i/a;return{minX:e.minX,maxX:e.maxX,minY:f-c*.5,maxY:f+c*.5}}function He(e,t,n,i,o){return{x:(t-e.minX)/Math.max(1,e.maxX-e.minX)*i,y:(n-e.minY)/Math.max(1,e.maxY-e.minY)*o}}function Bt(e){const t=M(e[9]);return{schema:e[0],frameId:e[1],publishedAtUtc:e[2],simulationTimeSeconds:e[3],runId:e[4],zoneIndex:e[5],zoneName:e[6],viewport:Ae(e[7]),layers:M(e[8]).map(Ut),splats:{count:t[0]??0,centerX:t[1]||[],centerY:t[2]||[],halfExtentX:t[3]||[],halfExtentY:t[4]||[],rotationCos:t[5]||[],rotationSin:t[6]||[],channel:t[7]||[],falloff:t[8]||[],valueR:t[9]||[],valueG:t[10]||[],valueB:t[11]||[],valueA:t[12]||[],sourceKey:t[13]||[],layerIndex:t[14]||[],sourceKind:t[15]||[],frequencyX:t[16]||[],frequencyY:t[17]||[],phaseX:t[18]||[],phaseY:t[19]||[],animationSpeed:t[20]||[],sourceFlags:t[21]||[]}}}function Dt(e){return{schema:e[0],frameId:e[1],publishedAtUtc:e[2],simulationTimeSeconds:e[3],runId:e[4],zoneIndex:e[5],zoneName:e[6],viewport:Ae(e[7]),gravityInfluences:M(e[8]).map(Wt),bodies:M(e[9]).map(Ot),terrainRadius:e[10],terrainDepth:e[11],terrainDepthExponent:e[12],terrainWaveFrequency:e[13]}}function $t(e){return{schema:e[0],frameId:e[1],publishedAtUtc:e[2],simulationTimeSeconds:e[3],runId:e[4],zoneIndex:e[5],zoneName:e[6],currentEntityKey:e[7],viewport:Ae(e[8]),controlledEntityIndices:M(e[9]),objects:M(e[10]).map(zt)}}function Ae(e){const t=M(e);return t.length?{minX:t[0],minY:t[1],maxX:t[2],maxY:t[3]}:e}function Ut(e){const t=M(e);return t.length?{layerKey:t[0],displayName:t[1],channel:t[2],blendMode:t[3],graphicsFormat:t[4],clearBeforeDraw:t[5],clearR:t[6],clearG:t[7],clearB:t[8],clearA:t[9]}:e}function Wt(e){const t=M(e);return t.length?{bodyKey:t[0],orbitKey:t[1],kind:t[2],x:t[3],y:t[4],radius:t[5],gravityDepth:t[6],gravityDepthExponent:t[7],waveRadius:t[8],waveDepth:t[9],waveSpeed:t[10]}:e}function Ot(e){const t=M(e);return t.length?{bodyKey:t[0],orbitKey:t[1],name:t[2],kind:t[3],x:t[4],y:t[5],radius:t[6],isAsteroidBelt:t[7],body:t[8],iconAsset:Ie(t[9])}:e}function zt(e){const t=M(e);return t.length?{entityIndex:t[0],entityKey:t[1],displayName:t[2],kind:t[3],factionKey:t[4],x:t[5],y:t[6],z:t[7],directionX:t[8],directionY:t[9],velocityX:t[10],velocityY:t[11],controlled:t[12],targetEntityIndex:t[13],isActive:t[14],visibility:t[15],status:Kt(t[16]),inventory:M(t[17]).map(Gt),iconAsset:Ie(t[18])}:e}function Kt(e){const t=M(e);return t.length?{hull:t[0],shield:t[1],heat:t[2]}:e||{}}function Gt(e){const t=M(e);return t.length?{source:t[0],itemKey:t[1],quantity:t[2],quality:t[3],durability:t[4],enabled:t[5],sourceIndex:t[6],x:t[7],y:t[8],iconAsset:Ie(t[9])}:e}function Ie(e){const t=M(e);return t.length?{assetKey:t[0],kind:t[1],uri:t[2],transport:t[3],contentHash:t[4],mimeType:t[5],metadata:t[6]||{}}:e||{}}function M(e){return Array.isArray(e)?e:[]}function me(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function T(...e){for(const t of e)if(typeof t=="string"&&t.trim())return t.trim();return""}function jt(e,t){return typeof e=="string"&&e?e:t}function Xt(e,t){const n=Number(e);return Number.isFinite(n)&&n>0?Math.floor(n):t}function we(e,t){const n=Number(e);return Number.isFinite(n)?n:t}const Ve=me,E=we;function qt(e){return typeof e=="boolean"?e:typeof e=="number"?e!==0:typeof e=="string"&&["1","true","yes","on"].includes(e.trim().toLowerCase())}const Yt=[xt],Ht={"--bg":"#020909","--bg-top":"#020909","--bg-mid":"#020909","--bg-bottom":"#020909","--shell-top":"#010707","--shell-bottom":"#010707","--panel":"#071918","--panel-2":"#0a2423","--line":"rgba(103, 240, 228, 0.28)","--line-deep":"rgba(103, 240, 228, 0.18)","--text":"#e7f1f1","--text-bright":"#e7f1f1","--quiet":"#8ba5a3","--accent":"#ffb84f","--accent-strong":"#ffb84f","--corner-accent":"#ffb84f","--cyan":"#8efcff","--shadow":"rgba(0, 0, 0, 0.35)","--pixel-grid":"rgba(142, 252, 255, 0.04)","--border-width":"1px","--border-bottom-width":"1px","--corner-accent-size":"0","--font-body":'"M PLUS 1", "Ubuntu Sans", Ubuntu, "Noto Sans JP", system-ui, sans-serif',"--font-title":'"Montserrat", "Zen Kaku Gothic New", "M PLUS 1", "Ubuntu Sans", system-ui, sans-serif',"--font-mono":'"Ubuntu Sans Mono", "M PLUS 1 Code", "Cascadia Mono", Consolas, monospace'};let oe,Je=_e(void 0),te,W={};const De=new WeakMap;function Ze(e,t,n={}){if(De.get(t)?.dispose(),te=e,W=n,Je=_e(e.surface?.styles),globalThis.__eveCurrentMesh=e.mesh,pn(e.surface?.styles,n.body??document.body),n.body&&(n.body.dataset.provider=e.providerId||n.provider?.providerId||""),n.statusElement&&(n.statusElement.textContent=`${e.title||e.surface?.title||"surface"}${n.source?` (${n.source})`:""}`),e.surface?.root){if(t.replaceChildren(F(e.surface.root,n)),n.stateBindingResolver){const i=new Jt(e,t,n);De.set(t,i),i.start()}}else t.replaceChildren(q("No surface root"));return t}function Vt(e,t,n){const i=t.targetProp.split(".").filter(Boolean);if(i.length===0)throw new Error("Eve state binding targetProp must not be empty.");e.props||={};let o=e.props;for(const a of i.slice(0,-1)){const s=o[a];(!s||typeof s!="object"||Array.isArray(s))&&(o[a]={}),o=o[a]}o[i[i.length-1]]=n}class Jt{surface;host;options;disposed=!1;unsubscribers=[];constructor(t,n,i){this.surface=t,this.host=n,this.options=i}async start(){const t=this.options.stateBindingResolver,n=this.surface.surface?.root;if(!(!t||!n))for(const i of Qe(n))for(const o of i.stateBindings||[]){if(this.disposed)return;const a=await t(o,i);if(!a||this.disposed)continue;const s=l=>{this.disposed||(Vt(i,o,l),this.renderCanonicalProjection())};if(s(await a.latest()),this.disposed)return;this.unsubscribers.push(a.watch(s))}}dispose(){this.disposed=!0;for(const t of this.unsubscribers.splice(0))t()}renderCanonicalProjection(){const t=this.surface.surface?.root;t&&this.host.replaceChildren(F(t,this.options))}}function*Qe(e){yield e;for(const t of e.children||[])yield*Qe(t)}function F(e,t=W){const n=e.kind||"panel",i=x(e.props),o=x(e.layout),a=x(e.style),s=e.children||[],l=e.embeddedDocuments||[];if(n==="surface"||n==="cockpit"||n==="dashboard"){const r=m("section","cultui-surface-root eve-surface");w(r,e),typeof o.direction=="string"?r.dataset.direction=o.direction:typeof i.layout=="object"&&i.layout&&typeof i.layout.direction=="string"&&(r.dataset.direction=String(i.layout.direction)),n!=="surface"&&(r.dataset.surfaceKind=n),S(r,o,a);for(const d of s)r.append(F(d,t));return r}if(n==="column"||n==="row"||n==="form"||n==="rail"){const r=m("div",`cultui-partition eve-${n}`);w(r,e),r.dataset.direction=n==="row"||n==="rail"?"horizontal":"vertical",n==="rail"&&(r.dataset.overflow="x"),ce(r,{...o,...i}),S(r,o,a);for(const d of s)r.append(F(d,t));return r}if(n==="grid"){const r=m("section","cultui-grid"),d=D(i.columns,0);d>0?r.style.gridTemplateColumns=`repeat(${d}, minmax(0, 1fr))`:typeof i.columns=="string"&&(r.style.gridTemplateColumns=i.columns);const u=D(i.rows,0);u>0&&(r.style.gridTemplateRows=`repeat(${u}, minmax(0, auto))`),S(r,o,a);for(const h of s)r.append(F(h,t));return r}if(n==="partition"){const r=m("section",`cultui-partition split-${g(i.split,"none")}`);w(r,e),ce(r,i),S(r,o,a),r.style.minWidth="0",g(i.split,"none")==="x"&&!p(i.flexWrap,o.flexWrap,"")&&(r.style.flexWrap="wrap"),typeof i.role=="string"&&(r.dataset.role=i.role);for(const d of s)r.append(F(d,t));return r}if(n==="input.binding-map")return dn(e,i,t);if(n==="inventory.drag_session")return on(e,i,o,a);if(n==="inventory.grid")return an(e,i,o,a,t);if(n==="inventory.item")return cn(e,i,o,a);const f=(t.pluginAdapters||Yt).find(r=>r.componentKinds.includes(n));if(f?.renderComponent)return f.renderComponent(e,i,o,a,t,{applyGeneratedLayout:S,providerId:te?.providerId||t.provider?.providerId,resolveAssetUrl:ee});if(n==="world.scene3d"||n==="world.scene2d")return Qt(e,i,o,a,t);if(n==="image.background"){const r=m("div","cultui-background"),d=ee(p(i.src,i.assetUri,i.assetRef,""));return d&&(r.style.backgroundImage=`url("${d}")`),r.setAttribute("aria-label",g(i.label,"background")),r}if(n==="image.sprite"){const r=m("figure",`cultui-sprite ${g(i.slot,"center")}`);w(r,e);const d=ee(p(i.src,i.assetUri,i.assetRef,""));if(d){const u=m("img");u.src=d,u.alt=g(i.alt,g(i.actor,g(i.label,""))),r.append(u)}return r}if(n==="avatar"){const r=m("figure","cultui-avatar-card");w(r,e);const d=ee(p(i.src,i.assetUri,i.assetRef,""));if(d){const b=m("img");b.src=d,b.alt=g(i.alt,g(i.text,g(i.label,""))),r.append(b)}else r.append(m("div","cultui-avatar-fallback",_n(p(i.text,i.label,i.actor,"?"))));const u=p(i.text,i.label,i.actor,"");u&&r.append(m("figcaption","cultui-avatar-name",u));const h=p(i.status,"");h&&r.append(m("div","cultui-avatar-status",h));const y=p(i.detail,"");return y&&r.append(m("div","cultui-avatar-detail",y)),r}if(n==="pane"||n==="panel"){const r=m("section","pane cultui-pane");w(r,e);const d=g(i.span,"");d&&(r.dataset.span=d);const u=g(i.density,"");u&&(r.dataset.density=u);const h=g(i.title,e.text||"");h&&r.append(m("h2","",h));for(const y of s)r.append(F(y,t));return r}if(n==="list"||n.endsWith(".roster")){const r=m("section","cultui-list");w(r,e),r.dataset.componentKind=n;const d=g(i.title,"");d&&r.append(m("h3","cultui-list-title",d));for(const[u,h]of An(i.items).entries())r.append(F({id:`${e.id||"list"}-item-${u}`,kind:"list.item",props:{...h}},t));for(const u of s)r.append(F(u,t));return r}if(n==="list.item"||n.endsWith(".item")){const r=et(e),d=m("article","cultui-list-item");w(d,e),d.dataset.componentKind=n;const u=m("div","cultui-list-item-heading");if(u.append(m("strong","cultui-list-item-label",r.label)),r.status&&u.append(m("span","cultui-list-item-status",r.status)),d.append(u),r.detail&&d.append(m("div","cultui-list-item-detail",r.detail)),r.badges.length){const h=m("div","cultui-list-item-badges");for(const y of r.badges)h.append(m("span","cultui-list-item-badge",y));d.append(h)}for(const h of s)d.append(F(h,t));return d}if(n==="bar"){const r=m("div","cultui-meter");w(r,e);const d=g(i.label,""),u=g(i.value,"");if(d||u){const b=m("div","cultui-meter-head");b.append(m("span","",d)),b.append(m("strong","",u)),r.append(b)}const h=m("div","cultui-meter-track"),y=m("span","cultui-meter-fill");return y.style.width=`${Ke(i.percent)}%`,h.append(y),r.append(h),r}if(n==="card"){const r=Oe(i,e),d=r?m("button","card cultui-card cultui-card-button"):m("article","card cultui-card");w(d,e),S(d,o,a),d instanceof HTMLButtonElement&&(d.type="button");const u=g(i.title,e.text||"");u&&d.append(m("div","card-title",u));for(const h of s)d.append(F(h,t));return r&&ze(d,e,r,i,t),d}if(n==="control.button"){const r=m("button","cultui-button eve-control-button",g(i.label,"Action"));return w(r,e),r.type="button",S(r,o,a),ze(r,e,Oe(i,e),i,t),r}if(n==="control.popup"){const r=m("button","cultui-button eve-control-popup",g(i.label,"Open"));return w(r,e),r.type="button",S(r,o,a),r.addEventListener("click",d=>{un(e,t,r,d.clientX,d.clientY)}),r}if(n==="text.dialogue"||n==="text"||n==="text.title"||n==="text.subtitle"||n==="label"){const r=m("div",vn(n,i),g(i.value,g(i.text,e.text||"")));return w(r,e),ce(r,i),S(r,o,a),r}if(n==="metric"){const r=m("dl","metric cultui-reactive-metric eve-metric");return w(r,e),S(r,o,a),r.append(m("dt","",g(i.label,"Metric"))),r.append(m("dd","metric-value",g(i.value,""))),r}if(n==="progress"){const r=m("div","cultui-meter eve-progress");w(r,e),S(r,o,a);const d=g(i.label,""),u=g(i.value,""),h=Number(i.min??0),y=Number(i.max??1),b=Number(i.value??0),v=Number.isFinite(b)&&Number.isFinite(h)&&Number.isFinite(y)&&y!==h?(b-h)/(y-h)*100:Ke(i.percent);if(d||u){const N=m("div","cultui-meter-head");N.append(m("span","",d)),N.append(m("strong","",u)),r.append(N)}const C=m("div","cultui-meter-track"),A=m("span","cultui-meter-fill");return A.style.width=`${Math.max(0,Math.min(100,v))}%`,C.append(A),r.append(C),r}if(n==="modal"){const r=m("section","cultui-modal-surface");w(r,e),S(r,o,a);const d=g(i.title,"");d&&r.append(m("h2","cultui-modal-surface-title",d));for(const u of s)r.append(F(u,t));return r}if(n==="options"){const r=m("section","cultui-options");w(r,e),S(r,o,a);const d=g(i.label,"");d&&r.append(m("h3","cultui-list-title",d));for(const u of s)r.append(F(u,t));return s.length===0&&r.append(q("waiting for options")),r}if(n==="image.preview"){const r=m("figure","cultui-image-preview");w(r,e);const d=m("div","cultui-image-frame"),u=ee(p(i.src,i.assetUri,i.assetRef,""));if(u){const h=m("img");h.src=u,h.alt=g(i.label,""),h.style.imageRendering=g(i.imageRendering,"auto"),i.zoom!==void 0&&(h.style.transform=`scale(${i.zoom})`,h.style.transformOrigin=g(i.crop,"50% 50%")),d.append(h)}else d.append(m("span","",g(i.label,"image")));return r.append(d),i.label&&r.append(m("figcaption","",String(i.label))),r}if(n==="canvas.preview"||n==="canvas.editor"){const r=m("div",`cultui-canvas-placeholder ${n==="canvas.editor"?"editor":"preview"}`);return w(r,e),r.append(m("div","viz-label",g(i.label,"Canvas"))),r.append(m("div","cultui-canvas-grid",i.state==="empty"?"waiting for pixels":g(i.state,""))),r}if(n==="surface.slot"){const r=m("section","cultui-embedded-slot");w(r,e),S(r,o,a),r.dataset.slotId=g(i.slotId,g(l[0]?.slotId,"")),r.dataset.documentId=g(i.documentId,g(l[0]?.documentId,"")),r.dataset.schemaId=g(i.schemaId,g(l[0]?.schemaId,"")),r.dataset.presentationKind=g(i.presentationKind,g(l[0]?.presentationKind,""));const d=l.map(h=>x(h.surface)).find(h=>x(h.root).kind||h.root),u=i.modal===!0||r.dataset.presentationKind.includes("modal");if((d||r.dataset.documentId)&&u){const h=m("button","cultui-button cultui-modal-trigger",g(i.label,r.dataset.slotId||"Configure"));h.type="button",h.addEventListener("click",()=>it(Se(e,t),t)),r.append(h)}else if(d||r.dataset.documentId){const h=m("div","cultui-embedded-slot-body");h.append(m("div","detail","materializing surface")),r.append(h),Se(e,t).then(y=>{h.replaceChildren(y?.root?F(y.root,t):q("Embedded surface unavailable"))}).catch(y=>{h.replaceChildren(q(`Embedded surface failed: ${y instanceof Error?y.message:String(y)}`))})}else r.append(m("div","detail",r.dataset.presentationKind||r.dataset.slotId||"embedded surface"));return r}if(n==="control.slider")return gn(i,s,t);if(n==="control.toggle"){const r=m("label","toggle-row cultui-toggle");return w(r,e),r.append(m("span","field-control",i.value?"on":"off")),r.append(m("span","toggle-copy",g(i.label,"Toggle"))),r}if(n==="input.number"||n==="input.select"||n==="control.range"||n==="control.input.text"||n==="control.select"){const r=m("label","field cultui-field");return w(r,e),ce(r,i),S(r,o,a),r.append(m("span","field-label",g(i.label,""))),r.append(m("span","field-control cultui-field-value",i.value===void 0?"":String(i.value))),r}if(n==="color.swatch"){const r=m("div","paint-swatch cultui-swatch");return w(r,e),r.style.background=g(i.value,g(i.color,"currentColor")),r.title=g(i.label,"Color"),r}const c=m("section","pane");w(c,e),c.append(m("h2","",n));for(const r of s)c.append(F(r,t));return c}function et(e){const t=x(e.props);return{label:p(t.label,t.title,t.displayName,e.text,e.kind,"item"),status:p(t.status,t.state,""),detail:p(t.detail,t.phase,t.repoName,""),badges:Array.isArray(t.badges)?t.badges.map(n=>String(n).trim()).filter(Boolean):p(t.badges,"").split(",").map(n=>n.trim()).filter(Boolean)}}function S(e,t,n={}){const i=p(t.display,"");i&&(e.style.display=i);const o=p(t.direction,"");o&&(e.style.flexDirection=o==="horizontal"?"row":o==="vertical"?"column":o);const a=p(t.flexWrap,"");a&&(e.style.flexWrap=a);const s=p(t.gridTemplateColumns,"");s&&(e.style.gridTemplateColumns=s);const l=p(t.gridTemplateRows,"");l&&(e.style.gridTemplateRows=l);const f=p(t.gridTemplateAreas,"");f&&(e.style.gridTemplateAreas=f);const c=p(t.gridArea,"");c&&(e.style.gridArea=c);const r=p(t.placeItems,"");r&&(e.style.placeItems=r),P(e,"gap",p(t.gap,"")),P(e,"padding",p(t.padding,"")),P(e,"margin",p(t.margin,"")),P(e,"top",p(t.top,"")),P(e,"right",p(t.right,"")),P(e,"bottom",p(t.bottom,"")),P(e,"left",p(t.left,"")),P(e,"width",p(t.width,"")),P(e,"minWidth",p(t.minWidth,"")),P(e,"maxWidth",p(t.maxWidth,"")),P(e,"height",p(t.height,"")),P(e,"minHeight",p(t.minHeight,"")),P(e,"maxHeight",p(t.maxHeight,""));const d=p(t.alignItems,"");d&&(e.style.alignItems=d);const u=p(t.justifyContent,"");u&&(e.style.justifyContent=u);const h=p(t.alignSelf,"");h&&(e.style.alignSelf=h);const y=p(t.overflow,"");y&&(e.style.overflow=y);const b=p(t.overflowX,"");b&&(e.style.overflowX=b);const v=p(t.overflowY,"");v&&(e.style.overflowY=v);const C=p(t.position,"");C&&(e.style.position=C);const A=p(t.cursor,"");A&&(e.style.cursor=A);const N=p(n.background,"");N&&(e.style.background=de(N));const Y=p(n.color,"");Y&&(e.style.color=de(Y)),P(e,"borderWidth",p(n.borderWidth,""));const z=p(n.borderColor,"");z&&(e.style.borderColor=de(z));const H=p(n.borderStyle,"");H&&(e.style.borderStyle=H),P(e,"borderRadius",p(n.borderRadius,""));const V=p(n.boxShadow,"");V&&(e.style.boxShadow=V);const K=p(n.font,"");K&&(e.style.font=K),P(e,"fontSize",p(n.fontSize,""));const _=p(n.fontWeight,"");_&&(e.style.fontWeight=_);const J=p(n.textTransform,"");J&&(e.style.textTransform=J);const ie=p(n.textAlign,"");ie&&(e.style.textAlign=ie);const he=p(n.whiteSpace,"");he&&(e.style.whiteSpace=he);const Fe=p(n.overflow,"");Fe&&(e.style.overflow=Fe);const Le=p(n.textOverflow,"");Le&&(e.style.textOverflow=Le),P(e,"lineHeight",p(n.lineHeight,""))}function P(e,t,n){n&&(e.style[t]=R(n))}function k(e,t){const n={};for(const[i,o]of Object.entries(e))i.startsWith(t)&&(n[i.slice(t.length)]=o);return n}function Zt(e){const t=(e.children||[]).filter(u=>u.kind==="world.entity3d"),n=t.map(u=>rn(x(u.props).position,[0,0,0])),i=n.map(u=>u[0]),o=n.map(u=>u[2]),a=Math.min(...i,-1),s=Math.max(...i,1),l=Math.min(...o,-1),f=Math.max(...o,1),c=Math.max(1,s-a),r=Math.max(1,f-l),d=6;return t.map((u,h)=>{const y=x(u.props);return{entityId:p(y.entityId,u.id),faction:g(y.faction,"neutral"),kind:g(y.entityKind,"entity"),label:p(y.label,y.entityId,u.id,"Entity"),controlled:Ce(y.controllable),xPercent:d+(n[h][0]-a)/c*(100-d*2),yPercent:d+(1-(n[h][2]-l)/r)*(100-d*2),source:u}})}function Qt(e,t,n,i,o){const a=m("section","cultui-world-scene");w(a,e),S(a,n,i),a.tabIndex=0,a.setAttribute("aria-label",g(t.label,"Interactive world"));const s=Zt(e),l=s.find(r=>r.controlled),f=m("div","cultui-world-heading");f.append(m("strong","",g(t.label,"World"))),f.append(m("span","",`${s.length} entities`)),a.append(f);const c=m("div","cultui-world-plane");for(const r of s){const d=m("button",`cultui-world-entity faction-${$e(r.faction)} kind-${$e(r.kind)}`);d.type="button",d.style.left=`${r.xPercent}%`,d.style.top=`${r.yPercent}%`,d.dataset.entityId=r.entityId,d.dataset.controlled=r.controlled?"true":"false",d.title=r.label,d.setAttribute("aria-label",`${r.label}, ${r.kind}, ${r.faction}`),d.append(m("span","cultui-world-entity-glyph",nn(r.kind))),d.append(m("span","cultui-world-entity-label",r.label));const u=x(r.source.props),h=p(u.targetCommand,t.targetCommand,u.focusCommand,t.focusCommand);h&&d.addEventListener("click",()=>ye(h,{actorEntityId:l?.entityId||p(t.playerEntityId),entityId:r.entityId,targetEntityId:r.entityId,targetEntityKey:r.entityId},r.source,o)),c.append(d)}return a.append(c),a.addEventListener("keydown",r=>{const d=tn(r.key);if(d){r.preventDefault();const h=p(t.movementCommand,x(l?.source.props).moveCommand);h&&ye(h,{actorEntityId:l?.entityId||p(t.playerEntityId),actorEntityKey:l?.entityId||p(t.playerEntityId),directionX:d[0],directionY:d[1],scalar:1},e,o);return}const u=r.key===" "?p(t.actionCommand,x(l?.source.props).actionCommand):r.key.toLowerCase()==="f"?p(t.focusCommand,x(l?.source.props).focusCommand):"";u&&(r.preventDefault(),ye(u,{actionId:r.key===" "?"0":"focus",actorEntityId:l?.entityId||p(t.playerEntityId),actorEntityKey:l?.entityId||p(t.playerEntityId)},e,o))}),a}function ye(e,t,n,i){i.commandSink?.(en(e,t,i),n)}function en(e,t,n=W){return ne(e,{action:t},n)}function tn(e){switch(e.toLowerCase()){case"w":case"arrowup":return[0,1];case"s":case"arrowdown":return[0,-1];case"a":case"arrowleft":return[-1,0];case"d":case"arrowright":return[1,0];default:return}}function nn(e){return e.includes("station")?"S":e.includes("projectile")?".":e.includes("ship")?"^":"+"}function $e(e){return e.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}function X(e,t){const n=Number(e);return Number.isFinite(n)?n:t}function rn(e,t){if(Array.isArray(e)){const n=e.map(i=>Number(i));if(n.length>=3&&n.slice(0,3).every(Number.isFinite))return[n[0],n[1],n[2]]}if(typeof e=="string"){const n=e.split(/[,\s]+/).map(i=>Number(i)).filter(Number.isFinite);if(n.length>=3)return[n[0],n[1],n[2]]}return t}function on(e,t,n,i){const o=Ce(t.active),a=m("section","cultui-inventory-drag");w(a,e),S(a,n,i),a.dataset.active=o?"true":"false";const s=m("div","cultui-inventory-section-label","Drag");if(S(s,k(n,"sectionLabel."),k(i,"sectionLabel.")),a.append(s),!o){const d=m("div","cultui-inventory-empty","None");return S(d,k(n,"empty."),k(i,"empty.")),a.append(d),a}const l=p(t.itemKey,t.item,"item"),f=m("div","cultui-inventory-drag-chip",l);S(f,k(n,"dragChip."),k(i,"dragChip.")),a.append(f);const c=[t.originOffsetX,t.originOffsetY].map(d=>Number(d)).map(d=>Number.isFinite(d)?d:0),r=m("div","cultui-inventory-meta",`origin ${c[0]}, ${c[1]}`);return S(r,k(n,"meta."),k(i,"meta.")),a.append(r),a}function an(e,t,n,i,o){const a=m("section","cultui-inventory-grid");w(a,e),S(a,n,i);const s=D(p(t.columns,t.gridColumns,t.widthCells,""),0),l=s>0?s:6,f=D(t.rows,0),c=f>0?f:Math.max(3,Math.ceil(Math.max((e.children||[]).length,1)/l));a.style.setProperty("--inventory-columns",String(l)),a.style.setProperty("--inventory-rows",String(c)),a.dataset.cellSpriteMode=g(t.cellSpriteMode,"");const r=p(t.title,t.label,"Inventory"),d=m("div","cultui-inventory-section-label",r);S(d,k(n,"sectionLabel."),k(i,"sectionLabel.")),a.append(d);const u=m("div","cultui-inventory-board");u.style.display="grid",u.style.gridTemplateColumns=`repeat(${l}, ${R(p(t.cellSize,"72"))})`,u.style.gridTemplateRows=`repeat(${c}, ${R(p(t.cellSize,"72"))})`,u.style.gap=R(p(t.cellGap,"4")),u.style.overflow=p(t.boardOverflow,"auto"),u.style.padding=R(p(t.boardPadding,"4")),S(u,k(n,"board."),k(i,"board.")),u.addEventListener("dragover",b=>{sn(t)&&(b.preventDefault(),b.dataTransfer&&(b.dataTransfer.dropEffect="move"))}),u.addEventListener("drop",b=>{const v=b.dataTransfer?.getData("application/vnd.gamecult.eve.inventory-item+json")||"";if(!v)return;let C;try{C=JSON.parse(v)}catch{return}const A=u.getBoundingClientRect(),N=Math.max(1,X(t.cellSize,72)),Y=Math.max(0,X(t.cellGap,4)),z=N+Y,H=Math.max(0,Math.min(l-1,Math.floor((b.clientX-A.left)/z))),V=Math.max(0,Math.min(c-1,Math.floor((b.clientY-A.top)/z))),K=ln(C,t,H,V,o);K&&(b.preventDefault(),o.commandSink?.(K,e))});const h=new Set;for(const b of e.children||[]){const v=x(b.props),C=D(v.x,0),A=D(v.y,0);h.add(`${C}:${A}`),u.append(F(b,o))}const y=Math.min(l*c,256);for(let b=0;b{!a.draggable||!y.dataTransfer||(y.dataTransfer.effectAllowed="move",y.dataTransfer.setData("application/vnd.gamecult.eve.inventory-item+json",JSON.stringify(t)))});let f=D(t.shapeWidth,1),c=D(t.shapeHeight,1);const r=p(t.rotation,"").toLowerCase();["clockwise","counterclockwise","right","left","rotate90","rotate270"].includes(r)&&([f,c]=[c,f]),a.style.gridColumn=`${s+1} / span ${f}`,a.style.gridRow=`${l+1} / span ${c}`;const d=m("span","cultui-inventory-item-icon");S(d,k(n,"icon."),k(i,"icon.")),d.textContent=In(p(t.iconAssetUri,t.iconAssetKey,t.itemKey,t.label,"")),a.append(d);const u=p(t.label,t.itemKey,"");if(u){const y=m("span","cultui-inventory-item-label",u);S(y,k(n,"label."),k(i,"label.")),a.append(y)}const h=Number(t.quantity);if(Number.isFinite(h)&&h>1){const y=m("span","cultui-inventory-item-quantity",String(h));S(y,k(n,"quantity."),k(i,"quantity.")),a.append(y)}return a.title=[u,p(t.source,""),p(t.quality,"")?`quality ${t.quality}`:"",p(t.durability,"")?`durability ${t.durability}`:""].filter(Boolean).join(" | "),a}function sn(e){return Object.entries(e).some(([t,n])=>(t==="dropCommand"||t.startsWith("dropCommand."))&&typeof n=="string"&&n.length>0)}function ln(e,t,n,i,o=W){const a=p(e.sourceKind,e.source,""),s=p(t[`dropCommand.${a}`],t.dropCommand,"");if(!a||!s)return;const l=X(e.sourceIndex,-1),f=X(t.targetIndex,-1),c=p(t.targetKind,""),r={sourceKind:a,originEntityKey:p(e.sourceEntityKey,e.entityKey,""),originIndex:l,originCargoIndex:a==="cargo"?l:-1,itemKey:p(e.itemKey,""),quantity:Math.max(1,X(e.quantity,1)),sourceX:X(e.x,-2147483648),sourceY:X(e.y,-2147483648),destinationKind:c,destinationEntityKey:p(t.targetEntityKey,t.entityKey,""),destinationIndex:f,destinationCargoIndex:c==="cargo"?f:-1,destinationX:Math.trunc(n),destinationY:Math.trunc(i),hasDestinationPosition:!0};return ne(s,{action:r},o)}function dn(e,t,n){const i=m("section","cultui-binding-map");w(i,e);const o=document.createElementNS("http://www.w3.org/2000/svg","svg");o.setAttribute("class","cultui-xbox-controller"),o.setAttribute("viewBox","0 0 780 420"),o.setAttribute("role","img"),o.setAttribute("aria-label",g(t.label,"Xbox controller remapping")),o.innerHTML=mn(),i.append(o);const a=m("div","cultui-binding-overlay");for(const s of e.children||[]){const l=x(s.props),f=g(l.target,s.id||""),c=m("button","cultui-binding-box");w(c,s),c.type="button",c.dataset.target=f,c.dataset.kind=g(l.bindingKind,"button"),c.style.left=R(l.x??"50%"),c.style.top=R(l.y??"50%"),c.append(m("span","cultui-binding-target",g(l.label,f))),c.append(m("span","cultui-binding-source",g(l.current,"unmapped"))),c.addEventListener("click",()=>{const d=nt(s);if(tt(s)||d?.documentId)it(Se(s,n),n);else{const u=g(l.commandId,"");u&&n.commandSink?.(ne(u,l,n),s)}}),a.append(c);const r=document.createElementNS("http://www.w3.org/2000/svg","line");r.setAttribute("class","cultui-binding-line"),r.setAttribute("x1",g(l.anchorX,"390")),r.setAttribute("y1",g(l.anchorY,"210")),r.setAttribute("x2",String(We(l.x,780))),r.setAttribute("y2",String(We(l.y,420))),o.append(r)}return i.append(a),i}function tt(e){for(const t of e.embeddedDocuments||[]){const n=x(t.surface);if(n.root)return n}}function nt(e){const t=(e.embeddedDocuments||[])[0],n=x(e.props),i=p(n.documentId,t?.documentId,"");if(i)return{documentId:i,presentationKind:p(n.presentationKind,t?.presentationKind,""),schemaId:p(n.schemaId,t?.schemaId,""),slotId:p(n.slotId,t?.slotId,"")}}async function Se(e,t){const n=tt(e);if(n)return n;const i=nt(e);if(!i?.documentId||!t.documentResolver)return;const o=await t.documentResolver(i,e);if(o)return x(o.surface).root?o.surface:o}function it(e,t){const n=m("div","cultui-modal-backdrop"),i=m("section","cultui-modal");i.setAttribute("role","dialog"),i.setAttribute("aria-modal","true");const o=m("header","cultui-modal-header");o.append(m("h2","","Configure Binding"));const a=m("button","cultui-modal-close","Close");a.type="button",a.addEventListener("click",()=>n.remove()),o.append(a);const s=m("div","cultui-modal-body");i.append(o,s),n.append(i),n.addEventListener("click",l=>{l.target===n&&n.remove()}),document.body.append(n),s.append(m("div","detail","materializing document")),Promise.resolve(e).then(l=>{o.querySelector("h2").textContent=l?.title||"Configure Binding",s.replaceChildren(l?.root?F(l.root,t):q("Embedded document unavailable"))}).catch(l=>{s.replaceChildren(q(`Embedded document failed: ${l instanceof Error?l.message:String(l)}`))})}function un(e,t,n,i,o){const a=x(e.props),s=(e.children||[])[0],l=x(s?.props),f=p(l.anchor,a.anchor,"trigger"),c=p(l.placement,a.placement,"below-start"),r=Number(p(l.offsetX,a.offsetX,"0"))||0,d=Number(p(l.offsetY,a.offsetY,"4"))||0,u=m("div","cultui-modal-backdrop");u.style.background="transparent",u.style.placeItems="start";const h=m("section","cultui-modal");h.setAttribute("role","dialog"),h.setAttribute("aria-modal","true"),h.style.position="fixed",h.style.width="min(420px, calc(100vw - 24px))",h.style.maxHeight="min(620px, calc(100vh - 24px))";const y=m("header","cultui-modal-header");y.append(m("h2","",p(l.title,a.title,a.label,"Options")));const b=m("button","cultui-modal-close","Close");b.type="button",b.addEventListener("click",()=>u.remove()),y.append(b);const v=m("div","cultui-modal-body");if(s){const A=s.children||[];A.length>0?v.replaceChildren(...A.map(N=>F(N,t))):v.append(F(s,t))}else v.append(q("Popup has no content"));h.append(y,v),u.append(h),u.addEventListener("click",A=>{A.target===u&&u.remove()}),document.body.append(u);const C=fn(f,c,n,h,i,o,r,d);h.style.left=`${C.left}px`,h.style.top=`${C.top}px`}function fn(e,t,n,i,o,a,s,l){const f=n.getBoundingClientRect(),c=i.getBoundingClientRect(),r=c.width||420,d=c.height||320,u=e==="cursor"?{left:o,right:o,top:a,bottom:a}:f;if(t==="right-down"||t==="dropdown")return ae(u,r,d,s,l,"right","down");if(t==="left-down")return ae(u,r,d,s,l,"left","down");if(t==="right-up")return ae(u,r,d,s,l,"right","up");if(t==="left-up")return ae(u,r,d,s,l,"left","up");switch(t){case"above-start":return U(u.left+s,u.top-d-l,r,d);case"above-end":return U(u.right-r+s,u.top-d-l,r,d);case"below-end":return U(u.right-r+s,u.bottom+l,r,d);case"right-start":return U(u.right+s,u.top+l,r,d);case"left-start":return U(u.left-r-s,u.top+l,r,d);case"center":return U((window.innerWidth-r)/2+s,(window.innerHeight-d)/2+l,r,d);default:return U(u.left+s,u.bottom+l,r,d)}}function ae(e,t,n,i,o,a,s){const f=window.innerWidth-e.right-i-12,c=e.left-i-12,r=window.innerHeight-e.top-o-12,d=e.bottom-o-12,u=a==="right"?f>=t||f>=c:!(c>=t||c>=f),h=s==="down"?r>=n||r>=d:!(d>=n||d>=r),y=u?e.right+i:e.left-t-i,b=h?e.top+o:e.bottom-n-o;return U(y,b,t,n)}function U(e,t,n,i){return{left:Ue(e,12,window.innerWidth-n-12),top:Ue(t,12,window.innerHeight-i-12)}}function Ue(e,t,n){return n - - - - - - - - - - - - - - - - - YBXA - `}function pn(e,t=document.body){const n=_e(e),i=document.documentElement.style;bn(n.assets.fontCss);for(const[c,r]of Object.entries(Ht))i.setProperty(c,r);const o={colorBackground:"--bg",colorBackgroundTop:"--bg-top",colorBackgroundMid:"--bg-mid",colorBackgroundBottom:"--bg-bottom",colorShellSurfaceTop:"--shell-top",colorShellSurfaceBottom:"--shell-bottom",colorPanel:"--panel",colorPanelAlt:"--panel-2",colorPanelBorder:"--line",colorPanelBorderDeep:"--line-deep",colorText:"--text",colorTextBright:"--text-bright",colorMuted:"--quiet",colorAccent:"--accent",colorAccentStrong:"--accent-strong",colorCornerAccent:"--corner-accent",colorLink:"--cyan",colorShadow:"--shadow",colorPixelGrid:"--pixel-grid"};for(const[c,r]of Object.entries(o)){const d=n.tokens[c];d!==void 0&&i.setProperty(r,String(d))}const a=n.tokens.fontBody,s=n.tokens.fontDisplay,l=n.tokens.fontTitle,f=n.tokens.fontMono;a&&i.setProperty("--font-body",se(String(a))),s&&i.setProperty("--font-title",se(String(s))),l&&i.setProperty("--font-title",se(String(l))),f&&i.setProperty("--font-mono",se(String(f))),n.tokens.borderWidthPx&&i.setProperty("--border-width",`${n.tokens.borderWidthPx}px`),n.tokens.borderBottomWidthPx&&i.setProperty("--border-bottom-width",`${n.tokens.borderBottomWidthPx}px`),n.tokens.cornerAccentPx&&i.setProperty("--corner-accent-size",`${n.tokens.cornerAccentPx}px`),t.dataset.pixelArt=n.tokens.pixelArt||n.tokens.imageRendering==="pixelated"?"true":"false",t.dataset.scanlines=n.tokens.scanlineOverlay?"true":"false"}function ne(e,t={},n=W){const i=x(t.action),o=n.provider?.providerId||te?.providerId||"surface unknown",a=n.activeSurfaceId||te?.surface?.id||n.provider?.surfaces?.[0]?.surfaceId||o,s=hn(n,a),l=p(s.commandBoundary,t.commandBoundary,i.commandBoundary,i.target),f=p(s.receiptSchema,t.receiptSchema,i.receiptSchema),c={type:"surface-command",schema:"gamecult.eve.command_invocation.v1",providerId:o,surfaceId:a,command:e||g(i.type,"invoke"),payload:{...i,transport:t.transport??null},issuedAt:new Date().toISOString(),clientId:n.clientId||"eve.browser"};return l&&(c.commandBoundary=l),f&&(c.receiptSchema=f),c}function hn(e,t){const n=[...e.provider?.surfaces||[],...e.provider?.localAdvertisement?.surfaces||[]];return n.find(i=>i.surfaceId===t&&i.worldInteraction)?.worldInteraction||n.find(i=>i.worldInteraction)?.worldInteraction||{}}function Oe(e,t){const n=x(e.action);return g(e.command,g(e.commandId,g(n.command,g(n.target,g(n.type,t?.commandId||"")))))}function q(e){const t=m("section","pane");return t.append(m("h2","","No Surface")),t.append(m("div","detail",e)),t}function ze(e,t,n,i,o){e.dataset.commandId=n,e.tabIndex=e instanceof HTMLButtonElement?e.tabIndex:0;const a=()=>{const s=ne(n,i,o);o.commandSink?.(s,t)};e.addEventListener("click",a),e.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),a())})}function gn(e,t,n){const i=yn(e,t),o=x(i.find(u=>u.kind==="control.box")?.props),a=i.filter(u=>u.kind==="control.part"),s=Number(e.min??0),l=Number(e.max??1),f=m("div","cultui-slider");f.dataset.skin=g(e.skin,"default"),f.dataset.bind=g(e.bind,""),xn(f,o);const c=m("div","cultui-slider-visual"),r=m("input","cultui-slider-input");r.type="range",r.min=String(s),r.max=String(l),r.step=String(e.step??.01),r.setAttribute("aria-label",g(e.bind,"slider"));for(const u of a){const h=x(u.props),y=m("span",`cultui-slider-part ${g(h.name,"part")}`);wn(y,h),c.append(y)}return a.some(u=>x(u.props).name==="track")||c.append(m("span","cultui-slider-part track")),a.some(u=>x(u.props).name==="fill")||c.append(m("span","cultui-slider-part fill")),a.some(u=>x(u.props).name==="thumb")||c.append(m("span","cultui-slider-part thumb")),f.append(c,r),(u=>{const h=Number(u??s),y=Math.max(s,Math.min(l,Number.isFinite(h)?h:s)),b=l===s?0:(y-s)/(l-s)*100;r.value=String(y),f.style.setProperty("--cultui-slider-value",`${b}%`),f.dataset.value=String(y)})(e.value??s),r.addEventListener("input",()=>{const u=ne(g(e.command,"control.slider.input"),{...e,action:{...x(e.action),value:Number(r.value)},value:Number(r.value)},n);n.commandSink?.(u,{kind:"control.slider",props:e})}),f}function yn(e,t){const n=typeof e.skin=="string"?e.skin:"",o=[...n?Je.controlSkins[n]?.children||[]:[],...t];return o.length?o:[{kind:"control.box",props:{height:18,overflow:"visible"}},{kind:"control.part",props:{name:"track",anchor:"center",size:["100%",6],radius:2,fill:"color.panelInset"}},{kind:"control.part",props:{name:"fill",anchor:["left","center"],size:["value%",6],radius:2,fill:"color.accent"}},{kind:"control.part",props:{name:"thumb",anchor:["value","center"],size:[12,12],bleed:3,radius:999,fill:"color.accent"}}]}function _e(e){if(Array.isArray(e)){const t={},n={};for(const i of e)i?.name&&(i.name==="font.web.google"&&typeof i.value=="string"?n.fontCss=i.value:t[i.name]=i.value);return{tokens:t,assets:n,controlSkins:{}}}return{tokens:x(e?.tokens),assets:x(e?.assets),controlSkins:x(e?.controlSkins)}}function ee(e){if(!e)return"";const t=W.assetUrlResolver;return t?t(e,te):/^(https?:|data:|blob:)/i.test(e)?e:W.assetBaseUrl&&e.startsWith("/")?`${W.assetBaseUrl.replace(/\/+$/,"")}${e}`:e}function bn(e){const t=typeof e=="string"?e.trim():"";if(oe?.dataset.href===t||(oe?.remove(),oe=void 0,!t))return;const n=document.createElement("link");n.rel="preconnect",n.href="https://fonts.gstatic.com",n.crossOrigin="anonymous",document.head.append(n);const i=document.createElement("link");i.rel="stylesheet",i.href=t,i.dataset.href=t,document.head.append(i),oe=i}function vn(e,t,n){const i=[];return(e==="text.title"||t.role==="title")&&i.push("cultui-title","eve-text-title"),e==="text.subtitle"&&i.push("eve-text-subtitle"),e==="label"&&i.push("cultui-label"),t.role==="mono"&&i.push("detail","mono"),i.length===0&&i.push("detail","eve-text"),i.join(" ")}function xn(e,t){t.height!==void 0&&(e.style.minHeight=R(t.height)),t.width!==void 0&&(e.style.width=R(t.width)),typeof t.overflow=="string"&&(e.style.overflow=t.overflow)}function wn(e,t){const n=Array.isArray(t.size)?t.size:[t.size,void 0];n[0]!==void 0&&n[0]!=="value%"&&(e.style.width=R(n[0])),n[1]!==void 0&&(e.style.height=R(n[1])),t.radius!==void 0&&(e.style.borderRadius=R(t.radius)),t.fill!==void 0&&(e.style.background=de(String(t.fill))),t.bleed!==void 0&&e.style.setProperty("--part-bleed",R(t.bleed)),(Array.isArray(t.anchor)?t.anchor:[t.anchor]).includes("value")&&(e.dataset.anchorValue="true")}function ce(e,t){t.gap!==void 0&&(e.style.gap=R(t.gap)),t.padding!==void 0&&(e.style.padding=R(t.padding)),t.size!==void 0&&(e.style.flex=Sn(t.size)),t.min!==void 0&&(e.style.minWidth=R(t.min)),t.max!==void 0&&(e.style.maxWidth=R(t.max)),t.align!==void 0&&(e.style.alignItems=t.align==="end"?"flex-end":String(t.align)),(t.clip==="true"||t.clip===!0)&&(e.style.overflow="hidden"),t.scroll==="y"&&(e.style.overflowY="auto"),t.scroll==="x"&&(e.style.overflowX="auto")}function Sn(e){return typeof e=="string"&&e.endsWith("fr")?`${Number(e.slice(0,-2))||1} 1 0`:e==="auto"||e==="content"?"0 0 auto":`0 0 ${R(e)}`}function R(e){return Array.isArray(e)?e.map(R).join(" "):typeof e=="number"?`${e}px`:typeof e=="string"&&/^-?\d+(\.\d+)?$/.test(e)?`${e}px`:String(e??"")}function de(e){return{"color.accent":"var(--accent)","color.panelInset":"rgba(0, 0, 0, 0.34)","color.panel":"var(--panel)","color.text":"var(--text)"}[e]||e}function se(e){return e.includes("Zen Kaku Gothic New")||e.includes("M PLUS 1")?e:e.includes("Montserrat")?`${e}, "Zen Kaku Gothic New", "M PLUS 1", "Noto Sans JP", "Hiragino Sans", "Yu Gothic", sans-serif`:e.includes("Ubuntu")?`${e}, "M PLUS 1", "Noto Sans JP", "Hiragino Sans", "Yu Gothic", sans-serif`:`${e}, "Noto Sans JP", "Hiragino Sans", "Yu Gothic", sans-serif`}function w(e,t){t.id&&(e.id=t.id),t.id&&(e.dataset.eveNodeId=t.id),t.kind&&(e.dataset.eveKind=t.kind)}function x(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function En(e){return Array.isArray(e)?e:[]}function An(e){return En(e).map((t,n)=>et({kind:"list.item",props:x(t)}))}function g(e,t){return e==null?t:String(e)}function p(...e){for(const t of e){if(typeof t=="string"&&t.trim())return t;if(typeof t=="number"&&Number.isFinite(t))return String(t)}return""}function Ce(e){return typeof e=="boolean"?e:typeof e=="number"?e!==0:typeof e=="string"?["1","true","yes","on"].includes(e.trim().toLowerCase()):!1}function D(e,t){const n=Number(e);return Number.isFinite(n)?Math.max(0,Math.floor(n)):t}function In(e){const t=e.toLowerCase();return t.includes("sensor")?"S":t.includes("thermal")?"T":t.includes("fuel")?"F":t.includes("cargo")?"C":t.includes("weapon")?"W":e.trim().slice(0,1).toUpperCase()||"?"}function _n(e){const t=e.trim().split(/\s+/).filter(Boolean);return t.length&&t.slice(0,2).map(n=>n[0]?.toUpperCase()||"").join("")||"?"}function Ke(e){const t=Number(e);return Number.isFinite(t)?Math.max(0,Math.min(100,t)):0}function m(e,t="",n=""){const i=document.createElement(e);return t&&(i.className=t),n&&(i.textContent=n),i}const Ge=document.querySelector("#surface"),B=document.querySelector("#status"),pe=document.querySelector("#receipt"),Cn=document.querySelector("#compiler"),Te=document.querySelector("#composer"),ue=document.querySelector("#destination-form"),Ee=document.querySelector("#compiler-results"),Tn=document.querySelector("#campaign-lab"),je=document.querySelector("#campaign-list");let Re=0;async function O(){const e=await fetch("/api/surface");if(e.status===401){B.textContent="This laboratory requires an unused invite link.";return}const t=await e.json(),n=t.surface_id==="ghostlight.compiler";if(Cn.hidden=!n,Te.hidden=n,ue.hidden=n,Ge.hidden=n,Tn.hidden=n,n){B.textContent="No campaign exists. Retrieve the Vault and approve a world seed.";return}Re=Number(t.version??0),Ze(t,Ge,{body:document.body,clientId:"ghostlight.browser",statusElement:B});const i=await fetch("/api/campaigns").then(o=>o.json());je.innerHTML=i.campaigns.map(o=>``).join(""),je.querySelectorAll("button:not(:disabled)").forEach(o=>o.addEventListener("click",async()=>{await $(`/api/campaigns/select/${o.dataset.campaignId}`,{}),await O()}))}async function $(e,t){B.textContent="Retrieving evidence and compiling…";const n=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),i=n.headers.get("content-type")?.includes("json")?await n.json():await n.text();if(!n.ok)throw B.textContent=typeof i=="string"?i:"Compilation failed",new Error(B.textContent);return i}function Xe(e,t,n){Ee.innerHTML=`
${e.map((i,o)=>`

${i.title??i.name}

${i.player_hook??i.premise}

${i.era?`${i.era} · ${i.place} · ${i.pressure}`:""}

`).join("")}
`,Ee.querySelectorAll("button").forEach(i=>i.addEventListener("click",()=>n(e[Number(i.dataset.index)])))}document.querySelector("#suggest-form").addEventListener("submit",async e=>{e.preventDefault();const t=await $("/api/compiler/openings",{setting:document.querySelector("#setting").value,constraints:[]});Xe(t.openings,"Choose opening",async n=>{const i=await $("/api/compiler/roles",n);Xe(i.roles,"Choose role",async o=>rt(await $("/api/compiler/selected",{campaign_name:n.title,opening:n,role:o})))})});document.querySelector("#custom-form").addEventListener("submit",async e=>{e.preventDefault(),await rt(await $("/api/compiler/custom",Object.fromEntries(new FormData(e.currentTarget))))});async function rt(e){const t=e.preview;Ee.innerHTML=`

${t.title}

${t.campaign.transcript?.[0]?.text??""}

${Object.keys(t.campaign.locations).length} locations · ${Object.keys(t.campaign.actors).length} actors · ${Object.keys(t.campaign.institutions).length} institutions

${t.gaps.length?`Material gaps: ${t.gaps.join("; ")}`:"No declared material gaps."}

Branch assumptions: ${t.branch_assumptions.join("; ")||"none"}

`,document.querySelector("#approve-world").addEventListener("click",async()=>{await $(`/api/compiler/approve/${e.preview_id}`,{}),await O()}),B.textContent="Preview compiled. Nothing has entered world state yet."}async function ke(e){B.textContent="The world is considering the command…";const t=await fetch("/api/command",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)}),n=await t.json();return pe.hidden=!1,pe.textContent=JSON.stringify(n,null,2),t.ok?(await O(),n):(B.textContent=n.error??"The command was refused.",await O(),n)}function ot(e){if(e?.kind!=="assessed")return;const t=document.createElement("button");t.type="button",t.textContent=e.assessment.admissible?"Confirm server roll":"Revise attempt",t.addEventListener("click",async()=>{if(!e.assessment.admissible){document.querySelector("#attempt").focus();return}const n=await ke({type:"attempt",assessment_digest:e.assessment.digest});t.remove(),ot(n)}),Te.append(t)}Te.addEventListener("submit",async e=>{e.preventDefault();const t=document.querySelector("#attempt").value.trim();t&&ot(await ke({type:"assess",expected_revision:Re,intent:{actor_id:"player",description:t,intended_effect:t}}))});document.querySelector("#wait").addEventListener("click",()=>{ke({type:"wait",expected_revision:Re,minutes:60})});ue.addEventListener("submit",async e=>{e.preventDefault();const t=await $("/api/compiler/destination",Object.fromEntries(new FormData(ue))),n=t.preview;pe.hidden=!1,pe.textContent=JSON.stringify(n,null,2),B.textContent="Destination preview compiled; topology is unchanged until approval.";const i=document.createElement("button");i.textContent="Approve destination",i.addEventListener("click",async()=>{await $(`/api/compiler/destination/approve/${t.preview_id}`,{}),i.remove(),await O()}),ue.append(i)});document.querySelector("#fork-form").addEventListener("submit",async e=>{e.preventDefault(),await $("/api/campaigns/fork",Object.fromEntries(new FormData(e.currentTarget))),await O()});document.querySelector("#reset-form").addEventListener("submit",async e=>{e.preventDefault(),await $("/api/campaigns/reset",Object.fromEntries(new FormData(e.currentTarget))),await O()});document.querySelector("#load-operator").addEventListener("click",async()=>{const t=await(await fetch("/api/operator")).json();Ze(t,document.querySelector("#operator-output"),{body:document.body,clientId:"ghostlight.operator",statusElement:B})});O(); diff --git a/web/dist/assets/index-Dt7lvyL0.css b/web/dist/assets/index-BnHnsfZy.css similarity index 95% rename from web/dist/assets/index-Dt7lvyL0.css rename to web/dist/assets/index-BnHnsfZy.css index c24bc68..9cefa1f 100644 --- a/web/dist/assets/index-Dt7lvyL0.css +++ b/web/dist/assets/index-BnHnsfZy.css @@ -1 +1 @@ -@import"https://fonts.googleapis.com/css2?family=M+PLUS+1:wght@100;300;400;500;700&family=Montserrat:wght@100;300;400;500;700&family=Ubuntu+Sans:wght@300;400;500;700&family=Zen+Kaku+Gothic+New:wght@300;400;500;700&display=swap";@import"https://fonts.googleapis.com/css2?family=Crimson+Pro:opsz,wght@8..144,400;8..144,600&family=IBM+Plex+Mono:wght@400;600&display=swap";:root{color-scheme:dark;--bg: #020909;--bg-top: var(--bg);--bg-mid: var(--bg);--bg-bottom: var(--bg);--shell-top: #010707;--shell-bottom: #010707;--panel: #071918;--panel-2: #0a2423;--line: rgba(103, 240, 228, .28);--line-deep: rgba(103, 240, 228, .18);--line-hot: rgba(142, 252, 255, .72);--text: #e7f1f1;--text-bright: var(--text);--quiet: #8ba5a3;--accent: #ffb84f;--accent-strong: var(--accent);--corner-accent: var(--accent);--cyan: #8efcff;--shadow: rgba(0, 0, 0, .35);--pixel-grid: rgba(142, 252, 255, .04);--border-width: 1px;--border-bottom-width: var(--border-width);--corner-accent-size: 0;--font-body: "M PLUS 1", "Ubuntu Sans", Ubuntu, "Noto Sans JP", system-ui, sans-serif;--font-title: "Montserrat", "Zen Kaku Gothic New", "M PLUS 1", "Ubuntu Sans", system-ui, sans-serif;--font-mono: "Ubuntu Sans Mono", "M PLUS 1 Code", "Cascadia Mono", Consolas, monospace}*{box-sizing:border-box}body{margin:0;min-height:100vh;background:linear-gradient(180deg,var(--bg-top),var(--bg-mid),var(--bg-bottom));color:var(--text);font-family:var(--font-body)}.topbar{height:84px;display:flex;justify-content:space-between;align-items:center;padding:10px 16px;border-bottom:1px solid var(--line);background:linear-gradient(180deg,var(--shell-top),var(--shell-bottom))}h1{margin:0;font-size:20px;letter-spacing:0}p{margin:4px 0 0;color:var(--quiet);font-size:13px}.hud{min-width:168px;padding:8px;border:1px solid var(--line-hot);border-radius:6px;background:#071918e0;color:var(--accent);font-family:Cascadia Mono,Consolas,monospace;font-size:11px;display:grid;gap:2px}.provider-bar{display:flex;align-items:center;gap:8px;padding:10px 16px;border-bottom:1px solid var(--line-deep);background:color-mix(in srgb,var(--panel) 70%,transparent)}.provider-bar label{color:var(--quiet);font:700 11px var(--font-mono);text-transform:uppercase}.provider-bar select{border:1px solid var(--line);border-radius:6px;background:var(--panel);color:var(--text);padding:8px 12px;font:700 13px var(--font-mono);min-width:min(28rem,52vw)}.provider-meta{color:var(--quiet);font:600 11px var(--font-mono);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.surface{padding:10px 16px 16px}.cockpit{display:grid;grid-template-columns:.78fr 1.08fr 1.34fr;gap:10px;min-height:calc(100vh - 138px)}.ctb{grid-column:1 / -1;min-height:88px;overflow-x:auto;display:flex;gap:8px;padding-bottom:8px}.pane{min-height:0;border:1px solid var(--line);border-radius:6px;background:#071918eb;padding:12px;box-shadow:0 12px 26px var(--shadow)}.pane h2{margin:0 0 10px;color:var(--quiet);font-size:12px;font-weight:500;text-transform:uppercase}.card{border:1px solid var(--line);border-radius:6px;background:#0a2423f5;padding:10px;box-shadow:0 8px 20px var(--shadow)}.cultui-card[data-command-id]{cursor:pointer;border-bottom-width:var(--border-bottom-width)}.cultui-card-button{display:block;width:100%;color:inherit;font:inherit;text-align:left}.ctb .card{flex:0 0 96px;min-height:76px;padding:6px}.avatar{width:34px;height:34px;border-radius:50%;border:1px solid var(--line-hot);object-fit:cover;background:#123}.card-title{white-space:pre-line;margin-top:4px;font:700 11px var(--font-mono)}.health{color:var(--accent);font:700 10px var(--font-mono)}.detail{white-space:pre-wrap;font:600 12px var(--font-mono);line-height:1.45}.list{display:grid;gap:8px}.metrics{display:grid;gap:9px;margin:12px 0}.metric label{display:flex;justify-content:space-between;color:var(--quiet);font:700 10px var(--font-mono)}.bar{height:7px;border-radius:7px;background:#010707;border:1px solid rgba(255,255,255,.12);overflow:hidden}.bar span{display:block;height:100%;background:linear-gradient(90deg,#bca8ff,#8efcff)}.graph{position:relative;min-height:calc(100vh - 166px);border:1px solid var(--line);border-radius:6px;background:linear-gradient(var(--pixel-grid) 1px,transparent 1px),linear-gradient(90deg,var(--pixel-grid) 1px,transparent 1px),#030f11f0;background-size:44px 44px}.node{position:absolute;transform:translate(-50%,-50%);border:1px solid var(--line);border-radius:7px;background:#0a2423f2;padding:10px;overflow:hidden}.node.selected{border-color:var(--line-hot);box-shadow:0 0 0 1px #8efcff61}.node .detail{margin-top:6px;color:var(--quiet);font-size:10px}@media(max-width:900px){.cockpit{grid-template-columns:1fr}}.cultui-vn-stage{position:relative;min-height:calc(100vh - 138px);overflow:hidden;border:1px solid var(--line);border-radius:6px;background:var(--bg)}.cultui-grid{min-height:calc(100vh - 138px);display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:10px;align-content:start}.cultui-surface-root{min-height:calc(100vh - 150px);display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:12px;align-content:start}.cultui-surface-root[data-direction=vertical]{grid-template-columns:minmax(0,1fr)}.cultui-surface-root[data-direction=horizontal]{grid-template-columns:repeat(auto-fit,minmax(260px,1fr))}.cultui-embedded-slot .cultui-surface-root{min-height:0;grid-template-columns:minmax(0,1fr)}@media(max-width:900px){.cultui-pane[data-span=wide]{grid-column:1 / -1}}.cultui-pane{border-width:var(--border-width);border-bottom-width:var(--border-bottom-width);min-width:0}.cultui-pane[data-span=wide]{grid-column:span 2}.cultui-pane .cultui-pane{box-shadow:none;background:#030f1161}.cultui-pane[data-density=compact]{padding:8px}.cultui-pane[data-density=compact] h2{margin-bottom:6px}.cultui-partition{min-width:0;min-height:0;display:flex;gap:10px}.cultui-partition[data-direction=horizontal]{flex-direction:row}.cultui-partition[data-direction=vertical]{flex-direction:column}.cultui-partition[data-overflow=x]{overflow-x:auto;padding-bottom:4px}.cultui-partition.split-x{flex-direction:row}.cultui-partition.split-y,.cultui-partition.split-none{flex-direction:column}.cultui-partition.split-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr))}.cultui-partition[data-role="inspector.row"]{min-height:34px;border:1px solid rgba(255,255,255,.06);border-radius:4px;background:linear-gradient(180deg,#201f2bf5,#13141df5);box-shadow:inset 0 1px #ffffff0d,0 2px 8px #0006}.cultui-partition[data-role="inspector.label"]{justify-content:center}.cultui-label{color:var(--accent);font:700 13px var(--font-mono);line-height:1.15;text-transform:uppercase}.cultui-slider{--cultui-slider-value: 0%;--part-bleed: 0px;position:relative;display:grid;align-items:center;width:100%;min-height:18px;overflow:visible}.cultui-slider-visual{position:absolute;inset:0;overflow:visible;pointer-events:none}.cultui-slider-input{position:absolute;inset:0;opacity:0;cursor:pointer}.cultui-slider-part{position:absolute;top:50%;display:block;transform:translateY(-50%)}.cultui-slider-part.track{right:0;left:0;height:6px;border-radius:2px;background:#00000057}.cultui-slider-part.fill{left:0;width:var(--cultui-slider-value);height:6px;border-radius:2px;background:var(--accent)}.cultui-slider-part.thumb{left:var(--cultui-slider-value);width:12px;height:12px;border-radius:999px;background:var(--accent);transform:translate(-50%,-50%);box-shadow:0 0 7px color-mix(in srgb,var(--accent) 45%,transparent)}.cultui-slider-part[data-anchor-value=true]{left:var(--cultui-slider-value);transform:translate(-50%,-50%)}@media(max-width:520px){.cultui-partition[data-role="inspector.row"]{flex-direction:column;align-items:stretch}.cultui-partition[data-role="inspector.label"]{flex:0 0 auto!important}}body[data-provider=repixelizer] .surface{position:relative}body[data-provider=repixelizer] .surface:after{content:"";pointer-events:none;position:fixed;inset:0;background:repeating-linear-gradient(0deg,rgba(255,255,255,.035) 0 1px,transparent 1px 4px);opacity:.28;mix-blend-mode:screen}body[data-pixel-art=true] img,body[data-pixel-art=true] .cultui-background{image-rendering:pixelated}.cultui-title{color:var(--accent);font:100 18px var(--font-title);line-height:1.35}.mono{color:var(--accent);font-family:var(--font-mono)}.cultui-reactive-metric{margin-top:8px}.cultui-reactive-list{display:grid;gap:8px}.cultui-list{display:grid;gap:8px;min-width:0}.cultui-list-title{margin:0;color:var(--quiet);font:700 10px var(--font-mono);letter-spacing:0;text-transform:uppercase}.cultui-list-item{display:grid;gap:5px;min-width:0;padding:8px;border:1px solid var(--line);border-radius:6px;background:var(--panel)}.cultui-list-item-heading,.cultui-list-item-badges{display:flex;gap:6px;align-items:center;flex-wrap:wrap;min-width:0}.cultui-list-item-label{min-width:0;overflow-wrap:anywhere}.cultui-list-item-status,.cultui-list-item-badge{padding:2px 5px;border:1px solid var(--line-hot);border-radius:4px;color:var(--quiet);font:600 10px var(--font-mono)}.cultui-list-item-detail{color:var(--quiet);font-size:12px;overflow-wrap:anywhere}.cultui-avatar-card{flex:0 0 104px;display:grid;gap:4px;align-content:start;min-height:92px;margin:0;padding:8px;border:1px solid var(--line);border-radius:6px;background:#0a2423f0;box-shadow:0 8px 20px var(--shadow)}.cultui-avatar-card img,.cultui-avatar-fallback{width:34px;height:34px;border:1px solid var(--line-hot);border-radius:50%;object-fit:cover;background:#010707db}.cultui-avatar-fallback{display:grid;place-items:center;color:var(--accent);font:700 12px var(--font-mono)}.cultui-avatar-name{color:var(--text-bright);font:700 11px var(--font-mono);line-height:1.15}.cultui-avatar-status,.cultui-avatar-detail{color:var(--quiet);font:700 10px var(--font-mono);line-height:1.2}.cultui-avatar-status{color:var(--accent)}.cultui-meter{display:grid;gap:4px}.cultui-meter-head{display:flex;justify-content:space-between;gap:8px;color:var(--quiet);font:700 10px var(--font-mono)}.cultui-meter-track{height:7px;overflow:hidden;border:1px solid rgba(255,255,255,.12);border-radius:7px;background:#010707e0}.cultui-meter-fill{display:block;height:100%;background:linear-gradient(90deg,#ffb84f,#8efcff)}.cultui-stream-item{border-left:2px solid var(--line-hot);padding-left:8px}.cultui-background{position:absolute;inset:0;background-size:cover;background-position:center;image-rendering:pixelated;opacity:.72}.cultui-graph{position:absolute;top:18px;left:18px;width:min(48rem,46vw);height:min(29rem,52vh);z-index:4}.cultui-placed{position:absolute;transform-origin:center}.cultui-placed[data-placement-mode=keystone],.cultui-placed[data-placement-mode=skew],.cultui-placed[data-placement-mode=sprite-chromakey]{box-shadow:0 12px 26px #00000047}.cultui-placed[data-chroma-key]{outline:1px dashed rgba(0,255,120,.45)}.cultui-node{position:absolute;transform:translate(-50%,-50%);border:2px solid var(--cyan);border-radius:999px;background:#07111ac2;color:var(--text);min-width:68px;min-height:44px;padding:8px 10px;font:700 12px Cascadia Mono,Consolas,monospace}.cultui-node.selected{border-color:var(--accent);box-shadow:0 0 0 2px #ffb84f47}.cultui-graph svg{position:absolute;inset:0;overflow:visible}.cultui-graph line{stroke:#8efcff5c;stroke-width:.006;stroke-linecap:round}.cultui-layer-embedded-surfaces{position:absolute;inset:0;z-index:5;pointer-events:none}.cultui-layer-embedded-surfaces>*{pointer-events:auto}.cultui-tex{min-width:12rem;min-height:3.2rem;border:1px solid rgba(142,252,255,.34);border-radius:6px;background:#07111ac7;color:var(--text);padding:10px 12px}.cultui-tex-label{color:var(--accent);font:700 10px Cascadia Mono,Consolas,monospace;text-transform:uppercase}.cultui-tex-source{margin-top:4px;font:700 15px "Cambria Math","STIX Two Math",Georgia,serif;white-space:pre-wrap}.cultui-layer-cards{position:absolute;top:18px;right:18px;left:calc(min(48rem,46vw) + 36px);z-index:3;display:grid;gap:10px}.cultui-dialogue{position:absolute;right:0;bottom:0;left:0;z-index:5;min-height:128px;border-right:0;border-bottom:0;border-left:0;border-radius:0;background:#05080deb}.cultui-rail-actions{position:absolute;right:18px;bottom:18px;z-index:6;display:grid;gap:8px;width:min(28rem,42vw)}.cultui-button{border:1px solid var(--line);border-radius:6px;background:#0a2423f0;color:var(--text);padding:9px 10px;text-align:left;font:700 12px Cascadia Mono,Consolas,monospace}.cultui-button:hover,.cultui-button:focus-visible{border-color:var(--line-hot);color:var(--accent)}.cultui-image-preview{display:grid;gap:8px;margin:0}.cultui-image-frame,.cultui-canvas-grid{display:grid;place-items:center;min-height:160px;border:2px solid var(--panel-border);background:repeating-linear-gradient(45deg,#f7efd80f 0 8px,#0000002e 8px 16px),linear-gradient(180deg,#07172c,#0a2039);overflow:hidden}.cultui-image-frame{aspect-ratio:1 / 1}.cultui-image-frame img{width:100%;height:100%;object-fit:cover}.cultui-image-preview figcaption,.cultui-canvas-grid{color:var(--muted);font-size:.75rem;line-height:1.25}.cultui-canvas-placeholder{display:grid;gap:8px}.cultui-canvas-placeholder.editor .cultui-canvas-grid{min-height:280px;background:linear-gradient(45deg,rgba(255,255,255,.08) 25%,transparent 25% 75%,rgba(255,255,255,.08) 75%),linear-gradient(45deg,rgba(255,255,255,.08) 25%,transparent 25% 75%,rgba(255,255,255,.08) 75%),#142033;background-position:0 0,8px 8px;background-size:16px 16px}.cultui-status-stage{display:grid;gap:8px;padding:12px;border:2px solid var(--panel-border);background:#061627eb}.cultui-field{display:grid;gap:4px}.cultui-field-value{display:block;border:2px solid var(--panel-border);background:#01040b94;padding:6px 8px}.cultui-world-scene{position:relative;z-index:2;width:100%;min-height:min(72vh,760px);overflow:hidden;outline:none;background:#02080c80}.cultui-world-scene:focus-visible{box-shadow:inset 0 0 0 2px var(--accent)}.cultui-world-heading{position:absolute;z-index:3;top:12px;left:12px;display:flex;gap:12px;align-items:baseline;color:var(--text);font-family:var(--font-mono);font-size:.75rem;pointer-events:none}.cultui-world-heading span{color:var(--quiet)}.cultui-world-plane{position:absolute;inset:0;background:linear-gradient(var(--pixel-grid) 1px,transparent 1px),linear-gradient(90deg,var(--pixel-grid) 1px,transparent 1px);background-size:48px 48px}.cultui-world-entity{position:absolute;display:grid;justify-items:center;width:34px;height:34px;padding:0;border:1px solid rgba(224,238,240,.65);border-radius:50%;color:#f1f5f4;background:#182226eb;transform:translate(-50%,-50%);cursor:pointer}.cultui-world-entity.faction-player{border-color:#54d9c7;color:#9ff8e8}.cultui-world-entity.faction-raider,.cultui-world-entity.faction-hostile{border-color:#ff695f;color:#ffaaa3}.cultui-world-entity[data-controlled=true]{box-shadow:0 0 0 3px #ffbe4866}.cultui-world-entity-glyph{align-self:center;font:700 16px/1 var(--font-mono)}.cultui-world-entity-label{position:absolute;top:38px;width:max-content;max-width:132px;overflow:hidden;color:var(--text);font:600 11px/1.2 var(--font-body);text-overflow:ellipsis;white-space:nowrap;pointer-events:none}.cultui-swatch{width:36px;min-height:36px;border:2px solid var(--accent);box-shadow:inset 0 0 0 2px #00000073}.cultui-binding-map{position:relative;min-height:510px;border:1px solid var(--line);border-radius:6px;background:linear-gradient(var(--pixel-grid) 1px,transparent 1px),linear-gradient(90deg,var(--pixel-grid) 1px,transparent 1px),#030f11eb;background-size:28px 28px;overflow:hidden}.cultui-xbox-controller{position:absolute;inset:18px;width:calc(100% - 36px);height:calc(100% - 36px)}.cultui-xbox-controller .shell,.cultui-xbox-controller .stick,.cultui-xbox-controller .dpad,.cultui-xbox-controller .face,.cultui-xbox-controller .menu,.cultui-xbox-controller .guide,.cultui-xbox-controller .bumper,.cultui-xbox-controller .trigger{fill:#0a2423f0;stroke:var(--line);stroke-width:3}.cultui-xbox-controller .stick-dot,.cultui-xbox-controller .guide{fill:#8efcff1f}.cultui-xbox-controller .face{fill:#ffb84f29}.cultui-xbox-controller text{fill:var(--text);font:700 16px var(--font-mono);text-anchor:middle}.cultui-binding-line{stroke:var(--accent);stroke-width:2;stroke-dasharray:5 6;opacity:.78}.cultui-binding-overlay{position:absolute;inset:0}.cultui-binding-box{position:absolute;width:clamp(112px,12vw,138px);min-height:50px;transform:translate(-50%,-50%);display:grid;gap:4px;border:1px solid var(--line-hot);border-radius:6px;background:#071918f5;color:var(--text);padding:8px;text-align:left;box-shadow:0 10px 20px var(--shadow)}.cultui-binding-box:hover,.cultui-binding-box:focus-visible{border-color:var(--accent);color:var(--accent)}.cultui-binding-target{font:700 11px var(--font-mono);text-transform:uppercase}.cultui-binding-source{color:var(--quiet);font:600 11px var(--font-mono);overflow-wrap:anywhere}.cultui-modal-backdrop{position:fixed;inset:0;z-index:1000;display:grid;place-items:center;background:#00000094;padding:20px}.cultui-modal{width:min(680px,96vw);max-height:min(780px,92vh);display:grid;grid-template-rows:auto minmax(0,1fr);border:1px solid var(--line-hot);border-radius:6px;background:var(--panel);box-shadow:0 18px 42px #00000085;overflow:hidden}.cultui-modal-header{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:12px 14px;border-bottom:1px solid var(--line);background:var(--shell-top)}.cultui-modal-header h2{margin:0;color:var(--accent);font:700 13px var(--font-mono);text-transform:uppercase}.cultui-modal-close{border:1px solid var(--line);border-radius:6px;background:var(--panel-2);color:var(--text);padding:7px 10px;font:700 11px var(--font-mono)}.cultui-modal-body{min-height:0;overflow:auto;padding:14px}@media(max-width:900px){.cultui-graph{right:12px;left:12px;width:auto;height:min(18rem,34vh)}.cultui-layer-cards{top:calc(30px + min(18rem,34vh));right:12px;left:12px}.cultui-rail-actions{left:12px;width:auto}}:root{color-scheme:dark;font-family:Crimson Pro,serif;background:#0c1110;color:#e8e1cf}body{margin:0;min-height:100vh;background:radial-gradient(circle at 15% 0,#253229 0,transparent 38rem),linear-gradient(145deg,#0c1110,#111513)}header,main{width:min(920px,calc(100% - 2rem));margin:auto}header{padding:3rem 0 1.25rem;border-bottom:1px solid #66543d}h1{font-size:clamp(2.6rem,8vw,5.5rem);font-weight:400;letter-spacing:-.045em;margin:.1rem 0}.eyebrow,#status,label,button,pre{font-family:IBM Plex Mono,monospace}.eyebrow{color:#d49b58;letter-spacing:.18em;font-size:.72rem}#status{color:#9aa69f;font-size:.78rem}main{padding:1.5rem 0 5rem}#surface{min-height:15rem}form,.card{margin-top:1.5rem;padding:1rem;border:1px solid #66543d;background:#17201ddd}label{display:block;font-size:.72rem;text-transform:uppercase;letter-spacing:.12em;margin-bottom:.65rem}textarea,input{box-sizing:border-box;width:100%;resize:vertical;background:#0b0f0d;color:#f2e7d0;border:1px solid #4a5148;padding:.9rem;margin:.35rem 0;font:1.05rem/1.4 Crimson Pro,serif}textarea{min-height:7rem}button{margin:.8rem .5rem 0 0;padding:.65rem 1rem;border:1px solid #d49b58;background:#d49b58;color:#17120c;cursor:pointer}button+button{background:transparent;color:#d49b58}pre{white-space:pre-wrap;padding:1rem;background:#080b09;color:#aeb9af;overflow:auto;font-size:.72rem}.compiler-grid{display:grid;grid-template-columns:1fr 1fr;gap:1rem}.cards{display:grid;gap:.7rem}.card h3{margin:.1rem 0}.card p{color:#b9c0b7}.warning{color:#e4a86a!important}@media(max-width:700px){.compiler-grid{grid-template-columns:1fr}}@media(max-width:600px){header{padding-top:2rem}h1{font-size:3rem}} +@import"https://fonts.googleapis.com/css2?family=M+PLUS+1:wght@100;300;400;500;700&family=Montserrat:wght@100;300;400;500;700&family=Ubuntu+Sans:wght@300;400;500;700&family=Zen+Kaku+Gothic+New:wght@300;400;500;700&display=swap";@import"https://fonts.googleapis.com/css2?family=Crimson+Pro:opsz,wght@8..144,400;8..144,600&family=IBM+Plex+Mono:wght@400;600&display=swap";:root{color-scheme:dark;--bg: #020909;--bg-top: var(--bg);--bg-mid: var(--bg);--bg-bottom: var(--bg);--shell-top: #010707;--shell-bottom: #010707;--panel: #071918;--panel-2: #0a2423;--line: rgba(103, 240, 228, .28);--line-deep: rgba(103, 240, 228, .18);--line-hot: rgba(142, 252, 255, .72);--text: #e7f1f1;--text-bright: var(--text);--quiet: #8ba5a3;--accent: #ffb84f;--accent-strong: var(--accent);--corner-accent: var(--accent);--cyan: #8efcff;--shadow: rgba(0, 0, 0, .35);--pixel-grid: rgba(142, 252, 255, .04);--border-width: 1px;--border-bottom-width: var(--border-width);--corner-accent-size: 0;--font-body: "M PLUS 1", "Ubuntu Sans", Ubuntu, "Noto Sans JP", system-ui, sans-serif;--font-title: "Montserrat", "Zen Kaku Gothic New", "M PLUS 1", "Ubuntu Sans", system-ui, sans-serif;--font-mono: "Ubuntu Sans Mono", "M PLUS 1 Code", "Cascadia Mono", Consolas, monospace}*{box-sizing:border-box}body{margin:0;min-height:100vh;background:linear-gradient(180deg,var(--bg-top),var(--bg-mid),var(--bg-bottom));color:var(--text);font-family:var(--font-body)}.topbar{height:84px;display:flex;justify-content:space-between;align-items:center;padding:10px 16px;border-bottom:1px solid var(--line);background:linear-gradient(180deg,var(--shell-top),var(--shell-bottom))}h1{margin:0;font-size:20px;letter-spacing:0}p{margin:4px 0 0;color:var(--quiet);font-size:13px}.hud{min-width:168px;padding:8px;border:1px solid var(--line-hot);border-radius:6px;background:#071918e0;color:var(--accent);font-family:Cascadia Mono,Consolas,monospace;font-size:11px;display:grid;gap:2px}.provider-bar{display:flex;align-items:center;gap:8px;padding:10px 16px;border-bottom:1px solid var(--line-deep);background:color-mix(in srgb,var(--panel) 70%,transparent)}.provider-bar label{color:var(--quiet);font:700 11px var(--font-mono);text-transform:uppercase}.provider-bar select{border:1px solid var(--line);border-radius:6px;background:var(--panel);color:var(--text);padding:8px 12px;font:700 13px var(--font-mono);min-width:min(28rem,52vw)}.provider-meta{color:var(--quiet);font:600 11px var(--font-mono);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.surface{padding:10px 16px 16px}.cockpit{display:grid;grid-template-columns:.78fr 1.08fr 1.34fr;gap:10px;min-height:calc(100vh - 138px)}.ctb{grid-column:1 / -1;min-height:88px;overflow-x:auto;display:flex;gap:8px;padding-bottom:8px}.pane{min-height:0;border:1px solid var(--line);border-radius:6px;background:#071918eb;padding:12px;box-shadow:0 12px 26px var(--shadow)}.pane h2{margin:0 0 10px;color:var(--quiet);font-size:12px;font-weight:500;text-transform:uppercase}.card{border:1px solid var(--line);border-radius:6px;background:#0a2423f5;padding:10px;box-shadow:0 8px 20px var(--shadow)}.cultui-card[data-command-id]{cursor:pointer;border-bottom-width:var(--border-bottom-width)}.cultui-card-button{display:block;width:100%;color:inherit;font:inherit;text-align:left}.ctb .card{flex:0 0 96px;min-height:76px;padding:6px}.avatar{width:34px;height:34px;border-radius:50%;border:1px solid var(--line-hot);object-fit:cover;background:#123}.card-title{white-space:pre-line;margin-top:4px;font:700 11px var(--font-mono)}.health{color:var(--accent);font:700 10px var(--font-mono)}.detail{white-space:pre-wrap;font:600 12px var(--font-mono);line-height:1.45}.list{display:grid;gap:8px}.metrics{display:grid;gap:9px;margin:12px 0}.metric label{display:flex;justify-content:space-between;color:var(--quiet);font:700 10px var(--font-mono)}.bar{height:7px;border-radius:7px;background:#010707;border:1px solid rgba(255,255,255,.12);overflow:hidden}.bar span{display:block;height:100%;background:linear-gradient(90deg,#bca8ff,#8efcff)}.graph{position:relative;min-height:calc(100vh - 166px);border:1px solid var(--line);border-radius:6px;background:linear-gradient(var(--pixel-grid) 1px,transparent 1px),linear-gradient(90deg,var(--pixel-grid) 1px,transparent 1px),#030f11f0;background-size:44px 44px}.node{position:absolute;transform:translate(-50%,-50%);border:1px solid var(--line);border-radius:7px;background:#0a2423f2;padding:10px;overflow:hidden}.node.selected{border-color:var(--line-hot);box-shadow:0 0 0 1px #8efcff61}.node .detail{margin-top:6px;color:var(--quiet);font-size:10px}@media(max-width:900px){.cockpit{grid-template-columns:1fr}}.cultui-vn-stage{position:relative;min-height:calc(100vh - 138px);overflow:hidden;border:1px solid var(--line);border-radius:6px;background:var(--bg)}.cultui-grid{min-height:calc(100vh - 138px);display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:10px;align-content:start}.cultui-surface-root{min-height:calc(100vh - 150px);display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:12px;align-content:start}.cultui-surface-root[data-direction=vertical]{grid-template-columns:minmax(0,1fr)}.cultui-surface-root[data-direction=horizontal]{grid-template-columns:repeat(auto-fit,minmax(260px,1fr))}.cultui-embedded-slot .cultui-surface-root{min-height:0;grid-template-columns:minmax(0,1fr)}@media(max-width:900px){.cultui-pane[data-span=wide]{grid-column:1 / -1}}.cultui-pane{border-width:var(--border-width);border-bottom-width:var(--border-bottom-width);min-width:0}.cultui-pane[data-span=wide]{grid-column:span 2}.cultui-pane .cultui-pane{box-shadow:none;background:#030f1161}.cultui-pane[data-density=compact]{padding:8px}.cultui-pane[data-density=compact] h2{margin-bottom:6px}.cultui-partition{min-width:0;min-height:0;display:flex;gap:10px}.cultui-partition[data-direction=horizontal]{flex-direction:row}.cultui-partition[data-direction=vertical]{flex-direction:column}.cultui-partition[data-overflow=x]{overflow-x:auto;padding-bottom:4px}.cultui-partition.split-x{flex-direction:row}.cultui-partition.split-y,.cultui-partition.split-none{flex-direction:column}.cultui-partition.split-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr))}.cultui-partition[data-role="inspector.row"]{min-height:34px;border:1px solid rgba(255,255,255,.06);border-radius:4px;background:linear-gradient(180deg,#201f2bf5,#13141df5);box-shadow:inset 0 1px #ffffff0d,0 2px 8px #0006}.cultui-partition[data-role="inspector.label"]{justify-content:center}.cultui-label{color:var(--accent);font:700 13px var(--font-mono);line-height:1.15;text-transform:uppercase}.cultui-slider{--cultui-slider-value: 0%;--part-bleed: 0px;position:relative;display:grid;align-items:center;width:100%;min-height:18px;overflow:visible}.cultui-slider-visual{position:absolute;inset:0;overflow:visible;pointer-events:none}.cultui-slider-input{position:absolute;inset:0;opacity:0;cursor:pointer}.cultui-slider-part{position:absolute;top:50%;display:block;transform:translateY(-50%)}.cultui-slider-part.track{right:0;left:0;height:6px;border-radius:2px;background:#00000057}.cultui-slider-part.fill{left:0;width:var(--cultui-slider-value);height:6px;border-radius:2px;background:var(--accent)}.cultui-slider-part.thumb{left:var(--cultui-slider-value);width:12px;height:12px;border-radius:999px;background:var(--accent);transform:translate(-50%,-50%);box-shadow:0 0 7px color-mix(in srgb,var(--accent) 45%,transparent)}.cultui-slider-part[data-anchor-value=true]{left:var(--cultui-slider-value);transform:translate(-50%,-50%)}@media(max-width:520px){.cultui-partition[data-role="inspector.row"]{flex-direction:column;align-items:stretch}.cultui-partition[data-role="inspector.label"]{flex:0 0 auto!important}}body[data-provider=repixelizer] .surface{position:relative}body[data-provider=repixelizer] .surface:after{content:"";pointer-events:none;position:fixed;inset:0;background:repeating-linear-gradient(0deg,rgba(255,255,255,.035) 0 1px,transparent 1px 4px);opacity:.28;mix-blend-mode:screen}body[data-pixel-art=true] img,body[data-pixel-art=true] .cultui-background{image-rendering:pixelated}.cultui-title{color:var(--accent);font:100 18px var(--font-title);line-height:1.35}.mono{color:var(--accent);font-family:var(--font-mono)}.cultui-reactive-metric{margin-top:8px}.cultui-reactive-list{display:grid;gap:8px}.cultui-list{display:grid;gap:8px;min-width:0}.cultui-list-title{margin:0;color:var(--quiet);font:700 10px var(--font-mono);letter-spacing:0;text-transform:uppercase}.cultui-list-item{display:grid;gap:5px;min-width:0;padding:8px;border:1px solid var(--line);border-radius:6px;background:var(--panel)}.cultui-list-item-heading,.cultui-list-item-badges{display:flex;gap:6px;align-items:center;flex-wrap:wrap;min-width:0}.cultui-list-item-label{min-width:0;overflow-wrap:anywhere}.cultui-list-item-status,.cultui-list-item-badge{padding:2px 5px;border:1px solid var(--line-hot);border-radius:4px;color:var(--quiet);font:600 10px var(--font-mono)}.cultui-list-item-detail{color:var(--quiet);font-size:12px;overflow-wrap:anywhere}.cultui-avatar-card{flex:0 0 104px;display:grid;gap:4px;align-content:start;min-height:92px;margin:0;padding:8px;border:1px solid var(--line);border-radius:6px;background:#0a2423f0;box-shadow:0 8px 20px var(--shadow)}.cultui-avatar-card img,.cultui-avatar-fallback{width:34px;height:34px;border:1px solid var(--line-hot);border-radius:50%;object-fit:cover;background:#010707db}.cultui-avatar-fallback{display:grid;place-items:center;color:var(--accent);font:700 12px var(--font-mono)}.cultui-avatar-name{color:var(--text-bright);font:700 11px var(--font-mono);line-height:1.15}.cultui-avatar-status,.cultui-avatar-detail{color:var(--quiet);font:700 10px var(--font-mono);line-height:1.2}.cultui-avatar-status{color:var(--accent)}.cultui-meter{display:grid;gap:4px}.cultui-meter-head{display:flex;justify-content:space-between;gap:8px;color:var(--quiet);font:700 10px var(--font-mono)}.cultui-meter-track{height:7px;overflow:hidden;border:1px solid rgba(255,255,255,.12);border-radius:7px;background:#010707e0}.cultui-meter-fill{display:block;height:100%;background:linear-gradient(90deg,#ffb84f,#8efcff)}.cultui-stream-item{border-left:2px solid var(--line-hot);padding-left:8px}.cultui-background{position:absolute;inset:0;background-size:cover;background-position:center;image-rendering:pixelated;opacity:.72}.cultui-graph{position:absolute;top:18px;left:18px;width:min(48rem,46vw);height:min(29rem,52vh);z-index:4}.cultui-placed{position:absolute;transform-origin:center}.cultui-placed[data-placement-mode=keystone],.cultui-placed[data-placement-mode=skew],.cultui-placed[data-placement-mode=sprite-chromakey]{box-shadow:0 12px 26px #00000047}.cultui-placed[data-chroma-key]{outline:1px dashed rgba(0,255,120,.45)}.cultui-node{position:absolute;transform:translate(-50%,-50%);border:2px solid var(--cyan);border-radius:999px;background:#07111ac2;color:var(--text);min-width:68px;min-height:44px;padding:8px 10px;font:700 12px Cascadia Mono,Consolas,monospace}.cultui-node.selected{border-color:var(--accent);box-shadow:0 0 0 2px #ffb84f47}.cultui-graph svg{position:absolute;inset:0;overflow:visible}.cultui-graph line{stroke:#8efcff5c;stroke-width:.006;stroke-linecap:round}.cultui-layer-embedded-surfaces{position:absolute;inset:0;z-index:5;pointer-events:none}.cultui-layer-embedded-surfaces>*{pointer-events:auto}.cultui-tex{min-width:12rem;min-height:3.2rem;border:1px solid rgba(142,252,255,.34);border-radius:6px;background:#07111ac7;color:var(--text);padding:10px 12px}.cultui-tex-label{color:var(--accent);font:700 10px Cascadia Mono,Consolas,monospace;text-transform:uppercase}.cultui-tex-source{margin-top:4px;font:700 15px "Cambria Math","STIX Two Math",Georgia,serif;white-space:pre-wrap}.cultui-layer-cards{position:absolute;top:18px;right:18px;left:calc(min(48rem,46vw) + 36px);z-index:3;display:grid;gap:10px}.cultui-dialogue{position:absolute;right:0;bottom:0;left:0;z-index:5;min-height:128px;border-right:0;border-bottom:0;border-left:0;border-radius:0;background:#05080deb}.cultui-rail-actions{position:absolute;right:18px;bottom:18px;z-index:6;display:grid;gap:8px;width:min(28rem,42vw)}.cultui-button{border:1px solid var(--line);border-radius:6px;background:#0a2423f0;color:var(--text);padding:9px 10px;text-align:left;font:700 12px Cascadia Mono,Consolas,monospace}.cultui-button:hover,.cultui-button:focus-visible{border-color:var(--line-hot);color:var(--accent)}.cultui-image-preview{display:grid;gap:8px;margin:0}.cultui-image-frame,.cultui-canvas-grid{display:grid;place-items:center;min-height:160px;border:2px solid var(--panel-border);background:repeating-linear-gradient(45deg,#f7efd80f 0 8px,#0000002e 8px 16px),linear-gradient(180deg,#07172c,#0a2039);overflow:hidden}.cultui-image-frame{aspect-ratio:1 / 1}.cultui-image-frame img{width:100%;height:100%;object-fit:cover}.cultui-image-preview figcaption,.cultui-canvas-grid{color:var(--muted);font-size:.75rem;line-height:1.25}.cultui-canvas-placeholder{display:grid;gap:8px}.cultui-canvas-placeholder.editor .cultui-canvas-grid{min-height:280px;background:linear-gradient(45deg,rgba(255,255,255,.08) 25%,transparent 25% 75%,rgba(255,255,255,.08) 75%),linear-gradient(45deg,rgba(255,255,255,.08) 25%,transparent 25% 75%,rgba(255,255,255,.08) 75%),#142033;background-position:0 0,8px 8px;background-size:16px 16px}.cultui-status-stage{display:grid;gap:8px;padding:12px;border:2px solid var(--panel-border);background:#061627eb}.cultui-field{display:grid;gap:4px}.cultui-field-value{display:block;border:2px solid var(--panel-border);background:#01040b94;padding:6px 8px}.cultui-world-scene{position:relative;z-index:2;width:100%;min-height:min(72vh,760px);overflow:hidden;outline:none;background:#02080c80}.cultui-world-scene:focus-visible{box-shadow:inset 0 0 0 2px var(--accent)}.cultui-world-heading{position:absolute;z-index:3;top:12px;left:12px;display:flex;gap:12px;align-items:baseline;color:var(--text);font-family:var(--font-mono);font-size:.75rem;pointer-events:none}.cultui-world-heading span{color:var(--quiet)}.cultui-world-plane{position:absolute;inset:0;background:linear-gradient(var(--pixel-grid) 1px,transparent 1px),linear-gradient(90deg,var(--pixel-grid) 1px,transparent 1px);background-size:48px 48px}.cultui-world-entity{position:absolute;display:grid;justify-items:center;width:34px;height:34px;padding:0;border:1px solid rgba(224,238,240,.65);border-radius:50%;color:#f1f5f4;background:#182226eb;transform:translate(-50%,-50%);cursor:pointer}.cultui-world-entity.faction-player{border-color:#54d9c7;color:#9ff8e8}.cultui-world-entity.faction-raider,.cultui-world-entity.faction-hostile{border-color:#ff695f;color:#ffaaa3}.cultui-world-entity[data-controlled=true]{box-shadow:0 0 0 3px #ffbe4866}.cultui-world-entity-glyph{align-self:center;font:700 16px/1 var(--font-mono)}.cultui-world-entity-label{position:absolute;top:38px;width:max-content;max-width:132px;overflow:hidden;color:var(--text);font:600 11px/1.2 var(--font-body);text-overflow:ellipsis;white-space:nowrap;pointer-events:none}.cultui-swatch{width:36px;min-height:36px;border:2px solid var(--accent);box-shadow:inset 0 0 0 2px #00000073}.cultui-binding-map{position:relative;min-height:510px;border:1px solid var(--line);border-radius:6px;background:linear-gradient(var(--pixel-grid) 1px,transparent 1px),linear-gradient(90deg,var(--pixel-grid) 1px,transparent 1px),#030f11eb;background-size:28px 28px;overflow:hidden}.cultui-xbox-controller{position:absolute;inset:18px;width:calc(100% - 36px);height:calc(100% - 36px)}.cultui-xbox-controller .shell,.cultui-xbox-controller .stick,.cultui-xbox-controller .dpad,.cultui-xbox-controller .face,.cultui-xbox-controller .menu,.cultui-xbox-controller .guide,.cultui-xbox-controller .bumper,.cultui-xbox-controller .trigger{fill:#0a2423f0;stroke:var(--line);stroke-width:3}.cultui-xbox-controller .stick-dot,.cultui-xbox-controller .guide{fill:#8efcff1f}.cultui-xbox-controller .face{fill:#ffb84f29}.cultui-xbox-controller text{fill:var(--text);font:700 16px var(--font-mono);text-anchor:middle}.cultui-binding-line{stroke:var(--accent);stroke-width:2;stroke-dasharray:5 6;opacity:.78}.cultui-binding-overlay{position:absolute;inset:0}.cultui-binding-box{position:absolute;width:clamp(112px,12vw,138px);min-height:50px;transform:translate(-50%,-50%);display:grid;gap:4px;border:1px solid var(--line-hot);border-radius:6px;background:#071918f5;color:var(--text);padding:8px;text-align:left;box-shadow:0 10px 20px var(--shadow)}.cultui-binding-box:hover,.cultui-binding-box:focus-visible{border-color:var(--accent);color:var(--accent)}.cultui-binding-target{font:700 11px var(--font-mono);text-transform:uppercase}.cultui-binding-source{color:var(--quiet);font:600 11px var(--font-mono);overflow-wrap:anywhere}.cultui-modal-backdrop{position:fixed;inset:0;z-index:1000;display:grid;place-items:center;background:#00000094;padding:20px}.cultui-modal{width:min(680px,96vw);max-height:min(780px,92vh);display:grid;grid-template-rows:auto minmax(0,1fr);border:1px solid var(--line-hot);border-radius:6px;background:var(--panel);box-shadow:0 18px 42px #00000085;overflow:hidden}.cultui-modal-header{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:12px 14px;border-bottom:1px solid var(--line);background:var(--shell-top)}.cultui-modal-header h2{margin:0;color:var(--accent);font:700 13px var(--font-mono);text-transform:uppercase}.cultui-modal-close{border:1px solid var(--line);border-radius:6px;background:var(--panel-2);color:var(--text);padding:7px 10px;font:700 11px var(--font-mono)}.cultui-modal-body{min-height:0;overflow:auto;padding:14px}@media(max-width:900px){.cultui-graph{right:12px;left:12px;width:auto;height:min(18rem,34vh)}.cultui-layer-cards{top:calc(30px + min(18rem,34vh));right:12px;left:12px}.cultui-rail-actions{left:12px;width:auto}}:root{color-scheme:dark;font-family:Crimson Pro,serif;background:#0c1110;color:#e8e1cf}body{margin:0;min-height:100vh;background:radial-gradient(circle at 15% 0,#253229 0,transparent 38rem),linear-gradient(145deg,#0c1110,#111513)}header,main{width:min(920px,calc(100% - 2rem));margin:auto}header{padding:3rem 0 1.25rem;border-bottom:1px solid #66543d}h1{font-size:clamp(2.6rem,8vw,5.5rem);font-weight:400;letter-spacing:-.045em;margin:.1rem 0}.eyebrow,#status,label,button,pre{font-family:IBM Plex Mono,monospace}.eyebrow{color:#d49b58;letter-spacing:.18em;font-size:.72rem}#status{color:#9aa69f;font-size:.78rem}main{padding:1.5rem 0 5rem}#surface{min-height:15rem}form,.card{margin-top:1.5rem;padding:1rem;border:1px solid #66543d;background:#17201ddd}label{display:block;font-size:.72rem;text-transform:uppercase;letter-spacing:.12em;margin-bottom:.65rem}textarea,input,select{box-sizing:border-box;width:100%;resize:vertical;background:#0b0f0d;color:#f2e7d0;border:1px solid #4a5148;padding:.9rem;margin:.35rem 0;font:1.05rem/1.4 Crimson Pro,serif}input[type=range]{padding:.25rem;accent-color:#d49b58}textarea{min-height:7rem}button{margin:.8rem .5rem 0 0;padding:.65rem 1rem;border:1px solid #d49b58;background:#d49b58;color:#17120c;cursor:pointer}button+button{background:transparent;color:#d49b58}pre{white-space:pre-wrap;padding:1rem;background:#080b09;color:#aeb9af;overflow:auto;font-size:.72rem}.compiler-grid{display:grid;grid-template-columns:1fr 1fr;gap:1rem}.cards{display:grid;gap:.7rem}.card h3{margin:.1rem 0}.card p{color:#b9c0b7}.warning{color:#e4a86a!important}code{font-family:IBM Plex Mono,monospace;color:#d49b58}@media(max-width:700px){.compiler-grid{grid-template-columns:1fr}}@media(max-width:600px){header{padding-top:2rem}h1{font-size:3rem}} diff --git a/web/dist/assets/index-DlJlHpS2.js b/web/dist/assets/index-DlJlHpS2.js new file mode 100644 index 0000000..757c0fc --- /dev/null +++ b/web/dist/assets/index-DlJlHpS2.js @@ -0,0 +1,153 @@ +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))i(a);new MutationObserver(a=>{for(const c of a)if(c.type==="childList")for(const s of c.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&i(s)}).observe(document,{childList:!0,subtree:!0});function n(a){const c={};return a.integrity&&(c.integrity=a.integrity),a.referrerPolicy&&(c.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?c.credentials="include":a.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function i(a){if(a.ep)return;a.ep=!0;const c=n(a);fetch(a.href,c)}})();const G=new WeakMap,Se=20;function lt(e,t,n,i,a,c,s,l){const f=mt(e.canvas);if(!f)return!1;const o=f.gl;if(!pt(f,c,s))return G.set(e.canvas,null),!1;const r=dt(t,n,i,a,l);o.bindFramebuffer(o.FRAMEBUFFER,f.framebuffer),o.viewport(0,0,c,s),o.disable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.enable(o.BLEND),o.blendFunc(o.ONE,o.ONE),o.clearColor(0,0,0,1),o.clear(o.COLOR_BUFFER_BIT),r.gravity.length>0&&(o.useProgram(f.splatProgram),o.uniform4f(o.getUniformLocation(f.splatProgram,"u_viewport"),a.minX,a.minY,a.maxX,a.maxY),o.uniform1f(o.getUniformLocation(f.splatProgram,"u_time"),A(t.simulationTimeSeconds,0)),o.bindBuffer(o.ARRAY_BUFFER,f.splatBuffer),o.bufferData(o.ARRAY_BUFFER,r.gravity,o.DYNAMIC_DRAW),De(o,f.splatProgram),o.drawArrays(o.TRIANGLES,0,r.gravity.length/Se)),o.bindFramebuffer(o.FRAMEBUFFER,f.tintFramebuffer),o.clearColor(0,0,0,0),o.clear(o.COLOR_BUFFER_BIT),r.tint.length>0&&(o.useProgram(f.splatProgram),o.uniform4f(o.getUniformLocation(f.splatProgram,"u_viewport"),a.minX,a.minY,a.maxX,a.maxY),o.uniform1f(o.getUniformLocation(f.splatProgram,"u_time"),A(t.simulationTimeSeconds,0)),o.bindBuffer(o.ARRAY_BUFFER,f.splatBuffer),o.bufferData(o.ARRAY_BUFFER,r.tint,o.DYNAMIC_DRAW),De(o,f.splatProgram),o.drawArrays(o.TRIANGLES,0,r.tint.length/Se)),o.disable(o.BLEND),o.bindFramebuffer(o.FRAMEBUFFER,null),o.viewport(0,0,c,s),o.useProgram(f.shadeProgram),o.activeTexture(o.TEXTURE0),o.bindTexture(o.TEXTURE_2D,f.fieldTexture),o.uniform1i(o.getUniformLocation(f.shadeProgram,"u_field"),0),o.activeTexture(o.TEXTURE1),o.bindTexture(o.TEXTURE_2D,f.tintTexture),o.uniform1i(o.getUniformLocation(f.shadeProgram,"u_tint"),1),o.uniform2f(o.getUniformLocation(f.shadeProgram,"u_resolution"),c,s),o.uniform1f(o.getUniformLocation(f.shadeProgram,"u_time"),A(n.simulationTimeSeconds,A(t.simulationTimeSeconds,0))),o.uniform1f(o.getUniformLocation(f.shadeProgram,"u_lineInterval"),A(t.lineInterval,A(t.scalarFieldLineInterval,A(t.depthRange,228.79605)/20))),o.uniform1f(o.getUniformLocation(f.shadeProgram,"u_lineOffset"),A(t.lineOffset,A(t.startDepth,2.310401))),o.uniform1f(o.getUniformLocation(f.shadeProgram,"u_lineWidth"),A(t.lineWidth,.3)),o.uniform1f(o.getUniformLocation(f.shadeProgram,"u_lineFade"),A(t.lineFade,5)),o.uniform1f(o.getUniformLocation(f.shadeProgram,"u_angleWidth"),A(t.angleWidth,.05)),o.uniform1f(o.getUniformLocation(f.shadeProgram,"u_angleFade"),A(t.angleFade,1.15)),o.uniform1f(o.getUniformLocation(f.shadeProgram,"u_dangerSteepness"),A(t.dangerSteepness,1.5)),o.uniform1f(o.getUniformLocation(f.shadeProgram,"u_scale"),A(t.isolineScale,2.6924083)),te(o,f.shadeProgram,"u_baseColor",ee(t.scalarFieldBaseColor,[.002,.006,.012])),te(o,f.shadeProgram,"u_fieldGlowColor",ee(t.scalarFieldGlowColor,[.018,.05,.075])),te(o,f.shadeProgram,"u_lineLowColor",ee(t.scalarFieldLowLineColor,[0,.34,.52])),te(o,f.shadeProgram,"u_lineHighColor",ee(t.scalarFieldHighLineColor,[1.45,.3,.05])),te(o,f.shadeProgram,"u_angleLowColor",ee(t.scalarFieldLowAngleColor,[.06,.16,.24])),te(o,f.shadeProgram,"u_angleHighColor",ee(t.scalarFieldHighAngleColor,[1.1,.24,.04])),o.uniform1f(o.getUniformLocation(f.shadeProgram,"u_tintScale"),A(t.vectorFieldTintScale,.45)),o.bindBuffer(o.ARRAY_BUFFER,f.quadBuffer);const d=o.getAttribLocation(f.shadeProgram,"a_position");return o.enableVertexAttribArray(d),o.vertexAttribPointer(d,2,o.FLOAT,!1,0,0),o.drawArrays(o.TRIANGLES,0,6),e.drawImage(f.canvas,0,0,c,s),!0}function dt(e,t,n,i,a){const c=[],s=[];return ut(c,e,t,n),ft(s,e,a),{gravity:new Float32Array(c),tint:new Float32Array(s)}}function ut(e,t,n,i,a){const c=A(n.terrainRadius,A(t.terrainRadius,1200)),s=A(n.terrainDepth,A(t.terrainDepth,-8));s!==0&&me(e,0,0,Math.max(1,c*2),Math.max(1,c*2),-s,0,0,1,Math.max(1e-4,A(n.terrainDepthExponent,A(t.terrainDepthExponent,1.2))),0,1,0,0);for(const l of i)me(e,l.x,l.y,Math.max(1,l.radius),Math.max(1,l.radius),-l.depth,0,0,1,Math.max(1e-4,l.exponent),0,1,0,0),l.waveRadius>0&&l.waveDepth!==0&&me(e,l.x,l.y,l.waveRadius,l.waveRadius,-l.waveDepth,0,0,1,8,4,A(n.terrainWaveFrequency,A(t.terrainWaveFrequency,.6)),l.waveSpeed,0)}function ft(e,t,n){const i=gt(n?.splats),a=Array.isArray(n?.layers)?n.layers:[],c=new Set,s=yt(t.vectorFieldLayer,t.tintFieldLayer,"fog.tint");a.forEach((I,Q)=>{const ce=ht(I?.layerKey,"");A(I?.channel,-1)===4&&ce===s&&c.add(Q)});const l=Math.max(0,bt(i.count,0));if(l<=0||c.size===0)return;const f=F(i.centerX),o=F(i.centerY),r=F(i.halfExtentX),d=F(i.halfExtentY),u=F(i.rotationCos),g=F(i.rotationSin),y=F(i.channel),b=F(i.falloff),v=F(i.valueR),C=F(i.valueG),E=F(i.valueB),D=F(i.valueA),V=F(i.sourceKind),W=F(i.frequencyX),J=F(i.animationSpeed),Z=F(i.sourceFlags),z=F(i.layerIndex);for(let I=0;INumber(i));if(n.length>=3&&n.slice(0,3).every(Number.isFinite))return[n[0],n[1],n[2]]}if(typeof e=="string"){const n=e.split(/[,\s]+/).map(i=>Number(i)).filter(Number.isFinite);if(n.length>=3)return[n[0],n[1],n[2]]}return t}function te(e,t,n,i){e.uniform3f(e.getUniformLocation(t,n),i[0],i[1],i[2])}function F(e){return Array.isArray(e)?e.map(t=>A(t,0)):[]}function gt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function ht(e,t){return e==null?t:String(e)}function yt(...e){for(const t of e){if(typeof t=="string"&&t.trim())return t;if(typeof t=="number"&&Number.isFinite(t))return String(t)}return""}function bt(e,t){const n=Number(e);return Number.isFinite(n)?Math.max(0,Math.floor(n)):t}const vt=`#version 300 es +in vec2 a_corner; +in vec2 a_center; +in vec2 a_half; +in vec2 a_rot; +in vec4 a_meta; +in vec4 a_source; +in vec4 a_value; +uniform vec4 u_viewport; +out vec2 v_local; +out vec4 v_meta; +out vec4 v_source; +out vec4 v_value; +void main() { + vec2 scaled = a_corner * a_half; + vec2 world = a_center + vec2( + scaled.x * a_rot.x - scaled.y * a_rot.y, + scaled.x * a_rot.y + scaled.y * a_rot.x + ); + vec2 clip = vec2( + ((world.x - u_viewport.x) / max(0.0001, u_viewport.z - u_viewport.x)) * 2.0 - 1.0, + ((world.y - u_viewport.y) / max(0.0001, u_viewport.w - u_viewport.y)) * 2.0 - 1.0 + ); + gl_Position = vec4(clip, 0.0, 1.0); + v_local = a_corner; + v_meta = a_meta; + v_source = a_source; + v_value = a_value; +}`,xt=`#version 300 es +precision highp float; +in vec2 v_local; +in vec4 v_meta; +in vec4 v_source; +in vec4 v_value; +uniform float u_time; +out vec4 outColor; +float hash21(vec2 p) { + p = fract(p * vec2(123.34, 456.21)); + p += dot(p, p + 45.32); + return fract(p.x * p.y); +} +float valueNoise(vec2 p) { + vec2 i = floor(p); + vec2 f = fract(p); + float a = hash21(i); + float b = hash21(i + vec2(1.0, 0.0)); + float c = hash21(i + vec2(0.0, 1.0)); + float d = hash21(i + vec2(1.0, 1.0)); + vec2 u = f * f * (3.0 - 2.0 * f); + return mix(mix(a, b, u.x), mix(c, d, u.x), u.y) * 2.0 - 1.0; +} +float powerPulse(float x, float power) { + x = clamp(abs(x), 0.0, 1.0); + return pow((x + 1.0) * (1.0 - x), max(0.0001, power)); +} +void main() { + float d = length(v_local); + if (d > 1.0) discard; + float alpha = powerPulse(d, v_meta.x); + if (alpha <= 0.0001) discard; + float source = 1.0; + if (v_source.x > 0.5 && v_source.x < 2.5) { + float timeOffset = v_source.x > 1.5 ? u_time * v_source.z : 0.0; + source = valueNoise(v_local * v_source.y + timeOffset); + if (v_source.w != 0.0) source = abs(source); + } else if (v_source.x > 3.5) { + source = cos(pow(d * 2.0, 1.25) * v_source.y + u_time * v_source.z); + } + outColor = v_value * alpha * source; +}`,wt=`#version 300 es +in vec2 a_position; +out vec2 v_uv; +void main() { + v_uv = a_position * 0.5 + 0.5; + gl_Position = vec4(a_position, 0.0, 1.0); +}`,St=`#version 300 es +precision highp float; +uniform sampler2D u_field; +uniform sampler2D u_tint; +uniform vec2 u_resolution; +uniform float u_time; +uniform float u_lineInterval; +uniform float u_lineOffset; +uniform float u_lineWidth; +uniform float u_lineFade; +uniform float u_angleWidth; +uniform float u_angleFade; +uniform float u_dangerSteepness; +uniform float u_scale; +uniform vec3 u_baseColor; +uniform vec3 u_fieldGlowColor; +uniform vec3 u_lineLowColor; +uniform vec3 u_lineHighColor; +uniform vec3 u_angleLowColor; +uniform vec3 u_angleHighColor; +uniform float u_tintScale; +in vec2 v_uv; +out vec4 outColor; +vec2 calcGrad(vec2 uv, float me) { + vec2 texel = 1.0 / max(vec2(1.0), u_resolution); + float n = -texture(u_field, vec2(uv.x, uv.y + texel.y)).r; + float e = -texture(u_field, vec2(uv.x + texel.x, uv.y)).r; + return vec2(e - me, n - me); +} +void main() { + float height = -texture(u_field, v_uv).r; + vec4 tint = texture(u_tint, v_uv); + vec2 plan = calcGrad(v_uv, height); + float slope = max(length(plan), 0.00001); + vec3 color = u_baseColor; + float fieldGlow = smoothstep(0.0, u_lineInterval * 7.0, abs(height)); + color += u_fieldGlowColor * fieldGlow; + color += tint.rgb * clamp(tint.a, 0.0, 1.0) * u_tintScale; + + float dangerBlend = smoothstep(0.0, u_dangerSteepness, pow(slope / max(0.0001, u_scale), 2.0)); + vec3 baseLine = mix(u_lineLowColor, u_lineHighColor, dangerBlend); + vec3 angleLine = mix(u_angleLowColor, u_angleHighColor, dangerBlend) * clamp(slope / max(0.0001, u_scale), 0.0, 1.0); + + vec3 lines = vec3(0.0); + float interval = max(0.0001, abs(u_lineInterval)); + float nearestLine = abs(fract((height + u_lineOffset) / interval) - 0.5) * interval; + float lineDistance = nearestLine / slope; + float line = 1.0 - smoothstep(u_lineWidth, u_lineWidth * u_lineFade, lineDistance); + lines += line * baseLine; + + float angle = atan(plan.y, plan.x) / 3.1415926536 + 1.0; + float nearestAngle = abs(fract(angle * 6.0) - 0.5) / 6.0; + float angleMask = smoothstep(interval * 0.25, interval * 1.5, abs(height)); + float angleLineAmount = 1.0 - smoothstep(u_angleWidth, u_angleWidth * u_angleFade, nearestAngle); + lines += angleLineAmount * angleMask * angleLine; + + color += clamp(lines, 0.0, 1.7); + outColor = vec4(color, 1.0); +}`,He=new Set(["gamecult.fields.splats.v1","gamecult.fields.gravity.v1","gamecult.fields.objects.v1"]),_t={pluginId:"fields.surface",capabilities:["field.surface2d","gravity.surface","field.scalar","field.vector","field.objects"],componentKinds:["field.surface2d","gravity.surface"],schemas:[...He],normalizeDocument:_e,renderComponent:Et};function Et(e,t,n,i,a,c){const s=document.createElement("canvas");s.className="cultui-gravity-surface",e.id&&(s.id=e.id),s.setAttribute("role","img"),s.setAttribute("aria-label",Yt(t.label,"gravity surface")),s.style.display="block",s.style.width="100%",s.style.height="100%",s.style.pointerEvents="none",c.applyGeneratedLayout(s,n,i);let l=!1;const f={},o=()=>Ct(s,t,f,c.resolveAssetUrl),r=()=>{!s.isConnected||l||(l=!0,requestAnimationFrame(()=>{l=!1,s.isConnected&&o()}))};s.addEventListener("cultui:asset-loaded",r);let d=0,u;const g=()=>{d&&window.clearInterval(d),u?.disconnect(),s.removeEventListener("cultui:asset-loaded",r)},y=()=>{if(!s.isConnected){g();return}At(e,t,a,c.providerId,f).then(v=>{v&&s.isConnected&&r()}).catch(v=>{f.lastError=v instanceof Error?v.message:String(v)})};typeof ResizeObserver<"u"&&(u=new ResizeObserver(r),u.observe(s)),r();const b=Math.max(33,Math.min(1e3,Ht(t.stateRefreshMs,100)));return d=window.setInterval(y,b),queueMicrotask(y),window.setTimeout(r,300),window.setTimeout(r,1e3),s}async function At(e,t,n,i,a){if(a.loading)return!1;const c=[xe(e,t,"renderSplats","renderSplatsDocumentId","renderSplatsSchemaId"),xe(e,t,"gravity","gravityDocumentId","gravitySchemaId"),xe(e,t,"objects","objectsDocumentId","objectsSchemaId")].filter(s=>!!s?.documentId);if(c.length===0)return!1;a.loading=!0;try{let s=!1;for(const l of c){const f=await n.documentResolver?.(l,e);let o=be(_e(f?.schemaId||l.schemaId,f?.document));if(Object.keys(o).length===0&&(o=be(_e(l.schemaId,await It(l,i||n.provider?.providerId)))),Object.keys(o).length===0)continue;const r=l.slotId==="renderSplats"?"renderSplats":l.slotId==="gravity"?"gravity":"objects",d=Ae(a[r]?.frameId,-1),u=Ae(o.frameId,d);a[r]=o,s||=u!==d}return a.lastLoadedAt=Date.now(),s}finally{a.loading=!1}}async function It(e,t){if(typeof fetch!="function"||typeof window>"u"||!t)return;const n=new URLSearchParams({documentId:e.documentId});e.schemaId&&n.set("schemaId",e.schemaId),e.slotId&&n.set("slotId",e.slotId);const i=await fetch(`/eir/document/${encodeURIComponent(t)}?${n.toString()}`,{cache:"no-store",headers:{Accept:"application/json"}});if(i.ok)return be(await i.json()).document}function xe(e,t,n,i,a){const c=(e.embeddedDocuments||[]).find(l=>String(l?.slotId||"")===n),s=T(t[i],c?.documentId);if(s)return{documentId:s,schemaId:T(t[a],c?.schemaId),presentationKind:T(c?.presentationKind)||"data",slotId:n}}function _e(e,t){const n=Array.isArray(t)?t:void 0,i=n?n[0]:t?.schema,a=String(e||i||"");return!n||!He.has(a)?t:a==="gamecult.fields.splats.v1"?Ut(n):a==="gamecult.fields.gravity.v1"?qt(n):Ot(n)}function Ct(e,t,n,i){const a=e.getBoundingClientRect(),c=Math.max(1,Math.floor(a.width||e.clientWidth||1)),s=Math.max(1,Math.floor(a.height||e.clientHeight||1)),l=Math.max(1,Math.min(2,window.devicePixelRatio||1)),f=Math.max(1,Math.floor(c*l)),o=Math.max(1,Math.floor(s*l));(e.width!==f||e.height!==o)&&(e.width=f,e.height=o);const r=e.getContext("2d");if(!r)return;r.setTransform(l,0,0,l,0,0),r.clearRect(0,0,c,s);const d=$t(Bt(t),c,s),u=Ze(n?.gravity),g=Nt(n?.gravity)||Pt(T(t.bodies,"")),y=Dt(n?.objects)||Mt(T(t.objects,""));lt(r,t,u,g,d,c,s,n?.renderSplats)||Tt(r,t,c,s,"field.surface2d requires WebGL2 float render targets"),Rt(r,g,t,d,c,s,i),Lt(r,y,t,d,c,s,i)}function Tt(e,t,n,i,a){e.save(),e.fillStyle=T(t.failureBackground,"rgba(0, 0, 0, 0.72)"),e.fillRect(0,0,n,i),e.font=T(t.failureFont,"700 13px Cascadia Mono, Consolas, monospace"),e.fillStyle=T(t.failureColor,"rgba(255, 184, 79, 0.95)"),e.fillText(a,16,28),e.restore()}function Rt(e,t,n,i,a,c,s){for(const l of t){const f=Je(i,l.x,l.y,a,c),o=Math.max(18,Math.min(190,l.radius/Math.max(1,i.maxX-i.minX)*a*.32)),r=s(l.icon),d=l.kind.toLowerCase().includes("sun")?Math.max(_(n.sunIconMinPx,34),o*_(n.sunIconScale,.72)):Math.max(_(n.bodyIconMinPx,24),o*_(n.bodyIconScale,.48)),u=l.iconSize>0?l.iconSize:d;r&&kt(e,r,f.x,f.y,u,.92),l.key&&Ve(e,n,l.key.replace(/^local\./,""),f.x+o*.44,f.y-o*.48,T(n.bodyLabelColor,"rgba(226, 244, 255, 0.82)"))}}const ye=new Map;function kt(e,t,n,i,a,c){let s=ye.get(t);s||(s=new Image,s.decoding="async",s.onload=()=>requestAnimationFrame(()=>{e.canvas.dispatchEvent(new CustomEvent("cultui:asset-loaded"))}),s.src=t,ye.set(t,s)),!(!s.complete||s.naturalWidth===0)&&(e.save(),e.globalAlpha=c,e.drawImage(s,n-a/2,i-a/2,a,a),e.restore())}function Lt(e,t,n,i,a,c,s){for(const l of t){const f=Je(i,l.x,l.y,a,c);if(f.x<-40||f.x>a+40||f.y<-40||f.y>c+40)continue;const o=l.kind.toLowerCase().includes("station")?_(n.stationIconSizePx,34):l.controlled?_(n.shipIconSizePx,22):_(n.remoteShipIconSizePx,18),r=Ft(n,l.faction,l.controlled,l.visibility),d=s(l.icon);e.save(),e.globalAlpha=Math.max(.25,Math.min(1,l.visibility)),e.translate(f.x,f.y);const u=Math.atan2(l.directionY,l.directionX)+Math.PI/2;if(l.kind.toLowerCase().includes("ship")&&e.rotate(u),d){const g=ye.get(d);if(g)g.complete&&g.naturalWidth>0&&e.drawImage(g,-o/2,-o/2,o,o);else{const y=new Image;y.decoding="async",y.onload=()=>e.canvas.dispatchEvent(new CustomEvent("cultui:asset-loaded")),y.src=d,ye.set(d,y)}}e.restore(),Ve(e,n,l.label,f.x+o*.55,f.y-o*.45,r)}}function Ve(e,t,n,i,a,c){n&&(e.save(),e.font=T(t.objectLabelFont,"700 12px Ubuntu, system-ui, sans-serif"),e.textBaseline="middle",e.lineWidth=_(t.objectLabelStrokeWidth,3),e.strokeStyle=T(t.objectLabelStroke,"rgba(0, 0, 0, 0.72)"),e.fillStyle=c,e.strokeText(n,i,a),e.fillText(n,i,a),e.restore())}function Ft(e,t,n,i){const a=Math.max(.25,Math.min(1,i));if(n)return se(T(e.objectControlledColor,"rgba(122, 240, 255, {alpha})"),a);const c=t.toLowerCase();return c.includes("raider")?se(T(e.objectRaiderColor,"rgba(255, 143, 74, {alpha})"),a):c.includes("neutral")?se(T(e.objectNeutralColor,"rgba(232, 232, 224, {alpha})"),a):se(T(e.objectDefaultColor,"rgba(214, 244, 255, {alpha})"),a)}function se(e,t){return e.replaceAll("{alpha}",String(t))}function Pt(e){return e.split(";").map(t=>t.trim()).filter(Boolean).map(t=>{const n=t.split("|");return{key:n[0]??"",kind:n[1]??"",x:Number(n[2])||0,y:Number(n[3])||0,radius:Math.max(1,Number(n[4])||1),depth:Number(n[5])||0,exponent:Number(n[6])||1,waveRadius:Number(n[7])||0,waveDepth:Number(n[8])||0,waveSpeed:Number(n[9])||0,icon:n[10]??"",iconSize:Number(n[12])||0,tint:n[11]??""}})}function Mt(e){return e.split(";").map(t=>t.trim()).filter(Boolean).map(t=>{const n=t.split("|");return{key:n[0]??"",kind:n[1]??"",label:n[2]??"",x:Number(n[3])||0,y:Number(n[4])||0,directionX:Number(n[5])||0,directionY:Number(n[6])||1,faction:n[7]??"",controlled:n[8]==="1"||n[8]==="true",visibility:Number(n[9])||1,icon:n[10]??""}})}function Nt(e){const t=Array.isArray(e?.gravityInfluences)?e.gravityInfluences:[],n=Array.isArray(e?.bodies)?e.bodies:[];if(t.length===0&&n.length===0)return;const i=new Map;for(const a of n){const c=T(a.bodyKey,a.name,"");c&&i.set(c,a)}return(t.length>0?t:n).map(a=>{const c=T(a.bodyKey,a.name,"body"),s=i.get(c),l=T(a.kind,"Body");return{key:c,kind:l,x:_(a.x,0),y:_(a.y,0),radius:Math.max(1,_(a.radius,80)),depth:_(a.gravityDepth,0),exponent:_(a.gravityDepthExponent,1),waveRadius:_(a.waveRadius,0),waveDepth:_(a.waveDepth,0),waveSpeed:_(a.waveSpeed,0),icon:Ee(a.iconAsset)||Ee(s?.iconAsset),iconSize:_(s?.iconSize,_(a.iconSize,0)),tint:""}})}function Dt(e){const t=Array.isArray(e?.objects)?e.objects:[];if(t.length!==0)return t.map(n=>{const i=T(n.kind,"object");return{key:T(n.entityKey,String(n.entityIndex??""),"object"),kind:i,label:T(n.displayName,n.entityKey,"object"),x:_(n.x,0),y:_(n.y,0),directionX:_(n.directionX,1),directionY:_(n.directionY,0),faction:T(n.factionKey,""),controlled:Vt(n.controlled),visibility:_(n.visibility,1),icon:Ee(n.iconAsset)}})}function Ee(e){const t=Ze(e);return T(t.uri,"")}function Bt(e){const t=Math.max(1,_(e.viewRadius,Math.max(1200,_(e.terrainRadius,1200))));return{minX:_(e.minX,-t),minY:_(e.minY,-t),maxX:_(e.maxX,t),maxY:_(e.maxY,t)}}function $t(e,t,n){const i=Math.max(1e-4,e.maxX-e.minX),a=Math.max(1e-4,e.maxY-e.minY),c=Math.max(1e-4,t/Math.max(1,n)),s=i/a,l=(e.minX+e.maxX)*.5,f=(e.minY+e.maxY)*.5;if(c>s){const r=a*c;return{minX:l-r*.5,maxX:l+r*.5,minY:e.minY,maxY:e.maxY}}const o=i/c;return{minX:e.minX,maxX:e.maxX,minY:f-o*.5,maxY:f+o*.5}}function Je(e,t,n,i,a){return{x:(t-e.minX)/Math.max(1,e.maxX-e.minX)*i,y:(n-e.minY)/Math.max(1,e.maxY-e.minY)*a}}function Ut(e){const t=M(e[9]);return{schema:e[0],frameId:e[1],publishedAtUtc:e[2],simulationTimeSeconds:e[3],runId:e[4],zoneIndex:e[5],zoneName:e[6],viewport:Te(e[7]),layers:M(e[8]).map(jt),splats:{count:t[0]??0,centerX:t[1]||[],centerY:t[2]||[],halfExtentX:t[3]||[],halfExtentY:t[4]||[],rotationCos:t[5]||[],rotationSin:t[6]||[],channel:t[7]||[],falloff:t[8]||[],valueR:t[9]||[],valueG:t[10]||[],valueB:t[11]||[],valueA:t[12]||[],sourceKey:t[13]||[],layerIndex:t[14]||[],sourceKind:t[15]||[],frequencyX:t[16]||[],frequencyY:t[17]||[],phaseX:t[18]||[],phaseY:t[19]||[],animationSpeed:t[20]||[],sourceFlags:t[21]||[]}}}function qt(e){return{schema:e[0],frameId:e[1],publishedAtUtc:e[2],simulationTimeSeconds:e[3],runId:e[4],zoneIndex:e[5],zoneName:e[6],viewport:Te(e[7]),gravityInfluences:M(e[8]).map(Wt),bodies:M(e[9]).map(zt),terrainRadius:e[10],terrainDepth:e[11],terrainDepthExponent:e[12],terrainWaveFrequency:e[13]}}function Ot(e){return{schema:e[0],frameId:e[1],publishedAtUtc:e[2],simulationTimeSeconds:e[3],runId:e[4],zoneIndex:e[5],zoneName:e[6],currentEntityKey:e[7],viewport:Te(e[8]),controlledEntityIndices:M(e[9]),objects:M(e[10]).map(Kt)}}function Te(e){const t=M(e);return t.length?{minX:t[0],minY:t[1],maxX:t[2],maxY:t[3]}:e}function jt(e){const t=M(e);return t.length?{layerKey:t[0],displayName:t[1],channel:t[2],blendMode:t[3],graphicsFormat:t[4],clearBeforeDraw:t[5],clearR:t[6],clearG:t[7],clearB:t[8],clearA:t[9]}:e}function Wt(e){const t=M(e);return t.length?{bodyKey:t[0],orbitKey:t[1],kind:t[2],x:t[3],y:t[4],radius:t[5],gravityDepth:t[6],gravityDepthExponent:t[7],waveRadius:t[8],waveDepth:t[9],waveSpeed:t[10]}:e}function zt(e){const t=M(e);return t.length?{bodyKey:t[0],orbitKey:t[1],name:t[2],kind:t[3],x:t[4],y:t[5],radius:t[6],isAsteroidBelt:t[7],body:t[8],iconAsset:Re(t[9])}:e}function Kt(e){const t=M(e);return t.length?{entityIndex:t[0],entityKey:t[1],displayName:t[2],kind:t[3],factionKey:t[4],x:t[5],y:t[6],z:t[7],directionX:t[8],directionY:t[9],velocityX:t[10],velocityY:t[11],controlled:t[12],targetEntityIndex:t[13],isActive:t[14],visibility:t[15],status:Gt(t[16]),inventory:M(t[17]).map(Xt),iconAsset:Re(t[18])}:e}function Gt(e){const t=M(e);return t.length?{hull:t[0],shield:t[1],heat:t[2]}:e||{}}function Xt(e){const t=M(e);return t.length?{source:t[0],itemKey:t[1],quantity:t[2],quality:t[3],durability:t[4],enabled:t[5],sourceIndex:t[6],x:t[7],y:t[8],iconAsset:Re(t[9])}:e}function Re(e){const t=M(e);return t.length?{assetKey:t[0],kind:t[1],uri:t[2],transport:t[3],contentHash:t[4],mimeType:t[5],metadata:t[6]||{}}:e||{}}function M(e){return Array.isArray(e)?e:[]}function be(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function T(...e){for(const t of e)if(typeof t=="string"&&t.trim())return t.trim();return""}function Yt(e,t){return typeof e=="string"&&e?e:t}function Ht(e,t){const n=Number(e);return Number.isFinite(n)&&n>0?Math.floor(n):t}function Ae(e,t){const n=Number(e);return Number.isFinite(n)?n:t}const Ze=be,_=Ae;function Vt(e){return typeof e=="boolean"?e:typeof e=="number"?e!==0:typeof e=="string"&&["1","true","yes","on"].includes(e.trim().toLowerCase())}const Jt=[_t],Zt={"--bg":"#020909","--bg-top":"#020909","--bg-mid":"#020909","--bg-bottom":"#020909","--shell-top":"#010707","--shell-bottom":"#010707","--panel":"#071918","--panel-2":"#0a2423","--line":"rgba(103, 240, 228, 0.28)","--line-deep":"rgba(103, 240, 228, 0.18)","--text":"#e7f1f1","--text-bright":"#e7f1f1","--quiet":"#8ba5a3","--accent":"#ffb84f","--accent-strong":"#ffb84f","--corner-accent":"#ffb84f","--cyan":"#8efcff","--shadow":"rgba(0, 0, 0, 0.35)","--pixel-grid":"rgba(142, 252, 255, 0.04)","--border-width":"1px","--border-bottom-width":"1px","--corner-accent-size":"0","--font-body":'"M PLUS 1", "Ubuntu Sans", Ubuntu, "Noto Sans JP", system-ui, sans-serif',"--font-title":'"Montserrat", "Zen Kaku Gothic New", "M PLUS 1", "Ubuntu Sans", system-ui, sans-serif',"--font-mono":'"Ubuntu Sans Mono", "M PLUS 1 Code", "Cascadia Mono", Consolas, monospace'};let le,Qe=ke(void 0),oe,O={};const Ue=new WeakMap;function et(e,t,n={}){if(Ue.get(t)?.dispose(),oe=e,O=n,Qe=ke(e.surface?.styles),globalThis.__eveCurrentMesh=e.mesh,yn(e.surface?.styles,n.body??document.body),n.body&&(n.body.dataset.provider=e.providerId||n.provider?.providerId||""),n.statusElement&&(n.statusElement.textContent=`${e.title||e.surface?.title||"surface"}${n.source?` (${n.source})`:""}`),e.surface?.root){if(t.replaceChildren(L(e.surface.root,n)),n.stateBindingResolver){const i=new en(e,t,n);Ue.set(t,i),i.start()}}else t.replaceChildren(Y("No surface root"));return t}function Qt(e,t,n){const i=t.targetProp.split(".").filter(Boolean);if(i.length===0)throw new Error("Eve state binding targetProp must not be empty.");e.props||={};let a=e.props;for(const c of i.slice(0,-1)){const s=a[c];(!s||typeof s!="object"||Array.isArray(s))&&(a[c]={}),a=a[c]}a[i[i.length-1]]=n}class en{surface;host;options;disposed=!1;unsubscribers=[];constructor(t,n,i){this.surface=t,this.host=n,this.options=i}async start(){const t=this.options.stateBindingResolver,n=this.surface.surface?.root;if(!(!t||!n))for(const i of tt(n))for(const a of i.stateBindings||[]){if(this.disposed)return;const c=await t(a,i);if(!c||this.disposed)continue;const s=l=>{this.disposed||(Qt(i,a,l),this.renderCanonicalProjection())};if(s(await c.latest()),this.disposed)return;this.unsubscribers.push(c.watch(s))}}dispose(){this.disposed=!0;for(const t of this.unsubscribers.splice(0))t()}renderCanonicalProjection(){const t=this.surface.surface?.root;t&&this.host.replaceChildren(L(t,this.options))}}function*tt(e){yield e;for(const t of e.children||[])yield*tt(t)}function L(e,t=O){const n=e.kind||"panel",i=x(e.props),a=x(e.layout),c=x(e.style),s=e.children||[],l=e.embeddedDocuments||[];if(n==="surface"||n==="cockpit"||n==="dashboard"){const r=m("section","cultui-surface-root eve-surface");w(r,e),typeof a.direction=="string"?r.dataset.direction=a.direction:typeof i.layout=="object"&&i.layout&&typeof i.layout.direction=="string"&&(r.dataset.direction=String(i.layout.direction)),n!=="surface"&&(r.dataset.surfaceKind=n),S(r,a,c);for(const d of s)r.append(L(d,t));return r}if(n==="column"||n==="row"||n==="form"||n==="rail"){const r=m("div",`cultui-partition eve-${n}`);w(r,e),r.dataset.direction=n==="row"||n==="rail"?"horizontal":"vertical",n==="rail"&&(r.dataset.overflow="x"),ue(r,{...a,...i}),S(r,a,c);for(const d of s)r.append(L(d,t));return r}if(n==="grid"){const r=m("section","cultui-grid"),d=$(i.columns,0);d>0?r.style.gridTemplateColumns=`repeat(${d}, minmax(0, 1fr))`:typeof i.columns=="string"&&(r.style.gridTemplateColumns=i.columns);const u=$(i.rows,0);u>0&&(r.style.gridTemplateRows=`repeat(${u}, minmax(0, auto))`),S(r,a,c);for(const g of s)r.append(L(g,t));return r}if(n==="partition"){const r=m("section",`cultui-partition split-${h(i.split,"none")}`);w(r,e),ue(r,i),S(r,a,c),r.style.minWidth="0",h(i.split,"none")==="x"&&!p(i.flexWrap,a.flexWrap,"")&&(r.style.flexWrap="wrap"),typeof i.role=="string"&&(r.dataset.role=i.role);for(const d of s)r.append(L(d,t));return r}if(n==="input.binding-map")return mn(e,i,t);if(n==="inventory.drag_session")return sn(e,i,a,c);if(n==="inventory.grid")return ln(e,i,a,c,t);if(n==="inventory.item")return dn(e,i,a,c);const f=(t.pluginAdapters||Jt).find(r=>r.componentKinds.includes(n));if(f?.renderComponent)return f.renderComponent(e,i,a,c,t,{applyGeneratedLayout:S,providerId:oe?.providerId||t.provider?.providerId,resolveAssetUrl:ie});if(n==="world.scene3d"||n==="world.scene2d")return nn(e,i,a,c,t);if(n==="image.background"){const r=m("div","cultui-background"),d=ie(p(i.src,i.assetUri,i.assetRef,""));return d&&(r.style.backgroundImage=`url("${d}")`),r.setAttribute("aria-label",h(i.label,"background")),r}if(n==="image.sprite"){const r=m("figure",`cultui-sprite ${h(i.slot,"center")}`);w(r,e);const d=ie(p(i.src,i.assetUri,i.assetRef,""));if(d){const u=m("img");u.src=d,u.alt=h(i.alt,h(i.actor,h(i.label,""))),r.append(u)}return r}if(n==="avatar"){const r=m("figure","cultui-avatar-card");w(r,e);const d=ie(p(i.src,i.assetUri,i.assetRef,""));if(d){const b=m("img");b.src=d,b.alt=h(i.alt,h(i.text,h(i.label,""))),r.append(b)}else r.append(m("div","cultui-avatar-fallback",Rn(p(i.text,i.label,i.actor,"?"))));const u=p(i.text,i.label,i.actor,"");u&&r.append(m("figcaption","cultui-avatar-name",u));const g=p(i.status,"");g&&r.append(m("div","cultui-avatar-status",g));const y=p(i.detail,"");return y&&r.append(m("div","cultui-avatar-detail",y)),r}if(n==="pane"||n==="panel"){const r=m("section","pane cultui-pane");w(r,e);const d=h(i.span,"");d&&(r.dataset.span=d);const u=h(i.density,"");u&&(r.dataset.density=u);const g=h(i.title,e.text||"");g&&r.append(m("h2","",g));for(const y of s)r.append(L(y,t));return r}if(n==="list"||n.endsWith(".roster")){const r=m("section","cultui-list");w(r,e),r.dataset.componentKind=n;const d=h(i.title,"");d&&r.append(m("h3","cultui-list-title",d));for(const[u,g]of Cn(i.items).entries())r.append(L({id:`${e.id||"list"}-item-${u}`,kind:"list.item",props:{...g}},t));for(const u of s)r.append(L(u,t));return r}if(n==="list.item"||n.endsWith(".item")){const r=nt(e),d=m("article","cultui-list-item");w(d,e),d.dataset.componentKind=n;const u=m("div","cultui-list-item-heading");if(u.append(m("strong","cultui-list-item-label",r.label)),r.status&&u.append(m("span","cultui-list-item-status",r.status)),d.append(u),r.detail&&d.append(m("div","cultui-list-item-detail",r.detail)),r.badges.length){const g=m("div","cultui-list-item-badges");for(const y of r.badges)g.append(m("span","cultui-list-item-badge",y));d.append(g)}for(const g of s)d.append(L(g,t));return d}if(n==="bar"){const r=m("div","cultui-meter");w(r,e);const d=h(i.label,""),u=h(i.value,"");if(d||u){const b=m("div","cultui-meter-head");b.append(m("span","",d)),b.append(m("strong","",u)),r.append(b)}const g=m("div","cultui-meter-track"),y=m("span","cultui-meter-fill");return y.style.width=`${Ke(i.percent)}%`,g.append(y),r.append(g),r}if(n==="card"){const r=We(i,e),d=r?m("button","card cultui-card cultui-card-button"):m("article","card cultui-card");w(d,e),S(d,a,c),d instanceof HTMLButtonElement&&(d.type="button");const u=h(i.title,e.text||"");u&&d.append(m("div","card-title",u));for(const g of s)d.append(L(g,t));return r&&ze(d,e,r,i,t),d}if(n==="control.button"){const r=m("button","cultui-button eve-control-button",h(i.label,"Action"));return w(r,e),r.type="button",S(r,a,c),ze(r,e,We(i,e),i,t),r}if(n==="control.popup"){const r=m("button","cultui-button eve-control-popup",h(i.label,"Open"));return w(r,e),r.type="button",S(r,a,c),r.addEventListener("click",d=>{pn(e,t,r,d.clientX,d.clientY)}),r}if(n==="text.dialogue"||n==="text"||n==="text.title"||n==="text.subtitle"||n==="label"){const r=m("div",Sn(n,i),h(i.value,h(i.text,e.text||"")));return w(r,e),ue(r,i),S(r,a,c),r}if(n==="metric"){const r=m("dl","metric cultui-reactive-metric eve-metric");return w(r,e),S(r,a,c),r.append(m("dt","",h(i.label,"Metric"))),r.append(m("dd","metric-value",h(i.value,""))),r}if(n==="progress"){const r=m("div","cultui-meter eve-progress");w(r,e),S(r,a,c);const d=h(i.label,""),u=h(i.value,""),g=Number(i.min??0),y=Number(i.max??1),b=Number(i.value??0),v=Number.isFinite(b)&&Number.isFinite(g)&&Number.isFinite(y)&&y!==g?(b-g)/(y-g)*100:Ke(i.percent);if(d||u){const D=m("div","cultui-meter-head");D.append(m("span","",d)),D.append(m("strong","",u)),r.append(D)}const C=m("div","cultui-meter-track"),E=m("span","cultui-meter-fill");return E.style.width=`${Math.max(0,Math.min(100,v))}%`,C.append(E),r.append(C),r}if(n==="modal"){const r=m("section","cultui-modal-surface");w(r,e),S(r,a,c);const d=h(i.title,"");d&&r.append(m("h2","cultui-modal-surface-title",d));for(const u of s)r.append(L(u,t));return r}if(n==="options"){const r=m("section","cultui-options");w(r,e),S(r,a,c);const d=h(i.label,"");d&&r.append(m("h3","cultui-list-title",d));for(const u of s)r.append(L(u,t));return s.length===0&&r.append(Y("waiting for options")),r}if(n==="image.preview"){const r=m("figure","cultui-image-preview");w(r,e);const d=m("div","cultui-image-frame"),u=ie(p(i.src,i.assetUri,i.assetRef,""));if(u){const g=m("img");g.src=u,g.alt=h(i.label,""),g.style.imageRendering=h(i.imageRendering,"auto"),i.zoom!==void 0&&(g.style.transform=`scale(${i.zoom})`,g.style.transformOrigin=h(i.crop,"50% 50%")),d.append(g)}else d.append(m("span","",h(i.label,"image")));return r.append(d),i.label&&r.append(m("figcaption","",String(i.label))),r}if(n==="canvas.preview"||n==="canvas.editor"){const r=m("div",`cultui-canvas-placeholder ${n==="canvas.editor"?"editor":"preview"}`);return w(r,e),r.append(m("div","viz-label",h(i.label,"Canvas"))),r.append(m("div","cultui-canvas-grid",i.state==="empty"?"waiting for pixels":h(i.state,""))),r}if(n==="surface.slot"){const r=m("section","cultui-embedded-slot");w(r,e),S(r,a,c),r.dataset.slotId=h(i.slotId,h(l[0]?.slotId,"")),r.dataset.documentId=h(i.documentId,h(l[0]?.documentId,"")),r.dataset.schemaId=h(i.schemaId,h(l[0]?.schemaId,"")),r.dataset.presentationKind=h(i.presentationKind,h(l[0]?.presentationKind,""));const d=l.map(g=>x(g.surface)).find(g=>x(g.root).kind||g.root),u=i.modal===!0||r.dataset.presentationKind.includes("modal");if((d||r.dataset.documentId)&&u){const g=m("button","cultui-button cultui-modal-trigger",h(i.label,r.dataset.slotId||"Configure"));g.type="button",g.addEventListener("click",()=>ot(Ie(e,t),t)),r.append(g)}else if(d||r.dataset.documentId){const g=m("div","cultui-embedded-slot-body");g.append(m("div","detail","materializing surface")),r.append(g),Ie(e,t).then(y=>{g.replaceChildren(y?.root?L(y.root,t):Y("Embedded surface unavailable"))}).catch(y=>{g.replaceChildren(Y(`Embedded surface failed: ${y instanceof Error?y.message:String(y)}`))})}else r.append(m("div","detail",r.dataset.presentationKind||r.dataset.slotId||"embedded surface"));return r}if(n==="control.slider")return vn(i,s,t);if(n==="control.toggle"){const r=m("label","toggle-row cultui-toggle");return w(r,e),r.append(m("span","field-control",i.value?"on":"off")),r.append(m("span","toggle-copy",h(i.label,"Toggle"))),r}if(n==="input.number"||n==="input.select"||n==="control.range"||n==="control.input.text"||n==="control.select"){const r=m("label","field cultui-field");return w(r,e),ue(r,i),S(r,a,c),r.append(m("span","field-label",h(i.label,""))),r.append(m("span","field-control cultui-field-value",i.value===void 0?"":String(i.value))),r}if(n==="color.swatch"){const r=m("div","paint-swatch cultui-swatch");return w(r,e),r.style.background=h(i.value,h(i.color,"currentColor")),r.title=h(i.label,"Color"),r}const o=m("section","pane");w(o,e),o.append(m("h2","",n));for(const r of s)o.append(L(r,t));return o}function nt(e){const t=x(e.props);return{label:p(t.label,t.title,t.displayName,e.text,e.kind,"item"),status:p(t.status,t.state,""),detail:p(t.detail,t.phase,t.repoName,""),badges:Array.isArray(t.badges)?t.badges.map(n=>String(n).trim()).filter(Boolean):p(t.badges,"").split(",").map(n=>n.trim()).filter(Boolean)}}function S(e,t,n={}){const i=p(t.display,"");i&&(e.style.display=i);const a=p(t.direction,"");a&&(e.style.flexDirection=a==="horizontal"?"row":a==="vertical"?"column":a);const c=p(t.flexWrap,"");c&&(e.style.flexWrap=c);const s=p(t.gridTemplateColumns,"");s&&(e.style.gridTemplateColumns=s);const l=p(t.gridTemplateRows,"");l&&(e.style.gridTemplateRows=l);const f=p(t.gridTemplateAreas,"");f&&(e.style.gridTemplateAreas=f);const o=p(t.gridArea,"");o&&(e.style.gridArea=o);const r=p(t.placeItems,"");r&&(e.style.placeItems=r),P(e,"gap",p(t.gap,"")),P(e,"padding",p(t.padding,"")),P(e,"margin",p(t.margin,"")),P(e,"top",p(t.top,"")),P(e,"right",p(t.right,"")),P(e,"bottom",p(t.bottom,"")),P(e,"left",p(t.left,"")),P(e,"width",p(t.width,"")),P(e,"minWidth",p(t.minWidth,"")),P(e,"maxWidth",p(t.maxWidth,"")),P(e,"height",p(t.height,"")),P(e,"minHeight",p(t.minHeight,"")),P(e,"maxHeight",p(t.maxHeight,""));const d=p(t.alignItems,"");d&&(e.style.alignItems=d);const u=p(t.justifyContent,"");u&&(e.style.justifyContent=u);const g=p(t.alignSelf,"");g&&(e.style.alignSelf=g);const y=p(t.overflow,"");y&&(e.style.overflow=y);const b=p(t.overflowX,"");b&&(e.style.overflowX=b);const v=p(t.overflowY,"");v&&(e.style.overflowY=v);const C=p(t.position,"");C&&(e.style.position=C);const E=p(t.cursor,"");E&&(e.style.cursor=E);const D=p(n.background,"");D&&(e.style.background=pe(D));const V=p(n.color,"");V&&(e.style.color=pe(V)),P(e,"borderWidth",p(n.borderWidth,""));const W=p(n.borderColor,"");W&&(e.style.borderColor=pe(W));const J=p(n.borderStyle,"");J&&(e.style.borderStyle=J),P(e,"borderRadius",p(n.borderRadius,""));const Z=p(n.boxShadow,"");Z&&(e.style.boxShadow=Z);const z=p(n.font,"");z&&(e.style.font=z),P(e,"fontSize",p(n.fontSize,""));const I=p(n.fontWeight,"");I&&(e.style.fontWeight=I);const Q=p(n.textTransform,"");Q&&(e.style.textTransform=Q);const ce=p(n.textAlign,"");ce&&(e.style.textAlign=ce);const ve=p(n.whiteSpace,"");ve&&(e.style.whiteSpace=ve);const Pe=p(n.overflow,"");Pe&&(e.style.overflow=Pe);const Me=p(n.textOverflow,"");Me&&(e.style.textOverflow=Me),P(e,"lineHeight",p(n.lineHeight,""))}function P(e,t,n){n&&(e.style[t]=R(n))}function k(e,t){const n={};for(const[i,a]of Object.entries(e))i.startsWith(t)&&(n[i.slice(t.length)]=a);return n}function tn(e){const t=(e.children||[]).filter(u=>u.kind==="world.entity3d"),n=t.map(u=>cn(x(u.props).position,[0,0,0])),i=n.map(u=>u[0]),a=n.map(u=>u[2]),c=Math.min(...i,-1),s=Math.max(...i,1),l=Math.min(...a,-1),f=Math.max(...a,1),o=Math.max(1,s-c),r=Math.max(1,f-l),d=6;return t.map((u,g)=>{const y=x(u.props);return{entityId:p(y.entityId,u.id),faction:h(y.faction,"neutral"),kind:h(y.entityKind,"entity"),label:p(y.label,y.entityId,u.id,"Entity"),controlled:Le(y.controllable),xPercent:d+(n[g][0]-c)/o*(100-d*2),yPercent:d+(1-(n[g][2]-l)/r)*(100-d*2),source:u}})}function nn(e,t,n,i,a){const c=m("section","cultui-world-scene");w(c,e),S(c,n,i),c.tabIndex=0,c.setAttribute("aria-label",h(t.label,"Interactive world"));const s=tn(e),l=s.find(r=>r.controlled),f=m("div","cultui-world-heading");f.append(m("strong","",h(t.label,"World"))),f.append(m("span","",`${s.length} entities`)),c.append(f);const o=m("div","cultui-world-plane");for(const r of s){const d=m("button",`cultui-world-entity faction-${qe(r.faction)} kind-${qe(r.kind)}`);d.type="button",d.style.left=`${r.xPercent}%`,d.style.top=`${r.yPercent}%`,d.dataset.entityId=r.entityId,d.dataset.controlled=r.controlled?"true":"false",d.title=r.label,d.setAttribute("aria-label",`${r.label}, ${r.kind}, ${r.faction}`),d.append(m("span","cultui-world-entity-glyph",an(r.kind))),d.append(m("span","cultui-world-entity-label",r.label));const u=x(r.source.props),g=p(u.targetCommand,t.targetCommand,u.focusCommand,t.focusCommand);g&&d.addEventListener("click",()=>we(g,{actorEntityId:l?.entityId||p(t.playerEntityId),entityId:r.entityId,targetEntityId:r.entityId,targetEntityKey:r.entityId},r.source,a)),o.append(d)}return c.append(o),c.addEventListener("keydown",r=>{const d=on(r.key);if(d){r.preventDefault();const g=p(t.movementCommand,x(l?.source.props).moveCommand);g&&we(g,{actorEntityId:l?.entityId||p(t.playerEntityId),actorEntityKey:l?.entityId||p(t.playerEntityId),directionX:d[0],directionY:d[1],scalar:1},e,a);return}const u=r.key===" "?p(t.actionCommand,x(l?.source.props).actionCommand):r.key.toLowerCase()==="f"?p(t.focusCommand,x(l?.source.props).focusCommand):"";u&&(r.preventDefault(),we(u,{actionId:r.key===" "?"0":"focus",actorEntityId:l?.entityId||p(t.playerEntityId),actorEntityKey:l?.entityId||p(t.playerEntityId)},e,a))}),c}function we(e,t,n,i){i.commandSink?.(rn(e,t,i),n)}function rn(e,t,n=O){return ae(e,{action:t},n)}function on(e){switch(e.toLowerCase()){case"w":case"arrowup":return[0,1];case"s":case"arrowdown":return[0,-1];case"a":case"arrowleft":return[-1,0];case"d":case"arrowright":return[1,0];default:return}}function an(e){return e.includes("station")?"S":e.includes("projectile")?".":e.includes("ship")?"^":"+"}function qe(e){return e.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}function X(e,t){const n=Number(e);return Number.isFinite(n)?n:t}function cn(e,t){if(Array.isArray(e)){const n=e.map(i=>Number(i));if(n.length>=3&&n.slice(0,3).every(Number.isFinite))return[n[0],n[1],n[2]]}if(typeof e=="string"){const n=e.split(/[,\s]+/).map(i=>Number(i)).filter(Number.isFinite);if(n.length>=3)return[n[0],n[1],n[2]]}return t}function sn(e,t,n,i){const a=Le(t.active),c=m("section","cultui-inventory-drag");w(c,e),S(c,n,i),c.dataset.active=a?"true":"false";const s=m("div","cultui-inventory-section-label","Drag");if(S(s,k(n,"sectionLabel."),k(i,"sectionLabel.")),c.append(s),!a){const d=m("div","cultui-inventory-empty","None");return S(d,k(n,"empty."),k(i,"empty.")),c.append(d),c}const l=p(t.itemKey,t.item,"item"),f=m("div","cultui-inventory-drag-chip",l);S(f,k(n,"dragChip."),k(i,"dragChip.")),c.append(f);const o=[t.originOffsetX,t.originOffsetY].map(d=>Number(d)).map(d=>Number.isFinite(d)?d:0),r=m("div","cultui-inventory-meta",`origin ${o[0]}, ${o[1]}`);return S(r,k(n,"meta."),k(i,"meta.")),c.append(r),c}function ln(e,t,n,i,a){const c=m("section","cultui-inventory-grid");w(c,e),S(c,n,i);const s=$(p(t.columns,t.gridColumns,t.widthCells,""),0),l=s>0?s:6,f=$(t.rows,0),o=f>0?f:Math.max(3,Math.ceil(Math.max((e.children||[]).length,1)/l));c.style.setProperty("--inventory-columns",String(l)),c.style.setProperty("--inventory-rows",String(o)),c.dataset.cellSpriteMode=h(t.cellSpriteMode,"");const r=p(t.title,t.label,"Inventory"),d=m("div","cultui-inventory-section-label",r);S(d,k(n,"sectionLabel."),k(i,"sectionLabel.")),c.append(d);const u=m("div","cultui-inventory-board");u.style.display="grid",u.style.gridTemplateColumns=`repeat(${l}, ${R(p(t.cellSize,"72"))})`,u.style.gridTemplateRows=`repeat(${o}, ${R(p(t.cellSize,"72"))})`,u.style.gap=R(p(t.cellGap,"4")),u.style.overflow=p(t.boardOverflow,"auto"),u.style.padding=R(p(t.boardPadding,"4")),S(u,k(n,"board."),k(i,"board.")),u.addEventListener("dragover",b=>{un(t)&&(b.preventDefault(),b.dataTransfer&&(b.dataTransfer.dropEffect="move"))}),u.addEventListener("drop",b=>{const v=b.dataTransfer?.getData("application/vnd.gamecult.eve.inventory-item+json")||"";if(!v)return;let C;try{C=JSON.parse(v)}catch{return}const E=u.getBoundingClientRect(),D=Math.max(1,X(t.cellSize,72)),V=Math.max(0,X(t.cellGap,4)),W=D+V,J=Math.max(0,Math.min(l-1,Math.floor((b.clientX-E.left)/W))),Z=Math.max(0,Math.min(o-1,Math.floor((b.clientY-E.top)/W))),z=fn(C,t,J,Z,a);z&&(b.preventDefault(),a.commandSink?.(z,e))});const g=new Set;for(const b of e.children||[]){const v=x(b.props),C=$(v.x,0),E=$(v.y,0);g.add(`${C}:${E}`),u.append(L(b,a))}const y=Math.min(l*o,256);for(let b=0;b{!c.draggable||!y.dataTransfer||(y.dataTransfer.effectAllowed="move",y.dataTransfer.setData("application/vnd.gamecult.eve.inventory-item+json",JSON.stringify(t)))});let f=$(t.shapeWidth,1),o=$(t.shapeHeight,1);const r=p(t.rotation,"").toLowerCase();["clockwise","counterclockwise","right","left","rotate90","rotate270"].includes(r)&&([f,o]=[o,f]),c.style.gridColumn=`${s+1} / span ${f}`,c.style.gridRow=`${l+1} / span ${o}`;const d=m("span","cultui-inventory-item-icon");S(d,k(n,"icon."),k(i,"icon.")),d.textContent=Tn(p(t.iconAssetUri,t.iconAssetKey,t.itemKey,t.label,"")),c.append(d);const u=p(t.label,t.itemKey,"");if(u){const y=m("span","cultui-inventory-item-label",u);S(y,k(n,"label."),k(i,"label.")),c.append(y)}const g=Number(t.quantity);if(Number.isFinite(g)&&g>1){const y=m("span","cultui-inventory-item-quantity",String(g));S(y,k(n,"quantity."),k(i,"quantity.")),c.append(y)}return c.title=[u,p(t.source,""),p(t.quality,"")?`quality ${t.quality}`:"",p(t.durability,"")?`durability ${t.durability}`:""].filter(Boolean).join(" | "),c}function un(e){return Object.entries(e).some(([t,n])=>(t==="dropCommand"||t.startsWith("dropCommand."))&&typeof n=="string"&&n.length>0)}function fn(e,t,n,i,a=O){const c=p(e.sourceKind,e.source,""),s=p(t[`dropCommand.${c}`],t.dropCommand,"");if(!c||!s)return;const l=X(e.sourceIndex,-1),f=X(t.targetIndex,-1),o=p(t.targetKind,""),r={sourceKind:c,originEntityKey:p(e.sourceEntityKey,e.entityKey,""),originIndex:l,originCargoIndex:c==="cargo"?l:-1,itemKey:p(e.itemKey,""),quantity:Math.max(1,X(e.quantity,1)),sourceX:X(e.x,-2147483648),sourceY:X(e.y,-2147483648),destinationKind:o,destinationEntityKey:p(t.targetEntityKey,t.entityKey,""),destinationIndex:f,destinationCargoIndex:o==="cargo"?f:-1,destinationX:Math.trunc(n),destinationY:Math.trunc(i),hasDestinationPosition:!0};return ae(s,{action:r},a)}function mn(e,t,n){const i=m("section","cultui-binding-map");w(i,e);const a=document.createElementNS("http://www.w3.org/2000/svg","svg");a.setAttribute("class","cultui-xbox-controller"),a.setAttribute("viewBox","0 0 780 420"),a.setAttribute("role","img"),a.setAttribute("aria-label",h(t.label,"Xbox controller remapping")),a.innerHTML=hn(),i.append(a);const c=m("div","cultui-binding-overlay");for(const s of e.children||[]){const l=x(s.props),f=h(l.target,s.id||""),o=m("button","cultui-binding-box");w(o,s),o.type="button",o.dataset.target=f,o.dataset.kind=h(l.bindingKind,"button"),o.style.left=R(l.x??"50%"),o.style.top=R(l.y??"50%"),o.append(m("span","cultui-binding-target",h(l.label,f))),o.append(m("span","cultui-binding-source",h(l.current,"unmapped"))),o.addEventListener("click",()=>{const d=rt(s);if(it(s)||d?.documentId)ot(Ie(s,n),n);else{const u=h(l.commandId,"");u&&n.commandSink?.(ae(u,l,n),s)}}),c.append(o);const r=document.createElementNS("http://www.w3.org/2000/svg","line");r.setAttribute("class","cultui-binding-line"),r.setAttribute("x1",h(l.anchorX,"390")),r.setAttribute("y1",h(l.anchorY,"210")),r.setAttribute("x2",String(je(l.x,780))),r.setAttribute("y2",String(je(l.y,420))),a.append(r)}return i.append(c),i}function it(e){for(const t of e.embeddedDocuments||[]){const n=x(t.surface);if(n.root)return n}}function rt(e){const t=(e.embeddedDocuments||[])[0],n=x(e.props),i=p(n.documentId,t?.documentId,"");if(i)return{documentId:i,presentationKind:p(n.presentationKind,t?.presentationKind,""),schemaId:p(n.schemaId,t?.schemaId,""),slotId:p(n.slotId,t?.slotId,"")}}async function Ie(e,t){const n=it(e);if(n)return n;const i=rt(e);if(!i?.documentId||!t.documentResolver)return;const a=await t.documentResolver(i,e);if(a)return x(a.surface).root?a.surface:a}function ot(e,t){const n=m("div","cultui-modal-backdrop"),i=m("section","cultui-modal");i.setAttribute("role","dialog"),i.setAttribute("aria-modal","true");const a=m("header","cultui-modal-header");a.append(m("h2","","Configure Binding"));const c=m("button","cultui-modal-close","Close");c.type="button",c.addEventListener("click",()=>n.remove()),a.append(c);const s=m("div","cultui-modal-body");i.append(a,s),n.append(i),n.addEventListener("click",l=>{l.target===n&&n.remove()}),document.body.append(n),s.append(m("div","detail","materializing document")),Promise.resolve(e).then(l=>{a.querySelector("h2").textContent=l?.title||"Configure Binding",s.replaceChildren(l?.root?L(l.root,t):Y("Embedded document unavailable"))}).catch(l=>{s.replaceChildren(Y(`Embedded document failed: ${l instanceof Error?l.message:String(l)}`))})}function pn(e,t,n,i,a){const c=x(e.props),s=(e.children||[])[0],l=x(s?.props),f=p(l.anchor,c.anchor,"trigger"),o=p(l.placement,c.placement,"below-start"),r=Number(p(l.offsetX,c.offsetX,"0"))||0,d=Number(p(l.offsetY,c.offsetY,"4"))||0,u=m("div","cultui-modal-backdrop");u.style.background="transparent",u.style.placeItems="start";const g=m("section","cultui-modal");g.setAttribute("role","dialog"),g.setAttribute("aria-modal","true"),g.style.position="fixed",g.style.width="min(420px, calc(100vw - 24px))",g.style.maxHeight="min(620px, calc(100vh - 24px))";const y=m("header","cultui-modal-header");y.append(m("h2","",p(l.title,c.title,c.label,"Options")));const b=m("button","cultui-modal-close","Close");b.type="button",b.addEventListener("click",()=>u.remove()),y.append(b);const v=m("div","cultui-modal-body");if(s){const E=s.children||[];E.length>0?v.replaceChildren(...E.map(D=>L(D,t))):v.append(L(s,t))}else v.append(Y("Popup has no content"));g.append(y,v),u.append(g),u.addEventListener("click",E=>{E.target===u&&u.remove()}),document.body.append(u);const C=gn(f,o,n,g,i,a,r,d);g.style.left=`${C.left}px`,g.style.top=`${C.top}px`}function gn(e,t,n,i,a,c,s,l){const f=n.getBoundingClientRect(),o=i.getBoundingClientRect(),r=o.width||420,d=o.height||320,u=e==="cursor"?{left:a,right:a,top:c,bottom:c}:f;if(t==="right-down"||t==="dropdown")return de(u,r,d,s,l,"right","down");if(t==="left-down")return de(u,r,d,s,l,"left","down");if(t==="right-up")return de(u,r,d,s,l,"right","up");if(t==="left-up")return de(u,r,d,s,l,"left","up");switch(t){case"above-start":return q(u.left+s,u.top-d-l,r,d);case"above-end":return q(u.right-r+s,u.top-d-l,r,d);case"below-end":return q(u.right-r+s,u.bottom+l,r,d);case"right-start":return q(u.right+s,u.top+l,r,d);case"left-start":return q(u.left-r-s,u.top+l,r,d);case"center":return q((window.innerWidth-r)/2+s,(window.innerHeight-d)/2+l,r,d);default:return q(u.left+s,u.bottom+l,r,d)}}function de(e,t,n,i,a,c,s){const f=window.innerWidth-e.right-i-12,o=e.left-i-12,r=window.innerHeight-e.top-a-12,d=e.bottom-a-12,u=c==="right"?f>=t||f>=o:!(o>=t||o>=f),g=s==="down"?r>=n||r>=d:!(d>=n||d>=r),y=u?e.right+i:e.left-t-i,b=g?e.top+a:e.bottom-n-a;return q(y,b,t,n)}function q(e,t,n,i){return{left:Oe(e,12,window.innerWidth-n-12),top:Oe(t,12,window.innerHeight-i-12)}}function Oe(e,t,n){return n + + + + + + + + + + + + + + + + + YBXA + `}function yn(e,t=document.body){const n=ke(e),i=document.documentElement.style;wn(n.assets.fontCss);for(const[o,r]of Object.entries(Zt))i.setProperty(o,r);const a={colorBackground:"--bg",colorBackgroundTop:"--bg-top",colorBackgroundMid:"--bg-mid",colorBackgroundBottom:"--bg-bottom",colorShellSurfaceTop:"--shell-top",colorShellSurfaceBottom:"--shell-bottom",colorPanel:"--panel",colorPanelAlt:"--panel-2",colorPanelBorder:"--line",colorPanelBorderDeep:"--line-deep",colorText:"--text",colorTextBright:"--text-bright",colorMuted:"--quiet",colorAccent:"--accent",colorAccentStrong:"--accent-strong",colorCornerAccent:"--corner-accent",colorLink:"--cyan",colorShadow:"--shadow",colorPixelGrid:"--pixel-grid"};for(const[o,r]of Object.entries(a)){const d=n.tokens[o];d!==void 0&&i.setProperty(r,String(d))}const c=n.tokens.fontBody,s=n.tokens.fontDisplay,l=n.tokens.fontTitle,f=n.tokens.fontMono;c&&i.setProperty("--font-body",fe(String(c))),s&&i.setProperty("--font-title",fe(String(s))),l&&i.setProperty("--font-title",fe(String(l))),f&&i.setProperty("--font-mono",fe(String(f))),n.tokens.borderWidthPx&&i.setProperty("--border-width",`${n.tokens.borderWidthPx}px`),n.tokens.borderBottomWidthPx&&i.setProperty("--border-bottom-width",`${n.tokens.borderBottomWidthPx}px`),n.tokens.cornerAccentPx&&i.setProperty("--corner-accent-size",`${n.tokens.cornerAccentPx}px`),t.dataset.pixelArt=n.tokens.pixelArt||n.tokens.imageRendering==="pixelated"?"true":"false",t.dataset.scanlines=n.tokens.scanlineOverlay?"true":"false"}function ae(e,t={},n=O){const i=x(t.action),a=n.provider?.providerId||oe?.providerId||"surface unknown",c=n.activeSurfaceId||oe?.surface?.id||n.provider?.surfaces?.[0]?.surfaceId||a,s=bn(n,c),l=p(s.commandBoundary,t.commandBoundary,i.commandBoundary,i.target),f=p(s.receiptSchema,t.receiptSchema,i.receiptSchema),o={type:"surface-command",schema:"gamecult.eve.command_invocation.v1",providerId:a,surfaceId:c,command:e||h(i.type,"invoke"),payload:{...i,transport:t.transport??null},issuedAt:new Date().toISOString(),clientId:n.clientId||"eve.browser"};return l&&(o.commandBoundary=l),f&&(o.receiptSchema=f),o}function bn(e,t){const n=[...e.provider?.surfaces||[],...e.provider?.localAdvertisement?.surfaces||[]];return n.find(i=>i.surfaceId===t&&i.worldInteraction)?.worldInteraction||n.find(i=>i.worldInteraction)?.worldInteraction||{}}function We(e,t){const n=x(e.action);return h(e.command,h(e.commandId,h(n.command,h(n.target,h(n.type,t?.commandId||"")))))}function Y(e){const t=m("section","pane");return t.append(m("h2","","No Surface")),t.append(m("div","detail",e)),t}function ze(e,t,n,i,a){e.dataset.commandId=n,e.tabIndex=e instanceof HTMLButtonElement?e.tabIndex:0;const c=()=>{const s=ae(n,i,a);a.commandSink?.(s,t)};e.addEventListener("click",c),e.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),c())})}function vn(e,t,n){const i=xn(e,t),a=x(i.find(u=>u.kind==="control.box")?.props),c=i.filter(u=>u.kind==="control.part"),s=Number(e.min??0),l=Number(e.max??1),f=m("div","cultui-slider");f.dataset.skin=h(e.skin,"default"),f.dataset.bind=h(e.bind,""),_n(f,a);const o=m("div","cultui-slider-visual"),r=m("input","cultui-slider-input");r.type="range",r.min=String(s),r.max=String(l),r.step=String(e.step??.01),r.setAttribute("aria-label",h(e.bind,"slider"));for(const u of c){const g=x(u.props),y=m("span",`cultui-slider-part ${h(g.name,"part")}`);En(y,g),o.append(y)}return c.some(u=>x(u.props).name==="track")||o.append(m("span","cultui-slider-part track")),c.some(u=>x(u.props).name==="fill")||o.append(m("span","cultui-slider-part fill")),c.some(u=>x(u.props).name==="thumb")||o.append(m("span","cultui-slider-part thumb")),f.append(o,r),(u=>{const g=Number(u??s),y=Math.max(s,Math.min(l,Number.isFinite(g)?g:s)),b=l===s?0:(y-s)/(l-s)*100;r.value=String(y),f.style.setProperty("--cultui-slider-value",`${b}%`),f.dataset.value=String(y)})(e.value??s),r.addEventListener("input",()=>{const u=ae(h(e.command,"control.slider.input"),{...e,action:{...x(e.action),value:Number(r.value)},value:Number(r.value)},n);n.commandSink?.(u,{kind:"control.slider",props:e})}),f}function xn(e,t){const n=typeof e.skin=="string"?e.skin:"",a=[...n?Qe.controlSkins[n]?.children||[]:[],...t];return a.length?a:[{kind:"control.box",props:{height:18,overflow:"visible"}},{kind:"control.part",props:{name:"track",anchor:"center",size:["100%",6],radius:2,fill:"color.panelInset"}},{kind:"control.part",props:{name:"fill",anchor:["left","center"],size:["value%",6],radius:2,fill:"color.accent"}},{kind:"control.part",props:{name:"thumb",anchor:["value","center"],size:[12,12],bleed:3,radius:999,fill:"color.accent"}}]}function ke(e){if(Array.isArray(e)){const t={},n={};for(const i of e)i?.name&&(i.name==="font.web.google"&&typeof i.value=="string"?n.fontCss=i.value:t[i.name]=i.value);return{tokens:t,assets:n,controlSkins:{}}}return{tokens:x(e?.tokens),assets:x(e?.assets),controlSkins:x(e?.controlSkins)}}function ie(e){if(!e)return"";const t=O.assetUrlResolver;return t?t(e,oe):/^(https?:|data:|blob:)/i.test(e)?e:O.assetBaseUrl&&e.startsWith("/")?`${O.assetBaseUrl.replace(/\/+$/,"")}${e}`:e}function wn(e){const t=typeof e=="string"?e.trim():"";if(le?.dataset.href===t||(le?.remove(),le=void 0,!t))return;const n=document.createElement("link");n.rel="preconnect",n.href="https://fonts.gstatic.com",n.crossOrigin="anonymous",document.head.append(n);const i=document.createElement("link");i.rel="stylesheet",i.href=t,i.dataset.href=t,document.head.append(i),le=i}function Sn(e,t,n){const i=[];return(e==="text.title"||t.role==="title")&&i.push("cultui-title","eve-text-title"),e==="text.subtitle"&&i.push("eve-text-subtitle"),e==="label"&&i.push("cultui-label"),t.role==="mono"&&i.push("detail","mono"),i.length===0&&i.push("detail","eve-text"),i.join(" ")}function _n(e,t){t.height!==void 0&&(e.style.minHeight=R(t.height)),t.width!==void 0&&(e.style.width=R(t.width)),typeof t.overflow=="string"&&(e.style.overflow=t.overflow)}function En(e,t){const n=Array.isArray(t.size)?t.size:[t.size,void 0];n[0]!==void 0&&n[0]!=="value%"&&(e.style.width=R(n[0])),n[1]!==void 0&&(e.style.height=R(n[1])),t.radius!==void 0&&(e.style.borderRadius=R(t.radius)),t.fill!==void 0&&(e.style.background=pe(String(t.fill))),t.bleed!==void 0&&e.style.setProperty("--part-bleed",R(t.bleed)),(Array.isArray(t.anchor)?t.anchor:[t.anchor]).includes("value")&&(e.dataset.anchorValue="true")}function ue(e,t){t.gap!==void 0&&(e.style.gap=R(t.gap)),t.padding!==void 0&&(e.style.padding=R(t.padding)),t.size!==void 0&&(e.style.flex=An(t.size)),t.min!==void 0&&(e.style.minWidth=R(t.min)),t.max!==void 0&&(e.style.maxWidth=R(t.max)),t.align!==void 0&&(e.style.alignItems=t.align==="end"?"flex-end":String(t.align)),(t.clip==="true"||t.clip===!0)&&(e.style.overflow="hidden"),t.scroll==="y"&&(e.style.overflowY="auto"),t.scroll==="x"&&(e.style.overflowX="auto")}function An(e){return typeof e=="string"&&e.endsWith("fr")?`${Number(e.slice(0,-2))||1} 1 0`:e==="auto"||e==="content"?"0 0 auto":`0 0 ${R(e)}`}function R(e){return Array.isArray(e)?e.map(R).join(" "):typeof e=="number"?`${e}px`:typeof e=="string"&&/^-?\d+(\.\d+)?$/.test(e)?`${e}px`:String(e??"")}function pe(e){return{"color.accent":"var(--accent)","color.panelInset":"rgba(0, 0, 0, 0.34)","color.panel":"var(--panel)","color.text":"var(--text)"}[e]||e}function fe(e){return e.includes("Zen Kaku Gothic New")||e.includes("M PLUS 1")?e:e.includes("Montserrat")?`${e}, "Zen Kaku Gothic New", "M PLUS 1", "Noto Sans JP", "Hiragino Sans", "Yu Gothic", sans-serif`:e.includes("Ubuntu")?`${e}, "M PLUS 1", "Noto Sans JP", "Hiragino Sans", "Yu Gothic", sans-serif`:`${e}, "Noto Sans JP", "Hiragino Sans", "Yu Gothic", sans-serif`}function w(e,t){t.id&&(e.id=t.id),t.id&&(e.dataset.eveNodeId=t.id),t.kind&&(e.dataset.eveKind=t.kind)}function x(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function In(e){return Array.isArray(e)?e:[]}function Cn(e){return In(e).map((t,n)=>nt({kind:"list.item",props:x(t)}))}function h(e,t){return e==null?t:String(e)}function p(...e){for(const t of e){if(typeof t=="string"&&t.trim())return t;if(typeof t=="number"&&Number.isFinite(t))return String(t)}return""}function Le(e){return typeof e=="boolean"?e:typeof e=="number"?e!==0:typeof e=="string"?["1","true","yes","on"].includes(e.trim().toLowerCase()):!1}function $(e,t){const n=Number(e);return Number.isFinite(n)?Math.max(0,Math.floor(n)):t}function Tn(e){const t=e.toLowerCase();return t.includes("sensor")?"S":t.includes("thermal")?"T":t.includes("fuel")?"F":t.includes("cargo")?"C":t.includes("weapon")?"W":e.trim().slice(0,1).toUpperCase()||"?"}function Rn(e){const t=e.trim().split(/\s+/).filter(Boolean);return t.length&&t.slice(0,2).map(n=>n[0]?.toUpperCase()||"").join("")||"?"}function Ke(e){const t=Number(e);return Number.isFinite(t)?Math.max(0,Math.min(100,t)):0}function m(e,t="",n=""){const i=document.createElement(e);return t&&(i.className=t),n&&(i.textContent=n),i}const Ge=document.querySelector("#surface"),N=document.querySelector("#status"),j=document.querySelector("#receipt"),kn=document.querySelector("#compiler"),Fe=document.querySelector("#composer"),ge=document.querySelector("#destination-form"),Ce=document.querySelector("#compiler-results"),Ln=document.querySelector("#campaign-lab"),Xe=document.querySelector("#campaign-list");let H=0,re=0,at=0,he=[];async function U(){const e=await fetch("/api/surface");if(e.status===401){N.textContent="This laboratory requires an unused invite link.";return}const t=await e.json(),n=t.surface_id==="ghostlight.compiler";if(kn.hidden=!n,Fe.hidden=n,ge.hidden=n,Ge.hidden=n,Ln.hidden=n,n){N.textContent="No campaign exists. Retrieve the Vault and approve a world seed.";return}H=Number(t.world_revision??t.version??0),re=Number(t.resolution?.policy?.resolution_epoch??0),at=Number(t.resolution?.policy?.provider_configuration_epoch??0),he=t.resolution?.pins??[];const i=Number(t.resolution?.policy?.active_cell_budget??8),a=document.querySelector("#active-cell-budget");a.value=String(i),document.querySelector("#active-cell-budget-value").value=String(i),document.querySelector("#resolution-status").textContent=`${t.resolution?.effective_budget??i} effective cells · ${t.resolution?.mandatory_overage??0} temporary overage · epoch ${re}`;const c=Number(t.resolution?.policy?.provider_parallelism??8);document.querySelector("#provider-parallelism").value=String(c),document.querySelector("#provider-parallelism-value").value=String(c);const s=document.querySelector("#pin-list");s.innerHTML=he.map(o=>`

${o.kind} ${[...o.subject_ids].join(", ")} — ${o.reason}

`).join("")||"

No persistent pins.

",s.querySelectorAll("[data-remove-pin]").forEach(o=>o.addEventListener("click",async()=>{await ne({type:"replace_resolution_pins",expected_revision:H,expected_resolution_epoch:re,pins:he.filter(r=>r.id!==o.dataset.removePin)})}));const l=document.querySelector("#fission-parent");l.innerHTML=(t.resolution?.fission_targets??[]).map(o=>``).join(""),document.querySelector("#fission-form").hidden=l.options.length===0,et(t,Ge,{body:document.body,clientId:"ghostlight.browser",statusElement:N});const f=await fetch("/api/campaigns").then(o=>o.json());Xe.innerHTML=f.campaigns.map(o=>``).join(""),Xe.querySelectorAll("button:not(:disabled)").forEach(o=>o.addEventListener("click",async()=>{await B(`/api/campaigns/select/${o.dataset.campaignId}`,{}),await U()}))}async function B(e,t){N.textContent="Retrieving evidence and compiling…";const n=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),i=n.headers.get("content-type")?.includes("json")?await n.json():await n.text();if(!n.ok)throw N.textContent=typeof i=="string"?i:"Compilation failed",new Error(N.textContent);return i}function Ye(e,t,n){Ce.innerHTML=`
${e.map((i,a)=>`

${i.title??i.name}

${i.player_hook??i.premise}

${i.era?`${i.era} · ${i.place} · ${i.pressure}`:""}

`).join("")}
`,Ce.querySelectorAll("button").forEach(i=>i.addEventListener("click",()=>n(e[Number(i.dataset.index)])))}document.querySelector("#suggest-form").addEventListener("submit",async e=>{e.preventDefault();const t=await B("/api/compiler/openings",{setting:document.querySelector("#setting").value,constraints:[]});Ye(t.openings,"Choose opening",async n=>{const i=await B("/api/compiler/roles",n);Ye(i.roles,"Choose role",async a=>ct(await B("/api/compiler/selected",{campaign_name:n.title,opening:n,role:a})))})});document.querySelector("#custom-form").addEventListener("submit",async e=>{e.preventDefault(),await ct(await B("/api/compiler/custom",Object.fromEntries(new FormData(e.currentTarget))))});async function ct(e){const t=e.preview;Ce.innerHTML=`

${t.title}

${t.campaign.transcript?.[0]?.text??""}

${Object.keys(t.campaign.locations).length} locations · ${Object.keys(t.campaign.actors).length} actors · ${Object.keys(t.campaign.institutions).length} institutions

${t.gaps.length?`Material gaps: ${t.gaps.join("; ")}`:"No declared material gaps."}

Branch assumptions: ${t.branch_assumptions.join("; ")||"none"}

`,document.querySelector("#approve-world").addEventListener("click",async()=>{await B(`/api/compiler/approve/${e.preview_id}`,{}),await U()}),N.textContent="Preview compiled. Nothing has entered world state yet."}async function ne(e){N.textContent="The world is considering the command…";const t=await fetch("/api/command",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)}),n=await t.json();return j.hidden=!1,j.textContent=JSON.stringify(n,null,2),t.ok?(await U(),n):(N.textContent=n.error??"The command was refused.",await U(),n)}function st(e){if(e?.kind!=="assessed")return;const t=document.createElement("button");t.type="button",t.textContent=e.assessment.admissible?"Confirm server roll":"Revise attempt",t.addEventListener("click",async()=>{if(!e.assessment.admissible){document.querySelector("#attempt").focus();return}const n=await ne({type:"attempt",assessment_digest:e.assessment.digest});t.remove(),st(n)}),Fe.append(t)}Fe.addEventListener("submit",async e=>{e.preventDefault();const t=document.querySelector("#attempt").value.trim();t&&st(await ne({type:"assess",expected_revision:H,intent:{actor_id:"player",description:t,intended_effect:t}}))});document.querySelector("#wait").addEventListener("click",()=>{ne({type:"wait",expected_revision:H,minutes:60})});document.querySelector("#active-cell-budget").addEventListener("input",e=>{document.querySelector("#active-cell-budget-value").value=e.currentTarget.value});document.querySelector("#resolution-form").addEventListener("submit",async e=>{e.preventDefault(),await ne({type:"set_resolution_budget",expected_revision:H,expected_resolution_epoch:re,active_cell_budget:Number(document.querySelector("#active-cell-budget").value)})});document.querySelector("#provider-parallelism").addEventListener("input",e=>{document.querySelector("#provider-parallelism-value").value=e.currentTarget.value});document.querySelector("#provider-parallelism-form").addEventListener("submit",async e=>{e.preventDefault(),N.textContent="Applying the provider concurrency limit…";const t=await fetch("/api/operator/provider-parallelism",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({expected_provider_configuration_epoch:at,provider_parallelism:Number(document.querySelector("#provider-parallelism").value)})}),n=await t.json();j.hidden=!1,j.textContent=JSON.stringify(n,null,2),t.ok||(N.textContent=n.error??"The operator limit was refused."),await U()});document.querySelector("#pin-form").addEventListener("submit",async e=>{e.preventDefault();const t=new FormData(e.currentTarget),n=String(t.get("subject_ids")??"").split(",").map(a=>a.trim()).filter(Boolean),i={schema:"ghostlight.resolution_pin.v1",id:`pin:${crypto.randomUUID()}`,kind:String(t.get("kind")),subject_ids:n,reason:String(t.get("reason")??"").trim(),created_world_revision:H};await ne({type:"replace_resolution_pins",expected_revision:H,expected_resolution_epoch:re,pins:[...he,i]})});ge.addEventListener("submit",async e=>{e.preventDefault();const t=await B("/api/compiler/destination",Object.fromEntries(new FormData(ge))),n=t.preview;j.hidden=!1,j.textContent=JSON.stringify(n,null,2),N.textContent="Destination preview compiled; topology is unchanged until approval.";const i=document.createElement("button");i.textContent="Approve destination",i.addEventListener("click",async()=>{await B(`/api/compiler/destination/approve/${t.preview_id}`,{}),i.remove(),await U()}),ge.append(i)});document.querySelector("#fission-form").addEventListener("submit",async e=>{e.preventDefault();const t=new FormData(e.currentTarget),n=await B("/api/compiler/gestalt/fission",{parent_gestalt_id:t.get("parent_gestalt_id"),partition_axis:t.get("partition_axis"),requested_partition_values:String(t.get("requested_partition_values")??"").split(",").map(a=>a.trim()).filter(Boolean),reason:t.get("reason")});j.hidden=!1,j.textContent=JSON.stringify(n.preview,null,2),N.textContent="Fission preview compiled. Canonical leaves are unchanged until approval.";const i=document.createElement("button");i.type="button",i.textContent="Approve population fission",i.addEventListener("click",async()=>{await B(`/api/compiler/gestalt/fission/approve/${n.preview_id}`,{}),i.remove(),await U()}),e.currentTarget.append(i)});document.querySelector("#fork-form").addEventListener("submit",async e=>{e.preventDefault(),await B("/api/campaigns/fork",Object.fromEntries(new FormData(e.currentTarget))),await U()});document.querySelector("#reset-form").addEventListener("submit",async e=>{e.preventDefault(),await B("/api/campaigns/reset",Object.fromEntries(new FormData(e.currentTarget))),await U()});document.querySelector("#load-operator").addEventListener("click",async()=>{const t=await(await fetch("/api/operator")).json();et(t,document.querySelector("#operator-output"),{body:document.body,clientId:"ghostlight.operator",statusElement:N})});U(); diff --git a/web/dist/index.html b/web/dist/index.html index 5e528d7..d1c7029 100644 --- a/web/dist/index.html +++ b/web/dist/index.html @@ -1,6 +1,6 @@ -GhostlightDungeon - +GhostlightDungeon +

STARFIRE / PRIVATE VERSE

GhostlightDungeon

Reading the world…

- +
diff --git a/web/index.html b/web/index.html index e696d5c..8ceed2a 100644 --- a/web/index.html +++ b/web/index.html @@ -7,5 +7,9 @@
- + diff --git a/web/src/main.ts b/web/src/main.ts index e3a97c6..91acb31 100644 --- a/web/src/main.ts +++ b/web/src/main.ts @@ -12,6 +12,9 @@ const compilerResults = document.querySelector("#compiler-results") const campaignLab = document.querySelector("#campaign-lab")!; const campaignList = document.querySelector("#campaign-list")!; let revision = 0; +let resolutionEpoch = 0; +let providerConfigurationEpoch = 0; +let resolutionPins: any[] = []; async function refresh() { const response = await fetch("/api/surface"); @@ -20,7 +23,26 @@ async function refresh() { const needsCompilation = surface.surface_id === "ghostlight.compiler"; compiler.hidden = !needsCompilation; composer.hidden = needsCompilation; destinationForm.hidden = needsCompilation; host.hidden = needsCompilation; campaignLab.hidden = needsCompilation; if (needsCompilation) { status.textContent = "No campaign exists. Retrieve the Vault and approve a world seed."; return; } - revision = Number(surface.version ?? 0); + revision = Number(surface.world_revision ?? surface.version ?? 0); + resolutionEpoch = Number(surface.resolution?.policy?.resolution_epoch ?? 0); + providerConfigurationEpoch = Number(surface.resolution?.policy?.provider_configuration_epoch ?? 0); + resolutionPins = surface.resolution?.pins ?? []; + const budget = Number(surface.resolution?.policy?.active_cell_budget ?? 8); + const budgetInput = document.querySelector("#active-cell-budget")!; + budgetInput.value = String(budget); + document.querySelector("#active-cell-budget-value")!.value = String(budget); + document.querySelector("#resolution-status")!.textContent = `${surface.resolution?.effective_budget ?? budget} effective cells · ${surface.resolution?.mandatory_overage ?? 0} temporary overage · epoch ${resolutionEpoch}`; + const providerParallelism = Number(surface.resolution?.policy?.provider_parallelism ?? 8); + document.querySelector("#provider-parallelism")!.value = String(providerParallelism); + document.querySelector("#provider-parallelism-value")!.value = String(providerParallelism); + const pinList = document.querySelector("#pin-list")!; + pinList.innerHTML = resolutionPins.map(pin => `

${pin.kind} ${[...pin.subject_ids].join(", ")} — ${pin.reason}

`).join("") || "

No persistent pins.

"; + pinList.querySelectorAll("[data-remove-pin]").forEach(button => button.addEventListener("click", async () => { + await send({ type: "replace_resolution_pins", expected_revision: revision, expected_resolution_epoch: resolutionEpoch, pins: resolutionPins.filter(pin => pin.id !== button.dataset.removePin) }); + })); + const fissionParent = document.querySelector("#fission-parent")!; + fissionParent.innerHTML = (surface.resolution?.fission_targets ?? []).map((target: any) => ``).join(""); + document.querySelector("#fission-form")!.hidden = fissionParent.options.length === 0; renderEveSurface(surface, host, { body: document.body, clientId: "ghostlight.browser", statusElement: status }); const campaigns = await fetch("/api/campaigns").then(response => response.json()); campaignList.innerHTML = campaigns.campaigns.map((item: any) => ``).join(""); @@ -84,7 +106,75 @@ composer.addEventListener("submit", async event => { installAssessment(await send({ type: "assess", expected_revision: revision, intent: { actor_id: "player", description: text, intended_effect: text } })); }); document.querySelector("#wait")!.addEventListener("click", () => void send({ type: "wait", expected_revision: revision, minutes: 60 })); +document.querySelector("#active-cell-budget")!.addEventListener("input", event => { + document.querySelector("#active-cell-budget-value")!.value = (event.currentTarget as HTMLInputElement).value; +}); +document.querySelector("#resolution-form")!.addEventListener("submit", async event => { + event.preventDefault(); + await send({ + type: "set_resolution_budget", + expected_revision: revision, + expected_resolution_epoch: resolutionEpoch, + active_cell_budget: Number(document.querySelector("#active-cell-budget")!.value), + }); +}); +document.querySelector("#provider-parallelism")!.addEventListener("input", event => { + document.querySelector("#provider-parallelism-value")!.value = (event.currentTarget as HTMLInputElement).value; +}); +document.querySelector("#provider-parallelism-form")!.addEventListener("submit", async event => { + event.preventDefault(); + status.textContent = "Applying the provider concurrency limit…"; + const response = await fetch("/api/operator/provider-parallelism", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + expected_provider_configuration_epoch: providerConfigurationEpoch, + provider_parallelism: Number(document.querySelector("#provider-parallelism")!.value), + }), + }); + const body = await response.json(); + receipt.hidden = false; + receipt.textContent = JSON.stringify(body, null, 2); + if (!response.ok) status.textContent = body.error ?? "The operator limit was refused."; + await refresh(); +}); +document.querySelector("#pin-form")!.addEventListener("submit", async event => { + event.preventDefault(); + const data = new FormData(event.currentTarget as HTMLFormElement); + const subjectIds = String(data.get("subject_ids") ?? "").split(",").map(value => value.trim()).filter(Boolean); + const pin = { + schema: "ghostlight.resolution_pin.v1", + id: `pin:${crypto.randomUUID()}`, + kind: String(data.get("kind")), + subject_ids: subjectIds, + reason: String(data.get("reason") ?? "").trim(), + created_world_revision: revision, + }; + await send({ type: "replace_resolution_pins", expected_revision: revision, expected_resolution_epoch: resolutionEpoch, pins: [...resolutionPins, pin] }); +}); destinationForm.addEventListener("submit",async event=>{event.preventDefault();const result=await compilerPost("/api/compiler/destination",Object.fromEntries(new FormData(destinationForm)));const preview=result.preview;receipt.hidden=false;receipt.textContent=JSON.stringify(preview,null,2);status.textContent="Destination preview compiled; topology is unchanged until approval.";const button=document.createElement("button");button.textContent="Approve destination";button.addEventListener("click",async()=>{await compilerPost(`/api/compiler/destination/approve/${result.preview_id}`,{});button.remove();await refresh();});destinationForm.append(button);}); +document.querySelector("#fission-form")!.addEventListener("submit", async event => { + event.preventDefault(); + const data = new FormData(event.currentTarget as HTMLFormElement); + const result = await compilerPost("/api/compiler/gestalt/fission", { + parent_gestalt_id: data.get("parent_gestalt_id"), + partition_axis: data.get("partition_axis"), + requested_partition_values: String(data.get("requested_partition_values") ?? "").split(",").map(value => value.trim()).filter(Boolean), + reason: data.get("reason"), + }); + receipt.hidden = false; + receipt.textContent = JSON.stringify(result.preview, null, 2); + status.textContent = "Fission preview compiled. Canonical leaves are unchanged until approval."; + const button = document.createElement("button"); + button.type = "button"; + button.textContent = "Approve population fission"; + button.addEventListener("click", async () => { + await compilerPost(`/api/compiler/gestalt/fission/approve/${result.preview_id}`, {}); + button.remove(); + await refresh(); + }); + (event.currentTarget as HTMLFormElement).append(button); +}); document.querySelector("#fork-form")!.addEventListener("submit",async event=>{event.preventDefault();await compilerPost("/api/campaigns/fork",Object.fromEntries(new FormData(event.currentTarget as HTMLFormElement)));await refresh();}); document.querySelector("#reset-form")!.addEventListener("submit",async event=>{event.preventDefault();await compilerPost("/api/campaigns/reset",Object.fromEntries(new FormData(event.currentTarget as HTMLFormElement)));await refresh();}); document.querySelector("#load-operator")!.addEventListener("click",async()=>{const response=await fetch("/api/operator");const surface=await response.json();renderEveSurface(surface,document.querySelector("#operator-output")!,{body:document.body,clientId:"ghostlight.operator",statusElement:status});}); diff --git a/web/src/style.css b/web/src/style.css index 9b82016..360e0a1 100644 --- a/web/src/style.css +++ b/web/src/style.css @@ -1,2 +1,2 @@ @import url('https://fonts.googleapis.com/css2?family=Crimson+Pro:opsz,wght@8..144,400;8..144,600&family=IBM+Plex+Mono:wght@400;600&display=swap'); -:root{color-scheme:dark;font-family:"Crimson Pro",serif;background:#0c1110;color:#e8e1cf}body{margin:0;min-height:100vh;background:radial-gradient(circle at 15% 0,#253229 0,transparent 38rem),linear-gradient(145deg,#0c1110,#111513)}header,main{width:min(920px,calc(100% - 2rem));margin:auto}header{padding:3rem 0 1.25rem;border-bottom:1px solid #66543d}h1{font-size:clamp(2.6rem,8vw,5.5rem);font-weight:400;letter-spacing:-.045em;margin:.1rem 0}.eyebrow,#status,label,button,pre{font-family:"IBM Plex Mono",monospace}.eyebrow{color:#d49b58;letter-spacing:.18em;font-size:.72rem}#status{color:#9aa69f;font-size:.78rem}main{padding:1.5rem 0 5rem}#surface{min-height:15rem}form,.card{margin-top:1.5rem;padding:1rem;border:1px solid #66543d;background:#17201ddd}label{display:block;font-size:.72rem;text-transform:uppercase;letter-spacing:.12em;margin-bottom:.65rem}textarea,input{box-sizing:border-box;width:100%;resize:vertical;background:#0b0f0d;color:#f2e7d0;border:1px solid #4a5148;padding:.9rem;margin:.35rem 0;font:1.05rem/1.4 "Crimson Pro",serif}textarea{min-height:7rem}button{margin:.8rem .5rem 0 0;padding:.65rem 1rem;border:1px solid #d49b58;background:#d49b58;color:#17120c;cursor:pointer}button+button{background:transparent;color:#d49b58}pre{white-space:pre-wrap;padding:1rem;background:#080b09;color:#aeb9af;overflow:auto;font-size:.72rem}.compiler-grid{display:grid;grid-template-columns:1fr 1fr;gap:1rem}.cards{display:grid;gap:.7rem}.card h3{margin:.1rem 0}.card p{color:#b9c0b7}.warning{color:#e4a86a!important}@media(max-width:700px){.compiler-grid{grid-template-columns:1fr}}@media(max-width:600px){header{padding-top:2rem}h1{font-size:3rem}} +:root{color-scheme:dark;font-family:"Crimson Pro",serif;background:#0c1110;color:#e8e1cf}body{margin:0;min-height:100vh;background:radial-gradient(circle at 15% 0,#253229 0,transparent 38rem),linear-gradient(145deg,#0c1110,#111513)}header,main{width:min(920px,calc(100% - 2rem));margin:auto}header{padding:3rem 0 1.25rem;border-bottom:1px solid #66543d}h1{font-size:clamp(2.6rem,8vw,5.5rem);font-weight:400;letter-spacing:-.045em;margin:.1rem 0}.eyebrow,#status,label,button,pre{font-family:"IBM Plex Mono",monospace}.eyebrow{color:#d49b58;letter-spacing:.18em;font-size:.72rem}#status{color:#9aa69f;font-size:.78rem}main{padding:1.5rem 0 5rem}#surface{min-height:15rem}form,.card{margin-top:1.5rem;padding:1rem;border:1px solid #66543d;background:#17201ddd}label{display:block;font-size:.72rem;text-transform:uppercase;letter-spacing:.12em;margin-bottom:.65rem}textarea,input,select{box-sizing:border-box;width:100%;resize:vertical;background:#0b0f0d;color:#f2e7d0;border:1px solid #4a5148;padding:.9rem;margin:.35rem 0;font:1.05rem/1.4 "Crimson Pro",serif}input[type="range"]{padding:.25rem;accent-color:#d49b58}textarea{min-height:7rem}button{margin:.8rem .5rem 0 0;padding:.65rem 1rem;border:1px solid #d49b58;background:#d49b58;color:#17120c;cursor:pointer}button+button{background:transparent;color:#d49b58}pre{white-space:pre-wrap;padding:1rem;background:#080b09;color:#aeb9af;overflow:auto;font-size:.72rem}.compiler-grid{display:grid;grid-template-columns:1fr 1fr;gap:1rem}.cards{display:grid;gap:.7rem}.card h3{margin:.1rem 0}.card p{color:#b9c0b7}.warning{color:#e4a86a!important}code{font-family:"IBM Plex Mono",monospace;color:#d49b58}@media(max-width:700px){.compiler-grid{grid-template-columns:1fr}}@media(max-width:600px){header{padding-top:2rem}h1{font-size:3rem}}