diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index 7ab86f64..227a54e1 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -106,6 +106,8 @@ pub use runtime_spine::RUNTIME_JOB_TYPE; pub use runtime_spine::RUNTIME_SESSION_TYPE; pub use runtime_spine::RUNTIME_SPINE_SCHEMA_VERSION; pub use runtime_spine::RuntimeSpineEventOptions; +pub use runtime_spine::RuntimeSpineHeartbeatLaunchPlan; +pub use runtime_spine::RuntimeSpineHeartbeatLaunchPlanOptions; pub use runtime_spine::RuntimeSpineHeartbeatJobOptions; pub use runtime_spine::RuntimeSpineInitOptions; pub use runtime_spine::RuntimeSpineJobOptions; @@ -118,6 +120,7 @@ pub use runtime_spine::create_runtime_session; pub use runtime_spine::ensure_runtime_session; pub use runtime_spine::initialize_runtime_spine; pub use runtime_spine::open_runtime_spine_heartbeat_job; +pub use runtime_spine::plan_runtime_spine_heartbeat_launch; pub use runtime_spine::runtime_hello_frame; pub use runtime_spine::runtime_job_snapshot; pub use runtime_spine::runtime_schema_catalog_response; diff --git a/epiphany-core/src/runtime_spine.rs b/epiphany-core/src/runtime_spine.rs index b9528584..cf795205 100644 --- a/epiphany-core/src/runtime_spine.rs +++ b/epiphany-core/src/runtime_spine.rs @@ -6,6 +6,10 @@ use crate::heartbeat_state::HEARTBEAT_STATE_SCHEMA_VERSION; use crate::heartbeat_state::HEARTBEAT_STATE_TYPE; use crate::state_ledger::STATE_LEDGER_SCHEMA_VERSION; use crate::state_ledger::STATE_LEDGER_STORE_TYPE; +use codex_protocol::protocol::EpiphanyJobBinding; +use codex_protocol::protocol::EpiphanyJobKind; +use codex_protocol::protocol::EpiphanyRuntimeLink; +use codex_protocol::protocol::EpiphanyThreadState; use cultcache_rs::CultCache; use cultcache_rs::DatabaseEntry; use cultcache_rs::SingleFileMessagePackBackingStore; @@ -24,6 +28,7 @@ use epiphany_openai_adapter::EpiphanyOpenAiAdapterStatus; use epiphany_openai_adapter::EpiphanyOpenAiModelReceipt; use epiphany_openai_adapter::EpiphanyOpenAiModelRequest; use epiphany_openai_adapter::EpiphanyOpenAiStreamEvent; +use crate::EpiphanyWorkerLaunchDocument; use serde::Deserialize; use serde::Serialize; use std::collections::BTreeMap; @@ -334,6 +339,28 @@ pub struct RuntimeSpineHeartbeatJobOptions { pub created_at: String, } +#[derive(Clone, Debug, PartialEq)] +pub struct RuntimeSpineHeartbeatLaunchPlanOptions { + pub binding_id: String, + pub kind: EpiphanyJobKind, + pub scope: String, + pub owner_role: String, + pub authority_scope: String, + pub linked_subgoal_ids: Vec, + pub linked_graph_node_ids: Vec, + pub instruction: String, + pub launch_document: EpiphanyWorkerLaunchDocument, + pub output_contract_id: String, + pub max_runtime_seconds: Option, + pub runtime_job_id: String, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct RuntimeSpineHeartbeatLaunchPlan { + pub binding: EpiphanyJobBinding, + pub runtime_link: EpiphanyRuntimeLink, +} + #[derive(Clone, Debug, PartialEq)] pub struct EpiphanyRuntimeJobSnapshot { pub job: EpiphanyRuntimeJob, @@ -510,6 +537,36 @@ pub fn create_runtime_job( Ok(job) } +pub fn plan_runtime_spine_heartbeat_launch( + state: &EpiphanyThreadState, + options: RuntimeSpineHeartbeatLaunchPlanOptions, +) -> Result { + validate_heartbeat_launch_options(state, &options)?; + Ok(RuntimeSpineHeartbeatLaunchPlan { + binding: EpiphanyJobBinding { + id: options.binding_id.clone(), + kind: options.kind, + scope: options.scope.clone(), + owner_role: options.owner_role.clone(), + authority_scope: Some(options.authority_scope.clone()), + linked_subgoal_ids: options.linked_subgoal_ids.clone(), + linked_graph_node_ids: options.linked_graph_node_ids.clone(), + blocking_reason: None, + }, + runtime_link: EpiphanyRuntimeLink { + id: format!("runtime-link-{}-{}", options.binding_id, options.runtime_job_id), + binding_id: options.binding_id, + surface: "jobLaunch".to_string(), + role_id: options.owner_role, + authority_scope: options.authority_scope, + runtime_job_id: options.runtime_job_id, + runtime_result_id: None, + linked_subgoal_ids: options.linked_subgoal_ids, + linked_graph_node_ids: options.linked_graph_node_ids, + }, + }) +} + pub fn open_runtime_spine_heartbeat_job( store_path: impl AsRef, options: RuntimeSpineHeartbeatJobOptions, @@ -1328,6 +1385,70 @@ fn validate_non_empty(value: &str, field: &str) -> Result<()> { Ok(()) } +fn validate_heartbeat_launch_options( + state: &EpiphanyThreadState, + options: &RuntimeSpineHeartbeatLaunchPlanOptions, +) -> Result<()> { + validate_non_empty(&options.binding_id, "epiphany job launch binding_id")?; + if matches!( + options.binding_id.as_str(), + "retrieval-index" | "graph-remap" | "verification" + ) { + return Err(anyhow!( + "epiphany job launch binding_id {:?} is reserved for a derived built-in slot", + options.binding_id + )); + } + if options.kind != EpiphanyJobKind::Specialist { + return Err(anyhow!( + "epiphany job launch currently supports only specialist heartbeat turns" + )); + } + validate_non_empty(&options.scope, "epiphany job launch scope")?; + validate_non_empty(&options.owner_role, "epiphany job launch owner_role")?; + validate_non_empty( + &options.authority_scope, + "epiphany job launch authority_scope", + )?; + validate_non_empty(&options.instruction, "epiphany job launch instruction")?; + validate_non_empty( + options.launch_document.thread_id(), + "epiphany job launch document thread id", + )?; + validate_non_empty( + &options.output_contract_id, + "epiphany job launch output_contract_id", + )?; + if options.output_contract_id != options.launch_document.output_contract_id() { + return Err(anyhow!( + "epiphany job launch output_contract_id must match the typed launch document" + )); + } + if let Some(max_runtime_seconds) = options.max_runtime_seconds + && max_runtime_seconds == 0 + { + return Err(anyhow!( + "epiphany job launch max_runtime_seconds must be >= 1" + )); + } + let existing_binding = state + .job_bindings + .iter() + .find(|binding| binding.id == options.binding_id); + let existing_runtime_link = state.runtime_links.iter().find(|link| { + link.binding_id == options.binding_id && !link.runtime_job_id.trim().is_empty() + }); + if existing_runtime_link.is_some() + && existing_binding.is_none_or(|binding| binding.blocking_reason.is_none()) + { + return Err(anyhow!( + "epiphany job binding {:?} is already bound to an active heartbeat turn; interrupt it before launching a replacement", + options.binding_id + )); + } + Ok(()) +} + fn terminal_status_for_verdict(verdict: &str) -> EpiphanyRuntimeJobStatus { if matches!( verdict, diff --git a/notes/codex-auth-spine-inventory.md b/notes/codex-auth-spine-inventory.md index f841b912..a5a166f4 100644 --- a/notes/codex-auth-spine-inventory.md +++ b/notes/codex-auth-spine-inventory.md @@ -165,6 +165,12 @@ call it while the app-server compatibility route survives, but the initialize-runtime, ensure-session, and create-job sequence is now native runtime-spine machinery rather than Codex thread machinery. +The heartbeat launch plan is native as well: +`epiphany-core::plan_runtime_spine_heartbeat_launch` validates the launch +contract and active runtime-link conflicts, then returns the durable job binding +and runtime link. Vendored `CodexThread` is still a persistence adapter for the +compatibility route, not the owner of that state mechanics. + The bad news is useful: the current spine still drags in `codex-api` and its large transport dependency stack. That is tolerable as a sealed compatibility reliquary, but not as the final shape. The next purification should shrink the diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index c5ff5117..c0ec3ac9 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -596,6 +596,13 @@ 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. +The job-launch plan has now followed it. `epiphany-core` owns +`plan_runtime_spine_heartbeat_launch`, which validates heartbeat launch +requests, reserved binding ids, output contract/document consistency, active +runtime-link conflicts, and projects the durable job binding plus runtime link. +Vendored `CodexThread` now performs only revision checking, persistence +validation, and rollout/session writeback around that native plan. + 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 intent/result/receipt documents internally and normal MCP JSON-RPC externally. diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index 9817128a..c5c39803 100644 Binary files a/state/ledgers.msgpack and b/state/ledgers.msgpack differ diff --git a/state/map.yaml b/state/map.yaml index bf20a591..887d001d 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`, and a native heartbeat runtime job opener in `epiphany-core`. 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, 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,071 lines, and `epiphany_state_helpers.rs` is down to a 19-line rollout-state loader. `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::open_runtime_spine_heartbeat_job` now owns the initialize-runtime/ensure-session/create-job sequence that vendored `CodexThread::epiphany_launch_job` used to perform inline. `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 more launch/mutation ownership out of vendored `codex_core::CodexThread` and `codex_message_processor.rs`: next extract job-launch validation/binding/runtime-link state mechanics into `epiphany-core` or `epiphany-codex-bridge`, 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`, and native heartbeat launch planning/job opening in `epiphany-core`. 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, 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,071 lines, and `epiphany_state_helpers.rs` is down to a 19-line rollout-state loader. `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. 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 the remaining Epiphany state update validation/revisioned write mechanics and mutation route orchestration out of vendored `codex_core::CodexThread` and `codex_message_processor.rs`, 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/core/src/codex_thread.rs b/vendor/codex/codex-rs/core/src/codex_thread.rs index 9dd581ac..49b44314 100644 --- a/vendor/codex/codex-rs/core/src/codex_thread.rs +++ b/vendor/codex/codex-rs/core/src/codex_thread.rs @@ -57,8 +57,10 @@ use codex_protocol::protocol::W3cTraceContext; use codex_protocol::user_input::UserInput; use codex_utils_absolute_path::AbsolutePathBuf; use epiphany_core::EpiphanyWorkerLaunchDocument; +use epiphany_core::RuntimeSpineHeartbeatLaunchPlanOptions; use epiphany_core::RuntimeSpineHeartbeatJobOptions; use epiphany_core::open_runtime_spine_heartbeat_job; +use epiphany_core::plan_runtime_spine_heartbeat_launch; use rmcp::model::ReadResourceRequestParams; use std::collections::HashMap; use std::collections::HashSet; @@ -491,8 +493,6 @@ impl CodexThread { &self, request: EpiphanyJobLaunchRequest, ) -> CodexResult { - validate_epiphany_job_launch_request(&request)?; - let current_state = self .codex .session @@ -507,10 +507,27 @@ impl CodexThread { current_state.revision ))); } - validate_epiphany_job_launch_target(¤t_state, &request)?; 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(), @@ -518,19 +535,16 @@ impl CodexThread { &request, backend_job_id.as_str(), )?; - let replacement_binding = build_epiphany_job_launch_binding(&request); - let replacement_runtime_link = - build_epiphany_runtime_link(&request, backend_job_id.as_str()); let next_job_bindings = replace_or_append_epiphany_job_binding( current_state.job_bindings.clone(), - replacement_binding, + launch_plan.binding, ); let validation_errors = epiphany_state_update_validation_errors( ¤t_state, &EpiphanyStateUpdate { job_bindings: Some(next_job_bindings.clone()), - runtime_links: vec![replacement_runtime_link.clone()], + runtime_links: vec![launch_plan.runtime_link.clone()], ..Default::default() }, ); @@ -545,7 +559,7 @@ impl CodexThread { .epiphany_update_state(EpiphanyStateUpdate { expected_revision: request.expected_revision, job_bindings: Some(next_job_bindings), - runtime_links: vec![replacement_runtime_link], + runtime_links: vec![launch_plan.runtime_link], ..Default::default() }) .await?; @@ -749,124 +763,6 @@ impl CodexThread { } } -fn validate_epiphany_job_launch_request(request: &EpiphanyJobLaunchRequest) -> CodexResult<()> { - if request.binding_id.trim().is_empty() { - return Err(CodexErr::InvalidRequest( - "epiphany job launch binding_id must be non-empty".to_string(), - )); - } - if matches!( - request.binding_id.as_str(), - "retrieval-index" | "graph-remap" | "verification" - ) { - return Err(CodexErr::InvalidRequest(format!( - "epiphany job launch binding_id {:?} is reserved for a derived built-in slot", - request.binding_id - ))); - } - if request.kind != EpiphanyJobKind::Specialist { - return Err(CodexErr::InvalidRequest( - "epiphany job launch currently supports only specialist heartbeat turns".to_string(), - )); - } - if request.scope.trim().is_empty() { - return Err(CodexErr::InvalidRequest( - "epiphany job launch scope must be non-empty".to_string(), - )); - } - if request.owner_role.trim().is_empty() { - return Err(CodexErr::InvalidRequest( - "epiphany job launch owner_role must be non-empty".to_string(), - )); - } - if request.authority_scope.trim().is_empty() { - return Err(CodexErr::InvalidRequest( - "epiphany job launch authority_scope must be non-empty".to_string(), - )); - } - if request.instruction.trim().is_empty() { - return Err(CodexErr::InvalidRequest( - "epiphany job launch instruction must be non-empty".to_string(), - )); - } - if request.launch_document.thread_id().trim().is_empty() { - return Err(CodexErr::InvalidRequest( - "epiphany job launch document must include a thread id".to_string(), - )); - } - if request.output_contract_id.trim().is_empty() { - return Err(CodexErr::InvalidRequest( - "epiphany job launch output_contract_id must be non-empty".to_string(), - )); - } - if request.output_contract_id != request.launch_document.output_contract_id() { - return Err(CodexErr::InvalidRequest( - "epiphany job launch output_contract_id must match the typed launch document" - .to_string(), - )); - } - if let Some(max_runtime_seconds) = request.max_runtime_seconds - && max_runtime_seconds == 0 - { - return Err(CodexErr::InvalidRequest( - "epiphany job launch max_runtime_seconds must be >= 1".to_string(), - )); - } - Ok(()) -} - -fn validate_epiphany_job_launch_target( - state: &EpiphanyThreadState, - request: &EpiphanyJobLaunchRequest, -) -> CodexResult<()> { - let existing_binding = state - .job_bindings - .iter() - .find(|binding| binding.id == request.binding_id); - let existing_runtime_link = state.runtime_links.iter().find(|link| { - link.binding_id == request.binding_id && !link.runtime_job_id.trim().is_empty() - }); - if existing_runtime_link.is_some() - && existing_binding.is_none_or(|binding| binding.blocking_reason.is_none()) - { - return Err(CodexErr::InvalidRequest(format!( - "epiphany job binding {:?} is already bound to an active heartbeat turn; interrupt it before launching a replacement", - request.binding_id - ))); - } - Ok(()) -} - -fn build_epiphany_job_launch_binding(request: &EpiphanyJobLaunchRequest) -> EpiphanyJobBinding { - EpiphanyJobBinding { - id: request.binding_id.clone(), - kind: request.kind, - scope: request.scope.clone(), - owner_role: request.owner_role.clone(), - authority_scope: Some(request.authority_scope.clone()), - linked_subgoal_ids: request.linked_subgoal_ids.clone(), - linked_graph_node_ids: request.linked_graph_node_ids.clone(), - blocking_reason: None, - } -} - -fn build_epiphany_runtime_link( - request: &EpiphanyJobLaunchRequest, - runtime_job_id: &str, -) -> EpiphanyRuntimeLink { - EpiphanyRuntimeLink { - id: format!("runtime-link-{}-{runtime_job_id}", request.binding_id), - binding_id: request.binding_id.clone(), - surface: "jobLaunch".to_string(), - role_id: request.owner_role.clone(), - authority_scope: request.authority_scope.clone(), - runtime_job_id: runtime_job_id.to_string(), - runtime_result_id: None, - linked_subgoal_ids: request.linked_subgoal_ids.clone(), - linked_graph_node_ids: request.linked_graph_node_ids.clone(), - } -} - fn open_epiphany_runtime_spine_job( store_path: &std::path::Path, state: &EpiphanyThreadState,