From 3a2a63377ca6bb74ba276130bb87b42259454e89 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 13 May 2026 01:49:39 +0100 Subject: [PATCH] Extract Epiphany automation orchestration --- notes/fresh-workspace-handoff.md | 10 +- notes/json-contamination-ledger.md | 2 +- state/ledgers.msgpack | Bin 74854 -> 75161 bytes state/map.yaml | 4 +- .../app-server/src/codex_message_processor.rs | 247 +----------------- .../epiphany_automation.rs | 245 +++++++++++++++++ 6 files changed, 259 insertions(+), 249 deletions(-) create mode 100644 vendor/codex/codex-rs/app-server/src/codex_message_processor/epiphany_automation.rs diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 0ab83220..f29ae11e 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -449,13 +449,19 @@ taking the processor to about 15,819 lines. The fourteenth cut moved runtime-spine result snapshot/adaptation helpers into `vendor/codex/codex-rs/app-server/src/codex_message_processor/epiphany_runtime_results.rs`, taking the processor to about 15,587 lines. +The fifteenth cut moved turn-boundary coordinator automation and pre-compaction +intervention orchestration into +`vendor/codex/codex-rs/app-server/src/codex_message_processor/epiphany_automation.rs`, +taking the processor to about 15,346 lines while preserving the old +`codex_message_processor` re-export path for event handling. 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 coordinator automation, -pre-compaction intervention orchestration, and remaining runtime authority out of +Continue with the actual whale-carcass cut: replace child-module parent +visibility with explicit typed service boundaries and move remaining Epiphany +prompt/state/runtime helpers 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 6464ebd4..764254b6 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`, Epiphany JSON-RPC route handling under `codex_message_processor/` split into read/proposal routes and mutation/launch/accept/index routes, mutation support helpers into `epiphany_mutation_routes.rs`, and runtime-spine result snapshot/adaptation helpers into `epiphany_runtime_results.rs`, reducing `codex_message_processor.rs` from about 21,263 to 15,587 lines. Next move coordinator automation and pre-compaction intervention orchestration out of the processor; 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, mutation support helpers into `epiphany_mutation_routes.rs`, runtime-spine result snapshot/adaptation helpers into `epiphany_runtime_results.rs`, and automation/pre-compaction orchestration into `epiphany_automation.rs`, reducing `codex_message_processor.rs` from about 21,263 to 15,346 lines. Next replace child-module parent visibility with explicit typed service boundaries and move remaining Epiphany prompt/state/runtime helpers 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 8c9e63a8f9f2acf14631f4f658c6d5ec75dd6027..936468ea7e1c45aa4ed710fd5fd67c4772e53932 100644 GIT binary patch delta 196 zcmaEMf@S7umI=yCs_`3Dr!g`fYTm=ReGen!6s74CWf_H8Of0R8Cl^lBX8GWjnKr#a znNc~rq_ikcHz~g~FD0?4QXx4%zbGX$FR>)QNFlMbBtJK?Br`uxAu%sSp`a*LH#tAI zATb#%l$lqOT2z*r2j=7#C1<1-mlQ!%1Eum6QVTK*G7|GD;}OP8|ESCus$gtlrjV1F cms+gXu*Jy0$V}J3RM*fr#K6D`&_=Q2+>Z3_t(? diff --git a/state/map.yaml b/state/map.yaml index 8f9c2d4a..e51af184 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 fourteen 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, mutation support helpers moved into `epiphany_mutation_routes.rs`, and runtime-spine result snapshot/adaptation helpers moved into `epiphany_runtime_results.rs`. The processor is down from about 21,263 lines to 15,587 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 and pre-compaction intervention orchestration 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. + summary: The Codex starvation pass has five typing receipts plus fifteen 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, mutation support helpers moved into `epiphany_mutation_routes.rs`, runtime-spine result snapshot/adaptation helpers moved into `epiphany_runtime_results.rs`, and coordinator automation/pre-compaction intervention orchestration moved into `epiphany_automation.rs`. The processor is down from about 21,263 lines to 15,346 lines. This is progress, not absolution: the route/automation 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: replace child-module parent visibility with explicit typed service boundaries, and move remaining Epiphany prompt/state/runtime helpers out of `codex_message_processor.rs`. 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 afa168a6..f02e6165 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,7 +1,10 @@ +mod epiphany_automation; mod epiphany_mutation_routes; mod epiphany_read_routes; mod epiphany_runtime_results; +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_job_launch_changed_fields; use self::epiphany_mutation_routes::epiphany_promote_changed_fields; use self::epiphany_mutation_routes::epiphany_update_patch_changed_fields; @@ -10260,250 +10263,6 @@ fn epiphany_imagination_finding_has_reviewable_state_patch( .is_some_and(|patch| imagination_role_accept_patch_errors(patch).is_empty()) } -pub(crate) async fn maybe_run_epiphany_coordinator_automation_for_turn_boundary( - thread_id: ThreadId, - thread: Arc, - epiphany_invalidation_manager: EpiphanyInvalidationManager, - outgoing: &ThreadScopedOutgoingMessageSender, - force_checkpoint_compaction: bool, -) { - let thread_id_text = thread_id.to_string(); - let Some(state) = thread.epiphany_state().await else { - return; - }; - - let retrieval_override = thread.epiphany_retrieval_state().await; - let config_snapshot = thread.config_snapshot().await; - epiphany_invalidation_manager - .ensure_thread_watch(&thread_id_text, &config_snapshot.cwd) - .await; - let watcher_snapshot = epiphany_invalidation_manager - .snapshot(&thread_id_text) - .await; - let token_usage_info = thread.token_usage_info().await; - let runtime_store_path = thread.epiphany_runtime_spine_store_path().await; - - let (_state_revision, retrieval, graph, watcher) = map_epiphany_freshness( - Some(&state), - Some(&retrieval_override), - Some(&watcher_snapshot), - ); - let pressure = map_epiphany_pressure(token_usage_info.as_ref()); - let (state_status, reorient_decision) = - map_epiphany_reorient(Some(&state), &pressure, &retrieval, &graph, &watcher); - if state_status != ThreadEpiphanyReorientStateStatus::Ready { - return; - } - - let jobs = map_epiphany_jobs(Some(&state), Some(&retrieval_override)); - let reorient_job = jobs - .iter() - .find(|job| job.id == EPIPHANY_REORIENT_LAUNCH_BINDING_ID) - .cloned(); - let (reorient_result_status, reorient_finding, _) = load_epiphany_reorient_result_snapshot( - Some(&state), - Some(runtime_store_path.as_path()), - EPIPHANY_REORIENT_LAUNCH_BINDING_ID, - ) - .await; - let reorient_finding_accepted = reorient_finding - .as_ref() - .is_some_and(|finding| epiphany_reorient_finding_already_accepted(&state, finding)); - let crrc_recommendation = map_epiphany_crrc_recommendation( - true, - state_status, - &pressure, - &reorient_decision, - reorient_result_status, - state.investigation_checkpoint.as_ref().is_some(), - reorient_finding.is_some(), - reorient_finding_accepted, - ); - let roles = map_epiphany_roles( - Some(&state), - &jobs, - &reorient_decision, - &pressure, - &crrc_recommendation, - reorient_result_status, - reorient_job.as_ref(), - ); - let (modeling_result_status, modeling_finding, _) = load_epiphany_role_result_snapshot( - &state, - Some(runtime_store_path.as_path()), - ThreadEpiphanyRoleId::Modeling, - EPIPHANY_MODELING_ROLE_BINDING_ID, - ) - .await; - let modeling_result_accepted = modeling_finding - .as_ref() - .is_some_and(|finding| epiphany_role_finding_already_accepted(&state, finding)); - let modeling_result_reviewable = modeling_finding - .as_ref() - .is_some_and(epiphany_modeling_finding_has_reviewable_state_patch); - let (verification_result_status, verification_finding, _) = load_epiphany_role_result_snapshot( - &state, - Some(runtime_store_path.as_path()), - ThreadEpiphanyRoleId::Verification, - EPIPHANY_VERIFICATION_ROLE_BINDING_ID, - ) - .await; - let verification_result_accepted = verification_finding - .as_ref() - .is_some_and(|finding| epiphany_role_finding_already_accepted(&state, finding)); - let verification_result_covers_current_modeling = - epiphany_verification_finding_covers_current_modeling( - &state, - modeling_result_accepted, - modeling_finding.as_ref(), - verification_finding.as_ref(), - ); - let modeling_result_accepted_after_verification = role_finding_accepted_after( - &state, - modeling_finding.as_ref(), - verification_finding.as_ref(), - ); - let implementation_evidence_after_verification = - implementation_evidence_after_role_finding(&state, verification_finding.as_ref()); - let verification_result_cites_implementation_evidence = - epiphany_role_finding_cites_implementation_evidence(&state, verification_finding.as_ref()); - let verification_result_allows_implementation = verification_result_accepted - && verification_finding - .as_ref() - .is_some_and(epiphany_verification_finding_allows_implementation); - let verification_result_needs_evidence = verification_result_accepted - && verification_finding - .as_ref() - .is_some_and(epiphany_verification_finding_needs_evidence); - let source_signals = ThreadEpiphanyCoordinatorSignals { - pressure_level: pressure.level, - should_prepare_compaction: pressure.should_prepare_compaction, - reorient_action: reorient_decision.action, - crrc_action: crrc_recommendation.action, - modeling_result_status, - verification_result_status, - reorient_result_status, - }; - let coordinator = map_epiphany_coordinator( - state_status, - state.investigation_checkpoint.as_ref().is_some(), - &pressure, - &crrc_recommendation, - &roles, - &source_signals, - modeling_result_accepted, - modeling_result_reviewable, - modeling_result_accepted_after_verification, - implementation_evidence_after_verification, - verification_result_cites_implementation_evidence, - verification_result_covers_current_modeling, - verification_result_accepted, - verification_result_allows_implementation, - verification_result_needs_evidence, - reorient_finding_accepted, - ); - - match select_epiphany_coordinator_automation_action(&coordinator, force_checkpoint_compaction) { - EpiphanyCoordinatorAutomationAction::None => {} - EpiphanyCoordinatorAutomationAction::CompactRehydrateReorient => { - if let Err(err) = thread.submit(Op::Compact).await { - warn!( - "failed to run Epiphany coordinator automatic compaction for {thread_id}: {err}" - ); - } - } - EpiphanyCoordinatorAutomationAction::LaunchReorientWorker => { - let Some(checkpoint) = state.investigation_checkpoint.as_ref() else { - return; - }; - let launch_request = build_epiphany_reorient_launch_request( - &thread_id_text, - Some(state.revision), - None, - &state, - checkpoint, - &reorient_decision, - ); - let launched = match thread.epiphany_launch_job(launch_request).await { - Ok(launched) => launched, - Err(err) => { - warn!( - "failed to launch Epiphany coordinator reorientation worker for {thread_id}: {err}" - ); - return; - } - }; - let epiphany_state = - client_visible_live_thread_epiphany_state(thread.as_ref(), launched.epiphany_state) - .await; - outgoing - .send_server_notification(ServerNotification::ThreadEpiphanyStateUpdated( - ThreadEpiphanyStateUpdatedNotification { - thread_id: thread_id_text, - source: ThreadEpiphanyStateUpdatedSource::JobLaunch, - revision: epiphany_state.revision, - changed_fields: epiphany_job_launch_changed_fields(), - epiphany_state, - }, - )) - .await; - } - } -} - -pub(crate) async fn maybe_run_epiphany_pre_compaction_checkpoint_intervention_for_token_count( - thread_id: ThreadId, - turn_id: String, - thread: Arc, - token_usage_info: Option, - thread_state: &Arc>, -) { - let pressure = map_epiphany_pressure(token_usage_info.as_ref()); - if !should_run_epiphany_pre_compaction_checkpoint_intervention(&pressure) { - return; - } - if thread.epiphany_state().await.is_none() { - return; - } - { - let mut state = thread_state.lock().await; - if state.turn_summary.context_compaction_started { - return; - } - if !state.record_epiphany_checkpoint_intervention(&turn_id) { - return; - } - } - - let text = render_epiphany_pre_compaction_checkpoint_intervention(&pressure); - match thread - .steer_input( - vec![CoreInputItem::Text { - text, - text_elements: Vec::new(), - }], - Some(&turn_id), - None, - ) - .await - { - Ok(_) => { - thread_state - .lock() - .await - .mark_epiphany_checkpoint_intervention_pending_compaction(&turn_id); - } - Err(SteerInputError::NoActiveTurn(_)) - | Err(SteerInputError::ExpectedTurnMismatch { .. }) - | Err(SteerInputError::ActiveTurnNotSteerable { .. }) - | Err(SteerInputError::EmptyInput) => { - warn!( - "failed to steer Epiphany pre-compaction checkpoint intervention for {thread_id}" - ); - } - } -} - 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_automation.rs b/vendor/codex/codex-rs/app-server/src/codex_message_processor/epiphany_automation.rs new file mode 100644 index 00000000..a6c722b0 --- /dev/null +++ b/vendor/codex/codex-rs/app-server/src/codex_message_processor/epiphany_automation.rs @@ -0,0 +1,245 @@ +use super::*; + +pub(crate) async fn maybe_run_epiphany_coordinator_automation_for_turn_boundary( + thread_id: ThreadId, + thread: Arc, + epiphany_invalidation_manager: EpiphanyInvalidationManager, + outgoing: &ThreadScopedOutgoingMessageSender, + force_checkpoint_compaction: bool, +) { + let thread_id_text = thread_id.to_string(); + let Some(state) = thread.epiphany_state().await else { + return; + }; + + let retrieval_override = thread.epiphany_retrieval_state().await; + let config_snapshot = thread.config_snapshot().await; + epiphany_invalidation_manager + .ensure_thread_watch(&thread_id_text, &config_snapshot.cwd) + .await; + let watcher_snapshot = epiphany_invalidation_manager + .snapshot(&thread_id_text) + .await; + let token_usage_info = thread.token_usage_info().await; + let runtime_store_path = thread.epiphany_runtime_spine_store_path().await; + + let (_state_revision, retrieval, graph, watcher) = map_epiphany_freshness( + Some(&state), + Some(&retrieval_override), + Some(&watcher_snapshot), + ); + let pressure = map_epiphany_pressure(token_usage_info.as_ref()); + let (state_status, reorient_decision) = + map_epiphany_reorient(Some(&state), &pressure, &retrieval, &graph, &watcher); + if state_status != ThreadEpiphanyReorientStateStatus::Ready { + return; + } + + let jobs = map_epiphany_jobs(Some(&state), Some(&retrieval_override)); + let reorient_job = jobs + .iter() + .find(|job| job.id == EPIPHANY_REORIENT_LAUNCH_BINDING_ID) + .cloned(); + let (reorient_result_status, reorient_finding, _) = load_epiphany_reorient_result_snapshot( + Some(&state), + Some(runtime_store_path.as_path()), + EPIPHANY_REORIENT_LAUNCH_BINDING_ID, + ) + .await; + let reorient_finding_accepted = reorient_finding + .as_ref() + .is_some_and(|finding| epiphany_reorient_finding_already_accepted(&state, finding)); + let crrc_recommendation = map_epiphany_crrc_recommendation( + true, + state_status, + &pressure, + &reorient_decision, + reorient_result_status, + state.investigation_checkpoint.as_ref().is_some(), + reorient_finding.is_some(), + reorient_finding_accepted, + ); + let roles = map_epiphany_roles( + Some(&state), + &jobs, + &reorient_decision, + &pressure, + &crrc_recommendation, + reorient_result_status, + reorient_job.as_ref(), + ); + let (modeling_result_status, modeling_finding, _) = load_epiphany_role_result_snapshot( + &state, + Some(runtime_store_path.as_path()), + ThreadEpiphanyRoleId::Modeling, + EPIPHANY_MODELING_ROLE_BINDING_ID, + ) + .await; + let modeling_result_accepted = modeling_finding + .as_ref() + .is_some_and(|finding| epiphany_role_finding_already_accepted(&state, finding)); + let modeling_result_reviewable = modeling_finding + .as_ref() + .is_some_and(epiphany_modeling_finding_has_reviewable_state_patch); + let (verification_result_status, verification_finding, _) = load_epiphany_role_result_snapshot( + &state, + Some(runtime_store_path.as_path()), + ThreadEpiphanyRoleId::Verification, + EPIPHANY_VERIFICATION_ROLE_BINDING_ID, + ) + .await; + let verification_result_accepted = verification_finding + .as_ref() + .is_some_and(|finding| epiphany_role_finding_already_accepted(&state, finding)); + let verification_result_covers_current_modeling = + epiphany_verification_finding_covers_current_modeling( + &state, + modeling_result_accepted, + modeling_finding.as_ref(), + verification_finding.as_ref(), + ); + let modeling_result_accepted_after_verification = role_finding_accepted_after( + &state, + modeling_finding.as_ref(), + verification_finding.as_ref(), + ); + let implementation_evidence_after_verification = + implementation_evidence_after_role_finding(&state, verification_finding.as_ref()); + let verification_result_cites_implementation_evidence = + epiphany_role_finding_cites_implementation_evidence(&state, verification_finding.as_ref()); + let verification_result_allows_implementation = verification_result_accepted + && verification_finding + .as_ref() + .is_some_and(epiphany_verification_finding_allows_implementation); + let verification_result_needs_evidence = verification_result_accepted + && verification_finding + .as_ref() + .is_some_and(epiphany_verification_finding_needs_evidence); + let source_signals = ThreadEpiphanyCoordinatorSignals { + pressure_level: pressure.level, + should_prepare_compaction: pressure.should_prepare_compaction, + reorient_action: reorient_decision.action, + crrc_action: crrc_recommendation.action, + modeling_result_status, + verification_result_status, + reorient_result_status, + }; + let coordinator = map_epiphany_coordinator( + state_status, + state.investigation_checkpoint.as_ref().is_some(), + &pressure, + &crrc_recommendation, + &roles, + &source_signals, + modeling_result_accepted, + modeling_result_reviewable, + modeling_result_accepted_after_verification, + implementation_evidence_after_verification, + verification_result_cites_implementation_evidence, + verification_result_covers_current_modeling, + verification_result_accepted, + verification_result_allows_implementation, + verification_result_needs_evidence, + reorient_finding_accepted, + ); + + match select_epiphany_coordinator_automation_action(&coordinator, force_checkpoint_compaction) { + EpiphanyCoordinatorAutomationAction::None => {} + EpiphanyCoordinatorAutomationAction::CompactRehydrateReorient => { + if let Err(err) = thread.submit(Op::Compact).await { + warn!( + "failed to run Epiphany coordinator automatic compaction for {thread_id}: {err}" + ); + } + } + EpiphanyCoordinatorAutomationAction::LaunchReorientWorker => { + let Some(checkpoint) = state.investigation_checkpoint.as_ref() else { + return; + }; + let launch_request = build_epiphany_reorient_launch_request( + &thread_id_text, + Some(state.revision), + None, + &state, + checkpoint, + &reorient_decision, + ); + let launched = match thread.epiphany_launch_job(launch_request).await { + Ok(launched) => launched, + Err(err) => { + warn!( + "failed to launch Epiphany coordinator reorientation worker for {thread_id}: {err}" + ); + return; + } + }; + let epiphany_state = + client_visible_live_thread_epiphany_state(thread.as_ref(), launched.epiphany_state) + .await; + outgoing + .send_server_notification(ServerNotification::ThreadEpiphanyStateUpdated( + ThreadEpiphanyStateUpdatedNotification { + thread_id: thread_id_text, + source: ThreadEpiphanyStateUpdatedSource::JobLaunch, + revision: epiphany_state.revision, + changed_fields: epiphany_job_launch_changed_fields(), + epiphany_state, + }, + )) + .await; + } + } +} + +pub(crate) async fn maybe_run_epiphany_pre_compaction_checkpoint_intervention_for_token_count( + thread_id: ThreadId, + turn_id: String, + thread: Arc, + token_usage_info: Option, + thread_state: &Arc>, +) { + let pressure = map_epiphany_pressure(token_usage_info.as_ref()); + if !should_run_epiphany_pre_compaction_checkpoint_intervention(&pressure) { + return; + } + if thread.epiphany_state().await.is_none() { + return; + } + { + let mut state = thread_state.lock().await; + if state.turn_summary.context_compaction_started { + return; + } + if !state.record_epiphany_checkpoint_intervention(&turn_id) { + return; + } + } + + let text = render_epiphany_pre_compaction_checkpoint_intervention(&pressure); + match thread + .steer_input( + vec![CoreInputItem::Text { + text, + text_elements: Vec::new(), + }], + Some(&turn_id), + None, + ) + .await + { + Ok(_) => { + thread_state + .lock() + .await + .mark_epiphany_checkpoint_intervention_pending_compaction(&turn_id); + } + Err(SteerInputError::NoActiveTurn(_)) + | Err(SteerInputError::ExpectedTurnMismatch { .. }) + | Err(SteerInputError::ActiveTurnNotSteerable { .. }) + | Err(SteerInputError::EmptyInput) => { + warn!( + "failed to steer Epiphany pre-compaction checkpoint intervention for {thread_id}" + ); + } + } +}