diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index 47a16974..4781dbbb 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -138,6 +138,8 @@ pub use state_ledger::close_state_branch; pub use state_ledger::load_state_ledger; pub use state_ledger::state_ledger_status; pub use state_update::EpiphanyStateUpdate; +pub use state_update::apply_epiphany_state_update; +pub use state_update::epiphany_state_update_validation_errors; pub use surfaces::EpiphanyAcceptanceBundle; pub use surfaces::EpiphanyContext; pub use surfaces::EpiphanyContextMissing; diff --git a/epiphany-core/src/state_update.rs b/epiphany-core/src/state_update.rs index 2ef4486a..0a7ac639 100644 --- a/epiphany-core/src/state_update.rs +++ b/epiphany-core/src/state_update.rs @@ -1,3 +1,5 @@ +use crate::EpiphanyStateReplacementValidationInput; +use crate::validate_state_replacement_patch; use codex_protocol::protocol::EpiphanyAcceptanceReceipt; use codex_protocol::protocol::EpiphanyChurnState; use codex_protocol::protocol::EpiphanyEvidenceRecord; @@ -10,9 +12,12 @@ use codex_protocol::protocol::EpiphanyJobBinding; use codex_protocol::protocol::EpiphanyModeState; use codex_protocol::protocol::EpiphanyObservation; use codex_protocol::protocol::EpiphanyPlanningState; +use codex_protocol::protocol::EpiphanyPlanningSourceRef; use codex_protocol::protocol::EpiphanyRuntimeLink; use codex_protocol::protocol::EpiphanyScratchPad; use codex_protocol::protocol::EpiphanySubgoal; +use codex_protocol::protocol::EpiphanyThreadState; +use std::collections::HashSet; #[derive(Debug, Clone, Default)] pub struct EpiphanyStateUpdate { @@ -57,3 +62,502 @@ impl EpiphanyStateUpdate { && self.planning.is_none() } } + +pub fn epiphany_state_update_validation_errors( + state: &EpiphanyThreadState, + update: &EpiphanyStateUpdate, +) -> Vec { + let mut errors = Vec::new(); + let mut known_evidence_ids: HashSet<&str> = state + .recent_evidence + .iter() + .filter_map(|evidence| nonempty_id(&evidence.id)) + .collect(); + let existing_evidence_ids = known_evidence_ids.clone(); + let existing_observation_ids: HashSet<&str> = state + .observations + .iter() + .filter_map(|observation| nonempty_id(&observation.id)) + .collect(); + + let mut patch_evidence_ids = HashSet::new(); + for evidence in &update.evidence { + require_nonempty_update(&evidence.id, "patch.evidence.id", &mut errors); + require_nonempty_update(&evidence.kind, "patch.evidence.kind", &mut errors); + require_nonempty_update(&evidence.status, "patch.evidence.status", &mut errors); + require_nonempty_update(&evidence.summary, "patch.evidence.summary", &mut errors); + if !evidence.id.is_empty() && !patch_evidence_ids.insert(evidence.id.as_str()) { + errors.push(format!("duplicate evidence id {:?}", evidence.id)); + } + if existing_evidence_ids.contains(evidence.id.as_str()) { + errors.push(format!( + "evidence id {:?} already exists in Epiphany state", + evidence.id + )); + } + if let Some(id) = nonempty_id(&evidence.id) { + known_evidence_ids.insert(id); + } + } + + let mut patch_observation_ids = HashSet::new(); + for observation in &update.observations { + require_nonempty_update(&observation.id, "patch.observations.id", &mut errors); + require_nonempty_update( + &observation.summary, + "patch.observations.summary", + &mut errors, + ); + require_nonempty_update( + &observation.source_kind, + "patch.observations.source_kind", + &mut errors, + ); + require_nonempty_update( + &observation.status, + "patch.observations.status", + &mut errors, + ); + if !observation.id.is_empty() && !patch_observation_ids.insert(observation.id.as_str()) { + errors.push(format!("duplicate observation id {:?}", observation.id)); + } + if existing_observation_ids.contains(observation.id.as_str()) { + errors.push(format!( + "observation id {:?} already exists in Epiphany state", + observation.id + )); + } + if observation.evidence_ids.is_empty() { + errors.push(format!( + "observation {:?} must cite at least one evidence id", + observation.id + )); + } + for evidence_id in &observation.evidence_ids { + if !known_evidence_ids.contains(evidence_id.as_str()) { + errors.push(format!( + "observation {:?} cites missing evidence id {:?}", + observation.id, evidence_id + )); + } + } + } + + if let Some(checkpoint) = update.investigation_checkpoint.as_ref() { + for evidence_id in &checkpoint.evidence_ids { + if !known_evidence_ids.contains(evidence_id.as_str()) { + errors.push(format!( + "investigation checkpoint cites missing evidence id {:?}", + evidence_id + )); + } + } + } + + if let Some(job_bindings) = update.job_bindings.as_ref() { + errors.extend(validate_epiphany_job_bindings(job_bindings)); + } + if !update.acceptance_receipts.is_empty() { + errors.extend(validate_epiphany_acceptance_receipts( + &state.acceptance_receipts, + &update.acceptance_receipts, + &known_evidence_ids, + )); + } + if !update.runtime_links.is_empty() { + errors.extend(validate_epiphany_runtime_links( + &state.runtime_links, + &update.runtime_links, + )); + } + if let Some(planning) = update.planning.as_ref() { + errors.extend(validate_epiphany_planning_state(planning)); + } + + errors.extend(epiphany_state_replacement_validation_errors(state, update)); + errors +} + +pub fn apply_epiphany_state_update( + state: &mut EpiphanyThreadState, + update: EpiphanyStateUpdate, + reference_turn_id: Option, +) { + if let Some(objective) = update.objective { + state.objective = Some(objective); + } + if let Some(active_subgoal_id) = update.active_subgoal_id { + state.active_subgoal_id = Some(active_subgoal_id); + } + if let Some(subgoals) = update.subgoals { + state.subgoals = subgoals; + } + if let Some(invariants) = update.invariants { + state.invariants = invariants; + } + if let Some(graphs) = update.graphs { + state.graphs = graphs; + } + if let Some(graph_frontier) = update.graph_frontier { + state.graph_frontier = Some(graph_frontier); + } + if let Some(graph_checkpoint) = update.graph_checkpoint { + state.graph_checkpoint = Some(graph_checkpoint); + } + if let Some(scratch) = update.scratch { + state.scratch = Some(scratch); + } + if let Some(checkpoint) = update.investigation_checkpoint { + state.investigation_checkpoint = Some(checkpoint); + } + if let Some(job_bindings) = update.job_bindings { + state.job_bindings = job_bindings; + } + prepend_recent(&mut state.acceptance_receipts, update.acceptance_receipts); + prepend_recent(&mut state.runtime_links, update.runtime_links); + if let Some(churn) = update.churn { + state.churn = Some(churn); + } + if let Some(mode) = update.mode { + state.mode = Some(mode); + } + if let Some(planning) = update.planning { + state.planning = planning; + } + + prepend_recent(&mut state.observations, update.observations); + prepend_recent(&mut state.recent_evidence, update.evidence); + state.revision = state.revision.saturating_add(1); + state.last_updated_turn_id = reference_turn_id; +} + +fn validate_epiphany_runtime_links( + existing: &[EpiphanyRuntimeLink], + links: &[EpiphanyRuntimeLink], +) -> Vec { + let mut errors = Vec::new(); + let mut seen_ids = existing + .iter() + .map(|link| link.id.as_str()) + .collect::>(); + for link in links { + require_nonempty_update(&link.id, "runtime_link.id", &mut errors); + require_nonempty_update(&link.binding_id, "runtime_link.binding_id", &mut errors); + require_nonempty_update(&link.surface, "runtime_link.surface", &mut errors); + require_nonempty_update(&link.role_id, "runtime_link.role_id", &mut errors); + require_nonempty_update( + &link.authority_scope, + "runtime_link.authority_scope", + &mut errors, + ); + require_nonempty_update( + &link.runtime_job_id, + "runtime_link.runtime_job_id", + &mut errors, + ); + if !seen_ids.insert(link.id.as_str()) { + errors.push(format!("runtime link id {:?} is duplicated", link.id)); + } + } + errors +} + +fn validate_epiphany_acceptance_receipts( + existing: &[EpiphanyAcceptanceReceipt], + receipts: &[EpiphanyAcceptanceReceipt], + known_evidence_ids: &HashSet<&str>, +) -> Vec { + let mut errors = Vec::new(); + let mut seen_ids = existing + .iter() + .map(|receipt| receipt.id.as_str()) + .collect::>(); + let mut seen_result_ids = existing + .iter() + .map(|receipt| receipt.result_id.as_str()) + .collect::>(); + + for receipt in receipts { + require_nonempty_update(&receipt.id, "acceptance_receipt.id", &mut errors); + require_nonempty_update( + &receipt.result_id, + "acceptance_receipt.result_id", + &mut errors, + ); + require_nonempty_update(&receipt.job_id, "acceptance_receipt.job_id", &mut errors); + require_nonempty_update( + &receipt.binding_id, + "acceptance_receipt.binding_id", + &mut errors, + ); + require_nonempty_update(&receipt.surface, "acceptance_receipt.surface", &mut errors); + require_nonempty_update(&receipt.role_id, "acceptance_receipt.role_id", &mut errors); + require_nonempty_update(&receipt.status, "acceptance_receipt.status", &mut errors); + require_nonempty_update( + &receipt.accepted_at, + "acceptance_receipt.accepted_at", + &mut errors, + ); + if !seen_ids.insert(receipt.id.as_str()) { + errors.push(format!( + "acceptance receipt id {:?} is duplicated", + receipt.id + )); + } + if !seen_result_ids.insert(receipt.result_id.as_str()) { + errors.push(format!( + "runtime result {:?} already has an acceptance receipt", + receipt.result_id + )); + } + if let Some(evidence_id) = receipt.accepted_evidence_id.as_deref() + && !known_evidence_ids.contains(evidence_id) + { + errors.push(format!( + "acceptance receipt {:?} cites missing evidence id {:?}", + receipt.id, evidence_id + )); + } + } + + errors +} + +fn validate_epiphany_job_bindings(job_bindings: &[EpiphanyJobBinding]) -> Vec { + let mut errors = Vec::new(); + let mut seen_ids = HashSet::<&str>::new(); + + for binding in job_bindings { + require_nonempty_update(&binding.id, "job_binding.id", &mut errors); + require_nonempty_update(&binding.scope, "job_binding.scope", &mut errors); + require_nonempty_update(&binding.owner_role, "job_binding.owner_role", &mut errors); + if let Some(authority_scope) = binding.authority_scope.as_deref() { + require_nonempty_update(authority_scope, "job_binding.authority_scope", &mut errors); + } + if let Some(blocking_reason) = binding.blocking_reason.as_deref() { + require_nonempty_update(blocking_reason, "job_binding.blocking_reason", &mut errors); + } + if !binding.id.is_empty() && !seen_ids.insert(binding.id.as_str()) { + errors.push(format!("duplicate job binding id {:?}", binding.id)); + } + } + + errors +} + +fn validate_epiphany_planning_state(planning: &EpiphanyPlanningState) -> Vec { + let mut errors = Vec::new(); + let mut capture_ids = HashSet::<&str>::new(); + for capture in &planning.captures { + require_nonempty_update(&capture.id, "planning.captures.id", &mut errors); + require_nonempty_update(&capture.title, "planning.captures.title", &mut errors); + require_nonempty_update( + &capture.confidence, + "planning.captures.confidence", + &mut errors, + ); + require_nonempty_update(&capture.status, "planning.captures.status", &mut errors); + validate_epiphany_planning_source_ref( + &capture.source, + "planning.captures.source", + &mut errors, + ); + if !capture.id.is_empty() && !capture_ids.insert(capture.id.as_str()) { + errors.push(format!("duplicate planning capture id {:?}", capture.id)); + } + } + + let mut backlog_ids = HashSet::<&str>::new(); + for item in &planning.backlog_items { + require_nonempty_update(&item.id, "planning.backlog_items.id", &mut errors); + require_nonempty_update(&item.title, "planning.backlog_items.title", &mut errors); + require_nonempty_update(&item.kind, "planning.backlog_items.kind", &mut errors); + require_nonempty_update(&item.summary, "planning.backlog_items.summary", &mut errors); + require_nonempty_update(&item.status, "planning.backlog_items.status", &mut errors); + require_nonempty_update(&item.horizon, "planning.backlog_items.horizon", &mut errors); + require_nonempty_update( + &item.priority.value, + "planning.backlog_items.priority.value", + &mut errors, + ); + require_nonempty_update( + &item.priority.rationale, + "planning.backlog_items.priority.rationale", + &mut errors, + ); + require_nonempty_update( + &item.confidence, + "planning.backlog_items.confidence", + &mut errors, + ); + require_nonempty_update( + &item.product_area, + "planning.backlog_items.product_area", + &mut errors, + ); + for (index, source_ref) in item.source_refs.iter().enumerate() { + validate_epiphany_planning_source_ref( + source_ref, + &format!("planning.backlog_items.source_refs[{index}]"), + &mut errors, + ); + } + if !item.id.is_empty() && !backlog_ids.insert(item.id.as_str()) { + errors.push(format!("duplicate planning backlog item id {:?}", item.id)); + } + } + + let mut stream_ids = HashSet::<&str>::new(); + for stream in &planning.roadmap_streams { + require_nonempty_update(&stream.id, "planning.roadmap_streams.id", &mut errors); + require_nonempty_update(&stream.title, "planning.roadmap_streams.title", &mut errors); + require_nonempty_update( + &stream.purpose, + "planning.roadmap_streams.purpose", + &mut errors, + ); + require_nonempty_update( + &stream.status, + "planning.roadmap_streams.status", + &mut errors, + ); + for item_id in &stream.item_ids { + if !backlog_ids.contains(item_id.as_str()) { + errors.push(format!( + "roadmap stream {:?} references missing backlog item {:?}", + stream.id, item_id + )); + } + } + if let Some(near_term_focus) = stream.near_term_focus.as_deref() + && !near_term_focus.trim().is_empty() + && !backlog_ids.contains(near_term_focus) + { + errors.push(format!( + "roadmap stream {:?} has missing near_term_focus {:?}", + stream.id, near_term_focus + )); + } + if !stream.id.is_empty() && !stream_ids.insert(stream.id.as_str()) { + errors.push(format!( + "duplicate planning roadmap stream id {:?}", + stream.id + )); + } + } + + let mut objective_draft_ids = HashSet::<&str>::new(); + for draft in &planning.objective_drafts { + require_nonempty_update(&draft.id, "planning.objective_drafts.id", &mut errors); + require_nonempty_update(&draft.title, "planning.objective_drafts.title", &mut errors); + require_nonempty_update( + &draft.summary, + "planning.objective_drafts.summary", + &mut errors, + ); + require_nonempty_update( + &draft.status, + "planning.objective_drafts.status", + &mut errors, + ); + if draft.acceptance_criteria.is_empty() { + errors.push(format!( + "objective draft {:?} must include at least one acceptance criterion", + draft.id + )); + } + for item_id in &draft.source_item_ids { + if !backlog_ids.contains(item_id.as_str()) { + errors.push(format!( + "objective draft {:?} references missing source backlog item {:?}", + draft.id, item_id + )); + } + } + if !draft.id.is_empty() && !objective_draft_ids.insert(draft.id.as_str()) { + errors.push(format!("duplicate objective draft id {:?}", draft.id)); + } + } + + errors +} + +fn validate_epiphany_planning_source_ref( + source_ref: &EpiphanyPlanningSourceRef, + label: &str, + errors: &mut Vec, +) { + require_nonempty_update(&source_ref.kind, &format!("{label}.kind"), errors); + if source_ref.kind == "github_issue" { + match source_ref.repo.as_deref() { + Some(repo) => require_nonempty_update(repo, &format!("{label}.repo"), errors), + None => errors.push(format!("{label}.repo is required for github_issue sources")), + } + if source_ref.issue_number.is_none() { + errors.push(format!( + "{label}.issue_number is required for github_issue sources" + )); + } + } +} + +fn epiphany_state_replacement_validation_errors( + state: &EpiphanyThreadState, + update: &EpiphanyStateUpdate, +) -> Vec { + let validates_subgoal_target = update.subgoals.is_some() || update.active_subgoal_id.is_some(); + let validates_graph_target = update.graphs.is_some() + || update.graph_frontier.is_some() + || update.graph_checkpoint.is_some(); + let mut known_evidence_ids: HashSet<&str> = state + .recent_evidence + .iter() + .filter_map(|evidence| nonempty_id(&evidence.id)) + .collect(); + for evidence in &update.evidence { + if let Some(id) = nonempty_id(&evidence.id) { + known_evidence_ids.insert(id); + } + } + + validate_state_replacement_patch(EpiphanyStateReplacementValidationInput { + active_subgoal_id: update.active_subgoal_id.as_deref(), + subgoals: if validates_subgoal_target { + update + .subgoals + .as_deref() + .or(Some(state.subgoals.as_slice())) + } else { + None + }, + invariants: update.invariants.as_deref(), + graphs: if validates_graph_target { + update.graphs.as_ref().or(Some(&state.graphs)) + } else { + None + }, + graph_frontier: update.graph_frontier.as_ref(), + graph_checkpoint: update.graph_checkpoint.as_ref(), + investigation_checkpoint: update.investigation_checkpoint.as_ref(), + available_evidence_ids: Some(&known_evidence_ids), + churn: update.churn.as_ref(), + }) +} + +fn nonempty_id(id: &str) -> Option<&str> { + if id.is_empty() { None } else { Some(id) } +} + +fn require_nonempty_update(value: &str, label: &str, errors: &mut Vec) { + if value.trim().is_empty() { + errors.push(format!("{label} must not be empty")); + } +} + +fn prepend_recent(items: &mut Vec, mut new_items: Vec) { + if new_items.is_empty() { + return; + } + new_items.append(items); + *items = new_items; +} diff --git a/notes/codex-auth-spine-inventory.md b/notes/codex-auth-spine-inventory.md index 136b9f8a..e3c3020a 100644 --- a/notes/codex-auth-spine-inventory.md +++ b/notes/codex-auth-spine-inventory.md @@ -171,13 +171,14 @@ 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 Epiphany state-update contract shape has also left vendored Codex. -`epiphany-core::EpiphanyStateUpdate` now owns the update document used by the -compatibility `thread/epiphany/update`, promotion, accept, and launch paths. -`codex-core` re-exports it only as a compatibility alias. Validation and -mutation application are still in `CodexThread`; those are the next state-write -mechanics to extract before the Codex thread can honestly call itself a -persistence adapter. +The Epiphany state-update contract and mutation law have also left vendored +Codex. `epiphany-core::EpiphanyStateUpdate` now owns the update document used +by the compatibility `thread/epiphany/update`, promotion, accept, and launch +paths. `epiphany-core::epiphany_state_update_validation_errors` and +`epiphany-core::apply_epiphany_state_update` own typed validation and mutation +application. `codex-core` re-exports the contract only as a compatibility +alias, and `CodexThread` now calls native state-update functions around its +remaining revision check, persistence validation, and rollout/session writeback. 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 diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 1b072a7a..68fc9c77 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -603,13 +603,17 @@ 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. -The Epiphany state-update document shape has now left vendored Codex too. -`epiphany-core::EpiphanyStateUpdate` owns the update contract used by update, -promote, role/reorient accept, and launch compatibility paths; `codex-core` -re-exports it only so older callers keep compiling. The remaining impurity is -the important one: `CodexThread` still owns validation, application, revisioned -writeback, and route-facing orchestration around that native update document. -Move those mechanics next. +The Epiphany state-update document shape and mutation law have now left +vendored Codex too. `epiphany-core::EpiphanyStateUpdate` owns the update +contract used by update, promote, role/reorient accept, and launch +compatibility paths, while +`epiphany-core::epiphany_state_update_validation_errors` and +`epiphany-core::apply_epiphany_state_update` own typed validation/application. +`codex-core` re-exports the contract only so older callers keep compiling. +`CodexThread` is now a compatibility caller around revision checks, +persistence validation, and rollout/session writeback. The remaining impurity +is route-facing orchestration in `codex_message_processor.rs` / +`epiphany_mutation_routes.rs`; move that behind a native service boundary next. 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 2b007062..faa46537 100644 Binary files a/state/ledgers.msgpack and b/state/ledgers.msgpack differ diff --git a/state/map.yaml b/state/map.yaml index 52e6ff2d..3fddd96a 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`, and the native `epiphany-core::EpiphanyStateUpdate` contract. 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; `epiphany-core::EpiphanyStateUpdate` now owns the state-update document shape while `codex-core` re-exports it for compatibility. Vendored `CodexThread::epiphany_launch_job` is now mostly revision check, persistence validation, and rollout/session writeback for the compatibility route, but `CodexThread` still owns state-update validation/application and revisioned persistence mechanics. `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 Epiphany state-update validation/application and revisioned write mechanics out of vendored `codex_core::CodexThread` into `epiphany-core`, leaving Codex as persistence/JSON-RPC compatibility only. Then move mutation route orchestration out of `codex_message_processor.rs`, 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`, and native state-update contract/validation/application 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, `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 mutation route orchestration out of `codex_message_processor.rs` / `epiphany_mutation_routes.rs` behind a native service boundary, 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 7b6fbd67..8106dc90 100644 --- a/vendor/codex/codex-rs/core/src/codex_thread.rs +++ b/vendor/codex/codex-rs/core/src/codex_thread.rs @@ -1,7 +1,5 @@ use crate::agent::AgentStatus; use crate::config::ConstraintResult; -use crate::epiphany_promotion::EpiphanyStateReplacementValidationInput; -use crate::epiphany_promotion::validate_state_replacement_patch; use crate::epiphany_retrieval; use crate::epiphany_retrieval::EpiphanyRetrieveQuery; use crate::epiphany_retrieval::EpiphanyRetrieveResponse; @@ -25,6 +23,7 @@ use codex_protocol::models::ResponseInputItem; use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::ReasoningEffort; use codex_protocol::protocol::AskForApproval; +#[cfg(test)] use codex_protocol::protocol::EpiphanyAcceptanceReceipt; #[cfg(test)] use codex_protocol::protocol::EpiphanyChurnState; @@ -40,9 +39,9 @@ use codex_protocol::protocol::EpiphanyJobBinding; use codex_protocol::protocol::EpiphanyJobKind; #[cfg(test)] use codex_protocol::protocol::EpiphanyObservation; +#[cfg(test)] use codex_protocol::protocol::EpiphanyPlanningState; use codex_protocol::protocol::EpiphanyRetrievalState; -use codex_protocol::protocol::EpiphanyRuntimeLink; use codex_protocol::protocol::EpiphanyStateItem; use codex_protocol::protocol::EpiphanyThreadState; use codex_protocol::protocol::Event; @@ -61,11 +60,12 @@ use epiphany_core::EpiphanyStateUpdate; use epiphany_core::EpiphanyWorkerLaunchDocument; use epiphany_core::RuntimeSpineHeartbeatLaunchPlanOptions; use epiphany_core::RuntimeSpineHeartbeatJobOptions; +use epiphany_core::apply_epiphany_state_update; +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 rmcp::model::ReadResourceRequestParams; use std::collections::HashMap; -use std::collections::HashSet; use std::path::PathBuf; use tokio::sync::Mutex; use tokio::sync::watch; @@ -782,505 +782,6 @@ fn clear_epiphany_job_binding_backend( bindings } -fn epiphany_state_update_validation_errors( - state: &EpiphanyThreadState, - update: &EpiphanyStateUpdate, -) -> Vec { - let mut errors = Vec::new(); - let mut known_evidence_ids: HashSet<&str> = state - .recent_evidence - .iter() - .filter_map(|evidence| nonempty_id(&evidence.id)) - .collect(); - let existing_evidence_ids = known_evidence_ids.clone(); - let existing_observation_ids: HashSet<&str> = state - .observations - .iter() - .filter_map(|observation| nonempty_id(&observation.id)) - .collect(); - - let mut patch_evidence_ids = HashSet::new(); - for evidence in &update.evidence { - require_nonempty_update(&evidence.id, "patch.evidence.id", &mut errors); - require_nonempty_update(&evidence.kind, "patch.evidence.kind", &mut errors); - require_nonempty_update(&evidence.status, "patch.evidence.status", &mut errors); - require_nonempty_update(&evidence.summary, "patch.evidence.summary", &mut errors); - if !evidence.id.is_empty() && !patch_evidence_ids.insert(evidence.id.as_str()) { - errors.push(format!("duplicate evidence id {:?}", evidence.id)); - } - if existing_evidence_ids.contains(evidence.id.as_str()) { - errors.push(format!( - "evidence id {:?} already exists in Epiphany state", - evidence.id - )); - } - if let Some(id) = nonempty_id(&evidence.id) { - known_evidence_ids.insert(id); - } - } - - let mut patch_observation_ids = HashSet::new(); - for observation in &update.observations { - require_nonempty_update(&observation.id, "patch.observations.id", &mut errors); - require_nonempty_update( - &observation.summary, - "patch.observations.summary", - &mut errors, - ); - require_nonempty_update( - &observation.source_kind, - "patch.observations.source_kind", - &mut errors, - ); - require_nonempty_update( - &observation.status, - "patch.observations.status", - &mut errors, - ); - if !observation.id.is_empty() && !patch_observation_ids.insert(observation.id.as_str()) { - errors.push(format!("duplicate observation id {:?}", observation.id)); - } - if existing_observation_ids.contains(observation.id.as_str()) { - errors.push(format!( - "observation id {:?} already exists in Epiphany state", - observation.id - )); - } - if observation.evidence_ids.is_empty() { - errors.push(format!( - "observation {:?} must cite at least one evidence id", - observation.id - )); - } - for evidence_id in &observation.evidence_ids { - if !known_evidence_ids.contains(evidence_id.as_str()) { - errors.push(format!( - "observation {:?} cites missing evidence id {:?}", - observation.id, evidence_id - )); - } - } - } - - if let Some(checkpoint) = update.investigation_checkpoint.as_ref() { - for evidence_id in &checkpoint.evidence_ids { - if !known_evidence_ids.contains(evidence_id.as_str()) { - errors.push(format!( - "investigation checkpoint cites missing evidence id {:?}", - evidence_id - )); - } - } - } - - if let Some(job_bindings) = update.job_bindings.as_ref() { - errors.extend(validate_epiphany_job_bindings(job_bindings)); - } - if !update.acceptance_receipts.is_empty() { - errors.extend(validate_epiphany_acceptance_receipts( - &state.acceptance_receipts, - &update.acceptance_receipts, - &known_evidence_ids, - )); - } - if !update.runtime_links.is_empty() { - errors.extend(validate_epiphany_runtime_links( - &state.runtime_links, - &update.runtime_links, - )); - } - if let Some(planning) = update.planning.as_ref() { - errors.extend(validate_epiphany_planning_state(planning)); - } - - errors.extend(epiphany_state_replacement_validation_errors(state, update)); - errors -} - -fn validate_epiphany_runtime_links( - existing: &[EpiphanyRuntimeLink], - links: &[EpiphanyRuntimeLink], -) -> Vec { - let mut errors = Vec::new(); - let mut seen_ids = existing - .iter() - .map(|link| link.id.as_str()) - .collect::>(); - for link in links { - require_nonempty_update(&link.id, "runtime_link.id", &mut errors); - require_nonempty_update(&link.binding_id, "runtime_link.binding_id", &mut errors); - require_nonempty_update(&link.surface, "runtime_link.surface", &mut errors); - require_nonempty_update(&link.role_id, "runtime_link.role_id", &mut errors); - require_nonempty_update( - &link.authority_scope, - "runtime_link.authority_scope", - &mut errors, - ); - require_nonempty_update( - &link.runtime_job_id, - "runtime_link.runtime_job_id", - &mut errors, - ); - if !seen_ids.insert(link.id.as_str()) { - errors.push(format!("runtime link id {:?} is duplicated", link.id)); - } - } - errors -} - -fn validate_epiphany_acceptance_receipts( - existing: &[EpiphanyAcceptanceReceipt], - receipts: &[EpiphanyAcceptanceReceipt], - known_evidence_ids: &HashSet<&str>, -) -> Vec { - let mut errors = Vec::new(); - let mut seen_ids = existing - .iter() - .map(|receipt| receipt.id.as_str()) - .collect::>(); - let mut seen_result_ids = existing - .iter() - .map(|receipt| receipt.result_id.as_str()) - .collect::>(); - - for receipt in receipts { - require_nonempty_update(&receipt.id, "acceptance_receipt.id", &mut errors); - require_nonempty_update( - &receipt.result_id, - "acceptance_receipt.result_id", - &mut errors, - ); - require_nonempty_update(&receipt.job_id, "acceptance_receipt.job_id", &mut errors); - require_nonempty_update( - &receipt.binding_id, - "acceptance_receipt.binding_id", - &mut errors, - ); - require_nonempty_update(&receipt.surface, "acceptance_receipt.surface", &mut errors); - require_nonempty_update(&receipt.role_id, "acceptance_receipt.role_id", &mut errors); - require_nonempty_update(&receipt.status, "acceptance_receipt.status", &mut errors); - require_nonempty_update( - &receipt.accepted_at, - "acceptance_receipt.accepted_at", - &mut errors, - ); - if !seen_ids.insert(receipt.id.as_str()) { - errors.push(format!( - "acceptance receipt id {:?} is duplicated", - receipt.id - )); - } - if !seen_result_ids.insert(receipt.result_id.as_str()) { - errors.push(format!( - "runtime result {:?} already has an acceptance receipt", - receipt.result_id - )); - } - if let Some(evidence_id) = receipt.accepted_evidence_id.as_deref() - && !known_evidence_ids.contains(evidence_id) - { - errors.push(format!( - "acceptance receipt {:?} cites missing evidence id {:?}", - receipt.id, evidence_id - )); - } - } - - errors -} - -fn validate_epiphany_job_bindings(job_bindings: &[EpiphanyJobBinding]) -> Vec { - let mut errors = Vec::new(); - let mut seen_ids = HashSet::<&str>::new(); - - for binding in job_bindings { - require_nonempty_update(&binding.id, "job_binding.id", &mut errors); - require_nonempty_update(&binding.scope, "job_binding.scope", &mut errors); - require_nonempty_update(&binding.owner_role, "job_binding.owner_role", &mut errors); - if let Some(authority_scope) = binding.authority_scope.as_deref() { - require_nonempty_update(authority_scope, "job_binding.authority_scope", &mut errors); - } - if let Some(blocking_reason) = binding.blocking_reason.as_deref() { - require_nonempty_update(blocking_reason, "job_binding.blocking_reason", &mut errors); - } - if !binding.id.is_empty() && !seen_ids.insert(binding.id.as_str()) { - errors.push(format!("duplicate job binding id {:?}", binding.id)); - } - } - - errors -} - -fn validate_epiphany_planning_state(planning: &EpiphanyPlanningState) -> Vec { - let mut errors = Vec::new(); - let mut capture_ids = HashSet::<&str>::new(); - for capture in &planning.captures { - require_nonempty_update(&capture.id, "planning.captures.id", &mut errors); - require_nonempty_update(&capture.title, "planning.captures.title", &mut errors); - require_nonempty_update( - &capture.confidence, - "planning.captures.confidence", - &mut errors, - ); - require_nonempty_update(&capture.status, "planning.captures.status", &mut errors); - validate_epiphany_planning_source_ref( - &capture.source, - "planning.captures.source", - &mut errors, - ); - if !capture.id.is_empty() && !capture_ids.insert(capture.id.as_str()) { - errors.push(format!("duplicate planning capture id {:?}", capture.id)); - } - } - - let mut backlog_ids = HashSet::<&str>::new(); - for item in &planning.backlog_items { - require_nonempty_update(&item.id, "planning.backlog_items.id", &mut errors); - require_nonempty_update(&item.title, "planning.backlog_items.title", &mut errors); - require_nonempty_update(&item.kind, "planning.backlog_items.kind", &mut errors); - require_nonempty_update(&item.summary, "planning.backlog_items.summary", &mut errors); - require_nonempty_update(&item.status, "planning.backlog_items.status", &mut errors); - require_nonempty_update(&item.horizon, "planning.backlog_items.horizon", &mut errors); - require_nonempty_update( - &item.priority.value, - "planning.backlog_items.priority.value", - &mut errors, - ); - require_nonempty_update( - &item.priority.rationale, - "planning.backlog_items.priority.rationale", - &mut errors, - ); - require_nonempty_update( - &item.confidence, - "planning.backlog_items.confidence", - &mut errors, - ); - require_nonempty_update( - &item.product_area, - "planning.backlog_items.product_area", - &mut errors, - ); - for (index, source_ref) in item.source_refs.iter().enumerate() { - validate_epiphany_planning_source_ref( - source_ref, - &format!("planning.backlog_items.source_refs[{index}]"), - &mut errors, - ); - } - if !item.id.is_empty() && !backlog_ids.insert(item.id.as_str()) { - errors.push(format!("duplicate planning backlog item id {:?}", item.id)); - } - } - - let mut stream_ids = HashSet::<&str>::new(); - for stream in &planning.roadmap_streams { - require_nonempty_update(&stream.id, "planning.roadmap_streams.id", &mut errors); - require_nonempty_update(&stream.title, "planning.roadmap_streams.title", &mut errors); - require_nonempty_update( - &stream.purpose, - "planning.roadmap_streams.purpose", - &mut errors, - ); - require_nonempty_update( - &stream.status, - "planning.roadmap_streams.status", - &mut errors, - ); - for item_id in &stream.item_ids { - if !backlog_ids.contains(item_id.as_str()) { - errors.push(format!( - "roadmap stream {:?} references missing backlog item {:?}", - stream.id, item_id - )); - } - } - if let Some(near_term_focus) = stream.near_term_focus.as_deref() - && !near_term_focus.trim().is_empty() - && !backlog_ids.contains(near_term_focus) - { - errors.push(format!( - "roadmap stream {:?} has missing near_term_focus {:?}", - stream.id, near_term_focus - )); - } - if !stream.id.is_empty() && !stream_ids.insert(stream.id.as_str()) { - errors.push(format!( - "duplicate planning roadmap stream id {:?}", - stream.id - )); - } - } - - let mut objective_draft_ids = HashSet::<&str>::new(); - for draft in &planning.objective_drafts { - require_nonempty_update(&draft.id, "planning.objective_drafts.id", &mut errors); - require_nonempty_update(&draft.title, "planning.objective_drafts.title", &mut errors); - require_nonempty_update( - &draft.summary, - "planning.objective_drafts.summary", - &mut errors, - ); - require_nonempty_update( - &draft.status, - "planning.objective_drafts.status", - &mut errors, - ); - if draft.acceptance_criteria.is_empty() { - errors.push(format!( - "objective draft {:?} must include at least one acceptance criterion", - draft.id - )); - } - for item_id in &draft.source_item_ids { - if !backlog_ids.contains(item_id.as_str()) { - errors.push(format!( - "objective draft {:?} references missing source backlog item {:?}", - draft.id, item_id - )); - } - } - if !draft.id.is_empty() && !objective_draft_ids.insert(draft.id.as_str()) { - errors.push(format!("duplicate objective draft id {:?}", draft.id)); - } - } - - errors -} - -fn validate_epiphany_planning_source_ref( - source_ref: &codex_protocol::protocol::EpiphanyPlanningSourceRef, - label: &str, - errors: &mut Vec, -) { - require_nonempty_update(&source_ref.kind, &format!("{label}.kind"), errors); - if source_ref.kind == "github_issue" { - match source_ref.repo.as_deref() { - Some(repo) => require_nonempty_update(repo, &format!("{label}.repo"), errors), - None => errors.push(format!("{label}.repo is required for github_issue sources")), - } - if source_ref.issue_number.is_none() { - errors.push(format!( - "{label}.issue_number is required for github_issue sources" - )); - } - } -} - -fn epiphany_state_replacement_validation_errors( - state: &EpiphanyThreadState, - update: &EpiphanyStateUpdate, -) -> Vec { - let validates_subgoal_target = update.subgoals.is_some() || update.active_subgoal_id.is_some(); - let validates_graph_target = update.graphs.is_some() - || update.graph_frontier.is_some() - || update.graph_checkpoint.is_some(); - let mut known_evidence_ids: HashSet<&str> = state - .recent_evidence - .iter() - .filter_map(|evidence| nonempty_id(&evidence.id)) - .collect(); - for evidence in &update.evidence { - if let Some(id) = nonempty_id(&evidence.id) { - known_evidence_ids.insert(id); - } - } - - validate_state_replacement_patch(EpiphanyStateReplacementValidationInput { - active_subgoal_id: update.active_subgoal_id.as_deref(), - subgoals: if validates_subgoal_target { - update - .subgoals - .as_deref() - .or(Some(state.subgoals.as_slice())) - } else { - None - }, - invariants: update.invariants.as_deref(), - graphs: if validates_graph_target { - update.graphs.as_ref().or(Some(&state.graphs)) - } else { - None - }, - graph_frontier: update.graph_frontier.as_ref(), - graph_checkpoint: update.graph_checkpoint.as_ref(), - investigation_checkpoint: update.investigation_checkpoint.as_ref(), - available_evidence_ids: Some(&known_evidence_ids), - churn: update.churn.as_ref(), - }) -} - -fn nonempty_id(id: &str) -> Option<&str> { - if id.is_empty() { None } else { Some(id) } -} - -fn require_nonempty_update(value: &str, label: &str, errors: &mut Vec) { - if value.trim().is_empty() { - errors.push(format!("{label} must not be empty")); - } -} - -fn apply_epiphany_state_update( - state: &mut EpiphanyThreadState, - update: EpiphanyStateUpdate, - reference_turn_id: Option, -) { - if let Some(objective) = update.objective { - state.objective = Some(objective); - } - if let Some(active_subgoal_id) = update.active_subgoal_id { - state.active_subgoal_id = Some(active_subgoal_id); - } - if let Some(subgoals) = update.subgoals { - state.subgoals = subgoals; - } - if let Some(invariants) = update.invariants { - state.invariants = invariants; - } - if let Some(graphs) = update.graphs { - state.graphs = graphs; - } - if let Some(graph_frontier) = update.graph_frontier { - state.graph_frontier = Some(graph_frontier); - } - if let Some(graph_checkpoint) = update.graph_checkpoint { - state.graph_checkpoint = Some(graph_checkpoint); - } - if let Some(scratch) = update.scratch { - state.scratch = Some(scratch); - } - if let Some(checkpoint) = update.investigation_checkpoint { - state.investigation_checkpoint = Some(checkpoint); - } - if let Some(job_bindings) = update.job_bindings { - state.job_bindings = job_bindings; - } - prepend_recent(&mut state.acceptance_receipts, update.acceptance_receipts); - prepend_recent(&mut state.runtime_links, update.runtime_links); - if let Some(churn) = update.churn { - state.churn = Some(churn); - } - if let Some(mode) = update.mode { - state.mode = Some(mode); - } - if let Some(planning) = update.planning { - state.planning = planning; - } - - prepend_recent(&mut state.observations, update.observations); - prepend_recent(&mut state.recent_evidence, update.evidence); - state.revision = state.revision.saturating_add(1); - state.last_updated_turn_id = reference_turn_id; -} - -fn prepend_recent(items: &mut Vec, mut new_items: Vec) { - if new_items.is_empty() { - return; - } - new_items.append(items); - *items = new_items; -} - #[cfg(test)] mod epiphany_update_tests { use super::*; diff --git a/vendor/codex/codex-rs/core/src/epiphany_promotion.rs b/vendor/codex/codex-rs/core/src/epiphany_promotion.rs index 31aa3d5f..9822817a 100644 --- a/vendor/codex/codex-rs/core/src/epiphany_promotion.rs +++ b/vendor/codex/codex-rs/core/src/epiphany_promotion.rs @@ -1,5 +1,3 @@ pub use epiphany_core::EpiphanyPromotionDecision; pub use epiphany_core::EpiphanyPromotionInput; -pub use epiphany_core::EpiphanyStateReplacementValidationInput; pub use epiphany_core::evaluate_promotion; -pub use epiphany_core::validate_state_replacement_patch;