Split native coordinator state organ

This commit is contained in:
Meta Vens 2026-07-11 19:35:40 +01:00
commit f8ac056369
7 changed files with 213 additions and 204 deletions

View file

@ -1,5 +1,5 @@
use crate::coordinator_results::latest_runtime_link;
use crate::coordinator_service::changed_fields;
use crate::coordinator_state::changed_fields;
use crate::*;
use epiphany_state_model::EpiphanyThreadState;
use std::path::Path;
@ -365,3 +365,25 @@ fn role_label_lower(role_id: EpiphanyRoleResultRoleId) -> &'static str {
EpiphanyRoleResultRoleId::Reorientation => "reorientation",
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn completed_finding_admission_refuses_missing_binding() {
let error = completed_role_finding(
None,
&EpiphanyThreadState::default(),
EpiphanyRoleResultRoleId::Modeling,
"modeling-worker",
)
.expect_err("missing binding must not become an acceptable finding");
assert_eq!(
error,
EpiphanyCoordinatorAdmissionError::InvalidRequest(
"epiphany role binding \"modeling-worker\" was not found".to_string()
)
);
}
}

View file

@ -1,19 +1,15 @@
use crate::EpiphanyCoordinatorReorientResultSnapshot;
use crate::EpiphanyCoordinatorRoleResultSnapshot;
use crate::EpiphanyCoordinatorStateApplied;
use crate::EpiphanyRoleResultRoleId;
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::apply_coordinator_state_update;
use crate::read_coordinator_state;
use crate::read_reorient_result_snapshot;
use crate::read_role_result_snapshot;
use crate::write_thread_state;
use anyhow::Result;
use anyhow::anyhow;
use epiphany_state_model::EpiphanyThreadState;
use std::path::Path;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone)]
pub struct EpiphanyCoordinatorService {
@ -21,13 +17,6 @@ pub struct EpiphanyCoordinatorService {
runtime_spine_store: PathBuf,
}
#[derive(Debug, Clone, PartialEq)]
pub struct EpiphanyCoordinatorStateApplied {
pub revision: u64,
pub changed_fields: Vec<EpiphanyStateUpdatedField>,
pub state: EpiphanyThreadState,
}
impl EpiphanyCoordinatorService {
pub fn new(
thread_state_store: impl Into<PathBuf>,
@ -42,13 +31,11 @@ impl EpiphanyCoordinatorService {
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<Option<EpiphanyThreadState>> {
load_thread_state(&self.thread_state_store)
read_coordinator_state(&self.thread_state_store)
}
pub fn role_result(
@ -83,196 +70,37 @@ impl EpiphanyCoordinatorService {
update: EpiphanyStateUpdate,
reference_turn_id: Option<String>,
) -> Result<EpiphanyCoordinatorStateApplied> {
let changed_fields = changed_fields(&update);
let state = apply_coordinator_state_update_to_state(
&self.state()?.unwrap_or_default(),
apply_coordinator_state_update(
&self.thread_state_store,
thread_id,
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<String>,
) -> Result<EpiphanyThreadState> {
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)
}
pub(crate) fn changed_fields(update: &EpiphanyStateUpdate) -> Vec<EpiphanyStateUpdatedField> {
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::*;
use crate::EpiphanyCoordinatorAdmissionError;
use crate::completed_role_finding;
#[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(())
}
#[test]
fn completed_finding_admission_refuses_missing_binding() {
let error = completed_role_finding(
None,
&EpiphanyThreadState::default(),
EpiphanyRoleResultRoleId::Modeling,
"modeling-worker",
)
.expect_err("missing binding must not become an acceptable finding");
assert_eq!(
error,
EpiphanyCoordinatorAdmissionError::InvalidRequest(
"epiphany role binding \"modeling-worker\" was not found".to_string()
)
fn facade_contains_no_coordinator_policy() {
let source = include_str!("coordinator_service.rs");
let production = source.split("#[cfg(test)]").next().unwrap_or(source);
assert!(
production.lines().count() < 90,
"coordinator facade regrew into a host brain"
);
for forbidden in [
"epiphany_state_update_validation_errors",
"runtime_worker_launch_request",
"mind_review_role_acceptance",
"build_role_acceptance_bundle",
"serde_json",
"thread/epiphany/",
] {
assert!(
!production.contains(forbidden),
"coordinator facade contains policy/protocol marker {forbidden:?}"
);
}
}
}

View file

@ -0,0 +1,146 @@
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;
#[derive(Debug, Clone, PartialEq)]
pub struct EpiphanyCoordinatorStateApplied {
pub revision: u64,
pub changed_fields: Vec<EpiphanyStateUpdatedField>,
pub state: EpiphanyThreadState,
}
pub fn read_coordinator_state(store: &Path) -> Result<Option<EpiphanyThreadState>> {
load_thread_state(store)
}
pub fn apply_coordinator_state_update(
store: &Path,
thread_id: &str,
update: EpiphanyStateUpdate,
reference_turn_id: Option<String>,
) -> Result<EpiphanyCoordinatorStateApplied> {
let changed_fields = changed_fields(&update);
let state = apply_coordinator_state_update_to_state(
&read_coordinator_state(store)?.unwrap_or_default(),
update,
reference_turn_id,
)?;
write_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<String>,
) -> Result<EpiphanyThreadState> {
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 errors = epiphany_state_update_validation_errors(current_state, &update);
if !errors.is_empty() {
return Err(anyhow!(
"invalid epiphany update patch: {}",
errors.join("; ")
));
}
let mut next_state = current_state.clone();
apply_epiphany_state_update(&mut next_state, update, reference_turn_id);
Ok(next_state)
}
pub(crate) fn changed_fields(update: &EpiphanyStateUpdate) -> Vec<EpiphanyStateUpdatedField> {
let mut fields = Vec::new();
macro_rules! field {
($condition:expr, $field:ident) => {
if $condition {
fields.push(EpiphanyStateUpdatedField::$field);
}
};
}
field!(update.objective.is_some(), Objective);
field!(update.active_subgoal_id.is_some(), ActiveSubgoalId);
field!(update.subgoals.is_some(), Subgoals);
field!(update.invariants.is_some(), Invariants);
field!(update.graphs.is_some(), Graphs);
field!(update.graph_frontier.is_some(), GraphFrontier);
field!(update.graph_checkpoint.is_some(), GraphCheckpoint);
field!(update.scratch.is_some(), Scratch);
field!(
update.investigation_checkpoint.is_some(),
InvestigationCheckpoint
);
field!(update.job_bindings.is_some(), JobBindings);
field!(!update.acceptance_receipts.is_empty(), AcceptanceReceipts);
field!(!update.runtime_links.is_empty(), RuntimeLinks);
field!(!update.observations.is_empty(), Observations);
field!(!update.evidence.is_empty(), Evidence);
field!(update.churn.is_some(), Churn);
field!(update.mode.is_some(), Mode);
field!(update.planning.is_some(), Planning);
fields
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn state_owner_writes_and_refuses_stale_revision() -> Result<()> {
let temp = tempfile::tempdir()?;
let store = temp.path().join("thread-state.msgpack");
let first = apply_coordinator_state_update(
&store,
"session-1",
EpiphanyStateUpdate {
expected_revision: Some(0),
objective: Some("Canonical objective".to_string()),
..Default::default()
},
None,
)?;
assert_eq!(first.revision, 1);
assert!(
apply_coordinator_state_update(
&store,
"session-1",
EpiphanyStateUpdate {
expected_revision: Some(0),
objective: Some("Stale overwrite".to_string()),
..Default::default()
},
None
)
.is_err()
);
assert_eq!(
read_coordinator_state(&store)?
.unwrap()
.objective
.as_deref(),
Some("Canonical objective")
);
Ok(())
}
}

View file

@ -5,6 +5,7 @@ mod continuity_gateway;
mod coordinator_acceptance;
mod coordinator_results;
mod coordinator_service;
mod coordinator_state;
mod cultmesh_integration;
mod distillation;
mod eyes_gateway;
@ -136,8 +137,10 @@ pub use coordinator_results::read_role_result_snapshot;
pub use coordinator_results::read_runtime_reorient_result;
pub use coordinator_results::read_runtime_role_result;
pub use coordinator_service::EpiphanyCoordinatorService;
pub use coordinator_service::EpiphanyCoordinatorStateApplied;
pub use coordinator_service::apply_coordinator_state_update_to_state;
pub use coordinator_state::EpiphanyCoordinatorStateApplied;
pub use coordinator_state::apply_coordinator_state_update;
pub use coordinator_state::apply_coordinator_state_update_to_state;
pub use coordinator_state::read_coordinator_state;
pub use cultcache_rs::CacheBackingStore;
pub use cultcache_rs::CultCache;
pub use cultcache_rs::CultCacheEnvelope;

View file

@ -700,6 +700,16 @@ service fell from 661 to 278 lines; acceptance is 367 lines and results remain
461 lines. The same sixteen coordinator-related core tests and eight bridge
tests pass. Extract state ownership next, leaving a policy-free facade.
The corrective anatomy split is complete. CultCache state load/write, revision
validation, mutation application, and changed-field derivation now live in
`coordinator_state.rs` (146 lines). The production coordinator facade is 81
lines; a source guard forbids policy functions, JSON, and
`thread/epiphany/*` markers and caps its size below 90 production lines.
Acceptance is 389 lines and results are 461 lines. Sixteen coordinator core
tests and all eight bridge tests pass. Resume receipt persistence/proof
enforcement extraction through the acceptance organ; do not add policy back to
the facade.
Bridge identity correction from 2026-06-22: Epiphany owns swarm execution,
repo Body work, branch-local lanes, memory, evidence, and Persona cognition.
Bifrost owns GameCult identity, governed crossings into GitHub/Discord/Reddit

Binary file not shown.

View file

@ -659,4 +659,4 @@ current_status:
- Service lifecycle receipt history is now event-only: `load_epiphany_cultmesh_daemon_service_lifecycle_receipts` filters out the `epiphany-local/daemon-service-lifecycle-receipt/latest` mirror, while `load_latest_epiphany_cultmesh_daemon_service_lifecycle_receipt` remains the latest-state reader. Focused unit test `service_lifecycle_receipt_history_excludes_latest_mirror` proves two per-receipt writes return exactly two history records and latest points at the second. Fresh smoke `verse-query-lifecycle-history-filter-smoke` and live overview/triage `local-20260618-145632-497-efac6f0d` / `local-20260618-145632-321-867947af` prove compact swarm sights still expose service lifecycle attention plus the present elevated runbook artifact without daemon pokes or service mutation. Do not use a broad unscoped cargo test filter for this check on Windows; it fans out across bin harnesses and hit a broken pipe during this pass.
- `epiphany-verse-query seed-compact` is the compact seed receipt for wrappers and read-only rites. The older `seed` command still prints the full local Verse context for explicit debugging, but compact wrapper modes now avoid full `seed`/final `query` readback after the combined overview proof exposed Windows debug stack overflow from full-context serialization pressure.
last_completed_repo_swarm_cut: Huginn live-fire has crossed the first real repo Body from Persona pressure to branch-local Hands commit and Soul/Mind closure, and now has repeatable closure and redacted-public-proof mouths. On `E:\Projects\Huginn` branch `epiphany/huginn/first-awakening`, `tools/epiphany_local_run.ps1 -Mode repo-persona-intake` accepted item `huginn-inspection-readback-livefire`, Weksa/Persona intake remained sealed, and `epiphany-work derive-plan` lowered it to model-authored safe family `repo.status_section` for `README.md` only. `tools/epiphany_local_run.ps1 -Mode repo-swarm-run` advanced four bounded pulses: run-from-plan, adopt-from-plan, execute-from-plan, and close-from-execute. Huginn commit `e9b07c38fceabbdc89ea35c2156326c80c0393a2` updated only `README.md`; closure receipt `.epiphany\work\work-close-huginn-inspection-readback-livefire.json` records status `closed`, Soul verdict `passed`, Mind state commit `repo-work-close-huginn-inspection-readback-livefire-mind-commit`, safe family `repo.status_section`, path scope `README.md`, Bifrost publication gate, and `privateStateExposed=false`. Verification also ran Huginn's TypeScript compiler through concrete Node path: `C:\Program Files\nodejs\node.exe E:\Projects\Huginn\node_modules\typescript\bin\tsc -p tsconfig.json` passed. Native verifier `epiphany-repo-livefire-closure-smoke --workspace E:\Projects\Huginn --item huginn-inspection-readback-livefire --expected-path README.md --expected-family repo.status_section --expected-gate awaiting-publication --expected-blocker bifrost-publication-missing` checks closure receipt, Mind map entry, overview gate/blocker, authority seals, and `git show` changed paths, returning `status=ok`, `soulVerdict=passed`, `publicationGate=Bifrost`, and `privateStateExposed=false`. Wrapper `tools/epiphany_local_run.ps1 -Mode repo-livefire-closure -Workspace E:\Projects\Huginn -RepoWorkItem huginn-inspection-readback-livefire -SkipBuild` exposes the same read-only proof through the local operator mouth; artifact `local-20260621-190156-803-2f85ba15` printed commit, path, gate, blocker, Soul verdict, Mind commit receipt, and `privateStateExposed=False` without push, merge, publication, or target mutation. New wrapper `tools/epiphany_local_run.ps1 -Mode repo-work-public-proof -Workspace E:\Projects\Huginn -RepoWorkItem huginn-inspection-readback-livefire -SkipBuild` exports the redacted proof bundle and repo-local Verse index without publishing; artifact `local-20260621-190645-345-4555b1dc` wrote `.epiphany\public\proof-bundles\repo-work-public-proof-huginn-inspection-readback-livefire.json`, proof id `repo-work-public-proof-huginn-inspection-readback-livefire`, SHA-256 `857545b199f3e37eb06c2e757e5cfc201958e46667bb1f8403fd333a22620f63`, nine artifact rows, zero publication rows, and `privateStateExposed=False`. Gjallar readback `local-20260621-190701-140-b9519ec6` sees the `REPO-WORK-PUBLIC-PROOF` row and action row from Huginn's repo-local Verse with the same SHA-256 while Bifrost publication remains missing. Launcher compact modes are now named compact operator-context modes instead of read-only modes, and `bifrost-public-proof` summaries print item, target public Verse, room, proof SHA-256, review receipts, and credit receipts so publication receipts are auditable without claiming upstream sync.
next_action: Finish the native coordinator anatomy split defined in `notes/native-coordinator-liberation-map.md`. Results and acceptance now have separate organs; `coordinator_service.rs` fell from 1,122 to 278 lines. Extract state ownership and leave a policy-free facade, then resume receipt persistence/proof enforcement extraction and remove `thread/epiphany/*` JSON-RPC from `epiphany-mvp-coordinator`.
next_action: Resume native coordinator liberation through the separated organs defined in `notes/native-coordinator-liberation-map.md`. The production facade is now 81 policy-free lines; state, acceptance, and results have separate modules. Move receipt persistence/proof enforcement into the acceptance organ, extract launch into its own organ, then remove `thread/epiphany/*` JSON-RPC from `epiphany-mvp-coordinator` and demote Codex routes to compatibility wrappers.