From 023b47cbe3c3619b92ddecc79541582bc5632a81 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 11 Jul 2026 18:52:22 +0100 Subject: [PATCH] Move coordinator state policy into core --- epiphany-codex-bridge/src/mutation_service.rs | 30 +-- epiphany-core/src/coordinator_service.rs | 232 ++++++++++++++++++ epiphany-core/src/lib.rs | 4 + state/ledgers.msgpack | Bin 398376 -> 398691 bytes 4 files changed, 239 insertions(+), 27 deletions(-) create mode 100644 epiphany-core/src/coordinator_service.rs diff --git a/epiphany-codex-bridge/src/mutation_service.rs b/epiphany-codex-bridge/src/mutation_service.rs index b7de9d89..4aee562a 100644 --- a/epiphany-codex-bridge/src/mutation_service.rs +++ b/epiphany-codex-bridge/src/mutation_service.rs @@ -30,7 +30,7 @@ use epiphany_core::RuntimeSpineHeartbeatJobOptions; use epiphany_core::RuntimeSpineHeartbeatLaunchPlanOptions; use epiphany_core::SOUL_VERDICT_RECEIPT_TYPE; use epiphany_core::SUBSTRATE_GATE_REPO_ACCESS_GRANT_RECEIPT_TYPE; -use epiphany_core::apply_epiphany_state_update; +use epiphany_core::apply_coordinator_state_update_to_state; use epiphany_core::build_epiphany_reorient_launch_request_with_dynamic_context; use epiphany_core::build_epiphany_role_launch_request_with_dynamic_context; use epiphany_core::clear_epiphany_job_binding_backend; @@ -205,32 +205,8 @@ pub fn apply_epiphany_state_update_to_state( update: EpiphanyStateUpdate, reference_turn_id: Option, ) -> BridgeResult { - if update.is_empty() { - return Err(EpiphanyBridgeError::InvalidRequest( - "epiphany update patch must contain at least one mutation".to_string(), - )); - } - - let mut next_state = current_state.clone(); - if let Some(expected_revision) = update.expected_revision - && next_state.revision != expected_revision - { - return Err(EpiphanyBridgeError::InvalidRequest(format!( - "epiphany state revision mismatch: expected {expected_revision}, found {}", - next_state.revision - ))); - } - - let validation_errors = epiphany_state_update_validation_errors(&next_state, &update); - if !validation_errors.is_empty() { - return Err(EpiphanyBridgeError::InvalidRequest(format!( - "invalid epiphany update patch: {}", - validation_errors.join("; ") - ))); - } - - apply_epiphany_state_update(&mut next_state, update, reference_turn_id); - Ok(next_state) + apply_coordinator_state_update_to_state(current_state, update, reference_turn_id) + .map_err(|error| EpiphanyBridgeError::InvalidRequest(error.to_string())) } pub async fn launch_epiphany_job_on_thread( diff --git a/epiphany-core/src/coordinator_service.rs b/epiphany-core/src/coordinator_service.rs new file mode 100644 index 00000000..f6e9d0c6 --- /dev/null +++ b/epiphany-core/src/coordinator_service.rs @@ -0,0 +1,232 @@ +use crate::EpiphanyStateUpdate; +use crate::EpiphanyStateUpdatedField; +use crate::apply_epiphany_state_update; +use crate::epiphany_state_update_validation_errors; +use crate::load_thread_state; +use crate::write_thread_state; +use anyhow::Result; +use anyhow::anyhow; +use epiphany_state_model::EpiphanyThreadState; +use std::path::Path; +use std::path::PathBuf; + +/// The Epiphany-native owner of coordinator state. +/// +/// Codex compatibility surfaces may translate requests into calls on this +/// service, but they do not receive a persistence hook or retain an independent +/// state opinion. +#[derive(Debug, Clone)] +pub struct EpiphanyCoordinatorService { + thread_state_store: PathBuf, + runtime_spine_store: PathBuf, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct EpiphanyCoordinatorStateApplied { + pub revision: u64, + pub changed_fields: Vec, + pub state: EpiphanyThreadState, +} + +impl EpiphanyCoordinatorService { + pub fn new( + thread_state_store: impl Into, + runtime_spine_store: impl Into, + ) -> Self { + Self { + thread_state_store: thread_state_store.into(), + runtime_spine_store: runtime_spine_store.into(), + } + } + + pub fn thread_state_store(&self) -> &Path { + &self.thread_state_store + } + + pub fn runtime_spine_store(&self) -> &Path { + &self.runtime_spine_store + } + + pub fn state(&self) -> Result> { + load_thread_state(&self.thread_state_store) + } + + pub fn apply_state_update( + &self, + thread_id: &str, + update: EpiphanyStateUpdate, + reference_turn_id: Option, + ) -> Result { + let changed_fields = changed_fields(&update); + let state = apply_coordinator_state_update_to_state( + &self.state()?.unwrap_or_default(), + update, + reference_turn_id, + )?; + write_thread_state(&self.thread_state_store, thread_id, &state)?; + Ok(EpiphanyCoordinatorStateApplied { + revision: state.revision, + changed_fields, + state, + }) + } +} + +pub fn apply_coordinator_state_update_to_state( + current_state: &EpiphanyThreadState, + update: EpiphanyStateUpdate, + reference_turn_id: Option, +) -> Result { + if update.is_empty() { + return Err(anyhow!( + "epiphany update patch must contain at least one mutation" + )); + } + if let Some(expected_revision) = update.expected_revision + && expected_revision != current_state.revision + { + return Err(anyhow!( + "epiphany state revision mismatch: expected {expected_revision}, found {}", + current_state.revision + )); + } + + let validation_errors = epiphany_state_update_validation_errors(current_state, &update); + if !validation_errors.is_empty() { + return Err(anyhow!( + "invalid epiphany update patch: {}", + validation_errors.join("; ") + )); + } + + let mut next_state = current_state.clone(); + apply_epiphany_state_update(&mut next_state, update, reference_turn_id); + Ok(next_state) +} + +fn changed_fields(update: &EpiphanyStateUpdate) -> Vec { + let mut fields = Vec::new(); + if update.objective.is_some() { + fields.push(EpiphanyStateUpdatedField::Objective); + } + if update.active_subgoal_id.is_some() { + fields.push(EpiphanyStateUpdatedField::ActiveSubgoalId); + } + if update.subgoals.is_some() { + fields.push(EpiphanyStateUpdatedField::Subgoals); + } + if update.invariants.is_some() { + fields.push(EpiphanyStateUpdatedField::Invariants); + } + if update.graphs.is_some() { + fields.push(EpiphanyStateUpdatedField::Graphs); + } + if update.graph_frontier.is_some() { + fields.push(EpiphanyStateUpdatedField::GraphFrontier); + } + if update.graph_checkpoint.is_some() { + fields.push(EpiphanyStateUpdatedField::GraphCheckpoint); + } + if update.scratch.is_some() { + fields.push(EpiphanyStateUpdatedField::Scratch); + } + if update.investigation_checkpoint.is_some() { + fields.push(EpiphanyStateUpdatedField::InvestigationCheckpoint); + } + if update.job_bindings.is_some() { + fields.push(EpiphanyStateUpdatedField::JobBindings); + } + if !update.acceptance_receipts.is_empty() { + fields.push(EpiphanyStateUpdatedField::AcceptanceReceipts); + } + if !update.runtime_links.is_empty() { + fields.push(EpiphanyStateUpdatedField::RuntimeLinks); + } + if !update.observations.is_empty() { + fields.push(EpiphanyStateUpdatedField::Observations); + } + if !update.evidence.is_empty() { + fields.push(EpiphanyStateUpdatedField::Evidence); + } + if update.churn.is_some() { + fields.push(EpiphanyStateUpdatedField::Churn); + } + if update.mode.is_some() { + fields.push(EpiphanyStateUpdatedField::Mode); + } + if update.planning.is_some() { + fields.push(EpiphanyStateUpdatedField::Planning); + } + fields +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn native_service_owns_revision_gated_thread_state() -> Result<()> { + let temp = tempfile::tempdir()?; + let service = EpiphanyCoordinatorService::new( + temp.path().join("thread-state.msgpack"), + temp.path().join("runtime-spine.msgpack"), + ); + + let applied = service.apply_state_update( + "coordinator-session-1", + EpiphanyStateUpdate { + expected_revision: Some(0), + objective: Some("Remove Codex from coordinator authority.".to_string()), + ..Default::default() + }, + Some("operator-turn-1".to_string()), + )?; + + assert_eq!(applied.revision, 1); + assert_eq!( + applied.changed_fields, + vec![EpiphanyStateUpdatedField::Objective] + ); + assert_eq!( + service.state()?.and_then(|state| state.objective), + Some("Remove Codex from coordinator authority.".to_string()) + ); + Ok(()) + } + + #[test] + fn rejected_revision_cannot_mutate_or_repair_native_state() -> Result<()> { + let temp = tempfile::tempdir()?; + let service = EpiphanyCoordinatorService::new( + temp.path().join("thread-state.msgpack"), + temp.path().join("runtime-spine.msgpack"), + ); + service.apply_state_update( + "coordinator-session-1", + EpiphanyStateUpdate { + expected_revision: Some(0), + objective: Some("Canonical objective".to_string()), + ..Default::default() + }, + None, + )?; + + let error = service + .apply_state_update( + "coordinator-session-1", + EpiphanyStateUpdate { + expected_revision: Some(0), + objective: Some("Stale overwrite".to_string()), + ..Default::default() + }, + None, + ) + .expect_err("stale revision must be refused"); + + assert!(error.to_string().contains("revision mismatch")); + let state = service.state()?.expect("canonical state must remain"); + assert_eq!(state.revision, 1); + assert_eq!(state.objective.as_deref(), Some("Canonical objective")); + Ok(()) + } +} diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index f4d33e49..d60d1169 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -2,6 +2,7 @@ mod agent_launch; mod agent_memory; mod agent_utterance_state; mod continuity_gateway; +mod coordinator_service; mod cultmesh_integration; mod distillation; mod eyes_gateway; @@ -118,6 +119,9 @@ pub use agent_utterance_state::AgentUtteranceValue; pub use agent_utterance_state::WEKSA_UTTERANCE_HANDOFF_SCHEMA_VERSION; pub use agent_utterance_state::derive_agent_utterance_state; pub use continuity_gateway::*; +pub use coordinator_service::EpiphanyCoordinatorService; +pub use coordinator_service::EpiphanyCoordinatorStateApplied; +pub use coordinator_service::apply_coordinator_state_update_to_state; pub use cultcache_rs::CacheBackingStore; pub use cultcache_rs::CultCache; pub use cultcache_rs::CultCacheEnvelope; diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index b4a28c596b0327157ea4bef547cef1d87df4560c..0d8a4d645f4348654c17f194e737c7a53caeac8b 100644 GIT binary patch delta 361 zcmYk1u}Z{15Qa_EYXnie;=pFWI%g8lgS$pZZ)Ih-mmQLY&F;FpNxbR`3m@RjI~+C& z7UB!|5VpRElL%t*GtBJ%-#@e6PQITfuSdbjEJ~7_WH!G@=Sh6~xicDHy`2SjLGbd> zg^yhrkovky+9U11cj0JrJbwB}vVl^&Aez3a;+^Fig|6pp>0HtpmYnm zRSvRR`i$izf-fyH9y!lEg4B#G#d&LmrwT^a4lFjp39W!B4vbgA4V}?aEDRt9ig3D{6^FMVtHtpUD5HC5fa_>2kn@D1ONa4 delta 65 zcmaF7N@B$di46jb!e+WgMj?h~Rwl+)Mut(x7}$haH!Cw1GBU1fp32ldm5C9EK{PWE Ovj8#c_Nh#4lLY~GixQ6j