diff --git a/epiphany-codex-bridge/src/mutation_service.rs b/epiphany-codex-bridge/src/mutation_service.rs index 429fe05b..961bd5ad 100644 --- a/epiphany-codex-bridge/src/mutation_service.rs +++ b/epiphany-codex-bridge/src/mutation_service.rs @@ -1,7 +1,11 @@ use chrono::SecondsFormat; use chrono::Utc; use codex_app_server_protocol::ThreadEpiphanyReorientFinding; +use codex_app_server_protocol::ThreadEpiphanyReorientDecision; +use codex_app_server_protocol::ThreadEpiphanyReorientSource; +use codex_app_server_protocol::ThreadEpiphanyReorientStateStatus; use codex_app_server_protocol::ThreadEpiphanyJob; +use codex_app_server_protocol::ThreadEpiphanyJobKind; use codex_app_server_protocol::ThreadEpiphanyRoleFinding; use codex_app_server_protocol::ThreadEpiphanyRoleId; use codex_app_server_protocol::ThreadEpiphanyStateUpdatedField; @@ -14,10 +18,16 @@ use codex_core::evaluate_promotion; use codex_protocol::error::CodexErr; use codex_protocol::protocol::EpiphanyJobKind as CoreEpiphanyJobKind; use codex_protocol::protocol::EpiphanyEvidenceRecord; +use codex_protocol::protocol::EpiphanyRetrievalState; use codex_protocol::protocol::EpiphanyThreadState; +use codex_protocol::protocol::TokenUsageInfo as CoreTokenUsageInfo; +use crate::jobs::epiphany_blocked_state_job; +use crate::jobs::map_epiphany_jobs; use crate::jobs::map_interrupted_epiphany_job; use crate::jobs::map_launched_epiphany_job; +use crate::launch::EPIPHANY_REORIENT_LAUNCH_BINDING_ID; +use crate::launch::build_epiphany_reorient_launch_request; use crate::launch::build_epiphany_role_launch_request; use crate::launch::epiphany_role_label; use crate::mutation::build_reorient_acceptance_update; @@ -30,6 +40,10 @@ use crate::mutation::thread_epiphany_patch_has_state_replacements; 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 crate::pressure::map_epiphany_pressure; +use crate::reorient::EpiphanyFreshnessWatcherSnapshot; +use crate::reorient::map_epiphany_freshness; +use crate::reorient::map_epiphany_reorient; use uuid::Uuid; #[derive(Debug, Clone)] @@ -86,6 +100,18 @@ pub struct EpiphanyJobInterruptApplied { pub job: ThreadEpiphanyJob, } +#[derive(Debug, Clone)] +pub struct EpiphanyReorientLaunchApplied { + pub source: ThreadEpiphanyReorientSource, + pub state_status: ThreadEpiphanyReorientStateStatus, + pub state_revision: Option, + pub decision: ThreadEpiphanyReorientDecision, + pub revision: u64, + pub changed_fields: Vec, + pub epiphany_state: EpiphanyThreadState, + pub job: ThreadEpiphanyJob, +} + pub async fn apply_thread_epiphany_update( thread: &CodexThread, expected_revision: Option, @@ -333,6 +359,71 @@ pub async fn interrupt_thread_epiphany_job( }) } +pub async fn launch_thread_epiphany_reorient( + thread: &CodexThread, + thread_id: &str, + expected_revision: Option, + max_runtime_seconds: Option, + state: Option<&EpiphanyThreadState>, + retrieval_override: Option<&EpiphanyRetrievalState>, + watcher_snapshot: Option>, + token_usage_info: Option<&CoreTokenUsageInfo>, +) -> Result { + let (state_revision, retrieval, graph, watcher) = + map_epiphany_freshness(state, retrieval_override, watcher_snapshot); + let pressure = map_epiphany_pressure(token_usage_info); + let (state_status, decision) = + map_epiphany_reorient(state, &pressure, &retrieval, &graph, &watcher); + + let state = state.ok_or_else(|| { + CodexErr::InvalidRequest(format!( + "cannot launch a reorientation worker without authoritative Epiphany state: {}", + decision.note + )) + })?; + let checkpoint = state.investigation_checkpoint.as_ref().ok_or_else(|| { + CodexErr::InvalidRequest(format!( + "cannot launch a reorientation worker without a durable investigation checkpoint: {}", + decision.note + )) + })?; + + let launch_request = build_epiphany_reorient_launch_request( + thread_id, + expected_revision, + max_runtime_seconds, + state, + checkpoint, + &decision, + ); + let changed_fields = epiphany_job_launch_changed_fields(); + let launched = thread.epiphany_launch_job(launch_request).await?; + let epiphany_state = + client_visible_live_thread_epiphany_state(thread, launched.epiphany_state).await; + let job = map_epiphany_jobs(Some(&epiphany_state), None) + .into_iter() + .find(|job| job.id == EPIPHANY_REORIENT_LAUNCH_BINDING_ID) + .unwrap_or_else(|| { + epiphany_blocked_state_job( + EPIPHANY_REORIENT_LAUNCH_BINDING_ID, + ThreadEpiphanyJobKind::Specialist, + "reorient-guided checkpoint regather", + "Launched reorientation worker was not reflected in Epiphany state.", + ) + }); + + Ok(EpiphanyReorientLaunchApplied { + source: ThreadEpiphanyReorientSource::Live, + state_status, + state_revision, + decision, + revision: epiphany_state.revision, + changed_fields, + epiphany_state, + job, + }) +} + fn validate_expected_revision( expected_revision: Option, actual_revision: u64, diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 1ca39e2d..f3036df7 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -636,9 +636,13 @@ Role launch, generic job launch, and job interrupt now route through the bridge service too. `launch_thread_epiphany_role`, `launch_thread_epiphany_job`, and `interrupt_thread_epiphany_job` own launch/interrupt application, changed-field derivation, live-state projection, and job projection. The -remaining thick mutation-route knot is reorient launch: it still composes -freshness, pressure, watcher state, reorientation decision, launch request, and -response shaping inside the vendored route. +remaining thick mutation-route knot was reorient launch, and its policy core +has now moved too: `launch_thread_epiphany_reorient` owns freshness/pressure +mapping, reorientation decision, checkpoint validation, launch request +construction, launch application, live-state projection, and job projection. +The vendored route still performs app-server-native work: thread-id parsing, +thread/read-view loading, watcher registration/snapshotting, JSON-RPC response +shaping, and notification emission. 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 7043c82e..4c1201a0 100644 Binary files a/state/ledgers.msgpack and b/state/ledgers.msgpack differ diff --git a/state/map.yaml b/state/map.yaml index 2110b2f9..e3f136c9 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 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/role-launch/job-launch/job-interrupt 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 reorient-launch orchestration. The processor is about 10,339 lines, `epiphany_mutation_routes.rs` is about 872 lines after the launch/interrupt 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 reorient-launch orchestration out of `codex_message_processor.rs` / `epiphany_mutation_routes.rs` behind native view/launch 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/role-launch/reorient-launch/job-launch/job-interrupt 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, JSON-RPC response shaping, watcher registration/snapshotting, and notification emission. The processor is about 10,339 lines, `epiphany_mutation_routes.rs` is about 815 lines after the reorient-launch 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 collapsing the remaining vendored `epiphany_mutation_routes.rs` JSON-RPC boilerplate where it still duplicates thread parsing/load/respond/notify patterns, 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/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 19910167..7d8c4bd8 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 @@ -2,13 +2,9 @@ use codex_app_server_protocol::*; use codex_core::EpiphanyJobLaunchRequest; use codex_protocol::ThreadId; use codex_protocol::error::CodexErr; -use epiphany_codex_bridge::jobs::epiphany_blocked_state_job; -use epiphany_codex_bridge::jobs::map_epiphany_jobs; 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::epiphany_role_binding_id; use epiphany_codex_bridge::launch::map_core_worker_launch_document; -use epiphany_codex_bridge::mutation::epiphany_job_launch_changed_fields; use epiphany_codex_bridge::mutation::epiphany_state_updated_notification; use epiphany_codex_bridge::mutation_service::EpiphanyThreadPromoteApplied; use epiphany_codex_bridge::mutation_service::apply_thread_epiphany_reorient_accept; @@ -17,12 +13,9 @@ use epiphany_codex_bridge::mutation_service::apply_thread_epiphany_promote; use epiphany_codex_bridge::mutation_service::apply_thread_epiphany_update; use epiphany_codex_bridge::mutation_service::interrupt_thread_epiphany_job; use epiphany_codex_bridge::mutation_service::launch_thread_epiphany_job; +use epiphany_codex_bridge::mutation_service::launch_thread_epiphany_reorient; use epiphany_codex_bridge::mutation_service::launch_thread_epiphany_role; -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::state::client_visible_live_thread_epiphany_state; use super::CodexMessageProcessor; use super::ConnectionRequestId; @@ -263,54 +256,19 @@ impl CodexMessageProcessor { .snapshot(&thread_id) .await; let token_usage_info = loaded_thread.token_usage_info().await; - let (state_revision, retrieval, graph, watcher) = map_epiphany_freshness( - thread.epiphany_state.as_ref(), - Some(&retrieval_override), - Some(epiphany_freshness_watcher_snapshot(&watcher_snapshot)), - ); - let pressure = map_epiphany_pressure(token_usage_info.as_ref()); - let (state_status, decision) = map_epiphany_reorient( - thread.epiphany_state.as_ref(), - &pressure, - &retrieval, - &graph, - &watcher, - ); - - let Some(state) = thread.epiphany_state.as_ref() else { - self.send_invalid_request_error( - request_id, - format!( - "cannot launch a reorientation worker without authoritative Epiphany state: {}", - decision.note - ), - ) - .await; - return; - }; - let Some(checkpoint) = state.investigation_checkpoint.as_ref() else { - self.send_invalid_request_error( - request_id, - format!( - "cannot launch a reorientation worker without a durable investigation checkpoint: {}", - decision.note - ), - ) - .await; - return; - }; - - let launch_request = build_epiphany_reorient_launch_request( + let applied = match launch_thread_epiphany_reorient( + loaded_thread.as_ref(), &thread_id, expected_revision, max_runtime_seconds, - state, - checkpoint, - &decision, - ); - let changed_fields = epiphany_job_launch_changed_fields(); - let launched = match loaded_thread.epiphany_launch_job(launch_request).await { - Ok(launched) => launched, + thread.epiphany_state.as_ref(), + Some(&retrieval_override), + Some(epiphany_freshness_watcher_snapshot(&watcher_snapshot)), + token_usage_info.as_ref(), + ) + .await + { + Ok(applied) => applied, Err(CodexErr::InvalidRequest(message)) => { self.send_invalid_request_error(request_id, message).await; return; @@ -326,37 +284,22 @@ impl CodexMessageProcessor { return; } }; - - let epiphany_state = client_visible_live_thread_epiphany_state( - loaded_thread.as_ref(), - launched.epiphany_state, - ) - .await; - let job = map_epiphany_jobs(Some(&epiphany_state), None) - .into_iter() - .find(|job| job.id == EPIPHANY_REORIENT_LAUNCH_BINDING_ID) - .unwrap_or_else(|| { - epiphany_blocked_state_job( - EPIPHANY_REORIENT_LAUNCH_BINDING_ID, - ThreadEpiphanyJobKind::Specialist, - "reorient-guided checkpoint regather", - "Launched reorientation worker was not reflected in Epiphany state.", - ) - }); + let changed_fields = applied.changed_fields; + let epiphany_state = applied.epiphany_state; self.outgoing .send_response( request_id, ThreadEpiphanyReorientLaunchResponse { thread_id: thread_uuid.to_string(), - source: ThreadEpiphanyReorientSource::Live, - state_status, - state_revision, - decision, - revision: epiphany_state.revision, + source: applied.source, + state_status: applied.state_status, + state_revision: applied.state_revision, + decision: applied.decision, + revision: applied.revision, changed_fields: changed_fields.clone(), epiphany_state: epiphany_state.clone(), - job, + job: applied.job, }, ) .await;