From 8f9b7ab3b550a5400ef3f122a5cceb26c1391492 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 19 May 2026 10:18:27 +0100 Subject: [PATCH] Move Epiphany thread policy to bridge --- epiphany-codex-bridge/src/mutation_service.rs | 240 +++++++++++++- epiphany-codex-bridge/src/retrieve.rs | 50 ++- epiphany-codex-bridge/src/state.rs | 4 +- notes/epiphany-current-algorithmic-map.md | 38 +-- notes/fresh-workspace-handoff.md | 22 +- state/ledgers.msgpack | Bin 134706 -> 135080 bytes state/map.yaml | 6 +- vendor/codex/codex-rs/Cargo.lock | 1 - .../epiphany_automation.rs | 8 +- .../epiphany_mutation_routes.rs | 3 +- .../epiphany_read_routes.rs | 9 +- vendor/codex/codex-rs/core/Cargo.toml | 1 - .../codex/codex-rs/core/src/codex_thread.rs | 293 +----------------- 13 files changed, 332 insertions(+), 343 deletions(-) diff --git a/epiphany-codex-bridge/src/mutation_service.rs b/epiphany-codex-bridge/src/mutation_service.rs index 450c8814..b4cd01ec 100644 --- a/epiphany-codex-bridge/src/mutation_service.rs +++ b/epiphany-codex-bridge/src/mutation_service.rs @@ -1,5 +1,7 @@ use chrono::SecondsFormat; use chrono::Utc; +use std::path::Path; + use codex_app_server_protocol::ThreadEpiphanyJob; use codex_app_server_protocol::ThreadEpiphanyJobKind; use codex_app_server_protocol::ThreadEpiphanyReorientDecision; @@ -18,9 +20,20 @@ use codex_protocol::protocol::EpiphanyRetrievalState; use codex_protocol::protocol::EpiphanyThreadState; use codex_protocol::protocol::TokenUsageInfo as CoreTokenUsageInfo; use epiphany_core::EpiphanyJobInterruptRequest; +use epiphany_core::EpiphanyJobInterruptResult; use epiphany_core::EpiphanyJobLaunchRequest; +use epiphany_core::EpiphanyJobLaunchResult; use epiphany_core::EpiphanyPromotionInput; +use epiphany_core::EpiphanyStateUpdate; +use epiphany_core::RuntimeSpineHeartbeatJobOptions; +use epiphany_core::RuntimeSpineHeartbeatLaunchPlanOptions; +use epiphany_core::apply_epiphany_state_update; +use epiphany_core::clear_epiphany_job_binding_backend; +use epiphany_core::epiphany_state_update_validation_errors; use epiphany_core::evaluate_promotion; +use epiphany_core::open_runtime_spine_heartbeat_job; +use epiphany_core::plan_runtime_spine_heartbeat_launch; +use epiphany_core::replace_or_append_epiphany_job_binding; use crate::jobs::epiphany_blocked_state_job; use crate::jobs::map_epiphany_jobs; @@ -112,6 +125,161 @@ pub struct EpiphanyReorientLaunchApplied { pub job: ThreadEpiphanyJob, } +pub async fn apply_epiphany_state_update_to_thread( + thread: &CodexThread, + update: EpiphanyStateUpdate, +) -> Result { + if update.is_empty() { + return Err(CodexErr::InvalidRequest( + "epiphany update patch must contain at least one mutation".to_string(), + )); + } + + let mut next_state = thread.epiphany_state().await.unwrap_or_default(); + if let Some(expected_revision) = update.expected_revision + && next_state.revision != expected_revision + { + return Err(CodexErr::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(CodexErr::InvalidRequest(format!( + "invalid epiphany update patch: {}", + validation_errors.join("; ") + ))); + } + + let reference_turn_id = thread.epiphany_reference_turn_id().await; + apply_epiphany_state_update(&mut next_state, update, reference_turn_id); + thread.epiphany_persist_state(next_state).await +} + +pub async fn launch_epiphany_job_on_thread( + thread: &CodexThread, + request: EpiphanyJobLaunchRequest, +) -> Result { + let current_state = thread.epiphany_state().await.unwrap_or_default(); + validate_expected_revision(request.expected_revision, current_state.revision)?; + + let launcher_job_id = format!("epiphany-heartbeat-launch-{}", Uuid::new_v4()); + let backend_job_id = Uuid::new_v4().to_string(); + let launch_plan = plan_runtime_spine_heartbeat_launch( + ¤t_state, + RuntimeSpineHeartbeatLaunchPlanOptions { + binding_id: request.binding_id.clone(), + kind: request.kind, + scope: request.scope.clone(), + owner_role: request.owner_role.clone(), + authority_scope: request.authority_scope.clone(), + linked_subgoal_ids: request.linked_subgoal_ids.clone(), + linked_graph_node_ids: request.linked_graph_node_ids.clone(), + instruction: request.instruction.clone(), + launch_document: request.launch_document.clone(), + output_contract_id: request.output_contract_id.clone(), + max_runtime_seconds: request.max_runtime_seconds, + runtime_job_id: backend_job_id.clone(), + }, + ) + .map_err(|err| CodexErr::InvalidRequest(err.to_string()))?; + let runtime_store = thread.epiphany_runtime_spine_store_path().await; + open_epiphany_runtime_spine_job( + runtime_store.as_path(), + ¤t_state, + &request, + backend_job_id.as_str(), + )?; + let next_job_bindings = replace_or_append_epiphany_job_binding( + current_state.job_bindings.clone(), + launch_plan.binding, + ); + + let validation_errors = epiphany_state_update_validation_errors( + ¤t_state, + &EpiphanyStateUpdate { + job_bindings: Some(next_job_bindings.clone()), + runtime_links: vec![launch_plan.runtime_link.clone()], + ..Default::default() + }, + ); + if !validation_errors.is_empty() { + return Err(CodexErr::InvalidRequest(format!( + "invalid Epiphany job launch patch: {}", + validation_errors.join("; ") + ))); + } + + let epiphany_state = apply_epiphany_state_update_to_thread( + thread, + EpiphanyStateUpdate { + expected_revision: request.expected_revision, + job_bindings: Some(next_job_bindings), + runtime_links: vec![launch_plan.runtime_link], + ..Default::default() + }, + ) + .await?; + + Ok(EpiphanyJobLaunchResult { + epiphany_state, + binding_id: request.binding_id, + launcher_job_id, + backend_job_id, + }) +} + +pub async fn interrupt_epiphany_job_on_thread( + thread: &CodexThread, + request: EpiphanyJobInterruptRequest, +) -> Result { + if request.binding_id.trim().is_empty() { + return Err(CodexErr::InvalidRequest( + "epiphany job interrupt binding_id must be non-empty".to_string(), + )); + } + + let current_state = thread.epiphany_state().await.unwrap_or_default(); + validate_expected_revision(request.expected_revision, current_state.revision)?; + + let Some(binding_index) = current_state + .job_bindings + .iter() + .position(|binding| binding.id == request.binding_id) + else { + return Err(CodexErr::InvalidRequest(format!( + "epiphany job binding {:?} was not found", + request.binding_id + ))); + }; + let interrupted_thread_ids = Vec::new(); + let cancel_requested = false; + + let next_job_bindings = clear_epiphany_job_binding_backend( + current_state.job_bindings.clone(), + binding_index, + "No active heartbeat turn is currently bound; launch explicitly to resume specialist work.", + ); + let epiphany_state = apply_epiphany_state_update_to_thread( + thread, + EpiphanyStateUpdate { + expected_revision: request.expected_revision, + job_bindings: Some(next_job_bindings), + ..Default::default() + }, + ) + .await?; + + Ok(EpiphanyJobInterruptResult { + epiphany_state, + binding_id: request.binding_id, + cancel_requested, + interrupted_thread_ids, + }) +} + pub async fn apply_thread_epiphany_update( thread: &CodexThread, expected_revision: Option, @@ -119,7 +287,7 @@ pub async fn apply_thread_epiphany_update( ) -> Result { let changed_fields = epiphany_update_patch_changed_fields(&patch); let update = state_update_from_thread_patch(expected_revision, patch); - let epiphany_state = thread.epiphany_update_state(update).await?; + let epiphany_state = apply_epiphany_state_update_to_thread(thread, update).await?; let epiphany_state = client_visible_live_thread_epiphany_state(thread, epiphany_state).await; Ok(EpiphanyThreadUpdateApplied { revision: epiphany_state.revision, @@ -158,7 +326,7 @@ pub async fn apply_thread_epiphany_promote( let mut patch = patch; patch.evidence.push(verifier_evidence); let update = state_update_from_thread_patch(expected_revision, patch); - let epiphany_state = thread.epiphany_update_state(update).await?; + let epiphany_state = apply_epiphany_state_update_to_thread(thread, update).await?; let epiphany_state = client_visible_live_thread_epiphany_state(thread, epiphany_state).await; Ok(EpiphanyThreadPromoteApplied::Accepted( EpiphanyThreadUpdateApplied { @@ -200,12 +368,14 @@ pub async fn apply_thread_epiphany_role_accept( 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( + let epiphany_state = apply_epiphany_state_update_to_thread( + thread, + state_update_from_thread_patch( expected_revision, acceptance_update.patch, - )) - .await?; + ), + ) + .await?; let epiphany_state = client_visible_live_thread_epiphany_state(thread, epiphany_state).await; Ok(EpiphanyRoleAcceptApplied { @@ -259,9 +429,8 @@ pub async fn apply_thread_epiphany_reorient_accept( 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 = + apply_epiphany_state_update_to_thread(thread, acceptance_update.state_update).await?; let epiphany_state = client_visible_live_thread_epiphany_state(thread, epiphany_state).await; Ok(EpiphanyReorientAcceptApplied { @@ -312,7 +481,7 @@ pub async fn launch_thread_epiphany_job( missing_projection_reason: &str, ) -> Result { let changed_fields = epiphany_job_launch_changed_fields(); - let launched = thread.epiphany_launch_job(launch_request).await?; + let launched = launch_epiphany_job_on_thread(thread, launch_request).await?; let epiphany_state = client_visible_live_thread_epiphany_state(thread, launched.epiphany_state).await; let job = map_launched_epiphany_job( @@ -338,13 +507,15 @@ pub async fn interrupt_thread_epiphany_job( reason: Option, ) -> Result { let changed_fields = vec![ThreadEpiphanyStateUpdatedField::JobBindings]; - let interrupted = thread - .epiphany_interrupt_job(EpiphanyJobInterruptRequest { + let interrupted = interrupt_epiphany_job_on_thread( + thread, + EpiphanyJobInterruptRequest { expected_revision, binding_id: binding_id.to_string(), reason, - }) - .await?; + }, + ) + .await?; let epiphany_state = client_visible_live_thread_epiphany_state(thread, interrupted.epiphany_state).await; let job = map_interrupted_epiphany_job(&epiphany_state, binding_id); @@ -397,7 +568,7 @@ pub async fn launch_thread_epiphany_reorient( &decision, ); let changed_fields = epiphany_job_launch_changed_fields(); - let launched = thread.epiphany_launch_job(launch_request).await?; + let launched = launch_epiphany_job_on_thread(thread, 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) @@ -424,6 +595,45 @@ pub async fn launch_thread_epiphany_reorient( }) } +fn open_epiphany_runtime_spine_job( + store_path: &Path, + state: &EpiphanyThreadState, + request: &EpiphanyJobLaunchRequest, + backend_job_id: &str, +) -> Result<(), CodexErr> { + let now = Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true); + open_runtime_spine_heartbeat_job( + store_path, + RuntimeSpineHeartbeatJobOptions { + runtime_id: "epiphany-local".to_string(), + display_name: "Epiphany Local".to_string(), + session_id: "epiphany-main".to_string(), + objective: state + .objective + .clone() + .filter(|objective| !objective.trim().is_empty()) + .unwrap_or_else(|| "Epiphany heartbeat activation".to_string()), + coordinator_note: "App-server launch opened this typed runtime session.".to_string(), + job_id: backend_job_id.to_string(), + role: request.owner_role.clone(), + binding_id: request.binding_id.clone(), + authority_scope: request.authority_scope.clone(), + instruction: request.instruction.clone(), + launch_document: request.launch_document.clone(), + output_contract_id: request.output_contract_id.clone(), + created_at: now, + }, + ) + .map_err(|err| { + CodexErr::Fatal(format!( + "failed to open Epiphany runtime spine job {:?} in {}: {err}", + backend_job_id, + store_path.display() + )) + })?; + Ok(()) +} + fn validate_expected_revision( expected_revision: Option, actual_revision: u64, diff --git a/epiphany-codex-bridge/src/retrieve.rs b/epiphany-codex-bridge/src/retrieve.rs index 2c771488..8383cfbd 100644 --- a/epiphany-codex-bridge/src/retrieve.rs +++ b/epiphany-codex-bridge/src/retrieve.rs @@ -7,9 +7,13 @@ use codex_app_server_protocol::ThreadEpiphanyRetrieveShardSummary; use codex_core::CodexThread; use codex_protocol::protocol::EpiphanyRetrievalState; use codex_utils_absolute_path::AbsolutePathBuf; +use epiphany_core::EpiphanyRetrieveQuery; use epiphany_core::EpiphanyRetrieveResponse as CoreEpiphanyRetrieveResponse; use epiphany_core::EpiphanyRetrieveResult as CoreEpiphanyRetrieveResult; use epiphany_core::EpiphanyRetrieveResultKind as CoreEpiphanyRetrieveResultKind; +use epiphany_core::index_workspace; +use epiphany_core::retrieval_state_for_workspace; +use epiphany_core::retrieve_workspace; pub fn map_epiphany_retrieve_response( response: CoreEpiphanyRetrieveResponse, @@ -29,13 +33,55 @@ pub async fn index_thread_epiphany_retrieval( thread: &CodexThread, force_full_rebuild: bool, ) -> anyhow::Result { - let index_summary = thread - .epiphany_index(force_full_rebuild) + let index_summary = index_thread_epiphany_retrieval_state(thread, force_full_rebuild) .await .and_then(map_epiphany_retrieve_index_summary)?; Ok(ThreadEpiphanyIndexResponse { index_summary }) } +pub async fn thread_epiphany_retrieval_state(thread: &CodexThread) -> EpiphanyRetrievalState { + let config = thread.config_snapshot().await; + let workspace_root = config.cwd.to_path_buf(); + let codex_home = thread.codex_home().await; + let fallback_workspace_root = workspace_root.clone(); + let fallback_codex_home = codex_home.clone(); + tokio::task::spawn_blocking(move || { + retrieval_state_for_workspace(&workspace_root, codex_home.as_path()) + }) + .await + .unwrap_or_else(|_| { + retrieval_state_for_workspace(&fallback_workspace_root, fallback_codex_home.as_path()) + }) +} + +pub async fn index_thread_epiphany_retrieval_state( + thread: &CodexThread, + force_full_rebuild: bool, +) -> anyhow::Result { + let config = thread.config_snapshot().await; + let workspace_root = config.cwd.to_path_buf(); + let codex_home = thread.codex_home().await; + tokio::task::spawn_blocking(move || { + index_workspace(&workspace_root, codex_home.as_path(), force_full_rebuild) + }) + .await + .map_err(|err| anyhow::anyhow!("epiphany index worker failed: {err}"))? +} + +pub async fn retrieve_thread_epiphany( + thread: &CodexThread, + query: EpiphanyRetrieveQuery, +) -> anyhow::Result { + let config = thread.config_snapshot().await; + let workspace_root = config.cwd.to_path_buf(); + let codex_home = thread.codex_home().await; + tokio::task::spawn_blocking(move || { + retrieve_workspace(&workspace_root, codex_home.as_path(), query) + }) + .await + .map_err(|err| anyhow::anyhow!("epiphany retrieval worker failed: {err}"))? +} + pub fn map_epiphany_retrieve_index_summary( summary: EpiphanyRetrievalState, ) -> anyhow::Result { diff --git a/epiphany-codex-bridge/src/state.rs b/epiphany-codex-bridge/src/state.rs index b1f4df58..8a81e3fc 100644 --- a/epiphany-codex-bridge/src/state.rs +++ b/epiphany-codex-bridge/src/state.rs @@ -10,6 +10,8 @@ use codex_protocol::protocol::InitialHistory; use epiphany_core::write_thread_state; use tracing::warn; +use crate::retrieve::thread_epiphany_retrieval_state; + pub async fn load_epiphany_state_from_rollout_path( rollout_path: &Path, ) -> std::result::Result, String> { @@ -33,7 +35,7 @@ pub async fn live_thread_epiphany_state(thread: &CodexThread) -> Option B["SessionState.epiphany_state"] B --> C["build_initial_context"] C --> D["EpiphanyStateInstructions wrapper"] - D --> E["epiphany-core render_epiphany_state"] + D --> E["epiphany-state-model render_epiphany_state"] E --> EA["Operating Discipline anti-Jenga section"] EA --> F[" developer fragment"] F --> G["Model/tool turn runs in normal Codex loop"] @@ -130,15 +130,15 @@ flowchart TD AE --> AF{"Accepted?"} AF -->|"No"| AG["Return reasons, no state mutation"] AF -->|"Yes"| Z - R --> T["CodexThread.epiphany_retrieve"] - S --> U["CodexThread.epiphany_index"] - Z --> ZA["CodexThread.epiphany_update_state"] - AJL --> AJLA["CodexThread.epiphany_launch_job"] + R --> T["epiphany-codex-bridge retrieve_thread_epiphany"] + S --> U["epiphany-codex-bridge index_thread_epiphany_retrieval_state"] + Z --> ZA["epiphany-codex-bridge apply_epiphany_state_update_to_thread"] + AJL --> AJLA["epiphany-codex-bridge launch_epiphany_job_on_thread"] QRLQ --> QRLA["Map checkpoint + reorient verdict into fixed reorient-worker launch"] QRLA --> AJLA AJLA --> AJLB["Persist authority-slot jobBinding + runtimeLink"] AJLB --> ZD - AJI --> AJIA["CodexThread.epiphany_interrupt_job"] + AJI --> AJIA["epiphany-codex-bridge interrupt_epiphany_job_on_thread"] AJIA --> AJIB["Interrupt backend worker(s) + clear bound backend from jobBinding"] AJIB --> ZD ZA --> ZB["Apply typed patch and increment revision"] @@ -415,7 +415,7 @@ For `thread/read`, `read_thread_view` loads the persisted thread view and option - if the thread is loaded, use `live_thread_epiphany_state`. - otherwise, read rollout items from disk and reconstruct the latest surviving Epiphany state with `latest_epiphany_state_from_rollout_items`. -`live_thread_epiphany_state` reads `CodexThread.epiphany_state()`. If state exists but has no retrieval summary, it calls `thread.epiphany_retrieval_state().await` and backfills the summary into the returned API object. That backfill is for the view; it is not a durable rollout write. +`live_thread_epiphany_state` reads `CodexThread.epiphany_state()`. If state exists but has no retrieval summary, it calls `epiphany-codex-bridge::thread_epiphany_retrieval_state` and backfills the summary into the returned API object. That backfill is for the view; it is not a durable rollout write. Code refs: @@ -468,10 +468,10 @@ The app-server handler: 3. rejects zero limits. 4. requires the thread to be loaded. 5. clamps limit to Epiphany bounds. -6. calls `CodexThread.epiphany_retrieve`. +6. calls `epiphany-codex-bridge::retrieve_thread_epiphany`. 7. maps core results into app-server protocol DTOs. -`CodexThread.epiphany_retrieve` snapshots the thread config, extracts `cwd` as workspace root, gets `codex_home`, and runs `epiphany_retrieval::retrieve_workspace` in `spawn_blocking`. +`retrieve_thread_epiphany` snapshots the host config, extracts `cwd` as workspace root, gets Codex home from the host seam, and runs `epiphany_core::retrieve_workspace` in `spawn_blocking`. `epiphany-core::retrieve_workspace`: @@ -541,10 +541,10 @@ The app-server handler: 1. parses the thread id. 2. requires the thread to be loaded. -3. calls `CodexThread.epiphany_index(force_full_rebuild)`. +3. calls `epiphany-codex-bridge::index_thread_epiphany_retrieval`. 4. maps the returned core retrieval state into an app-server index summary response. -`CodexThread.epiphany_index` snapshots `cwd`, reads `codex_home`, and runs `epiphany_retrieval::index_workspace` in `spawn_blocking`. +`index_thread_epiphany_retrieval_state` snapshots `cwd`, reads Codex home from the host seam, and runs `epiphany_core::index_workspace` in `spawn_blocking`. `epiphany-core::index_workspace`: @@ -595,7 +595,7 @@ It must stay light. It should measure the catalog, not rewrite the catalog. If t ### Mechanism -`live_thread_epiphany_state` calls `thread.epiphany_retrieval_state().await`. That method runs `retrieval_state_for_workspace`, which: +`live_thread_epiphany_state` calls `epiphany-codex-bridge::thread_epiphany_retrieval_state`. That bridge helper runs `retrieval_state_for_workspace`, which: 1. checks the workspace exists. 2. loads backend config. @@ -653,14 +653,14 @@ The app-server handler: 1. parses the thread id. 2. requires the thread to be loaded. 3. maps the app-server patch DTO into `EpiphanyStateUpdate`. -4. calls `CodexThread.epiphany_update_state`. +4. calls `epiphany-codex-bridge::apply_epiphany_state_update_to_thread`. 5. computes `changedFields` from the accepted patch surface. 6. projects the just-written state through `client_visible_live_thread_epiphany_state`, which reuses the `thread/read` live-state helper and backfills retrieval summary metadata when needed. 7. returns the client-visible `EpiphanyThreadState` plus response-level `revision` and `changedFields`. 8. emits `thread/epiphany/stateUpdated` with `source: "update"`, event-level `revision`, typed `changedFields`, and the same client-visible updated state. 9. reports empty patches and revision mismatches as invalid requests before notification. -`CodexThread.epiphany_update_state`: +`apply_epiphany_state_update_to_thread`: 1. rejects an empty patch. 2. reads the current reference turn id when one exists. @@ -920,7 +920,7 @@ The app-server handler: 4. returns `accepted: false`, reasons, and `epiphanyState: null` when policy rejects. 5. appends verifier evidence to the patch evidence when policy accepts. 6. maps the patch into `EpiphanyStateUpdate`. -7. calls `CodexThread.epiphany_update_state`. +7. calls `epiphany-codex-bridge::apply_epiphany_state_update_to_thread`. 8. projects the just-written state through `client_visible_live_thread_epiphany_state`, matching the `thread/read` live-state view and retrieval-summary backfill. 9. returns the client-visible `EpiphanyThreadState` plus response-level `revision` and `changedFields`. 10. emits `thread/epiphany/stateUpdated` with `source: "promote"`, event-level `revision`, and typed `changedFields` only for the accepted path; `Evidence` is included even if the accepted patch had no patch evidence because verifier evidence was appended to the durable state. @@ -958,7 +958,7 @@ Rejected promotions return reasons and no state. Accepted promotions return the ### Invariant -Promotion is a gate, not independent persistence. It does not write rollout items directly, it does not mutate state on rejection, and rejected promotions emit no state update notification. Accepted promotions still go through `CodexThread.epiphany_update_state`, so the red pen remains one tool, not three tools in a coat. +Promotion is a gate, not independent persistence. It does not write rollout items directly, it does not mutate state on rejection, and rejected promotions emit no state update notification. Accepted promotions still go through `epiphany-codex-bridge::apply_epiphany_state_update_to_thread`, so the red pen remains one tool, not three tools in a coat. ## Flow 13: Scene View Lens Control Flow @@ -1509,7 +1509,7 @@ Current tests cover the landed flows at useful seams: - deterministic map/churn proposal in `epiphany-core`. - verifier-backed promotion policy in `epiphany-core`. - map/churn promotion validation for evidence-backed state replacements in `epiphany-core`. -- typed state-update patch application in `codex-core`. +- typed state-update patch application in `epiphany-codex-bridge` plus host persistence in `codex-core`. - retrieval ranking, fallback, stale manifest detection, and mocked Qdrant/Ollama indexing in `epiphany-core`. - app-server protocol serde for `thread/epiphany/retrieve`, `thread/epiphany/index`, `thread/epiphany/distill`, `thread/epiphany/propose`, `thread/epiphany/promote`, `thread/epiphany/update`, `thread/epiphany/stateUpdated`, and `thread/epiphany/jobsUpdated`. - focused app-server coverage for sealed `thread/epiphany/jobsUpdated` behavior and heartbeat-backed job projection. diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 4020f014..f9edecbf 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -656,21 +656,19 @@ there is one runtime job for the worker, owned by runtime-spine, and the worker runner completes that job. The Codex-core re-export husks for `epiphany_distillation`, `epiphany_promotion`, -`epiphany_proposal`, and `epiphany_retrieval` have also been deleted. -`codex-core` now re-exports those native types/functions directly from -`epiphany-core`, and `CodexThread` calls `epiphany_core::retrieve_workspace` / -`index_workspace` / `retrieval_state_for_workspace` directly. -The `epiphany_rollout` husk is gone too; `codex-core::lib` keeps only the -one host-boundary function that passes Codex's turn-boundary predicate into -`epiphany-core`. +`epiphany_proposal`, and `epiphany_retrieval` have also been deleted. The +`epiphany_rollout` husk is gone too; `codex-core::lib` keeps only the one +host-boundary function that passes Codex's turn-boundary predicate into +`epiphany-core`. `codex-core` no longer depends on `epiphany-core` at all: +`CodexThread` exposes host persistence/path facts, while `epiphany-codex-bridge` +calls native retrieval/indexing and state-update policy. The runtime-spine job-opening mechanism for heartbeat/specialist launches has also been pulled into `epiphany-core` as `open_runtime_spine_heartbeat_job`. -Vendored `codex_core::CodexThread::epiphany_launch_job` still validates, -persists, and updates Codex thread state, but it no longer owns the -initialize-session-open-job sequence. That is a small cut, but a real ownership -move: native runtime lifecycle belongs to the runtime spine, not the Codex -thread wrapper. +Launch/interrupt policy now lives in `epiphany-codex-bridge`; vendored +`CodexThread` only persists the typed state snapshot and exposes the runtime +store path. Native runtime lifecycle belongs to the runtime spine, not the +Codex thread wrapper. That job-opening path now preserves the work order instead of shaving it into a generic job id. `epiphany-core::EpiphanyRuntimeWorkerLaunchRequest` is a diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index e5e099a4c9cdf7db8eb02c42ab26c87b720f3dcd..3b4c2c0830f3f811c7b65dcdf500f74393c5f45c 100644 GIT binary patch delta 327 zcmX|-F-rqM5QW(k8bM;0LYn~*8!wj}Xh^I?>@8AA8lCJ;yp>~j-Q7!am4bz>Hf|$m zX=9-XHut0SA9$KzJMVq(4e$N2{_<46+pMjrx2*@pvYV3KmW+Lttai2SY4f-@TWSw-rq6x;xy#uYXV*kG)tPfdZtf$J&sVFz1f&q=mBu6i` z+5t=6N}6C6%j%JtROeMO@qDhL5|9#FKO*#Sp+}Hmu6SCRJz1L@4@OsEML3beRAE delta 53 zcmZ26pJUS;jtR<4ygxRoPGe-uZr;P#zK4-<`yNK71Rk-5Ek*`LX1WHZx`vh^1{PMv JrdGxVQ2_2$5HbJ& diff --git a/state/map.yaml b/state/map.yaml index 58fca94f..597990a8 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -116,7 +116,7 @@ accepted_design: - Qdrant is the preferred persistent semantic backend; BM25 remains the bootstrap/fallback/control path. - `notes/epiphany-memory-graph-unified-plan.md` applies the mapped-fractal-domain/cache lesson to Epiphany and corrects the organ boundary: repo architecture/dataflow and agent memory are profiles over one `EpiphanyMemoryGraph`, not separate graph engines. The first native skeleton is landed: `epiphany-state-model` owns the public document vocabulary, `epiphany-core::memory_graph` owns stable ids/validation/freshness/context cuts/CultCache persistence, and `epiphany-memory-graph` exposes status/validate/context/smoke without Qdrant. `notes/repo-fractal-dataflow-cache-plan.md` and `notes/agent-memory-fractal-cache-plan.md` are profile plans beneath that substrate. If deleting Qdrant deletes understanding, the design is wrong; the fallback must be slower but still correct typed graph traversal. - `epiphany-state-model` owns the deterministic prompt-state renderer beside the typed `EpiphanyThreadState` document it serializes. `epiphany-core` re-exports that renderer for compatibility and owns rollout replay helpers, retrieval/indexing, distillation, proposal, promotion policy, scene projection, freshness derivation, pressure derivation, job/progress view derivation, planning view derivation, reorientation resume/regather verdict policy, pure CRRC recommendation policy, fixed-lane coordinator decision policy, role-board projection policy, and role-result interpretation/self-persistence review policy where possible. - - Vendored Codex keeps the thin typed host seam: protocol types, thread bridges, app-server protocol, request routing, watcher lifecycle, notifications, and rollout integration. Epiphany projection and coordinator policy should keep moving into `epiphany-core` / `epiphany-codex-bridge` instead of living in `codex_message_processor.rs`. + - Vendored Codex keeps the thin typed host seam: protocol types, thread bridges, app-server protocol, request routing, watcher lifecycle, notifications, rollout integration, and host persistence facts such as current Epiphany state, reference turn id, workspace root, Codex home, and runtime store path. `codex-core` must not import `epiphany-core`; Epiphany update law, retrieval/indexing, and heartbeat launch/interrupt policy belong in `epiphany-codex-bridge` / `epiphany-core`. - The current algorithmic map is the source-grounded description of live control flow. - Compact-Rehydrate-Reorient-Continue is an architecture primitive; automatic runtime coordination is not landed yet. - Context pressure must become an explicit runtime signal for automatic CRRC; inference from transcript vibes, user warnings, or shrinking safe scope is useful only as a temporary human/agent heuristic. @@ -289,7 +289,7 @@ 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, fifty-six processor/foundation cuts, a real physical extraction in `epiphany-codex-bridge`, a root `epiphany-state-model` crate for durable Epiphany state, 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`, native exact retrieval path matching in `epiphany-core`, and the route-facing mutation/view/coordinator projection services in `epiphany-codex-bridge`. `codex-protocol` no longer defines the durable `Epiphany*` state structs; it re-exports the native model for legacy rollout/API compatibility while `epiphany-core` imports the native model directly. `epiphany-core` now has no direct vendored Codex dependency: pressure derivation accepts native `EpiphanyTokenUsageSnapshot`, Codex rollout replay moved to `codex-core::epiphany_rollout`, and exact retrieval search uses Epiphany-owned workspace walking/path scoring instead of `codex-file-search`. The bridge owns Codex-facing Epiphany adapters for scene, jobs, context/planning/graph query, retrieval/indexing projection, 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, watcher invalidation adaptation, full `thread/epiphany/view` response construction, freshness/context/graph-query response construction, role/reorient result response construction, distill/propose patch-response construction, coordinator status/view construction, and acceptance/evidence signal helpers. Vendored app-server no longer retains root Epiphany modules; `codex_message_processor.rs` still contains route dispatch, JSON-RPC response shaping, watcher registration/snapshotting calls, and notification emission, but its root no longer imports the evacuated Epiphany policy/protocol registry or owns the watcher invalidation manager. Codex product surfaces for apps, skills, plugins, marketplace, and external agent config import are cut from the live app-server/protocol path: list routes return empty lists only where compatibility shells still exist, mutation/detail routes report disabled where they survive, `externalAgentConfig/*` routes and import-completed notification are gone, helper/import modules and stale implementation-shape tests were deleted, runtime feature enablement no longer supports `apps` or `plugins`, config writes no longer emit plugin-toggle analytics, plugin/skill cache invalidation on config writes is gone, plugin startup warmups and app-list refreshes were removed, and app-server no longer directly depends on `codex-plugin`, `codex-chatgpt`, or `codex-core-plugins`. `Config::to_mcp_config` now keeps user-declared MCP servers but no longer accepts `PluginsManager`, folds plugin MCP servers into the runtime, enables Codex apps, enables skill MCP dependency install, or advertises plugin capability summaries; `TurnContext::apps_enabled()` now returns false so model turns cannot awaken Codex Apps through ChatGPT auth or feature flags; session startup and per-turn context no longer load skills, turns receive an empty `SkillLoadOutcome`, internal `Op::ListSkills` is gone from `codex-protocol` / `codex-core` / TUI command routing, the Codex skill watcher has been collapsed to a no-op marker with no file watcher, skill-root registration, cache-clear task, or `SkillsUpdateAvailable` session listener, model turns no longer run skill mention collection, skill env-var prompts, skill MCP dependency installation, skill instruction injection, or implicit skill invocation analytics from shell tools, and the turn prompt/router path no longer loads plugin/app capability summaries, injects available-skill/available-plugin/plugin instruction fragments, parses plugin/app mentions, records app/plugin invocation telemetry, or filters MCP tools through Codex app connectors. Skill mutation/list/notification is gone from the app-server edge too: `skills/list`, `skills/config/write`, `skills/changed`, `Op::ListSkills`, `EventMsg::ListSkillsResponse`, `EventMsg::SkillsUpdateAvailable`, the app-server handlers, TUI slash/startup/list/manage-skill surfaces, generated schema entries, core skill-list suite, and fake live-reload/developer-message tests were deleted. Skill mention plumbing is also gone from the live TUI/protocol edge: no `UserInput::Skill` variant, app-server schema branch, TUI skill popup, `skills_all` cache, composer `set_skill_mentions`, skill mention insertion, `skill://` / `SKILL.md` history decoding, or stale skill popup snapshot remains. The `codex-core-skills` crate, core `skills` re-export shim, no-op `skills_watcher`, session `SkillsManager` service, and per-turn `TurnSkillsContext` are deleted; core/protocol no longer keep legacy `` or `` prompt compatibility, memory usage classification, snapshot normalization, or cleanup paths. Remaining product-shaped skill residue is also cut from memory templates, app-server docs/tests/warnings, TUI tooltips/placeholders/warnings/comments, app-server v1 docs, agent-tool schema text, stale `UserInput::Skill` test arms, and obsolete feature flags/schema entries. App-instruction prompt compatibility is cut too: no `APPS_INSTRUCTIONS` protocol constants, no `` snapshot canonicalization, and MCP fixture tests now use neutral `demo_mcp` / `calendar_mcp` names instead of `codex_apps` / `/api/codex/apps` branding. The TUI app connector product path is also deleted: no `/apps` slash command, app-link view, connector AppEvent variants, app connector cache/popup/refresh loop, app mention insertion, `app://` mention codec support, stale app-popup tests, or TUI browser-opening shim remains. The `app/list` route and `app/list/updated` notification are gone from app-server protocol, generated schemas, app-server dispatch, test helpers, and docs; `AppInfo`/app-list metadata schema structs are deleted; the orphaned `codex-connectors` crate and `core::connectors` shim are deleted from the workspace; Codex app analytics no longer tracks `codex_app_mentioned` / `codex_app_used` facts, events, reducer arms, client APIs, or dedupe cache state; `[apps.*]`, `Feature::Apps`, `include_apps_instructions`, app config/read schemas, app managed requirements, app prompt tests, and app file-MCP tests are gone; `Feature::Plugins`, `Feature::RemotePlugin`, `plugin://` structured mentions, plugin instruction tags, and stale plugin popup snapshots are gone too; `[plugins]` / `[marketplaces]`, `PluginConfig`, `MarketplaceConfig`, marketplace edit helpers, stale plugin/external-agent README route claims, and generated schema entries are removed from config; and the bundled `codex-skills` sample-skill crate plus embedded imagegen/openai-docs/plugin-creator/skill-creator/skill-installer payloads are deleted from the workspace. The vendored `vendor/codex/sdk` subtree is deleted as non-spine app-server client/release scaffolding, including stale generated Python SDK route types for removed product surfaces; the root pnpm workspace no longer lists `sdk/typescript`. Live MCP tool approval is named `McpToolApproval`, not `AppToolApproval`, and remains under MCP server config; live structured user-input mentions are MCP-shaped only. `codex_message_processor.rs` is about 1,009 lines after route/lifecycle/projection/resume-helper/config-helper extraction; root `message_processor.rs` is about 1,292 lines after the external-agent/config-product cuts; `epiphany_read_routes.rs` is about 579 lines after the full view and read-response extractions; `epiphany_mutation_routes.rs` is about 694 lines after route-load/notification helper cuts and product-surface starvation; the old vendored `epiphany_state_helpers.rs` rollout-state loader is deleted and its remaining function lives in `epiphany-codex-bridge::state`; 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` owns the native OpenAI model transport path: it exposes `default_codex_home` and `auth_manager`, projects `epiphany-openai-auth-spine` `AuthManager` / `CodexAuth` into typed `EpiphanyOpenAiAdapterStatus`, builds a local serializable OpenAI Responses request body instead of Codex protocol request/item/config types, opens HTTP Responses streams through `codex-client`, parses Responses SSE frames into typed stream events and receipts, and no longer directly or transitively depends on Codex's Responses client, model-provider stack, `codex-protocol`, `codex-api`, `codex-model-provider`, or `codex-model-provider-info`; it intentionally reaches retained vendored `codex-login` only through `epiphany-openai-auth-spine`. Auth identity, credential storage, and ChatGPT token refresh remain owned by the Codex-compatible auth organ; external bearer command auth and agent identity remain retained Codex auth capabilities to expose only if a typed Epiphany surface needs them. `epiphany-openai-runtime` no longer depends directly on `codex-login`; it writes OpenAI status/request/stream-event/receipt records plus runtime sessions/jobs/results/events into `epiphany-core::runtime_spine_cache`, can emit the assistant text artifact for legacy result consumers, is now the default executor for startup-only repo birth specialists, and now has `run-worker` to load a durable `EpiphanyRuntimeWorkerLaunchRequest`, call the typed OpenAI runtime through the spine, persist typed `EpiphanyRuntimeRoleWorkerResult` / `EpiphanyRuntimeReorientWorkerResult` documents, and complete the original heartbeat/specialist runtime job without Codex worker execution; `codex exec` survives only as explicit fallback in repo-birth startup. `epiphany-mvp-coordinator` now invokes `epiphany-openai-runtime run-worker` for launched runtime job ids and no longer creates a second coordinator-owned shadow runtime job/result as a compensator. `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 and now persists `EpiphanyRuntimeWorkerLaunchRequest` CultCache records keyed by runtime job id, with indexed kind/contract fields plus MessagePack-encoded typed launch documents instead of discarding work intent after queue receipt creation; `roleResult` and `reorientResult` now require typed worker result documents; generic job summaries are lifecycle receipts, not reviewable findings; `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, launch request handoff, and rollout/session writeback for the compatibility route. Vendored `codex-core` no longer has `epiphany_distillation`, `epiphany_promotion`, `epiphany_proposal`, or `epiphany_retrieval` husk modules; it re-exports native surfaces from `epiphany-core` directly, and now owns only the real Codex rollout adapter because it is a host seam. `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 request path no longer pulls `codex-api`; `codex-login` remains deliberately sealed behind `epiphany-openai-auth-spine`, and the next spine decision is another Epiphany-in-vendor evacuation surface unless a concrete typed auth-status/runtime need requires exposing external bearer or agent-identity auth. + summary: The Codex starvation pass has five typing receipts, fifty-six processor/foundation cuts, a real physical extraction in `epiphany-codex-bridge`, a root `epiphany-state-model` crate for durable Epiphany state plus prompt-state rendering, 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`, native exact retrieval path matching in `epiphany-core`, and the route-facing mutation/view/coordinator projection services in `epiphany-codex-bridge`. `codex-protocol` no longer defines durable `Epiphany*` state structs; it re-exports the native model and renderer for legacy rollout/API compatibility. `epiphany-core` has no direct vendored Codex dependency, and `codex-core` no longer depends on `epiphany-core`: pressure derives from native `EpiphanyTokenUsageSnapshot`, Codex rollout replay stays in the real Codex rollout adapter, prompt rendering lives in `epiphany-state-model`, and `CodexThread` exposes only host state/path/persistence facts. The bridge owns Codex-facing Epiphany adapters for scene, jobs, context/planning/graph query, retrieval/indexing execution and projection, result projection, runtime-spine result adaptation, launch/prompt doctrine, mutation document mechanics, state 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, watcher invalidation adaptation, full `thread/epiphany/view` response construction, freshness/context/graph-query response construction, role/reorient result response construction, distill/propose patch-response construction, coordinator status/view construction, and acceptance/evidence signal helpers. Vendored app-server no longer retains root Epiphany modules; `codex_message_processor.rs` still contains route dispatch, JSON-RPC response shaping, watcher registration/snapshotting calls, and notification emission. Codex product surfaces for apps, skills, plugins, marketplace, external agent config import, SDK scaffolding, connectors, ChatGPT app discovery, plugin provenance, and skill mention plumbing have been cut from the live path. `codex_thread.rs` is now about 449 lines and owns Codex thread hosting, not Epiphany policy. `epiphany-openai-codex-spine` owns the native OpenAI model transport path while intentionally reaching retained vendored `codex-login` only through `epiphany-openai-auth-spine`; auth identity, credential storage, and ChatGPT token refresh remain owned by the Codex-compatible auth organ. `epiphany-openai-runtime` writes typed OpenAI/runtime documents, loads durable worker launch requests, persists typed role/reorient worker result documents, and completes heartbeat/specialist runtime jobs without Codex worker execution. MCP itself is correctly JSON at its protocol edge; the target remains typed Epiphany intent/result/receipt wrappers around MCP, not replacing MCP JSON. latest_cut: > The first `EpiphanyMemoryGraph` skeleton is implemented. Public typed graph documents live in `epiphany-state-model`; `epiphany-core::memory_graph` @@ -297,4 +297,4 @@ current_status: freshness propagation, summary-versus-child context cuts, and a validated CultCache store entry; the native `epiphany-memory-graph` binary can status/validate/query/smoke the store without Qdrant. - next_action: Continue Codex starvation before outward feature growth. The prompt-state renderer now lives with `epiphany-state-model`, and Codex core reaches it through the protocol re-export; the next clean cut is the remaining `codex-core::CodexThread` Epiphany seam, where retrieval/indexing/state update/job launch still imports `epiphany-core` directly. Classify whether those methods belong in a tiny host persistence trait, `epiphany-codex-bridge`, or an Epiphany-owned runtime route before adding new capability. + next_action: Continue Codex starvation before outward feature growth. The prompt-state renderer now lives with `epiphany-state-model`, and `codex-core` no longer depends on `epiphany-core`: `CodexThread` now exposes only host persistence/path facts while `epiphany-codex-bridge` owns state-update application, retrieval/indexing execution, and heartbeat job launch/interrupt policy. The next clean cut is reducing app-server JSON-RPC Epiphany route exposure toward CultNet contracts, unless another vendored Codex policy dependency appears. diff --git a/vendor/codex/codex-rs/Cargo.lock b/vendor/codex/codex-rs/Cargo.lock index c6c53933..e5f0e505 100644 --- a/vendor/codex/codex-rs/Cargo.lock +++ b/vendor/codex/codex-rs/Cargo.lock @@ -2393,7 +2393,6 @@ dependencies = [ "dirs", "dunce", "env-flags", - "epiphany-core", "eventsource-stream", "futures", "http 1.4.0", diff --git a/vendor/codex/codex-rs/app-server/src/codex_message_processor/epiphany_automation.rs b/vendor/codex/codex-rs/app-server/src/codex_message_processor/epiphany_automation.rs index 85881fea..43aff373 100644 --- a/vendor/codex/codex-rs/app-server/src/codex_message_processor/epiphany_automation.rs +++ b/vendor/codex/codex-rs/app-server/src/codex_message_processor/epiphany_automation.rs @@ -15,9 +15,11 @@ use epiphany_codex_bridge::coordinator::select_epiphany_coordinator_automation; use epiphany_codex_bridge::invalidation::EpiphanyInvalidationManager; use epiphany_codex_bridge::invalidation::epiphany_freshness_watcher_snapshot; use epiphany_codex_bridge::mutation::epiphany_job_launch_changed_fields; +use epiphany_codex_bridge::mutation_service::launch_epiphany_job_on_thread; use epiphany_codex_bridge::pressure::map_epiphany_pressure; use epiphany_codex_bridge::pressure::render_epiphany_pre_compaction_checkpoint_intervention; use epiphany_codex_bridge::pressure::should_run_epiphany_pre_compaction_checkpoint_intervention; +use epiphany_codex_bridge::retrieve::thread_epiphany_retrieval_state; use epiphany_codex_bridge::state::client_visible_live_thread_epiphany_state; use tokio::sync::Mutex; use tracing::warn; @@ -37,7 +39,7 @@ pub(crate) async fn maybe_run_epiphany_coordinator_automation_for_turn_boundary( return; }; - let retrieval_override = thread.epiphany_retrieval_state().await; + let retrieval_override = thread_epiphany_retrieval_state(thread.as_ref()).await; let config_snapshot = thread.config_snapshot().await; epiphany_invalidation_manager .ensure_thread_watch(&thread_id_text, &config_snapshot.cwd) @@ -72,7 +74,9 @@ pub(crate) async fn maybe_run_epiphany_coordinator_automation_for_turn_boundary( let Some(launch_request) = verdict.launch_request else { return; }; - let launched = match thread.epiphany_launch_job(launch_request).await { + let launched = match launch_epiphany_job_on_thread(thread.as_ref(), launch_request) + .await + { Ok(launched) => launched, Err(err) => { warn!( 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 3859441d..920d6382 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 @@ -18,6 +18,7 @@ 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::retrieve::index_thread_epiphany_retrieval; +use epiphany_codex_bridge::retrieve::thread_epiphany_retrieval_state; use epiphany_core::EpiphanyJobLaunchRequest; use std::sync::Arc; @@ -248,7 +249,7 @@ impl CodexMessageProcessor { } }; - let retrieval_override = loaded_thread.epiphany_retrieval_state().await; + let retrieval_override = thread_epiphany_retrieval_state(loaded_thread.as_ref()).await; let config_snapshot = loaded_thread.config_snapshot().await; self.epiphany_invalidation_manager .ensure_thread_watch(&thread_id, &config_snapshot.cwd) diff --git a/vendor/codex/codex-rs/app-server/src/codex_message_processor/epiphany_read_routes.rs b/vendor/codex/codex-rs/app-server/src/codex_message_processor/epiphany_read_routes.rs index bba35e31..10c74221 100644 --- a/vendor/codex/codex-rs/app-server/src/codex_message_processor/epiphany_read_routes.rs +++ b/vendor/codex/codex-rs/app-server/src/codex_message_processor/epiphany_read_routes.rs @@ -4,6 +4,8 @@ use epiphany_codex_bridge::invalidation::epiphany_freshness_watcher_snapshot; use epiphany_codex_bridge::launch::EPIPHANY_REORIENT_LAUNCH_BINDING_ID; use epiphany_codex_bridge::launch::epiphany_role_binding_id; use epiphany_codex_bridge::retrieve::map_epiphany_retrieve_response; +use epiphany_codex_bridge::retrieve::retrieve_thread_epiphany; +use epiphany_codex_bridge::retrieve::thread_epiphany_retrieval_state; use epiphany_codex_bridge::view::EpiphanyFreshnessResponseInput; use epiphany_codex_bridge::view::EpiphanyReorientResultResponseInput; use epiphany_codex_bridge::view::EpiphanyRoleResultResponseInput; @@ -75,7 +77,7 @@ impl CodexMessageProcessor { .is_none() { if let Some(loaded_thread) = loaded_thread.as_ref() { - Some(loaded_thread.epiphany_retrieval_state().await) + Some(thread_epiphany_retrieval_state(loaded_thread.as_ref()).await) } else { None } @@ -238,7 +240,7 @@ impl CodexMessageProcessor { }; let retrieval_override = if let Some(loaded_thread) = loaded_thread.as_ref() { - Some(loaded_thread.epiphany_retrieval_state().await) + Some(thread_epiphany_retrieval_state(loaded_thread.as_ref()).await) } else { None }; @@ -438,8 +440,7 @@ impl CodexMessageProcessor { } }; - let response = match thread - .epiphany_retrieve(query) + let response = match retrieve_thread_epiphany(thread.as_ref(), query) .await .and_then(map_epiphany_retrieve_response) { diff --git a/vendor/codex/codex-rs/core/Cargo.toml b/vendor/codex/codex-rs/core/Cargo.toml index 4e585e6c..dac6db37 100644 --- a/vendor/codex/codex-rs/core/Cargo.toml +++ b/vendor/codex/codex-rs/core/Cargo.toml @@ -70,7 +70,6 @@ codex-utils-string = { workspace = true } codex-utils-stream-parser = { workspace = true } codex-utils-template = { workspace = true } codex-windows-sandbox = { package = "codex-windows-sandbox", path = "../windows-sandbox-rs" } -epiphany-core = { path = "../../../../epiphany-core" } csv = { workspace = true } dirs = { workspace = true } dunce = { workspace = true } diff --git a/vendor/codex/codex-rs/core/src/codex_thread.rs b/vendor/codex/codex-rs/core/src/codex_thread.rs index 61a3c025..5411a113 100644 --- a/vendor/codex/codex-rs/core/src/codex_thread.rs +++ b/vendor/codex/codex-rs/core/src/codex_thread.rs @@ -20,7 +20,6 @@ use codex_protocol::models::ResponseInputItem; use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::ReasoningEffort; use codex_protocol::protocol::AskForApproval; -use codex_protocol::protocol::EpiphanyRetrievalState; use codex_protocol::protocol::EpiphanyStateItem; use codex_protocol::protocol::EpiphanyThreadState; use codex_protocol::protocol::Event; @@ -35,21 +34,6 @@ use codex_protocol::protocol::TokenUsageInfo; use codex_protocol::protocol::W3cTraceContext; use codex_protocol::user_input::UserInput; use codex_utils_absolute_path::AbsolutePathBuf; -use epiphany_core::EpiphanyJobInterruptRequest; -use epiphany_core::EpiphanyJobInterruptResult; -use epiphany_core::EpiphanyJobLaunchRequest; -use epiphany_core::EpiphanyJobLaunchResult; -use epiphany_core::EpiphanyRetrieveQuery; -use epiphany_core::EpiphanyRetrieveResponse; -use epiphany_core::EpiphanyStateUpdate; -use epiphany_core::RuntimeSpineHeartbeatJobOptions; -use epiphany_core::RuntimeSpineHeartbeatLaunchPlanOptions; -use epiphany_core::apply_epiphany_state_update; -use epiphany_core::clear_epiphany_job_binding_backend; -use epiphany_core::epiphany_state_update_validation_errors; -use epiphany_core::open_runtime_spine_heartbeat_job; -use epiphany_core::plan_runtime_spine_heartbeat_launch; -use epiphany_core::replace_or_append_epiphany_job_binding; use rmcp::model::ReadResourceRequestParams; use std::collections::HashMap; use std::path::PathBuf; @@ -57,7 +41,6 @@ use tokio::sync::Mutex; use tokio::sync::watch; use codex_rollout::state_db::StateDbHandle; -use uuid::Uuid; #[derive(Clone, Debug)] pub struct ThreadConfigSnapshot { @@ -339,46 +322,19 @@ impl CodexThread { self.codex.session.epiphany_state().await } - pub async fn epiphany_update_state( - &self, - update: EpiphanyStateUpdate, - ) -> CodexResult { - if update.is_empty() { - return Err(CodexErr::InvalidRequest( - "epiphany update patch must contain at least one mutation".to_string(), - )); - } - - let reference_turn_id = self - .codex + pub async fn epiphany_reference_turn_id(&self) -> Option { + self.codex .session .reference_context_item() .await - .and_then(|item| item.turn_id); - let mut next_state = self - .codex - .session - .epiphany_state() - .await - .unwrap_or_default(); - if let Some(expected_revision) = update.expected_revision - && next_state.revision != expected_revision - { - return Err(CodexErr::InvalidRequest(format!( - "epiphany state revision mismatch: expected {expected_revision}, found {}", - next_state.revision - ))); - } + .and_then(|item| item.turn_id) + } - let validation_errors = epiphany_state_update_validation_errors(&next_state, &update); - if !validation_errors.is_empty() { - return Err(CodexErr::InvalidRequest(format!( - "invalid epiphany update patch: {}", - validation_errors.join("; ") - ))); - } - - apply_epiphany_state_update(&mut next_state, update, reference_turn_id.clone()); + pub async fn epiphany_persist_state( + &self, + next_state: EpiphanyThreadState, + ) -> CodexResult { + let reference_turn_id = self.epiphany_reference_turn_id().await; self.codex .session .set_epiphany_state(Some(next_state.clone())) @@ -394,166 +350,6 @@ impl CodexThread { Ok(next_state) } - pub async fn epiphany_launch_job( - &self, - request: EpiphanyJobLaunchRequest, - ) -> CodexResult { - let current_state = self - .codex - .session - .epiphany_state() - .await - .unwrap_or_default(); - if let Some(expected_revision) = request.expected_revision - && current_state.revision != expected_revision - { - return Err(CodexErr::InvalidRequest(format!( - "epiphany state revision mismatch: expected {expected_revision}, found {}", - current_state.revision - ))); - } - - let launcher_job_id = format!("epiphany-heartbeat-launch-{}", Uuid::new_v4()); - let backend_job_id = Uuid::new_v4().to_string(); - let launch_plan = plan_runtime_spine_heartbeat_launch( - ¤t_state, - RuntimeSpineHeartbeatLaunchPlanOptions { - binding_id: request.binding_id.clone(), - kind: request.kind, - scope: request.scope.clone(), - owner_role: request.owner_role.clone(), - authority_scope: request.authority_scope.clone(), - linked_subgoal_ids: request.linked_subgoal_ids.clone(), - linked_graph_node_ids: request.linked_graph_node_ids.clone(), - instruction: request.instruction.clone(), - launch_document: request.launch_document.clone(), - output_contract_id: request.output_contract_id.clone(), - max_runtime_seconds: request.max_runtime_seconds, - runtime_job_id: backend_job_id.clone(), - }, - ) - .map_err(|err| CodexErr::InvalidRequest(err.to_string()))?; - let runtime_store = self.epiphany_runtime_spine_store_path().await; - open_epiphany_runtime_spine_job( - runtime_store.as_path(), - ¤t_state, - &request, - backend_job_id.as_str(), - )?; - let next_job_bindings = replace_or_append_epiphany_job_binding( - current_state.job_bindings.clone(), - launch_plan.binding, - ); - - let validation_errors = epiphany_state_update_validation_errors( - ¤t_state, - &EpiphanyStateUpdate { - job_bindings: Some(next_job_bindings.clone()), - runtime_links: vec![launch_plan.runtime_link.clone()], - ..Default::default() - }, - ); - if !validation_errors.is_empty() { - return Err(CodexErr::InvalidRequest(format!( - "invalid Epiphany job launch patch: {}", - validation_errors.join("; ") - ))); - } - - let epiphany_state = self - .epiphany_update_state(EpiphanyStateUpdate { - expected_revision: request.expected_revision, - job_bindings: Some(next_job_bindings), - runtime_links: vec![launch_plan.runtime_link], - ..Default::default() - }) - .await?; - - Ok(EpiphanyJobLaunchResult { - epiphany_state, - binding_id: request.binding_id, - launcher_job_id, - backend_job_id, - }) - } - - pub async fn epiphany_interrupt_job( - &self, - request: EpiphanyJobInterruptRequest, - ) -> CodexResult { - if request.binding_id.trim().is_empty() { - return Err(CodexErr::InvalidRequest( - "epiphany job interrupt binding_id must be non-empty".to_string(), - )); - } - - let current_state = self - .codex - .session - .epiphany_state() - .await - .unwrap_or_default(); - if let Some(expected_revision) = request.expected_revision - && current_state.revision != expected_revision - { - return Err(CodexErr::InvalidRequest(format!( - "epiphany state revision mismatch: expected {expected_revision}, found {}", - current_state.revision - ))); - } - - let Some(binding_index) = current_state - .job_bindings - .iter() - .position(|binding| binding.id == request.binding_id) - else { - return Err(CodexErr::InvalidRequest(format!( - "epiphany job binding {:?} was not found", - request.binding_id - ))); - }; - let interrupted_thread_ids = Vec::new(); - let cancel_requested = false; - - let next_job_bindings = clear_epiphany_job_binding_backend( - current_state.job_bindings.clone(), - binding_index, - "No active heartbeat turn is currently bound; launch explicitly to resume specialist work.", - ); - let epiphany_state = self - .epiphany_update_state(EpiphanyStateUpdate { - expected_revision: request.expected_revision, - job_bindings: Some(next_job_bindings), - ..Default::default() - }) - .await?; - - Ok(EpiphanyJobInterruptResult { - epiphany_state, - binding_id: request.binding_id, - cancel_requested, - interrupted_thread_ids, - }) - } - - pub async fn epiphany_retrieval_state(&self) -> EpiphanyRetrievalState { - let config = self.codex.thread_config_snapshot().await; - let workspace_root = config.cwd.to_path_buf(); - let codex_home = self.codex.session.codex_home().await; - let fallback_workspace_root = workspace_root.clone(); - let fallback_codex_home = codex_home.clone(); - tokio::task::spawn_blocking(move || { - epiphany_core::retrieval_state_for_workspace(&workspace_root, codex_home.as_path()) - }) - .await - .unwrap_or_else(|_| { - epiphany_core::retrieval_state_for_workspace( - &fallback_workspace_root, - fallback_codex_home.as_path(), - ) - }) - } - pub async fn epiphany_runtime_spine_store_path(&self) -> PathBuf { self.config_snapshot() .await @@ -563,36 +359,8 @@ impl CodexThread { .to_path_buf() } - pub async fn epiphany_index( - &self, - force_full_rebuild: bool, - ) -> anyhow::Result { - let config = self.codex.thread_config_snapshot().await; - let workspace_root = config.cwd.to_path_buf(); - let codex_home = self.codex.session.codex_home().await; - tokio::task::spawn_blocking(move || { - epiphany_core::index_workspace( - &workspace_root, - codex_home.as_path(), - force_full_rebuild, - ) - }) - .await - .map_err(|err| anyhow::anyhow!("epiphany index worker failed: {err}"))? - } - - pub async fn epiphany_retrieve( - &self, - query: EpiphanyRetrieveQuery, - ) -> anyhow::Result { - let config = self.codex.thread_config_snapshot().await; - let workspace_root = config.cwd.to_path_buf(); - let codex_home = self.codex.session.codex_home().await; - tokio::task::spawn_blocking(move || { - epiphany_core::retrieve_workspace(&workspace_root, codex_home.as_path(), query) - }) - .await - .map_err(|err| anyhow::anyhow!("epiphany retrieval worker failed: {err}"))? + pub async fn codex_home(&self) -> PathBuf { + self.codex.session.codex_home().await.to_path_buf() } pub async fn read_mcp_resource( @@ -668,45 +436,6 @@ impl CodexThread { } } -fn open_epiphany_runtime_spine_job( - store_path: &std::path::Path, - state: &EpiphanyThreadState, - request: &EpiphanyJobLaunchRequest, - backend_job_id: &str, -) -> CodexResult<()> { - let now = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - open_runtime_spine_heartbeat_job( - store_path, - RuntimeSpineHeartbeatJobOptions { - runtime_id: "epiphany-local".to_string(), - display_name: "Epiphany Local".to_string(), - session_id: "epiphany-main".to_string(), - objective: state - .objective - .clone() - .filter(|objective| !objective.trim().is_empty()) - .unwrap_or_else(|| "Epiphany heartbeat activation".to_string()), - coordinator_note: "App-server launch opened this typed runtime session.".to_string(), - job_id: backend_job_id.to_string(), - role: request.owner_role.clone(), - binding_id: request.binding_id.clone(), - authority_scope: request.authority_scope.clone(), - instruction: request.instruction.clone(), - launch_document: request.launch_document.clone(), - output_contract_id: request.output_contract_id.clone(), - created_at: now, - }, - ) - .map_err(|err| { - CodexErr::Fatal(format!( - "failed to open Epiphany runtime spine job {:?} in {}: {err}", - backend_job_id, - store_path.display() - )) - })?; - Ok(()) -} - fn pending_message_input_item(message: &ResponseItem) -> CodexResult { match message { ResponseItem::Message { role, content, .. } => Ok(ResponseInputItem::Message {