Move Epiphany mutation helpers to bridge

This commit is contained in:
Meta Vens 2026-05-13 03:37:32 +01:00
commit 6b9c430aa4
12 changed files with 407 additions and 393 deletions

View file

@ -2,9 +2,11 @@ pub mod context;
pub mod coordinator;
pub mod jobs;
pub mod launch;
pub mod mutation;
pub mod pressure;
pub mod reorient;
pub mod retrieve;
pub mod results;
pub mod runtime_results;
pub mod scene;
pub mod state;

View file

@ -0,0 +1,253 @@
use std::path::PathBuf;
use codex_app_server_protocol::ThreadEpiphanyReorientFinding;
use codex_app_server_protocol::ThreadEpiphanyRoleFinding;
use codex_app_server_protocol::ThreadEpiphanyRoleId;
use codex_app_server_protocol::ThreadEpiphanyStateUpdatedField;
use codex_app_server_protocol::ThreadEpiphanyUpdatePatch;
use codex_protocol::protocol::EpiphanyCodeRef;
use codex_protocol::protocol::EpiphanyInvestigationCheckpoint;
use codex_protocol::protocol::EpiphanyInvestigationDisposition;
use codex_protocol::protocol::EpiphanyScratchPad;
use epiphany_core::EpiphanyRoleStatePatchDocument;
use epiphany_core::imagination_role_state_patch_policy_errors;
use epiphany_core::modeling_role_state_patch_policy_errors;
pub fn parse_role_finding_state_patch(
finding: &ThreadEpiphanyRoleFinding,
) -> Result<ThreadEpiphanyUpdatePatch, String> {
finding
.state_patch
.clone()
.ok_or_else(|| "completed role finding did not include a reviewable statePatch".to_string())
}
pub fn core_state_patch_from_protocol(
patch: &ThreadEpiphanyUpdatePatch,
) -> EpiphanyRoleStatePatchDocument {
EpiphanyRoleStatePatchDocument {
objective: patch.objective.clone(),
active_subgoal_id: patch.active_subgoal_id.clone(),
subgoals: patch.subgoals.clone(),
invariants: patch.invariants.clone(),
graphs: patch.graphs.clone(),
graph_frontier: patch.graph_frontier.clone(),
graph_checkpoint: patch.graph_checkpoint.clone(),
scratch: patch.scratch.clone(),
investigation_checkpoint: patch.investigation_checkpoint.clone(),
job_bindings: patch.job_bindings.clone(),
acceptance_receipts: patch.acceptance_receipts.clone(),
runtime_links: patch.runtime_links.clone(),
observations: patch.observations.clone(),
evidence: patch.evidence.clone(),
churn: patch.churn.clone(),
mode: patch.mode.clone(),
planning: patch.planning.clone(),
}
}
pub fn imagination_role_accept_patch_errors(patch: &ThreadEpiphanyUpdatePatch) -> Vec<String> {
imagination_role_state_patch_policy_errors(&core_state_patch_from_protocol(patch))
}
pub fn modeling_role_accept_patch_errors(patch: &ThreadEpiphanyUpdatePatch) -> Vec<String> {
modeling_role_state_patch_policy_errors(&core_state_patch_from_protocol(patch))
}
pub fn epiphany_modeling_finding_has_reviewable_state_patch(
finding: &ThreadEpiphanyRoleFinding,
) -> bool {
finding.role_id == ThreadEpiphanyRoleId::Modeling
&& finding
.state_patch
.as_ref()
.is_some_and(|patch| modeling_role_accept_patch_errors(patch).is_empty())
}
pub fn epiphany_imagination_finding_has_reviewable_state_patch(
finding: &ThreadEpiphanyRoleFinding,
) -> bool {
finding.role_id == ThreadEpiphanyRoleId::Imagination
&& finding
.state_patch
.as_ref()
.is_some_and(|patch| imagination_role_accept_patch_errors(patch).is_empty())
}
pub fn role_finding_summary(finding: &ThreadEpiphanyRoleFinding) -> String {
let summary = finding
.summary
.clone()
.unwrap_or_else(|| "Role worker returned a structured finding.".to_string());
if let Some(next_safe_move) = finding.next_safe_move.as_deref() {
format!("{summary} Next safe move: {next_safe_move}")
} else {
summary
}
}
pub fn reorient_finding_code_refs(
finding: &ThreadEpiphanyReorientFinding,
) -> Vec<EpiphanyCodeRef> {
finding
.files_inspected
.iter()
.filter(|path| !path.trim().is_empty())
.map(|path| EpiphanyCodeRef {
path: PathBuf::from(path),
start_line: None,
end_line: None,
symbol: None,
note: Some("Inspected by accepted reorientation worker.".to_string()),
})
.collect()
}
pub fn reorient_finding_scratch(
binding_id: &str,
finding: &ThreadEpiphanyReorientFinding,
) -> EpiphanyScratchPad {
let mode = finding.mode.as_deref().unwrap_or("unknown");
let checkpoint_validity = match finding.checkpoint_still_valid {
Some(true) => "valid",
Some(false) => "invalid",
None => "unknown",
};
EpiphanyScratchPad {
summary: finding.summary.clone(),
hypothesis: Some(format!(
"Accepted {mode} reorientation finding from {binding_id}; checkpoint validity is {checkpoint_validity}."
)),
next_probe: finding.next_safe_move.clone(),
notes: vec![format!(
"Files inspected: {}",
if finding.files_inspected.is_empty() {
"none reported".to_string()
} else {
finding.files_inspected.join(", ")
}
)],
}
}
pub fn reorient_finding_investigation_checkpoint(
checkpoint: &EpiphanyInvestigationCheckpoint,
evidence_id: &str,
code_refs: &[EpiphanyCodeRef],
finding: &ThreadEpiphanyReorientFinding,
) -> EpiphanyInvestigationCheckpoint {
let mut checkpoint = checkpoint.clone();
checkpoint.summary = finding.summary.clone().or(checkpoint.summary);
checkpoint.next_action = finding.next_safe_move.clone().or(checkpoint.next_action);
checkpoint.disposition = EpiphanyInvestigationDisposition::ResumeReady;
if !checkpoint
.evidence_ids
.iter()
.any(|existing| existing == evidence_id)
{
checkpoint.evidence_ids.push(evidence_id.to_string());
}
for code_ref in code_refs {
if !checkpoint
.code_refs
.iter()
.any(|existing| existing.path == code_ref.path)
{
checkpoint.code_refs.push(code_ref.clone());
}
}
checkpoint
}
pub fn epiphany_job_launch_changed_fields() -> Vec<ThreadEpiphanyStateUpdatedField> {
vec![
ThreadEpiphanyStateUpdatedField::JobBindings,
ThreadEpiphanyStateUpdatedField::RuntimeLinks,
]
}
pub fn thread_epiphany_patch_has_state_replacements(patch: &ThreadEpiphanyUpdatePatch) -> bool {
patch.objective.is_some()
|| patch.active_subgoal_id.is_some()
|| patch.subgoals.is_some()
|| patch.invariants.is_some()
|| patch.graphs.is_some()
|| patch.graph_frontier.is_some()
|| patch.graph_checkpoint.is_some()
|| patch.scratch.is_some()
|| patch.investigation_checkpoint.is_some()
|| patch.job_bindings.is_some()
|| !patch.acceptance_receipts.is_empty()
|| !patch.runtime_links.is_empty()
|| patch.churn.is_some()
|| patch.mode.is_some()
|| patch.planning.is_some()
}
pub fn epiphany_update_patch_changed_fields(
patch: &ThreadEpiphanyUpdatePatch,
) -> Vec<ThreadEpiphanyStateUpdatedField> {
let mut fields = Vec::new();
if patch.objective.is_some() {
fields.push(ThreadEpiphanyStateUpdatedField::Objective);
}
if patch.active_subgoal_id.is_some() {
fields.push(ThreadEpiphanyStateUpdatedField::ActiveSubgoalId);
}
if patch.subgoals.is_some() {
fields.push(ThreadEpiphanyStateUpdatedField::Subgoals);
}
if patch.invariants.is_some() {
fields.push(ThreadEpiphanyStateUpdatedField::Invariants);
}
if patch.graphs.is_some() {
fields.push(ThreadEpiphanyStateUpdatedField::Graphs);
}
if patch.graph_frontier.is_some() {
fields.push(ThreadEpiphanyStateUpdatedField::GraphFrontier);
}
if patch.graph_checkpoint.is_some() {
fields.push(ThreadEpiphanyStateUpdatedField::GraphCheckpoint);
}
if patch.scratch.is_some() {
fields.push(ThreadEpiphanyStateUpdatedField::Scratch);
}
if patch.investigation_checkpoint.is_some() {
fields.push(ThreadEpiphanyStateUpdatedField::InvestigationCheckpoint);
}
if patch.job_bindings.is_some() {
fields.push(ThreadEpiphanyStateUpdatedField::JobBindings);
}
if !patch.acceptance_receipts.is_empty() {
fields.push(ThreadEpiphanyStateUpdatedField::AcceptanceReceipts);
}
if !patch.runtime_links.is_empty() {
fields.push(ThreadEpiphanyStateUpdatedField::RuntimeLinks);
}
if !patch.observations.is_empty() {
fields.push(ThreadEpiphanyStateUpdatedField::Observations);
}
if !patch.evidence.is_empty() {
fields.push(ThreadEpiphanyStateUpdatedField::Evidence);
}
if patch.churn.is_some() {
fields.push(ThreadEpiphanyStateUpdatedField::Churn);
}
if patch.mode.is_some() {
fields.push(ThreadEpiphanyStateUpdatedField::Mode);
}
if patch.planning.is_some() {
fields.push(ThreadEpiphanyStateUpdatedField::Planning);
}
fields
}
pub fn epiphany_promote_changed_fields(
patch: &ThreadEpiphanyUpdatePatch,
) -> Vec<ThreadEpiphanyStateUpdatedField> {
let mut fields = epiphany_update_patch_changed_fields(patch);
if !fields.contains(&ThreadEpiphanyStateUpdatedField::Evidence) {
fields.push(ThreadEpiphanyStateUpdatedField::Evidence);
}
fields
}

