diff --git a/crates/ghostlight-dungeon/src/agent.rs b/crates/ghostlight-dungeon/src/agent.rs index cf143b7..19b5b82 100644 --- a/crates/ghostlight-dungeon/src/agent.rs +++ b/crates/ghostlight-dungeon/src/agent.rs @@ -46,6 +46,13 @@ pub struct ModelAgentToolContext { } pub enum ModelAgentToolOutcome { + /// The typed action was applied to the tool's private workbench, but the + /// agent has not yet produced a terminal result. Canonical state remains + /// untouched; the observation describes the updated draft or next need. + Continue { + observation: Finding, + receipts: Vec, + }, Accepted { output: Output, receipts: Vec, @@ -87,7 +94,7 @@ pub async fn run_model_agent( let mut receipts = Vec::new(); let mut transcript = String::new(); - let mut last_finding = None; + let mut last_observation = None; for step in 0..spec.max_steps { let source_receipt_ids = causal_source_ids(&spec.source_receipt_ids, &receipts); let request = ModelStageRequest { @@ -126,8 +133,13 @@ pub async fn run_model_agent( "message":"agent returned no typed action", }); mark_model_receipt_semantic_invalid(&mut stage.receipt, &finding); - transcript.push_str(&tool_observation(step, &serde_json::Value::Null, &finding)); - last_finding = Some(finding); + transcript.push_str(&tool_observation( + step, + "rejected", + &serde_json::Value::Null, + &finding, + )); + last_observation = Some(finding); receipts.push(stage.receipt); continue; } @@ -140,8 +152,8 @@ pub async fn run_model_agent( "message":error.to_string(), }); mark_model_receipt_semantic_invalid(&mut stage.receipt, &finding); - transcript.push_str(&tool_observation(step, &action_value, &finding)); - last_finding = Some(finding); + transcript.push_str(&tool_observation(step, "rejected", &action_value, &finding)); + last_observation = Some(finding); receipts.push(stage.receipt); continue; } @@ -157,6 +169,33 @@ pub async fn run_model_agent( ), }; match tool.invoke(action, &tool_context).await { + ModelAgentToolOutcome::Continue { + observation, + receipts: tool_receipts, + } => { + let observation = match serde_json::to_value(observation) { + Ok(observation) => observation, + Err(error) => { + let message = format!( + "model agent {} could not serialize its typed tool observation: {error}", + spec.stage + ); + mark_model_receipt_semantic_invalid(&mut stage.receipt, &message); + receipts.push(stage.receipt); + receipts.extend(tool_receipts); + return Err(ModelAgentFailure { message, receipts }); + } + }; + transcript.push_str(&tool_observation( + step, + "continued", + &action_value, + &observation, + )); + last_observation = Some(observation); + receipts.push(stage.receipt); + receipts.extend(tool_receipts); + } ModelAgentToolOutcome::Accepted { output, receipts: tool_receipts, @@ -183,8 +222,8 @@ pub async fn run_model_agent( } }; mark_model_receipt_semantic_invalid(&mut stage.receipt, &finding); - transcript.push_str(&tool_observation(step, &action_value, &finding)); - last_finding = Some(finding); + transcript.push_str(&tool_observation(step, "rejected", &action_value, &finding)); + last_observation = Some(finding); receipts.push(stage.receipt); receipts.extend(tool_receipts); } @@ -202,18 +241,21 @@ pub async fn run_model_agent( Err(ModelAgentFailure { message: format!( - "model agent {} exhausted {} semantic steps; final tool finding: {}", + "model agent {} exhausted {} semantic steps; final tool observation: {}", spec.stage, spec.max_steps, - last_finding - .map(|finding| finding.to_string()) + last_observation + .map(|observation| observation.to_string()) .unwrap_or_else(|| "none".into()), ), receipts, }) } -fn causal_source_ids(base: &[String], receipts: &[ModelStageReceipt]) -> Vec { +/// Builds one deterministic causal ancestry set for every model stage. This is +/// model/tool provenance only; callers must not reuse it as canonical world +/// evidence. +pub(crate) fn causal_source_ids(base: &[String], receipts: &[ModelStageReceipt]) -> Vec { base.iter() .cloned() .chain( @@ -228,14 +270,15 @@ fn causal_source_ids(base: &[String], receipts: &[ModelStageReceipt]) -> Vec String { format!( - "\n\nTOOL OBSERVATION AFTER AGENT STEP {}:\n{}\nPREVIOUS REJECTED ACTION:\n{}\nReturn the next complete typed tool action. Preserve frozen identity and useful valid work; change what the finding actually rejects.", + "\n\nTOOL OBSERVATION AFTER AGENT STEP {} ({status}):\n{}\nPREVIOUS TOOL ACTION:\n{}\nReturn the next complete typed tool action. Preserve frozen identity and useful valid draft work; change only what the observation actually rejects or requests.", step + 1, - serde_json::to_string(finding).unwrap_or_else(|_| "null".into()), - serde_json::to_string(rejected_action).unwrap_or_else(|_| "null".into()), + serde_json::to_string(observation).unwrap_or_else(|_| "null".into()), + serde_json::to_string(action).unwrap_or_else(|_| "null".into()), ) } @@ -257,6 +300,7 @@ mod tests { #[derive(Clone, Debug, Serialize)] #[serde(tag = "kind", rename_all = "snake_case")] enum ExactFinding { + DraftStored { value: String }, WrongValue { received: String }, } @@ -303,6 +347,13 @@ mod tests { output: action.value, receipts: Vec::new(), } + } else if action.value == "drafted" { + ModelAgentToolOutcome::Continue { + observation: ExactFinding::DraftStored { + value: action.value, + }, + receipts: Vec::new(), + } } else { ModelAgentToolOutcome::Rejected { finding: ExactFinding::WrongValue { @@ -376,10 +427,45 @@ mod tests { ); let requests = model.requests.lock().unwrap(); assert!(requests[1].lived_stream.contains("wrong_value")); + assert!(requests[1].lived_stream.contains("PREVIOUS TOOL ACTION")); + } + + #[tokio::test] + async fn successful_nonterminal_tool_action_preserves_draft_progress() { + let model = ScriptedModel { + outputs: Mutex::new(vec![ + r#"{"value":"drafted"}"#.into(), + r#"{"value":"accepted"}"#.into(), + ]), + requests: Mutex::new(Vec::new()), + }; + let spec = ModelAgentSpec { + stage: "fixture_agent".into(), + model: MODEL_BALANCED.into(), + snapshot_binding: "snapshot:1".into(), + instructions: "Use the tool.".into(), + action_schema: serde_json::to_value(schema_for!(CandidateAction)).unwrap(), + source_receipt_ids: vec!["source:one".into()], + temperature: Some(0.0), + max_output_tokens: Some(128), + max_steps: 2, + }; + + let run = run_model_agent(&model, &spec, &mut ExactTool) + .await + .unwrap(); + + assert_eq!(run.output, "accepted"); + assert_eq!(run.receipts.len(), 2); + assert_eq!(run.receipts[0].validation_result, "valid"); + assert_eq!(run.receipts[1].validation_result, "valid"); + let requests = model.requests.lock().unwrap(); + assert!(requests[1].lived_stream.contains("continued")); + assert!(requests[1].lived_stream.contains("draft_stored")); assert!( requests[1] - .lived_stream - .contains("PREVIOUS REJECTED ACTION") + .source_receipt_ids + .contains(&run.receipts[0].storage_key().to_owned()) ); } diff --git a/crates/ghostlight-dungeon/src/compiler.rs b/crates/ghostlight-dungeon/src/compiler.rs index 133b050..601389d 100644 --- a/crates/ghostlight-dungeon/src/compiler.rs +++ b/crates/ghostlight-dungeon/src/compiler.rs @@ -7621,7 +7621,7 @@ mod tests { && request.lived_stream.contains("duplicate_statement") && request.lived_stream.contains("fact:refuge_authority") && request.lived_stream.contains("fact:refuge_resources") - && request.lived_stream.contains("PREVIOUS REJECTED ACTION"), + && request.lived_stream.contains("PREVIOUS TOOL ACTION"), Ordering::SeqCst, ); reconciliation["candidate"]["facts"][1]["statement"] = serde_json::json!( diff --git a/crates/ghostlight-dungeon/src/elaboration.rs b/crates/ghostlight-dungeon/src/elaboration.rs new file mode 100644 index 0000000..6e61b38 --- /dev/null +++ b/crates/ghostlight-dungeon/src/elaboration.rs @@ -0,0 +1,799 @@ +use anyhow::{Result, anyhow}; +use async_trait::async_trait; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::sync::Arc; + +pub const MAX_ELABORATOR_WEIGHT: u16 = 100; + +#[derive( + Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord, Hash, +)] +#[serde(rename_all = "snake_case")] +pub enum ElaboratorTitle { + /// Ordinary objects, customs, nicknames, local jokes, and other reusable + /// low-stakes texture. + Patina, + /// Government, law, offices, selection, succession, and redress. + Charter, + /// Resources, labor, trade, infrastructure, scarcity, and class pressure. + Ledger, + /// Kinship, daily life, care, obligation, belonging, and neighborhood ties. + Hearth, + /// Factions, alliances, rivalries, leverage, and political maneuvering. + Tangle, + /// Secrets, rumors, misinformation, taboos, and unevenly held knowledge. + Veil, + /// Active disputes, hazards, instability, escalation, and urgent pressure. + Ember, + /// Religion, magic, ritual, awe, cosmology, and the genuinely strange. + Numen, +} + +impl ElaboratorTitle { + pub const ALL: [Self; 8] = [ + Self::Patina, + Self::Charter, + Self::Ledger, + Self::Hearth, + Self::Tangle, + Self::Veil, + Self::Ember, + Self::Numen, + ]; + + pub fn mandate(self) -> &'static str { + match self { + Self::Patina => { + "Add durable, locally grounded, low-stakes texture that later events may acquire meaning from." + } + Self::Charter => { + "Elaborate legible institutions, offices, procedures, succession, public authority, and redress." + } + Self::Ledger => { + "Elaborate material dependencies: work, resources, infrastructure, exchange, scarcity, and class pressure." + } + Self::Hearth => { + "Elaborate ordinary social life: kinship, care, neighborhood, obligation, belonging, and private stakes." + } + Self::Tangle => { + "Elaborate political relationships: factions, alliances, rivalries, leverage, constituencies, and plots." + } + Self::Veil => { + "Elaborate uneven knowledge: secrets, rumors, taboos, misinformation, mysteries, and disclosure paths." + } + Self::Ember => { + "Elaborate active pressure: disputes, hazards, instability, escalation paths, and urgent consequences." + } + Self::Numen => { + "Elaborate numinous meaning: religion, ritual, magic, cosmology, wonder, and bounded strangeness." + } + } + } + + pub fn display_name(self) -> &'static str { + match self { + Self::Patina => "Patina", + Self::Charter => "Charter", + Self::Ledger => "Ledger", + Self::Hearth => "Hearth", + Self::Tangle => "Tangle", + Self::Veil => "Veil", + Self::Ember => "Ember", + Self::Numen => "Numen", + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct ElaboratorDescriptor { + pub title: ElaboratorTitle, + pub display_name: String, + pub mandate: String, +} + +pub fn elaborator_catalog() -> Vec { + ElaboratorTitle::ALL + .into_iter() + .map(|title| ElaboratorDescriptor { + title, + display_name: title.display_name().into(), + mandate: title.mandate().into(), + }) + .collect() +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct ElaboratorControl { + pub title: ElaboratorTitle, + /// Relative scheduler weight. Zero disables this elaborator. Positive + /// values are normalized across the titles eligible for each dispatch. + #[schemars(range(min = 0, max = 100))] + pub weight: u16, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct WorldElaborationProfile { + pub schema: String, + pub controls: Vec, +} + +impl Default for WorldElaborationProfile { + fn default() -> Self { + Self { + schema: "ghostlight.world_elaboration_profile.v1".into(), + controls: ElaboratorTitle::ALL + .into_iter() + .map(|title| ElaboratorControl { title, weight: 50 }) + .collect(), + } + } +} + +impl WorldElaborationProfile { + pub fn weights(&self) -> Result> { + if self.schema != "ghostlight.world_elaboration_profile.v1" { + return Err(anyhow!("world elaboration profile schema is unsupported")); + } + let mut weights = BTreeMap::new(); + for control in &self.controls { + if control.weight > MAX_ELABORATOR_WEIGHT + || weights.insert(control.title, control.weight).is_some() + { + return Err(anyhow!( + "world elaboration profile requires unique titles with weights from zero to {MAX_ELABORATOR_WEIGHT}" + )); + } + } + if weights.values().all(|weight| *weight == 0) { + return Err(anyhow!( + "world elaboration profile must enable at least one titled elaborator" + )); + } + Ok(weights) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct ElaborationDispatchState { + pub schema: String, + pub profile_digest: String, + /// Smooth weighted-round-robin credit across every enabled title. Blocked + /// selections consume their configured slots without invoking an agent, + /// so their share is never donated to another elaborator. + pub current_scores: BTreeMap, + pub dispatch_counts: BTreeMap, + pub total_budget_slots: u64, + pub total_dispatches: u64, +} + +impl Default for ElaborationDispatchState { + fn default() -> Self { + Self { + schema: "ghostlight.elaboration_dispatch_state.v1".into(), + profile_digest: String::new(), + current_scores: BTreeMap::new(), + dispatch_counts: BTreeMap::new(), + total_budget_slots: 0, + total_dispatches: 0, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct ElaborationDispatch { + pub schema: String, + pub budget_ordinal: u64, + pub ordinal: u64, + pub title: ElaboratorTitle, + pub title_weight: u16, + pub total_enabled_weight: u32, + /// Requested share of the complete configured invocation budget. + pub requested_share_millionths: u32, + pub title_dispatch_count: u64, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct ElaborationScheduleReceipt { + pub schema: String, + pub requested_invocations: u32, + pub unused_invocations: u32, + pub eligible_titles: BTreeSet, + /// Actual invocations allocated inside this receipt's budget window. + pub dispatch_counts: BTreeMap, + /// Configured allocations that could not invoke their titled agent. These + /// remain unused instead of being redistributed to another slider. + pub unused_counts: BTreeMap, + pub dispatches: Vec, + pub final_state: ElaborationDispatchState, +} + +enum ElaborationBudgetAllocation { + Dispatch(ElaborationDispatch), + Unused(ElaboratorTitle), +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct ElaborationWaveBinding { + pub schema: String, + /// Content-addressed or revision-addressed identity for the immutable + /// world projection shared by every invocation in this wave. + pub snapshot_binding: String, +} + +impl ElaborationWaveBinding { + pub fn validate(&self) -> Result<()> { + if self.schema != "ghostlight.elaboration_wave_binding.v1" { + return Err(anyhow!("elaboration wave binding schema is unsupported")); + } + if self.snapshot_binding.trim().is_empty() { + return Err(anyhow!("elaboration wave snapshot binding cannot be empty")); + } + Ok(()) + } +} + +#[derive(Clone, Debug)] +pub struct ElaborationSubAgentInvocation { + pub wave: ElaborationWaveBinding, + pub dispatch: ElaborationDispatch, +} + +#[derive(Debug)] +pub struct ElaborationInvocation { + pub wave: ElaborationWaveBinding, + pub dispatch: ElaborationDispatch, + /// A proposal against the frozen elaboration snapshot. The invocation + /// cannot commit canonical world state; admission and conflict handling + /// remain downstream owners. + pub proposal: Proposal, +} + +#[derive(Debug)] +pub struct ElaborationWaveRun { + pub wave: ElaborationWaveBinding, + pub schedule: ElaborationScheduleReceipt, + pub invocations: Vec>, +} + +#[derive(Clone, Debug)] +pub struct ElaborationInvocationFailure { + pub dispatch: Option, + pub diagnostic: String, +} + +#[derive(Debug)] +pub struct ElaborationWaveFailure { + pub wave: Option, + pub schedule: Option, + pub completed_invocations: Vec>, + pub invocation_failures: Vec, +} + +#[async_trait] +pub trait ElaborationSubAgentPort: Send + Sync { + async fn invoke(&self, invocation: ElaborationSubAgentInvocation) -> Result; +} + +pub struct ElaborationScheduler { + weights: BTreeMap, + state: ElaborationDispatchState, +} + +impl ElaborationScheduler { + pub fn new(profile: &WorldElaborationProfile) -> Result { + Self::from_state(profile, ElaborationDispatchState::default()) + } + + pub fn from_state( + profile: &WorldElaborationProfile, + mut state: ElaborationDispatchState, + ) -> Result { + let weights = profile.weights()?; + let profile_digest = crate::legacy_transition::digest_serializable(&( + "ghostlight.world_elaboration_profile.v1", + &weights, + ))?; + if state.schema != "ghostlight.elaboration_dispatch_state.v1" { + return Err(anyhow!("elaboration dispatch state schema is unsupported")); + } + if state.profile_digest.is_empty() { + state.profile_digest = profile_digest; + } else if state.profile_digest != profile_digest { + return Err(anyhow!( + "elaboration dispatch state belongs to a different slider profile" + )); + } + state + .current_scores + .retain(|title, _| weights.contains_key(title)); + state + .dispatch_counts + .retain(|title, _| weights.contains_key(title)); + Ok(Self { weights, state }) + } + + pub fn state(&self) -> &ElaborationDispatchState { + &self.state + } + + fn next_allocation( + &mut self, + eligible_titles: &BTreeSet, + ) -> ElaborationBudgetAllocation { + let enabled = self + .weights + .iter() + .filter(|(_, weight)| **weight > 0) + .map(|(title, weight)| (*title, *weight)) + .collect::>(); + let total_enabled_weight = enabled + .iter() + .map(|(_, weight)| u32::from(*weight)) + .sum::(); + debug_assert!(total_enabled_weight > 0); + + let mut selected = None; + for (title, weight) in &enabled { + let score = self.state.current_scores.entry(*title).or_default(); + *score = score.saturating_add(i64::from(*weight)); + let candidate = (*title, *score); + if selected.is_none_or(|best: (ElaboratorTitle, i64)| candidate.1 > best.1) { + selected = Some(candidate); + } + } + let (title, _) = selected.expect("a valid profile requires one enabled title"); + *self.state.current_scores.entry(title).or_default() -= i64::from(total_enabled_weight); + self.state.total_budget_slots = self.state.total_budget_slots.saturating_add(1); + if !eligible_titles.contains(&title) { + return ElaborationBudgetAllocation::Unused(title); + } + + self.state.total_dispatches = self.state.total_dispatches.saturating_add(1); + let title_dispatch_count = self + .state + .dispatch_counts + .entry(title) + .and_modify(|count| *count = count.saturating_add(1)) + .or_insert(1); + let title_weight = self.weights[&title]; + ElaborationBudgetAllocation::Dispatch(ElaborationDispatch { + schema: "ghostlight.elaboration_dispatch.v1".into(), + budget_ordinal: self.state.total_budget_slots, + ordinal: self.state.total_dispatches, + title, + title_weight, + total_enabled_weight, + requested_share_millionths: u32::from(title_weight).saturating_mul(1_000_000) + / total_enabled_weight, + title_dispatch_count: *title_dispatch_count, + }) + } + + pub fn schedule( + &mut self, + eligible_titles: &BTreeSet, + invocation_budget: u32, + ) -> ElaborationScheduleReceipt { + let mut dispatches = Vec::with_capacity(invocation_budget as usize); + let mut unused_counts = BTreeMap::new(); + for _ in 0..invocation_budget { + match self.next_allocation(eligible_titles) { + ElaborationBudgetAllocation::Dispatch(dispatch) => dispatches.push(dispatch), + ElaborationBudgetAllocation::Unused(title) => { + *unused_counts.entry(title).or_default() += 1; + } + } + } + ElaborationScheduleReceipt { + schema: "ghostlight.elaboration_schedule_receipt.v1".into(), + requested_invocations: invocation_budget, + unused_invocations: unused_counts.values().copied().sum(), + eligible_titles: eligible_titles.clone(), + dispatch_counts: dispatches + .iter() + .fold(BTreeMap::new(), |mut counts, dispatch| { + *counts.entry(dispatch.title).or_default() += 1; + counts + }), + unused_counts, + dispatches, + final_state: self.state.clone(), + } + } +} + +/// Dispatches one immutable-snapshot elaboration wave. Weight determines the +/// number of actual sub-agent invocations, not prompt emphasis. Proposals are +/// returned in deterministic dispatch order after parallel execution; this +/// function has no canonical world-state writer. +pub async fn dispatch_elaboration_wave( + scheduler: &mut ElaborationScheduler, + wave: ElaborationWaveBinding, + eligible_titles: &BTreeSet, + invocation_budget: u32, + parallelism: usize, + worker: Arc, +) -> std::result::Result, ElaborationWaveFailure> +where + Worker: ElaborationSubAgentPort + 'static, + Proposal: Send + 'static, +{ + if let Err(error) = wave.validate() { + return Err(ElaborationWaveFailure { + wave: Some(wave), + schedule: None, + completed_invocations: Vec::new(), + invocation_failures: vec![ElaborationInvocationFailure { + dispatch: None, + diagnostic: error.to_string(), + }], + }); + } + if parallelism == 0 { + return Err(ElaborationWaveFailure { + wave: Some(wave), + schedule: None, + completed_invocations: Vec::new(), + invocation_failures: vec![ElaborationInvocationFailure { + dispatch: None, + diagnostic: "elaboration wave parallelism must be greater than zero".into(), + }], + }); + } + let schedule = scheduler.schedule(eligible_titles, invocation_budget); + let semaphore = Arc::new(tokio::sync::Semaphore::new(parallelism)); + let mut jobs = tokio::task::JoinSet::new(); + let mut task_dispatches = HashMap::new(); + for dispatch in schedule.dispatches.iter().cloned() { + let worker = worker.clone(); + let semaphore = semaphore.clone(); + let wave = wave.clone(); + let task_dispatch = dispatch.clone(); + let task = jobs.spawn(async move { + let _slot = + semaphore + .acquire_owned() + .await + .map_err(|_| ElaborationInvocationFailure { + dispatch: Some(dispatch.clone()), + diagnostic: "elaboration invocation gate closed".into(), + })?; + let request = ElaborationSubAgentInvocation { + wave: wave.clone(), + dispatch: dispatch.clone(), + }; + let proposal = + worker + .invoke(request) + .await + .map_err(|error| ElaborationInvocationFailure { + dispatch: Some(dispatch.clone()), + diagnostic: error.to_string().chars().take(2_000).collect(), + })?; + Ok::<_, ElaborationInvocationFailure>(ElaborationInvocation { + wave, + dispatch, + proposal, + }) + }); + task_dispatches.insert(task.id(), task_dispatch); + } + + let mut invocations = Vec::with_capacity(schedule.dispatches.len()); + let mut invocation_failures = Vec::new(); + while let Some(result) = jobs.join_next_with_id().await { + match result { + Ok((task_id, Ok(invocation))) => { + task_dispatches.remove(&task_id); + invocations.push(invocation); + } + Ok((task_id, Err(failure))) => { + task_dispatches.remove(&task_id); + invocation_failures.push(failure); + } + Err(error) => invocation_failures.push(ElaborationInvocationFailure { + dispatch: task_dispatches.remove(&error.id()), + diagnostic: format!("elaboration sub-agent task failed: {error}"), + }), + } + } + invocations.sort_by_key(|invocation| invocation.dispatch.ordinal); + invocation_failures.sort_by_key(|failure| { + failure + .dispatch + .as_ref() + .map(|dispatch| dispatch.ordinal) + .unwrap_or(u64::MAX) + }); + if !invocation_failures.is_empty() { + return Err(ElaborationWaveFailure { + wave: Some(wave), + schedule: Some(schedule), + completed_invocations: invocations, + invocation_failures, + }); + } + Ok(ElaborationWaveRun { + wave, + schedule, + invocations, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn profile(weights: &[(ElaboratorTitle, u16)]) -> WorldElaborationProfile { + WorldElaborationProfile { + schema: "ghostlight.world_elaboration_profile.v1".into(), + controls: weights + .iter() + .map(|(title, weight)| ElaboratorControl { + title: *title, + weight: *weight, + }) + .collect(), + } + } + + fn wave_binding() -> ElaborationWaveBinding { + ElaborationWaveBinding { + schema: "ghostlight.elaboration_wave_binding.v1".into(), + snapshot_binding: "world:7:seed-sha256".into(), + } + } + + struct CountingSubAgent { + counts: std::sync::Mutex>, + active: std::sync::atomic::AtomicUsize, + maximum: std::sync::atomic::AtomicUsize, + } + + #[async_trait] + impl ElaborationSubAgentPort for CountingSubAgent { + async fn invoke(&self, invocation: ElaborationSubAgentInvocation) -> Result { + use std::sync::atomic::Ordering; + assert_eq!(invocation.wave, wave_binding()); + let dispatch = invocation.dispatch; + let active = self.active.fetch_add(1, Ordering::SeqCst) + 1; + self.maximum.fetch_max(active, Ordering::SeqCst); + tokio::time::sleep(std::time::Duration::from_millis(2)).await; + *self + .counts + .lock() + .unwrap() + .entry(dispatch.title) + .or_default() += 1; + self.active.fetch_sub(1, Ordering::SeqCst); + Ok(format!("proposal:{}", dispatch.ordinal)) + } + } + + struct PartiallyFailingSubAgent; + + #[async_trait] + impl ElaborationSubAgentPort for PartiallyFailingSubAgent { + async fn invoke(&self, invocation: ElaborationSubAgentInvocation) -> Result { + if invocation.dispatch.ordinal == 3 { + return Err(anyhow!("fixture refusal")); + } + if invocation.dispatch.ordinal == 4 { + panic!("fixture panic"); + } + Ok(format!("proposal:{}", invocation.dispatch.ordinal)) + } + } + + #[test] + fn weighted_schedule_dispatches_in_proportion_to_slider_share() { + let profile = profile(&[(ElaboratorTitle::Patina, 20), (ElaboratorTitle::Tangle, 80)]); + let mut scheduler = ElaborationScheduler::new(&profile).unwrap(); + let eligible = BTreeSet::from([ElaboratorTitle::Patina, ElaboratorTitle::Tangle]); + + let receipt = scheduler.schedule(&eligible, 100); + + assert_eq!(receipt.unused_invocations, 0); + assert_eq!(receipt.dispatch_counts[&ElaboratorTitle::Patina], 20); + assert_eq!(receipt.dispatch_counts[&ElaboratorTitle::Tangle], 80); + assert_eq!( + receipt.final_state.dispatch_counts[&ElaboratorTitle::Patina], + 20 + ); + assert_eq!( + receipt.final_state.dispatch_counts[&ElaboratorTitle::Tangle], + 80 + ); + assert!(receipt.dispatches.iter().all(|dispatch| { + dispatch.requested_share_millionths + == match dispatch.title { + ElaboratorTitle::Patina => 200_000, + ElaboratorTitle::Tangle => 800_000, + _ => unreachable!(), + } + })); + } + + #[tokio::test] + async fn weighted_share_controls_actual_parallel_sub_agent_invocations() { + use std::sync::atomic::Ordering; + let profile = profile(&[(ElaboratorTitle::Patina, 30), (ElaboratorTitle::Tangle, 70)]); + let mut scheduler = ElaborationScheduler::new(&profile).unwrap(); + let eligible = BTreeSet::from([ElaboratorTitle::Patina, ElaboratorTitle::Tangle]); + let worker = Arc::new(CountingSubAgent { + counts: std::sync::Mutex::new(BTreeMap::new()), + active: std::sync::atomic::AtomicUsize::new(0), + maximum: std::sync::atomic::AtomicUsize::new(0), + }); + + let run = dispatch_elaboration_wave( + &mut scheduler, + wave_binding(), + &eligible, + 100, + 6, + worker.clone(), + ) + .await + .unwrap(); + + assert_eq!(run.wave, wave_binding()); + assert_eq!(run.invocations.len(), 100); + assert!( + run.invocations + .iter() + .all(|invocation| invocation.wave == wave_binding()) + ); + assert_eq!(run.invocations[0].dispatch.ordinal, 1); + assert_eq!(run.invocations[99].dispatch.ordinal, 100); + let counts = worker.counts.lock().unwrap(); + assert_eq!(counts[&ElaboratorTitle::Patina], 30); + assert_eq!(counts[&ElaboratorTitle::Tangle], 70); + assert!(worker.maximum.load(Ordering::SeqCst) > 1); + assert!(worker.maximum.load(Ordering::SeqCst) <= 6); + } + + #[tokio::test] + async fn failed_wave_preserves_consumed_schedule_and_completed_evidence() { + let profile = profile(&[(ElaboratorTitle::Patina, 100)]); + let mut scheduler = ElaborationScheduler::new(&profile).unwrap(); + let failure = dispatch_elaboration_wave( + &mut scheduler, + wave_binding(), + &BTreeSet::from([ElaboratorTitle::Patina]), + 4, + 2, + Arc::new(PartiallyFailingSubAgent), + ) + .await + .unwrap_err(); + + assert_eq!(failure.wave, Some(wave_binding())); + assert_eq!(failure.schedule.as_ref().unwrap().dispatches.len(), 4); + assert_eq!(failure.completed_invocations.len(), 2); + assert_eq!(failure.invocation_failures.len(), 2); + assert_eq!( + failure.invocation_failures[0] + .dispatch + .as_ref() + .unwrap() + .ordinal, + 3 + ); + assert_eq!( + failure.invocation_failures[1] + .dispatch + .as_ref() + .unwrap() + .ordinal, + 4 + ); + assert_eq!(scheduler.state().total_budget_slots, 4); + assert!(failure.completed_invocations.iter().all(|invocation| { + invocation.wave == wave_binding() && invocation.dispatch.ordinal != 3 + })); + } + + #[test] + fn ineligible_titles_consume_their_share_without_catchup_debt() { + let profile = profile(&[(ElaboratorTitle::Patina, 20), (ElaboratorTitle::Tangle, 80)]); + let mut scheduler = ElaborationScheduler::new(&profile).unwrap(); + + let patina_only = BTreeSet::from([ElaboratorTitle::Patina]); + let first = scheduler.schedule(&patina_only, 5); + assert_eq!( + first.final_state.dispatch_counts[&ElaboratorTitle::Patina], + 1 + ); + assert_eq!(first.unused_invocations, 4); + assert_eq!(first.unused_counts[&ElaboratorTitle::Tangle], 4); + + let both = BTreeSet::from([ElaboratorTitle::Patina, ElaboratorTitle::Tangle]); + let second = scheduler.schedule(&both, 100); + assert_eq!(second.dispatch_counts[&ElaboratorTitle::Patina], 20); + assert_eq!(second.dispatch_counts[&ElaboratorTitle::Tangle], 80); + assert_eq!( + second.final_state.dispatch_counts[&ElaboratorTitle::Patina], + 21 + ); + assert_eq!( + second.final_state.dispatch_counts[&ElaboratorTitle::Tangle], + 80 + ); + } + + #[test] + fn disabled_or_blocked_elaborators_leave_budget_visibly_unused() { + let profile = profile(&[(ElaboratorTitle::Patina, 100)]); + let mut scheduler = ElaborationScheduler::new(&profile).unwrap(); + let receipt = scheduler.schedule(&BTreeSet::from([ElaboratorTitle::Veil]), 7); + + assert!(receipt.dispatches.is_empty()); + assert_eq!(receipt.unused_invocations, 7); + assert_eq!(receipt.unused_counts[&ElaboratorTitle::Patina], 7); + assert_eq!(receipt.final_state.total_budget_slots, 7); + assert_eq!(receipt.final_state.total_dispatches, 0); + } + + #[test] + fn a_partially_blocked_profile_does_not_donate_its_share() { + let profile = profile(&[(ElaboratorTitle::Patina, 20), (ElaboratorTitle::Tangle, 80)]); + let mut scheduler = ElaborationScheduler::new(&profile).unwrap(); + let receipt = scheduler.schedule(&BTreeSet::from([ElaboratorTitle::Patina]), 100); + + assert_eq!(receipt.dispatch_counts[&ElaboratorTitle::Patina], 20); + assert_eq!(receipt.unused_counts[&ElaboratorTitle::Tangle], 80); + assert_eq!(receipt.unused_invocations, 80); + assert_eq!(receipt.final_state.total_budget_slots, 100); + assert_eq!(receipt.final_state.total_dispatches, 20); + } + + #[test] + fn profile_rejects_duplicate_titles_and_an_all_zero_budget() { + assert!( + profile(&[(ElaboratorTitle::Patina, 10), (ElaboratorTitle::Patina, 20),]) + .weights() + .is_err() + ); + assert!(profile(&[(ElaboratorTitle::Patina, 0)]).weights().is_err()); + } + + #[test] + fn persisted_scheduler_state_binds_semantic_weights_not_control_order() { + let first = profile(&[(ElaboratorTitle::Patina, 25), (ElaboratorTitle::Tangle, 75)]); + let scheduler = ElaborationScheduler::new(&first).unwrap(); + let state = scheduler.state().clone(); + let reordered = profile(&[(ElaboratorTitle::Tangle, 75), (ElaboratorTitle::Patina, 25)]); + assert!(ElaborationScheduler::from_state(&reordered, state.clone()).is_ok()); + + let changed = profile(&[(ElaboratorTitle::Patina, 75), (ElaboratorTitle::Tangle, 25)]); + assert!(ElaborationScheduler::from_state(&changed, state).is_err()); + } + + #[test] + fn catalog_exposes_every_titled_slider_with_a_distinct_mandate() { + let catalog = elaborator_catalog(); + assert_eq!(catalog.len(), ElaboratorTitle::ALL.len()); + assert_eq!( + catalog + .iter() + .map(|entry| entry.title) + .collect::>() + .len(), + ElaboratorTitle::ALL.len() + ); + assert!(catalog.iter().all(|entry| !entry.mandate.trim().is_empty())); + assert!(catalog.iter().any(|entry| { + entry.title == ElaboratorTitle::Patina && entry.mandate.contains("low-stakes texture") + })); + } +} diff --git a/crates/ghostlight-dungeon/src/lib.rs b/crates/ghostlight-dungeon/src/lib.rs index b363cfa..f708414 100644 --- a/crates/ghostlight-dungeon/src/lib.rs +++ b/crates/ghostlight-dungeon/src/lib.rs @@ -7,6 +7,7 @@ pub mod compiler; pub mod consumer; pub mod d20; pub mod domain; +pub mod elaboration; pub mod gestalt; pub mod idunn_health; pub mod initiative; diff --git a/crates/ghostlight-dungeon/src/persona.rs b/crates/ghostlight-dungeon/src/persona.rs index aaf4972..af26eb9 100644 --- a/crates/ghostlight-dungeon/src/persona.rs +++ b/crates/ghostlight-dungeon/src/persona.rs @@ -1,3 +1,7 @@ +use crate::agent::{ + ModelAgentFailure, ModelAgentSpec, ModelAgentTool, ModelAgentToolContext, + ModelAgentToolOutcome, causal_source_ids, run_model_agent, +}; use crate::model::{ModelPort, ModelStageOutput, ModelStageRequest, run_validated_stage}; use crate::session_zero::{AggregatedBoundary, CampaignContract}; use anyhow::{Context, Result, anyhow}; @@ -202,10 +206,20 @@ fn cell_pipeline_failure( } anyhow::Error::new(CellPipelineFailure { diagnostic: format!("{error:#}").chars().take(4_000).collect(), - stage_receipts: prior_stage_receipts, + stage_receipts: distinct_stage_receipts(prior_stage_receipts), }) } +fn distinct_stage_receipts( + receipts: Vec, +) -> Vec { + let mut seen = BTreeSet::new(); + receipts + .into_iter() + .filter(|receipt| seen.insert(receipt.storage_key().to_owned())) + .collect() +} + #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] #[serde(deny_unknown_fields)] struct CellAppraisalProposal { @@ -213,10 +227,73 @@ struct CellAppraisalProposal { inactions: Vec, } +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +enum CellInterpreterAgentAction { + /// Efficient first attempt: publish one complete private draft for + /// deterministic compilation and semantic verification. + Submit { + decisions: BTreeMap, + }, + /// Replace exactly one decision while preserving every other draft entry. + UpsertDecision { + subject_id: String, + decision: serde_json::Value, + }, + RemoveDecision { + subject_id: String, + }, + InspectDraft, +} + +#[derive(Debug)] +enum CellInterpreterAgentOutput { + Appraisal(crate::domain::CellAppraisal), + MissingPersonaDecision { subject_ids: Vec }, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +enum CellInterpreterFinding { + DraftProgress { + decision_subject_ids: Vec, + missing_subject_ids: Vec, + }, + DraftRequired, + UnknownDecisionOwner { + subject_id: String, + allowed_subject_ids: Vec, + }, + SubmitRequiresEmptyDraft { + repair_subject_ids: Vec, + }, + DecisionNotRepairable { + subject_id: String, + repair_subject_ids: Vec, + }, + LocalValidation { + diagnostic: String, + decision_subject_ids: Vec, + }, + EffectMismatch { + rejected: Vec, + }, +} + +#[derive(Clone, Debug, Serialize)] +struct CellInterpreterEffectFinding { + subject_id: String, + mismatch_kind: CellEffectMismatchKind, + repair_guidance: String, +} + #[derive(Debug)] struct MissingExplicitCellDecision { cell_id: String, stage_receipts: Vec, + lived_stream: LivedNarrativeStream, + active_subject_ids: BTreeSet, + projector_receipts: Vec, } impl std::fmt::Display for MissingExplicitCellDecision { @@ -428,16 +505,11 @@ const CELL_PROJECTION_OUTPUT_CONTRACT: &str = r#"{ ] }"#; -const CELL_APPRAISAL_OUTPUT_CONTRACT: &str = r#"{ - "type":"object", - "required":["decisions"], - "properties":{ - "decisions":{"type":"object","description":"The supplied schema creates exactly one canonical subject-ID key per projected perspective. Never add, remove, or duplicate a subject key.","additionalProperties":{"oneOf":[ - {"type":"object","required":["action"],"properties":{"action":{"type":"object","required":["subject_id","intent","intended_effect","priority","state_references","public_channels","effects"],"properties":{"subject_id":{"type":"string"},"intent":{"type":"string"},"intended_effect":{"type":"string"},"priority":{"type":"integer"},"state_references":{"type":"array","items":{"type":"string"}},"public_channels":{"type":"array","items":{"type":"string"}},"effects":{"type":"object"}}}}}, - {"type":"object","required":["inaction"],"properties":{"inaction":{"type":"object","required":["subject_id","reason"],"properties":{"subject_id":{"type":"string"},"reason":{"type":"string","minLength":1,"maxLength":240}}}}}, - {"type":"object","required":["undecided"],"properties":{"undecided":{"type":"object","required":["reason"],"properties":{"reason":{"type":"string","minLength":1,"maxLength":240}}}}} - ]}} - } +const CELL_INTERPRETER_AGENT_OUTPUT_CONTRACT: &str = r#"{ + "kind":"submit | upsert_decision | remove_decision | inspect_draft", + "decisions":"required only for submit; the exact complete decision map", + "subject_id":"required for one-decision operations", + "decision":"required only for upsert_decision; one exact action, inaction, or undecided value" }"#; const CELL_EFFECT_VERIFIER_INSTRUCTIONS: &str = "You are the private semantic verifier between an Interpreter and the world kernel. Judge this one candidate action's typed effects as one composition against the exact attributed subject's choice in the Persona turn. Structural permissions were already checked. Use exact_subject_permission as the sole map of canonical subjects, locations, and destinations for this actor. canonical_locations is sibling identity context: compare it with exact_subject_permission.location_ids, and never treat a name as granting locality, co-presence, reach, publication, movement, target, effect, or mutation authority. A matching current-location name denotes that place or its unnamed local public, not an omitted canonical subject. activity_targets supplies each canonical target's exact name and current locations; reachable_destinations supplies exact actor-movement destination IDs and names; migration_destinations supplies exact population names and locations. Preserve every distinct affirmative means the subject actually chooses. Do not invent another means from a purpose, refusal, restraint, condition to preserve, desired social norm, or hoped-for state. Keeping someone's choice open, declining to coerce them, leaving state unchanged, respecting autonomy, or waiting for another subject's decision requires no additional typed effect unless the Persona separately chooses an observable act to do it. Communication can therefore be faithfully combined with restraint without implying coordinate, recruit, posture, or pressure effects. Reject effect omission only when the Persona explicitly undertakes another observable act. When one choice contains relocation, an activity at the subject's exact snapshot location occurs before relocation and an activity at the exact admitted destination occurs after arrival; activities within one location phase are an unordered atomic set. Array and object field order are not chronology. When the Persona chooses to go to a canonical target, actor_move must use that target's actual different reachable location. If actor and target are already co-located, reject movement to some other place; a local communicate, coordinate, or prepare may encode the stated attempt instead. A place named only in prose and absent from reachable_destinations and migration_destinations is local texture inside the supplied activity location; walking to it cannot justify rejecting a concrete local prepare or repair as omitted travel. Return exactly one verdict with action_index 0. A gestalt_migration means that exact population leaf chooses to travel together to the supplied destination within the strategic horizon; loading, waiting, giving away passage, sending only some other subject, or merely considering travel does not entail it. Conversely, when the population chooses to board, depart, or relocate together, reject gestalt_activity prepare that erases the chosen journey. Gestalt migration never entails that a named member moved. A member_migration means that named member personally chooses to travel to the destination. Boarding a transport whose supplied destination is unambiguous in the lived stream is a chosen journey; the Persona need not repeat the place name. Giving away a berth, sending somebody else, waiting, or merely considering travel does not entail migration. Conversely, when the member chooses to board, depart, travel, or join the supplied destination, reject member_activity that reduces that commitment to preparing, queuing, or approaching. A member_activity belongs only to that exact named person's stated attempt; it cannot be reassigned to their population. Communication targets must be the exact canonical subjects actually addressed in the Persona turn. An exact activity_targets entry is sufficient authority to attempt direct communication with that named subject; allowed_persistent_publication_channels governs only durable public publication and is never an additional requirement for direct contact. One communicate activity is also the complete supported composition when the same utterance addresses exact canonical targets and an unnamed public audience: target_subject_ids names the canonical addressees and candidate_action.public_channels names the simultaneous public reach. A call to unnamed people at a canonical location is such public or local audience, not a missing activity target. Do not demand a second targetless communicate for that same utterance. Use a targetless communicate only when the communication has no exact canonical addressee. Internal-population coordination is owner-specific: apply only coordination_target_contract.rule for this exact attributed subject, never a rule belonging to another subject kind. If the Persona addresses an unnamed clerk, dock master, passerby, or local environment, reject any effect that substitutes a containing population, related institution, or merely permitted ID. A targetless local investigate at the subject's exact current or paired movement destination is the faithful supported shape for seeking information from an unnamed role or the environment; its empty target list is intentional and must not itself be grounds for rejection. An institution posture must express its stated commitment or withholding. A gestalt pressure resolution must be causally supported by its stated attempt, and an added pressure must be a resulting unresolved condition rather than completed-action prose. An activity records only the exact attempt—never successful preparation, coordination, discovery, recruitment, obstruction, exchange, delivery, persuasion, acceptance, or target response. Reject omissions, reversals, subject swaps, wrong destinations, wishful outcomes, and effects that the Persona did not choose. Be concise. Return exactly one JSON object. A faithful verdict uses result \"match\", null mismatch_kind, and null repair_guidance. Otherwise use result \"mismatch\", exactly one mismatch_kind (\"subject_swap\", \"effect_omission\", \"effect_reversal\", \"target_substitution\", \"invented_outcome\", or \"wrong_effect_kind\"), and one concrete repair_guidance sentence of at most 240 characters. Name the exact omitted choice, substituted target, or wrong destination. When no supplied typed effect composition can faithfully encode the choice, explicitly say to remove the action rather than downgrade or redirect it. Shape: {\"verdicts\":[{\"action_index\":0,\"result\":\"match\",\"mismatch_kind\":null,\"repair_guidance\":null}]}"; @@ -521,7 +593,10 @@ impl PersonaProjectionEngine { word_budget: 160, }), output_schema: None, - source_receipt_ids: vec![], + source_receipt_ids: causal_source_ids( + &slice.source_receipt_ids, + std::slice::from_ref(&projected.receipt), + ), temperature: Some(0.7), max_output_tokens: Some(256), }, @@ -548,7 +623,10 @@ impl PersonaProjectionEngine { domain_guidance: &permission_guidance, }), output_schema: Some(schema), - source_receipt_ids: slice.source_receipt_ids.clone(), + source_receipt_ids: causal_source_ids( + &slice.source_receipt_ids, + &[projected.receipt.clone(), persona.receipt.clone()], + ), temperature: Some(0.0), max_output_tokens: Some(768), }; @@ -1194,6 +1272,298 @@ fn agency_footing( format!("{subject_name}'s grounded agency: {destinations} {targets} {channels}") } +struct CellInterpreterWorkbench { + model: Arc, + permit: Arc, + interpreter_model: String, + slice: PermittedCellSlice, + active_subject_ids: BTreeSet, + lived_stream: String, + persona_turn: String, + campaign_policy: String, + draft: BTreeMap, + repair_subject_ids: BTreeSet, + accepted_verifier_bindings: BTreeSet, +} + +impl CellInterpreterWorkbench { + fn progress(&self) -> CellInterpreterFinding { + let decision_subject_ids = self.draft.keys().cloned().collect::>(); + let decided = decision_subject_ids + .iter() + .cloned() + .collect::>(); + CellInterpreterFinding::DraftProgress { + decision_subject_ids, + missing_subject_ids: self + .active_subject_ids + .difference(&decided) + .cloned() + .collect(), + } + } + + async fn compile_draft( + &mut self, + source_receipt_ids: &[String], + ) -> ModelAgentToolOutcome { + let undecided_subject_ids = self + .draft + .iter() + .filter_map(|(subject_id, decision)| { + decision + .get("undecided") + .is_some() + .then_some(subject_id.clone()) + }) + .collect::>(); + if !undecided_subject_ids.is_empty() { + return ModelAgentToolOutcome::Accepted { + output: CellInterpreterAgentOutput::MissingPersonaDecision { + subject_ids: undecided_subject_ids, + }, + receipts: Vec::new(), + }; + } + if !self + .active_subject_ids + .iter() + .all(|subject_id| self.draft.contains_key(subject_id)) + { + self.repair_subject_ids = self + .active_subject_ids + .iter() + .filter(|subject_id| !self.draft.contains_key(*subject_id)) + .cloned() + .collect(); + return ModelAgentToolOutcome::Continue { + observation: self.progress(), + receipts: Vec::new(), + }; + } + + let value = serde_json::json!({"decisions":self.draft}); + let appraisal = + decode_cell_appraisal_proposal(&self.slice.cell_id, value).and_then(|proposal| { + let appraisal = + bind_cell_appraisal(&self.slice, &self.active_subject_ids, proposal)?; + validate_cell_appraisal(&self.slice, &appraisal)?; + validate_active_decision_owners(&self.active_subject_ids, &appraisal)?; + Ok(appraisal) + }); + let appraisal = match appraisal { + Ok(appraisal) => appraisal, + Err(error) => { + if self.repair_subject_ids.is_empty() { + self.repair_subject_ids = self.active_subject_ids.clone(); + } + return ModelAgentToolOutcome::Rejected { + finding: CellInterpreterFinding::LocalValidation { + diagnostic: error.to_string().chars().take(1_000).collect(), + decision_subject_ids: self.repair_subject_ids.iter().cloned().collect(), + }, + receipts: Vec::new(), + }; + } + }; + + let mut pending_actions = Vec::new(); + for action in &appraisal.actions { + let binding = match cell_effect_verification_binding( + &self.slice.snapshot_binding, + std::slice::from_ref(action), + ) { + Ok(binding) => binding, + Err(error) => { + return ModelAgentToolOutcome::Failed { + message: error.to_string(), + receipts: Vec::new(), + }; + } + }; + if !self.accepted_verifier_bindings.contains(&binding) { + pending_actions.push(action.clone()); + } + } + if pending_actions.is_empty() { + self.repair_subject_ids.clear(); + return ModelAgentToolOutcome::Accepted { + output: CellInterpreterAgentOutput::Appraisal(appraisal), + receipts: Vec::new(), + }; + } + + if let Err(error) = self + .permit + .require( + &self.slice.cell_id, + &self.slice.snapshot_binding, + "cell_effect_verifier", + ) + .await + { + return ModelAgentToolOutcome::Failed { + message: error.to_string(), + receipts: Vec::new(), + }; + } + let mut verifications = match run_cell_effect_verifier_wave( + self.model.clone(), + &self.interpreter_model, + &self.slice, + &self.lived_stream, + &self.persona_turn, + &self.campaign_policy, + &pending_actions, + source_receipt_ids, + ) + .await + { + Ok(verifications) => verifications, + Err(error) => { + let receipts = error + .downcast_ref::() + .map(|failure| failure.completed_stage_receipts.clone()) + .unwrap_or_default(); + return ModelAgentToolOutcome::Failed { + message: error.to_string(), + receipts, + }; + } + }; + let mut rejected = Vec::new(); + let mut receipts = Vec::with_capacity(verifications.len()); + for verification in &mut verifications { + let action = &pending_actions[verification.action_index]; + let binding = cell_effect_verification_binding( + &self.slice.snapshot_binding, + std::slice::from_ref(action), + ) + .expect("pending action binding was already computed"); + if matches!(verification.verdict.result, CellEffectMatchResult::Match) { + self.accepted_verifier_bindings.insert(binding); + } else { + let mismatch_kind = verification + .verdict + .mismatch_kind + .clone() + .expect("validated mismatch requires a kind"); + let repair_guidance = verification + .verdict + .repair_guidance + .clone() + .expect("validated mismatch requires repair guidance"); + verification.output.receipt.validation_result = "semantic_invalid".into(); + verification.output.receipt.local_validation_error = + Some(repair_guidance.chars().take(1_000).collect()); + rejected.push(CellInterpreterEffectFinding { + subject_id: action.subject_id.clone(), + mismatch_kind, + repair_guidance, + }); + } + receipts.push(verification.output.receipt.clone()); + } + if rejected.is_empty() { + self.repair_subject_ids.clear(); + ModelAgentToolOutcome::Accepted { + output: CellInterpreterAgentOutput::Appraisal(appraisal), + receipts, + } + } else { + self.repair_subject_ids = rejected + .iter() + .map(|finding| finding.subject_id.clone()) + .collect(); + ModelAgentToolOutcome::Rejected { + finding: CellInterpreterFinding::EffectMismatch { rejected }, + receipts, + } + } + } +} + +#[async_trait] +impl ModelAgentTool for CellInterpreterWorkbench { + type Action = CellInterpreterAgentAction; + type Output = CellInterpreterAgentOutput; + type Finding = CellInterpreterFinding; + + async fn invoke( + &mut self, + action: Self::Action, + context: &ModelAgentToolContext, + ) -> ModelAgentToolOutcome { + match action { + CellInterpreterAgentAction::Submit { decisions } => { + if !self.draft.is_empty() { + return ModelAgentToolOutcome::Rejected { + finding: CellInterpreterFinding::SubmitRequiresEmptyDraft { + repair_subject_ids: self.repair_subject_ids.iter().cloned().collect(), + }, + receipts: Vec::new(), + }; + } + self.repair_subject_ids = decisions.keys().cloned().collect(); + self.draft = decisions; + self.compile_draft(&context.source_receipt_ids).await + } + CellInterpreterAgentAction::UpsertDecision { + subject_id, + decision, + } => { + if !self.active_subject_ids.contains(&subject_id) { + return ModelAgentToolOutcome::Rejected { + finding: CellInterpreterFinding::UnknownDecisionOwner { + subject_id, + allowed_subject_ids: self.active_subject_ids.iter().cloned().collect(), + }, + receipts: Vec::new(), + }; + } + if self.draft.contains_key(&subject_id) + && !self.repair_subject_ids.contains(&subject_id) + { + return ModelAgentToolOutcome::Rejected { + finding: CellInterpreterFinding::DecisionNotRepairable { + subject_id, + repair_subject_ids: self.repair_subject_ids.iter().cloned().collect(), + }, + receipts: Vec::new(), + }; + } + self.repair_subject_ids = BTreeSet::from([subject_id.clone()]); + self.draft.insert(subject_id, decision); + self.compile_draft(&context.source_receipt_ids).await + } + CellInterpreterAgentAction::RemoveDecision { subject_id } => { + if self.draft.is_empty() { + return ModelAgentToolOutcome::Rejected { + finding: CellInterpreterFinding::DraftRequired, + receipts: Vec::new(), + }; + } + if !self.repair_subject_ids.contains(&subject_id) { + return ModelAgentToolOutcome::Rejected { + finding: CellInterpreterFinding::DecisionNotRepairable { + subject_id, + repair_subject_ids: self.repair_subject_ids.iter().cloned().collect(), + }, + receipts: Vec::new(), + }; + } + self.repair_subject_ids = BTreeSet::from([subject_id.clone()]); + self.draft.remove(&subject_id); + self.compile_draft(&context.source_receipt_ids).await + } + CellInterpreterAgentAction::InspectDraft => ModelAgentToolOutcome::Continue { + observation: self.progress(), + receipts: Vec::new(), + }, + } + } +} + fn required_projection_subject_ids(slice: &PermittedCellSlice) -> BTreeSet { slice.decision_owner_ids.clone() } @@ -1237,16 +1607,31 @@ pub struct CellProjectionEngine { pub aggregate_boundaries: Vec, } +#[derive(Clone)] +struct CellProjectedMoment { + lived_stream: LivedNarrativeStream, + active_subject_ids: BTreeSet, + projector_receipts: Vec, + causal_receipts: Vec, +} + impl CellProjectionEngine { pub async fn execute(&self, slice: PermittedCellSlice) -> Result { - match self.execute_once(slice.clone(), false).await { + match self.execute_once(slice.clone(), false, None).await { Ok(bundle) => Ok(bundle), Err(error) => { let Some(omission) = error.downcast_ref::() else { return Err(cell_pipeline_failure(error, Vec::new())); }; let mut prior_receipts = omission.stage_receipts.clone(); - let mut bundle = match self.execute_once(slice, true).await { + let retry_projection = CellProjectedMoment { + lived_stream: omission.lived_stream.clone(), + active_subject_ids: omission.active_subject_ids.clone(), + projector_receipts: omission.projector_receipts.clone(), + causal_receipts: omission.stage_receipts.clone(), + }; + let mut bundle = match self.execute_once(slice, true, Some(retry_projection)).await + { Ok(bundle) => bundle, Err(error) => { return Err(cell_pipeline_failure( @@ -1258,7 +1643,7 @@ impl CellProjectionEngine { } }; prior_receipts.append(&mut bundle.stage_receipts); - bundle.stage_receipts = prior_receipts; + bundle.stage_receipts = distinct_stage_receipts(prior_receipts); Ok(bundle) } } @@ -1268,112 +1653,129 @@ impl CellProjectionEngine { &self, slice: PermittedCellSlice, require_explicit_decision: bool, + projection: Option, ) -> Result { - self.permit - .require(&slice.cell_id, &slice.snapshot_binding, "cell_projector") - .await?; - let projector_context = serde_json::to_string(&cell_projector_context(&slice))?; let campaign_policy = serde_json::to_string(&serde_json::json!({ "campaign_contract":self.campaign_contract, "aggregate_content_boundaries":self.aggregate_boundaries, }))?; - let visible_stimulus = slice - .perceived_events - .iter() - .map(|event| { - format!( - "Perceived by [{}]: {}", - event - .perceived_by_subject_ids - .iter() - .cloned() - .collect::>() - .join(", "), - event.summary - ) - }) - .collect::>() - .join("\n"); - let mode_guidance = cell_projector_mode_guidance(&slice.mode); - let mode_guidance = format!( - "{mode_guidance} Treat already_committed_posture as an institutional course already in force, not a pressure, option, or fresh decision. Continuing it is holding steady; only a materially different commitment is a new posture choice. Each perceived event names the exact constituents that can perceive it; do not teach it to anyone else. Only supplied constituents and member_exceptions may own an internal perspective or choice. A person merely mentioned in an event is external observation when absent from those lists: never voice them. Every supplied member_exception was selected because that person has an actionable decision in this horizon. Render each selected person explicitly by name, with only their own footing and choices." - ); - let required_projection_subject_ids = required_projection_subject_ids(&slice); - let word_budget = - (120 + 45 * (slice.constituents.len() + slice.member_exceptions.len())).min(360); - let perspective_limit = slice - .max_actions - .max(required_projection_subject_ids.len()) - .max(1); - let mut projection_schema = serde_json::to_value(schema_for!(CellProjectionProposal))?; - constrain_cell_projection_schema(&mut projection_schema, &slice)?; - let mut projection_request = ModelStageRequest { - stage: "cell_projector".into(), - model: self.projector_model.clone(), - snapshot_binding: slice.snapshot_binding.clone(), - lived_stream: format!( - "\nYou are a private cell Projector. Convert only the permitted typed context and visible stimulus into compact lived narrative segments. Each segment belongs to exactly one supplied subject_id and contains only that subject's perceptions, memories, wants, fears, knowledge, and explicit uncertainty. Mentioned outsiders remain external observations: never give them an internal viewpoint. Campaign policy constrains what may become simulation content, but is never actor knowledge: omit line topics, keep veil topics off-screen, and introduce no ask_first topic. Do not narrativize or reveal the policy itself. Do not choose actions or claim world effects. Omit decorative recap. Return between {} and {perspective_limit} unique segments; do not narrate every ordinary constituent. Include every exact subject ID in REQUIRED PERSPECTIVE OWNERS, because each named member exception or debt focus has an actionable decision that must not disappear inside the aggregate. Put detail_focus_subject_id first when present. Spend any remaining slots only on subjects facing a materially different decision in this horizon.\n\nREQUIRED PERSPECTIVE OWNERS:\n{}\n\nReturn exactly one JSON object matching this stable shape:\n{CELL_PROJECTION_OUTPUT_CONTRACT}\n\nCAMPAIGN POLICY:\n{campaign_policy}\n\nDomain guidance:\n{mode_guidance}\n\nIdentity:\n{}\n\nPermitted typed context:\n{projector_context}\n\nVisible stimulus:\n{visible_stimulus}\n\nUse no more than {word_budget} narrative words across all segments.", - required_projection_subject_ids.len().max(1), - serde_json::to_string(&required_projection_subject_ids)?, - slice.cell_id - ), - output_schema: Some(projection_schema), - source_receipt_ids: slice.source_receipt_ids.clone(), - temperature: Some(0.0), - max_output_tokens: Some(768), - }; - let mut projector_receipts = Vec::new(); - let (projected_narrative, active_subject_ids, projector_receipt) = loop { - let mut projected = match run_validated_stage(self.model.as_ref(), &projection_request) - .await - .context("cell projector model stage failed") - { - Ok(projected) => projected, - Err(error) => return Err(cell_pipeline_failure(error, projector_receipts)), + let CellProjectedMoment { + lived_stream: lived, + active_subject_ids, + projector_receipts, + causal_receipts, + } = if let Some(projection) = projection { + projection + } else { + self.permit + .require(&slice.cell_id, &slice.snapshot_binding, "cell_projector") + .await?; + let projector_context = serde_json::to_string(&cell_projector_context(&slice))?; + let visible_stimulus = slice + .perceived_events + .iter() + .map(|event| { + format!( + "Perceived by [{}]: {}", + event + .perceived_by_subject_ids + .iter() + .cloned() + .collect::>() + .join(", "), + event.summary + ) + }) + .collect::>() + .join("\n"); + let mode_guidance = cell_projector_mode_guidance(&slice.mode); + let mode_guidance = format!( + "{mode_guidance} Treat already_committed_posture as an institutional course already in force, not a pressure, option, or fresh decision. Continuing it is holding steady; only a materially different commitment is a new posture choice. Each perceived event names the exact constituents that can perceive it; do not teach it to anyone else. Only supplied constituents and member_exceptions may own an internal perspective or choice. A person merely mentioned in an event is external observation when absent from those lists: never voice them. Every supplied member_exception was selected because that person has an actionable decision in this horizon. Render each selected person explicitly by name, with only their own footing and choices." + ); + let required_projection_subject_ids = required_projection_subject_ids(&slice); + let word_budget = + (120 + 45 * (slice.constituents.len() + slice.member_exceptions.len())).min(360); + let perspective_limit = slice + .max_actions + .max(required_projection_subject_ids.len()) + .max(1); + let mut projection_schema = serde_json::to_value(schema_for!(CellProjectionProposal))?; + constrain_cell_projection_schema(&mut projection_schema, &slice)?; + let mut projection_request = ModelStageRequest { + stage: "cell_projector".into(), + model: self.projector_model.clone(), + snapshot_binding: slice.snapshot_binding.clone(), + lived_stream: format!( + "\nYou are a private cell Projector. Convert only the permitted typed context and visible stimulus into compact lived narrative segments. Each segment belongs to exactly one supplied subject_id and contains only that subject's perceptions, memories, wants, fears, knowledge, and explicit uncertainty. Mentioned outsiders remain external observations: never give them an internal viewpoint. Campaign policy constrains what may become simulation content, but is never actor knowledge: omit line topics, keep veil topics off-screen, and introduce no ask_first topic. Do not narrativize or reveal the policy itself. Do not choose actions or claim world effects. Omit decorative recap. Return between {} and {perspective_limit} unique segments; do not narrate every ordinary constituent. Include every exact subject ID in REQUIRED PERSPECTIVE OWNERS, because each named member exception or debt focus has an actionable decision that must not disappear inside the aggregate. Put detail_focus_subject_id first when present. Spend any remaining slots only on subjects facing a materially different decision in this horizon.\n\nREQUIRED PERSPECTIVE OWNERS:\n{}\n\nReturn exactly one JSON object matching this stable shape:\n{CELL_PROJECTION_OUTPUT_CONTRACT}\n\nCAMPAIGN POLICY:\n{campaign_policy}\n\nDomain guidance:\n{mode_guidance}\n\nIdentity:\n{}\n\nPermitted typed context:\n{projector_context}\n\nVisible stimulus:\n{visible_stimulus}\n\nUse no more than {word_budget} narrative words across all segments.", + required_projection_subject_ids.len().max(1), + serde_json::to_string(&required_projection_subject_ids)?, + slice.cell_id + ), + output_schema: Some(projection_schema), + source_receipt_ids: slice.source_receipt_ids.clone(), + temperature: Some(0.0), + max_output_tokens: Some(768), }; - let proposal = projected - .structured - .clone() - .ok_or_else(|| anyhow!("cell Projector produced no typed segments")) - .and_then(|value| serde_json::from_value(value).map_err(Into::into)); - match proposal.and_then(|proposal| bind_cell_projection(&slice, proposal)) { - Ok((narrative, active_subject_ids)) => { - let receipt = projected.receipt.clone(); - projector_receipts.push(projected.receipt); - break (narrative, active_subject_ids, receipt); - } - Err(error) if projector_receipts.is_empty() => { - projected.receipt.validation_result = "semantic_invalid".into(); - projected.receipt.local_validation_error = - Some(error.to_string().chars().take(1_000).collect()); - projector_receipts.push(projected.receipt); - projection_request.lived_stream.push_str(&format!( + let mut projector_receipts = Vec::new(); + let (projected_narrative, active_subject_ids, projector_receipt) = loop { + let mut projected = + match run_validated_stage(self.model.as_ref(), &projection_request) + .await + .context("cell projector model stage failed") + { + Ok(projected) => projected, + Err(error) => return Err(cell_pipeline_failure(error, projector_receipts)), + }; + let proposal = projected + .structured + .clone() + .ok_or_else(|| anyhow!("cell Projector produced no typed segments")) + .and_then(|value| serde_json::from_value(value).map_err(Into::into)); + match proposal.and_then(|proposal| bind_cell_projection(&slice, proposal)) { + Ok((narrative, active_subject_ids)) => { + let receipt = projected.receipt.clone(); + projector_receipts.push(projected.receipt); + break (narrative, active_subject_ids, receipt); + } + Err(error) if projector_receipts.is_empty() => { + projected.receipt.validation_result = "semantic_invalid".into(); + projected.receipt.local_validation_error = + Some(error.to_string().chars().take(1_000).collect()); + projector_receipts.push(projected.receipt); + projection_request.lived_stream.push_str(&format!( "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS SEGMENTS: {error}\nReturn one corrected complete JSON object against the same snapshot and contract." )); + } + Err(error) => { + projected.receipt.validation_result = "semantic_invalid".into(); + projected.receipt.local_validation_error = + Some(error.to_string().chars().take(1_000).collect()); + projector_receipts.push(projected.receipt); + return Err(cell_pipeline_failure( + anyhow!( + "cell Projector failed perspective binding after one correction: {error}" + ), + projector_receipts, + )); + } } - Err(error) => { - projected.receipt.validation_result = "semantic_invalid".into(); - projected.receipt.local_validation_error = - Some(error.to_string().chars().take(1_000).collect()); - projector_receipts.push(projected.receipt); - return Err(cell_pipeline_failure( - anyhow!( - "cell Projector failed perspective binding after one correction: {error}" - ), - projector_receipts, - )); - } + }; + let lived_stream = LivedNarrativeStream { + text: format!( + "{}\n\n{}", + cell_scene_boundaries(&slice, &active_subject_ids), + projected_narrative + ), + snapshot_binding: slice.snapshot_binding.clone(), + projector_receipt, + }; + CellProjectedMoment { + lived_stream, + active_subject_ids, + causal_receipts: projector_receipts.clone(), + projector_receipts, } }; - let lived = LivedNarrativeStream { - text: format!( - "{}\n\n{}", - cell_scene_boundaries(&slice, &active_subject_ids), - projected_narrative - ), - snapshot_binding: slice.snapshot_binding.clone(), - projector_receipt, - }; self.permit .require(&slice.cell_id, &slice.snapshot_binding, "cell_persona") .await @@ -1399,7 +1801,7 @@ impl CellProjectionEngine { word_budget: (160 + 30 * slice.constituents.len()).min(320), }), output_schema: None, - source_receipt_ids: vec![], + source_receipt_ids: causal_source_ids(&slice.source_receipt_ids, &causal_receipts), temperature: Some(0.7), max_output_tokens: Some(512), }, @@ -1410,7 +1812,7 @@ impl CellProjectionEngine { Ok(persona) => persona, Err(error) => return Err(cell_pipeline_failure(error, projector_receipts)), }; - let mut stage_receipts = projector_receipts; + let mut stage_receipts = projector_receipts.clone(); stage_receipts.push(persona.receipt.clone()); self.permit .require(&slice.cell_id, &slice.snapshot_binding, "cell_interpreter") @@ -1445,225 +1847,79 @@ impl CellProjectionEngine { let permission_guidance = format!( "{permission_guidance} Campaign policy is a hard output boundary, not actor knowledge. Emit no action, inaction rationale, pressure, migration, posture, or activity that introduces a line topic, depicts a veil topic on-screen, or introduces an ask_first topic. Never reveal boundary attribution. CAMPAIGN POLICY: {campaign_policy}" ); - let mut request = ModelStageRequest { + let action_schema = cell_interpreter_agent_schema(&schema) + .map_err(|error| cell_pipeline_failure(error, stage_receipts.clone()))?; + let instructions = build_interpreter_prompt(&InterpreterPrompt { + identity: &slice.cell_id, + typed_context: &interpreter_context, + lived_stream: &lived.text, + persona_output: &persona.narrative, + output_schema: CELL_INTERPRETER_AGENT_OUTPUT_CONTRACT, + domain_guidance: &format!( + "{permission_guidance} Operate the private Interpreter workbench. Prefer one submit action containing the complete exact decision map on the first step. A rejected submit preserves its draft. Repair only named decisions with upsert_decision; inspect_draft and remove_decision are nonterminal. Only the deterministic workbench can accept the appraisal." + ), + }); + let mut interpreter_causal_receipts = causal_receipts; + interpreter_causal_receipts.push(persona.receipt.clone()); + let source_receipt_ids = + causal_source_ids(&slice.source_receipt_ids, &interpreter_causal_receipts); + let spec = ModelAgentSpec { 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: &interpreter_context, - lived_stream: &lived.text, - persona_output: &persona.narrative, - output_schema: CELL_APPRAISAL_OUTPUT_CONTRACT, - domain_guidance: &permission_guidance, - }), - output_schema: Some(schema), - source_receipt_ids: slice.source_receipt_ids.clone(), + instructions, + action_schema, + source_receipt_ids, temperature: Some(0.0), max_output_tokens: Some(1_600), + max_steps: active_subject_ids.len().saturating_add(4).clamp(4, 8), }; - for attempt in 0..3 { - let mut interpreted = match run_validated_stage(self.model.as_ref(), &request) - .await - .context("cell interpreter model stage failed") - { - Ok(interpreted) => interpreted, - Err(error) => { - return Err(cell_pipeline_failure(error, stage_receipts)); - } - }; - let proposal = interpreted - .structured - .clone() - .ok_or_else(|| anyhow!("cell interpreter produced no typed proposal")) - .and_then(|value| decode_cell_appraisal_proposal(&slice.cell_id, value)); - match proposal.and_then(|proposal: CellAppraisalProposal| { - if proposal.actions.is_empty() && proposal.inactions.is_empty() { - return Err(anyhow::Error::new(MissingExplicitCellDecision { - cell_id: slice.cell_id.clone(), - stage_receipts: Vec::new(), - })); - } - let appraisal = bind_cell_appraisal(&slice, &active_subject_ids, proposal)?; - validate_cell_appraisal(&slice, &appraisal)?; - validate_active_decision_owners(&active_subject_ids, &appraisal)?; - Ok(appraisal) - }) { - Ok(appraisal) => { - stage_receipts.push(interpreted.receipt); - if !appraisal.actions.is_empty() { - self.permit - .require( - &slice.cell_id, - &slice.snapshot_binding, - "cell_effect_verifier", - ) - .await - .map_err(|error| { - cell_pipeline_failure(error, stage_receipts.clone()) - })?; - let mut verifications = run_cell_effect_verifier_wave( - self.model.clone(), - &self.interpreter_model, - &slice, - &lived.text, - &persona.narrative, - &campaign_policy, - &appraisal.actions, - ) - .await - .map_err(|error| { - let mut completed = stage_receipts.clone(); - if let Some(failure) = - error.downcast_ref::() - { - completed.extend(failure.completed_stage_receipts.clone()); - } - cell_pipeline_failure(error, completed) - })?; - let rejected_action_indices = verifications - .iter() - .filter_map(|verification| { - matches!( - verification.verdict.result, - CellEffectMatchResult::Mismatch - ) - .then_some(verification.action_index) - }) - .collect::>(); - if rejected_action_indices.is_empty() { - stage_receipts.extend( - verifications - .into_iter() - .map(|verification| verification.output.receipt), - ); - } else { - let rejection_rationale = verifications - .iter() - .filter_map(|verification| { - let CellEffectMatchResult::Mismatch = - verification.verdict.result - else { - return None; - }; - let mismatch_kind = verification - .verdict - .mismatch_kind - .as_ref() - .expect("validated mismatch kind"); - format!( - "action {}: {:?} — {}", - verification.action_index, - mismatch_kind, - verification - .verdict - .repair_guidance - .as_deref() - .expect("validated mismatch guidance") - .chars() - .take(240) - .collect::() - ) - .into() - }) - .collect::>() - .join("; "); - let error = anyhow!( - "effect verifier rejected action indices {:?}: {}", - rejected_action_indices, - rejection_rationale - ); - for verification in &mut verifications { - if matches!( - verification.verdict.result, - CellEffectMatchResult::Mismatch - ) { - verification.output.receipt.validation_result = - "semantic_invalid".into(); - verification.output.receipt.local_validation_error = - Some(error.to_string().chars().take(1_000).collect()); - } - } - stage_receipts.extend( - verifications - .into_iter() - .map(|verification| verification.output.receipt), - ); - if attempt < 2 { - append_cell_correction( - &mut request, - &error, - &serde_json::to_string(&encode_cell_appraisal_decisions( - &appraisal, - ))?, - ); - continue; - } - let rejected_actions = rejected_action_diagnostic( - &appraisal.actions, - &rejected_action_indices, - ); - return Err(cell_pipeline_failure( - anyhow!( - "cell effect verifier rejected the appraisal after two corrections: {error}; rejected_actions={rejected_actions}" - ), - stage_receipts, - )); - } - } - self.permit - .require(&slice.cell_id, &slice.snapshot_binding, "cell_terminal") - .await - .map_err(|error| cell_pipeline_failure(error, stage_receipts.clone()))?; - return Ok(CellTerminalBundle { - lived_stream: lived, - persona_output: persona.narrative, - appraisal, - stage_receipts, - }); - } - Err(error) - if error - .downcast_ref::() - .is_some() => - { - interpreted.receipt.validation_result = "semantic_invalid".into(); - interpreted.receipt.local_validation_error = - Some(error.to_string().chars().take(1_000).collect()); - stage_receipts.push(interpreted.receipt); - return Err(anyhow::Error::new(MissingExplicitCellDecision { - cell_id: slice.cell_id.clone(), - stage_receipts, - })); - } - Err(error) if attempt < 2 => { - let rejected_appraisal = interpreted - .structured - .as_ref() - .map(serde_json::to_string) - .transpose()? - .unwrap_or_else(|| "null".into()); - interpreted.receipt.validation_result = "semantic_invalid".into(); - interpreted.receipt.local_validation_error = - Some(error.to_string().chars().take(1_000).collect()); - stage_receipts.push(interpreted.receipt); - append_cell_correction(&mut request, &error, &rejected_appraisal); - } - Err(error) => { - interpreted.receipt.validation_result = "semantic_invalid".into(); - interpreted.receipt.local_validation_error = - Some(error.to_string().chars().take(1_000).collect()); - stage_receipts.push(interpreted.receipt); - return Err(cell_pipeline_failure( - anyhow!( - "cell interpreter failed semantic validation after two corrections: {error}" - ), - stage_receipts, - )); - } + let mut workbench = CellInterpreterWorkbench { + model: self.model.clone(), + permit: self.permit.clone(), + interpreter_model: self.interpreter_model.clone(), + slice: slice.clone(), + active_subject_ids: active_subject_ids.clone(), + lived_stream: lived.text.clone(), + persona_turn: persona.narrative.clone(), + campaign_policy: campaign_policy.clone(), + draft: BTreeMap::new(), + repair_subject_ids: BTreeSet::new(), + accepted_verifier_bindings: BTreeSet::new(), + }; + let run = match run_model_agent(self.model.as_ref(), &spec, &mut workbench).await { + Ok(run) => run, + Err(ModelAgentFailure { message, receipts }) => { + stage_receipts.extend(receipts); + return Err(cell_pipeline_failure( + anyhow!("cell Interpreter agent failed: {message}"), + stage_receipts, + )); } - } - unreachable!() + }; + stage_receipts.extend(run.receipts); + let appraisal = match run.output { + CellInterpreterAgentOutput::Appraisal(appraisal) => appraisal, + CellInterpreterAgentOutput::MissingPersonaDecision { subject_ids } => { + return Err(anyhow::Error::new(MissingExplicitCellDecision { + cell_id: format!("{} ({})", slice.cell_id, subject_ids.join(", ")), + stage_receipts: distinct_stage_receipts(stage_receipts), + lived_stream: lived, + active_subject_ids, + projector_receipts, + })); + } + }; + self.permit + .require(&slice.cell_id, &slice.snapshot_binding, "cell_terminal") + .await + .map_err(|error| cell_pipeline_failure(error, stage_receipts.clone()))?; + return Ok(CellTerminalBundle { + lived_stream: lived, + persona_output: persona.narrative, + appraisal, + stage_receipts, + }); } } @@ -1675,6 +1931,7 @@ async fn run_cell_effect_verifier_wave( persona_turn: &str, campaign_policy: &str, actions: &[crate::domain::CellActionProposal], + source_receipt_ids: &[String], ) -> Result> { let campaign_policy = serde_json::from_str::(campaign_policy)?; let verifier_schema = cell_effect_verifier_schema(1)?; @@ -1718,7 +1975,7 @@ async fn run_cell_effect_verifier_wave( serde_json::to_string(&verifier_context)? ), output_schema: Some(verifier_schema.clone()), - source_receipt_ids: slice.source_receipt_ids.clone(), + source_receipt_ids: source_receipt_ids.to_vec(), temperature: Some(0.0), max_output_tokens: Some(192), }; @@ -1819,63 +2076,6 @@ fn cell_persona_mode_guidance(mode: &crate::domain::SimulationCellMode) -> &'sta } } -fn append_cell_correction( - request: &mut ModelStageRequest, - error: &anyhow::Error, - rejected_appraisal: &str, -) { - let repair_guidance = cell_correction_guidance(error); - request.lived_stream.push_str(&format!( - "\n\nCORRECTION TASK—THE PREVIOUS APPRAISAL WAS REJECTED.\nREJECTION: {error}\nPREVIOUS_REJECTED_APPRAISAL:\n{rejected_appraisal}\nReturn one corrected complete appraisal against the same snapshot, lived stream, Persona turn, and exact permission context. The semantic verifier's concrete repair guidance in REJECTION names the exact mismatch and is the primary correction instruction. {repair_guidance} When repairing bounded text, rewrite the whole field concisely: put every explicit act and addressee before supporting detail, remove recap and ornament, and end with a complete clause well below the character limit. Never append repair text to a field already at its limit. {CELL_ACTIVITY_CLASSIFICATION_GUIDANCE} Every retained action must still carry one to four non-null exact effects under the original contract. Preserve all distinct chosen means in one action; repeated activity kinds must use separate exact target and location scopes. With relocation, snapshot-location activities occur before departure and exact-destination activities occur after arrival; field order is not chronology. If an institution merely continues or restates already_committed_posture, move that exact voiced subject to inactions; it is holding steady. If the Persona chose travel but that subject has no exact permitted destination in reachable_destinations or migration_destinations, no movement transition is available: remove that action and record attributed inaction only when the Persona explicitly holds or waits without making another attempt. If an attempted preparation, investigation, request, or deliberation has no permitted typed consequence, remove it and record attributed inaction only when the Persona explicitly holds or waits without making another attempt; never emit an empty transition or upgrade consideration into a completed consequence. Never add inaction for an unvoiced subject. Keep each reason within 160 characters." - )); -} - -fn rejected_action_diagnostic( - actions: &[crate::domain::CellActionProposal], - rejected_action_indices: &[usize], -) -> String { - serde_json::to_string( - &rejected_action_indices - .iter() - .filter_map(|index| { - actions.get(*index).map(|action| { - serde_json::json!({ - "action_index": index, - "subject_id": action.subject_id, - "intent": action.intent, - "intended_effect": action.intended_effect, - "state_references": action.state_references, - "public_channels": action.public_channels, - "typed_effects": action.effects, - }) - }) - }) - .collect::>(), - ) - .unwrap_or_else(|_| "[]".into()) - .chars() - .take(2_000) - .collect() -} - -fn cell_correction_guidance(error: &anyhow::Error) -> &'static str { - if error - .to_string() - .contains("appears in both actions and inactions") - { - "The named subject already has a concrete chosen attempt in actions. Remove its inaction entry. Waiting for that attempt's result or declining some other option is not inaction. Do not change a faithful permitted action merely to preserve the duplicate inaction." - } else if error.to_string().contains("duplicate strategic actions") { - "The named subject may own exactly one strategic choice in this horizon. Merge all faithful chosen means into one action and use its exact effects together; remove any separate alternative, deliberation, or unreachable choice rather than emitting a second action." - } else if error - .to_string() - .contains("omitted explicit strategic decisions") - { - "Every projected perspective must end in exactly one attributed decision. Preserve existing valid decisions and add an action only when the Persona explicitly chose a concrete attempt; otherwise add that voiced subject's explicit hold or wait as an inaction. Never invent a decision for an unprojected subject." - } else { - "Repair the semantic mismatch named by the verifier while preserving every unaffected faithful effect. A correction may retain exact unaffected values; do not alter text merely to make it bytewise different. Compress bounded text into complete clauses rather than truncating its meaning." - } -} - fn validate_effect_verification( verification: &CellEffectVerification, action_count: usize, @@ -2159,10 +2359,9 @@ fn decode_cell_appraisal_proposal( inactions.push(inaction); } (None, None, Some(_)) => { - return Err(anyhow::Error::new(MissingExplicitCellDecision { - cell_id: cell_id.into(), - stage_receipts: Vec::new(), - })); + return Err(anyhow!( + "cell {cell_id} decision for subject {subject_id} remained undecided" + )); } _ => { return Err(anyhow!( @@ -2174,23 +2373,6 @@ fn decode_cell_appraisal_proposal( Ok(CellAppraisalProposal { actions, inactions }) } -fn encode_cell_appraisal_decisions(appraisal: &crate::domain::CellAppraisal) -> serde_json::Value { - let mut decisions = serde_json::Map::new(); - for action in &appraisal.actions { - decisions.insert( - action.subject_id.clone(), - serde_json::json!({"action":action}), - ); - } - for inaction in &appraisal.inactions { - decisions.insert( - inaction.subject_id.clone(), - serde_json::json!({"inaction":inaction}), - ); - } - serde_json::json!({"decisions":decisions}) -} - fn validate_cell_appraisal( slice: &PermittedCellSlice, appraisal: &crate::domain::CellAppraisal, @@ -2835,6 +3017,64 @@ fn constrain_cell_proposal_schema( Ok(()) } +fn cell_interpreter_agent_schema( + appraisal_schema: &serde_json::Value, +) -> Result { + let decisions_schema = appraisal_schema + .pointer("/properties/decisions") + .cloned() + .ok_or_else(|| anyhow!("cell appraisal schema has no exact decisions map"))?; + let decision_properties = decisions_schema + .get("properties") + .and_then(serde_json::Value::as_object) + .ok_or_else(|| anyhow!("cell appraisal schema has no exact decision owners"))?; + let allowed_subject_ids = decision_properties.keys().cloned().collect::>(); + let mut commands = vec![serde_json::json!({ + "type":"object", + "additionalProperties":false, + "required":["kind","decisions"], + "properties":{ + "kind":{"const":"submit"}, + "decisions":decisions_schema + } + })]; + commands.extend( + decision_properties + .iter() + .map(|(subject_id, decision_schema)| { + serde_json::json!({ + "type":"object", + "additionalProperties":false, + "required":["kind","subject_id","decision"], + "properties":{ + "kind":{"const":"upsert_decision"}, + "subject_id":{"const":subject_id}, + "decision":decision_schema + } + }) + }), + ); + commands.push(serde_json::json!({ + "type":"object", + "additionalProperties":false, + "required":["kind","subject_id"], + "properties":{ + "kind":{"const":"remove_decision"}, + "subject_id":{"type":"string","enum":allowed_subject_ids} + } + })); + commands.push(serde_json::json!({ + "type":"object", + "additionalProperties":false, + "required":["kind"], + "properties":{"kind":{"const":"inspect_draft"}} + })); + Ok(serde_json::json!({ + "$schema":"https://json-schema.org/draft/2020-12/schema", + "oneOf":commands + })) +} + fn exact_cell_action_schema( mut action_schema: serde_json::Value, subject_id: &str, @@ -3347,6 +3587,7 @@ mod tests { assert!(request.lived_stream.contains("is investigate, not prepare")); if call == 0 { return Ok(serde_json::json!({ + "kind":"submit", "decisions":{"faction-06":{"action":{ "subject_id":"faction-06", "intent":"continue weighing the position", @@ -3360,7 +3601,9 @@ mod tests { .to_string()); } let repeated = serde_json::json!({ - "decisions":{"faction-06":{"action":{ + "kind":"upsert_decision", + "subject_id":"faction-06", + "decision":{"action":{ "subject_id":"faction-06", "intent":"continue weighing the position", "intended_effect":"retain the posture already in force", @@ -3371,7 +3614,7 @@ mod tests { "posture":"weighing whether to publish a position", "location_ids":["forum"] }} - }}} + }} }); assert!( jsonschema::validator_for( @@ -3385,7 +3628,7 @@ mod tests { "the correction schema must keep describing the same semantic action space; the verifier owns semantic rejection" ); self.saw_rejected_appraisal.store( - request.lived_stream.contains("PREVIOUS_REJECTED_APPRAISAL") + request.lived_stream.contains("local_validation") && request .lived_stream .contains("weighing whether to publish a position") @@ -3393,7 +3636,9 @@ mod tests { Ordering::SeqCst, ); Ok(serde_json::json!({ - "decisions":{"faction-06":{"action":{ + "kind":"upsert_decision", + "subject_id":"faction-06", + "decision":{"action":{ "subject_id":"faction-06", "intent":"publish a position", "intended_effect":"state its bounded institutional posture", @@ -3401,7 +3646,7 @@ mod tests { "state_references":["institution:faction-06"], "public_channels":["public bulletin"], "effects":{"institution":{"posture":"published a bounded position","location_ids":["forum"]}} - }}} + }} }).to_string()) } "cell_effect_verifier" => { @@ -3487,26 +3732,37 @@ mod tests { } struct MissingDecisionRetryModel { + projector_calls: AtomicUsize, persona_calls: AtomicUsize, interpreter_calls: AtomicUsize, saw_retry_guidance: AtomicBool, + request_sources: Mutex)>>, } #[async_trait] impl ModelPort for MissingDecisionRetryModel { async fn run(&self, request: &ModelStageRequest) -> Result { + self.request_sources + .lock() + .unwrap() + .push((request.stage.clone(), request.source_receipt_ids.clone())); match request.stage.as_str() { - "cell_projector" => Ok(serde_json::json!({ - "segments":[{ - "subject_id":"faction-06", - "narrative":"The deadline is visible, but the institution has not yet chosen a new course." - }] - }) - .to_string()), + "cell_projector" => { + self.projector_calls.fetch_add(1, Ordering::SeqCst); + Ok(serde_json::json!({ + "segments":[{ + "subject_id":"faction-06", + "narrative":"The deadline is visible, but the institution has not yet chosen a new course." + }] + }) + .to_string()) + } "cell_persona" => { let call = self.persona_calls.fetch_add(1, Ordering::SeqCst); if call == 0 { - return Ok("Faction Six weighs the deadline and its existing posture.".into()); + return Ok( + "Faction Six weighs the deadline and its existing posture.".into() + ); } self.saw_retry_guidance.store( request @@ -3520,6 +3776,7 @@ mod tests { let call = self.interpreter_calls.fetch_add(1, Ordering::SeqCst); if call == 0 { return Ok(serde_json::json!({ + "kind":"submit", "decisions":{"faction-06":{"undecided":{ "reason":"The Persona supplied no explicit action or hold." }}} @@ -3527,6 +3784,7 @@ mod tests { .to_string()); } Ok(serde_json::json!({ + "kind":"submit", "decisions":{"faction-06":{"inaction":{ "subject_id":"faction-06", "reason":"Faction Six explicitly holds its existing posture for this horizon." @@ -3546,9 +3804,11 @@ mod tests { #[tokio::test] async fn missing_persona_decision_retries_the_lived_turn_not_the_interpreter_invention() { let model = Arc::new(MissingDecisionRetryModel { + projector_calls: AtomicUsize::new(0), persona_calls: AtomicUsize::new(0), interpreter_calls: AtomicUsize::new(0), saw_retry_guidance: AtomicBool::new(false), + request_sources: Mutex::new(Vec::new()), }); let engine = CellProjectionEngine { model: model.clone(), @@ -3562,19 +3822,43 @@ mod tests { let output = engine.execute(fixture_cell_slice()).await.unwrap(); + assert_eq!(model.projector_calls.load(Ordering::SeqCst), 1); assert_eq!(model.persona_calls.load(Ordering::SeqCst), 2); assert_eq!(model.interpreter_calls.load(Ordering::SeqCst), 2); assert!(model.saw_retry_guidance.load(Ordering::SeqCst)); assert!(output.appraisal.actions.is_empty()); assert_eq!(output.appraisal.inactions.len(), 1); assert_eq!(output.appraisal.inactions[0].subject_id, "faction-06"); - assert_eq!(output.stage_receipts.len(), 6); + assert_eq!(output.stage_receipts.len(), 5); assert!( output .stage_receipts .iter() - .any(|receipt| receipt.validation_result == "semantic_invalid") + .all(|receipt| receipt.validation_result == "valid") ); + let receipt_ids = output + .stage_receipts + .iter() + .map(|receipt| receipt.storage_key().to_owned()) + .collect::>(); + let request_sources = model.request_sources.lock().unwrap(); + let persona_sources = request_sources + .iter() + .filter(|(stage, _)| stage == "cell_persona") + .map(|(_, sources)| sources) + .collect::>(); + let interpreter_sources = request_sources + .iter() + .filter(|(stage, _)| stage == "cell_interpreter") + .map(|(_, sources)| sources) + .collect::>(); + assert!(persona_sources[0].contains(&receipt_ids[0])); + assert!(interpreter_sources[0].contains(&receipt_ids[0])); + assert!(interpreter_sources[0].contains(&receipt_ids[1])); + assert!(persona_sources[1].contains(&receipt_ids[0])); + assert!(persona_sources[1].contains(&receipt_ids[1])); + assert!(persona_sources[1].contains(&receipt_ids[2])); + assert!(interpreter_sources[1].contains(&receipt_ids[3])); } #[tokio::test] @@ -3630,22 +3914,15 @@ mod tests { let call = self.interpreter_calls.fetch_add(1, Ordering::SeqCst); if call > 0 { self.saw_verifier_rejection.store( - request.lived_stream.contains("effect verifier rejected") + request.lived_stream.contains("effect_mismatch") && request.lived_stream.contains("releases the reserve"), Ordering::SeqCst, ); assert!(request .lived_stream - .contains("do not alter text merely to make it bytewise different")); - assert!(request - .lived_stream - .contains("no exact permitted destination")); - assert!(request - .lived_stream - .contains("rewrite the whole field concisely")); + .contains("Preserve the Persona's exact withholding decision")); } - Ok(serde_json::json!({ - "decisions":{"faction-06":{"action":{ + let decision = serde_json::json!({"action":{ "subject_id":"faction-06", "intent":"state the reserve decision", "intended_effect":match call { @@ -3664,8 +3941,19 @@ mod tests { }, "location_ids":["forum"] }} - }}} - }).to_string()) + }}); + Ok(if call == 0 { + serde_json::json!({ + "kind":"submit", + "decisions":{"faction-06":decision} + }) + } else { + serde_json::json!({ + "kind":"upsert_decision", + "subject_id":"faction-06", + "decision":decision + }) + }.to_string()) } "cell_effect_verifier" => { assert!( @@ -3754,6 +4042,193 @@ mod tests { assert!(posture.contains("notify ward clerks")); } + struct CachingVerifierModel { + calls: AtomicUsize, + faction_seven_calls: AtomicUsize, + } + + #[async_trait] + impl ModelPort for CachingVerifierModel { + async fn run(&self, request: &ModelStageRequest) -> Result { + assert_eq!(request.stage, "cell_effect_verifier"); + self.calls.fetch_add(1, Ordering::SeqCst); + if request.lived_stream.contains("steady-seven") { + self.faction_seven_calls.fetch_add(1, Ordering::SeqCst); + } + let mismatch = request.lived_stream.contains("reverse-six"); + Ok(serde_json::json!({ + "verdicts":[{ + "action_index":0, + "result":if mismatch { "mismatch" } else { "match" }, + "mismatch_kind":if mismatch { Some("effect_reversal") } else { None }, + "repair_guidance":if mismatch { + Some("Preserve Faction Six's stated withholding rather than reversing it.") + } else { + None + } + }] + }) + .to_string()) + } + + fn provider(&self) -> &'static str { + "caching-verifier-fixture" + } + } + + fn institution_decision( + subject_id: &str, + intended_effect: &str, + posture: &str, + state_reference: &str, + ) -> serde_json::Value { + serde_json::json!({"action":{ + "subject_id":subject_id, + "intent":"state a bounded institutional course", + "intended_effect":intended_effect, + "priority":50, + "state_references":[state_reference], + "public_channels":["public bulletin"], + "effects":{"institution":{"posture":posture,"location_ids":["forum"]}} + }}) + } + + #[tokio::test] + async fn interpreter_workbench_reuses_unchanged_valid_effect_verification() { + let mut slice = fixture_cell_slice(); + let mut second = slice.constituents[0].clone(); + second.subject_id = "faction-07".into(); + second.name = "Faction Seven".into(); + second.permitted_state_references = BTreeSet::from(["institution:faction-07".into()]); + second.current_posture = Some("observing the count".into()); + slice.constituents.push(second); + slice.decision_owner_ids.insert("faction-07".into()); + slice.max_actions = 2; + let active_subject_ids = slice.decision_owner_ids.clone(); + let model = Arc::new(CachingVerifierModel { + calls: AtomicUsize::new(0), + faction_seven_calls: AtomicUsize::new(0), + }); + let mut workbench = CellInterpreterWorkbench { + model: model.clone(), + permit: Arc::new(AllowAllPermit), + interpreter_model: "flash".into(), + slice, + active_subject_ids, + lived_stream: "At location forum: Faction Six and Faction Seven.".into(), + persona_turn: "Faction Six withholds; Faction Seven publishes.".into(), + campaign_policy: "{}".into(), + draft: BTreeMap::new(), + repair_subject_ids: BTreeSet::new(), + accepted_verifier_bindings: BTreeSet::new(), + }; + let context = ModelAgentToolContext { + source_receipt_ids: vec!["persona:one".into()], + }; + let first = workbench + .invoke( + CellInterpreterAgentAction::Submit { + decisions: BTreeMap::from([ + ( + "faction-06".into(), + institution_decision( + "faction-06", + "reverse-six", + "release immediately", + "institution:faction-06", + ), + ), + ( + "faction-07".into(), + institution_decision( + "faction-07", + "steady-seven", + "publish the verified count", + "institution:faction-07", + ), + ), + ]), + }, + &context, + ) + .await; + assert!(matches!( + first, + ModelAgentToolOutcome::Rejected { + finding: CellInterpreterFinding::EffectMismatch { .. }, + .. + } + )); + assert_eq!(model.calls.load(Ordering::SeqCst), 2); + assert_eq!(model.faction_seven_calls.load(Ordering::SeqCst), 1); + + let wholesale_resubmit = workbench + .invoke( + CellInterpreterAgentAction::Submit { + decisions: BTreeMap::new(), + }, + &context, + ) + .await; + assert!(matches!( + wholesale_resubmit, + ModelAgentToolOutcome::Rejected { + finding: CellInterpreterFinding::SubmitRequiresEmptyDraft { .. }, + .. + } + )); + let unrelated_repair = workbench + .invoke( + CellInterpreterAgentAction::UpsertDecision { + subject_id: "faction-07".into(), + decision: institution_decision( + "faction-07", + "rewrite-seven", + "replace the already accepted course", + "institution:faction-07", + ), + }, + &context, + ) + .await; + assert!(matches!( + unrelated_repair, + ModelAgentToolOutcome::Rejected { + finding: CellInterpreterFinding::DecisionNotRepairable { .. }, + .. + } + )); + assert_eq!(model.calls.load(Ordering::SeqCst), 2); + + let second = workbench + .invoke( + CellInterpreterAgentAction::UpsertDecision { + subject_id: "faction-06".into(), + decision: institution_decision( + "faction-06", + "withhold-six", + "withhold pending the verified count", + "institution:faction-06", + ), + }, + &context, + ) + .await; + assert!(matches!( + second, + ModelAgentToolOutcome::Accepted { + output: CellInterpreterAgentOutput::Appraisal(_), + .. + } + )); + assert_eq!(model.calls.load(Ordering::SeqCst), 3); + assert_eq!( + model.faction_seven_calls.load(Ordering::SeqCst), + 1, + "the unchanged accepted action must not repay its semantic verifier" + ); + } + #[test] fn empty_cell_appraisal_requires_exact_attributed_inaction() { let mut slice = fixture_cell_slice(); @@ -3835,7 +4310,6 @@ mod tests { let error = validate_cell_appraisal(&slice, &appraisal).unwrap_err(); assert!(error.to_string().contains("faction-07")); - assert!(cell_correction_guidance(&error).contains("Every projected perspective must end")); appraisal.inactions.push(crate::domain::CellInaction { subject_id: "faction-07".into(), @@ -3845,33 +4319,9 @@ mod tests { validate_active_decision_owners(&active, &appraisal).unwrap(); } - #[test] - fn duplicate_action_inaction_correction_preserves_the_chosen_attempt() { - let guidance = cell_correction_guidance(&anyhow!( - "subject refugees-east appears in both actions and inactions; retain exactly one of those decisions" - )); - assert!(guidance.contains("Remove its inaction entry")); - assert!(guidance.contains("Waiting for that attempt's result")); - assert!(!guidance.contains("rejected action is forbidden")); - - let duplicate_action_guidance = cell_correction_guidance(&anyhow!( - "subject refugees-east has duplicate strategic actions; combine every chosen movement and activity means into one composed action" - )); - assert!(duplicate_action_guidance.contains("exactly one strategic choice")); - assert!(duplicate_action_guidance.contains("exact effects together")); - - let semantic_guidance = cell_correction_guidance(&anyhow!( - "effect verifier rejected action 0 because its bounded posture ended mid-clause" - )); - assert!(semantic_guidance.contains("preserving every unaffected faithful effect")); - assert!(semantic_guidance.contains("complete clauses")); - assert!(!semantic_guidance.contains("forbidden unchanged")); - } - #[test] fn compact_cell_prompt_contract_is_valid_json() { - serde_json::from_str::(CELL_APPRAISAL_OUTPUT_CONTRACT).unwrap(); - assert!(CELL_APPRAISAL_OUTPUT_CONTRACT.contains("\"maxLength\":240")); + serde_json::from_str::(CELL_INTERPRETER_AGENT_OUTPUT_CONTRACT).unwrap(); let mut schema = serde_json::to_value(schema_for!(CellAppraisalProposal)).unwrap(); constrain_cell_proposal_schema( &mut schema, @@ -3886,10 +4336,16 @@ mod tests { assert!(schema.pointer("/properties/decisions").is_some()); assert!(schema.pointer("/properties/actions").is_none()); assert!(schema.pointer("/properties/inactions").is_none()); - assert!(!CELL_APPRAISAL_OUTPUT_CONTRACT.contains("\"institution_id\"")); - assert!(!CELL_APPRAISAL_OUTPUT_CONTRACT.contains("\"gestalt_id\"")); - assert!(!CELL_APPRAISAL_OUTPUT_CONTRACT.contains("\"actor_id\"")); - assert!(!CELL_APPRAISAL_OUTPUT_CONTRACT.contains("\"member_id\"")); + let agent_schema = cell_interpreter_agent_schema(&schema).unwrap(); + let agent_schema_text = serde_json::to_string(&agent_schema).unwrap(); + assert!(agent_schema_text.contains("upsert_decision")); + assert!(agent_schema_text.contains("inspect_draft")); + assert!(agent_schema_text.contains("\"maxLength\":240")); + assert!( + jsonschema::validator_for(&agent_schema) + .unwrap() + .is_valid(&serde_json::json!({"kind":"inspect_draft"})) + ); assert_eq!( exact_constituent_effect_bundle_schema(&fixture_cell_slice().constituents[0]) .pointer("/properties/institution/anyOf/0/properties/posture/maxLength"), @@ -4179,26 +4635,6 @@ mod tests { ); } - #[test] - fn rejected_action_diagnostic_contains_only_the_selected_typed_candidates() { - let action = crate::domain::CellActionProposal { - subject_id: "member:reed".into(), - intent: "offer terms through Mira".into(), - intended_effect: "make the offer without leaving".into(), - priority: 80, - state_references: vec!["member:reed".into()], - public_channels: vec![], - effects: vec![StrategicCellEffect::MemberMigration { - destination_gestalt_id: "refugee-encampment".into(), - }], - }; - let diagnostic = rejected_action_diagnostic(&[action], &[0]); - assert!(diagnostic.contains("member:reed")); - assert!(diagnostic.contains("member_migration")); - assert!(diagnostic.contains("refugee-encampment")); - assert_eq!(rejected_action_diagnostic(&[], &[4]), "[]"); - } - #[test] fn effect_verifier_separates_direct_contact_from_publication_authority() { assert!(CELL_EFFECT_VERIFIER_INSTRUCTIONS.contains( @@ -4456,6 +4892,7 @@ mod tests { "Each institution chooses its own public statement.", "{}", &actions, + &[], ), ) .await @@ -4953,10 +5390,32 @@ mod tests { assert!(error.to_string().contains("exact maximum is 460")); } + struct CausalFixtureModel { + request_sources: Mutex)>>, + } + + #[async_trait] + impl ModelPort for CausalFixtureModel { + async fn run(&self, request: &ModelStageRequest) -> Result { + self.request_sources + .lock() + .unwrap() + .push((request.stage.clone(), request.source_receipt_ids.clone())); + FixtureModel.run(request).await + } + + fn provider(&self) -> &'static str { + "causal-fixture" + } + } + #[tokio::test] async fn persona_receives_only_projected_stream() { + let model = Arc::new(CausalFixtureModel { + request_sources: Mutex::new(Vec::new()), + }); let engine = PersonaProjectionEngine { - model: Arc::new(FixtureModel), + model: model.clone(), permit: Arc::new(AllowAllPermit), projector_model: "flash".into(), persona_model: "pro".into(), @@ -5000,6 +5459,25 @@ mod tests { let result = engine.execute(slice).await.unwrap(); assert_eq!(result.stage_receipts.len(), 3); assert_eq!(result.proposals.reaction_priority, 0); + let receipt_ids = result + .stage_receipts + .iter() + .map(|receipt| receipt.storage_key().to_owned()) + .collect::>(); + let request_sources = model.request_sources.lock().unwrap(); + let persona_sources = request_sources + .iter() + .find(|(stage, _)| stage == "persona") + .map(|(_, sources)| sources) + .unwrap(); + let interpreter_sources = request_sources + .iter() + .find(|(stage, _)| stage == "interpreter") + .map(|(_, sources)| sources) + .unwrap(); + assert!(persona_sources.contains(&receipt_ids[0])); + assert!(interpreter_sources.contains(&receipt_ids[0])); + assert!(interpreter_sources.contains(&receipt_ids[1])); } #[test] @@ -5183,37 +5661,6 @@ mod tests { ); } - #[test] - fn semantic_correction_restates_non_empty_effect_contract() { - let mut request = ModelStageRequest { - stage: "cell_interpreter".into(), - model: "flash".into(), - snapshot_binding: "campaign:one:revision:2".into(), - lived_stream: "original contract".into(), - output_schema: None, - source_receipt_ids: vec![], - temperature: Some(0.0), - max_output_tokens: Some(100), - }; - append_cell_correction( - &mut request, - &anyhow::anyhow!("the typed effect was unsupported"), - r#"{"decisions":{"crowd":{"action":{"effects":{"gestalt_pressure":{"pressure_additions":[],"pressure_resolutions":[]}}}}}}"#, - ); - assert!( - request - .lived_stream - .contains("one to four non-null exact effects") - ); - assert!( - request - .lived_stream - .contains("preparation, investigation, request, or deliberation") - ); - assert!(request.lived_stream.contains("is investigate, not prepare")); - assert!(request.lived_stream.contains("record attributed inaction")); - } - #[test] fn cell_guidance_preserves_attribution_and_ends_on_a_decision() { let arena_projector = cell_projector_mode_guidance(&SimulationCellMode::Arena); diff --git a/crates/ghostlight-dungeon/src/scheduler.rs b/crates/ghostlight-dungeon/src/scheduler.rs index 8822b9f..b729d4e 100644 --- a/crates/ghostlight-dungeon/src/scheduler.rs +++ b/crates/ghostlight-dungeon/src/scheduler.rs @@ -96,9 +96,6 @@ pub struct StrategicResolutionOutput { #[derive(Clone, Debug, Serialize)] pub struct PrivateCellTrace { pub cell_id: String, - pub pipeline_attempts: usize, - pub rejected_pipeline_errors: Vec, - pub rejected_pipeline_receipt_hashes: Vec, pub terminal_pipeline_receipt_hashes: Vec, pub lived_stream: String, pub persona_output: String, @@ -129,8 +126,6 @@ struct CellPipelineExhaustion { stage_receipts: Vec, } -const MAX_CELL_PIPELINE_ATTEMPTS: usize = 3; - pub async fn propose_resolution_wave( model: Arc, permit: Arc, @@ -177,54 +172,27 @@ pub async fn propose_resolution_wave_with_policy( jobs.spawn(async move { let cell_id = cell.id; let subject_ids = cell.subject_ids; - let mut rejected_pipeline_errors = Vec::new(); - let mut rejected_pipeline_receipts = Vec::new(); - let terminal = loop { - let Ok(_provider_slot) = semaphore.clone().acquire_owned().await else { - return Err(CellPipelineExhaustion { - diagnostic: "provider concurrency gate closed".into(), - stage_receipts: rejected_pipeline_receipts, - }); - }; - match engine.execute(slice.clone()).await { - Ok(terminal) => break terminal, - Err(error) - if rejected_pipeline_errors.len() + 1 < MAX_CELL_PIPELINE_ATTEMPTS => - { - if let Some(failure) = error.downcast_ref::() { - rejected_pipeline_receipts.extend(failure.stage_receipts.clone()); - } - rejected_pipeline_errors - .push(format!("{error:#}").chars().take(1_000).collect()); - } - Err(error) => { - if let Some(failure) = error.downcast_ref::() { - rejected_pipeline_receipts.extend(failure.stage_receipts.clone()); - } - rejected_pipeline_errors - .push(format!("{error:#}").chars().take(1_000).collect()); - let terminal_error = rejected_pipeline_errors - .last() - .cloned() - .unwrap_or_else(|| "unknown cell pipeline failure".into()); - return Err(CellPipelineExhaustion { - diagnostic: format!( - "simulation cell {cell_id} subjects {} pipeline failed after {} attempts: {terminal_error}", - serde_json::to_string(&subject_ids) - .unwrap_or_else(|_| "[unavailable]".into()), - MAX_CELL_PIPELINE_ATTEMPTS - ), - stage_receipts: rejected_pipeline_receipts, - }); - } - } + let Ok(_provider_slot) = semaphore.acquire_owned().await else { + return Err(CellPipelineExhaustion { + diagnostic: "provider concurrency gate closed".into(), + stage_receipts: Vec::new(), + }); }; - Ok::<_, CellPipelineExhaustion>(( - cell_id, - terminal, - rejected_pipeline_errors, - rejected_pipeline_receipts, - )) + let terminal = engine.execute(slice).await.map_err(|error| { + let stage_receipts = error + .downcast_ref::() + .map(|failure| failure.stage_receipts.clone()) + .unwrap_or_default(); + CellPipelineExhaustion { + diagnostic: format!( + "simulation cell {cell_id} subjects {} pipeline failed: {error:#}", + serde_json::to_string(&subject_ids) + .unwrap_or_else(|_| "[unavailable]".into()) + ), + stage_receipts, + } + })?; + Ok::<_, CellPipelineExhaustion>((cell_id, terminal)) }); } let mut terminals = Vec::new(); @@ -246,12 +214,7 @@ pub async fn propose_resolution_wave_with_policy( .chain( terminals .iter() - .flat_map(|(_, terminal, _, rejected_receipts)| { - rejected_receipts - .iter() - .chain(terminal.stage_receipts.iter()) - .cloned() - }), + .flat_map(|(_, terminal)| terminal.stage_receipts.iter().cloned()), ) .collect::>(); stage_receipts.extend( @@ -270,42 +233,23 @@ pub async fn propose_resolution_wave_with_policy( terminals.sort_by(|left, right| left.0.cmp(&right.0)); let appraisals = terminals .iter() - .map(|(_, terminal, _, _)| terminal.appraisal.clone()) + .map(|(_, terminal)| terminal.appraisal.clone()) .collect(); let private_cell_traces = terminals .iter() - .map( - |(cell_id, terminal, rejected_pipeline_errors, rejected_pipeline_receipts)| { - PrivateCellTrace { - cell_id: cell_id.clone(), - pipeline_attempts: rejected_pipeline_errors.len() + 1, - rejected_pipeline_errors: rejected_pipeline_errors.clone(), - rejected_pipeline_receipt_hashes: rejected_pipeline_receipts - .iter() - .map(|receipt| receipt.storage_key().to_owned()) - .collect(), - terminal_pipeline_receipt_hashes: terminal - .stage_receipts - .iter() - .map(|receipt| receipt.storage_key().to_owned()) - .collect(), - lived_stream: terminal.lived_stream.text.clone(), - persona_output: terminal.persona_output.clone(), - } - }, - ) + .map(|(cell_id, terminal)| PrivateCellTrace { + cell_id: cell_id.clone(), + terminal_pipeline_receipt_hashes: terminal + .stage_receipts + .iter() + .map(|receipt| receipt.storage_key().to_owned()) + .collect(), + lived_stream: terminal.lived_stream.text.clone(), + persona_output: terminal.persona_output.clone(), + }) .collect(); let mut committed_stages = stages.clone(); - for (_, terminal, _, rejected_pipeline_receipts) in terminals { - stages.extend( - rejected_pipeline_receipts - .into_iter() - .map(|receipt| ModelStageOutput { - narrative: String::new(), - structured: None, - receipt, - }), - ); + for (_, terminal) in terminals { let terminal_stages = terminal .stage_receipts .into_iter() @@ -1607,7 +1551,7 @@ mod tests { .as_ref() .and_then(|schema| { schema - .pointer("/properties/decisions/properties") + .pointer("/oneOf/0/properties/decisions/properties") .and_then(serde_json::Value::as_object) }) .map(|properties| properties.keys().cloned().collect::>()) @@ -1626,6 +1570,7 @@ mod tests { }) .collect::>(); Ok(serde_json::json!({ + "kind":"submit", "decisions":decisions }) .to_string()) @@ -2249,14 +2194,13 @@ mod tests { output .private_cell_traces .iter() - .all(|trace| trace.pipeline_attempts == 1 - && trace.rejected_pipeline_errors.is_empty()) + .all(|trace| !trace.terminal_pipeline_receipt_hashes.is_empty()) ); validate_and_resolve_wave(&campaign, &output.wave).unwrap(); } #[tokio::test] - async fn one_transient_cell_failure_retries_only_that_same_snapshot() { + async fn cell_failure_is_terminal_and_does_not_replay_the_membrane() { let mut campaign = crate::resolution::tests::campaign(6, 2); campaign.resolution_policy.provider_parallelism = 2; let model = Arc::new(TransientCellFixtureModel { @@ -2266,60 +2210,30 @@ mod tests { malformed_cell: false, }, target_binding: Mutex::new(None), - failures_remaining: AtomicUsize::new(2), + failures_remaining: AtomicUsize::new(4), }); - let output = propose_resolution_wave(model.clone(), Arc::new(AllowAllPermit), &campaign) - .await - .unwrap(); + let error = + match propose_resolution_wave(model.clone(), Arc::new(AllowAllPermit), &campaign).await + { + Ok(_) => panic!("the scheduler replayed a failed cell membrane"), + Err(error) => error, + }; + let failure = error + .downcast_ref::() + .expect("cell failure must retain pipeline receipts"); - assert_eq!(output.wave.cover.cells.len(), 2); - let retried = output - .private_cell_traces - .iter() - .filter(|trace| trace.pipeline_attempts == 2) - .collect::>(); - assert_eq!(retried.len(), 1); - assert_eq!(retried[0].rejected_pipeline_errors.len(), 1); - assert_eq!(retried[0].rejected_pipeline_receipt_hashes.len(), 1); - assert!(retried[0].rejected_pipeline_errors[0].contains( + assert_eq!(failure.pipeline_errors.len(), 1); + assert!(failure.pipeline_errors[0].contains( "cell Persona model stage failed: model stage cell_persona provider failed twice against the same snapshot" )); - assert!(output.stages.iter().any(|stage| { - retried[0] - .rejected_pipeline_receipt_hashes - .contains(&stage.receipt.storage_key().to_owned()) - })); - assert!( - retried[0] - .rejected_pipeline_receipt_hashes - .iter() - .filter(|hash| output.wave.model_receipt_hashes.contains(hash)) - .all(|hash| retried[0].terminal_pipeline_receipt_hashes.contains(hash)) - ); - let dir = tempfile::tempdir().unwrap(); - let store = - crate::persistence::CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let receipts = output - .stages - .iter() - .map(|stage| stage.receipt.clone()) - .collect::>(); - store.persist_model_stage_receipts(&receipts).unwrap(); - store.persist_model_stage_receipts(&receipts).unwrap(); assert_eq!( - store.keys("persona_stage_receipt.v1").unwrap().len(), - receipts - .iter() - .map(ModelStageReceipt::storage_key) - .collect::>() - .len() + model.failures_remaining.load(Ordering::SeqCst), + 2, + "the provider may perform its bounded transport retry, but the scheduler must not replay Projector and Persona" ); - assert_eq!(model.failures_remaining.load(Ordering::SeqCst), 0); assert!(model.fixture.maximum.load(Ordering::SeqCst) <= 2); - validate_and_resolve_wave(&campaign, &output.wave).unwrap(); } - #[tokio::test] async fn two_hundred_cell_wave_dispatches_in_parallel_under_one_provider_gate() { let mut campaign = crate::resolution::tests::campaign(1_000, 200); @@ -2435,28 +2349,38 @@ mod tests { }; let failure = error .downcast_ref::() - .expect("exhausted cell retries must preserve wave failure evidence"); + .expect("terminal cell failure must preserve wave failure evidence"); assert!(!failure.pipeline_errors.is_empty()); assert!( failure .pipeline_errors .iter() - .all(|error| error.contains("pipeline failed after 3 attempts")) + .all(|error| error.contains("pipeline failed: cell Interpreter agent failed")) ); - assert!(failure.stage_receipts.len() >= 7); + assert!(failure.stage_receipts.len() >= 5); assert!( failure .stage_receipts .iter() .any(|receipt| receipt.stage == "resolution_demand") ); - assert!( + assert_eq!( failure .stage_receipts .iter() .filter(|receipt| receipt.stage == "cell_projector") - .count() - >= 3 + .count(), + 2, + "the scheduler must not replay a completed Projector" + ); + assert_eq!( + failure + .stage_receipts + .iter() + .filter(|receipt| receipt.stage == "cell_persona") + .count(), + 2, + "the scheduler must not replay a completed Persona" ); assert_eq!(campaign, before); } diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index e860619..d72d93b 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -598,31 +598,83 @@ stale DeepSeek route and received HTTP 402 because this machine has neither a Codex Connector service nor a usable key. That is not provider acceptance or a harness failure; the provider smoke belongs on Yggdrasil. -Reconciliation is the harness's first executable proof. Patina remains the -named next consumer: an agent whose bounded tools can introduce durable, -locally grounded low-stakes texture which later events may organically -appropriate, without granting the texture agent independent commit authority. -No Patina implementation is claimed. +Exact-source run 22 exercised commit `842e265` through Codex Connector. The +world compiled and locality 1 committed. At locality 2 the Sol destination +compile, Terra reconciliation action, and fresh Sol civic verifier all +accepted; WorldKernel then rejected admission with `region admission evidence +receipts were not supplied`. The run ended at one of four elaborations and zero +of six strategic waves, so it produced no newspaper. The unchanged root is +archived at +`F:\GameCult\GhostlightDungeon\acceptance\elven-realms-autonomous-842e265-22.tar`, +whose SHA-256 is +`90972df1c90eaff699469357ff5de026838940ac07ec5f5faefbaf5d1d266ed9`. +This retires run 21 as the current blocker while preserving it as prior failure +history. Run 22 proves the provider-backed agentic reconciliation path reached +fresh semantic acceptance; the remaining rejection came from mixing causal +ModelAgent receipt IDs into canonical profile and relation evidence fields. +Commit `c757e5a09d884d263ae3533f537a71ce69010e94` owns the focused +namespace split and is pushed: model-causal ancestry remains available to +the harness and verifier receipts, while profiles and relations lower only the +canonical admission-evidence receipt IDs. Provider verification remains +pending. -1. Commit and push this phase-boundary Mind update with implementation commit - `842e265`. -2. Dispatch exact source `842e265` on Yggdrasil through Codex Connector for a - fresh four-elaboration/six-wave provider run. If it completes, preserve - and verify the immutable artifact manifest without mutating the live daemon - or any prior run root. -3. Only after all six waves commit and an immutable manifest exists, dispatch a +The current verified working tree makes the strategic Interpreter another +consumer of the same generic harness. Shared `causal_source_ids` bind both actor +and cell Projector-to-Persona-to-Interpreter chains. One agent incrementally +edits a private draft against the frozen Persona decision. The deterministic +draft compiler owns exact structure, permissions, topology, and bounds; the +independent semantic verifier returns subject-scoped findings; unchanged +accepted actions retain their exact verifier binding. Missing cell decisions +reuse one exact `CellProjectedMoment`: one Projector call feeds two Persona and +two Interpreter attempts, and the second attempts cite the first. Draft +admission rejects whole resubmission and edits to unrelated decisions. The +former bespoke correction prompt, whole-cell retry ownership, and dead retry +trace fields are retired. All 419 library tests pass, and the second bounded +Modeling audit found no P1 or P2 issue. + +World elaboration now has a typed catalog of eight named workers: Patina, +Charter, Ledger, Hearth, Tangle, Veil, Ember, and Numen. Persisted semantic +profile weights allocate against the complete enabled profile and control actual +invocation frequency through a deterministic smooth weighted scheduler. An +ineligible or blocked title keeps its scheduled share visibly unused; the +scheduler does not redistribute those slots among eligible titles or accrue +catch-up debt. With Patina 20 and blocked Tangle 80, a 100-slot window therefore +invokes Patina 20 times and reports 80 unused slots. A bounded invocation port +runs scheduled sub-agents in parallel against one frozen snapshot and restores +deterministic ordinal order. Every invocation and proposal carries an exact +`ElaborationWaveBinding`. Typed failures retain the consumed schedule, +completed invocations, and exact failed dispatch for ordinary worker errors and +task panic or cancellation; task-ID mapping preserves dispatch identity even +when the task produces no normal payload. +This is not yet an end-to-end elaboration path. World-domain proposal types, +admission and conflict/merge ownership, and canonical WorldKernel integration +remain unimplemented. Patina is therefore a real named control and schedulable +title, but not a canonical writer. Provider run 23 remains stopped and no new +newspaper acceptance is claimed. + +1. Commit and push the verified agentic Interpreter plus elaboration scheduling + cut. +2. Map and implement the missing world-domain elaboration proposal, + deterministic admission/conflict/merge boundary, and canonical WorldKernel + integration without granting any titled worker commit authority. +3. Keep provider run 23 stopped until that domain path is verified. Then dispatch + the resulting exact source on Yggdrasil through Codex Connector for + a fresh four-elaboration/six-wave provider run. If it completes, preserve and + verify the immutable artifact manifest without mutating the live daemon or + any prior run root. +4. Only after all six waves commit and an immutable manifest exists, dispatch a fresh blind reviewer with only the strongest unedited page and a neutral editorial brief, then independently audit it against committed public events. -4. Have the game-side adapter lower its authored hierarchy into the published +5. Have the game-side adapter lower its authored hierarchy into the published generic schemas; keep projection and economy translation consumer-owned. -5. Prove one consumer-owned effect crosses that public API, changes two foreign +6. Prove one consumer-owned effect crosses that public API, changes two foreign political layers, causes one durable named figure to emerge and later act, and returns attributed news or intent without mutating Delvehold-owned truth. -6. Measure provider cost and continuity on the existing 200-cell authored-world +7. Measure provider cost and continuity on the existing 200-cell authored-world path without coupling wave width to the provider concurrency ceiling. -7. Leave the unpublished Mars seed and Kalsa refuge expansion unapproved unless +8. Leave the unpublished Mars seed and Kalsa refuge expansion unapproved unless the operator explicitly admits either; retain Kalsa as regression evidence. -8. Keep `gamecult-ops` synchronized with every executable deployment and model +9. Keep `gamecult-ops` synchronized with every executable deployment and model transport change. Use Idunn on Yggdrasil for all builds and deployments. Do not weaken actor custody, private projection, unanimous approval, diff --git a/notes/ghostlight-current-system-map.md b/notes/ghostlight-current-system-map.md index 32abdde..eafc312 100644 --- a/notes/ghostlight-current-system-map.md +++ b/notes/ghostlight-current-system-map.md @@ -167,8 +167,10 @@ exact campaign revision -> connected agency graph + budget/pins/leases/detail debt -> cohesive or arena simulation-cell cover -> one private Projector/Persona/Interpreter membrane per cell - -> model proposes exact constituent-attributed actions or explicit inaction - -> independent effect verifier checks the typed action against the Persona choice + -> Interpreter agent submits or incrementally edits one private exact-decision draft + -> deterministic draft compiler checks exact ownership, permissions, topology, and bounds + -> independent per-action effect verifier checks the typed action against the Persona choice + -> accepted unchanged actions retain their exact verifier binding across local draft repair -> runtime selects compatible attempts and content-addresses each activity -> parallel per-activity fast outcome candidates choose bounded typed consequences -> one local binder plus selective semantic verifier admit or reject each frozen candidate @@ -192,14 +194,28 @@ code bounds it before correction and never publishes private cell choices to a player error surface. A rejected wave returns one spoiler-free message while its exact diagnostic remains operator-only. -On the one same-snapshot Interpreter correction, Ghostlight also removes each -exact subject/effect pair rejected by either per-action local validation or the -independent effect verifier from the output schema. Neither validator chooses -the replacement or gains commit authority; the correction constraint only -makes an already-known-invalid mapping impossible to repeat. The Interpreter -must use another permitted typed lane, omit the action, or fail the whole wave -without mutation. Cross-action failures do not guess at an offender and remain -ordinary semantic corrections. +The Interpreter is a bounded model agent over a private workbench. Its efficient +first action may submit the complete exact decision map only while the draft is +empty. A rejected draft stays in the tool; later actions may upsert or remove +only the exact decisions named as missing or rejected, or inspect the draft. +The tool structurally rejects whole-draft replacement and edits to unrelated +accepted decisions. Local validation returns a typed `local_validation` +finding and the semantic verifier returns exact subject-scoped mismatch +findings. Neither validator chooses the replacement or gains commit authority. +Verifier matches are cached by the exact snapshot-and-action binding, so +repairing one action does not repay inference for unchanged accepted actions. +An `undecided` result returns to the Persona owner instead of letting the +Interpreter invent a choice. + +The strategic scheduler dispatches every simulation cell membrane once and +owns no cell retry. The cell engine projects one exact lived moment. If the +Persona supplies no explicit decision, the engine retries only Persona and +Interpreter against that same projected stream; Projector does not rerun. The +second Persona cites the first Persona and Interpreter attempt as causal +ancestry. Provider transport retains its separately bounded same-request retry, +and Interpreter draft repair remains workbench-local. Actor and cell membranes +share one causal-source derivation primitive for Projector to Persona to +Interpreter, while canonical evidence remains a separate namespace. The effect verifier receives the same exact typed permission slice used by the Interpreter. That slice is its sole map of canonical locations, reachable actor @@ -673,8 +689,8 @@ Ghostlight owns exact verdict coverage and derives the aggregate rejected set; the model cannot reject one arena constituent merely because another constituent's mapping failed, omit a candidate, duplicate an index, or publish a global decision that contradicts its per-action rationale. Rejected actions -receive one same-snapshot Interpreter correction and may not be returned -unchanged. +return to the same private Interpreter draft as exact subject-scoped findings; +unchanged accepted actions retain their verifier binding. Population scale uses reversible individuation: @@ -994,11 +1010,33 @@ admission. Completed compiler, action, tool, and verifier receipts survive terminal failure and are persisted by both the strategic harness and the Dungeon API. Generic harness tests prove that a later action cites both the rejected action and tool receipts, and that exhaustion returns every completed -action and tool receipt. Accepted civic systems persist as versioned component +action and tool receipt. A tool may also return `Continue`: the valid action +updates only consumer-owned private draft state, its receipt remains valid, and +the typed observation requests the next step without pretending the task was +rejected or complete. Accepted civic systems persist as versioned component state, so a later pass receives the current institutions, populations, facts, and relations and must extend that apparatus instead of inventing a parallel government. +World-elaboration tone has one typed catalog of titled workers. `Patina` owns +reusable low-stakes local texture; `Charter` civic institutions and procedure; +`Ledger` material economy; `Hearth` ordinary relationships and belonging; +`Tangle` factions and political leverage; `Veil` uneven knowledge; `Ember` +active pressure; and `Numen` ritual, magic, and wonder. Each user slider is a +zero-to-one-hundred relative dispatch weight, not prompt decoration. The +deterministic smooth weighted scheduler apportions every invocation-budget slot +against the complete enabled profile. It records requested share, actual +dispatch count, and per-title unused allocations; when a selected title is +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. +Those proposals are not canonical mutations; a later admission and conflict +owner must compile and atomically commit them through `WorldKernel`. + 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 diff --git a/state/evidence.jsonl b/state/evidence.jsonl index ac2df0e..e19fa9a 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -165,4 +165,9 @@ {"note": "Supersedes only the transient root-absent portion of the preceding run-20 dispatch record. The result root now exists at /var/lib/gamecult/ghostlight-dungeon/acceptance/elven-realms-autonomous-2875e45-20. Its isolated release BUILD-WITNESS binds exact source 2875e45b3abd9c8c5e207d85444c797884c57136, binary SHA-256 f3015218baaa8f6d70596f5be8a793f7444ce47b93558a44c7958e2b58841c68, and live_service_mutated=false. status.json remains at compiling_world with updated_at 2026-08-27T20:57:14.217251532Z, and the service remains active. No provider result, locality elaboration, strategic wave, newspaper, manifest, or provider acceptance is claimed.", "status": "ok", "ts": "2026-08-27T20:59:56+00:00", "type": "correction"} {"note": "Falsifies run 20 compiling_world as the live steering state. Exact-source run 20 at /var/lib/gamecult/ghostlight-dungeon/acceptance/elven-realms-autonomous-2875e45-20 committed one locality elaboration through revision 1, then Downstream Grain-Pump Station civic reconciliation failed ordinary fact validation with destination expansion facts must have new IDs and non-empty unique statements. No strategic wave, newspaper, or result-root SHA256SUMS exists. The unchanged failure root is archived at F:\\GameCult\\GhostlightDungeon\\acceptance\\elven-realms-autonomous-2875e45-20.tar; its independently rechecked SHA-256 is 6cc564ec70dd6e0279180fb547610d9355418ecdf1ff2cc4f083480ce7841b43. Exact pushed commit 965c9faadcde9a8dced158b00e37d9491d589cde centralizes a maximum-two Terra reconciliation budget in one scheduler across application, structural-validation, and civic-verifier findings, never reruns Sol, and retains ordinary validation as admission owner; 409 library tests and the strategic smoke check pass. Exact-source run 21 is active as ghostlight-newspaper-965c9fa-21.service for /var/lib/gamecult/ghostlight-dungeon/acceptance/elven-realms-autonomous-965c9fa-21. No provider or fantasy-newspaper acceptance is claimed while it is active.", "status": "ok", "ts": "2026-08-27T21:50:50+00:00", "type": "correction"} {"note": "Falsifies the active run-21 steering claim. Exact source 965c9faadcde9a8dced158b00e37d9491d589cde terminated during the second of four locality elaborations at loc:pump_house after one elaboration and zero strategic waves. Both bounded Terra reconciliation actions still yielded destination facts rejected by ordinary namespace validation; no newspaper or completed result-root SHA256SUMS exists. The unchanged root is archived at F:\\GameCult\\GhostlightDungeon\\acceptance\\elven-realms-autonomous-965c9fa-21.tar, independently rechecked SHA-256 2f4d48d47acd3733c99ab8899427e1d33bd4b5cde93da52efa67a3baf98da8e3. Current source surgery correctly treats the fixed retry scheduler as the obsolete owner: the intended replacement is one provider-neutral hand-rolled model-agent harness above ModelPort with bounded observe/action/tool-result steps and causal receipts, plus a destination adapter that applies, lowers, validates, and independently verifies through existing authority. This direction is not yet implementation acceptance; it requires focused and full tests, commit/push, then a fresh four-elaboration/six-wave provider run and separate blind editorial and grounding gates.", "status": "ok", "ts": "2026-08-27T22:32:33+00:00", "type": "correction"} -{"ts": "2026-08-27T23:12:58+00:00", "type": "verification", "status": "ok", "note": "Local phase boundary for commit 842e265f2969d7047e6b2a35fcca7cc371de5c6b: the provider-neutral hand-rolled model-agent harness now owns bounded observe/action/tool-result steps and causal receipts above ModelPort; the destination adapter owns complete candidate application, one canonical fact-namespace checker, ordinary lowering/validation, and a fresh one-shot civic verifier; compiler branches no longer own reconciliation retries and WorldKernel admission remains final. The focused regression proves exact initial fact collision, a different first Terra collision, typed tool finding, causally corrected second action, frozen institution identity, and fresh-verifier acceptance. All 411 library tests pass, and the bounded Modeling re-audit passed all four authority boundaries. The local strategic smoke binary builds but runtime provider execution is not accepted: this workstation selected stale DeepSeek and received HTTP 402 because it has neither Codex Connector service nor a usable key. Provider verification remains pending on Yggdrasil through Codex Connector. Patina remains a planned future harness consumer and is not implemented."} +{"note": "Local phase boundary for commit 842e265f2969d7047e6b2a35fcca7cc371de5c6b: the provider-neutral hand-rolled model-agent harness now owns bounded observe/action/tool-result steps and causal receipts above ModelPort; the destination adapter owns complete candidate application, one canonical fact-namespace checker, ordinary lowering/validation, and a fresh one-shot civic verifier; compiler branches no longer own reconciliation retries and WorldKernel admission remains final. The focused regression proves exact initial fact collision, a different first Terra collision, typed tool finding, causally corrected second action, frozen institution identity, and fresh-verifier acceptance. All 411 library tests pass, and the bounded Modeling re-audit passed all four authority boundaries. The local strategic smoke binary builds but runtime provider execution is not accepted: this workstation selected stale DeepSeek and received HTTP 402 because it has neither Codex Connector service nor a usable key. Provider verification remains pending on Yggdrasil through Codex Connector. Patina remains a planned future harness consumer and is not implemented.", "status": "ok", "ts": "2026-08-27T23:12:58+00:00", "type": "verification"} +{"note": "Falsifies run 21 as the current provider blocker. Exact source 842e265f2969d7047e6b2a35fcca7cc371de5c6b ran through Codex Connector for run 22: the world compiled, locality 1 committed, and locality 2 Sol destination compile, Terra reconciliation action, and fresh Sol civic verifier all accepted before WorldKernel rejected admission with region admission evidence receipts were not supplied. The run ended at 1/4 locality elaborations and 0/6 strategic waves with no newspaper. The unchanged archive is F:\\GameCult\\GhostlightDungeon\\acceptance\\elven-realms-autonomous-842e265-22.tar, SHA-256 90972df1c90eaff699469357ff5de026838940ac07ec5f5faefbaf5d1d266ed9. Root diagnosis: causal ModelAgent receipt IDs were incorrectly copied into canonical profile and relation evidence fields. A focused receipt-namespace split is implemented locally but remains uncommitted and provider-unverified. No later provider run or fantasy-newspaper acceptance is claimed.", "status": "ok", "ts": "2026-08-27T23:40:54+00:00", "type": "correction"} +{"note": "Supersedes only the uncommitted status of the run-22 receipt-namespace diagnosis. Commit c757e5a09d884d263ae3533f537a71ce69010e94 is pushed and separates model-causal source receipt ancestry from canonical admission-evidence receipt IDs. Destination compile, reconciliation, and verification retain causal receipts; population and institution profiles plus migration and local relations lower only canonical admission evidence. Source inspection confirms the regression asserts both namespaces. Provider verification remains pending, and no later run or fantasy-newspaper acceptance is claimed. Patina remains a planned future harness consumer, not an implemented authority.", "status": "ok", "ts": "2026-08-27T23:46:16+00:00", "type": "correction"} +{"note": "Post-verification local boundary: all 417 ghostlight-dungeon library tests pass for the current uncommitted working tree. The generic ModelAgent harness now drives incremental strategic Interpreter draft repair against a frozen Persona decision; deterministic compilation owns structural authority, the independent semantic verifier returns subject-scoped findings, and unchanged accepted actions retain their verifier binding. A typed eight-title elaborator catalog (Patina, Charter, Ledger, Hearth, Tangle, Veil, Ember, Numen), persisted semantic profile and dispatch state, deterministic smooth weighted scheduling, and an actual bounded parallel ElaborationSubAgentPort now exist. Tests prove configured weights change real call counts and blocked work leaves budget unused without catch-up debt. This is not canonical world integration: world-domain elaboration proposal types, deterministic admission/conflict/merge, and WorldKernel integration remain unimplemented. Provider run 23 remains stopped; no provider or fantasy-newspaper acceptance is claimed.", "status": "ok", "ts": "2026-08-28T00:45:02+00:00", "type": "verification"} +{"note": "Corrects two claims in the immediately preceding post-verification record. The full ghostlight-dungeon library suite now passes 418 tests, not 417. Elaborator allocation is against the complete enabled profile, not renormalized across currently eligible titles: scheduled shares for blocked or ineligible titles remain visibly unused with no redistribution or catch-up debt. For Patina 20 and blocked Tangle 80, a 100-slot budget invokes Patina 20 times and records 80 unused slots. All other ownership, missing canonical-integration, stopped run-23, and non-acceptance claims remain unchanged.", "status": "ok", "ts": "2026-08-28T00:47:07+00:00", "type": "correction"} +{"ts": "2026-08-28T01:18:47+00:00", "type": "verification", "status": "ok", "note": "Final local post-audit boundary: all 419 ghostlight-dungeon library tests pass, and the second bounded Modeling audit reports no P1 or P2 issue. Shared causal_source_ids bind actor and cell Projector-to-Persona-to-Interpreter chains. Missing cell-decision recovery reuses one exact CellProjectedMoment: one Projector call, two Persona attempts, two Interpreter attempts, with each second attempt citing the first. Interpreter draft admission rejects whole resubmission and unrelated decision edits; dead scheduler retry trace fields are removed. Every elaboration invocation and proposal now carries ElaborationWaveBinding. Typed ordinary-error and task-panic/cancellation failures retain the consumed schedule, completed invocations, and exact failed dispatch through task-ID mapping. Complete-profile proportional allocation and visibly unused blocked shares remain unchanged. World-domain elaboration proposal/admission/conflict/merge and WorldKernel integration remain unimplemented; provider run 23 remains stopped and no provider or fantasy-newspaper acceptance is claimed."} diff --git a/state/ghostlight-state.cultcache.jsonl b/state/ghostlight-state.cultcache.jsonl index ecb3fd6..e21cbdc 100644 --- a/state/ghostlight-state.cultcache.jsonl +++ b/state/ghostlight-state.cultcache.jsonl @@ -167,3 +167,8 @@ {"key": "2026-08-27T215050Z0000-0165-41519b59ae83", "payload": "eyJub3RlIjogIkZhbHNpZmllcyBydW4gMjAgY29tcGlsaW5nX3dvcmxkIGFzIHRoZSBsaXZlIHN0ZWVyaW5nIHN0YXRlLiBFeGFjdC1zb3VyY2UgcnVuIDIwIGF0IC92YXIvbGliL2dhbWVjdWx0L2dob3N0bGlnaHQtZHVuZ2Vvbi9hY2NlcHRhbmNlL2VsdmVuLXJlYWxtcy1hdXRvbm9tb3VzLTI4NzVlNDUtMjAgY29tbWl0dGVkIG9uZSBsb2NhbGl0eSBlbGFib3JhdGlvbiB0aHJvdWdoIHJldmlzaW9uIDEsIHRoZW4gRG93bnN0cmVhbSBHcmFpbi1QdW1wIFN0YXRpb24gY2l2aWMgcmVjb25jaWxpYXRpb24gZmFpbGVkIG9yZGluYXJ5IGZhY3QgdmFsaWRhdGlvbiB3aXRoIGRlc3RpbmF0aW9uIGV4cGFuc2lvbiBmYWN0cyBtdXN0IGhhdmUgbmV3IElEcyBhbmQgbm9uLWVtcHR5IHVuaXF1ZSBzdGF0ZW1lbnRzLiBObyBzdHJhdGVnaWMgd2F2ZSwgbmV3c3BhcGVyLCBvciByZXN1bHQtcm9vdCBTSEEyNTZTVU1TIGV4aXN0cy4gVGhlIHVuY2hhbmdlZCBmYWlsdXJlIHJvb3QgaXMgYXJjaGl2ZWQgYXQgRjpcXEdhbWVDdWx0XFxHaG9zdGxpZ2h0RHVuZ2VvblxcYWNjZXB0YW5jZVxcZWx2ZW4tcmVhbG1zLWF1dG9ub21vdXMtMjg3NWU0NS0yMC50YXI7IGl0cyBpbmRlcGVuZGVudGx5IHJlY2hlY2tlZCBTSEEtMjU2IGlzIDZjYzU2NGVjNzBkZDZlMDI3OTE4MGZiNTQ3NjEwZDkzNTU0MThlY2RmMWZmMmNjNGYwODM0ODBjZTc4NDFiNDMuIEV4YWN0IHB1c2hlZCBjb21taXQgOTY1YzlmYWFkY2RlOWE4ZGNlZDE1OGIwMGUzN2Q5NDkxZDU4OWNkZSBjZW50cmFsaXplcyBhIG1heGltdW0tdHdvIFRlcnJhIHJlY29uY2lsaWF0aW9uIGJ1ZGdldCBpbiBvbmUgc2NoZWR1bGVyIGFjcm9zcyBhcHBsaWNhdGlvbiwgc3RydWN0dXJhbC12YWxpZGF0aW9uLCBhbmQgY2l2aWMtdmVyaWZpZXIgZmluZGluZ3MsIG5ldmVyIHJlcnVucyBTb2wsIGFuZCByZXRhaW5zIG9yZGluYXJ5IHZhbGlkYXRpb24gYXMgYWRtaXNzaW9uIG93bmVyOyA0MDkgbGlicmFyeSB0ZXN0cyBhbmQgdGhlIHN0cmF0ZWdpYyBzbW9rZSBjaGVjayBwYXNzLiBFeGFjdC1zb3VyY2UgcnVuIDIxIGlzIGFjdGl2ZSBhcyBnaG9zdGxpZ2h0LW5ld3NwYXBlci05NjVjOWZhLTIxLnNlcnZpY2UgZm9yIC92YXIvbGliL2dhbWVjdWx0L2dob3N0bGlnaHQtZHVuZ2Vvbi9hY2NlcHRhbmNlL2VsdmVuLXJlYWxtcy1hdXRvbm9tb3VzLTk2NWM5ZmEtMjEuIE5vIHByb3ZpZGVyIG9yIGZhbnRhc3ktbmV3c3BhcGVyIGFjY2VwdGFuY2UgaXMgY2xhaW1lZCB3aGlsZSBpdCBpcyBhY3RpdmUuIiwgInN0YXR1cyI6ICJvayIsICJ0cyI6ICIyMDI2LTA4LTI3VDIxOjUwOjUwKzAwOjAwIiwgInR5cGUiOiAiY29ycmVjdGlvbiJ9", "stored_at": "2026-08-27T21:50:50.095351+00:00", "type": "ghostlight.evidence_record.v0"} {"key": "2026-08-27T223233Z0000-0166-9328fec4a631", "payload": "eyJub3RlIjogIkZhbHNpZmllcyB0aGUgYWN0aXZlIHJ1bi0yMSBzdGVlcmluZyBjbGFpbS4gRXhhY3Qgc291cmNlIDk2NWM5ZmFhZGNkZTlhOGRjZWQxNThiMDBlMzdkOTQ5MWQ1ODljZGUgdGVybWluYXRlZCBkdXJpbmcgdGhlIHNlY29uZCBvZiBmb3VyIGxvY2FsaXR5IGVsYWJvcmF0aW9ucyBhdCBsb2M6cHVtcF9ob3VzZSBhZnRlciBvbmUgZWxhYm9yYXRpb24gYW5kIHplcm8gc3RyYXRlZ2ljIHdhdmVzLiBCb3RoIGJvdW5kZWQgVGVycmEgcmVjb25jaWxpYXRpb24gYWN0aW9ucyBzdGlsbCB5aWVsZGVkIGRlc3RpbmF0aW9uIGZhY3RzIHJlamVjdGVkIGJ5IG9yZGluYXJ5IG5hbWVzcGFjZSB2YWxpZGF0aW9uOyBubyBuZXdzcGFwZXIgb3IgY29tcGxldGVkIHJlc3VsdC1yb290IFNIQTI1NlNVTVMgZXhpc3RzLiBUaGUgdW5jaGFuZ2VkIHJvb3QgaXMgYXJjaGl2ZWQgYXQgRjpcXEdhbWVDdWx0XFxHaG9zdGxpZ2h0RHVuZ2VvblxcYWNjZXB0YW5jZVxcZWx2ZW4tcmVhbG1zLWF1dG9ub21vdXMtOTY1YzlmYS0yMS50YXIsIGluZGVwZW5kZW50bHkgcmVjaGVja2VkIFNIQS0yNTYgMmY0ZDQ4ZDQ3YWNkMzczM2M5OWFiODg5OTQyN2UxZDMzYmQ0YjVjZGU5M2RhNTJlZmE2N2EzYmFmOThkYThlMy4gQ3VycmVudCBzb3VyY2Ugc3VyZ2VyeSBjb3JyZWN0bHkgdHJlYXRzIHRoZSBmaXhlZCByZXRyeSBzY2hlZHVsZXIgYXMgdGhlIG9ic29sZXRlIG93bmVyOiB0aGUgaW50ZW5kZWQgcmVwbGFjZW1lbnQgaXMgb25lIHByb3ZpZGVyLW5ldXRyYWwgaGFuZC1yb2xsZWQgbW9kZWwtYWdlbnQgaGFybmVzcyBhYm92ZSBNb2RlbFBvcnQgd2l0aCBib3VuZGVkIG9ic2VydmUvYWN0aW9uL3Rvb2wtcmVzdWx0IHN0ZXBzIGFuZCBjYXVzYWwgcmVjZWlwdHMsIHBsdXMgYSBkZXN0aW5hdGlvbiBhZGFwdGVyIHRoYXQgYXBwbGllcywgbG93ZXJzLCB2YWxpZGF0ZXMsIGFuZCBpbmRlcGVuZGVudGx5IHZlcmlmaWVzIHRocm91Z2ggZXhpc3RpbmcgYXV0aG9yaXR5LiBUaGlzIGRpcmVjdGlvbiBpcyBub3QgeWV0IGltcGxlbWVudGF0aW9uIGFjY2VwdGFuY2U7IGl0IHJlcXVpcmVzIGZvY3VzZWQgYW5kIGZ1bGwgdGVzdHMsIGNvbW1pdC9wdXNoLCB0aGVuIGEgZnJlc2ggZm91ci1lbGFib3JhdGlvbi9zaXgtd2F2ZSBwcm92aWRlciBydW4gYW5kIHNlcGFyYXRlIGJsaW5kIGVkaXRvcmlhbCBhbmQgZ3JvdW5kaW5nIGdhdGVzLiIsICJzdGF0dXMiOiAib2siLCAidHMiOiAiMjAyNi0wOC0yN1QyMjozMjozMyswMDowMCIsICJ0eXBlIjogImNvcnJlY3Rpb24ifQ==", "stored_at": "2026-08-27T22:32:33.327539+00:00", "type": "ghostlight.evidence_record.v0"} {"key": "2026-08-27T231258Z0000-0167-045a1f3bd4cb", "payload": "eyJub3RlIjogIkxvY2FsIHBoYXNlIGJvdW5kYXJ5IGZvciBjb21taXQgODQyZTI2NWYyOTY5ZDcwNDdlNmIyYTM1ZmNjYTdjYzM3MWRlNWM2YjogdGhlIHByb3ZpZGVyLW5ldXRyYWwgaGFuZC1yb2xsZWQgbW9kZWwtYWdlbnQgaGFybmVzcyBub3cgb3ducyBib3VuZGVkIG9ic2VydmUvYWN0aW9uL3Rvb2wtcmVzdWx0IHN0ZXBzIGFuZCBjYXVzYWwgcmVjZWlwdHMgYWJvdmUgTW9kZWxQb3J0OyB0aGUgZGVzdGluYXRpb24gYWRhcHRlciBvd25zIGNvbXBsZXRlIGNhbmRpZGF0ZSBhcHBsaWNhdGlvbiwgb25lIGNhbm9uaWNhbCBmYWN0LW5hbWVzcGFjZSBjaGVja2VyLCBvcmRpbmFyeSBsb3dlcmluZy92YWxpZGF0aW9uLCBhbmQgYSBmcmVzaCBvbmUtc2hvdCBjaXZpYyB2ZXJpZmllcjsgY29tcGlsZXIgYnJhbmNoZXMgbm8gbG9uZ2VyIG93biByZWNvbmNpbGlhdGlvbiByZXRyaWVzIGFuZCBXb3JsZEtlcm5lbCBhZG1pc3Npb24gcmVtYWlucyBmaW5hbC4gVGhlIGZvY3VzZWQgcmVncmVzc2lvbiBwcm92ZXMgZXhhY3QgaW5pdGlhbCBmYWN0IGNvbGxpc2lvbiwgYSBkaWZmZXJlbnQgZmlyc3QgVGVycmEgY29sbGlzaW9uLCB0eXBlZCB0b29sIGZpbmRpbmcsIGNhdXNhbGx5IGNvcnJlY3RlZCBzZWNvbmQgYWN0aW9uLCBmcm96ZW4gaW5zdGl0dXRpb24gaWRlbnRpdHksIGFuZCBmcmVzaC12ZXJpZmllciBhY2NlcHRhbmNlLiBBbGwgNDExIGxpYnJhcnkgdGVzdHMgcGFzcywgYW5kIHRoZSBib3VuZGVkIE1vZGVsaW5nIHJlLWF1ZGl0IHBhc3NlZCBhbGwgZm91ciBhdXRob3JpdHkgYm91bmRhcmllcy4gVGhlIGxvY2FsIHN0cmF0ZWdpYyBzbW9rZSBiaW5hcnkgYnVpbGRzIGJ1dCBydW50aW1lIHByb3ZpZGVyIGV4ZWN1dGlvbiBpcyBub3QgYWNjZXB0ZWQ6IHRoaXMgd29ya3N0YXRpb24gc2VsZWN0ZWQgc3RhbGUgRGVlcFNlZWsgYW5kIHJlY2VpdmVkIEhUVFAgNDAyIGJlY2F1c2UgaXQgaGFzIG5laXRoZXIgQ29kZXggQ29ubmVjdG9yIHNlcnZpY2Ugbm9yIGEgdXNhYmxlIGtleS4gUHJvdmlkZXIgdmVyaWZpY2F0aW9uIHJlbWFpbnMgcGVuZGluZyBvbiBZZ2dkcmFzaWwgdGhyb3VnaCBDb2RleCBDb25uZWN0b3IuIFBhdGluYSByZW1haW5zIGEgcGxhbm5lZCBmdXR1cmUgaGFybmVzcyBjb25zdW1lciBhbmQgaXMgbm90IGltcGxlbWVudGVkLiIsICJzdGF0dXMiOiAib2siLCAidHMiOiAiMjAyNi0wOC0yN1QyMzoxMjo1OCswMDowMCIsICJ0eXBlIjogInZlcmlmaWNhdGlvbiJ9", "stored_at": "2026-08-27T23:12:58.254241+00:00", "type": "ghostlight.evidence_record.v0"} +{"key": "2026-08-27T234054Z0000-0168-6e2b83f619ec", "payload": "eyJub3RlIjogIkZhbHNpZmllcyBydW4gMjEgYXMgdGhlIGN1cnJlbnQgcHJvdmlkZXIgYmxvY2tlci4gRXhhY3Qgc291cmNlIDg0MmUyNjVmMjk2OWQ3MDQ3ZTZiMmEzNWZjY2E3Y2MzNzFkZTVjNmIgcmFuIHRocm91Z2ggQ29kZXggQ29ubmVjdG9yIGZvciBydW4gMjI6IHRoZSB3b3JsZCBjb21waWxlZCwgbG9jYWxpdHkgMSBjb21taXR0ZWQsIGFuZCBsb2NhbGl0eSAyIFNvbCBkZXN0aW5hdGlvbiBjb21waWxlLCBUZXJyYSByZWNvbmNpbGlhdGlvbiBhY3Rpb24sIGFuZCBmcmVzaCBTb2wgY2l2aWMgdmVyaWZpZXIgYWxsIGFjY2VwdGVkIGJlZm9yZSBXb3JsZEtlcm5lbCByZWplY3RlZCBhZG1pc3Npb24gd2l0aCByZWdpb24gYWRtaXNzaW9uIGV2aWRlbmNlIHJlY2VpcHRzIHdlcmUgbm90IHN1cHBsaWVkLiBUaGUgcnVuIGVuZGVkIGF0IDEvNCBsb2NhbGl0eSBlbGFib3JhdGlvbnMgYW5kIDAvNiBzdHJhdGVnaWMgd2F2ZXMgd2l0aCBubyBuZXdzcGFwZXIuIFRoZSB1bmNoYW5nZWQgYXJjaGl2ZSBpcyBGOlxcR2FtZUN1bHRcXEdob3N0bGlnaHREdW5nZW9uXFxhY2NlcHRhbmNlXFxlbHZlbi1yZWFsbXMtYXV0b25vbW91cy04NDJlMjY1LTIyLnRhciwgU0hBLTI1NiA5MDk3MmRmMWM5MGVhZmY2OTk0NjkzNTdmZjVkZTAyNjgzODk0MGFjMDdlYzVmNWZhZWZiYWY1ZDFkMjY2ZWQ5LiBSb290IGRpYWdub3NpczogY2F1c2FsIE1vZGVsQWdlbnQgcmVjZWlwdCBJRHMgd2VyZSBpbmNvcnJlY3RseSBjb3BpZWQgaW50byBjYW5vbmljYWwgcHJvZmlsZSBhbmQgcmVsYXRpb24gZXZpZGVuY2UgZmllbGRzLiBBIGZvY3VzZWQgcmVjZWlwdC1uYW1lc3BhY2Ugc3BsaXQgaXMgaW1wbGVtZW50ZWQgbG9jYWxseSBidXQgcmVtYWlucyB1bmNvbW1pdHRlZCBhbmQgcHJvdmlkZXItdW52ZXJpZmllZC4gTm8gbGF0ZXIgcHJvdmlkZXIgcnVuIG9yIGZhbnRhc3ktbmV3c3BhcGVyIGFjY2VwdGFuY2UgaXMgY2xhaW1lZC4iLCAic3RhdHVzIjogIm9rIiwgInRzIjogIjIwMjYtMDgtMjdUMjM6NDA6NTQrMDA6MDAiLCAidHlwZSI6ICJjb3JyZWN0aW9uIn0=", "stored_at": "2026-08-27T23:40:54.643152+00:00", "type": "ghostlight.evidence_record.v0"} +{"key": "2026-08-27T234616Z0000-0169-20385ea2f6a3", "payload": "eyJub3RlIjogIlN1cGVyc2VkZXMgb25seSB0aGUgdW5jb21taXR0ZWQgc3RhdHVzIG9mIHRoZSBydW4tMjIgcmVjZWlwdC1uYW1lc3BhY2UgZGlhZ25vc2lzLiBDb21taXQgYzc1N2U1YTA5ZDg4NGQyNjNhZTM1MzNmNTM3YTcxY2U2OTAxMGU5NCBpcyBwdXNoZWQgYW5kIHNlcGFyYXRlcyBtb2RlbC1jYXVzYWwgc291cmNlIHJlY2VpcHQgYW5jZXN0cnkgZnJvbSBjYW5vbmljYWwgYWRtaXNzaW9uLWV2aWRlbmNlIHJlY2VpcHQgSURzLiBEZXN0aW5hdGlvbiBjb21waWxlLCByZWNvbmNpbGlhdGlvbiwgYW5kIHZlcmlmaWNhdGlvbiByZXRhaW4gY2F1c2FsIHJlY2VpcHRzOyBwb3B1bGF0aW9uIGFuZCBpbnN0aXR1dGlvbiBwcm9maWxlcyBwbHVzIG1pZ3JhdGlvbiBhbmQgbG9jYWwgcmVsYXRpb25zIGxvd2VyIG9ubHkgY2Fub25pY2FsIGFkbWlzc2lvbiBldmlkZW5jZS4gU291cmNlIGluc3BlY3Rpb24gY29uZmlybXMgdGhlIHJlZ3Jlc3Npb24gYXNzZXJ0cyBib3RoIG5hbWVzcGFjZXMuIFByb3ZpZGVyIHZlcmlmaWNhdGlvbiByZW1haW5zIHBlbmRpbmcsIGFuZCBubyBsYXRlciBydW4gb3IgZmFudGFzeS1uZXdzcGFwZXIgYWNjZXB0YW5jZSBpcyBjbGFpbWVkLiBQYXRpbmEgcmVtYWlucyBhIHBsYW5uZWQgZnV0dXJlIGhhcm5lc3MgY29uc3VtZXIsIG5vdCBhbiBpbXBsZW1lbnRlZCBhdXRob3JpdHkuIiwgInN0YXR1cyI6ICJvayIsICJ0cyI6ICIyMDI2LTA4LTI3VDIzOjQ2OjE2KzAwOjAwIiwgInR5cGUiOiAiY29ycmVjdGlvbiJ9", "stored_at": "2026-08-27T23:46:16.502543+00:00", "type": "ghostlight.evidence_record.v0"} +{"key": "2026-08-28T004502Z0000-0170-c45325f7cd18", "payload": "eyJub3RlIjogIlBvc3QtdmVyaWZpY2F0aW9uIGxvY2FsIGJvdW5kYXJ5OiBhbGwgNDE3IGdob3N0bGlnaHQtZHVuZ2VvbiBsaWJyYXJ5IHRlc3RzIHBhc3MgZm9yIHRoZSBjdXJyZW50IHVuY29tbWl0dGVkIHdvcmtpbmcgdHJlZS4gVGhlIGdlbmVyaWMgTW9kZWxBZ2VudCBoYXJuZXNzIG5vdyBkcml2ZXMgaW5jcmVtZW50YWwgc3RyYXRlZ2ljIEludGVycHJldGVyIGRyYWZ0IHJlcGFpciBhZ2FpbnN0IGEgZnJvemVuIFBlcnNvbmEgZGVjaXNpb247IGRldGVybWluaXN0aWMgY29tcGlsYXRpb24gb3ducyBzdHJ1Y3R1cmFsIGF1dGhvcml0eSwgdGhlIGluZGVwZW5kZW50IHNlbWFudGljIHZlcmlmaWVyIHJldHVybnMgc3ViamVjdC1zY29wZWQgZmluZGluZ3MsIGFuZCB1bmNoYW5nZWQgYWNjZXB0ZWQgYWN0aW9ucyByZXRhaW4gdGhlaXIgdmVyaWZpZXIgYmluZGluZy4gQSB0eXBlZCBlaWdodC10aXRsZSBlbGFib3JhdG9yIGNhdGFsb2cgKFBhdGluYSwgQ2hhcnRlciwgTGVkZ2VyLCBIZWFydGgsIFRhbmdsZSwgVmVpbCwgRW1iZXIsIE51bWVuKSwgcGVyc2lzdGVkIHNlbWFudGljIHByb2ZpbGUgYW5kIGRpc3BhdGNoIHN0YXRlLCBkZXRlcm1pbmlzdGljIHNtb290aCB3ZWlnaHRlZCBzY2hlZHVsaW5nLCBhbmQgYW4gYWN0dWFsIGJvdW5kZWQgcGFyYWxsZWwgRWxhYm9yYXRpb25TdWJBZ2VudFBvcnQgbm93IGV4aXN0LiBUZXN0cyBwcm92ZSBjb25maWd1cmVkIHdlaWdodHMgY2hhbmdlIHJlYWwgY2FsbCBjb3VudHMgYW5kIGJsb2NrZWQgd29yayBsZWF2ZXMgYnVkZ2V0IHVudXNlZCB3aXRob3V0IGNhdGNoLXVwIGRlYnQuIFRoaXMgaXMgbm90IGNhbm9uaWNhbCB3b3JsZCBpbnRlZ3JhdGlvbjogd29ybGQtZG9tYWluIGVsYWJvcmF0aW9uIHByb3Bvc2FsIHR5cGVzLCBkZXRlcm1pbmlzdGljIGFkbWlzc2lvbi9jb25mbGljdC9tZXJnZSwgYW5kIFdvcmxkS2VybmVsIGludGVncmF0aW9uIHJlbWFpbiB1bmltcGxlbWVudGVkLiBQcm92aWRlciBydW4gMjMgcmVtYWlucyBzdG9wcGVkOyBubyBwcm92aWRlciBvciBmYW50YXN5LW5ld3NwYXBlciBhY2NlcHRhbmNlIGlzIGNsYWltZWQuIiwgInN0YXR1cyI6ICJvayIsICJ0cyI6ICIyMDI2LTA4LTI4VDAwOjQ1OjAyKzAwOjAwIiwgInR5cGUiOiAidmVyaWZpY2F0aW9uIn0=", "stored_at": "2026-08-28T00:45:02.928339+00:00", "type": "ghostlight.evidence_record.v0"} +{"key": "2026-08-28T004707Z0000-0171-d3e19f6efd7f", "payload": "eyJub3RlIjogIkNvcnJlY3RzIHR3byBjbGFpbXMgaW4gdGhlIGltbWVkaWF0ZWx5IHByZWNlZGluZyBwb3N0LXZlcmlmaWNhdGlvbiByZWNvcmQuIFRoZSBmdWxsIGdob3N0bGlnaHQtZHVuZ2VvbiBsaWJyYXJ5IHN1aXRlIG5vdyBwYXNzZXMgNDE4IHRlc3RzLCBub3QgNDE3LiBFbGFib3JhdG9yIGFsbG9jYXRpb24gaXMgYWdhaW5zdCB0aGUgY29tcGxldGUgZW5hYmxlZCBwcm9maWxlLCBub3QgcmVub3JtYWxpemVkIGFjcm9zcyBjdXJyZW50bHkgZWxpZ2libGUgdGl0bGVzOiBzY2hlZHVsZWQgc2hhcmVzIGZvciBibG9ja2VkIG9yIGluZWxpZ2libGUgdGl0bGVzIHJlbWFpbiB2aXNpYmx5IHVudXNlZCB3aXRoIG5vIHJlZGlzdHJpYnV0aW9uIG9yIGNhdGNoLXVwIGRlYnQuIEZvciBQYXRpbmEgMjAgYW5kIGJsb2NrZWQgVGFuZ2xlIDgwLCBhIDEwMC1zbG90IGJ1ZGdldCBpbnZva2VzIFBhdGluYSAyMCB0aW1lcyBhbmQgcmVjb3JkcyA4MCB1bnVzZWQgc2xvdHMuIEFsbCBvdGhlciBvd25lcnNoaXAsIG1pc3NpbmcgY2Fub25pY2FsLWludGVncmF0aW9uLCBzdG9wcGVkIHJ1bi0yMywgYW5kIG5vbi1hY2NlcHRhbmNlIGNsYWltcyByZW1haW4gdW5jaGFuZ2VkLiIsICJzdGF0dXMiOiAib2siLCAidHMiOiAiMjAyNi0wOC0yOFQwMDo0NzowNyswMDowMCIsICJ0eXBlIjogImNvcnJlY3Rpb24ifQ==", "stored_at": "2026-08-28T00:47:07.037174+00:00", "type": "ghostlight.evidence_record.v0"} +{"key": "2026-08-28T011847Z0000-0172-d239fd681a50", "payload": "eyJub3RlIjogIkZpbmFsIGxvY2FsIHBvc3QtYXVkaXQgYm91bmRhcnk6IGFsbCA0MTkgZ2hvc3RsaWdodC1kdW5nZW9uIGxpYnJhcnkgdGVzdHMgcGFzcywgYW5kIHRoZSBzZWNvbmQgYm91bmRlZCBNb2RlbGluZyBhdWRpdCByZXBvcnRzIG5vIFAxIG9yIFAyIGlzc3VlLiBTaGFyZWQgY2F1c2FsX3NvdXJjZV9pZHMgYmluZCBhY3RvciBhbmQgY2VsbCBQcm9qZWN0b3ItdG8tUGVyc29uYS10by1JbnRlcnByZXRlciBjaGFpbnMuIE1pc3NpbmcgY2VsbC1kZWNpc2lvbiByZWNvdmVyeSByZXVzZXMgb25lIGV4YWN0IENlbGxQcm9qZWN0ZWRNb21lbnQ6IG9uZSBQcm9qZWN0b3IgY2FsbCwgdHdvIFBlcnNvbmEgYXR0ZW1wdHMsIHR3byBJbnRlcnByZXRlciBhdHRlbXB0cywgd2l0aCBlYWNoIHNlY29uZCBhdHRlbXB0IGNpdGluZyB0aGUgZmlyc3QuIEludGVycHJldGVyIGRyYWZ0IGFkbWlzc2lvbiByZWplY3RzIHdob2xlIHJlc3VibWlzc2lvbiBhbmQgdW5yZWxhdGVkIGRlY2lzaW9uIGVkaXRzOyBkZWFkIHNjaGVkdWxlciByZXRyeSB0cmFjZSBmaWVsZHMgYXJlIHJlbW92ZWQuIEV2ZXJ5IGVsYWJvcmF0aW9uIGludm9jYXRpb24gYW5kIHByb3Bvc2FsIG5vdyBjYXJyaWVzIEVsYWJvcmF0aW9uV2F2ZUJpbmRpbmcuIFR5cGVkIG9yZGluYXJ5LWVycm9yIGFuZCB0YXNrLXBhbmljL2NhbmNlbGxhdGlvbiBmYWlsdXJlcyByZXRhaW4gdGhlIGNvbnN1bWVkIHNjaGVkdWxlLCBjb21wbGV0ZWQgaW52b2NhdGlvbnMsIGFuZCBleGFjdCBmYWlsZWQgZGlzcGF0Y2ggdGhyb3VnaCB0YXNrLUlEIG1hcHBpbmcuIENvbXBsZXRlLXByb2ZpbGUgcHJvcG9ydGlvbmFsIGFsbG9jYXRpb24gYW5kIHZpc2libHkgdW51c2VkIGJsb2NrZWQgc2hhcmVzIHJlbWFpbiB1bmNoYW5nZWQuIFdvcmxkLWRvbWFpbiBlbGFib3JhdGlvbiBwcm9wb3NhbC9hZG1pc3Npb24vY29uZmxpY3QvbWVyZ2UgYW5kIFdvcmxkS2VybmVsIGludGVncmF0aW9uIHJlbWFpbiB1bmltcGxlbWVudGVkOyBwcm92aWRlciBydW4gMjMgcmVtYWlucyBzdG9wcGVkIGFuZCBubyBwcm92aWRlciBvciBmYW50YXN5LW5ld3NwYXBlciBhY2NlcHRhbmNlIGlzIGNsYWltZWQuIiwgInN0YXR1cyI6ICJvayIsICJ0cyI6ICIyMDI2LTA4LTI4VDAxOjE4OjQ3KzAwOjAwIiwgInR5cGUiOiAidmVyaWZpY2F0aW9uIn0=", "stored_at": "2026-08-28T01:18:47.318353+00:00", "type": "ghostlight.evidence_record.v0"} diff --git a/state/map.yaml b/state/map.yaml index a762c4c..06837b9 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -323,6 +323,6 @@ data_flow: - If state grows faster than understanding, cut it back. current_status: - summary: Ghostlight's generic consumer boundary admits sparse WorldSeeds, runs the hundreds-class parallel cell machinery used by Dungeon, and exposes a grounded newspaper projection over committed public events. Local acceptance proves 1,000 subjects across 200 cells and two-wave durable named-person emergence, but fantasy-newspaper presentation remains unaccepted. Exact-source run 21 terminated during the second of four locality elaborations at `loc:pump_house`; one elaboration committed, zero strategic waves ran, and both bounded Terra reconciliation actions still produced facts rejected by ordinary namespace validation. No newspaper or completed result-root manifest exists. The unchanged run is archived at `F:\GameCult\GhostlightDungeon\acceptance\elven-realms-autonomous-965c9fa-21.tar`, SHA-256 `2f4d48d47acd3733c99ab8899427e1d33bd4b5cde93da52efa67a3baf98da8e3`. Commit `842e265f2969d7047e6b2a35fcca7cc371de5c6b` replaces compiler-owned reconciliation retries with a hand-rolled, provider-neutral model-agent harness above `ModelPort`; the harness owns bounded observe/action/tool-result steps and causal receipts, while the destination adapter applies the complete candidate, uses one canonical fact-namespace checker, lowers through the ordinary path, and asks a fresh one-shot civic verifier. WorldKernel admission remains final. The focused regression proves an initial exact fact collision, a different first Terra collision, the resulting typed tool finding, a corrected second action, and fresh-verifier acceptance while institution identity remains frozen. All 411 library tests pass, and the Modeling re-audit found the transport, harness, destination adapter, and kernel boundaries coherent. The strategic smoke binary builds, but this workstation selected its stale DeepSeek route and received HTTP 402 because it has neither the Codex Connector service nor a usable key; provider smoke is therefore pending on Yggdrasil, not locally accepted. Reconciliation is the first harness consumer. Patina remains a planned later consumer whose typed tools may add durable, locally grounded low-stakes texture that later events can reuse; no Patina implementation or acceptance is claimed. The live Ghostlight daemon is not the test body. Dungeon play remains regression pressure, the Delvehold game-side adapter remains unimplemented, and unpublished Mars and Kalsa destination previews remain unapproved. - next_action: Commit and push this phase-boundary Mind update with implementation commit `842e265`, then run the exact source on Yggdrasil through Codex Connector. Require four locality elaborations, six committed strategic waves, and an immutable artifact manifest. Only then send the strongest unedited page to separate blind editorial and grounding audits. Do not treat the local DeepSeek HTTP 402 as a harness failure or claim provider acceptance before the Yggdrasil run and both review gates pass. + summary: Ghostlight's generic consumer boundary admits sparse WorldSeeds, runs the hundreds-class parallel cell machinery used by Dungeon, and exposes a grounded newspaper projection over committed public events. Local acceptance proves 1,000 subjects across 200 cells and two-wave durable named-person emergence, but fantasy-newspaper presentation remains unaccepted. Commit `842e265f2969d7047e6b2a35fcca7cc371de5c6b` introduced the provider-neutral model-agent harness, and pushed commit `c757e5a09d884d263ae3533f537a71ce69010e94` separates model-causal ancestry from canonical admission evidence after run 22 reached semantic acceptance and failed only at WorldKernel evidence admission. The current verified working tree extends that harness into the strategic Interpreter: shared `causal_source_ids` bind both actor and cell Projector-to-Persona-to-Interpreter chains; the agent incrementally edits one private frozen-decision draft; deterministic compilation owns structure and authority; the independent semantic verifier returns subject-scoped findings; and unchanged accepted actions retain their binding. Missing cell decisions reuse one exact `CellProjectedMoment`: one Projector call feeds two Persona and two Interpreter attempts, and the second attempts cite the first. Draft admission rejects whole resubmission and edits to unrelated decisions; dead scheduler retry trace fields are removed. A typed eight-title elaborator catalog includes Patina, Charter, Ledger, Hearth, Tangle, Veil, Ember, and Numen; persisted profile weights allocate the complete enabled-profile budget. Ineligible or blocked scheduled slots remain visibly unused instead of being redistributed or accruing catch-up debt. Every invocation and proposal carries an `ElaborationWaveBinding`; bounded parallel execution returns deterministic ordinal results, while typed ordinary-error and task-panic/cancellation failures retain the consumed schedule, completed invocations, and exact failed dispatch through task-ID mapping. All 419 library tests pass, and the second bounded Modeling audit found no P1 or P2 issue. This is still control-plane and proposal machinery only: world-domain elaboration proposal types, admission/conflict/merge ownership, and integration of accepted elaboration into canonical WorldKernel state remain unimplemented. Patina exists as a named weighted control and schedulable sub-agent title, not as a canonical world writer or an end-to-end admitted elaborator. Provider run 23 remains stopped; no new provider or newspaper acceptance is claimed. The live Ghostlight daemon is not the test body. Dungeon play remains regression pressure, the Delvehold game-side adapter remains unimplemented, and unpublished Mars and Kalsa destination previews remain unapproved. + next_action: Commit and push the verified agentic Interpreter plus elaboration scheduling cut, then map and implement the missing world-domain elaboration proposal, deterministic admission/conflict/merge boundary, and canonical WorldKernel integration without granting any titled worker commit authority. Keep provider run 23 stopped until that domain path is verified. Then resume the four-elaboration/six-wave Codex Connector acceptance run and require an immutable manifest plus separate blind editorial and grounding audits. gestalt_population: Gestalt Personas own shared population baselines; persistent member deltas own named individuality; WorldKernel materialization and approval-gated fission preserve lineage and identity. Materialisation/folding changes only representation and the exact member delta, advances resolution epoch, and retires the old cover; it has no Gestalt-wide effect authority. Selected actionable member exceptions are mandatory Projector perspective owners, so aggregation cannot silently erase their decision. Presence projection is limited to nearby active leaves and exact-location dormant members, includes reciprocal player relationship evidence, and may propose an earned cast without committing it. Simulation cells are derived covers only.