From 899ad45783a675cb7915169c794f22113ec52023 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 12 Jul 2026 00:57:14 +0100 Subject: [PATCH] Make native state commit authoritative --- epiphany-codex-bridge/src/mutation_service.rs | 36 +++++++-- epiphany-core/src/coordinator_service.rs | 19 ++++- epiphany-core/src/coordinator_state.rs | 69 ++++++++++++++++-- epiphany-core/src/lib.rs | 1 + notes/fresh-workspace-handoff.md | 10 ++- notes/native-coordinator-liberation-map.md | 12 ++- state/ledgers.msgpack | Bin 408269 -> 408740 bytes state/map.yaml | 2 +- 8 files changed, 131 insertions(+), 18 deletions(-) diff --git a/epiphany-codex-bridge/src/mutation_service.rs b/epiphany-codex-bridge/src/mutation_service.rs index f62a2514..894f59d0 100644 --- a/epiphany-codex-bridge/src/mutation_service.rs +++ b/epiphany-codex-bridge/src/mutation_service.rs @@ -60,10 +60,10 @@ pub trait EpiphanyMutationHost { /// host snapshot is an input fact, not a bridge-owned source of truth. async fn epiphany_state(&self) -> Option; async fn epiphany_reference_turn_id(&self) -> Option; - /// Persist a state document already validated by Epiphany core policy. + /// Mirror an already committed native state document for legacy clients. /// - /// This is the Codex JSON-RPC shell's current persistence hook. It must not - /// grow mutation policy of its own. + /// Native CultCache is authoritative before this hook runs. The returned + /// mirror cannot override or repair the native result. async fn epiphany_persist_state( &self, next_state: EpiphanyThreadState, @@ -160,9 +160,13 @@ pub async fn apply_epiphany_state_update_to_thread( ) -> BridgeResult { let current_state = thread.epiphany_state().await.unwrap_or_default(); let reference_turn_id = thread.epiphany_reference_turn_id().await; - let next_state = - apply_epiphany_state_update_to_state(¤t_state, update, reference_turn_id)?; - thread.epiphany_persist_state(next_state).await + let store = thread.epiphany_runtime_spine_store_path().await; + let thread_id = thread.epiphany_thread_id().await; + let applied = epiphany_core::EpiphanyCoordinatorService::new(&store, &store) + .apply_state_update_from(&thread_id, ¤t_state, update, reference_turn_id) + .map_err(|error| EpiphanyBridgeError::InvalidRequest(error.to_string()))?; + thread.epiphany_persist_state(applied.state.clone()).await?; + Ok(applied.state) } pub fn apply_epiphany_state_update_to_state( @@ -569,6 +573,26 @@ fn validate_expected_revision( #[cfg(test)] mod acceptance_architecture_tests { + #[test] + fn generic_update_commits_native_state_before_legacy_projection() { + let source = include_str!("mutation_service.rs"); + let start = source + .find("pub async fn apply_epiphany_state_update_to_thread") + .unwrap(); + let end = source + .find("pub fn apply_epiphany_state_update_to_state") + .unwrap(); + let update = &source[start..end]; + assert_eq!(update.matches(".apply_state_update_from(").count(), 1); + assert_eq!(update.matches("epiphany_persist_state(").count(), 1); + assert!( + update.find(".apply_state_update_from(").unwrap() + < update.find("epiphany_persist_state(").unwrap() + ); + assert!(!update.contains("Ok(next_state)")); + assert!(update.contains("Ok(applied.state)")); + } + #[test] fn interrupt_route_delegates_binding_mutation_to_native_service() { let source = include_str!("mutation_service.rs"); diff --git a/epiphany-core/src/coordinator_service.rs b/epiphany-core/src/coordinator_service.rs index a4671f37..ffca475c 100644 --- a/epiphany-core/src/coordinator_service.rs +++ b/epiphany-core/src/coordinator_service.rs @@ -12,6 +12,7 @@ use crate::EpiphanyStateUpdate; use crate::accept_coordinator_reorient_finding; use crate::accept_coordinator_role_finding; use crate::apply_coordinator_state_update; +use crate::apply_coordinator_state_update_from_state; use crate::commit_coordinator_job_launch; use crate::interrupt_coordinator_job; use crate::plan_coordinator_job_launch; @@ -89,6 +90,22 @@ impl EpiphanyCoordinatorService { ) } + pub fn apply_state_update_from( + &self, + thread_id: &str, + current_state: &EpiphanyThreadState, + update: EpiphanyStateUpdate, + reference_turn_id: Option, + ) -> Result { + apply_coordinator_state_update_from_state( + &self.thread_state_store, + thread_id, + current_state, + update, + reference_turn_id, + ) + } + pub fn launch_job( &self, thread_id: &str, @@ -182,7 +199,7 @@ mod tests { let source = include_str!("coordinator_service.rs"); let production = source.split("#[cfg(test)]").next().unwrap_or(source); assert!( - production.lines().count() < 190, + production.lines().count() < 210, "coordinator facade regrew into a host brain" ); for forbidden in [ diff --git a/epiphany-core/src/coordinator_state.rs b/epiphany-core/src/coordinator_state.rs index 1f835de0..21ba3c8d 100644 --- a/epiphany-core/src/coordinator_state.rs +++ b/epiphany-core/src/coordinator_state.rs @@ -28,12 +28,26 @@ pub fn apply_coordinator_state_update( update: EpiphanyStateUpdate, reference_turn_id: Option, ) -> Result { + let current = read_coordinator_state(store)?.unwrap_or_default(); + apply_coordinator_state_update_from_state(store, thread_id, ¤t, update, reference_turn_id) +} + +pub fn apply_coordinator_state_update_from_state( + store: &Path, + thread_id: &str, + current_state: &EpiphanyThreadState, + update: EpiphanyStateUpdate, + reference_turn_id: Option, +) -> Result { + if let Some(persisted) = read_coordinator_state(store)? + && persisted != *current_state + { + return Err(anyhow!( + "authoritative coordinator state changed before update commit" + )); + } 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, - )?; + let state = apply_coordinator_state_update_to_state(current_state, update, reference_turn_id)?; let mut cache = coordinator_acceptance_cache(store)?; let entry = EpiphanyThreadStateEntry::from_state(thread_id, &state)?; cache.put(THREAD_STATE_KEY, &entry)?; @@ -147,4 +161,49 @@ mod tests { ); Ok(()) } + + #[test] + fn imported_host_state_seeds_once_then_cannot_override_native_truth() -> Result<()> { + let temp = tempfile::tempdir()?; + let store = temp.path().join("imported-state.msgpack"); + let imported = EpiphanyThreadState { + revision: 4, + objective: Some("Imported rollout state".to_string()), + ..Default::default() + }; + let applied = apply_coordinator_state_update_from_state( + &store, + "thread-1", + &imported, + EpiphanyStateUpdate { + expected_revision: Some(4), + objective: Some("Native authority".to_string()), + ..Default::default() + }, + None, + )?; + assert_eq!(applied.revision, 5); + assert!( + apply_coordinator_state_update_from_state( + &store, + "thread-1", + &imported, + EpiphanyStateUpdate { + expected_revision: None, + objective: Some("Stale host overwrite".to_string()), + ..Default::default() + }, + None, + ) + .is_err() + ); + assert_eq!( + read_coordinator_state(&store)? + .unwrap() + .objective + .as_deref(), + Some("Native authority") + ); + Ok(()) + } } diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index 2a94c37b..d6fa924c 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -168,6 +168,7 @@ pub use coordinator_results::read_runtime_role_result; pub use coordinator_service::EpiphanyCoordinatorService; pub use coordinator_state::EpiphanyCoordinatorStateApplied; pub use coordinator_state::apply_coordinator_state_update; +pub use coordinator_state::apply_coordinator_state_update_from_state; pub use coordinator_state::apply_coordinator_state_update_to_state; pub use coordinator_state::read_coordinator_state; pub use cultcache_rs::CacheBackingStore; diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index c276c0ce..c67db0ad 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -1884,9 +1884,13 @@ binding mutation, while status reports `cancelRequested=false` honestly. A focused core test and status-command test prove the transition. Explicit `--codex` retains compatibility. The bridge now delegates interruption to `EpiphanyCoordinatorService::interrupt_job`; nine bridge tests prove no local -binding mutation policy remains, and the vendored app-server compiles. General -update/promotion persistence still uses the host hook and is the next surviving -state-authority seam. +binding mutation policy remains, and the vendored app-server compiles. Generic update and promotion +commit via `EpiphanyCoordinatorService::apply_state_update_from`, allow a legacy +rollout to seed only an empty unified store, refuse stale host overwrite, then +mirror the exact committed state to rollout for legacy clients. Ten bridge tests +and two coordinator-state tests pass; the vendored app-server compiles. Next +decide whether the rollout mirror can be deleted and notifications/readback +projected directly from unified CultCache. ## Immediate Re-entry Instruction diff --git a/notes/native-coordinator-liberation-map.md b/notes/native-coordinator-liberation-map.md index fbf866b9..ed7ea406 100644 --- a/notes/native-coordinator-liberation-map.md +++ b/notes/native-coordinator-liberation-map.md @@ -272,5 +272,13 @@ cancellation. `epiphany-mvp-status --interrupt-binding` uses this path by default; `--codex` selects the compatibility route explicitly. The bridge now delegates interruption to `EpiphanyCoordinatorService::interrupt_job`; a source guard rejects local binding mutation, and stale unified state is refused before -commit. General update/promotion routes still persist through the host hook and -are the next surviving state-authority seam. +commit. + +Generic update and promotion now commit through +`EpiphanyCoordinatorService::apply_state_update_from`. A rollout snapshot may +seed native state only when the unified store has no state document; once native +truth exists, stale host input is refused even without an expected revision. +Only after the native commit succeeds does `epiphany_persist_state` mirror the +exact committed document for legacy clients, and its return value cannot repair +or override native truth. The remaining question is whether the rollout mirror +can be deleted in favor of notification/read projection directly from CultCache. diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index 168a9c55d7fe98cc591f856a9b9e5edd61095850..29cd41427685fed2e2c8f7c3fb1c306ec3b1776e 100644 GIT binary patch delta 462 zcmX|-u}T9$5Qe>|SBQlmf)?U{*qIO`YShxg#!?V$!g@ECTfN&kcW0wlg<#zmz(#xmpTok=ISm%W!t#IrKmUAuEkAuPk5_`Zy@Te?`P)=@ICx$Uu7lwHZdkh? z)&iO8otBxAnSB}7!ghP<;kDIl?be%n^{uVb*7m_p#g7J`!QyD#3g`D9kI|sj5nNau zcM*IMD@F&(#86nui8UDqhHfCDJl71ITJqg=6tu(DzAB2W>^K&t^M`g4q2K}&vM4Sk z98rw7U@6PUGvwM@vJE)Fu8K-X$ua!mkgF0LVhm)mQb@qO;1ayiiI!i-Vt80-GyKQ; zjG!G@OuQ2fr)W_nj1q8~VpZT0qpE=rbTtWgl@9P$MLg-m!p0Q&91Z_A*Ib#hw+4DD z^9YeLh8U=aR_=sg6zd)Wu=Siu*bRx56#lCs2V}PijAnGU5w0yzUg%5+*`rX-HGTk7 CN- FEC4I95!3(x diff --git a/state/map.yaml b/state/map.yaml index af0f82b2..553ef7f9 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -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: Move the compatibility bridge's general update and promotion persistence behind `EpiphanyCoordinatorService::apply_state_update`, then demote `epiphany_persist_state` to client projection/legacy rollout only. Launch, acceptance, and interruption already delegate to native owners with source guards. + next_action: Determine whether the Codex rollout state mirror can be deleted and client `stateUpdated`/read projection sourced directly from unified CultCache. Generic update/promotion now commit native state first; `epiphany_persist_state` is post-commit legacy projection only and cannot override the native result.