View file

@ -5,6 +5,9 @@ use codex_app_server_protocol::ThreadEpiphanyReorientResultStatus;
use codex_app_server_protocol::ThreadEpiphanyRoleFinding;
use codex_app_server_protocol::ThreadEpiphanyRoleId;
use codex_app_server_protocol::ThreadEpiphanyRoleResultStatus;
use codex_core::CodexThread;
use codex_protocol::error::CodexErr;
use codex_protocol::error::Result as CodexResult;
use codex_protocol::protocol::EpiphanyRuntimeLink;
use codex_protocol::protocol::EpiphanyThreadState;
use epiphany_core::EpiphanyRuntimeJobSnapshot;
@ -216,6 +219,50 @@ pub async fn load_epiphany_role_result_snapshot(
)
}
pub async fn load_completed_epiphany_role_finding(
thread: &CodexThread,
state: &EpiphanyThreadState,
role_id: ThreadEpiphanyRoleId,
binding_id: &str,
) -> CodexResult<ThreadEpiphanyRoleFinding> {
if let Some(link) = latest_epiphany_runtime_link_for_binding(state, binding_id) {
let runtime_store_path = thread.epiphany_runtime_spine_store_path().await;
let (status, finding, _note) = load_epiphany_role_result_from_runtime_spine_job(
link.runtime_job_id.as_str(),
Some(runtime_store_path.as_path()),
role_id,
);
if status != ThreadEpiphanyRoleResultStatus::Completed {
return Err(CodexErr::InvalidRequest(format!(
"cannot accept role result while worker status is {:?}",
status
)));
}
return finding.ok_or_else(|| {
CodexErr::InvalidRequest(
"cannot accept completed role worker because no typed runtime-spine result was recorded"
.to_string(),
)
});
}
if !state
.job_bindings
.iter()
.any(|binding| binding.id == binding_id)
{
return Err(CodexErr::InvalidRequest(format!(
"epiphany role binding {:?} was not found",
binding_id
)));
}
Err(CodexErr::InvalidRequest(
"role findings without runtime-spine results are unsupported; accept only typed runtime-spine results"
.to_string(),
))
}
pub async fn load_epiphany_reorient_result_snapshot(
state: Option<&EpiphanyThreadState>,
runtime_store_path: Option<&Path>,
@ -257,6 +304,48 @@ pub async fn load_epiphany_reorient_result_snapshot(
)
}
pub async fn load_completed_epiphany_reorient_finding(
thread: &CodexThread,
state: &EpiphanyThreadState,
binding_id: &str,
) -> CodexResult<ThreadEpiphanyReorientFinding> {
if let Some(link) = latest_epiphany_runtime_link_for_binding(state, binding_id) {
let runtime_store_path = thread.epiphany_runtime_spine_store_path().await;
let (status, finding, _note) = load_epiphany_reorient_result_from_runtime_spine_job(
link.runtime_job_id.as_str(),
Some(runtime_store_path.as_path()),
);
if status != ThreadEpiphanyReorientResultStatus::Completed {
return Err(CodexErr::InvalidRequest(format!(
"cannot accept reorientation result while worker status is {:?}",
status
)));
}
return finding.ok_or_else(|| {
CodexErr::InvalidRequest(
"cannot accept completed reorientation worker because no typed runtime-spine result was recorded"
.to_string(),
)
});
}
if !state
.job_bindings
.iter()
.any(|binding| binding.id == binding_id)
{
return Err(CodexErr::InvalidRequest(format!(
"epiphany reorientation binding {:?} was not found",
binding_id
)));
}
Err(CodexErr::InvalidRequest(
"reorientation findings without runtime-spine results are unsupported; accept only typed runtime-spine results"
.to_string(),
))
}
pub fn latest_epiphany_runtime_link_for_binding<'a>(
state: &'a EpiphanyThreadState,
binding_id: &str,

