From e0d7878273774a5a40f30a62d3ebec6a4accab73 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 13 May 2026 06:51:28 +0100 Subject: [PATCH] Move Epiphany accept routes into bridge service --- epiphany-codex-bridge/Cargo.toml | 2 + epiphany-codex-bridge/src/mutation_service.rs | 154 ++++++++++++++ notes/fresh-workspace-handoff.md | 12 +- state/ledgers.msgpack | Bin 84291 -> 84770 bytes state/map.yaml | 4 +- vendor/codex/codex-rs/Cargo.lock | 2 + .../epiphany_mutation_routes.rs | 197 +++--------------- 7 files changed, 195 insertions(+), 176 deletions(-) diff --git a/epiphany-codex-bridge/Cargo.toml b/epiphany-codex-bridge/Cargo.toml index 01316b04..df96686e 100644 --- a/epiphany-codex-bridge/Cargo.toml +++ b/epiphany-codex-bridge/Cargo.toml @@ -11,6 +11,7 @@ path = "src/lib.rs" [dependencies] anyhow = "1" +chrono = { version = "0.4", default-features = false, features = ["clock", "serde"] } codex-app-server-protocol = { path = "../vendor/codex/codex-rs/app-server-protocol" } codex-core = { path = "../vendor/codex/codex-rs/core" } codex-protocol = { path = "../vendor/codex/codex-rs/protocol" } @@ -21,3 +22,4 @@ epiphany-openai-codex-spine = { path = "../epiphany-openai-codex-spine" } serde_json = "1" serde = { version = "1", features = ["derive"] } toml = "0.9" +uuid = { version = "1", features = ["v4"] } diff --git a/epiphany-codex-bridge/src/mutation_service.rs b/epiphany-codex-bridge/src/mutation_service.rs index 4e6d7087..82195501 100644 --- a/epiphany-codex-bridge/src/mutation_service.rs +++ b/epiphany-codex-bridge/src/mutation_service.rs @@ -1,3 +1,8 @@ +use chrono::SecondsFormat; +use chrono::Utc; +use codex_app_server_protocol::ThreadEpiphanyReorientFinding; +use codex_app_server_protocol::ThreadEpiphanyRoleFinding; +use codex_app_server_protocol::ThreadEpiphanyRoleId; use codex_app_server_protocol::ThreadEpiphanyStateUpdatedField; use codex_app_server_protocol::ThreadEpiphanyUpdatePatch; use codex_core::CodexThread; @@ -7,11 +12,17 @@ use codex_protocol::error::CodexErr; use codex_protocol::protocol::EpiphanyEvidenceRecord; use codex_protocol::protocol::EpiphanyThreadState; +use crate::mutation::build_reorient_acceptance_update; +use crate::mutation::build_role_acceptance_update; use crate::mutation::epiphany_promote_changed_fields; use crate::mutation::epiphany_update_patch_changed_fields; use crate::mutation::state_update_from_thread_patch; use crate::mutation::thread_epiphany_patch_has_state_replacements; +use crate::launch::epiphany_role_label; +use crate::runtime_results::load_completed_epiphany_reorient_finding; +use crate::runtime_results::load_completed_epiphany_role_finding; use crate::state::client_visible_live_thread_epiphany_state; +use uuid::Uuid; #[derive(Debug, Clone)] pub struct EpiphanyThreadUpdateApplied { @@ -26,6 +37,29 @@ pub enum EpiphanyThreadPromoteApplied { Accepted(EpiphanyThreadUpdateApplied), } +#[derive(Debug, Clone)] +pub struct EpiphanyRoleAcceptApplied { + pub revision: u64, + pub changed_fields: Vec, + pub epiphany_state: EpiphanyThreadState, + pub accepted_receipt_id: String, + pub accepted_observation_id: String, + pub accepted_evidence_id: String, + pub applied_patch: ThreadEpiphanyUpdatePatch, + pub finding: ThreadEpiphanyRoleFinding, +} + +#[derive(Debug, Clone)] +pub struct EpiphanyReorientAcceptApplied { + pub revision: u64, + pub changed_fields: Vec, + pub epiphany_state: EpiphanyThreadState, + pub accepted_receipt_id: String, + pub accepted_observation_id: String, + pub accepted_evidence_id: String, + pub finding: ThreadEpiphanyReorientFinding, +} + pub async fn apply_thread_epiphany_update( thread: &CodexThread, expected_revision: Option, @@ -82,3 +116,123 @@ pub async fn apply_thread_epiphany_promote( }, )) } + +pub async fn apply_thread_epiphany_role_accept( + thread: &CodexThread, + role_id: ThreadEpiphanyRoleId, + expected_revision: Option, + binding_id: &str, +) -> Result { + let state = thread.epiphany_state().await.ok_or_else(|| { + CodexErr::InvalidRequest( + "cannot accept an Epiphany role finding without authoritative Epiphany state" + .to_string(), + ) + })?; + validate_expected_revision(expected_revision, state.revision)?; + + let finding = load_completed_epiphany_role_finding(thread, &state, role_id, binding_id).await?; + let accepted_prefix = epiphany_role_label(role_id); + let acceptance_update = build_role_acceptance_update( + role_id, + binding_id, + &finding, + format!("ev-{accepted_prefix}-{}", Uuid::new_v4()), + format!("obs-{accepted_prefix}-{}", Uuid::new_v4()), + Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true), + ) + .map_err(CodexErr::InvalidRequest)?; + + let accepted_receipt_id = acceptance_update.accepted_receipt_id.clone(); + let accepted_observation_id = acceptance_update.accepted_observation_id.clone(); + let accepted_evidence_id = acceptance_update.accepted_evidence_id.clone(); + let changed_fields = acceptance_update.changed_fields.clone(); + let applied_patch = acceptance_update.patch.clone(); + let epiphany_state = thread + .epiphany_update_state(state_update_from_thread_patch( + expected_revision, + acceptance_update.patch, + )) + .await?; + let epiphany_state = client_visible_live_thread_epiphany_state(thread, epiphany_state).await; + + Ok(EpiphanyRoleAcceptApplied { + revision: epiphany_state.revision, + changed_fields, + epiphany_state, + accepted_receipt_id, + accepted_observation_id, + accepted_evidence_id, + applied_patch, + finding, + }) +} + +pub async fn apply_thread_epiphany_reorient_accept( + thread: &CodexThread, + expected_revision: Option, + binding_id: &str, + update_scratch: bool, + update_investigation_checkpoint: bool, +) -> Result { + let state = thread.epiphany_state().await.ok_or_else(|| { + CodexErr::InvalidRequest( + "cannot accept a reorientation finding without authoritative Epiphany state" + .to_string(), + ) + })?; + validate_expected_revision(expected_revision, state.revision)?; + if update_investigation_checkpoint && state.investigation_checkpoint.is_none() { + return Err(CodexErr::InvalidRequest( + "cannot update investigation checkpoint because this thread has no durable checkpoint" + .to_string(), + )); + } + + let finding = load_completed_epiphany_reorient_finding(thread, &state, binding_id).await?; + let acceptance_update = build_reorient_acceptance_update( + expected_revision, + binding_id, + &finding, + format!("ev-reorient-{}", Uuid::new_v4()), + format!("obs-reorient-{}", Uuid::new_v4()), + Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true), + update_scratch, + update_investigation_checkpoint, + state.investigation_checkpoint.clone(), + ) + .map_err(CodexErr::InvalidRequest)?; + + let accepted_receipt_id = acceptance_update.accepted_receipt_id.clone(); + let accepted_observation_id = acceptance_update.accepted_observation_id.clone(); + let accepted_evidence_id = acceptance_update.accepted_evidence_id.clone(); + let changed_fields = acceptance_update.changed_fields.clone(); + let epiphany_state = thread + .epiphany_update_state(acceptance_update.state_update) + .await?; + let epiphany_state = client_visible_live_thread_epiphany_state(thread, epiphany_state).await; + + Ok(EpiphanyReorientAcceptApplied { + revision: epiphany_state.revision, + changed_fields, + epiphany_state, + accepted_receipt_id, + accepted_observation_id, + accepted_evidence_id, + finding, + }) +} + +fn validate_expected_revision( + expected_revision: Option, + actual_revision: u64, +) -> Result<(), CodexErr> { + if let Some(expected_revision) = expected_revision + && actual_revision != expected_revision + { + return Err(CodexErr::InvalidRequest(format!( + "epiphany state revision mismatch: expected {expected_revision}, found {actual_revision}" + ))); + } + Ok(()) +} diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 758f00f1..6c9a37a2 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -622,8 +622,16 @@ apply_thread_epiphany_promote}` so the vendored app-server handler no longer owns promotion evaluation, patch-to-update projection, changed-field derivation, or state application for those two write verbs. The handler still owns thread-id parsing, loaded-thread lookup, JSON-RPC response shaping, and -notification emission; role/reorient accept plus launch/interrupt route -orchestration remain to cut. +notification emission. + +Role/reorient accept have followed into the same bridge service. +`apply_thread_epiphany_role_accept` and +`apply_thread_epiphany_reorient_accept` now own authoritative state/revision +checks, typed runtime-spine finding load, acceptance id/timestamp generation, +acceptance update construction, state application, and client-visible state +projection. The vendored mutation route still parses JSON-RPC params, loads the +thread, shapes responses, and emits notifications. Launch/interrupt route +orchestration remains to cut. Also: MCP itself is allowed to be JSON. The target is not "replace MCP JSON"; the target is an Epiphany-owned boundary that speaks typed Epiphany diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index bee7749bb729c257a539c0c2d041474ef54bc5ab..b4a2712c566a2a59db3f90faf368e1caa56e4f68 100644 GIT binary patch delta 335 zcmZ9Iu}T9$6h(PL0wN+75mAc=Dq8F&+0_Kx#==4o>{8jtI{T6gZf4e**`!p^4-kb+ zVI%ng5d;ZrA@~FSfW3uZU?Fazh1j2a&*i>c7Y6;p)$+vt`@?D<;O!!Vrwrh9w{$r$ zdgxdEx?8Qe-bSNZ3u>Od11J}74`i33oA`6VeyzZw&FV0H76hHtgoaCTq)Bx-qcS$y zgvW|UEkYrCD0@Pq&LOHO>T;d4$lAnCw1X-YhIh!-2^WM-E+Q^k7|SqnFl3Ap6ADJi zqsj=&OF9X*NRS#U9rXS{X%giQWKw9OQa0M;{CF`;l9;n`#(uc4G~1Nww;z>E4Qc!8 o!`kGQw~2ASMBC>g%-P{OOxf)nDB1fxn3>n*^T+?!1YZ5{8_imE-v9sr delta 49 zcmZ29jrH&()(Of?o}3$1r!g|#Y2L%QeGemJp}Sba79#^AGhG8yT|?s#15+y#BP$bw FC;*=E4&DF& diff --git a/state/map.yaml b/state/map.yaml index c66c7bed..ef4118aa 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -279,5 +279,5 @@ rejected_paths: reason: making Epiphany cleaner inside Codex still preserves the wrong organ; Codex must be starved down to OpenAI subscription auth/model transport, while Epiphany data and subsystem communication move to typed CultCache/CultNet. current_status: - summary: The Codex starvation pass has five typing receipts, seventeen processor cuts, a real physical extraction in `epiphany-codex-bridge`, a source-grounded Codex auth spine inventory, the native `epiphany-openai-adapter` document boundary, a buildable Codex auth/model wrapper in `epiphany-openai-codex-spine`, the first native runtime caller in `epiphany-openai-runtime`, native heartbeat launch planning/job opening in `epiphany-core`, native state-update contract/validation/application in `epiphany-core`, and the first route-facing mutation service in `epiphany-codex-bridge`. The bridge owns Codex-facing Epiphany adapters for scene, jobs, context/planning/graph query, retrieval, result projection, runtime-spine result adaptation, launch/prompt doctrine, mutation document mechanics, mutation service update/promote application, live-state projection, pressure/pre-compaction rendering, freshness/reorientation projection, CRRC/coordinator/role-board projection, and acceptance/evidence signal helpers. Vendored app-server now retains only `epiphany_invalidation.rs` as a root Epiphany module because watcher lifecycle is still app-server machinery; `codex_message_processor.rs` still contains route dispatch and mutation orchestration. The processor is about 10,339 lines, `epiphany_mutation_routes.rs` is about 1,061 lines after the update/promote service cut, `epiphany_state_helpers.rs` is down to a 19-line rollout-state loader, and `codex_thread.rs` is about 1,425 lines after state-update law moved native. `epiphany-openai-adapter` defines CultCache `DatabaseEntry` request/event/receipt/auth-status documents with no Codex app-server or generic JSON dependency. `epiphany-openai-codex-spine` projects `AuthManager` / `CodexAuth` into typed `EpiphanyOpenAiAdapterStatus`, maps typed `EpiphanyOpenAiModelRequest` into Codex API `ResponsesApiRequest`, resolves auth/provider through keeper Codex crates, opens HTTP Responses streams through `codex-api`, and maps deltas/completion into typed stream events and receipts. `epiphany-openai-runtime` writes OpenAI status/request/stream-event/receipt records plus runtime sessions/jobs/results/events into `epiphany-core::runtime_spine_cache`, and its smoke proves the route without network. `epiphany-core::plan_runtime_spine_heartbeat_launch` validates launch contracts/conflicts and projects durable job bindings/runtime links; `epiphany-core::open_runtime_spine_heartbeat_job` owns the initialize-runtime/ensure-session/create-job sequence; `epiphany-core::EpiphanyStateUpdate`, `epiphany_state_update_validation_errors`, and `apply_epiphany_state_update` own state-update document shape and mutation law while `codex-core` calls them for compatibility. Vendored `CodexThread::epiphany_launch_job` is now mostly revision check, persistence validation, and rollout/session writeback for the compatibility route. `epiphany-runtime-spine` advertises OpenAI adapter status/model-request/stream-event/receipt CultNet schemas and mutation contracts, so the native caller now has a real storage route instead of only JSON-RPC. MCP itself is correctly JSON at its protocol edge; the target is typed Epiphany intent/result/receipt wrappers around MCP, not replacing MCP JSON. The current OpenAI spine still pulls `codex-api` and a large transport dependency stack, so its next cut is dependency starvation after live callers move. - next_action: Continue Codex starvation by moving role/reorient accept plus launch/interrupt route orchestration out of `codex_message_processor.rs` / `epiphany_mutation_routes.rs` behind native service boundaries, leaving Codex as persistence/JSON-RPC compatibility only. Then move live model-turn callers onto `epiphany-openai-runtime` or the same native CultNet contract and shrink the surviving Codex dependency surface to credential refresh, provider/model routing, and the smallest OpenAI Responses call required for Codex subscription compatibility. + summary: The Codex starvation pass has five typing receipts, seventeen processor cuts, a real physical extraction in `epiphany-codex-bridge`, a source-grounded Codex auth spine inventory, the native `epiphany-openai-adapter` document boundary, a buildable Codex auth/model wrapper in `epiphany-openai-codex-spine`, the first native runtime caller in `epiphany-openai-runtime`, native heartbeat launch planning/job opening in `epiphany-core`, native state-update contract/validation/application in `epiphany-core`, and the route-facing mutation service in `epiphany-codex-bridge`. The bridge owns Codex-facing Epiphany adapters for scene, jobs, context/planning/graph query, retrieval, result projection, runtime-spine result adaptation, launch/prompt doctrine, mutation document mechanics, mutation service update/promote/role-accept/reorient-accept application, live-state projection, pressure/pre-compaction rendering, freshness/reorientation projection, CRRC/coordinator/role-board projection, and acceptance/evidence signal helpers. Vendored app-server now retains only `epiphany_invalidation.rs` as a root Epiphany module because watcher lifecycle is still app-server machinery; `codex_message_processor.rs` still contains route dispatch and launch/interrupt mutation orchestration. The processor is about 10,339 lines, `epiphany_mutation_routes.rs` is about 914 lines after the accept service cut, `epiphany_state_helpers.rs` is down to a 19-line rollout-state loader, and `codex_thread.rs` is about 1,425 lines after state-update law moved native. `epiphany-openai-adapter` defines CultCache `DatabaseEntry` request/event/receipt/auth-status documents with no Codex app-server or generic JSON dependency. `epiphany-openai-codex-spine` projects `AuthManager` / `CodexAuth` into typed `EpiphanyOpenAiAdapterStatus`, maps typed `EpiphanyOpenAiModelRequest` into Codex API `ResponsesApiRequest`, resolves auth/provider through keeper Codex crates, opens HTTP Responses streams through `codex-api`, and maps deltas/completion into typed stream events and receipts. `epiphany-openai-runtime` writes OpenAI status/request/stream-event/receipt records plus runtime sessions/jobs/results/events into `epiphany-core::runtime_spine_cache`, and its smoke proves the route without network. `epiphany-core::plan_runtime_spine_heartbeat_launch` validates launch contracts/conflicts and projects durable job bindings/runtime links; `epiphany-core::open_runtime_spine_heartbeat_job` owns the initialize-runtime/ensure-session/create-job sequence; `epiphany-core::EpiphanyStateUpdate`, `epiphany_state_update_validation_errors`, and `apply_epiphany_state_update` own state-update document shape and mutation law while `codex-core` calls them for compatibility. Vendored `CodexThread::epiphany_launch_job` is now mostly revision check, persistence validation, and rollout/session writeback for the compatibility route. `epiphany-runtime-spine` advertises OpenAI adapter status/model-request/stream-event/receipt CultNet schemas and mutation contracts, so the native caller now has a real storage route instead of only JSON-RPC. MCP itself is correctly JSON at its protocol edge; the target is typed Epiphany intent/result/receipt wrappers around MCP, not replacing MCP JSON. The current OpenAI spine still pulls `codex-api` and a large transport dependency stack, so its next cut is dependency starvation after live callers move. + next_action: Continue Codex starvation by moving role/reorient/generic launch plus interrupt route orchestration out of `codex_message_processor.rs` / `epiphany_mutation_routes.rs` behind native service boundaries, leaving Codex as persistence/JSON-RPC compatibility only. Then move live model-turn callers onto `epiphany-openai-runtime` or the same native CultNet contract and shrink the surviving Codex dependency surface to credential refresh, provider/model routing, and the smallest OpenAI Responses call required for Codex subscription compatibility. diff --git a/vendor/codex/codex-rs/Cargo.lock b/vendor/codex/codex-rs/Cargo.lock index afb9b2a2..a5bbf405 100644 --- a/vendor/codex/codex-rs/Cargo.lock +++ b/vendor/codex/codex-rs/Cargo.lock @@ -5222,6 +5222,7 @@ name = "epiphany-codex-bridge" version = "0.1.0" dependencies = [ "anyhow", + "chrono", "codex-app-server-protocol", "codex-core", "codex-protocol", @@ -5232,6 +5233,7 @@ dependencies = [ "serde", "serde_json", "toml 0.9.11+spec-1.1.0", + "uuid", ] [[package]] diff --git a/vendor/codex/codex-rs/app-server/src/codex_message_processor/epiphany_mutation_routes.rs b/vendor/codex/codex-rs/app-server/src/codex_message_processor/epiphany_mutation_routes.rs index 411789ed..fd815264 100644 --- a/vendor/codex/codex-rs/app-server/src/codex_message_processor/epiphany_mutation_routes.rs +++ b/vendor/codex/codex-rs/app-server/src/codex_message_processor/epiphany_mutation_routes.rs @@ -1,5 +1,3 @@ -use chrono::SecondsFormat; -use chrono::Utc; use codex_app_server_protocol::*; use codex_core::EpiphanyJobInterruptRequest; use codex_core::EpiphanyJobLaunchRequest; @@ -14,24 +12,19 @@ use epiphany_codex_bridge::launch::EPIPHANY_REORIENT_LAUNCH_BINDING_ID; use epiphany_codex_bridge::launch::build_epiphany_reorient_launch_request; use epiphany_codex_bridge::launch::build_epiphany_role_launch_request; use epiphany_codex_bridge::launch::epiphany_role_binding_id; -use epiphany_codex_bridge::launch::epiphany_role_label; use epiphany_codex_bridge::launch::map_core_worker_launch_document; -use epiphany_codex_bridge::mutation::build_reorient_acceptance_update; -use epiphany_codex_bridge::mutation::build_role_acceptance_update; use epiphany_codex_bridge::mutation::epiphany_job_launch_changed_fields; use epiphany_codex_bridge::mutation::epiphany_state_updated_notification; -use epiphany_codex_bridge::mutation::state_update_from_thread_patch; use epiphany_codex_bridge::mutation_service::EpiphanyThreadPromoteApplied; +use epiphany_codex_bridge::mutation_service::apply_thread_epiphany_reorient_accept; +use epiphany_codex_bridge::mutation_service::apply_thread_epiphany_role_accept; use epiphany_codex_bridge::mutation_service::apply_thread_epiphany_promote; use epiphany_codex_bridge::mutation_service::apply_thread_epiphany_update; use epiphany_codex_bridge::pressure::map_epiphany_pressure; use epiphany_codex_bridge::reorient::map_epiphany_freshness; use epiphany_codex_bridge::reorient::map_epiphany_reorient; use epiphany_codex_bridge::retrieve::map_epiphany_retrieve_index_summary; -use epiphany_codex_bridge::runtime_results::load_completed_epiphany_reorient_finding; -use epiphany_codex_bridge::runtime_results::load_completed_epiphany_role_finding; use epiphany_codex_bridge::state::client_visible_live_thread_epiphany_state; -use uuid::Uuid; use super::CodexMessageProcessor; use super::ConnectionRequestId; @@ -195,83 +188,15 @@ impl CodexMessageProcessor { return; } }; - let Some(state) = loaded_thread.epiphany_state().await else { - self.send_invalid_request_error( - request_id, - "cannot accept an Epiphany role finding without authoritative Epiphany state" - .to_string(), - ) - .await; - return; - }; - if let Some(expected_revision) = expected_revision - && state.revision != expected_revision - { - self.send_invalid_request_error( - request_id, - format!( - "epiphany state revision mismatch: expected {expected_revision}, found {}", - state.revision - ), - ) - .await; - return; - } - - let finding = match load_completed_epiphany_role_finding( + let applied = match apply_thread_epiphany_role_accept( loaded_thread.as_ref(), - &state, role_id, + expected_revision, &binding_id, ) .await { - Ok(finding) => finding, - Err(CodexErr::InvalidRequest(message)) => { - self.send_invalid_request_error(request_id, message).await; - return; - } - Err(err) => { - self.send_internal_error( - request_id, - format!("failed to accept Epiphany role finding: {err}"), - ) - .await; - return; - } - }; - - let accepted_prefix = epiphany_role_label(role_id); - let accepted_evidence_id = format!("ev-{accepted_prefix}-{}", Uuid::new_v4()); - let accepted_observation_id = format!("obs-{accepted_prefix}-{}", Uuid::new_v4()); - let acceptance_update = match build_role_acceptance_update( - role_id, - &binding_id, - &finding, - accepted_evidence_id, - accepted_observation_id, - Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true), - ) { - Ok(update) => update, - Err(message) => { - self.send_invalid_request_error(request_id, message).await; - return; - } - }; - let accepted_receipt_id = acceptance_update.accepted_receipt_id.clone(); - let accepted_observation_id = acceptance_update.accepted_observation_id.clone(); - let accepted_evidence_id = acceptance_update.accepted_evidence_id.clone(); - let changed_fields = acceptance_update.changed_fields.clone(); - let patch = acceptance_update.patch; - let applied_patch = patch.clone(); - - let epiphany_state = match loaded_thread - .epiphany_update_state(state_update_from_thread_patch(expected_revision, patch)) - .await - { - Ok(state) => { - client_visible_live_thread_epiphany_state(loaded_thread.as_ref(), state).await - } + Ok(applied) => applied, Err(CodexErr::InvalidRequest(message)) => { self.send_invalid_request_error(request_id, message).await; return; @@ -285,21 +210,23 @@ impl CodexMessageProcessor { return; } }; + let changed_fields = applied.changed_fields; + let epiphany_state = applied.epiphany_state; self.outgoing .send_response( request_id, ThreadEpiphanyRoleAcceptResponse { - revision: epiphany_state.revision, + revision: applied.revision, changed_fields: changed_fields.clone(), epiphany_state: epiphany_state.clone(), role_id, binding_id: binding_id.clone(), - accepted_receipt_id, - accepted_observation_id, - accepted_evidence_id, - applied_patch, - finding, + accepted_receipt_id: applied.accepted_receipt_id, + accepted_observation_id: applied.accepted_observation_id, + accepted_evidence_id: applied.accepted_evidence_id, + applied_patch: applied.applied_patch, + finding: applied.finding, }, ) .await; @@ -513,37 +440,16 @@ impl CodexMessageProcessor { return; } }; - let Some(state) = loaded_thread.epiphany_state().await else { - self.send_invalid_request_error( - request_id, - "cannot accept a reorientation finding without authoritative Epiphany state" - .to_string(), - ) - .await; - return; - }; - if let Some(expected_revision) = expected_revision - && state.revision != expected_revision - { - self.send_invalid_request_error( - request_id, - format!( - "epiphany state revision mismatch: expected {expected_revision}, found {}", - state.revision - ), - ) - .await; - return; - } - - let finding = match load_completed_epiphany_reorient_finding( + let applied = match apply_thread_epiphany_reorient_accept( loaded_thread.as_ref(), - &state, + expected_revision, binding_id.as_str(), + update_scratch, + update_investigation_checkpoint, ) .await { - Ok(finding) => finding, + Ok(applied) => applied, Err(CodexErr::InvalidRequest(message)) => { self.send_invalid_request_error(request_id, message).await; return; @@ -557,74 +463,21 @@ impl CodexMessageProcessor { return; } }; - - if update_investigation_checkpoint && state.investigation_checkpoint.is_none() { - self.send_invalid_request_error( - request_id, - "cannot update investigation checkpoint because this thread has no durable checkpoint" - .to_string(), - ) - .await; - return; - } - - let accepted_evidence_id = format!("ev-reorient-{}", Uuid::new_v4()); - let accepted_observation_id = format!("obs-reorient-{}", Uuid::new_v4()); - let acceptance_update = match build_reorient_acceptance_update( - expected_revision, - &binding_id, - &finding, - accepted_evidence_id, - accepted_observation_id, - Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true), - update_scratch, - update_investigation_checkpoint, - state.investigation_checkpoint.clone(), - ) { - Ok(update) => update, - Err(message) => { - self.send_invalid_request_error(request_id, message).await; - return; - } - }; - let accepted_receipt_id = acceptance_update.accepted_receipt_id.clone(); - let accepted_observation_id = acceptance_update.accepted_observation_id.clone(); - let accepted_evidence_id = acceptance_update.accepted_evidence_id.clone(); - let changed_fields = acceptance_update.changed_fields.clone(); - - let epiphany_state = match loaded_thread - .epiphany_update_state(acceptance_update.state_update) - .await - { - Ok(state) => { - client_visible_live_thread_epiphany_state(loaded_thread.as_ref(), state).await - } - Err(CodexErr::InvalidRequest(message)) => { - self.send_invalid_request_error(request_id, message).await; - return; - } - Err(err) => { - self.send_internal_error( - request_id, - format!("failed to apply Epiphany reorientation finding: {err}"), - ) - .await; - return; - } - }; + let changed_fields = applied.changed_fields; + let epiphany_state = applied.epiphany_state; self.outgoing .send_response( request_id, ThreadEpiphanyReorientAcceptResponse { - revision: epiphany_state.revision, + revision: applied.revision, changed_fields: changed_fields.clone(), epiphany_state: epiphany_state.clone(), binding_id: binding_id.clone(), - accepted_receipt_id, - accepted_observation_id, - accepted_evidence_id, - finding, + accepted_receipt_id: applied.accepted_receipt_id, + accepted_observation_id: applied.accepted_observation_id, + accepted_evidence_id: applied.accepted_evidence_id, + finding: applied.finding, }, ) .await;