From 71c4bbbb28d25d1c922c9a3c1808aa92abc08912 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 13 May 2026 01:43:41 +0100 Subject: [PATCH] Move Epiphany mutation helpers --- notes/fresh-workspace-handoff.md | 10 +- notes/json-contamination-ledger.md | 2 +- state/ledgers.msgpack | Bin 74218 -> 74575 bytes state/map.yaml | 4 +- .../app-server/src/codex_message_processor.rs | 288 +----------------- .../epiphany_mutation_routes.rs | 282 +++++++++++++++++ 6 files changed, 301 insertions(+), 285 deletions(-) diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index ff95af89..412c8f21 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -441,14 +441,18 @@ cut split that route chamber into read/proposal routes at and mutation/launch/accept/index routes at `vendor/codex/codex-rs/app-server/src/codex_message_processor/epiphany_mutation_routes.rs`. The processor is about 16,089 lines after the split; this pass clarified -authority rather than removing another large block. +authority rather than removing another large block. The thirteenth cut moved +mutation support helpers for completed-result loading, accept patch rendering, +patch validation, and changed-field derivation into +`vendor/codex/codex-rs/app-server/src/codex_message_processor/epiphany_mutation_routes.rs`, +taking the processor to about 15,819 lines. 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: move mutation policy and runtime -authority out of the mutation route module and out of +Continue with the actual whale-carcass cut: move coordinator automation, +result snapshot plumbing, and remaining runtime authority out of `codex_message_processor.rs` into Epiphany-owned app-server modules, moving logic further into `epiphany-core` whenever it owns real policy. Success is a visibly smaller `codex_message_processor.rs`, not merely nicer payload names. Do diff --git a/notes/json-contamination-ledger.md b/notes/json-contamination-ledger.md index ecaab0ed..128e32d0 100644 --- a/notes/json-contamination-ledger.md +++ b/notes/json-contamination-ledger.md @@ -62,6 +62,6 @@ Rule: JSON is allowed at external schema/wire boundaries. Inside Epiphany, live 3. Done: replace role `statePatch` JSON with typed map/planning/graph patch documents. `EpiphanyRoleFindingInterpretation` now carries `EpiphanyRoleStatePatchDocument`; app-server maps it to the legacy protocol patch without JSON round-tripping. 4. Done: replace runtime job result JSON projections. Runtime-spine results now project through typed role/reorient interpreters instead of `runtime_job_result_to_role_json` and `runtime_job_result_to_reorient_json`. 5. Done: replace app-server launch protocol `input_json` / `output_schema_json` with typed launch documents and `output_contract_id`. -6. Continue the whale-carcass cut: the first cuts moved Epiphany launch doctrine and protocol-to-core launch document mapping into `epiphany_launch.rs`, role/reorient result projection into `epiphany_results.rs`, scene projection into `epiphany_scene.rs`, freshness/reorientation mapping into `epiphany_reorient.rs`, context/planning/graph-query projection into `epiphany_context.rs`, jobs projection into `epiphany_jobs.rs`, retrieve projection into `epiphany_retrieve.rs`, pressure/pre-compaction checkpoint projection into `epiphany_pressure.rs`, CRRC/coordinator/role-board projection plus acceptance/evidence signal helpers into `epiphany_coordinator.rs`, and Epiphany JSON-RPC route handling under `codex_message_processor/` split into read/proposal routes and mutation/launch/accept/index routes, reducing `codex_message_processor.rs` from about 21,263 to 16,089 lines. Next move mutation policy and runtime authority toward native CultNet/CultCache contracts; success means the processor keeps shrinking and ownership gets clearer, not merely better typed. +6. Continue the whale-carcass cut: the first cuts moved Epiphany launch doctrine and protocol-to-core launch document mapping into `epiphany_launch.rs`, role/reorient result projection into `epiphany_results.rs`, scene projection into `epiphany_scene.rs`, freshness/reorientation mapping into `epiphany_reorient.rs`, context/planning/graph-query projection into `epiphany_context.rs`, jobs projection into `epiphany_jobs.rs`, retrieve projection into `epiphany_retrieve.rs`, pressure/pre-compaction checkpoint projection into `epiphany_pressure.rs`, CRRC/coordinator/role-board projection plus acceptance/evidence signal helpers into `epiphany_coordinator.rs`, Epiphany JSON-RPC route handling under `codex_message_processor/` split into read/proposal routes and mutation/launch/accept/index routes, and mutation support helpers into `epiphany_mutation_routes.rs`, reducing `codex_message_processor.rs` from about 21,263 to 15,819 lines. Next move coordinator automation/result snapshot plumbing and remaining runtime authority out of the processor; success means the processor keeps shrinking and ownership gets clearer, not merely better typed. 7. Seal MCP payloads behind an Epiphany boundary that speaks typed Epiphany documents internally and MCP JSON externally. 8. Audit heartbeat cognition values and either type them or explicitly expire them. diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index bc68b457d5d0b4f35551321a76f46cfef60ee51a..dfe71c858f472715115963b3d1ff71a57f2d7a5f 100644 GIT binary patch delta 242 zcmXwy!Ab%_7=Rh^(oKq>4#i&*bZ}*LT}fX_oXNH-7_iE4sWC-nZ2tk)U z2tilhqn9W%x_*3o-`7WT|Jhu(8}0M$-790er<%Rjj9ozWa>dRXgJknubx&@lnev2a zsv6kkDz_y{$P416tbtHCXFWlN+My4yupWfXokl_#c?^Xn(3VSOmL1?ipd)acL zM1SOepyXP~WA*(_e(r5S7^>AZo7|?Ihu#RZG8np# WZ~eGGjN&xvCDS+_50Y_`&VB&4099H5 delta 49 zcmX?qjOEo~mI=yCiW@enPGe-;-@J!$`yNI{2?eo+Ek*`LX1WHZx`xIf1_oBfmR3fl FQ2@f`4|f0n diff --git a/state/map.yaml b/state/map.yaml index 3bc90dff..e1865459 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -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 plus twelve real ownership cuts: Epiphany launch doctrine/prompt/builders and protocol-to-core launch document mapping moved into `vendor/codex/codex-rs/app-server/src/epiphany_launch.rs`, role/reorient result projection/note rendering moved into `vendor/codex/codex-rs/app-server/src/epiphany_results.rs`, scene projection moved into `vendor/codex/codex-rs/app-server/src/epiphany_scene.rs`, freshness/reorientation input mapping moved into `vendor/codex/codex-rs/app-server/src/epiphany_reorient.rs`, context/planning/graph-query projection moved into `vendor/codex/codex-rs/app-server/src/epiphany_context.rs`, jobs projection moved into `vendor/codex/codex-rs/app-server/src/epiphany_jobs.rs`, retrieve projection moved into `vendor/codex/codex-rs/app-server/src/epiphany_retrieve.rs`, pressure/pre-compaction checkpoint projection moved into `vendor/codex/codex-rs/app-server/src/epiphany_pressure.rs`, CRRC/coordinator/role-board projection plus acceptance/evidence signal helpers moved into `vendor/codex/codex-rs/app-server/src/epiphany_coordinator.rs`, the Epiphany JSON-RPC route-handler cluster moved under `vendor/codex/codex-rs/app-server/src/codex_message_processor/`, and that cluster is now split into read/proposal routes (`epiphany_read_routes.rs`) versus mutation/launch/accept/index routes (`epiphany_mutation_routes.rs`). The processor is down from about 21,263 lines to 16,089 lines. This is progress, not absolution: the route modules still have parent-internal visibility and mutation authority still lives in the Codex adapter layer. 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 the actual whale-carcass cut: move mutation policy and runtime authority out of the mutation route module into `epiphany-core` or native CultNet/CultCache runtime contracts, starting with the launch/accept/update helper duplication. Success metric remains a visibly smaller processor and clearer ownership, not merely typed payloads. + summary: The Codex starvation pass has five typing receipts plus thirteen real ownership cuts: Epiphany launch doctrine/prompt/builders and protocol-to-core launch document mapping moved into `vendor/codex/codex-rs/app-server/src/epiphany_launch.rs`, role/reorient result projection/note rendering moved into `vendor/codex/codex-rs/app-server/src/epiphany_results.rs`, scene projection moved into `vendor/codex/codex-rs/app-server/src/epiphany_scene.rs`, freshness/reorientation input mapping moved into `vendor/codex/codex-rs/app-server/src/epiphany_reorient.rs`, context/planning/graph-query projection moved into `vendor/codex/codex-rs/app-server/src/epiphany_context.rs`, jobs projection moved into `vendor/codex/codex-rs/app-server/src/epiphany_jobs.rs`, retrieve projection moved into `vendor/codex/codex-rs/app-server/src/epiphany_retrieve.rs`, pressure/pre-compaction checkpoint projection moved into `vendor/codex/codex-rs/app-server/src/epiphany_pressure.rs`, CRRC/coordinator/role-board projection plus acceptance/evidence signal helpers moved into `vendor/codex/codex-rs/app-server/src/epiphany_coordinator.rs`, the Epiphany JSON-RPC route-handler cluster moved under `vendor/codex/codex-rs/app-server/src/codex_message_processor/`, that cluster split into read/proposal routes versus mutation/launch/accept/index routes, and mutation support helpers for completed-result loading, accept patch rendering, patch validation, and changed-field derivation moved into `epiphany_mutation_routes.rs`. The processor is down from about 21,263 lines to 15,819 lines. This is progress, not absolution: the route modules still have parent-internal visibility and mutation authority still lives in the Codex adapter layer. 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 the actual whale-carcass cut: move coordinator automation/result snapshot plumbing and remaining runtime authority out of `codex_message_processor.rs`, then replace route-module parent visibility with explicit typed service boundaries. Success metric remains a visibly smaller processor and clearer ownership, not merely typed payloads. diff --git a/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs b/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs index a05ddc78..85ef863d 100644 --- a/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs +++ b/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs @@ -1,6 +1,15 @@ mod epiphany_mutation_routes; mod epiphany_read_routes; +use self::epiphany_mutation_routes::epiphany_job_launch_changed_fields; +use self::epiphany_mutation_routes::epiphany_promote_changed_fields; +use self::epiphany_mutation_routes::epiphany_update_patch_changed_fields; +use self::epiphany_mutation_routes::imagination_role_accept_patch_errors; +use self::epiphany_mutation_routes::modeling_role_accept_patch_errors; +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 crate::bespoke_event_handling::apply_bespoke_event_handling; use crate::bespoke_event_handling::maybe_emit_hook_prompt_item_completed; use crate::command_exec::CommandExecManager; @@ -10483,192 +10492,6 @@ fn latest_epiphany_runtime_link_for_binding<'a>( .find(|link| link.binding_id == binding_id && !link.runtime_job_id.trim().is_empty()) } -async fn load_completed_epiphany_reorient_finding( - thread: &CodexThread, - state: &EpiphanyThreadState, - binding_id: &str, -) -> CodexResult { - 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 { - 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, -) -> Result { - finding - .state_patch - .clone() - .ok_or_else(|| "completed role finding did not include a reviewable statePatch".to_string()) -} - -fn imagination_role_accept_patch_errors(patch: &ThreadEpiphanyUpdatePatch) -> Vec { - imagination_role_state_patch_policy_errors(&core_state_patch_from_protocol(patch)) -} - -fn modeling_role_accept_patch_errors(patch: &ThreadEpiphanyUpdatePatch) -> Vec { - modeling_role_state_patch_policy_errors(&core_state_patch_from_protocol(patch)) -} - -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 - } -} - -fn reorient_finding_code_refs(finding: &ThreadEpiphanyReorientFinding) -> Vec { - 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() -} - -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(", ") - } - )], - } -} - -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(crate) async fn maybe_run_epiphany_coordinator_automation_for_turn_boundary( thread_id: ThreadId, thread: Arc, @@ -10860,13 +10683,6 @@ pub(crate) async fn maybe_run_epiphany_coordinator_automation_for_turn_boundary( } } -fn epiphany_job_launch_changed_fields() -> Vec { - vec![ - ThreadEpiphanyStateUpdatedField::JobBindings, - ThreadEpiphanyStateUpdatedField::RuntimeLinks, - ] -} - pub(crate) async fn maybe_run_epiphany_pre_compaction_checkpoint_intervention_for_token_count( thread_id: ThreadId, turn_id: String, @@ -10920,92 +10736,6 @@ pub(crate) async fn maybe_run_epiphany_pre_compaction_checkpoint_intervention_fo } } -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() -} - -fn epiphany_update_patch_changed_fields( - patch: &ThreadEpiphanyUpdatePatch, -) -> Vec { - 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 -} - -fn epiphany_promote_changed_fields( - patch: &ThreadEpiphanyUpdatePatch, -) -> Vec { - let mut fields = epiphany_update_patch_changed_fields(patch); - if !fields.contains(&ThreadEpiphanyStateUpdatedField::Evidence) { - fields.push(ThreadEpiphanyStateUpdatedField::Evidence); - } - fields -} - pub(crate) fn summary_to_thread( summary: ConversationSummary, fallback_cwd: &AbsolutePathBuf, diff --git a/vendor/codex/codex-rs/app-server/src/codex_message_processor/epiphany_mutation_routes.rs b/vendor/codex/codex-rs/app-server/src/codex_message_processor/epiphany_mutation_routes.rs index 0da2a40d..590f6e4e 100644 --- a/vendor/codex/codex-rs/app-server/src/codex_message_processor/epiphany_mutation_routes.rs +++ b/vendor/codex/codex-rs/app-server/src/codex_message_processor/epiphany_mutation_routes.rs @@ -1222,3 +1222,285 @@ impl CodexMessageProcessor { .await; } } +async fn load_completed_epiphany_reorient_finding( + thread: &CodexThread, + state: &EpiphanyThreadState, + binding_id: &str, +) -> CodexResult { + 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 { + 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, +) -> Result { + 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 { + imagination_role_state_patch_policy_errors(&core_state_patch_from_protocol(patch)) +} + +pub(super) fn modeling_role_accept_patch_errors(patch: &ThreadEpiphanyUpdatePatch) -> Vec { + 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 { + 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 { + 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 { + 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 { + let mut fields = epiphany_update_patch_changed_fields(patch); + if !fields.contains(&ThreadEpiphanyStateUpdatedField::Evidence) { + fields.push(ThreadEpiphanyStateUpdatedField::Evidence); + } + fields +}