View file

@ -0,0 +1,19 @@
use codex_core::CodexThread;
use codex_protocol::protocol::EpiphanyThreadState;
pub async fn live_thread_epiphany_state(thread: &CodexThread) -> Option<EpiphanyThreadState> {
let mut epiphany_state = thread.epiphany_state().await;
if let Some(state) = epiphany_state.as_mut()
&& state.retrieval.is_none()
{
state.retrieval = Some(thread.epiphany_retrieval_state().await);
}
epiphany_state
}
pub async fn client_visible_live_thread_epiphany_state(
thread: &CodexThread,
fallback: EpiphanyThreadState,
) -> EpiphanyThreadState {
live_thread_epiphany_state(thread).await.unwrap_or(fallback)
}

View file

@ -498,18 +498,29 @@ visibility now; only generic Codex plugin/test modules still do. The processor
is about 10,339 lines. This is not final purity: mutation orchestration still
lives in the Codex processor and should move behind a small typed service
boundary next.
The twenty-third cut moved route-independent mutation document mechanics into
`epiphany-codex-bridge/src/mutation.rs`: state-patch parsing, protocol-to-core
patch projection, role patch policy reviewability, finding summaries,
reorient acceptance scratch/checkpoint synthesis, and changed-field derivation.
It also moved completed role/reorient runtime-result loading into
`epiphany-codex-bridge/src/runtime_results.rs` and live-state projection into
`epiphany-codex-bridge/src/state.rs`. `epiphany_mutation_routes.rs` is now
about 1,271 lines and `epiphany_state_helpers.rs` is down to a 19-line
rollout-state loader. This is a real authority cut, but not a sufficient
carcass cut: route-level launch/accept/update/promote/interrupt orchestration
still lives in vendored Codex.
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.
Continue with the actual whale-carcass cut: replace child-module parent
visibility with explicit typed bridge/service calls, then move route-independent
state/runtime helpers out of `codex_message_processor.rs`. Success is a visibly
smaller processor and less mutation authority in Codex, not merely nicer payload
names or another adapter reliquary. Do not resume Rider, Unity, Aquarium, Face,
dogfood, planning, app, skill, marketplace, or bridge expansion until this organ
is being cut cleanly.
Continue with the actual whale-carcass cut: carve route-level mutation
orchestration into explicit typed bridge/service calls, starting with launch
response/notification construction and acceptance update bundles. Success is a
visibly smaller processor and less mutation authority in Codex, not merely
nicer payload names or another adapter reliquary. Do not resume Rider, Unity,
Aquarium, Face, dogfood, planning, app, skill, marketplace, or bridge expansion
until this organ is being cut cleanly.
The Phase 6 freshness slice is landed. It exposes read-only
`thread/epiphany/freshness` from live retrieval summaries plus graph

