diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs index d3f4231..138f6ab 100644 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs @@ -15,6 +15,11 @@ async fn main() -> anyhow::Result<()> { use ghostlight_dungeon::{ compiler::DestinationCompilationFailure, domain::{TickSource, WorldCommand}, + elaboration::{ + ElaborationScheduler, ElaboratorTitle, ModelWorldElaborationWorker, + admit_world_elaboration_wave, dispatch_elaboration_wave, finalize_world_elaboration, + world_elaboration_wave_binding, + }, kernel::{CommandResult, WorldKernel}, model_runtime::ModelRuntimeSelection, persistence::CampaignStore, @@ -154,6 +159,16 @@ async fn main() -> anyhow::Result<()> { { let compiler = strategic_world_compiler(model.clone(), description, &strategic_world_when()); + let titled_profile = strategic_world_elaboration_profile(); + let titled_invocation_budget = titled_profile + .controls + .iter() + .map(|control| u32::from(control.weight)) + .sum::(); + let titled_parallelism = + bounded_environment_usize("GHOSTLIGHT_WORLD_ELABORATION_PARALLELISM", 8, 1, 32)?; + let titled_eligible = ElaboratorTitle::ALL.into_iter().collect(); + let mut titled_scheduler = ElaborationScheduler::new(&titled_profile)?; for (index, location_id) in initial_location_ids.iter().enumerate() { let location_name = campaign.locations[location_id].name.clone(); std::fs::write( @@ -252,11 +267,155 @@ async fn main() -> anyhow::Result<()> { anyhow::bail!("strategic locality elaboration did not commit") }; campaign = elaborated; + let titled_wave = world_elaboration_wave_binding(&campaign, location_id)?; + let titled_worker = Arc::new(ModelWorldElaborationWorker::new( + model.clone(), + Arc::new(campaign.clone()), + location_id.clone(), + format!( + "{request}\nAfter the civic foundation, add independently authored texture, material pressure, ordinary life, political leverage, secrets, active instability, and numinous meaning without rewriting the admitted apparatus." + ), + )?); + let titled_run = match dispatch_elaboration_wave( + &mut titled_scheduler, + titled_wave, + &titled_eligible, + titled_invocation_budget, + titled_parallelism, + titled_worker, + ) + .await + { + Ok(run) => run, + Err(failure) => { + let receipts = failure + .completed_invocations + .iter() + .flat_map(|invocation| invocation.model_stage_receipts.iter()) + .chain( + failure + .invocation_failures + .iter() + .flat_map(|failure| failure.model_stage_receipts.iter()), + ) + .cloned() + .collect::>(); + if !receipts.is_empty() { + store.persist_model_stage_receipts(&receipts)?; + } + let failure_path = root.join(format!( + "titled-elaboration-{:02}-terminal-failure.json", + index + 1 + )); + std::fs::write( + &failure_path, + serde_json::to_vec_pretty(&serde_json::json!({ + "schema":"ghostlight.titled_elaboration_failure.v1", + "location_id":location_id, + "location_name":location_name, + "request":request, + "wave":failure.wave, + "schedule":failure.schedule, + "completed_invocations":failure.completed_invocations.iter().map(|invocation|serde_json::json!({ + "dispatch":invocation.dispatch, + "proposal":invocation.proposal, + "model_receipt_hashes":invocation.model_stage_receipts.iter().map(|receipt|receipt.storage_key()).collect::>(), + })).collect::>(), + "invocation_failures":failure.invocation_failures.iter().map(|failure|serde_json::json!({ + "dispatch":failure.dispatch, + "diagnostic":failure.diagnostic, + "model_receipt_hashes":failure.model_stage_receipts.iter().map(|receipt|receipt.storage_key()).collect::>(), + })).collect::>(), + }))?, + )?; + anyhow::bail!( + "titled elaboration wave failed for {location_id}; exact receipt at {}", + failure_path.display() + ); + } + }; + let proposal_receipts = titled_run + .invocations() + .iter() + .flat_map(|invocation| invocation.model_stage_receipts.iter()) + .cloned() + .collect::>(); + store.persist_model_stage_receipts(&proposal_receipts)?; + let admission = admit_world_elaboration_wave(&campaign, location_id, titled_run)?; + let titled_preview_path = + root.join(format!("titled-elaboration-{:02}-preview.json", index + 1)); + std::fs::write( + &titled_preview_path, + serde_json::to_vec_pretty(&serde_json::json!({ + "schema":"ghostlight.titled_elaboration_preview.v1", + "location_id":location_id, + "location_name":location_name, + "request":request, + "wave":admission.wave(), + "schedule":admission.schedule(), + "accepted_operations":admission.accepted_operations(), + "rejections":admission.rejections(), + "candidate":admission.candidate(), + "candidate_diagnostic":admission.candidate_diagnostic(), + "model_receipt_hashes":admission.model_stage_receipts().iter().map(|receipt|receipt.storage_key()).collect::>(), + }))?, + )?; + let candidate = admission.candidate().ok_or_else(|| { + anyhow::anyhow!( + "titled elaboration produced no candidate: {}", + admission.candidate_diagnostic().unwrap_or("no diagnostic") + ) + })?; + if let Some(diagnostic) = admission.candidate_diagnostic() { + anyhow::bail!("titled elaboration candidate requires reconciliation: {diagnostic}"); + } + let causal_receipt_ids = admission + .model_stage_receipts() + .iter() + .map(|receipt| receipt.storage_key().to_owned()) + .collect::>(); + let verifier_receipt = match compiler + .verify_titled_locality_elaboration( + &campaign, + &request, + description, + candidate, + &causal_receipt_ids, + ) + .await + { + Ok(receipt) => receipt, + Err(error) => { + if let Some(failure) = error.downcast_ref::< + ghostlight_dungeon::compiler::CivicElaborationVerificationFailure, + >() { + store.persist_model_stage_receipts(&failure.model_receipts)?; + } + return Err(error); + } + }; + store.persist_model_stage_receipts(std::slice::from_ref(&verifier_receipt))?; + let finalized = + finalize_world_elaboration(&campaign, admission, verifier_receipt.clone())?; + let CommandResult::Committed { + campaign: titled_elaborated, + .. + } = kernel + .commit_elaboration(finalized) + .await + .map_err(anyhow::Error::new)? + else { + anyhow::bail!("titled locality elaboration did not commit") + }; + campaign = titled_elaborated; elaboration_reports.push(serde_json::json!({ "location_id":location_id, "location_name":location_name, "world_revision":campaign.revision, "preview_path":preview_path, + "titled_preview_path":titled_preview_path, + "titled_model_receipts":proposal_receipts, + "titled_semantic_verifier_receipt":verifier_receipt, "model_receipts":receipts, })); } @@ -774,6 +933,30 @@ fn strategic_locality_request(location_name: &str, location_id: &str, pressure: request.chars().take(500).collect() } +fn strategic_world_elaboration_profile() -> ghostlight_dungeon::elaboration::WorldElaborationProfile +{ + use ghostlight_dungeon::elaboration::{ + ElaboratorControl, ElaboratorTitle, WorldElaborationProfile, + }; + + WorldElaborationProfile { + schema: "ghostlight.world_elaboration_profile.v1".into(), + controls: ElaboratorTitle::ALL + .into_iter() + .map(|title| ElaboratorControl { + title, + // Patina's bounded child place requires an outward and return + // route. Every other title receives two operations per pass. + weight: if title == ElaboratorTitle::Patina { + 3 + } else { + 2 + }, + }) + .collect(), + } +} + fn admitted_public_channel(value: &str) -> anyhow::Result { let channel = value.trim(); if !ghostlight_dungeon::resolution::information_channel_is_concrete(channel) { diff --git a/crates/ghostlight-dungeon/src/compiler.rs b/crates/ghostlight-dungeon/src/compiler.rs index 784a261..0499040 100644 --- a/crates/ghostlight-dungeon/src/compiler.rs +++ b/crates/ghostlight-dungeon/src/compiler.rs @@ -129,6 +129,20 @@ impl std::fmt::Display for DestinationCompilationFailure { impl std::error::Error for DestinationCompilationFailure {} +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct CivicElaborationVerificationFailure { + pub message: String, + pub model_receipts: Vec, +} + +impl std::fmt::Display for CivicElaborationVerificationFailure { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(&self.message) + } +} + +impl std::error::Error for CivicElaborationVerificationFailure {} + #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] struct OpeningSet { openings: Vec, @@ -1990,24 +2004,7 @@ impl WorldCompiler { }) }) .collect::>(); - let current_civic_context = campaign - .civic_systems - .get(expansion_origin_location_id) - .map(|system| { - serde_json::json!({ - "manifest":system, - "institutions":system.governing_institution_ids.iter().filter_map(|id|campaign.institutions.get(id)).collect::>(), - "institution_profiles":system.governing_institution_ids.iter().filter_map(|id|campaign.agency_profiles.get(id)).collect::>(), - "residents":system.resident_population_ids.iter().filter_map(|id|campaign.gestalts.get(id)).collect::>(), - "resident_profiles":system.resident_population_ids.iter().filter_map(|id|campaign.agency_profiles.get(id)).collect::>(), - "public_facts":system.public_authority_fact_ids.iter() - .chain(system.public_selection_fact_ids.iter()) - .chain(system.public_resource_fact_ids.iter()) - .chain(system.public_redress_fact_ids.iter()) - .filter_map(|id|campaign.facts.get(id)).collect::>(), - "political_relations":system.political_relation_ids.iter().filter_map(|id|campaign.agency_relations.get(id)).collect::>(), - }) - }); + let current_civic_context = civic_context(campaign, expansion_origin_location_id); let scope_instruction = if let Some(target_id) = existing_destination_id.as_deref() { format!( "The primary destination already exists as exact canonical location {target_id}. Elaborate it in place. Never emit that location again, rename it, replace it, or alter its existing routes or container. Every new location must be a bounded child whose containment chain reaches {target_id}; origin_routes are new local routes owned by {target_id}." @@ -2186,7 +2183,6 @@ impl WorldCompiler { destination_request, &destination_evidence, ¤t_civic_context, - &seed, expansion_candidate, &snapshot, &verification_sources, @@ -2989,7 +2985,6 @@ impl WorldCompiler { destination_request: &str, evidence: &str, current_civic_context: &Option, - seed: &CompiledExpansionSeed, expansion: &mut crate::domain::RegionExpansion, snapshot: &str, sources: &[String], @@ -3001,12 +2996,12 @@ impl WorldCompiler { let candidate = match serde_json::to_string(&serde_json::json!({ "previous_civic_apparatus":current_civic_context, "civic_system":civic_system, - "new_facts":&seed.facts, - "new_institutions":&seed.institutions, - "new_local_relations":&seed.local_relations, - "new_resident_populations":seed.populations.iter().map(|population| serde_json::json!({ + "new_facts":&expansion.facts, + "new_institutions":&expansion.institutions, + "new_local_relations":&expansion.local_relations, + "new_resident_populations":expansion.populations.iter().map(|population| serde_json::json!({ "id":population.id, - "shared_fact_ids":population.shared_fact_ids, + "shared_knowledge":population.shared_knowledge, })).collect::>(), })) { Ok(candidate) => candidate, @@ -3099,6 +3094,58 @@ impl WorldCompiler { } } + /// Independently verifies a complete titled-elaboration candidate without + /// granting the verifier any rewrite authority. The returned receipt is + /// rebound to the exact compiler candidate and can be consumed only by the + /// deterministic finalization boundary. + pub async fn verify_titled_locality_elaboration( + &self, + campaign: &Campaign, + destination_request: &str, + evidence: &str, + elaboration: &LocalityElaboration, + causal_source_receipt_ids: &[String], + ) -> Result { + validate_locality_elaboration(campaign, elaboration)?; + let mut expansion = elaboration.expansion.clone(); + let current_civic_context = civic_context(campaign, &elaboration.target_location_id); + let snapshot = format!( + "campaign:{}:revision:{}:titled-elaboration-verification", + campaign.id, campaign.revision + ); + match self + .verify_destination_civic_system( + campaign, + destination_request, + evidence, + ¤t_civic_context, + &mut expansion, + &snapshot, + causal_source_receipt_ids, + ) + .await + { + CivicSystemVerificationOutcome::Accepted { mut receipts } => receipts + .pop() + .ok_or_else(|| anyhow!("civic verifier accepted without a receipt")), + CivicSystemVerificationOutcome::Rejected { verdict, receipts } => { + Err(anyhow::Error::new(CivicElaborationVerificationFailure { + message: format!( + "titled elaboration civic verifier rejected the candidate: {}", + verdict.rationale.trim() + ), + model_receipts: receipts, + })) + } + CivicSystemVerificationOutcome::Failed { message, receipts } => { + Err(anyhow::Error::new(CivicElaborationVerificationFailure { + message, + model_receipts: receipts, + })) + } + } + } + async fn structured( &self, stage: &str, @@ -3205,7 +3252,6 @@ impl ModelAgentTool for DestinationReconciliationAgentTool<'_> { self.destination_request, self.evidence, self.current_civic_context, - &corrected, &mut expansion, self.snapshot, &context.source_receipt_ids, @@ -4636,6 +4682,24 @@ fn normalized_contains(document: &str, excerpt: &str) -> bool { !excerpt.is_empty() && document.contains(&excerpt) } +fn civic_context(campaign: &Campaign, location_id: &str) -> Option { + campaign.civic_systems.get(location_id).map(|system| { + serde_json::json!({ + "manifest":system, + "institutions":system.governing_institution_ids.iter().filter_map(|id|campaign.institutions.get(id)).collect::>(), + "institution_profiles":system.governing_institution_ids.iter().filter_map(|id|campaign.agency_profiles.get(id)).collect::>(), + "residents":system.resident_population_ids.iter().filter_map(|id|campaign.gestalts.get(id)).collect::>(), + "resident_profiles":system.resident_population_ids.iter().filter_map(|id|campaign.agency_profiles.get(id)).collect::>(), + "public_facts":system.public_authority_fact_ids.iter() + .chain(system.public_selection_fact_ids.iter()) + .chain(system.public_resource_fact_ids.iter()) + .chain(system.public_redress_fact_ids.iter()) + .filter_map(|id|campaign.facts.get(id)).collect::>(), + "political_relations":system.political_relation_ids.iter().filter_map(|id|campaign.agency_relations.get(id)).collect::>(), + }) + }) +} + pub(crate) fn civic_candidate_digest(expansion: &crate::domain::RegionExpansion) -> Result { let mut candidate = expansion.clone(); if let Some(system) = &mut candidate.civic_system { diff --git a/crates/ghostlight-dungeon/src/elaboration.rs b/crates/ghostlight-dungeon/src/elaboration.rs index e1734fa..0419417 100644 --- a/crates/ghostlight-dungeon/src/elaboration.rs +++ b/crates/ghostlight-dungeon/src/elaboration.rs @@ -1,6 +1,6 @@ use anyhow::{Result, anyhow}; use async_trait::async_trait; -use schemars::JsonSchema; +use schemars::{JsonSchema, schema_for}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::sync::Arc; @@ -256,8 +256,40 @@ pub struct ElaborationInvocation { /// cannot commit canonical world state; admission and conflict handling /// remain downstream owners. pub proposal: Proposal, + /// Exact model/tool ancestry for this proposal. These receipts are audit + /// evidence only; they never become source evidence or mutation authority. + pub model_stage_receipts: Vec, } +#[derive(Debug)] +pub struct ElaborationSubAgentOutput { + pub proposal: Proposal, + pub model_stage_receipts: Vec, +} + +impl ElaborationSubAgentOutput { + pub fn deterministic(proposal: Proposal) -> Self { + Self { + proposal, + model_stage_receipts: Vec::new(), + } + } +} + +#[derive(Clone, Debug)] +pub struct ElaborationSubAgentFailure { + pub diagnostic: String, + pub model_stage_receipts: Vec, +} + +impl std::fmt::Display for ElaborationSubAgentFailure { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(&self.diagnostic) + } +} + +impl std::error::Error for ElaborationSubAgentFailure {} + #[derive(Debug)] pub struct ElaborationWaveRun { wave: ElaborationWaveBinding, @@ -283,6 +315,7 @@ impl ElaborationWaveRun { pub struct ElaborationInvocationFailure { pub dispatch: Option, pub diagnostic: String, + pub model_stage_receipts: Vec, } #[derive(Debug)] @@ -295,7 +328,10 @@ pub struct ElaborationWaveFailure { #[async_trait] pub trait ElaborationSubAgentPort: Send + Sync { - async fn invoke(&self, invocation: ElaborationSubAgentInvocation) -> Result; + async fn invoke( + &self, + invocation: ElaborationSubAgentInvocation, + ) -> std::result::Result, ElaborationSubAgentFailure>; } pub struct ElaborationScheduler { @@ -450,6 +486,7 @@ where invocation_failures: vec![ElaborationInvocationFailure { dispatch: None, diagnostic: error.to_string(), + model_stage_receipts: Vec::new(), }], }); } @@ -461,6 +498,7 @@ where invocation_failures: vec![ElaborationInvocationFailure { dispatch: None, diagnostic: "elaboration wave parallelism must be greater than zero".into(), + model_stage_receipts: Vec::new(), }], }); } @@ -481,23 +519,26 @@ where .map_err(|_| ElaborationInvocationFailure { dispatch: Some(dispatch.clone()), diagnostic: "elaboration invocation gate closed".into(), + model_stage_receipts: Vec::new(), })?; let request = ElaborationSubAgentInvocation { wave: wave.clone(), dispatch: dispatch.clone(), }; - let proposal = + let output = worker .invoke(request) .await .map_err(|error| ElaborationInvocationFailure { dispatch: Some(dispatch.clone()), - diagnostic: error.to_string().chars().take(2_000).collect(), + diagnostic: error.diagnostic.chars().take(2_000).collect(), + model_stage_receipts: error.model_stage_receipts, })?; Ok::<_, ElaborationInvocationFailure>(ElaborationInvocation { wave, dispatch, - proposal, + proposal: output.proposal, + model_stage_receipts: output.model_stage_receipts, }) }); task_dispatches.insert(task.id(), task_dispatch); @@ -518,6 +559,7 @@ where Err(error) => invocation_failures.push(ElaborationInvocationFailure { dispatch: task_dispatches.remove(&error.id()), diagnostic: format!("elaboration sub-agent task failed: {error}"), + model_stage_receipts: Vec::new(), }), } } @@ -544,6 +586,429 @@ where }) } +/// Provider-backed titled worker for one additive locality operation. The +/// model chooses content through the generic agent harness; a deterministic +/// tool checks the exact task assignment and frozen campaign namespace before +/// returning a proposal to wave admission. +pub struct ModelWorldElaborationWorker { + model: Arc, + campaign: Arc, + target_location_id: String, + request: String, +} + +impl ModelWorldElaborationWorker { + pub fn new( + model: Arc, + campaign: Arc, + target_location_id: impl Into, + request: impl Into, + ) -> Result { + let target_location_id = target_location_id.into(); + if !campaign.locations.contains_key(&target_location_id) { + return Err(anyhow!("world elaboration worker target is unknown")); + } + if !campaign.civic_systems.contains_key(&target_location_id) { + return Err(anyhow!( + "provider-backed titled elaboration currently requires an admitted civic foundation" + )); + } + Ok(Self { + model, + campaign, + target_location_id, + request: request.into(), + }) + } + + fn projection(&self) -> Result { + let civic = &self.campaign.civic_systems[&self.target_location_id]; + let subject_ids = civic + .governing_institution_ids + .iter() + .chain(civic.resident_population_ids.iter()) + .cloned() + .collect::>(); + let projection = serde_json::json!({ + "campaign_id":self.campaign.id, + "world_revision":self.campaign.revision, + "campaign_name":self.campaign.name, + "target_location":self.campaign.locations.get(&self.target_location_id), + "current_civic_system":civic, + "civic_institutions":subject_ids.iter().filter_map(|id|self.campaign.institutions.get(id)).collect::>(), + "civic_populations":subject_ids.iter().filter_map(|id|self.campaign.gestalts.get(id)).collect::>(), + "political_relations":civic.political_relation_ids.iter().filter_map(|id|self.campaign.agency_relations.get(id)).collect::>(), + "public_facts":civic.public_authority_fact_ids.iter() + .chain(civic.public_selection_fact_ids.iter()) + .chain(civic.public_resource_fact_ids.iter()) + .chain(civic.public_redress_fact_ids.iter()) + .filter_map(|id|self.campaign.facts.get(id)).collect::>(), + "existing_fact_namespace":self.campaign.facts.values().map(|fact|serde_json::json!({ + "id":fact.id, + "statement":fact.statement, + })).collect::>(), + "request":self.request, + }); + Ok(serde_json::to_string(&projection)?) + } +} + +#[derive(Clone, Debug)] +enum WorldElaborationAssignment { + PatinaPlace { + child_location_id: String, + }, + PatinaOriginRoute { + child_location_id: String, + route_id: String, + }, + PatinaReturnRoute { + child_location_id: String, + route_id: String, + }, + PreserveCivicSystem { + system: crate::domain::CivicSystemManifest, + }, + AddFact { + fact_id: String, + }, + AddPoliticalRelation { + relation_id: String, + allowed_subject_ids: BTreeSet, + }, +} + +impl WorldElaborationAssignment { + fn for_dispatch( + campaign: &crate::domain::Campaign, + target_location_id: &str, + dispatch: &ElaborationDispatch, + ) -> Result { + let title_count = dispatch.title_dispatch_count; + let title_name = dispatch.title.display_name().to_ascii_lowercase(); + match dispatch.title { + ElaboratorTitle::Patina => { + let cycle = (title_count.saturating_sub(1) / 3).saturating_add(1); + let child_location_id = format!("elab:{target_location_id}:patina-place:{cycle}"); + match title_count.saturating_sub(1) % 3 { + 0 => Ok(Self::PatinaPlace { child_location_id }), + 1 => Ok(Self::PatinaOriginRoute { + child_location_id, + route_id: format!("elab:{target_location_id}:patina-route:{cycle}:out"), + }), + _ => Ok(Self::PatinaReturnRoute { + child_location_id, + route_id: format!("elab:{target_location_id}:patina-route:{cycle}:back"), + }), + } + } + ElaboratorTitle::Charter if title_count % 2 == 1 => { + let mut system = campaign + .civic_systems + .get(target_location_id) + .cloned() + .ok_or_else(|| anyhow!("Charter requires an admitted civic system"))?; + system.version = system.version.saturating_add(1); + system.semantic_verification_receipt_id.clear(); + Ok(Self::PreserveCivicSystem { system }) + } + ElaboratorTitle::Tangle if title_count % 2 == 1 => { + let civic = campaign + .civic_systems + .get(target_location_id) + .ok_or_else(|| anyhow!("Tangle requires an admitted civic system"))?; + let allowed_subject_ids = civic + .governing_institution_ids + .iter() + .chain(civic.resident_population_ids.iter()) + .cloned() + .collect::>(); + if allowed_subject_ids.len() < 2 { + return Err(anyhow!("Tangle requires at least two exact civic subjects")); + } + Ok(Self::AddPoliticalRelation { + relation_id: format!( + "elab:{target_location_id}:{title_name}-relation:{title_count}" + ), + allowed_subject_ids, + }) + } + _ => Ok(Self::AddFact { + fact_id: format!("elab:{target_location_id}:{title_name}-fact:{title_count}"), + }), + } + } + + fn instruction(&self, target_location_id: &str) -> Result { + let instruction = match self { + Self::PatinaPlace { child_location_id } => format!( + "Submit exactly one add_place operation. Its id must be {child_location_id:?}, container_id must be {target_location_id:?}, name must be concrete, and persistent_features must contain one or more durable visible local details. This is Patina's texture-bearing place; a later assigned operation supplies its routes." + ), + Self::PatinaOriginRoute { + child_location_id, + route_id, + } => format!( + "Submit exactly one add_route operation from {target_location_id:?}. route_id must be {route_id:?}; destination_id must be {child_location_id:?}; distance must be \"a short internal path\"; travel_minutes must be 3." + ), + Self::PatinaReturnRoute { + child_location_id, + route_id, + } => format!( + "Submit exactly one add_route operation from {child_location_id:?}. route_id must be {route_id:?}; destination_id must be {target_location_id:?}; distance must be \"a short internal path\"; travel_minutes must be 3." + ), + Self::PreserveCivicSystem { system } => format!( + "Submit exactly one set_civic_system operation containing this exact next-version manifest, byte-for-byte in meaning and with an empty semantic_verification_receipt_id: {}. Do not add or omit an ID; the independent verifier owns semantic acceptance.", + serde_json::to_string(system)? + ), + Self::AddFact { fact_id } => format!( + "Submit exactly one add_fact operation. The fact id must be {fact_id:?}; scope must be branch_local; evidence_receipt_ids must be empty; discoverable_at_location_ids must contain exactly {target_location_id:?}. Invent one concrete, consequential, title-appropriate statement that does not duplicate an existing fact." + ), + Self::AddPoliticalRelation { + relation_id, + allowed_subject_ids, + } => format!( + "Submit exactly one add_local_relation operation. Its id must be {relation_id:?}; both distinct endpoints must come from {}; kind must be alliance, rivalry, trade, communication, command, or coercion; strength must be 1 through 100; active must be true; evidence_receipt_ids must be empty.", + serde_json::to_string(allowed_subject_ids)? + ), + }; + Ok(instruction) + } + + fn validate( + &self, + campaign: &crate::domain::Campaign, + target_location_id: &str, + proposal: &WorldElaborationProposal, + ) -> Result<()> { + if proposal.schema != "ghostlight.world_elaboration_proposal.v1" { + return Err(anyhow!("world elaboration proposal schema is unsupported")); + } + operation_claims(&proposal.operation)?; + use WorldElaborationOperation::*; + match (self, &proposal.operation) { + ( + Self::PatinaPlace { child_location_id }, + AddPlace { + id, + name, + container_id, + persistent_features, + }, + ) if id == child_location_id + && !name.trim().is_empty() + && container_id.as_deref() == Some(target_location_id) + && !persistent_features.is_empty() => {} + ( + Self::PatinaOriginRoute { + child_location_id, + route_id: expected_route_id, + }, + AddRoute { + origin_location_id, + route_id, + route, + }, + ) if origin_location_id == target_location_id + && route_id == expected_route_id + && route.destination_id == *child_location_id + && route.distance == "a short internal path" + && route.travel_minutes == 3 => {} + ( + Self::PatinaReturnRoute { + child_location_id, + route_id: expected_route_id, + }, + AddRoute { + origin_location_id, + route_id, + route, + }, + ) if origin_location_id == child_location_id + && route_id == expected_route_id + && route.destination_id == target_location_id + && route.distance == "a short internal path" + && route.travel_minutes == 3 => {} + (Self::PreserveCivicSystem { system }, SetCivicSystem { system: proposed }) + if proposed == system => {} + (Self::AddFact { fact_id }, AddFact { fact }) + if fact.id == *fact_id + && fact.scope == crate::domain::FactScope::BranchLocal + && fact.evidence_receipt_ids.is_empty() + && fact.discoverable_at_location_ids + == BTreeSet::from([target_location_id.to_owned()]) + && !fact.statement.trim().is_empty() + && fact.statement.chars().count() <= 500 + && campaign + .facts + .values() + .all(|existing| existing.statement != fact.statement) => {} + ( + Self::AddPoliticalRelation { + relation_id, + allowed_subject_ids, + }, + AddLocalRelation { relation }, + ) if relation.id == *relation_id + && allowed_subject_ids.contains(&relation.from_subject_id) + && allowed_subject_ids.contains(&relation.to_subject_id) + && relation.from_subject_id != relation.to_subject_id + && matches!( + relation.kind, + crate::domain::AgencyRelationKind::Alliance + | crate::domain::AgencyRelationKind::Rivalry + | crate::domain::AgencyRelationKind::Trade + | crate::domain::AgencyRelationKind::Communication + | crate::domain::AgencyRelationKind::Command + | crate::domain::AgencyRelationKind::Coercion + ) + && relation.active + && (1..=100).contains(&relation.strength) + && relation.evidence_receipt_ids.is_empty() => {} + _ => { + return Err(anyhow!( + "proposal does not satisfy the exact titled elaboration task assignment" + )); + } + } + Ok(()) + } +} + +#[derive(Clone, Debug, Serialize)] +#[serde(deny_unknown_fields)] +struct WorldElaborationAgentFinding { + diagnostic: String, +} + +struct WorldElaborationAgentTool<'a> { + campaign: &'a crate::domain::Campaign, + target_location_id: &'a str, + assignment: &'a WorldElaborationAssignment, +} + +#[async_trait] +impl crate::agent::ModelAgentTool for WorldElaborationAgentTool<'_> { + type Action = WorldElaborationProposal; + type Output = WorldElaborationProposal; + type Finding = WorldElaborationAgentFinding; + + async fn invoke( + &mut self, + action: Self::Action, + _context: &crate::agent::ModelAgentToolContext, + ) -> crate::agent::ModelAgentToolOutcome { + match self + .assignment + .validate(self.campaign, self.target_location_id, &action) + { + Ok(()) => crate::agent::ModelAgentToolOutcome::Accepted { + output: action, + receipts: Vec::new(), + }, + Err(error) => crate::agent::ModelAgentToolOutcome::Rejected { + finding: WorldElaborationAgentFinding { + diagnostic: error.to_string(), + }, + receipts: Vec::new(), + }, + } + } +} + +#[async_trait] +impl ElaborationSubAgentPort for ModelWorldElaborationWorker { + async fn invoke( + &self, + invocation: ElaborationSubAgentInvocation, + ) -> std::result::Result< + ElaborationSubAgentOutput, + ElaborationSubAgentFailure, + > { + let expected_wave = + world_elaboration_wave_binding(&self.campaign, &self.target_location_id).map_err( + |error| ElaborationSubAgentFailure { + diagnostic: error.to_string(), + model_stage_receipts: Vec::new(), + }, + )?; + if invocation.wave != expected_wave { + return Err(ElaborationSubAgentFailure { + diagnostic: + "world elaboration worker invocation does not match its frozen campaign".into(), + model_stage_receipts: Vec::new(), + }); + } + let assignment = WorldElaborationAssignment::for_dispatch( + &self.campaign, + &self.target_location_id, + &invocation.dispatch, + ) + .map_err(|error| ElaborationSubAgentFailure { + diagnostic: error.to_string(), + model_stage_receipts: Vec::new(), + })?; + let snapshot_binding = + world_elaboration_invocation_binding(&invocation.wave, &invocation.dispatch).map_err( + |error| ElaborationSubAgentFailure { + diagnostic: error.to_string(), + model_stage_receipts: Vec::new(), + }, + )?; + let instructions = format!( + "You are {}, one titled elaborator in a parallel worldbuilding wave. {} Your authority is one proposal only. Use the typed submit tool to negotiate with the deterministic validator; never claim canonical state, invent evidence receipts, or alter another assignment. Preserve the frozen civic foundation and make your contribution specific enough that later events can use it.\n\nEXACT ASSIGNMENT:\n{}\n\nFROZEN PUBLIC WORLD PROJECTION:\n{}", + invocation.dispatch.title.display_name(), + invocation.dispatch.title.mandate(), + assignment + .instruction(&self.target_location_id) + .map_err(|error| ElaborationSubAgentFailure { + diagnostic: error.to_string(), + model_stage_receipts: Vec::new(), + })?, + self.projection() + .map_err(|error| ElaborationSubAgentFailure { + diagnostic: error.to_string(), + model_stage_receipts: Vec::new(), + })?, + ); + let model = match invocation.dispatch.title { + ElaboratorTitle::Charter | ElaboratorTitle::Tangle => crate::model::MODEL_BALANCED, + ElaboratorTitle::Numen => crate::model::MODEL_CAPABLE, + _ => crate::model::MODEL_FAST, + }; + let spec = crate::agent::ModelAgentSpec { + stage: elaborator_stage(invocation.dispatch.title), + model: model.into(), + snapshot_binding, + instructions, + action_schema: serde_json::to_value(schema_for!(WorldElaborationProposal)).map_err( + |error| ElaborationSubAgentFailure { + diagnostic: error.to_string(), + model_stage_receipts: Vec::new(), + }, + )?, + source_receipt_ids: Vec::new(), + temperature: Some(0.4), + max_output_tokens: Some(1_800), + max_steps: 2, + }; + let mut tool = WorldElaborationAgentTool { + campaign: &self.campaign, + target_location_id: &self.target_location_id, + assignment: &assignment, + }; + match crate::agent::run_model_agent(self.model.as_ref(), &spec, &mut tool).await { + Ok(run) => Ok(ElaborationSubAgentOutput { + proposal: run.output, + model_stage_receipts: run.receipts, + }), + Err(error) => Err(ElaborationSubAgentFailure { + diagnostic: error.message, + model_stage_receipts: error.receipts, + }), + } + } +} + /// One additive world operation proposed by one titled elaborator. These are /// deliberately compiler inputs, not kernel commands or mutation permits. #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] @@ -628,6 +1093,7 @@ pub struct WorldElaborationAdmission { schedule: ElaborationScheduleReceipt, accepted_operations: Vec, rejections: Vec, + model_stage_receipts: Vec, candidate: Option, candidate_diagnostic: Option, digest: String, @@ -663,6 +1129,17 @@ pub fn world_elaboration_wave_binding( }) } +pub fn world_elaboration_invocation_binding( + wave: &ElaborationWaveBinding, + dispatch: &ElaborationDispatch, +) -> Result { + crate::legacy_transition::digest_serializable(&( + "ghostlight.world_elaboration_agent_snapshot.v1", + wave, + dispatch, + )) +} + /// Deterministically validates, conflict-selects, and merges every proposal in /// a successful wave. First writer in scheduler dispatch order owns a write /// claim; later colliding proposals are retained as exact rejections. @@ -678,6 +1155,7 @@ pub fn admit_world_elaboration_wave( )); } validate_successful_wave_run(&run)?; + validate_invocation_model_receipts(&run)?; let mut invocations = run.invocations; invocations.sort_by_key(|invocation| invocation.dispatch.ordinal); if invocations @@ -695,7 +1173,9 @@ pub fn admit_world_elaboration_wave( let mut claim_owners = BTreeMap::::new(); let mut accepted_operations = Vec::new(); let mut rejections = Vec::new(); + let mut model_stage_receipts = Vec::new(); for invocation in invocations { + model_stage_receipts.extend(invocation.model_stage_receipts); let proposal = invocation.proposal; let claims = if proposal.schema == "ghostlight.world_elaboration_proposal.v1" { operation_claims(&proposal.operation) @@ -751,6 +1231,7 @@ pub fn admit_world_elaboration_wave( schedule: run.schedule, accepted_operations, rejections, + model_stage_receipts, candidate, candidate_diagnostic, digest: String::new(), @@ -850,11 +1331,85 @@ fn validate_successful_wave_run(run: &ElaborationWaveRun) -> Ok(()) } +fn validate_invocation_model_receipts(run: &ElaborationWaveRun) -> Result<()> { + let mut receipt_ids = BTreeSet::new(); + for invocation in &run.invocations { + if invocation.model_stage_receipts.is_empty() { + return Err(anyhow!( + "world elaboration invocation lacks model receipt custody" + )); + } + let expected_binding = + world_elaboration_invocation_binding(&invocation.wave, &invocation.dispatch)?; + let expected_stage = elaborator_stage(invocation.dispatch.title); + for receipt in &invocation.model_stage_receipts { + let mut rebound = receipt.clone(); + rebound.rebind_snapshot(receipt.snapshot_binding.clone()); + if receipt.schema != "ghostlight.persona_stage_receipt.v1" + || receipt.stage != expected_stage + || receipt.snapshot_binding != expected_binding + || !matches!( + receipt.validation_result.as_str(), + "valid" | "semantic_invalid" + ) + || rebound.storage_key() != receipt.storage_key() + || !receipt_ids.insert(receipt.storage_key().to_owned()) + { + return Err(anyhow!( + "world elaboration model receipt provenance is invalid or duplicated" + )); + } + } + if invocation + .model_stage_receipts + .last() + .is_none_or(|receipt| { + receipt.validation_result != "valid" || receipt.local_validation_error.is_some() + }) + { + return Err(anyhow!( + "world elaboration invocation lacks a terminal accepted model receipt" + )); + } + } + Ok(()) +} + +fn elaborator_stage(title: ElaboratorTitle) -> String { + format!( + "world_elaboration_{}", + title.display_name().to_ascii_lowercase() + ) +} + +fn validate_semantic_verifier_ancestry( + admission: &WorldElaborationAdmission, + semantic_verifier_receipt: &crate::model::ModelStageReceipt, +) -> Result<()> { + let expected = admission + .model_stage_receipts + .iter() + .map(|receipt| receipt.storage_key().to_owned()) + .collect::>(); + let actual = semantic_verifier_receipt + .source_receipt_ids + .iter() + .cloned() + .collect::>(); + if actual.len() != semantic_verifier_receipt.source_receipt_ids.len() || actual != expected { + return Err(anyhow!( + "world elaboration semantic verifier ancestry does not exactly cover admitted model receipts" + )); + } + Ok(()) +} + pub fn finalize_world_elaboration( campaign: &crate::domain::Campaign, admission: WorldElaborationAdmission, semantic_verifier_receipt: crate::model::ModelStageReceipt, ) -> Result { + validate_semantic_verifier_ancestry(&admission, &semantic_verifier_receipt)?; let mut elaboration = admission.valid_candidate(campaign)?; elaboration .expansion @@ -894,6 +1449,10 @@ impl WorldElaborationAdmission { &self.rejections } + pub fn model_stage_receipts(&self) -> &[crate::model::ModelStageReceipt] { + &self.model_stage_receipts + } + pub fn candidate(&self) -> Option<&crate::domain::LocalityElaboration> { self.candidate.as_ref() } @@ -969,7 +1528,7 @@ impl FinalizedWorldElaboration { ) -> Result<( u64, crate::domain::LocalityElaboration, - crate::model::ModelStageReceipt, + Vec, )> { if self.schema != "ghostlight.finalized_world_elaboration.v1" || self.digest != finalized_world_elaboration_digest(&self)? @@ -978,6 +1537,7 @@ impl FinalizedWorldElaboration { "finalized world elaboration is malformed or tampered" )); } + validate_semantic_verifier_ancestry(&self.admission, &self.semantic_verifier_receipt)?; let mut elaboration = self.admission.valid_candidate(campaign)?; elaboration .expansion @@ -990,10 +1550,12 @@ impl FinalizedWorldElaboration { &elaboration.expansion, std::slice::from_ref(&self.semantic_verifier_receipt), )?; + let mut model_stage_receipts = self.admission.model_stage_receipts.clone(); + model_stage_receipts.push(self.semantic_verifier_receipt); Ok(( self.admission.expected_revision, elaboration, - self.semantic_verifier_receipt, + model_stage_receipts, )) } } @@ -1048,6 +1610,11 @@ fn operation_claims(operation: &WorldElaborationOperation) -> Result "titled elaborators cannot assert canon-baseline facts" )); } + if !fact.evidence_receipt_ids.is_empty() { + return Err(anyhow!( + "titled elaborators cannot attach source-evidence receipts" + )); + } Ok(vec![format!("fact:{}", fact.id)]) } AddPopulation { @@ -1057,6 +1624,7 @@ fn operation_claims(operation: &WorldElaborationOperation) -> Result nonempty(&population.id, "population id")?; if profile.subject_id != population.id || profile.subject_kind != crate::domain::AgencySubjectKind::Gestalt + || !profile.evidence_receipt_ids.is_empty() { return Err(anyhow!( "world elaboration population profile does not bind its population" @@ -1074,6 +1642,7 @@ fn operation_claims(operation: &WorldElaborationOperation) -> Result nonempty(&institution.id, "institution id")?; if profile.subject_id != institution.id || profile.subject_kind != crate::domain::AgencySubjectKind::Institution + || !profile.evidence_receipt_ids.is_empty() { return Err(anyhow!( "world elaboration institution profile does not bind its institution" @@ -1086,6 +1655,11 @@ fn operation_claims(operation: &WorldElaborationOperation) -> Result } AddLocalRelation { relation } | AddMigrationRelation { relation } => { nonempty(&relation.id, "relation id")?; + if !relation.evidence_receipt_ids.is_empty() { + return Err(anyhow!( + "titled elaborators cannot attach source-evidence receipts" + )); + } Ok(vec![format!("relation:{}", relation.id)]) } SetCivicSystem { system } => { @@ -1244,6 +1818,7 @@ fn world_elaboration_admission_digest(admission: &WorldElaborationAdmission) -> &admission.schedule, &admission.accepted_operations, &admission.rejections, + &admission.model_stage_receipts, &admission.candidate, &admission.candidate_diagnostic, )) @@ -1293,7 +1868,11 @@ mod tests { #[async_trait] impl ElaborationSubAgentPort for CountingSubAgent { - async fn invoke(&self, invocation: ElaborationSubAgentInvocation) -> Result { + async fn invoke( + &self, + invocation: ElaborationSubAgentInvocation, + ) -> std::result::Result, ElaborationSubAgentFailure> + { use std::sync::atomic::Ordering; assert_eq!(invocation.wave, wave_binding()); let dispatch = invocation.dispatch; @@ -1307,7 +1886,10 @@ mod tests { .entry(dispatch.title) .or_default() += 1; self.active.fetch_sub(1, Ordering::SeqCst); - Ok(format!("proposal:{}", dispatch.ordinal)) + Ok(ElaborationSubAgentOutput::deterministic(format!( + "proposal:{}", + dispatch.ordinal + ))) } } @@ -1315,14 +1897,24 @@ mod tests { #[async_trait] impl ElaborationSubAgentPort for PartiallyFailingSubAgent { - async fn invoke(&self, invocation: ElaborationSubAgentInvocation) -> Result { + async fn invoke( + &self, + invocation: ElaborationSubAgentInvocation, + ) -> std::result::Result, ElaborationSubAgentFailure> + { if invocation.dispatch.ordinal == 3 { - return Err(anyhow!("fixture refusal")); + return Err(ElaborationSubAgentFailure { + diagnostic: "fixture refusal".into(), + model_stage_receipts: Vec::new(), + }); } if invocation.dispatch.ordinal == 4 { panic!("fixture panic"); } - Ok(format!("proposal:{}", invocation.dispatch.ordinal)) + Ok(ElaborationSubAgentOutput::deterministic(format!( + "proposal:{}", + invocation.dispatch.ordinal + ))) } } @@ -1528,4 +2120,131 @@ mod tests { entry.title == ElaboratorTitle::Patina && entry.mandate.contains("low-stakes texture") })); } + + #[test] + fn titled_operations_cannot_mint_source_evidence_authority() { + let operation = WorldElaborationOperation::AddFact { + fact: crate::domain::WorldFact { + id: "branch-fact".into(), + statement: "The gate duck is called Harold.".into(), + scope: crate::domain::FactScope::BranchLocal, + evidence_receipt_ids: vec!["invented-receipt".into()], + discoverable_at_location_ids: BTreeSet::from(["room".into()]), + }, + }; + + let error = operation_claims(&operation).unwrap_err(); + + assert!(error.to_string().contains("cannot attach source-evidence")); + } + + struct PanicIfInvokedModel; + + struct ReceiptlessWorldWorker; + + #[async_trait] + impl ElaborationSubAgentPort for ReceiptlessWorldWorker { + async fn invoke( + &self, + _invocation: ElaborationSubAgentInvocation, + ) -> std::result::Result< + ElaborationSubAgentOutput, + ElaborationSubAgentFailure, + > { + Ok(ElaborationSubAgentOutput::deterministic( + WorldElaborationProposal { + schema: "ghostlight.world_elaboration_proposal.v1".into(), + operation: WorldElaborationOperation::AddFact { + fact: crate::domain::WorldFact { + id: "receiptless-fact".into(), + statement: "This proposal has no provider custody.".into(), + scope: crate::domain::FactScope::BranchLocal, + evidence_receipt_ids: vec![], + discoverable_at_location_ids: BTreeSet::from(["room".into()]), + }, + }, + }, + )) + } + } + + #[async_trait] + impl crate::model::ModelPort for PanicIfInvokedModel { + async fn run(&self, _request: &crate::model::ModelStageRequest) -> Result { + panic!("stale world worker reached the model") + } + + fn provider(&self) -> &'static str { + "panic-fixture" + } + } + + #[tokio::test] + async fn provider_worker_rejects_a_wave_from_a_newer_world_before_model_inference() { + let mut frozen = crate::kernel::tests::campaign(); + frozen.civic_systems.insert( + "room".into(), + crate::domain::CivicSystemManifest { + schema: "ghostlight.civic_system_manifest.v1".into(), + version: 0, + jurisdiction_location_id: "room".into(), + governing_institution_ids: BTreeSet::new(), + resident_population_ids: BTreeSet::new(), + public_authority_fact_ids: BTreeSet::new(), + public_selection_fact_ids: BTreeSet::new(), + public_resource_fact_ids: BTreeSet::new(), + public_redress_fact_ids: BTreeSet::new(), + political_relation_ids: BTreeSet::new(), + semantic_verification_receipt_id: String::new(), + }, + ); + let worker = ModelWorldElaborationWorker::new( + Arc::new(PanicIfInvokedModel), + Arc::new(frozen.clone()), + "room", + "add texture", + ) + .unwrap(); + let mut current = frozen; + current.revision = 1; + let invocation = ElaborationSubAgentInvocation { + wave: world_elaboration_wave_binding(¤t, "room").unwrap(), + dispatch: ElaborationDispatch { + schema: "ghostlight.elaboration_dispatch.v1".into(), + budget_ordinal: 1, + ordinal: 1, + title: ElaboratorTitle::Patina, + title_weight: 1, + total_enabled_weight: 1, + requested_share_millionths: 1_000_000, + title_dispatch_count: 1, + }, + }; + + let error = worker.invoke(invocation).await.unwrap_err(); + + assert!(error.diagnostic.contains("frozen campaign")); + assert!(error.model_stage_receipts.is_empty()); + } + + #[tokio::test] + async fn world_admission_rejects_a_successful_receiptless_agent_proposal() { + let campaign = crate::kernel::tests::campaign(); + let mut scheduler = + ElaborationScheduler::new(&profile(&[(ElaboratorTitle::Patina, 1)])).unwrap(); + let run = dispatch_elaboration_wave( + &mut scheduler, + world_elaboration_wave_binding(&campaign, "room").unwrap(), + &BTreeSet::from([ElaboratorTitle::Patina]), + 1, + 1, + Arc::new(ReceiptlessWorldWorker), + ) + .await + .unwrap(); + + let error = admit_world_elaboration_wave(&campaign, "room", run).unwrap_err(); + + assert!(error.to_string().contains("lacks model receipt custody")); + } } diff --git a/crates/ghostlight-dungeon/src/kernel.rs b/crates/ghostlight-dungeon/src/kernel.rs index c137da0..1c51ace 100644 --- a/crates/ghostlight-dungeon/src/kernel.rs +++ b/crates/ghostlight-dungeon/src/kernel.rs @@ -75,11 +75,7 @@ pub enum CommandResult { enum KernelInput { World(WorldCommand), - Elaboration { - finalized: crate::elaboration::FinalizedWorldElaboration, - evidence_receipts: Vec, - canon_candidates: Vec, - }, + Elaboration(crate::elaboration::FinalizedWorldElaboration), Mutation { authority: crate::transition::MutationAuthorityEnvelope, batch: crate::transition::WorldMutationBatch, @@ -116,17 +112,9 @@ impl WorldKernel { while let Some(request) = rx.recv().await { let result = match request.input { KernelInput::World(command) => execute(&store, &mut assessments, command), - KernelInput::Elaboration { - finalized, - evidence_receipts, - canon_candidates, - } => execute_finalized_elaboration( - &store, - &mut assessments, - finalized, - evidence_receipts, - canon_candidates, - ), + KernelInput::Elaboration(finalized) => { + execute_finalized_elaboration(&store, &mut assessments, finalized) + } KernelInput::Mutation { authority, batch } => { execute_mutation_batch(&store, authority, batch) } @@ -171,17 +159,11 @@ impl WorldKernel { pub async fn commit_elaboration( &self, finalized: crate::elaboration::FinalizedWorldElaboration, - evidence_receipts: Vec, - canon_candidates: Vec, ) -> Result { let (reply, receive) = oneshot::channel(); self.tx .send(Request { - input: KernelInput::Elaboration { - finalized, - evidence_receipts, - canon_candidates, - }, + input: KernelInput::Elaboration(finalized), reply, }) .await @@ -196,15 +178,13 @@ fn execute_finalized_elaboration( store: &CampaignStore, assessments: &mut BTreeMap, finalized: crate::elaboration::FinalizedWorldElaboration, - evidence_receipts: Vec, - canon_candidates: Vec, ) -> Result { let campaign_id = single_campaign_id(store)?; let (_, campaign): (_, Campaign) = store .load("campaign.v1", &campaign_id) .map_err(persist)? .ok_or(KernelError::NotFound)?; - let (expected_revision, elaboration, semantic_verifier_receipt) = finalized + let (expected_revision, elaboration, model_stage_receipts) = finalized .into_kernel_parts(&campaign) .map_err(|error| KernelError::Invalid(error.to_string()))?; execute( @@ -213,9 +193,9 @@ fn execute_finalized_elaboration( WorldCommand::ElaborateLocality { expected_revision, elaboration, - evidence_receipts, - canon_candidates, - model_stage_receipts: vec![semantic_verifier_receipt], + evidence_receipts: Vec::new(), + canon_candidates: Vec::new(), + model_stage_receipts, }, ) } @@ -4735,6 +4715,7 @@ pub(crate) mod tests { fn civic_verifier_receipt( campaign: &Campaign, expansion: &mut RegionExpansion, + source_receipt_ids: Vec, ) -> crate::model::ModelStageReceipt { let digest = crate::compiler::civic_candidate_digest(expansion).unwrap(); let mut receipt = crate::model::ModelStageReceipt { @@ -4746,7 +4727,7 @@ pub(crate) mod tests { snapshot_binding: String::new(), request_hash: test_action_digest("civic-verifier-request"), output_hash: test_action_digest("civic-verifier-output"), - source_receipt_ids: vec![], + source_receipt_ids, latency_ms: 1, validation_result: "valid".into(), local_validation_error: None, @@ -4881,17 +4862,67 @@ pub(crate) mod tests { async fn invoke( &self, invocation: crate::elaboration::ElaborationSubAgentInvocation, - ) -> anyhow::Result { + ) -> std::result::Result< + crate::elaboration::ElaborationSubAgentOutput< + crate::elaboration::WorldElaborationProposal, + >, + crate::elaboration::ElaborationSubAgentFailure, + > { let index = invocation.dispatch.title_dispatch_count as usize - 1; let operation = self .operations .get(&invocation.dispatch.title) .and_then(|operations| operations.get(index)) .cloned() - .ok_or_else(|| anyhow::anyhow!("fixture elaborator received an extra dispatch"))?; - Ok(crate::elaboration::WorldElaborationProposal { - schema: "ghostlight.world_elaboration_proposal.v1".into(), - operation, + .ok_or_else(|| crate::elaboration::ElaborationSubAgentFailure { + diagnostic: "fixture elaborator received an extra dispatch".into(), + model_stage_receipts: Vec::new(), + })?; + let binding = crate::elaboration::world_elaboration_invocation_binding( + &invocation.wave, + &invocation.dispatch, + ) + .map_err(|error| crate::elaboration::ElaborationSubAgentFailure { + diagnostic: error.to_string(), + model_stage_receipts: Vec::new(), + })?; + let mut model_receipt = crate::model::ModelStageReceipt { + schema: "ghostlight.persona_stage_receipt.v1".into(), + receipt_hash: String::new(), + provider: "fixture".into(), + model: "fixture-model".into(), + stage: format!( + "world_elaboration_{}", + invocation + .dispatch + .title + .display_name() + .to_ascii_lowercase() + ), + snapshot_binding: String::new(), + request_hash: test_action_digest(&format!( + "elaboration-request:{}", + invocation.dispatch.ordinal + )), + output_hash: test_action_digest(&format!( + "elaboration-output:{}", + invocation.dispatch.ordinal + )), + source_receipt_ids: Vec::new(), + latency_ms: 1, + validation_result: "valid".into(), + local_validation_error: None, + input_chars: 1, + output_chars: 1, + provider_attempts: Vec::new(), + }; + model_receipt.rebind_snapshot(binding); + Ok(crate::elaboration::ElaborationSubAgentOutput { + proposal: crate::elaboration::WorldElaborationProposal { + schema: "ghostlight.world_elaboration_proposal.v1".into(), + operation, + }, + model_stage_receipts: vec![model_receipt], }) } } @@ -7923,7 +7954,7 @@ pub(crate) mod tests { let seed = campaign(); let original = seed.locations["room"].clone(); let mut elaboration = civic_locality_elaboration(); - let verifier_receipt = civic_verifier_receipt(&seed, &mut elaboration.expansion); + let verifier_receipt = civic_verifier_receipt(&seed, &mut elaboration.expansion, vec![]); kernel .command(WorldCommand::CreateCampaign { campaign: seed, @@ -8081,7 +8112,9 @@ pub(crate) mod tests { expected.expansion.locations[0] .persistent_features .push("A weathered bronze duck statue locals call Harold".into()); - let run = dispatch_titled_operations(&seed, "room", titled_operations_for(&expected)).await; + let operations = titled_operations_for(&expected); + let expected_model_receipt_count = operations.len() + 1; + let run = dispatch_titled_operations(&seed, "room", operations).await; let admission = admit_world_elaboration_wave(&seed, "room", run).unwrap(); assert!(admission.rejections().is_empty()); assert_eq!(admission.candidate(), Some(&expected)); @@ -8095,8 +8128,18 @@ pub(crate) mod tests { } if persistent_features.iter().any(|feature| feature.contains("Harold")) ) })); + let causal_receipt_ids = admission + .model_stage_receipts() + .iter() + .map(|receipt| receipt.storage_key().to_owned()) + .collect::>(); let mut verifier_candidate = expected.expansion.clone(); - let verifier_receipt = civic_verifier_receipt(&seed, &mut verifier_candidate); + let missing_ancestry = civic_verifier_receipt(&seed, &mut verifier_candidate, vec![]); + let error = + finalize_world_elaboration(&seed, admission.clone(), missing_ancestry).unwrap_err(); + assert!(error.to_string().contains("ancestry")); + let verifier_receipt = + civic_verifier_receipt(&seed, &mut verifier_candidate, causal_receipt_ids); let finalized = finalize_world_elaboration(&seed, admission, verifier_receipt).unwrap(); kernel .command(WorldCommand::CreateCampaign { @@ -8107,10 +8150,7 @@ pub(crate) mod tests { .await .unwrap(); - let result = kernel - .commit_elaboration(finalized, vec![], vec![]) - .await - .unwrap(); + let result = kernel.commit_elaboration(finalized).await.unwrap(); let CommandResult::Committed { campaign, receipt } = result else { panic!("expected committed titled elaboration") }; @@ -8123,6 +8163,10 @@ pub(crate) mod tests { .any(|feature| feature.contains("Harold")) ); assert_eq!(store.keys("world_mutation_batch.v1").unwrap().len(), 1); + assert_eq!( + store.keys("persona_stage_receipt.v1").unwrap().len(), + expected_model_receipt_count + ); let batch = store .load_all::("world_mutation_batch.v1") .unwrap() @@ -8152,8 +8196,14 @@ pub(crate) mod tests { let expected = civic_locality_elaboration(); let run = dispatch_titled_operations(&seed, "room", titled_operations_for(&expected)).await; let admission = admit_world_elaboration_wave(&seed, "room", run).unwrap(); + let causal_receipt_ids = admission + .model_stage_receipts() + .iter() + .map(|receipt| receipt.storage_key().to_owned()) + .collect::>(); let mut verifier_candidate = expected.expansion.clone(); - let verifier_receipt = civic_verifier_receipt(&seed, &mut verifier_candidate); + let verifier_receipt = + civic_verifier_receipt(&seed, &mut verifier_candidate, causal_receipt_ids); let finalized = finalize_world_elaboration(&seed, admission, verifier_receipt).unwrap(); kernel .command(WorldCommand::CreateCampaign { @@ -8171,10 +8221,7 @@ pub(crate) mod tests { .await .unwrap(); - let error = kernel - .commit_elaboration(finalized, vec![], vec![]) - .await - .unwrap_err(); + let error = kernel.commit_elaboration(finalized).await.unwrap_err(); assert!(error.to_string().contains("stale")); let stored = store diff --git a/notes/ghostlight-current-system-map.md b/notes/ghostlight-current-system-map.md index a0deeac..d7d3d44 100644 --- a/notes/ghostlight-current-system-map.md +++ b/notes/ghostlight-current-system-map.md @@ -1031,14 +1031,22 @@ blocked, that slot remains unused instead of increasing another title's frequency or creating catch-up debt. A bounded wave invokes the scheduled sub-agents in parallel. One typed wave binding names the immutable snapshot and is passed to every invocation and returned with every proposal. Successful -proposals return in deterministic ordinal order. A failed wave returns the -consumed schedule, every completed proposal, and the exact failed dispatches, -so persisted fairness state cannot advance without an explanatory receipt. +proposals return in deterministic ordinal order. Provider-backed titled workers +use the generic `ModelAgent` harness to submit one assigned typed operation to a +deterministic frozen-snapshot validator; local rejection returns as the next +tool observation within a two-step semantic budget. Patina, Ledger, Hearth, +Veil, and Ember use the fast model class; Charter and Tangle use balanced; +Numen uses capable. The worker returns the complete action/tool receipt chain +with its proposal. A failed wave returns the consumed schedule, every completed +proposal, each failed dispatch, and all available worker receipts, so fairness +state cannot advance without an explanatory receipt. Successful wave construction is opaque outside the dispatcher. The admission boundary rechecks requested and unused slots, per-title and total dispatch counts, eligible titles, ordinal windows, weights, requested shares, final -scheduler state, and the exact invocation partition before dispatch order may -decide a conflict. +scheduler state, the exact invocation partition, and every supplied worker +receipt's dispatch-specific snapshot binding before dispatch order may decide a +conflict. Every successful invocation must carry a terminal accepted model +receipt; generic receiptless scheduler fixtures cannot cross world admission. Those proposals are not canonical mutations. Each invocation may return one additive `WorldElaborationOperation`: place, route, branch-local fact, @@ -1050,9 +1058,18 @@ prior dispatch ordinal. It merges accepted operations into one non-canonical `LocalityElaboration`; ordinary locality validation owns the resulting structural diagnostic. +Titled operations cannot claim source-evidence receipt IDs or canon-candidate +authority. Facts are branch-local or provisional; profiles and relations carry +no source receipts. `WorldKernel::commit_elaboration` accepts only the opaque +finalized elaboration capability, not caller-supplied evidence or canon +candidates. Adding source-grounded elaboration later therefore requires an +explicit typed binding rather than an unattached vector at the commit seam. + A titled worker must leave the civic semantic-verifier receipt empty. `finalize_world_elaboration` binds the immutable admitted candidate to one independent verifier receipt that may accept or reject but cannot rewrite it. +Its ancestry must equal the complete admitted worker-receipt set, without +omissions, additions, or duplicates. Admission and finalization values are opaque, serialize-only capability receipts; callers cannot deserialize or reconstruct them as commit authority. `WorldKernel::commit_elaboration` consumes that final value, revalidates the @@ -1061,11 +1078,24 @@ inside its mailbox, then uses the existing `ElaborateLocality` path. That shared path lowers the complete candidate into exact permitted `WorldMutation` operations, applies the closed reducer, projects the accepted result, and persists the aggregate campaign, authority, batch, and mutation receipt -atomically. Titled workers never receive a `WorldCommand`, permit, mutation -batch, store, or kernel write handle. The current proposal algebra is additive +atomically together with every titled-worker and semantic-verifier model +receipt. Titled workers never receive a `WorldCommand`, permit, mutation batch, +store, or kernel write handle. The current proposal algebra is additive locality elaboration; replacement of existing canonical subjects remains outside this authority. +The strategic acceptance runner exercises this path as a deliberate hybrid. +The existing destination compiler first commits the complete civic foundation +for one canonical locality. A second revision-bound titled wave then adds one +Patina child place with exact reciprocal routes, preserves the next civic +manifest version through Charter, and admits title-specific facts and a +political relation before independent civic verification and a second kernel +commit. The acceptance profile allocates three Patina calls and two calls to +each other title per locality; a seventeen-slot pass therefore invokes workers +in exact configured proportion under bounded parallelism. This proves the +titled path against a real provider without claiming that the older civic +foundation compiler has already been replaced by the swarm. + Both destination paths synthesize the smallest compatible branch-local routes, geometry, people, supplies, procedures, capacity, responsibility, and doctrine needed for play. Those choices remain visible as `branch_assumptions`; they may