Implement multiresolution gestalt agency graph
This commit is contained in:
parent
434da0dc99
commit
bf586b90d0
33 changed files with 5579 additions and 300 deletions
|
|
@ -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,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<dyn ModelPort> = 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<String>,
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct SuggestedOpenings {
|
||||
pub openings: Vec<OpeningSuggestion>,
|
||||
|
|
@ -110,6 +119,29 @@ struct CompiledSeed {
|
|||
gaps: Vec<String>,
|
||||
branch_assumptions: Vec<String>,
|
||||
opening_narration: String,
|
||||
#[serde(default)]
|
||||
agency_profiles: Vec<CompiledAgencyProfile>,
|
||||
#[serde(default)]
|
||||
agency_relations: Vec<CompiledAgencyRelation>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
struct CompiledAgencyProfile {
|
||||
subject_id: String,
|
||||
subject_kind: AgencySubjectKind,
|
||||
collective_authority_id: Option<String>,
|
||||
facets: BTreeMap<AgencyAxis, BTreeSet<String>>,
|
||||
location_ids: BTreeSet<String>,
|
||||
information_channels: BTreeSet<String>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
struct CompiledFissionSeed {
|
||||
children: Vec<GestaltPersonaState>,
|
||||
child_partition_values: BTreeMap<String, String>,
|
||||
#[serde(default)]
|
||||
member_child_assignments: BTreeMap<String, String>,
|
||||
gaps: Vec<String>,
|
||||
}
|
||||
|
||||
pub struct WorldCompiler {
|
||||
vault: Arc<dyn VaultProvider>,
|
||||
model: Arc<dyn ModelPort>,
|
||||
|
|
@ -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<VaultEvidenceReceipt>,
|
||||
Vec<ModelStageReceipt>,
|
||||
)> {
|
||||
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::<Vec<_>>(),
|
||||
"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::<BTreeSet<_>>()
|
||||
.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<Campaign> {
|
||||
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<CompiledAgencyProfile>,
|
||||
relations: Vec<CompiledAgencyRelation>,
|
||||
) -> 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"
|
||||
|
|
|
|||
|
|
@ -36,6 +36,20 @@ pub struct Campaign {
|
|||
pub gestalt_members: BTreeMap<String, GestaltMemberDelta>,
|
||||
#[serde(default)]
|
||||
pub pending_world_proposals: Vec<WorldActionProposal>,
|
||||
#[serde(default)]
|
||||
pub agency_profiles: BTreeMap<String, AgencyProfile>,
|
||||
#[serde(default)]
|
||||
pub agency_relations: BTreeMap<String, AgencyRelation>,
|
||||
#[serde(default)]
|
||||
pub gestalt_lineages: BTreeMap<String, GestaltLineage>,
|
||||
#[serde(default)]
|
||||
pub resolution_policy: ResolutionPolicy,
|
||||
#[serde(default)]
|
||||
pub resolution_pins: BTreeMap<String, ResolutionPin>,
|
||||
#[serde(default)]
|
||||
pub resolution_cover: Option<ResolutionCover>,
|
||||
#[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<String>,
|
||||
pub parent_subject_id: Option<String>,
|
||||
pub active_leaf: bool,
|
||||
#[serde(default = "default_true")]
|
||||
pub simulation_eligible: bool,
|
||||
pub facets: BTreeMap<AgencyAxis, BTreeSet<String>>,
|
||||
pub location_ids: BTreeSet<String>,
|
||||
pub information_channels: BTreeSet<String>,
|
||||
pub detail_debt: u64,
|
||||
pub last_detail_tick: u64,
|
||||
pub evidence_receipt_ids: Vec<String>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
pub struct GestaltLineage {
|
||||
pub schema: String,
|
||||
pub parent_gestalt_id: String,
|
||||
pub child_gestalt_ids: Vec<String>,
|
||||
pub partition_axis: AgencyAxis,
|
||||
pub partition_values: BTreeMap<String, String>,
|
||||
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<u8>,
|
||||
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<String>,
|
||||
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<AgencyAxis, f32>,
|
||||
pub focal_subject_ids: BTreeSet<String>,
|
||||
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<String>,
|
||||
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<String>,
|
||||
}
|
||||
|
||||
#[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<SimulationCell>,
|
||||
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<String>,
|
||||
pub mandatory_overage: u8,
|
||||
pub preserved_cell_ids: Vec<String>,
|
||||
pub collapsed_boundaries: Vec<String>,
|
||||
pub merge_losses: BTreeMap<String, MergeLoss>,
|
||||
pub rationale: String,
|
||||
pub created_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
pub committed_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
},
|
||||
Gestalt {
|
||||
gestalt_id: String,
|
||||
pressure_additions: Vec<String>,
|
||||
},
|
||||
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<String>,
|
||||
pub public_channels: Vec<String>,
|
||||
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<String>,
|
||||
pub actions: Vec<CellActionProposal>,
|
||||
pub inaction_reason: Option<String>,
|
||||
}
|
||||
|
||||
#[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<CellAppraisal>,
|
||||
pub model_receipt_hashes: Vec<String>,
|
||||
}
|
||||
|
||||
#[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<GestaltPersonaState>,
|
||||
pub child_partition_values: BTreeMap<String, String>,
|
||||
pub residual_child_id: String,
|
||||
#[serde(default)]
|
||||
pub member_child_assignments: BTreeMap<String, String>,
|
||||
pub evidence_receipt_ids: Vec<String>,
|
||||
pub gaps: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub canon_candidates: Vec<CanonCandidate>,
|
||||
pub requires_approval: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Default)]
|
||||
pub struct ActorStateDelta {
|
||||
pub memories_add: Vec<String>,
|
||||
|
|
@ -307,6 +599,12 @@ pub struct StrategicTickReceipt {
|
|||
pub revision: u64,
|
||||
pub source: TickSource,
|
||||
pub model_receipt_hash: Option<String>,
|
||||
#[serde(default)]
|
||||
pub model_receipt_hashes: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub resolution_epoch: Option<u64>,
|
||||
#[serde(default)]
|
||||
pub resolution_cover_id: Option<String>,
|
||||
pub event_ids: Vec<String>,
|
||||
pub committed_at: DateTime<Utc>,
|
||||
}
|
||||
|
|
@ -415,6 +713,30 @@ pub enum WorldCommand {
|
|||
plan: Option<StrategicTickPlan>,
|
||||
#[serde(default)]
|
||||
model_receipt_hash: Option<String>,
|
||||
#[serde(default)]
|
||||
resolution_wave: Option<ResolutionWaveCommit>,
|
||||
},
|
||||
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<ResolutionPin>,
|
||||
},
|
||||
FissionGestalt {
|
||||
expected_revision: u64,
|
||||
preview: GestaltFissionPreview,
|
||||
evidence_receipts: Vec<VaultEvidenceReceipt>,
|
||||
#[serde(default)]
|
||||
model_stage_receipts: Vec<crate::model::ModelStageReceipt>,
|
||||
},
|
||||
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,
|
||||
|
|
|
|||
|
|
@ -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<CommandResult, KernelError> {
|
||||
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::<crate::model::ModelStageReceipt>("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<CommandResult, KernelError> {
|
||||
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<String>,
|
||||
event_ids: Vec<String>,
|
||||
resolution_wave: Option<ResolutionWaveCommit>,
|
||||
) -> Result<CommandResult, KernelError> {
|
||||
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<CommandResult, KernelError> {
|
||||
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<RollReceipt>,
|
||||
) -> Result<CommandResult, KernelError> {
|
||||
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<CanonCandidate>,
|
||||
model_receipts: Vec<crate::model::ModelStageReceipt>,
|
||||
) -> Result<CommandResult, KernelError> {
|
||||
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>("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>("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>("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>("campaign.v1", &seed.id.to_string())
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.1;
|
||||
assert_eq!(after, before);
|
||||
assert!(store.keys("strategic_tick.v1").unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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<Arc<dyn ModelPort>>,
|
||||
compile_previews: Arc<Mutex<BTreeMap<String, OwnedPreview<WorldCompilePreview>>>>,
|
||||
expansion_previews: Arc<Mutex<BTreeMap<String, OwnedPreview<RegionExpansionPreview>>>>,
|
||||
fission_previews: Arc<Mutex<BTreeMap<String, OwnedFissionPreview>>>,
|
||||
live_turns: Arc<AtomicUsize>,
|
||||
mesh: MeshPublisher,
|
||||
}
|
||||
|
|
@ -75,6 +79,20 @@ struct OwnedPreview<T> {
|
|||
model_receipts: Vec<ghostlight_dungeon::model::ModelStageReceipt>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct OwnedFissionPreview {
|
||||
session_hash: String,
|
||||
value: GestaltFissionPreview,
|
||||
evidence_receipts: Vec<ghostlight_dungeon::domain::VaultEvidenceReceipt>,
|
||||
model_receipts: Vec<ghostlight_dungeon::model::ModelStageReceipt>,
|
||||
}
|
||||
|
||||
#[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<AppState>,
|
||||
Json(request): Json<GestaltFissionRequest>,
|
||||
) -> 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<String>,
|
||||
headers: HeaderMap,
|
||||
State(state): State<AppState>,
|
||||
) -> 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<serde_json::Value> {
|
|||
.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<AppState>,
|
||||
Json(request): Json<ProviderParallelismRequest>,
|
||||
) -> 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<AppState>) -> 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::<ghostlight_dungeon::model::ModelStageReceipt>(
|
||||
"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",
|
||||
));
|
||||
|
|
|
|||
|
|
@ -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<StrategicTickReceipt>,
|
||||
pub gestalt_receipts: Vec<GestaltMaterializationReceipt>,
|
||||
pub rejected: Vec<RejectedProposalReceipt>,
|
||||
pub resolution_plans: Vec<ResolutionPlanReceipt>,
|
||||
pub cell_appraisals: Vec<CellAppraisal>,
|
||||
pub resolution_controls: Vec<ResolutionControlReceipt>,
|
||||
}
|
||||
|
||||
#[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());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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<CultCacheEnvelope> {
|
||||
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<CultCacheEnvelope> {
|
||||
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)?
|
||||
|
|
|
|||
|
|
@ -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<crate::model::ModelStageReceipt>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
pub location_ids: BTreeSet<String>,
|
||||
pub knowledge: BTreeSet<String>,
|
||||
pub capabilities: BTreeSet<String>,
|
||||
pub resources: BTreeSet<String>,
|
||||
pub information_channels: BTreeSet<String>,
|
||||
pub permitted_state_references: BTreeSet<String>,
|
||||
pub reachable_destination_ids: BTreeSet<String>,
|
||||
pub goals: Vec<String>,
|
||||
pub pressures: Vec<String>,
|
||||
}
|
||||
|
||||
#[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<CellConstituentSlice>,
|
||||
pub shared_knowledge: BTreeSet<String>,
|
||||
pub shared_capabilities: BTreeSet<String>,
|
||||
pub perceived_events: Vec<String>,
|
||||
pub world_clock_pressure: Vec<String>,
|
||||
pub detail_focus_subject_id: Option<String>,
|
||||
pub max_actions: usize,
|
||||
pub source_receipt_ids: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct CellTerminalBundle {
|
||||
pub lived_stream: LivedNarrativeStream,
|
||||
pub persona_output: String,
|
||||
pub appraisal: crate::domain::CellAppraisal,
|
||||
pub stage_receipts: Vec<crate::model::ModelStageReceipt>,
|
||||
}
|
||||
|
||||
#[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<dyn ModelPort>,
|
||||
pub permit: Arc<dyn ExecutionPermit>,
|
||||
pub projector_model: String,
|
||||
pub persona_model: String,
|
||||
pub interpreter_model: String,
|
||||
}
|
||||
|
||||
impl CellProjectionEngine {
|
||||
pub async fn execute(&self, slice: PermittedCellSlice) -> Result<CellTerminalBundle> {
|
||||
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::<Vec<_>>()}
|
||||
}),
|
||||
);
|
||||
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::<Vec<_>>() }),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn constrain_interpreter_schema(
|
||||
schema: &mut serde_json::Value,
|
||||
slice: &PermittedActorSlice,
|
||||
|
|
|
|||
|
|
@ -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>("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<VaultEvidenceReceipt>,
|
||||
model_receipts: Vec<ModelStageReceipt>,
|
||||
) -> Result<CampaignRuntime> {
|
||||
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>("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
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
2454
crates/ghostlight-dungeon/src/resolution.rs
Normal file
2454
crates/ghostlight-dungeon/src/resolution.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -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<AgencyAxis, f32>,
|
||||
focal_subject_ids: BTreeSet<String>,
|
||||
rationale: String,
|
||||
}
|
||||
|
||||
pub struct StrategicResolutionOutput {
|
||||
pub wave: ResolutionWaveCommit,
|
||||
pub stages: Vec<ModelStageOutput>,
|
||||
pub aggregate_receipt_hash: String,
|
||||
}
|
||||
|
||||
pub async fn propose_resolution_wave(
|
||||
model: Arc<dyn ModelPort>,
|
||||
permit: Arc<dyn ExecutionPermit>,
|
||||
campaign: &Campaign,
|
||||
) -> Result<StrategicResolutionOutput> {
|
||||
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::<Vec<_>>();
|
||||
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<ModelStageOutput>) {
|
||||
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::<Vec<_>>();
|
||||
.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::<Vec<_>>()
|
||||
"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::<Vec<_>>(),
|
||||
"relations": campaign.agency_relations.values().filter(|relation| relation.active).collect::<Vec<_>>(),
|
||||
"profiles": campaign.agency_profiles.values().filter(|profile| profile.active_leaf && profile.simulation_eligible).collect::<Vec<_>>()
|
||||
});
|
||||
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::<DemandProjection>(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<PermittedCellSlice> {
|
||||
let constituents = cell
|
||||
.subject_ids
|
||||
.iter()
|
||||
.map(|id| constituent_slice(campaign, id))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
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<CellConstituentSlice> {
|
||||
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<String>>) -> BTreeSet<String> {
|
||||
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<Utc>, last_player_activity: DateTime<Utc>) -> u8 {
|
||||
|
|
@ -79,6 +342,86 @@ pub fn due_tick_target(now: DateTime<Utc>, last_player_activity: DateTime<Utc>)
|
|||
#[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<String> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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::<Vec<_>>();
|
||||
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::<Vec<_>>()
|
||||
.join("\n");
|
||||
let news=campaign.news.iter().map(|item|json!({"id":item.id,"kind":"text","props":{"value":format!("[{}] {}",item.channel,item.headline)},"children":[]})).collect::<Vec<_>>();
|
||||
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::<Vec<_>>(),
|
||||
"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::<Vec<_>>()
|
||||
},
|
||||
"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::<Vec<_>>()
|
||||
.join(", "),
|
||||
cell.merge_loss.total,
|
||||
cell.detail_focus_subject_id.as_deref().unwrap_or("none"),
|
||||
cell.rationale
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.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::<Vec<_>>()
|
||||
.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":[]
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ pub struct SnapshotPermit {
|
|||
store: CampaignStore,
|
||||
campaign_id: uuid::Uuid,
|
||||
revision: u64,
|
||||
resolution_epoch: Option<u64>,
|
||||
}
|
||||
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>("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::<std::collections::BTreeMap<_, _>>();
|
||||
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(),
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
215
docs/architecture/ghostlight-multiresolution-agency.md
Normal file
215
docs/architecture/ghostlight-multiresolution-agency.md
Normal file
|
|
@ -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.
|
||||
|
||||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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:
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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."}
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
153
web/dist/assets/index-BINdyAeG.js
vendored
153
web/dist/assets/index-BINdyAeG.js
vendored
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
153
web/dist/assets/index-DlJlHpS2.js
vendored
Normal file
153
web/dist/assets/index-DlJlHpS2.js
vendored
Normal file
File diff suppressed because one or more lines are too long
10
web/dist/index.html
vendored
10
web/dist/index.html
vendored
|
|
@ -1,6 +1,6 @@
|
|||
<!doctype html>
|
||||
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>GhostlightDungeon</title> <script type="module" crossorigin src="/assets/index-BINdyAeG.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-Dt7lvyL0.css">
|
||||
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>GhostlightDungeon</title> <script type="module" crossorigin src="/assets/index-DlJlHpS2.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-BnHnsfZy.css">
|
||||
</head>
|
||||
<body><header><p class="eyebrow">STARFIRE / PRIVATE VERSE</p><h1>GhostlightDungeon</h1><p id="status">Reading the world…</p></header><main>
|
||||
<section id="compiler" hidden><h2>Compile a world</h2><div class="compiler-grid">
|
||||
|
|
@ -9,5 +9,9 @@
|
|||
</div><div id="compiler-results"></div></section><section id="surface"></section>
|
||||
<form id="composer"><label for="attempt">Describe what you attempt</label><textarea id="attempt" required></textarea><div><button type="submit">Assess</button><button type="button" id="wait">Wait one hour</button></div></form><pre id="receipt" hidden></pre>
|
||||
<form id="destination-form"><label>Compile a destination without moving there</label><input name="origin_location_id" placeholder="Current location id" required><input name="destination" placeholder="Where do you want the world to extend?" required><button type="submit">Retrieve destination</button></form>
|
||||
<section id="campaign-lab" hidden><h2>Campaign laboratory</h2><div id="campaign-list"></div><form id="fork-form"><input name="name" placeholder="Fork name" required><button type="submit">Fork selected campaign</button></form><form id="reset-form"><input name="name" placeholder="Reset branch name" required><button type="submit">Reset from approved seed</button></form><a href="/api/campaigns/export" download>Export selected CultCache .cc</a> <a href="/api/campaigns/canon-candidates.md" download>Export canon candidates Markdown</a><details><summary>Operator inspector</summary><button type="button" id="load-operator">Load private state and receipts</button><div id="operator-output"></div></details></section>
|
||||
<section id="campaign-lab" hidden><h2>Campaign laboratory</h2><div id="campaign-list"></div>
|
||||
<form id="resolution-form"><label for="active-cell-budget">Active Persona-cell budget: <output id="active-cell-budget-value">8</output></label><input id="active-cell-budget" name="active_cell_budget" type="range" min="1" max="32" value="8"><p id="resolution-status"></p><button type="submit">Apply at safe boundary</button></form>
|
||||
<form id="pin-form"><label>Resolution pin</label><select name="kind"><option value="minimum_individual_detail">Keep one subject individual</option><option value="keep_separate">Keep subjects separate</option><option value="keep_together">Keep subjects together</option></select><input name="subject_ids" placeholder="Exact subject IDs, comma separated" required><input name="reason" placeholder="Why preserve this cut?" required><button type="submit">Add pin</button><div id="pin-list"></div></form>
|
||||
<form id="fission-form"><label>Approval-gated population fission</label><select name="parent_gestalt_id" id="fission-parent" required></select><select name="partition_axis"><option value="geography">Geography</option><option value="ideology">Ideology</option><option value="authority">Authority</option><option value="economy_role">Economic role</option><option value="species_body">Species/body</option><option value="information">Information</option></select><input name="requested_partition_values" placeholder="Named cuts, comma separated" required><input name="reason" placeholder="Why the population needs canonical leaves" required><button type="submit">Compile fission preview</button></form>
|
||||
<form id="fork-form"><input name="name" placeholder="Fork name" required><button type="submit">Fork selected campaign</button></form><form id="reset-form"><input name="name" placeholder="Reset branch name" required><button type="submit">Reset from approved seed</button></form><a href="/api/campaigns/export" download>Export selected CultCache .cc</a> <a href="/api/campaigns/canon-candidates.md" download>Export canon candidates Markdown</a><details><summary>Operator inspector</summary><form id="provider-parallelism-form"><label for="provider-parallelism">Provider request parallelism: <output id="provider-parallelism-value">8</output></label><input id="provider-parallelism" type="range" min="1" max="32" value="8"><button type="submit">Apply operator limit</button></form><button type="button" id="load-operator">Load private state and receipts</button><div id="operator-output"></div></details></section>
|
||||
</main></body></html>
|
||||
|
|
|
|||
|
|
@ -7,5 +7,9 @@
|
|||
</div><div id="compiler-results"></div></section><section id="surface"></section>
|
||||
<form id="composer"><label for="attempt">Describe what you attempt</label><textarea id="attempt" required></textarea><div><button type="submit">Assess</button><button type="button" id="wait">Wait one hour</button></div></form><pre id="receipt" hidden></pre>
|
||||
<form id="destination-form"><label>Compile a destination without moving there</label><input name="origin_location_id" placeholder="Current location id" required><input name="destination" placeholder="Where do you want the world to extend?" required><button type="submit">Retrieve destination</button></form>
|
||||
<section id="campaign-lab" hidden><h2>Campaign laboratory</h2><div id="campaign-list"></div><form id="fork-form"><input name="name" placeholder="Fork name" required><button type="submit">Fork selected campaign</button></form><form id="reset-form"><input name="name" placeholder="Reset branch name" required><button type="submit">Reset from approved seed</button></form><a href="/api/campaigns/export" download>Export selected CultCache .cc</a> <a href="/api/campaigns/canon-candidates.md" download>Export canon candidates Markdown</a><details><summary>Operator inspector</summary><button type="button" id="load-operator">Load private state and receipts</button><div id="operator-output"></div></details></section>
|
||||
<section id="campaign-lab" hidden><h2>Campaign laboratory</h2><div id="campaign-list"></div>
|
||||
<form id="resolution-form"><label for="active-cell-budget">Active Persona-cell budget: <output id="active-cell-budget-value">8</output></label><input id="active-cell-budget" name="active_cell_budget" type="range" min="1" max="32" value="8"><p id="resolution-status"></p><button type="submit">Apply at safe boundary</button></form>
|
||||
<form id="pin-form"><label>Resolution pin</label><select name="kind"><option value="minimum_individual_detail">Keep one subject individual</option><option value="keep_separate">Keep subjects separate</option><option value="keep_together">Keep subjects together</option></select><input name="subject_ids" placeholder="Exact subject IDs, comma separated" required><input name="reason" placeholder="Why preserve this cut?" required><button type="submit">Add pin</button><div id="pin-list"></div></form>
|
||||
<form id="fission-form"><label>Approval-gated population fission</label><select name="parent_gestalt_id" id="fission-parent" required></select><select name="partition_axis"><option value="geography">Geography</option><option value="ideology">Ideology</option><option value="authority">Authority</option><option value="economy_role">Economic role</option><option value="species_body">Species/body</option><option value="information">Information</option></select><input name="requested_partition_values" placeholder="Named cuts, comma separated" required><input name="reason" placeholder="Why the population needs canonical leaves" required><button type="submit">Compile fission preview</button></form>
|
||||
<form id="fork-form"><input name="name" placeholder="Fork name" required><button type="submit">Fork selected campaign</button></form><form id="reset-form"><input name="name" placeholder="Reset branch name" required><button type="submit">Reset from approved seed</button></form><a href="/api/campaigns/export" download>Export selected CultCache .cc</a> <a href="/api/campaigns/canon-candidates.md" download>Export canon candidates Markdown</a><details><summary>Operator inspector</summary><form id="provider-parallelism-form"><label for="provider-parallelism">Provider request parallelism: <output id="provider-parallelism-value">8</output></label><input id="provider-parallelism" type="range" min="1" max="32" value="8"><button type="submit">Apply operator limit</button></form><button type="button" id="load-operator">Load private state and receipts</button><div id="operator-output"></div></details></section>
|
||||
</main><script type="module" src="/src/main.ts"></script></body></html>
|
||||
|
|
|
|||
|
|
@ -12,6 +12,9 @@ const compilerResults = document.querySelector<HTMLElement>("#compiler-results")
|
|||
const campaignLab = document.querySelector<HTMLElement>("#campaign-lab")!;
|
||||
const campaignList = document.querySelector<HTMLElement>("#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<HTMLInputElement>("#active-cell-budget")!;
|
||||
budgetInput.value = String(budget);
|
||||
document.querySelector<HTMLOutputElement>("#active-cell-budget-value")!.value = String(budget);
|
||||
document.querySelector<HTMLElement>("#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<HTMLInputElement>("#provider-parallelism")!.value = String(providerParallelism);
|
||||
document.querySelector<HTMLOutputElement>("#provider-parallelism-value")!.value = String(providerParallelism);
|
||||
const pinList = document.querySelector<HTMLElement>("#pin-list")!;
|
||||
pinList.innerHTML = resolutionPins.map(pin => `<p><code>${pin.kind}</code> ${[...pin.subject_ids].join(", ")} — ${pin.reason} <button type="button" data-remove-pin="${pin.id}">Remove</button></p>`).join("") || "<p>No persistent pins.</p>";
|
||||
pinList.querySelectorAll<HTMLButtonElement>("[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<HTMLSelectElement>("#fission-parent")!;
|
||||
fissionParent.innerHTML = (surface.resolution?.fission_targets ?? []).map((target: any) => `<option value="${target.id}">${target.name} · ${target.id}</option>`).join("");
|
||||
document.querySelector<HTMLFormElement>("#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) => `<button data-campaign-id="${item.id}" ${item.selected ? "disabled" : ""}>${item.selected ? "●" : "○"} ${item.name} · revision ${item.revision}</button>`).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<HTMLButtonElement>("#wait")!.addEventListener("click", () => void send({ type: "wait", expected_revision: revision, minutes: 60 }));
|
||||
document.querySelector<HTMLInputElement>("#active-cell-budget")!.addEventListener("input", event => {
|
||||
document.querySelector<HTMLOutputElement>("#active-cell-budget-value")!.value = (event.currentTarget as HTMLInputElement).value;
|
||||
});
|
||||
document.querySelector<HTMLFormElement>("#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<HTMLInputElement>("#active-cell-budget")!.value),
|
||||
});
|
||||
});
|
||||
document.querySelector<HTMLInputElement>("#provider-parallelism")!.addEventListener("input", event => {
|
||||
document.querySelector<HTMLOutputElement>("#provider-parallelism-value")!.value = (event.currentTarget as HTMLInputElement).value;
|
||||
});
|
||||
document.querySelector<HTMLFormElement>("#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<HTMLInputElement>("#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<HTMLFormElement>("#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<HTMLFormElement>("#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<HTMLFormElement>("#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<HTMLFormElement>("#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<HTMLButtonElement>("#load-operator")!.addEventListener("click",async()=>{const response=await fetch("/api/operator");const surface=await response.json();renderEveSurface(surface,document.querySelector<HTMLElement>("#operator-output")!,{body:document.body,clientId:"ghostlight.operator",statusElement:status});});
|
||||
|
|
|
|||
|
|
@ -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}}
|
||||
|
|
|
|||
Loading…
Reference in a new issue