Binary file not shown.

View file

@ -278,5 +278,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, and now a real physical extraction: `epiphany-codex-bridge` lives outside `vendor/codex` and owns the Codex-facing Epiphany adapters for scene, jobs, context/planning/graph query, retrieval, result projection, runtime-spine result adaptation, launch/prompt doctrine, 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, mutation orchestration, and state hydration. The processor is about 10,339 lines after moving runtime result adaptation and making all Epiphany child-module dependencies explicit; only generic Codex plugin/test child modules still use parent wildcards. Vendored Codex lost roughly 3.6k lines of Epiphany adapter/prompt/runtime-result ownership across the bridge extraction. This is progress, not absolution: the bridge is still Codex-facing compatibility, not the final CultNet runtime, and mutation orchestration still lives inside the Codex processor. MCP itself is correctly JSON at its protocol edge; the target is typed Epiphany intent/result/receipt wrappers around MCP, not replacing MCP JSON.
next_action: Continue Codex starvation by moving Epiphany mutation orchestration behind an explicit service boundary outside `codex_message_processor.rs`, starting with launch/accept/update helper functions that can take a small typed context instead of borrowing the whole processor. Do not resume app/skill/marketplace expansion.
summary: The Codex starvation pass has five typing receipts, seventeen processor cuts, and now a real physical extraction: `epiphany-codex-bridge` lives outside `vendor/codex` and owns the 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,271 lines, and `epiphany_state_helpers.rs` is down to a 19-line rollout-state loader after moving typed mutation helpers, reviewability checks, completed runtime-result acceptance loading, and live-state projection out to the bridge. This is progress, not absolution: the bridge is still Codex-facing compatibility, not the final CultNet runtime, and route-level launch/accept/update/promote/interrupt orchestration still lives inside the Codex processor. MCP itself is correctly JSON at its protocol edge; the target is typed Epiphany intent/result/receipt wrappers around MCP, not replacing MCP JSON.
next_action: Continue Codex starvation by carving route-level mutation orchestration into explicit outside-vendor service calls, starting with launch response/notification construction and acceptance update bundles that can take small typed inputs instead of borrowing `CodexMessageProcessor`. Do not resume app/skill/marketplace expansion.

View file

@ -5,15 +5,6 @@ mod epiphany_state_helpers;
pub(crate) use self::epiphany_automation::maybe_run_epiphany_coordinator_automation_for_turn_boundary;
pub(crate) use self::epiphany_automation::maybe_run_epiphany_pre_compaction_checkpoint_intervention_for_token_count;
use self::epiphany_mutation_routes::epiphany_promote_changed_fields;
use self::epiphany_mutation_routes::epiphany_update_patch_changed_fields;
use self::epiphany_mutation_routes::reorient_finding_code_refs;
use self::epiphany_mutation_routes::reorient_finding_investigation_checkpoint;
use self::epiphany_mutation_routes::reorient_finding_scratch;
use self::epiphany_mutation_routes::role_finding_summary;
use self::epiphany_state_helpers::epiphany_imagination_finding_has_reviewable_state_patch;
use self::epiphany_state_helpers::epiphany_modeling_finding_has_reviewable_state_patch;
use self::epiphany_state_helpers::live_thread_epiphany_state;
use self::epiphany_state_helpers::load_epiphany_state_from_rollout_path;
use crate::bespoke_event_handling::apply_bespoke_event_handling;
use crate::bespoke_event_handling::maybe_emit_hook_prompt_item_completed;
@ -456,6 +447,14 @@ use epiphany_codex_bridge::launch::epiphany_reorient_launch_output_schema;
use epiphany_codex_bridge::launch::epiphany_role_launch_output_schema;
use epiphany_codex_bridge::launch::epiphany_specialist_prompt_config;
use epiphany_codex_bridge::launch::render_epiphany_coordinator_note;
use epiphany_codex_bridge::mutation::epiphany_imagination_finding_has_reviewable_state_patch;
use epiphany_codex_bridge::mutation::epiphany_modeling_finding_has_reviewable_state_patch;
use epiphany_codex_bridge::mutation::epiphany_promote_changed_fields;
use epiphany_codex_bridge::mutation::epiphany_update_patch_changed_fields;
use epiphany_codex_bridge::mutation::reorient_finding_code_refs;
use epiphany_codex_bridge::mutation::reorient_finding_investigation_checkpoint;
use epiphany_codex_bridge::mutation::reorient_finding_scratch;
use epiphany_codex_bridge::mutation::role_finding_summary;
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;
@ -468,6 +467,7 @@ use epiphany_codex_bridge::retrieve::map_epiphany_retrieve_index_summary;
use epiphany_codex_bridge::retrieve::map_epiphany_retrieve_response;
use epiphany_codex_bridge::runtime_results::load_epiphany_role_result_from_runtime_spine_job;
use epiphany_codex_bridge::scene::map_epiphany_scene;
use epiphany_codex_bridge::state::live_thread_epiphany_state;
use epiphany_core::EpiphanyWorkerLaunchDocument;
use std::collections::HashMap;
use std::collections::HashSet;

View file

@ -30,6 +30,8 @@ use epiphany_codex_bridge::launch::EPIPHANY_MODELING_ROLE_BINDING_ID;
use epiphany_codex_bridge::launch::EPIPHANY_REORIENT_LAUNCH_BINDING_ID;
use epiphany_codex_bridge::launch::EPIPHANY_VERIFICATION_ROLE_BINDING_ID;
use epiphany_codex_bridge::launch::build_epiphany_reorient_launch_request;
use epiphany_codex_bridge::mutation::epiphany_job_launch_changed_fields;
use epiphany_codex_bridge::mutation::epiphany_modeling_finding_has_reviewable_state_patch;
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;
@ -37,13 +39,11 @@ use epiphany_codex_bridge::reorient::map_epiphany_freshness;
use epiphany_codex_bridge::reorient::map_epiphany_reorient;
use epiphany_codex_bridge::runtime_results::load_epiphany_reorient_result_snapshot;
use epiphany_codex_bridge::runtime_results::load_epiphany_role_result_snapshot;
use epiphany_codex_bridge::state::client_visible_live_thread_epiphany_state;
use tokio::sync::Mutex;
use tracing::warn;
use super::epiphany_freshness_watcher_snapshot;
use super::epiphany_mutation_routes::epiphany_job_launch_changed_fields;
use super::epiphany_state_helpers::client_visible_live_thread_epiphany_state;
use super::epiphany_state_helpers::epiphany_modeling_finding_has_reviewable_state_patch;
use crate::epiphany_invalidation::EpiphanyInvalidationManager;
use crate::outgoing_message::ThreadScopedOutgoingMessageSender;
use crate::thread_state::ThreadState;

View file

@ -1,9 +1,6 @@
use std::path::PathBuf;
use chrono::SecondsFormat;
use chrono::Utc;
use codex_app_server_protocol::*;
use codex_core::CodexThread;
use codex_core::EpiphanyJobInterruptRequest;
use codex_core::EpiphanyJobLaunchRequest;
use codex_core::EpiphanyPromotionInput;
@ -11,12 +8,6 @@ use codex_core::EpiphanyStateUpdate;
use codex_core::evaluate_promotion;
use codex_protocol::ThreadId;
use codex_protocol::error::CodexErr;
use codex_protocol::error::Result as CodexResult;
use codex_protocol::protocol::EpiphanyCodeRef;
use codex_protocol::protocol::EpiphanyInvestigationCheckpoint;
use codex_protocol::protocol::EpiphanyInvestigationDisposition;
use codex_protocol::protocol::EpiphanyScratchPad;
use codex_protocol::protocol::EpiphanyThreadState;
use epiphany_codex_bridge::jobs::epiphany_blocked_state_job;
use epiphany_codex_bridge::jobs::map_core_epiphany_job_kind;
use epiphany_codex_bridge::jobs::map_epiphany_jobs;
@ -26,32 +17,35 @@ use epiphany_codex_bridge::launch::build_epiphany_role_launch_request;
use epiphany_codex_bridge::launch::epiphany_role_binding_id;
use epiphany_codex_bridge::launch::epiphany_role_label;
use epiphany_codex_bridge::launch::map_core_worker_launch_document;
use epiphany_codex_bridge::mutation::epiphany_job_launch_changed_fields;
use epiphany_codex_bridge::mutation::epiphany_promote_changed_fields;
use epiphany_codex_bridge::mutation::epiphany_update_patch_changed_fields;
use epiphany_codex_bridge::mutation::imagination_role_accept_patch_errors;
use epiphany_codex_bridge::mutation::modeling_role_accept_patch_errors;
use epiphany_codex_bridge::mutation::parse_role_finding_state_patch;
use epiphany_codex_bridge::mutation::thread_epiphany_patch_has_state_replacements;
use epiphany_codex_bridge::pressure::map_epiphany_pressure;
use epiphany_codex_bridge::reorient::map_epiphany_freshness;
use epiphany_codex_bridge::reorient::map_epiphany_reorient;
use epiphany_codex_bridge::results::map_core_role_result_role_id;
use epiphany_codex_bridge::retrieve::map_epiphany_retrieve_index_summary;
use epiphany_codex_bridge::runtime_results::latest_epiphany_runtime_link_for_binding;
use epiphany_codex_bridge::runtime_results::load_epiphany_reorient_result_from_runtime_spine_job;
use epiphany_codex_bridge::runtime_results::load_epiphany_role_result_from_runtime_spine_job;
use epiphany_codex_bridge::runtime_results::load_completed_epiphany_reorient_finding;
use epiphany_codex_bridge::runtime_results::load_completed_epiphany_role_finding;
use epiphany_codex_bridge::runtime_results::reorient_finding_runtime_job_id;
use epiphany_codex_bridge::runtime_results::reorient_finding_runtime_result_id;
use epiphany_codex_bridge::runtime_results::role_finding_runtime_job_id;
use epiphany_codex_bridge::runtime_results::role_finding_runtime_result_id;
use epiphany_codex_bridge::state::client_visible_live_thread_epiphany_state;
use epiphany_core::EpiphanyReorientAcceptanceFinding;
use epiphany_core::EpiphanyRoleAcceptanceFinding;
use epiphany_core::build_reorient_acceptance_bundle;
use epiphany_core::build_role_acceptance_bundle;
use epiphany_core::imagination_role_state_patch_policy_errors;
use epiphany_core::modeling_role_state_patch_policy_errors;
use uuid::Uuid;
use super::CodexMessageProcessor;
use super::ConnectionRequestId;
use super::ThreadReadViewError;
use super::epiphany_freshness_watcher_snapshot;
use super::epiphany_state_helpers::client_visible_live_thread_epiphany_state;
use super::epiphany_state_helpers::core_state_patch_from_protocol;
impl CodexMessageProcessor {
pub(super) async fn thread_epiphany_role_launch(
@ -1275,285 +1269,3 @@ impl CodexMessageProcessor {
.await;
}
}
async fn load_completed_epiphany_reorient_finding(
thread: &CodexThread,
state: &EpiphanyThreadState,
binding_id: &str,
) -> CodexResult<ThreadEpiphanyReorientFinding> {
if let Some(link) = latest_epiphany_runtime_link_for_binding(state, binding_id) {
let runtime_store_path = thread.epiphany_runtime_spine_store_path().await;
let (status, finding, _note) = load_epiphany_reorient_result_from_runtime_spine_job(
link.runtime_job_id.as_str(),
Some(runtime_store_path.as_path()),
);
if status != ThreadEpiphanyReorientResultStatus::Completed {
return Err(CodexErr::InvalidRequest(format!(
"cannot accept reorientation result while worker status is {:?}",
status
)));
}
return finding.ok_or_else(|| {
CodexErr::InvalidRequest(
"cannot accept completed reorientation worker because no typed runtime-spine result was recorded"
.to_string(),
)
});
}
if !state
.job_bindings
.iter()
.any(|binding| binding.id == binding_id)
{
return Err(CodexErr::InvalidRequest(format!(
"epiphany reorientation binding {:?} was not found",
binding_id
)));
}
Err(CodexErr::InvalidRequest(
"reorientation findings without runtime-spine results are unsupported; accept only typed runtime-spine results"
.to_string(),
))
}
async fn load_completed_epiphany_role_finding(
thread: &CodexThread,
state: &EpiphanyThreadState,
role_id: ThreadEpiphanyRoleId,
binding_id: &str,
) -> CodexResult<ThreadEpiphanyRoleFinding> {
if let Some(link) = latest_epiphany_runtime_link_for_binding(state, binding_id) {
let runtime_store_path = thread.epiphany_runtime_spine_store_path().await;
let (status, finding, _note) = load_epiphany_role_result_from_runtime_spine_job(
link.runtime_job_id.as_str(),
Some(runtime_store_path.as_path()),
role_id,
);
if status != ThreadEpiphanyRoleResultStatus::Completed {
return Err(CodexErr::InvalidRequest(format!(
"cannot accept role result while worker status is {:?}",
status
)));
}
return finding.ok_or_else(|| {
CodexErr::InvalidRequest(
"cannot accept completed role worker because no typed runtime-spine result was recorded"
.to_string(),
)
});
}
if !state
.job_bindings
.iter()
.any(|binding| binding.id == binding_id)
{
return Err(CodexErr::InvalidRequest(format!(
"epiphany role binding {:?} was not found",
binding_id
)));
}
Err(CodexErr::InvalidRequest(
"role findings without runtime-spine results are unsupported; accept only typed runtime-spine results"
.to_string(),
))
}
fn parse_role_finding_state_patch(
finding: &ThreadEpiphanyRoleFinding,
) -> std::result::Result<ThreadEpiphanyUpdatePatch, String> {
finding
.state_patch
.clone()
.ok_or_else(|| "completed role finding did not include a reviewable statePatch".to_string())
}
pub(super) fn imagination_role_accept_patch_errors(
patch: &ThreadEpiphanyUpdatePatch,
) -> Vec<String> {
imagination_role_state_patch_policy_errors(&core_state_patch_from_protocol(patch))
}
pub(super) fn modeling_role_accept_patch_errors(patch: &ThreadEpiphanyUpdatePatch) -> Vec<String> {
modeling_role_state_patch_policy_errors(&core_state_patch_from_protocol(patch))
}
pub(super) fn role_finding_summary(finding: &ThreadEpiphanyRoleFinding) -> String {
let summary = finding
.summary
.clone()
.unwrap_or_else(|| "Role worker returned a structured finding.".to_string());
if let Some(next_safe_move) = finding.next_safe_move.as_deref() {
format!("{summary} Next safe move: {next_safe_move}")
} else {
summary
}
}
pub(super) fn reorient_finding_code_refs(
finding: &ThreadEpiphanyReorientFinding,
) -> Vec<EpiphanyCodeRef> {
finding
.files_inspected
.iter()
.filter(|path| !path.trim().is_empty())
.map(|path| EpiphanyCodeRef {
path: PathBuf::from(path),
start_line: None,
end_line: None,
symbol: None,
note: Some("Inspected by accepted reorientation worker.".to_string()),
})
.collect()
}
pub(super) fn reorient_finding_scratch(
binding_id: &str,
finding: &ThreadEpiphanyReorientFinding,
) -> EpiphanyScratchPad {
let mode = finding.mode.as_deref().unwrap_or("unknown");
let checkpoint_validity = match finding.checkpoint_still_valid {
Some(true) => "valid",
Some(false) => "invalid",
None => "unknown",
};
EpiphanyScratchPad {
summary: finding.summary.clone(),
hypothesis: Some(format!(
"Accepted {mode} reorientation finding from {binding_id}; checkpoint validity is {checkpoint_validity}."
)),
next_probe: finding.next_safe_move.clone(),
notes: vec![format!(
"Files inspected: {}",
if finding.files_inspected.is_empty() {
"none reported".to_string()
} else {
finding.files_inspected.join(", ")
}
)],
}
}
pub(super) fn reorient_finding_investigation_checkpoint(
checkpoint: &EpiphanyInvestigationCheckpoint,
evidence_id: &str,
code_refs: &[EpiphanyCodeRef],
finding: &ThreadEpiphanyReorientFinding,
) -> EpiphanyInvestigationCheckpoint {
let mut checkpoint = checkpoint.clone();
checkpoint.summary = finding.summary.clone().or(checkpoint.summary);
checkpoint.next_action = finding.next_safe_move.clone().or(checkpoint.next_action);
checkpoint.disposition = EpiphanyInvestigationDisposition::ResumeReady;
if !checkpoint
.evidence_ids
.iter()
.any(|existing| existing == evidence_id)
{
checkpoint.evidence_ids.push(evidence_id.to_string());
}
for code_ref in code_refs {
if !checkpoint
.code_refs
.iter()
.any(|existing| existing.path == code_ref.path)
{
checkpoint.code_refs.push(code_ref.clone());
}
}
checkpoint
}
pub(super) fn epiphany_job_launch_changed_fields() -> Vec<ThreadEpiphanyStateUpdatedField> {
vec![
ThreadEpiphanyStateUpdatedField::JobBindings,
ThreadEpiphanyStateUpdatedField::RuntimeLinks,
]
}
fn thread_epiphany_patch_has_state_replacements(patch: &ThreadEpiphanyUpdatePatch) -> bool {
patch.objective.is_some()
|| patch.active_subgoal_id.is_some()
|| patch.subgoals.is_some()
|| patch.invariants.is_some()
|| patch.graphs.is_some()
|| patch.graph_frontier.is_some()
|| patch.graph_checkpoint.is_some()
|| patch.scratch.is_some()
|| patch.investigation_checkpoint.is_some()
|| patch.job_bindings.is_some()
|| !patch.acceptance_receipts.is_empty()
|| !patch.runtime_links.is_empty()
|| patch.churn.is_some()
|| patch.mode.is_some()
|| patch.planning.is_some()
}
pub(super) fn epiphany_update_patch_changed_fields(
patch: &ThreadEpiphanyUpdatePatch,
) -> Vec<ThreadEpiphanyStateUpdatedField> {
let mut fields = Vec::new();
if patch.objective.is_some() {
fields.push(ThreadEpiphanyStateUpdatedField::Objective);
}
if patch.active_subgoal_id.is_some() {
fields.push(ThreadEpiphanyStateUpdatedField::ActiveSubgoalId);
}
if patch.subgoals.is_some() {
fields.push(ThreadEpiphanyStateUpdatedField::Subgoals);
}
if patch.invariants.is_some() {
fields.push(ThreadEpiphanyStateUpdatedField::Invariants);
}
if patch.graphs.is_some() {
fields.push(ThreadEpiphanyStateUpdatedField::Graphs);
}
if patch.graph_frontier.is_some() {
fields.push(ThreadEpiphanyStateUpdatedField::GraphFrontier);
}
if patch.graph_checkpoint.is_some() {
fields.push(ThreadEpiphanyStateUpdatedField::GraphCheckpoint);
}
if patch.scratch.is_some() {
fields.push(ThreadEpiphanyStateUpdatedField::Scratch);
}
if patch.investigation_checkpoint.is_some() {
fields.push(ThreadEpiphanyStateUpdatedField::InvestigationCheckpoint);
}
if patch.job_bindings.is_some() {
fields.push(ThreadEpiphanyStateUpdatedField::JobBindings);
}
if !patch.acceptance_receipts.is_empty() {
fields.push(ThreadEpiphanyStateUpdatedField::AcceptanceReceipts);
}
if !patch.runtime_links.is_empty() {
fields.push(ThreadEpiphanyStateUpdatedField::RuntimeLinks);
}
if !patch.observations.is_empty() {
fields.push(ThreadEpiphanyStateUpdatedField::Observations);
}
if !patch.evidence.is_empty() {
fields.push(ThreadEpiphanyStateUpdatedField::Evidence);
}
if patch.churn.is_some() {
fields.push(ThreadEpiphanyStateUpdatedField::Churn);
}
if patch.mode.is_some() {
fields.push(ThreadEpiphanyStateUpdatedField::Mode);
}
if patch.planning.is_some() {
fields.push(ThreadEpiphanyStateUpdatedField::Planning);
}
fields
}
pub(super) fn epiphany_promote_changed_fields(
patch: &ThreadEpiphanyUpdatePatch,
) -> Vec<ThreadEpiphanyStateUpdatedField> {
let mut fields = epiphany_update_patch_changed_fields(patch);
if !fields.contains(&ThreadEpiphanyStateUpdatedField::Evidence) {
fields.push(ThreadEpiphanyStateUpdatedField::Evidence);
}
fields
}

View file

@ -27,6 +27,7 @@ use epiphany_codex_bridge::launch::EPIPHANY_REORIENT_LAUNCH_BINDING_ID;
use epiphany_codex_bridge::launch::EPIPHANY_VERIFICATION_ROLE_BINDING_ID;
use epiphany_codex_bridge::launch::epiphany_role_binding_id;
use epiphany_codex_bridge::launch::render_epiphany_coordinator_note;
use epiphany_codex_bridge::mutation::epiphany_modeling_finding_has_reviewable_state_patch;
use epiphany_codex_bridge::pressure::map_epiphany_pressure;
use epiphany_codex_bridge::reorient::map_epiphany_freshness;
use epiphany_codex_bridge::reorient::map_epiphany_reorient;
@ -42,7 +43,6 @@ use super::CodexMessageProcessor;
use super::ConnectionRequestId;
use super::ThreadReadViewError;
use super::epiphany_freshness_watcher_snapshot;
use super::epiphany_state_helpers::epiphany_modeling_finding_has_reviewable_state_patch;
use super::latest_token_usage_info_from_rollout_path;
impl CodexMessageProcessor {

View file

@ -1,80 +1,8 @@
use std::path::Path;
use codex_app_server_protocol::ThreadEpiphanyRoleFinding;
use codex_app_server_protocol::ThreadEpiphanyRoleId;
use codex_app_server_protocol::ThreadEpiphanyUpdatePatch;
use codex_core::CodexThread;
use super::read_rollout_items_from_rollout;
use codex_core::latest_epiphany_state_from_rollout_items;
use codex_protocol::protocol::EpiphanyThreadState;
use epiphany_core::EpiphanyRoleStatePatchDocument;
use super::epiphany_mutation_routes::imagination_role_accept_patch_errors;
use super::epiphany_mutation_routes::modeling_role_accept_patch_errors;
use super::read_rollout_items_from_rollout;
pub(super) async fn live_thread_epiphany_state(
thread: &CodexThread,
) -> Option<EpiphanyThreadState> {
let mut epiphany_state = thread.epiphany_state().await;
if let Some(state) = epiphany_state.as_mut()
&& state.retrieval.is_none()
{
state.retrieval = Some(thread.epiphany_retrieval_state().await);
}
epiphany_state
}
pub(super) async fn client_visible_live_thread_epiphany_state(
thread: &CodexThread,
fallback: EpiphanyThreadState,
) -> EpiphanyThreadState {
live_thread_epiphany_state(thread).await.unwrap_or(fallback)
}
pub(super) fn core_state_patch_from_protocol(
patch: &ThreadEpiphanyUpdatePatch,
) -> EpiphanyRoleStatePatchDocument {
EpiphanyRoleStatePatchDocument {
objective: patch.objective.clone(),
active_subgoal_id: patch.active_subgoal_id.clone(),
subgoals: patch.subgoals.clone(),
invariants: patch.invariants.clone(),
graphs: patch.graphs.clone(),
graph_frontier: patch.graph_frontier.clone(),
graph_checkpoint: patch.graph_checkpoint.clone(),
scratch: patch.scratch.clone(),
investigation_checkpoint: patch.investigation_checkpoint.clone(),
job_bindings: patch.job_bindings.clone(),
acceptance_receipts: patch.acceptance_receipts.clone(),
runtime_links: patch.runtime_links.clone(),
observations: patch.observations.clone(),
evidence: patch.evidence.clone(),
churn: patch.churn.clone(),
mode: patch.mode.clone(),
planning: patch.planning.clone(),
}
}
pub(super) fn epiphany_modeling_finding_has_reviewable_state_patch(
finding: &ThreadEpiphanyRoleFinding,
) -> bool {
finding.role_id == ThreadEpiphanyRoleId::Modeling
&& finding
.state_patch
.as_ref()
.is_some_and(|patch| modeling_role_accept_patch_errors(patch).is_empty())
}
#[cfg(test)]
pub(super) fn epiphany_imagination_finding_has_reviewable_state_patch(
finding: &ThreadEpiphanyRoleFinding,
) -> bool {
finding.role_id == ThreadEpiphanyRoleId::Imagination
&& finding
.state_patch
.as_ref()
.is_some_and(|patch| imagination_role_accept_patch_errors(patch).is_empty())
}
pub(super) async fn load_epiphany_state_from_rollout_path(
rollout_path: &Path,