From 1662a012c0214f0a99526b8bbb8273be431e6ce1 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 18 Aug 2026 04:18:02 +0200 Subject: [PATCH] Route coordinator from keyed current work --- .../src/bin/epiphany-mvp-coordinator.rs | 818 +----- epiphany-core/src/bin/epiphany-mvp-status.rs | 1477 ++-------- epiphany-core/src/current_work.rs | 464 ++++ epiphany-core/src/lib.rs | 6 - epiphany-core/src/runtime_spine.rs | 6 +- epiphany-core/src/surfaces/coordinator.rs | 2425 +++-------------- .../src/surfaces/coordinator_contract.rs | 158 +- epiphany-core/src/surfaces/jobs.rs | 632 +---- epiphany-core/src/surfaces/mod.rs | 3 - epiphany-core/src/surfaces/planning.rs | 41 +- epiphany-core/src/surfaces/role_board.rs | 705 ++--- epiphany-core/src/surfaces/scene.rs | 222 +- 12 files changed, 1734 insertions(+), 5223 deletions(-) diff --git a/epiphany-core/src/bin/epiphany-mvp-coordinator.rs b/epiphany-core/src/bin/epiphany-mvp-coordinator.rs index c9796cfc..f2df58eb 100644 --- a/epiphany-core/src/bin/epiphany-mvp-coordinator.rs +++ b/epiphany-core/src/bin/epiphany-mvp-coordinator.rs @@ -39,7 +39,6 @@ use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::thread; use std::time::Duration; -use std::time::Instant; use uuid::Uuid; #[cfg(windows)] @@ -78,7 +77,6 @@ struct Args { codex_home: PathBuf, mcp_config: PathBuf, artifact_dir: PathBuf, - agent_memory_dir: PathBuf, runtime_store: PathBuf, local_verse_store: PathBuf, mode: String, @@ -117,7 +115,6 @@ impl Args { .unwrap_or_else(|| home_dir().join(".codex")), mcp_config: root.join(".epiphany").join("mcp.toml"), artifact_dir: root.join(".epiphany-dogfood").join("coordinator"), - agent_memory_dir: root.join("state").join("agents.msgpack"), runtime_store: root.join("state").join("runtime-spine.msgpack"), local_verse_store: root .join(".epiphany-run") @@ -203,9 +200,6 @@ impl Args { "--codex-home" => parsed.codex_home = take_path(&mut args, "--codex-home")?, "--mcp-config" => parsed.mcp_config = take_path(&mut args, "--mcp-config")?, "--artifact-dir" => parsed.artifact_dir = take_path(&mut args, "--artifact-dir")?, - "--agent-memory-dir" => { - parsed.agent_memory_dir = take_path(&mut args, "--agent-memory-dir")?; - } "--runtime-store" => { parsed.runtime_store = take_path(&mut args, "--runtime-store")? } @@ -291,7 +285,6 @@ fn run_coordinator(args: &Args) -> Result { let codex_home = status_cli::absolute_path(&args.codex_home)?; let mcp_config = status_cli::absolute_path(&args.mcp_config)?; let artifact_dir = status_cli::absolute_path(&args.artifact_dir)?; - let agent_memory_dir = status_cli::absolute_path(&args.agent_memory_dir)?; let runtime_store = status_cli::absolute_path(&args.runtime_store)?; reset_artifact_dir(&artifact_dir)?; fs::create_dir_all(&codex_home)?; @@ -387,32 +380,14 @@ fn run_coordinator(args: &Args) -> Result { "typed consideration cannot share operator objective intake" )); } - let service = epiphany_core::EpiphanyCoordinatorService::new(&runtime_store); - let state = service - .state()? - .ok_or_else(|| anyhow!("consideration launch requires coordinator state"))?; - let request = epiphany_core::build_epiphany_imagination_consideration_launch_request( - &thread_id, - Some(state.revision), - Some(args.max_runtime_seconds), - &state, - request_id.to_string(), - ) - .map_err(anyhow::Error::msg)?; - let launched = service.launch_job( - &thread_id, - &state, - &request, - format!("epiphany-resident-consideration-launch-{}", Uuid::new_v4()), - Uuid::new_v4().to_string(), - now(), + let worker_job_id = epiphany_core::launch_current_imagination_consideration_work( + &runtime_store, + request_id, + &now(), )?; - let worker_job_id = launched.backend_job_id.clone(); let operator_launch = json!({ - "bindingId": launched.binding_id, - "launcherJobId": launched.launcher_job_id, - "backendJobId": launched.backend_job_id, - "stateRevision": launched.epiphany_state.revision, + "bindingId": epiphany_core::EPIPHANY_IMAGINATION_ROLE_BINDING_ID, + "backendJobId": worker_job_id.clone(), }); let worker_run = launch_worker_runtime_detached( &model_runtime_bin, @@ -449,31 +424,12 @@ fn run_coordinator(args: &Args) -> Result { "typed model direction consideration requires exclusive objective-free intake" )); } - let service = epiphany_core::EpiphanyCoordinatorService::new(&runtime_store); - let state = service - .state()? - .ok_or_else(|| anyhow!("model direction launch requires coordinator state"))?; - let request = - epiphany_core::build_epiphany_admitted_model_direction_consideration_launch_request( - &thread_id, - Some(state.revision), - Some(args.max_runtime_seconds), - &state, - request_id.to_string(), - ) - .map_err(anyhow::Error::msg)?; - let launched = service.launch_job( - &thread_id, - &state, - &request, - format!( - "epiphany-resident-model-direction-launch-{}", - Uuid::new_v4() - ), - Uuid::new_v4().to_string(), - now(), - )?; - let worker_job_id = launched.backend_job_id.clone(); + let worker_job_id = + epiphany_core::launch_current_admitted_model_direction_consideration_work( + &runtime_store, + request_id, + &now(), + )?; let worker_run = launch_worker_runtime_detached( &model_runtime_bin, &tool_adapter_bin, @@ -586,7 +542,6 @@ fn run_coordinator(args: &Args) -> Result { "index": index, "action": action, "coordinator": coordinator, - "stateRevision": state_revision(&status), "events": [], }); final_status = status.clone(); @@ -617,7 +572,11 @@ fn run_coordinator(args: &Args) -> Result { if action == "awaitFrontierProposal" || matches!( action.as_str(), - "waitForModelingResult" | "waitForImaginationResult" | "waitForMindPlanResult" + "waitForModelingResult" + | "waitForImaginationResult" + | "waitForMindPlanResult" + | "waitForImaginationConsideration" + | "waitForAdmittedModelDirectionConsideration" ) || (action == "reviewFrontierPlanningFailure" && !args.supersede_failed_results) || (is_stop_action(&action) @@ -629,7 +588,6 @@ fn run_coordinator(args: &Args) -> Result { break; } - let revision = state_revision(&status); match action.as_str() { "reviewFrontierPlanningFailure" => { let lifecycle = @@ -958,103 +916,9 @@ fn run_coordinator(args: &Args) -> Result { steps.push(step); continue; } - let result = read_role_result(&runtime_store, &thread_id, role_id)?; - push_event( - &mut step, - json!({"type": "roleResult", "roleId": role_id, "result": status_cli::sanitize_for_operator(result.clone())}), - ); - if !matches!( - result["status"].as_str(), - Some("completed" | "failed" | "cancelled") - ) { - final_action = json!({ - "action": wait_action_for_role(role_id), - "reason": result["note"], - }); - append_operator_step_jsonl(&steps_path, &step)?; - steps.push(step); - break; - } - if args.supersede_failed_results - && role_result_needs_supersession(role_id, &result) - { - let superseded = supersede_role_result( - &runtime_store, - &thread_id, - role_id, - revision, - &result, - )?; - push_event( - &mut step, - json!({"type": "roleFailureReview", "roleId": role_id, "superseded": status_cli::sanitize_for_operator(superseded)}), - ); - final_status = collect_coordinator_status(&runtime_store, &thread_id)?; - refresh_final_action_from_status(&final_status, &mut final_action); - append_operator_step_jsonl(&steps_path, &step)?; - steps.push(step); - continue; - } - let can_accept = args.auto_review - && role_result_auto_acceptable(role_id, &result) - && revision.is_some(); - if !can_accept { - final_action = json!({ - "action": review_action_for_role(role_id), - "reason": result["note"] - }); - append_operator_step_jsonl(&steps_path, &step)?; - steps.push(step); - break; - } - let accepted = match accept_role( - &runtime_store, - &thread_id, - role_id, - revision.and_then(|value| u64::try_from(value).ok()), - ) { - Ok(accepted) => accepted, - Err(error) if args.supersede_failed_results => { - let superseded = supersede_role_result( - &runtime_store, - &thread_id, - role_id, - revision, - &result, - )?; - push_event( - &mut step, - json!({ - "type": "roleAdmissionRejected", - "roleId": role_id, - "error": format!("{error:#}"), - "superseded": status_cli::sanitize_for_operator(superseded), - }), - ); - final_status = collect_coordinator_status(&runtime_store, &thread_id)?; - refresh_final_action_from_status(&final_status, &mut final_action); - append_operator_step_jsonl(&steps_path, &step)?; - steps.push(step); - continue; - } - Err(error) => return Err(error), - }; - if let Some(memory) = maybe_apply_role_self_patch(&accepted, &agent_memory_dir)? - { - let mut accepted_with_memory = accepted.clone(); - accepted_with_memory["selfMemoryApply"] = memory; - push_event( - &mut step, - json!({"type": "roleAccept", "roleId": role_id, "accepted": status_cli::sanitize_for_operator(accepted_with_memory)}), - ); - } else { - push_event( - &mut step, - json!({"type": "roleAccept", "roleId": role_id, "accepted": status_cli::sanitize_for_operator(accepted)}), - ); - } - final_status = collect_coordinator_status(&runtime_store, &thread_id)?; - refresh_final_action_from_status(&final_status, &mut final_action); + return Err(anyhow!( + "{role_id} review has no keyed current-work owner; generic role-lane review is retired" + )); } "reviewReorientResult" => { let result = read_reorient_result(&runtime_store, &thread_id)?; @@ -1119,28 +983,110 @@ fn run_coordinator(args: &Args) -> Result { steps.push(step); break; } + "launchImaginationConsideration" => { + let work = epiphany_core::project_current_work(&runtime_store)? + .imagination_considerations + .into_iter() + .next() + .ok_or_else(|| { + anyhow!("no current Persona-feedback Imagination consideration exists") + })?; + let worker_job_id = + epiphany_core::launch_current_imagination_consideration_work( + &runtime_store, + &work.request.request_id, + &now(), + )?; + push_event( + &mut step, + json!({ + "type": "imaginationConsiderationLaunch", + "requestId": work.request.request_id, + "runtimeJobId": worker_job_id, + }), + ); + let worker_run = launch_worker_runtime_detached( + &model_runtime_bin, + &tool_adapter_bin, + &args.model_provider, + &runtime_store, + &codex_home, + &mcp_config, + &cwd, + args.resident_state_store.as_deref(), + &worker_job_id, + "imagination", + index, + &artifact_dir, + args.max_runtime_seconds, + args.auto_tools, + )?; + push_event( + &mut step, + json!({"type": "workerRuntime", "roleId": "imagination", "run": worker_run}), + ); + final_status = collect_coordinator_status(&runtime_store, &thread_id)?; + } + "launchAdmittedModelDirectionConsideration" => { + let work = epiphany_core::project_current_work(&runtime_store)? + .admitted_model_direction_consideration + .ok_or_else(|| { + anyhow!("no current admitted-model direction consideration exists") + })?; + let worker_job_id = + epiphany_core::launch_current_admitted_model_direction_consideration_work( + &runtime_store, + &work.request.request_id, + &now(), + )?; + push_event( + &mut step, + json!({ + "type": "admittedModelDirectionConsiderationLaunch", + "requestId": work.request.request_id, + "runtimeJobId": worker_job_id, + }), + ); + let worker_run = launch_worker_runtime_detached( + &model_runtime_bin, + &tool_adapter_bin, + &args.model_provider, + &runtime_store, + &codex_home, + &mcp_config, + &cwd, + args.resident_state_store.as_deref(), + &worker_job_id, + "imagination", + index, + &artifact_dir, + args.max_runtime_seconds, + args.auto_tools, + )?; + push_event( + &mut step, + json!({"type": "workerRuntime", "roleId": "imagination", "run": worker_run}), + ); + final_status = collect_coordinator_status(&runtime_store, &thread_id)?; + } "launchResearch" | "launchModeling" | "launchVerification" => { let role_id = role_id_for_coordinator_action(&action) .ok_or_else(|| anyhow!("unsupported launch action {action}"))?; let pending_proposal_request_id = if role_id == "modeling" { - status["findingSignals"]["pendingProposalModelingRequestId"].as_str() + epiphany_core::project_current_work(&runtime_store)? + .proposal_modeling + .map(|work| work.request.request_id) } else { None }; let proposal_modeling_request_id = if role_id == "modeling" { resolve_proposal_modeling_request_hint( args.proposal_modeling_request_id.as_deref(), - pending_proposal_request_id, + pending_proposal_request_id.as_deref(), )? } else { None }; - let thread_free_role = role_id == "research" - || role_id == "verification" - || (role_id == "modeling" - && (proposal_modeling_request_id.is_some() - || status["currentWork"]["bodyModeling"].is_object() - || status["currentWork"]["frontierVerdictModeling"].is_object())); let launch = if role_id == "research" { let job_id = epiphany_core::launch_current_frontier_research_work( &runtime_store, @@ -1212,14 +1158,9 @@ fn run_coordinator(args: &Args) -> Result { "backendJobId": job_id, }) } else { - launch_role( - &runtime_store, - &local_verse_store, - &thread_id, - role_id, - revision, - args.max_runtime_seconds, - )? + return Err(anyhow!( + "{role_id} launch has no keyed current-work owner; generic role-lane launch is retired" + )); }; let worker_job_id = worker_job_id_from_launch(&launch)?; push_event( @@ -1246,22 +1187,18 @@ fn run_coordinator(args: &Args) -> Result { &mut step, json!({"type": "workerRuntime", "roleId": role_id, "run": worker_run}), ); - let result = if thread_free_role { - match epiphany_core::runtime_role_worker_result( - &runtime_store, - &worker_job_id, - )? { - Some(result) => json!({ - "status": "completed", - "note": result.summary, - }), - None => json!({ - "status": "running", - "note": "The exact keyed role attempt has not produced a terminal result.", - }), - } - } else { - read_role_result(&runtime_store, &thread_id, role_id)? + let result = match epiphany_core::runtime_role_worker_result( + &runtime_store, + &worker_job_id, + )? { + Some(result) => json!({ + "status": "completed", + "note": result.summary, + }), + None => json!({ + "status": "running", + "note": "The exact keyed role attempt has not produced a terminal result.", + }), }; push_event( &mut step, @@ -1293,13 +1230,7 @@ fn run_coordinator(args: &Args) -> Result { } } "launchReorientWorker" => { - let launch = launch_reorient( - &runtime_store, - &local_verse_store, - &thread_id, - revision, - args.max_runtime_seconds, - )?; + let launch = launch_reorient(&runtime_store)?; let worker_job_id = worker_job_id_from_launch(&launch)?; push_event( &mut step, @@ -1559,8 +1490,7 @@ fn intake_operator_objective( thread_id: &str, objective: &str, ) -> Result { - let service = epiphany_core::EpiphanyCoordinatorService::new(runtime_store); - service.intake_user_objective(epiphany_core::UserObjectiveIntakeInput { + epiphany_core::intake_user_objective(runtime_store, epiphany_core::UserObjectiveIntakeInput { thread_id: thread_id.to_string(), objective: objective.to_string(), source_actor: "operator".to_string(), @@ -1781,126 +1711,6 @@ fn hands_record_pass_command( }) } -fn launch_role( - runtime_store: &Path, - local_verse_store: &Path, - thread_id: &str, - role_id: &str, - expected_revision: Option, - max_runtime_seconds: u64, -) -> Result { - let started = Instant::now(); - let service = epiphany_core::EpiphanyCoordinatorService::new(runtime_store); - let state = service - .state()? - .ok_or_else(|| anyhow!("cannot launch role without native coordinator state"))?; - let state_loaded_ms = started.elapsed().as_millis(); - let role = parse_role_id(role_id)?; - if role == epiphany_core::EpiphanyRoleResultRoleId::Research { - return Err(anyhow!( - "Research launch must use the keyed frontier Research current-work owner" - )); - } - if role == epiphany_core::EpiphanyRoleResultRoleId::Verification { - return Err(anyhow!( - "Verification launch must use the keyed frontier Verification current-work owner" - )); - } - let expected_revision = expected_revision.and_then(|value| u64::try_from(value).ok()); - let focus = - epiphany_core::role_launch_context_focus(&state, epiphany_core::epiphany_role_label(role)); - let context = if role == epiphany_core::EpiphanyRoleResultRoleId::Modeling { - epiphany_core::render_modeling_launch_dynamic_prompt_context( - runtime_store, - local_verse_store, - &state, - focus, - ) - } else { - epiphany_core::render_launch_dynamic_prompt_context( - runtime_store, - local_verse_store, - &state, - focus, - ) - } - .map_err(anyhow::Error::msg)?; - let dynamic_context_rendered_ms = started.elapsed().as_millis(); - let role_context_augmented_ms = started.elapsed().as_millis(); - let request = epiphany_core::build_epiphany_role_launch_request_with_dynamic_context( - thread_id, - role, - expected_revision, - Some(max_runtime_seconds), - &state, - Some(context), - ) - .map_err(anyhow::Error::msg)?; - let request_built_ms = started.elapsed().as_millis(); - let launched = service.launch_job( - thread_id, - &state, - &request, - format!("epiphany-heartbeat-launch-{}", Uuid::new_v4()), - Uuid::new_v4().to_string(), - now(), - )?; - let job_committed_ms = started.elapsed().as_millis(); - Ok(json!({ - "bindingId": launched.binding_id, - "launcherJobId": launched.launcher_job_id, - "backendJobId": launched.backend_job_id, - "revision": launched.epiphany_state.revision, - "state": launched.epiphany_state, - "timingsMs": { - "stateLoad": state_loaded_ms, - "dynamicContextRender": dynamic_context_rendered_ms.saturating_sub(state_loaded_ms), - "roleContextAugment": role_context_augmented_ms.saturating_sub(dynamic_context_rendered_ms), - "requestBuild": request_built_ms.saturating_sub(role_context_augmented_ms), - "jobCommit": job_committed_ms.saturating_sub(request_built_ms), - "total": job_committed_ms, - }, - })) -} - -fn accept_role( - runtime_store: &Path, - thread_id: &str, - role_id: &str, - expected_revision: Option, -) -> Result { - let service = epiphany_core::EpiphanyCoordinatorService::new(runtime_store); - let state = service - .state()? - .ok_or_else(|| anyhow!("cannot accept role without native coordinator state"))?; - let role = parse_role_id(role_id)?; - if role == epiphany_core::EpiphanyRoleResultRoleId::Verification { - return Err(anyhow!( - "Verification acceptance must use the keyed frontier Verification current-work owner" - )); - } - let accepted = service.accept_role( - thread_id, - &state, - role, - &default_binding_id_for_role(role_id), - expected_revision, - None, - now(), - &Uuid::new_v4().to_string(), - )?; - Ok(json!({ - "roleId": role, - "revision": accepted.state.revision, - "state": accepted.state, - "acceptedReceiptId": accepted.update.accepted_receipt_id, - "acceptedObservationId": accepted.update.accepted_observation_id, - "acceptedEvidenceId": accepted.update.accepted_evidence_id, - "appliedPatch": accepted.update.applied_patch, - "finding": accepted.finding, - })) -} - fn accept_reorient(runtime_store: &Path) -> Result { let work = epiphany_core::project_current_work(runtime_store)? .reorientation @@ -1928,16 +1738,6 @@ fn accept_reorient(runtime_store: &Path) -> Result { })) } -fn parse_role_id(role_id: &str) -> Result { - match role_id { - "imagination" => Ok(epiphany_core::EpiphanyRoleResultRoleId::Imagination), - "research" => Ok(epiphany_core::EpiphanyRoleResultRoleId::Research), - "modeling" => Ok(epiphany_core::EpiphanyRoleResultRoleId::Modeling), - "verification" => Ok(epiphany_core::EpiphanyRoleResultRoleId::Verification), - _ => Err(anyhow!("unsupported coordinator role {role_id:?}")), - } -} - fn role_id_for_coordinator_action(action: &str) -> Option<&'static str> { match action { "launchResearch" | "reviewResearchResult" => Some("research"), @@ -1965,37 +1765,6 @@ fn review_action_for_role(role_id: &str) -> &'static str { } } -fn role_result_auto_acceptable(role_id: &str, result: &Value) -> bool { - if result["status"].as_str() != Some("completed") { - return false; - } - let finding = &result["finding"]; - if finding["jobError"].is_string() || finding["itemError"].is_string() { - return false; - } - let has_runtime_identity = finding["runtimeResultId"] - .as_str() - .is_some_and(|id| !id.trim().is_empty()) - && finding["runtimeJobId"] - .as_str() - .is_some_and(|id| !id.trim().is_empty()); - if !has_runtime_identity { - return false; - } - match role_id { - "verification" => true, - "research" | "imagination" => finding["statePatch"].is_object(), - "modeling" => { - finding["repoModelMutationProposal"].is_object() - || (matches!( - finding["verdict"].as_str(), - Some("checkpoint-ready" | "regather-needed") - ) && finding["repoModelMutationProposal"].is_null()) - } - _ => false, - } -} - fn reorient_result_auto_acceptable(result: &Value) -> bool { if result["status"].as_str() != Some("completed") { return false; @@ -2015,106 +1784,8 @@ fn reorient_result_auto_acceptable(result: &Value) -> bool { && !finding["itemError"].is_string() } -fn role_result_needs_supersession(role_id: &str, result: &Value) -> bool { - match result["status"].as_str() { - Some("failed") => true, - Some("completed") if matches!(role_id, "research" | "modeling" | "imagination") => { - !role_result_auto_acceptable(role_id, result) - } - _ => false, - } -} - -fn supersede_role_result( - runtime_store: &Path, - thread_id: &str, - role_id: &str, - expected_revision: Option, - result: &Value, -) -> Result { - let result_id = first_string_at(result, &[&["finding", "runtimeResultId"]]) - .context("failed role result did not include finding.runtimeResultId")?; - let job_id = first_string_at(result, &[&["finding", "runtimeJobId"]]) - .context("failed role result did not include finding.runtimeJobId")?; - let binding_id = first_string_at(result, &[&["bindingId"]]) - .unwrap_or_else(|| default_binding_id_for_role(role_id)); - let summary = first_string_at(result, &[&["finding", "summary"], &["note"]]) - .unwrap_or_else(|| "Role result reviewed and superseded.".to_string()); - let service = epiphany_core::EpiphanyCoordinatorService::new(runtime_store); - if let Some(state) = service.state()? - && let Some(existing) = state - .acceptance_receipts - .iter() - .find(|receipt| receipt.result_id == result_id) - { - if existing.job_id == job_id - && existing.binding_id == binding_id - && existing.surface == "roleFailureReview" - && existing.role_id == role_id - && existing.status == "superseded" - { - return Ok(json!({ - "revision": state.revision, - "changedFields": [], - "state": state, - "receipt": existing, - "changed": false, - })); - } - return Err(anyhow!( - "runtime result already has conflicting acceptance authority: surface={:?} role={:?} status={:?} binding={:?}", - existing.surface, - existing.role_id, - existing.status, - existing.binding_id - )); - } - let receipt = epiphany_state_model::EpiphanyAcceptanceReceipt { - id: format!("role-failure-review-{}", Uuid::new_v4()), - result_id, - job_id, - binding_id, - surface: "roleFailureReview".to_string(), - role_id: role_id.to_string(), - status: "superseded".to_string(), - accepted_at: now(), - accepted_observation_id: None, - accepted_evidence_id: None, - summary: Some(summary), - }; - let applied = service.apply_state_update( - thread_id, - epiphany_core::EpiphanyStateUpdate { - expected_revision: expected_revision.and_then(|value| u64::try_from(value).ok()), - acceptance_receipts: vec![receipt.clone()], - ..Default::default() - }, - None, - )?; - Ok(json!({ - "revision": applied.revision, - "changedFields": applied.changed_fields.iter().map(|field| format!("{field:?}")).collect::>(), - "state": applied.state, - "receipt": receipt, - })) -} - -fn default_binding_id_for_role(role_id: &str) -> String { - match role_id { - "imagination" => epiphany_core::EPIPHANY_IMAGINATION_ROLE_BINDING_ID.to_string(), - "research" => epiphany_core::EPIPHANY_RESEARCH_ROLE_BINDING_ID.to_string(), - "modeling" => epiphany_core::EPIPHANY_MODELING_ROLE_BINDING_ID.to_string(), - "verification" => epiphany_core::EPIPHANY_VERIFICATION_ROLE_BINDING_ID.to_string(), - _ => role_id.to_string(), - } -} - fn launch_reorient( runtime_store: &Path, - _local_verse_store: &Path, - _thread_id: &str, - _expected_revision: Option, - _max_runtime_seconds: u64, ) -> Result { let requested_at = now(); let request = epiphany_core::request_current_reorientation(runtime_store, &requested_at)?; @@ -2254,10 +1925,6 @@ fn launch_worker_runtime_detached( })) } -fn read_role_result(runtime_store: &Path, thread_id: &str, role_id: &str) -> Result { - Ok(collect_coordinator_status(runtime_store, thread_id)?["roleResults"][role_id].clone()) -} - fn read_reorient_result(runtime_store: &Path, _thread_id: &str) -> Result { let Some(work) = epiphany_core::project_current_work(runtime_store)?.reorientation else { return Ok(json!({ @@ -2289,43 +1956,6 @@ fn read_reorient_result(runtime_store: &Path, _thread_id: &str) -> Result Ok(value) } -fn maybe_apply_role_self_patch(accepted: &Value, agent_memory_dir: &Path) -> Result> { - let finding = &accepted["finding"]; - let self_patch = &finding["selfPatch"]; - let review = &finding["selfPersistence"]; - if !self_patch.is_object() || !review.is_object() { - return Ok(None); - } - if review["status"].as_str() != Some("accepted") { - return Ok(Some(json!({ - "status": "rejected", - "targetAgentId": review["targetAgentId"], - "targetPath": review["targetPath"], - "reasons": review["reasons"], - "applied": false, - }))); - } - let role_id = accepted["roleId"] - .as_str() - .ok_or_else(|| anyhow!("roleAccept response did not include roleId"))?; - let patch = serde_json::to_string(self_patch)?; - let output = status_cli::native_json( - "epiphany-agent-memory-store", - &[ - "apply-patch", - "--store", - &agent_memory_dir.to_string_lossy(), - "--role-id", - role_id, - "--patch", - &patch, - ], - )?; - let mut output = output; - output["appliedFromRoleAccept"] = json!(true); - Ok(Some(output)) -} - fn first_string_at(value: &Value, paths: &[&[&str]]) -> Option { 'paths: for path in paths { let mut cursor = value; @@ -2468,21 +2098,6 @@ fn reset_artifact_dir(path: &Path) -> Result<()> { Ok(()) } -fn state_revision(status: &Value) -> Option { - status - .pointer("/scene/scene/revision") - .and_then(Value::as_i64) -} - -fn refresh_final_action_from_status(status: &Value, final_action: &mut Value) { - if let Some(coordinator) = status - .get("coordinator") - .filter(|value| value.get("action").and_then(Value::as_str).is_some()) - { - *final_action = coordinator.clone(); - } -} - fn push_event(step: &mut Value, event: Value) { step["events"].as_array_mut().unwrap().push(event); } @@ -2553,22 +2168,6 @@ fn home_dir() -> PathBuf { mod tests { use super::*; - #[test] - fn role_review_receipt_uses_the_post_transaction_coordinator_action() { - let mut final_action = json!({"action": "reviewModelingResult"}); - let status = json!({ - "coordinator": { - "action": "awaitFrontierProposal", - "reason": "The proposal-bound result was terminally reviewed." - } - }); - refresh_final_action_from_status(&status, &mut final_action); - assert_eq!(final_action["action"], "awaitFrontierProposal"); - - refresh_final_action_from_status(&json!({"coordinator": {}}), &mut final_action); - assert_eq!(final_action["action"], "awaitFrontierProposal"); - } - #[test] fn resident_required_action_refusal_precedes_the_action_match() { let source = include_str!("epiphany-mvp-coordinator.rs"); @@ -2630,7 +2229,6 @@ mod tests { codex_home: temp.path().join("codex-home"), mcp_config: cwd.join(".epiphany/mcp.toml"), artifact_dir: cwd.join(".epiphany-smoke/error-terminalization"), - agent_memory_dir: temp.path().join("mind.cc"), runtime_store: runtime_store.clone(), local_verse_store: temp.path().join("local-verse.cc"), mode: "plan".to_string(), @@ -2707,53 +2305,30 @@ mod tests { } #[test] - fn coordinator_status_and_result_reads_are_native() { + fn coordinator_uses_keyed_family_owners_without_generic_role_routing() { let source = include_str!("epiphany-mvp-coordinator.rs"); - let status_start = source.find("fn collect_coordinator_status").unwrap(); - let status_end = source.find("fn resolve_model_runtime_bin").unwrap(); - let status = &source[status_start..status_end]; - assert!(status.contains("native_coordinator_json")); - assert!(!status.contains("native_json(")); - assert!(!status.contains("Command::new")); - assert!(!status.contains("--native")); - assert!(!status.contains("AppServerClient")); - assert!(!status.contains("thread/epiphany/")); - - let reads_start = source.find("fn read_role_result").unwrap(); - let reads_end = source.find("fn maybe_apply_role_self_patch").unwrap(); - let reads = &source[reads_start..reads_end]; - assert!(reads.contains("collect_coordinator_status")); - assert!(!reads.contains("AppServerClient")); - assert!(!reads.contains("thread/epiphany/")); - } - - #[test] - fn coordinator_role_launch_and_acceptance_are_native() { - let source = include_str!("epiphany-mvp-coordinator.rs"); - let start = source.find("fn launch_role").unwrap(); - let end = source.find("fn role_id_for_coordinator_action").unwrap(); - let native_roles = &source[start..end]; + let production = source.split("#[cfg(test)]").next().unwrap_or(source); for required in [ - "render_launch_dynamic_prompt_context", - "render_modeling_launch_dynamic_prompt_context", - ".launch_job(", - ".accept_role(", + "launch_current_imagination_consideration_work", + "launch_current_admitted_model_direction_consideration_work", + "launch_current_frontier_research_work", + "launch_current_frontier_verification_work", ] { - assert!( - native_roles.contains(required), - "missing native role seam {required:?}" - ); + assert!(production.contains(required), "missing keyed owner {required:?}"); } for forbidden in [ - concat!("append_modeling_work_loop_telemetry_", "context"), - concat!("accepted_research_is_newest_", "unmodeled_boundary"), - concat!("append_verification_hands_receipt_", "context"), + "fn launch_role(", + "fn accept_role(", + "fn supersede_role_result(", + ".apply_state_update(", + ".accept_role(", + "stateRevision", ] { - assert!(!source.contains(forbidden)); + assert!( + !production.contains(forbidden), + "generic aggregate role authority survived: {forbidden:?}" + ); } - assert!(!native_roles.contains("append_modeling_repo_model_shape_context(")); - assert!(!native_roles.contains("AppServerClient")); - assert!(!native_roles.contains("thread/epiphany/")); } #[test] @@ -2792,111 +2367,6 @@ mod tests { Ok(()) } - #[test] - fn auto_review_accepts_receipt_only_verification_findings() { - let result = json!({ - "status": "completed", - "finding": { - "verdict": "needs-evidence", - "summary": "Soul needs a source-backed receipt path.", - "runtimeResultId": "result-verification-1", - "runtimeJobId": "job-verification-1" - } - }); - - assert!(role_result_auto_acceptable("verification", &result)); - assert!(!role_result_auto_acceptable("modeling", &result)); - } - - #[test] - fn auto_review_refuses_identityless_or_errored_findings() { - let missing_identity = json!({ - "status": "completed", - "finding": { - "statePatch": {"scratch": {"summary": "mapped"}}, - "runtimeResultId": "", - "runtimeJobId": "job-modeling-1" - } - }); - let errored = json!({ - "status": "completed", - "finding": { - "statePatch": {"scratch": {"summary": "mapped"}}, - "runtimeResultId": "result-modeling-1", - "runtimeJobId": "job-modeling-1", - "itemError": "missing required field" - } - }); - - assert!(!role_result_auto_acceptable("modeling", &missing_identity)); - assert!(!role_result_auto_acceptable("modeling", &errored)); - } - - #[test] - fn auto_review_accepts_runtime_authored_modeling_proposal_without_generic_state_patch() { - let result = json!({ - "status": "completed", - "finding": { - "verdict": "checkpoint-update-needed", - "runtimeResultId": "result-modeling-typed", - "runtimeJobId": "job-modeling-typed", - "repoModelMutationProposal": { - "proposal_id": "runtime-owned-proposal", - "source_result_id": "result-modeling-typed" - }, - "statePatch": null - } - }); - - assert!(role_result_auto_acceptable("modeling", &result)); - assert!(!role_result_needs_supersession("modeling", &result)); - } - - #[test] - fn supersession_includes_unreviewable_modeling_results() { - let unreviewable = json!({ - "status": "completed", - "finding": { - "verdict": "checkpoint-update-needed", - "summary": "Mapped in prose only.", - "runtimeResultId": "result-modeling-1", - "runtimeJobId": "job-modeling-1", - "itemError": "modeling result is not reviewable: missing required statePatch" - } - }); - let reviewable = json!({ - "status": "completed", - "finding": { - "verdict": "checkpoint-update-needed", - "summary": "Mapped with state.", - "runtimeResultId": "result-modeling-2", - "runtimeJobId": "job-modeling-2", - "repoModelMutationProposal": { - "proposal_id": "runtime-owned-proposal-2", - "source_result_id": "result-modeling-2" - }, - "statePatch": {"scratch": {"summary": "mapped"}} - } - }); - let null_patch = json!({ - "status": "completed", - "finding": { - "summary": "Explicit null is still no state patch.", - "runtimeResultId": "result-modeling-null", - "runtimeJobId": "job-modeling-null", - "statePatch": null - } - }); - - assert!(role_result_needs_supersession("modeling", &unreviewable)); - assert!(role_result_needs_supersession("modeling", &null_patch)); - assert!(!role_result_needs_supersession("modeling", &reviewable)); - assert!(!role_result_needs_supersession( - "verification", - &unreviewable - )); - } - #[test] fn operator_can_approve_only_a_self_derived_manual_regather() -> Result<()> { let mut coordinator = json!({ diff --git a/epiphany-core/src/bin/epiphany-mvp-status.rs b/epiphany-core/src/bin/epiphany-mvp-status.rs index 29e74773..6af84a70 100644 --- a/epiphany-core/src/bin/epiphany-mvp-status.rs +++ b/epiphany-core/src/bin/epiphany-mvp-status.rs @@ -1,53 +1,19 @@ -use anyhow::Context; -use anyhow::Result; -use anyhow::anyhow; -use epiphany_core::EpiphanyCoordinatorRoleResultStatus; -use epiphany_core::EpiphanyCoordinatorStatus; -use epiphany_core::EpiphanyCoordinatorStatusInput; -use epiphany_core::EpiphanyCrrcAction; -use epiphany_core::EpiphanyCrrcRecommendation; -use epiphany_core::EpiphanyCrrcResultStatus; -use epiphany_core::EpiphanyCrrcSceneAction; -use epiphany_core::EpiphanyCrrcStateStatus; -use epiphany_core::EpiphanyJobStatus; -use epiphany_core::EpiphanyJobsInput; -use epiphany_core::EpiphanyReorientAction; -use epiphany_core::EpiphanyRoleBoardCheckpointSummary; -use epiphany_core::EpiphanyRoleBoardInput; -use epiphany_core::EpiphanyRoleBoardJob; -use epiphany_core::EpiphanyRoleBoardJobStatus; -use epiphany_core::EpiphanyRoleBoardPlanningSummary; -use epiphany_core::EpiphanyRoleFindingInterpretation; -use epiphany_core::EpiphanyRoleResultRoleId; -use epiphany_core::EpiphanyRuntimeJobSnapshot; -use epiphany_core::EpiphanyRuntimeJobStatus; -use epiphany_core::EpiphanySceneInput; -use epiphany_core::EpiphanyTokenUsageSnapshot; -use epiphany_core::derive_jobs; -use epiphany_core::derive_planning_view; -use epiphany_core::derive_pressure_view; -use epiphany_core::derive_role_board; -use epiphany_core::derive_scene; -use epiphany_core::read_accepted_coordinator_state; -use epiphany_core::runtime_job_snapshot; -use epiphany_self_policy::crrc_scene_action_to_coordinator_scene_action; -use epiphany_self_policy::derive_coordinator_finding_signals; +use anyhow::{Context, Result, anyhow}; +use epiphany_core::{ + EpiphanyAgentPassContinuationAction, EpiphanyCoordinatorStatus, + EpiphanyCoordinatorStatusInput, EpiphanyCrrcAction, EpiphanyCrrcRecommendation, + EpiphanyCrrcResultStatus, EpiphanyCrrcSceneAction, EpiphanyCurrentWorkProjection, + EpiphanyJobsInput, EpiphanyReorientAction, EpiphanyRoleBoardInput, EpiphanyRoleBoardJob, + EpiphanyRoleBoardJobStatus, EpiphanyRoleResultRoleId, EpiphanyRuntimeJobStatus, + EpiphanySceneInput, EpiphanyTokenUsageSnapshot, RepoFrontierPlanningLifecycleStage, + derive_jobs, derive_planning_view, derive_pressure_view, derive_role_board, derive_scene, + runtime_job_snapshot, +}; use epiphany_self_policy::derive_coordinator_status; -use epiphany_state_model::EpiphanyThreadState; -use serde_json::Value; -use serde_json::json; -use std::env; -use std::fs; -use std::path::{Path, PathBuf}; -use std::process::Command; +use serde_json::{Value, json}; +use std::{env, fs, path::{Path, PathBuf}}; -const DEFAULT_CARGO_TARGET_DIR: &str = r"C:\Users\Meta\.cargo-target-codex"; const DEFAULT_COORDINATOR_STORE: &str = "state/runtime-spine.msgpack"; -const REORIENT_BINDING_ID: &str = "reorient-worker"; -const IMAGINATION_BINDING_ID: &str = "imagination-synthesis-worker"; -const RESEARCH_BINDING_ID: &str = "research-source-gather-worker"; -const MODELING_BINDING_ID: &str = "modeling-checkpoint-worker"; -const VERIFICATION_BINDING_ID: &str = "verification-review-worker"; const SEALED_DIRECT_THOUGHT_KEYS: &[&str] = &[ "rawResult", "turns", @@ -57,68 +23,6 @@ const SEALED_DIRECT_THOUGHT_KEYS: &[&str] = &[ ]; const SEALED_LONG_TEXT_KEYS: &[&str] = &["note"]; const MAX_OPERATOR_TEXT_CHARS: usize = 1200; -const PERSONA_SURFACE_SCHEMA_VERSION: &str = "epiphany.persona_surface.v0"; - -#[derive(Clone, Copy, Debug, serde::Serialize)] -#[serde(rename_all = "kebab-case")] -enum PersonaArtifactKind { - Bubble, - DiscordChat, - RedditPost, - OtherRequest, -} - -#[derive(Clone, Copy, Debug, serde::Serialize)] -#[serde(rename_all = "lowercase")] -enum PersonaArtifactLifecycle { - Projected, - Draft, - Blocked, - Posted, - DraftCandidate, - CrossingRequested, -} - -#[derive(Debug, serde::Serialize)] -#[serde(rename_all = "camelCase")] -struct PersonaArtifactRef { - kind: PersonaArtifactKind, - schema_version: String, - path: String, - lifecycle: PersonaArtifactLifecycle, - modified_at: Option, - target: Option, - private_state_exposed: bool, -} - -#[derive(Debug, serde::Serialize)] -#[serde(rename_all = "camelCase")] -struct PersonaActionRef { - action_id: &'static str, - intent_schema_version: &'static str, - consequence_owner: &'static str, - surface_owns_consequence: bool, -} - -#[derive(Clone, Copy, Debug, serde::Serialize)] -#[serde(rename_all = "lowercase")] -enum PersonaSurfaceStatus { - Loaded, - Attention, -} - -#[derive(Debug, serde::Serialize)] -#[serde(rename_all = "camelCase")] -struct PersonaSurface { - schema_version: &'static str, - status: PersonaSurfaceStatus, - artifact_dir: String, - artifacts: Vec, - rejected_artifact_count: usize, - source_error_count: usize, - available_actions: Vec, - private_state_exposed: bool, -} fn main() -> Result<()> { let args = Args::parse()?; @@ -128,11 +32,8 @@ fn main() -> Result<()> { fs::create_dir_all(parent) .with_context(|| format!("failed to create {}", parent.display()))?; } - fs::write( - result, - format!("{}\n", serde_json::to_string_pretty(&status)?), - ) - .with_context(|| format!("failed to write {}", result.display()))?; + fs::write(result, format!("{}\n", serde_json::to_string_pretty(&status)?)) + .with_context(|| format!("failed to write {}", result.display()))?; } if args.json { println!("{}", serde_json::to_string_pretty(&status)?); @@ -147,13 +48,8 @@ struct Args { thread_id: Option, cwd: PathBuf, store: PathBuf, - ephemeral: bool, json: bool, result: Option, - transcript: PathBuf, - stderr: PathBuf, - interrupt_binding: Option, - interrupt_reason: Option, include_auxiliary_status: bool, } @@ -161,21 +57,12 @@ impl Args { fn parse() -> Result { let root = env::current_dir().context("failed to resolve current directory")?; let mut args = env::args().skip(1); - let mut parsed = Args { + let mut parsed = Self { thread_id: None, - cwd: root.clone(), + cwd: root, store: PathBuf::from(DEFAULT_COORDINATOR_STORE), - ephemeral: true, json: false, result: None, - transcript: root - .join(".epiphany-status") - .join("epiphany-mvp-status-transcript.jsonl"), - stderr: root - .join(".epiphany-status") - .join("epiphany-mvp-status-server.stderr.log"), - interrupt_binding: None, - interrupt_reason: None, include_auxiliary_status: true, }; while let Some(arg) = args.next() { @@ -183,19 +70,14 @@ impl Args { "--thread-id" => parsed.thread_id = Some(take_string(&mut args, "--thread-id")?), "--cwd" => parsed.cwd = take_path(&mut args, "--cwd")?, "--store" => parsed.store = take_path(&mut args, "--store")?, - "--ephemeral" => parsed.ephemeral = true, - "--no-ephemeral" => parsed.ephemeral = false, "--json" => parsed.json = true, "--result" => parsed.result = Some(take_path(&mut args, "--result")?), - "--transcript" => parsed.transcript = take_path(&mut args, "--transcript")?, - "--stderr" => parsed.stderr = take_path(&mut args, "--stderr")?, - "--interrupt-binding" => { - parsed.interrupt_binding = Some(take_string(&mut args, "--interrupt-binding")?) - } - "--interrupt-reason" => { - parsed.interrupt_reason = Some(take_string(&mut args, "--interrupt-reason")?) - } "--coordinator-only" => parsed.include_auxiliary_status = false, + // Historical presentation switches remain accepted but own no state. + "--ephemeral" | "--no-ephemeral" => {} + "--transcript" | "--stderr" => { + let _ = take_string(&mut args, &arg)?; + } _ => return Err(anyhow!("unknown argument: {arg}")), } } @@ -204,64 +86,18 @@ impl Args { } fn run_status(args: &Args) -> Result { - if args.interrupt_binding.is_some() { - return run_native_interrupt(args); - } run_native_status(args, args.include_auxiliary_status) } -fn run_native_interrupt(args: &Args) -> Result { - let thread_id = args - .thread_id - .as_ref() - .ok_or_else(|| anyhow!("--interrupt-binding requires --thread-id"))?; - let binding_id = args - .interrupt_binding - .as_ref() - .ok_or_else(|| anyhow!("--interrupt-binding requires a binding id"))?; - let store = absolute_path(&args.store)?; - let service = epiphany_core::EpiphanyCoordinatorService::new(&store); - let state = service - .state()? - .ok_or_else(|| anyhow!("cannot interrupt without native coordinator state"))?; - let result = service.interrupt_job( - thread_id, - &state, - epiphany_core::EpiphanyJobInterruptRequest { - expected_revision: Some(state.revision), - binding_id: binding_id.clone(), - reason: args.interrupt_reason.clone(), - }, - )?; - Ok(json!({ - "source": "native", - "threadId": thread_id, - "bindingId": result.binding_id, - "revision": result.epiphany_state.revision, - "cancelRequested": result.cancel_requested, - "interruptedThreadIds": result.interrupted_thread_ids, - "state": result.epiphany_state, - })) -} - pub fn native_coordinator_json(runtime_store: &Path, thread_id: &str) -> Result { let root = env::current_dir().context("failed to resolve current directory")?; run_native_status( &Args { thread_id: Some(thread_id.to_string()), - cwd: root.clone(), + cwd: root, store: runtime_store.to_path_buf(), - ephemeral: true, json: true, result: None, - transcript: root - .join(".epiphany-status") - .join("epiphany-mvp-status-transcript.jsonl"), - stderr: root - .join(".epiphany-status") - .join("epiphany-mvp-status-server.stderr.log"), - interrupt_binding: None, - interrupt_reason: None, include_auxiliary_status: false, }, false, @@ -271,31 +107,29 @@ pub fn native_coordinator_json(runtime_store: &Path, thread_id: &str) -> Result< fn run_native_status(args: &Args, include_auxiliary_status: bool) -> Result { let _cwd = absolute_path(&args.cwd)?; let store_path = absolute_path(&args.store)?; - let runtime_store_path = store_path.clone(); - let state = if store_path.exists() { - read_accepted_coordinator_state(&store_path) - .with_context(|| format!("failed to load {}", store_path.display()))? - } else { - None - }; let thread_id = args .thread_id .clone() .unwrap_or_else(|| "native-local".to_string()); - let state_ref = state.as_ref(); - let loaded = state_ref.is_some(); - let current_work = epiphany_core::project_current_work(&runtime_store_path) - .context("failed to derive current work from keyed Mind and runtime receipts")?; - let scene = derive_scene(EpiphanySceneInput { - state: state_ref, - loaded, - reorient_binding_id: REORIENT_BINDING_ID, - }); + let mind = if store_path.exists() { + Some( + epiphany_core::assemble_mind_view(&store_path) + .with_context(|| format!("failed to assemble keyed Mind {}", store_path.display()))?, + ) + } else { + None + }; + let current_work = if mind.is_some() { + epiphany_core::project_current_work(&store_path) + .context("failed to derive current work from keyed Mind and runtime receipts")? + } else { + empty_current_work() + }; let pressure = derive_pressure_view(None::<&EpiphanyTokenUsageSnapshot>); - let mind = epiphany_core::assemble_mind_view(&runtime_store_path)?; - let durable_checkpoint_present = mind.investigation_checkpoint.is_some(); - let latest_reorientation_decision = mind.reorientation_decisions.last(); + let latest_reorientation_decision = mind + .as_ref() + .and_then(|mind| mind.reorientation_decisions.last()); let reorientation_work = current_work.reorientation.as_ref(); let reorient_action = latest_reorientation_decision .map(|decision| { @@ -306,48 +140,24 @@ fn run_native_status(args: &Args, include_auxiliary_status: bool) -> Result "resume", - EpiphanyReorientAction::Regather => "regather", - }, - "nextAction": reorient_next_action, - "requestId": reorientation_work.map(|work| work.request.request_id.as_str()), - "basisDigest": reorientation_work.map(|work| work.request.projection.projection_digest.as_str()), - "authority": "keyedMindCurrentWork", - }); - let planning = derive_planning_view(state_ref); - let mut jobs = derive_jobs(EpiphanyJobsInput { - state: state_ref, - retrieval_override: None, - }); - reconcile_native_runtime_jobs(&mut jobs, state_ref, &runtime_store_path); - let state_status = if state_ref.is_some() { - EpiphanyCrrcStateStatus::Ready - } else { - EpiphanyCrrcStateStatus::Missing - }; - let result_status = keyed_reorientation_result_status( - &runtime_store_path, + let reorient_result_status = keyed_reorientation_result_status( + &store_path, reorientation_work, latest_reorientation_decision.is_some(), )?; - let reorient_finding_accepted = latest_reorientation_decision.is_some(); - let modeling_result_status = - native_role_result_status(state_ref, &runtime_store_path, MODELING_BINDING_ID); - let research_result_status = - native_role_result_status(state_ref, &runtime_store_path, RESEARCH_BINDING_ID); - let verification_result_status = - native_role_result_status(state_ref, &runtime_store_path, VERIFICATION_BINDING_ID); let recommendation = keyed_reorientation_recommendation( reorientation_work, latest_reorientation_decision, pressure.should_prepare_compaction, ); + + let scene = derive_scene(EpiphanySceneInput { + mind: mind.as_ref(), + loaded: mind.is_some(), + reorientation_work_present: reorientation_work.is_some(), + }); + let planning = derive_planning_view(mind.as_ref()); + let jobs = derive_jobs(EpiphanyJobsInput { mind: mind.as_ref() }); let role_jobs = jobs .iter() .map(|job| EpiphanyRoleBoardJob { @@ -359,497 +169,175 @@ fn run_native_status(args: &Args, include_auxiliary_status: bool) -> Result>(); let roles = derive_role_board(EpiphanyRoleBoardInput { - state_present: state_ref.is_some(), - planning: EpiphanyRoleBoardPlanningSummary { - capture_count: planning.summary.capture_count as usize, - backlog_item_count: planning.summary.backlog_item_count as usize, - roadmap_stream_count: planning.summary.roadmap_stream_count as usize, - objective_draft_count: planning.summary.objective_draft_count as usize, - }, - checkpoint: state_ref.and_then(|state| { - state.investigation_checkpoint.as_ref().map(|checkpoint| { - EpiphanyRoleBoardCheckpointSummary { - disposition: Some(format!("{:?}", checkpoint.disposition)), - next_action: checkpoint.next_action.clone(), - } - }) - }), - reorient_next_action: reorient_next_action.clone(), - jobs: role_jobs.clone(), - crrc_action: recommendation.action, - crrc_recommended_scene_action: recommendation - .recommended_scene_action - .map(crrc_scene_action_to_coordinator_scene_action), - crrc_reason: recommendation.reason.clone(), - reorient_decision_action: format!("{:?}", reorient_action), - pressure_level: format!("{:?}", pressure.level), - reorient_result_status: result_status, - reorient_job: role_jobs - .iter() - .find(|job| job.id == REORIENT_BINDING_ID) - .cloned(), - imagination_binding_id: IMAGINATION_BINDING_ID.to_string(), - research_binding_id: RESEARCH_BINDING_ID.to_string(), - modeling_binding_id: MODELING_BINDING_ID.to_string(), - verification_binding_id: VERIFICATION_BINDING_ID.to_string(), - reorient_owner_role: "epiphany-reorienter".to_string(), - imagination_owner_role: "epiphany-imagination".to_string(), - research_owner_role: "epiphany-eyes".to_string(), + mind_present: mind.is_some(), + current_work: current_work.clone(), + jobs: role_jobs, }); - let research_finding = native_role_finding( - state_ref, - &runtime_store_path, - RESEARCH_BINDING_ID, - EpiphanyRoleResultRoleId::Research, - ); - let modeling_finding = native_role_finding( - state_ref, - &runtime_store_path, - MODELING_BINDING_ID, - EpiphanyRoleResultRoleId::Modeling, - ); - let verification_finding = native_role_finding( - state_ref, - &runtime_store_path, - VERIFICATION_BINDING_ID, - EpiphanyRoleResultRoleId::Verification, - ); - let finding_signals = derive_coordinator_finding_signals( - state_ref, - research_finding.as_ref(), - modeling_finding.as_ref(), - verification_finding.as_ref(), - None, - ); - let modeling_result_proposal_bound = - latest_runtime_job_id_for_binding(state_ref, MODELING_BINDING_ID) - .and_then(|job_id| { - epiphany_core::runtime_role_worker_result(&runtime_store_path, job_id) - .ok() - .flatten() - }) - .is_some_and(|result| result.proposal_modeling_request_id.is_some()); - let hands_frontier_ready = current_work.hands_frontier_ready; - let research_continuation_action = current_work.research_continuation_action; - let frontier_planning_eligibility = epiphany_core::runtime_repo_frontier_planning_eligibility( - &runtime_store_path, - ) - .context("failed to derive Imagination frontier eligibility from runtime-spine state")?; - let imagination_frontier_ready = frontier_planning_eligibility.current_model_count == 1 - && frontier_planning_eligibility - .candidates - .iter() - .any(|candidate| candidate.eligible); - let frontier_planning = - epiphany_core::runtime_repo_frontier_planning_lifecycle(&runtime_store_path) - .context("failed to derive frontier planning lifecycle from runtime-spine state")?; - if frontier_planning.stage != current_work.frontier_planning_stage { - return Err(anyhow!( - "current-work frontier planning projection diverged" - )); - } - let frontier_relinquishment = - epiphany_core::runtime_latest_repo_frontier_relinquishment(&runtime_store_path) - .context("failed to derive latest frontier relinquishment from runtime-spine state")?; - let proposal_modeling_work = current_work.proposal_modeling.as_ref(); let coordinator = derive_coordinator_status(EpiphanyCoordinatorStatusInput { - state_status, - checkpoint_present: durable_checkpoint_present, + mind_present: mind.is_some(), pressure: pressure.clone(), recommendation: recommendation.clone(), roles: roles.clone(), reorient_action, - research_result_status, - modeling_result_status, - verification_result_status, - reorient_result_status: result_status, - research_result_accepted: finding_signals.research_result_accepted, - research_result_reviewable: finding_signals.research_result_reviewable, - research_result_failure_reviewed: finding_signals.research_result_failure_reviewed, - modeling_result_accepted_after_research: finding_signals - .modeling_result_accepted_after_research, - modeling_result_requests_regather: finding_signals.modeling_result_requests_regather, - modeling_result_accepted: finding_signals.modeling_result_accepted, - modeling_result_reviewable: finding_signals.modeling_result_reviewable, - modeling_result_failure_reviewed: finding_signals.modeling_result_failure_reviewed, - modeling_result_proposal_bound, - modeling_result_accepted_after_verification: finding_signals - .modeling_result_accepted_after_verification, - implementation_evidence_after_verification: finding_signals - .implementation_evidence_after_verification, - verification_result_cites_implementation_evidence: finding_signals - .verification_result_cites_implementation_evidence, - verification_result_covers_current_modeling: finding_signals - .verification_result_covers_current_modeling, - verification_result_accepted: finding_signals.verification_result_accepted, - verification_result_failure_reviewed: finding_signals.verification_result_failure_reviewed, - verification_result_allows_implementation: finding_signals - .verification_result_allows_implementation, - verification_result_needs_evidence: finding_signals.verification_result_needs_evidence, - reorient_finding_accepted, - hands_frontier_ready, - research_continuation_action, - frontier_planning_stage: frontier_planning.stage, - proposal_modeling_action: proposal_modeling_work.map(|work| work.action), - frontier_verdict_modeling_action: current_work - .frontier_verdict_modeling - .as_ref() - .map(|work| work.action), - verification_action: current_work.verification.as_ref().map(|work| work.action), - body_modeling_work_ready: current_work.body_modeling.is_some(), - body_modeling_review_ready: current_work.body_modeling_action - == Some(epiphany_core::EpiphanyAgentPassContinuationAction::Review), + reorient_result_status, + current_work: current_work.clone(), }); let coordinator_json = coordinator_status_json(&coordinator)?; - let tool_invocations = native_tool_invocation_surface(&runtime_store_path)?; - let root = env::current_dir().context("failed to resolve current directory")?; - let native_aux = if include_auxiliary_status { - native_auxiliary_status(&root)? + let research_lifecycle = mind + .as_ref() + .map(|_| epiphany_core::runtime_repo_frontier_research_lifecycle(&store_path)) + .transpose()?; + let planning_lifecycle = mind + .as_ref() + .map(|_| epiphany_core::runtime_repo_frontier_planning_lifecycle(&store_path)) + .transpose()?; + let planning_eligibility = mind + .as_ref() + .map(|_| epiphany_core::runtime_repo_frontier_planning_eligibility(&store_path)) + .transpose()?; + let frontier_relinquishment = mind + .as_ref() + .map(|_| epiphany_core::runtime_latest_repo_frontier_relinquishment(&store_path)) + .transpose()? + .flatten(); + let body_job_id = if current_work.body_modeling_action.is_some() { + epiphany_core::current_body_modeling_job_id(&store_path)? } else { - NativeAuxiliaryStatus::omitted_for_coordinator() + None }; - let status = json!({ + let modeling_job_id = current_work + .proposal_modeling + .as_ref() + .and_then(|work| work.job_id.as_deref()) + .or(body_job_id.as_deref()) + .or(current_work + .frontier_verdict_modeling + .as_ref() + .and_then(|work| work.job_id.as_deref())); + let imagination_job_id = planning_lifecycle + .as_ref() + .and_then(|lifecycle| lifecycle.imagination_job_id.as_deref()) + .or(current_work + .imagination_considerations + .first() + .and_then(|work| work.job_id.as_deref())) + .or(current_work + .admitted_model_direction_consideration + .as_ref() + .and_then(|work| work.job_id.as_deref())); + let role_results = json!({ + "imagination": native_role_result(&store_path, imagination_job_id, EpiphanyRoleResultRoleId::Imagination), + "research": native_role_result( + &store_path, + research_lifecycle.as_ref().and_then(|lifecycle| lifecycle.worker_job_id.as_deref()), + EpiphanyRoleResultRoleId::Research, + ), + "modeling": native_role_result(&store_path, modeling_job_id, EpiphanyRoleResultRoleId::Modeling), + "verification": native_role_result( + &store_path, + current_work.verification.as_ref().and_then(|work| work.job_id.as_deref()), + EpiphanyRoleResultRoleId::Verification, + ), + }); + let tools = if mind.is_some() { + native_tool_invocation_surface(&store_path)? + } else { + json!({"source": "native", "status": "missingMind"}) + }; + let reorient_result = keyed_reorientation_result( + &store_path, + reorientation_work, + latest_reorientation_decision, + )?; + let auxiliary = if include_auxiliary_status { + json!({ + "status": "derivedOnly", + "note": "Auxiliary physiology and Persona transport are not coordinator routing inputs." + }) + } else { + json!({"status": "omitted"}) + }; + + Ok(sanitize_for_operator(json!({ "threadId": thread_id, "read": { "source": "native", - "threadStateStore": store_path, - "statePresent": state_ref.is_some(), + "mindStore": store_path, + "mindPresent": mind.is_some(), + "projectionDigest": mind.as_ref().map(|mind| mind.projection_digest.as_str()), }, "view": { "source": "native", - "scene": scene, - "pressure": pressure, - "jobs": jobs, - "roles": { - "threadId": thread_id, - "source": "native", - "stateStatus": crrc_state_status_text(state_status), - "roles": roles, - }, - "planning": planning, - "reorient": { - "threadId": thread_id, - "source": "native", - "stateStatus": reorient_state_status, - "decision": reorient_decision, - }, - "crrc": { - "threadId": thread_id, - "source": "native", - "recommendation": recommendation, - }, - "coordinator": coordinator_json, - "tools": tool_invocations.clone(), - }, - "scene": { - "threadId": thread_id, - "scene": scene, - }, - "pressure": { - "threadId": thread_id, - "source": "native", - "pressure": pressure, + "scene": &scene, + "pressure": &pressure, + "jobs": &jobs, + "roles": &roles, + "planning": &planning, + "coordinator": &coordinator_json, + "tools": &tools, }, + "scene": {"threadId": thread_id, "scene": scene}, + "pressure": {"threadId": thread_id, "source": "native", "pressure": pressure}, "reorient": { "threadId": thread_id, "source": "native", - "stateStatus": reorient_state_status, - "decision": reorient_decision, - }, - "jobs": { - "threadId": thread_id, - "source": "native", - "jobs": jobs, - }, - "roles": { - "threadId": thread_id, - "source": "native", - "stateStatus": crrc_state_status_text(state_status), - "roles": roles, + "decision": { + "action": reorient_action, + "nextAction": latest_reorientation_decision + .map(|decision| decision.next_safe_move.as_str()) + .unwrap_or("No unresolved keyed reorientation obligation."), + "requestId": reorientation_work.map(|work| work.request.request_id.as_str()), + "authority": "keyedMindCurrentWork", + }, }, + "jobs": {"threadId": thread_id, "source": "native", "jobs": jobs}, + "roles": {"threadId": thread_id, "source": "native", "roles": roles}, "planning": planning, - "currentWork": ¤t_work, + "currentWork": current_work, "frontierPlanning": { - "lifecycle": frontier_planning, - "eligibility": frontier_planning_eligibility, + "lifecycle": planning_lifecycle, + "eligibility": planning_eligibility, }, "frontierRelinquishment": frontier_relinquishment, - "roleResults": { - "imagination": native_role_result(state_ref, &runtime_store_path, IMAGINATION_BINDING_ID, EpiphanyRoleResultRoleId::Imagination), - "research": native_role_result(state_ref, &runtime_store_path, RESEARCH_BINDING_ID, EpiphanyRoleResultRoleId::Research), - "modeling": native_role_result(state_ref, &runtime_store_path, MODELING_BINDING_ID, EpiphanyRoleResultRoleId::Modeling), - "verification": native_role_result(state_ref, &runtime_store_path, VERIFICATION_BINDING_ID, EpiphanyRoleResultRoleId::Verification), - }, - "findingSignals": { - "researchResultAccepted": finding_signals.research_result_accepted, - "researchResultReviewable": finding_signals.research_result_reviewable, - "researchResultFailureReviewed": finding_signals.research_result_failure_reviewed, - "modelingResultAcceptedAfterResearch": finding_signals.modeling_result_accepted_after_research, - "modelingResultAccepted": finding_signals.modeling_result_accepted, - "modelingResultReviewable": finding_signals.modeling_result_reviewable, - "modelingResultFailureReviewed": finding_signals.modeling_result_failure_reviewed, - "modelingResultProposalBound": modeling_result_proposal_bound, - "imaginationFrontierReady": imagination_frontier_ready, - "pendingProposalModelingRequestId": proposal_modeling_work - .filter(|work| work.action == epiphany_core::EpiphanyAgentPassContinuationAction::Launch) - .map(|work| work.request.request_id.as_str()), - "verificationResultAccepted": finding_signals.verification_result_accepted, - "verificationResultFailureReviewed": finding_signals.verification_result_failure_reviewed, - }, - "reorientResult": keyed_reorientation_result(&runtime_store_path, reorientation_work, latest_reorientation_decision)?, - "crrc": { - "threadId": thread_id, - "source": "native", - "recommendation": recommendation, - }, + "roleResults": role_results, + "reorientResult": reorient_result, + "crrc": {"threadId": thread_id, "source": "native", "recommendation": recommendation}, "coordinator": coordinator_json, - "tools": tool_invocations, - "heartbeat": native_aux.heartbeat, - "persona": native_aux.persona, - "voidMemory": native_aux.void_memory, - }); - Ok(sanitize_for_operator(status)) + "tools": tools, + "auxiliary": auxiliary, + }))) } -struct NativeAuxiliaryStatus { - heartbeat: Value, - persona: Value, - void_memory: Value, -} - -impl NativeAuxiliaryStatus { - fn omitted_for_coordinator() -> Self { - let omitted = || { - json!({ - "status": "omitted", - "reason": "Auxiliary operator projection is not a coordinator routing input." - }) - }; - Self { - heartbeat: omitted(), - persona: omitted(), - void_memory: omitted(), - } +fn empty_current_work() -> EpiphanyCurrentWorkProjection { + EpiphanyCurrentWorkProjection { + mind_projection_digest: String::new(), + body_modeling: None, + body_modeling_action: None, + research_continuation_action: None, + frontier_planning_stage: RepoFrontierPlanningLifecycleStage::Unavailable, + proposal_modeling: None, + frontier_verdict_modeling: None, + verification: None, + reorientation: None, + imagination_considerations: Vec::new(), + admitted_model_direction_consideration: None, + hands_frontier_ready: false, } } -fn native_auxiliary_status(root: &Path) -> Result { - let heartbeat_dir = root.join(".epiphany-heartbeats"); - let persona_dir = root.join(".epiphany-persona"); - let heartbeat = native_json( - "epiphany-heartbeat-store", - &[ - "status", - "--store", - "state/agent-heartbeats.msgpack", - "--artifact-dir", - &heartbeat_dir.to_string_lossy(), - "--limit", - "8", - ], - ) - .unwrap_or_else(|error| { - json!({ - "status": "unavailable", - "surface": "heartbeat", - "reason": error.to_string(), - "authority": "auxiliary projection is optional and cannot summon a build" - }) - }); - let latest_discord_persona = native_json( - "epiphany-persona-discord", - &[ - "latest", - "--artifact-dir", - &persona_dir.to_string_lossy(), - "--limit", - "8", - ], - ) - .unwrap_or_else( - |error| json!({"status": "error", "error": error.to_string(), "latestArtifacts": []}), - ); - let latest_other_persona = native_json( - "epiphany-persona-other", - &[ - "latest", - "--artifact-dir", - &persona_dir.to_string_lossy(), - "--limit", - "8", - ], - ) - .unwrap_or_else( - |error| json!({"status": "error", "error": error.to_string(), "latestArtifacts": []}), - ); - let latest_reddit_persona = native_json( - "epiphany-persona-reddit", - &[ - "latest", - "--artifact-dir", - &persona_dir.to_string_lossy(), - "--limit", - "8", - ], - ) - .unwrap_or_else( - |error| json!({"status": "error", "error": error.to_string(), "latestArtifacts": []}), - ); - let mut rejected_artifact_count = 0_usize; - let mut source_error_count = 0_usize; - let mut artifacts = Vec::new(); - for (source, readback) in [ - ("discord", &latest_discord_persona), - ("reddit", &latest_reddit_persona), - ("other", &latest_other_persona), - ] { - if readback.get("status").and_then(Value::as_str) == Some("error") { - source_error_count += 1; - continue; - } - for artifact in readback - .get("latestArtifacts") - .and_then(Value::as_array) - .into_iter() - .flatten() - { - if let Some(artifact) = persona_artifact_ref(source, artifact) { - artifacts.push(artifact); - } else { - rejected_artifact_count += 1; - } - } - } - let persona = serde_json::to_value(PersonaSurface { - schema_version: PERSONA_SURFACE_SCHEMA_VERSION, - status: if rejected_artifact_count == 0 && source_error_count == 0 { - PersonaSurfaceStatus::Loaded - } else { - PersonaSurfaceStatus::Attention - }, - artifact_dir: persona_dir.to_string_lossy().into_owned(), - artifacts, - rejected_artifact_count, - source_error_count, - available_actions: vec![ - PersonaActionRef { - action_id: "personaBubble", - intent_schema_version: "epiphany.persona_bubble_intent.v0", - consequence_owner: "persona-mouth-projection", - surface_owns_consequence: false, - }, - PersonaActionRef { - action_id: "characterTurn", - intent_schema_version: "epiphany.character_turn_intent.v0", - consequence_owner: "character-loop", - surface_owns_consequence: false, - }, - PersonaActionRef { - action_id: "discordPersonaPost", - intent_schema_version: "epiphany.discord_persona_post_intent.v0", - consequence_owner: "Bifrost", - surface_owns_consequence: false, - }, - PersonaActionRef { - action_id: "redditPersonaPost", - intent_schema_version: "epiphany.reddit_persona_post_intent.v0", - consequence_owner: "Bifrost", - surface_owns_consequence: false, - }, - ], - private_state_exposed: false, - })?; - let void_memory = native_json( - "epiphany-void-memory", - &["status", "--config", "state/void-memory.toml"], - ) - .unwrap_or_else(|error| json!({"ok": false, "error": error.to_string()})); - - Ok(NativeAuxiliaryStatus { - heartbeat, - persona, - void_memory, - }) -} - -fn persona_artifact_ref(source: &str, artifact: &Value) -> Option { - let schema_version = artifact.get("schemaVersion")?.as_str()?; - let (kind, expected_schema) = match (source, schema_version) { - ("discord", "epiphany.persona_bubble.v0") => { - (PersonaArtifactKind::Bubble, "epiphany.persona_bubble.v0") - } - ("discord", "epiphany.persona_chat.v0") => { - (PersonaArtifactKind::DiscordChat, "epiphany.persona_chat.v0") - } - ("reddit", "epiphany.persona_reddit_post.v0") => ( - PersonaArtifactKind::RedditPost, - "epiphany.persona_reddit_post.v0", - ), - ("other", "epiphany.persona_other_request.v0") => ( - PersonaArtifactKind::OtherRequest, - "epiphany.persona_other_request.v0", - ), - _ => return None, - }; - let lifecycle = match artifact - .get("lifecycle") - .or_else(|| artifact.get("status"))? - .as_str()? - { - "projected" => PersonaArtifactLifecycle::Projected, - "draft" => PersonaArtifactLifecycle::Draft, - "blocked" => PersonaArtifactLifecycle::Blocked, - "posted" => PersonaArtifactLifecycle::Posted, - "draft-candidate" => PersonaArtifactLifecycle::DraftCandidate, - "crossing-requested" => PersonaArtifactLifecycle::CrossingRequested, - _ => return None, - }; - let target = match kind { - PersonaArtifactKind::Bubble => Some("aquarium".to_string()), - PersonaArtifactKind::DiscordChat => None, - PersonaArtifactKind::RedditPost => artifact - .get("subreddit") - .and_then(Value::as_str) - .map(str::to_string), - PersonaArtifactKind::OtherRequest => artifact - .get("targetLocator") - .and_then(Value::as_str) - .map(str::to_string), - }; - Some(PersonaArtifactRef { - kind, - schema_version: expected_schema.to_string(), - path: artifact.get("path")?.as_str()?.to_string(), - lifecycle, - modified_at: artifact - .get("modifiedAt") - .and_then(Value::as_str) - .map(str::to_string), - target, - private_state_exposed: false, - }) -} - fn native_role_result( - state: Option<&EpiphanyThreadState>, runtime_store: &Path, - binding_id: &str, + job_id: Option<&str>, role_id: EpiphanyRoleResultRoleId, ) -> Value { - let Some(job_id) = latest_runtime_job_id_for_binding(state, binding_id) else { - return json!({ - "source": "native", - "status": "backendMissing", - "bindingId": binding_id, - "note": "No runtime-spine job is linked to this native role binding.", - }); + let Some(job_id) = job_id else { + return json!({"source": "native", "status": "noCurrentWork"}); }; let snapshot = epiphany_core::read_runtime_role_result(Some(runtime_store), job_id, role_id); let mut result = json!({ "source": "native", "status": snapshot.status, - "bindingId": binding_id, "runtimeJobId": job_id, "note": snapshot.note, }); @@ -859,104 +347,6 @@ fn native_role_result( result } -fn native_role_result_status( - state: Option<&EpiphanyThreadState>, - runtime_store: &Path, - binding_id: &str, -) -> EpiphanyCoordinatorRoleResultStatus { - let Some(job_id) = latest_runtime_job_id_for_binding(state, binding_id) else { - return EpiphanyCoordinatorRoleResultStatus::BackendMissing; - }; - match runtime_job_snapshot(runtime_store, job_id) { - Ok(Some(snapshot)) => map_runtime_role_result_status(&snapshot), - Ok(None) => EpiphanyCoordinatorRoleResultStatus::BackendMissing, - Err(_) => EpiphanyCoordinatorRoleResultStatus::BackendUnavailable, - } -} - -fn native_role_finding( - state: Option<&EpiphanyThreadState>, - runtime_store: &Path, - binding_id: &str, - role_id: EpiphanyRoleResultRoleId, -) -> Option { - let job_id = latest_runtime_job_id_for_binding(state, binding_id)?; - epiphany_core::read_runtime_role_result(Some(runtime_store), job_id, role_id).finding -} - -fn reconcile_native_runtime_jobs( - jobs: &mut [epiphany_core::EpiphanyJobView], - state: Option<&EpiphanyThreadState>, - runtime_store: &Path, -) { - for job in jobs { - let Some(runtime_job_id) = job - .runtime_job_id - .clone() - .or_else(|| latest_runtime_job_id_for_binding(state, &job.id).map(str::to_string)) - else { - continue; - }; - let Ok(Some(snapshot)) = runtime_job_snapshot(runtime_store, &runtime_job_id) else { - continue; - }; - job.runtime_job_id = Some(runtime_job_id); - job.status = map_runtime_job_status(snapshot.job.status); - job.progress_note = Some(snapshot.job.summary.clone()); - } -} - -fn latest_runtime_job_id_for_binding<'a>( - state: Option<&'a EpiphanyThreadState>, - binding_id: &str, -) -> Option<&'a str> { - state? - .runtime_links - .iter() - .find(|link| link.binding_id == binding_id && !link.runtime_job_id.trim().is_empty()) - .map(|link| link.runtime_job_id.as_str()) -} - -fn map_runtime_role_result_status( - snapshot: &EpiphanyRuntimeJobSnapshot, -) -> EpiphanyCoordinatorRoleResultStatus { - match snapshot.job.status { - EpiphanyRuntimeJobStatus::Queued => EpiphanyCoordinatorRoleResultStatus::Pending, - EpiphanyRuntimeJobStatus::Running | EpiphanyRuntimeJobStatus::WaitingForReview => { - EpiphanyCoordinatorRoleResultStatus::Running - } - EpiphanyRuntimeJobStatus::Completed => { - if snapshot.result.is_some() { - EpiphanyCoordinatorRoleResultStatus::Completed - } else { - EpiphanyCoordinatorRoleResultStatus::Pending - } - } - EpiphanyRuntimeJobStatus::Failed => EpiphanyCoordinatorRoleResultStatus::Failed, - EpiphanyRuntimeJobStatus::Cancelled => EpiphanyCoordinatorRoleResultStatus::Cancelled, - } -} - -fn map_runtime_reorient_result_status( - snapshot: &EpiphanyRuntimeJobSnapshot, -) -> EpiphanyCrrcResultStatus { - match snapshot.job.status { - EpiphanyRuntimeJobStatus::Queued => EpiphanyCrrcResultStatus::Pending, - EpiphanyRuntimeJobStatus::Running | EpiphanyRuntimeJobStatus::WaitingForReview => { - EpiphanyCrrcResultStatus::Running - } - EpiphanyRuntimeJobStatus::Completed => { - if snapshot.result.is_some() { - EpiphanyCrrcResultStatus::Completed - } else { - EpiphanyCrrcResultStatus::Pending - } - } - EpiphanyRuntimeJobStatus::Failed => EpiphanyCrrcResultStatus::Failed, - EpiphanyRuntimeJobStatus::Cancelled => EpiphanyCrrcResultStatus::Cancelled, - } -} - fn keyed_reorientation_result_status( runtime_store: &Path, work: Option<&epiphany_core::EpiphanyReorientationWorkProjection>, @@ -974,7 +364,15 @@ fn keyed_reorientation_result_status( }; let snapshot = runtime_job_snapshot(runtime_store, job_id)? .ok_or_else(|| anyhow!("keyed reorientation work lost its runtime job"))?; - Ok(map_runtime_reorient_result_status(&snapshot)) + Ok(match snapshot.job.status { + EpiphanyRuntimeJobStatus::Queued => EpiphanyCrrcResultStatus::Pending, + EpiphanyRuntimeJobStatus::Running | EpiphanyRuntimeJobStatus::WaitingForReview => { + EpiphanyCrrcResultStatus::Running + } + EpiphanyRuntimeJobStatus::Completed => EpiphanyCrrcResultStatus::Completed, + EpiphanyRuntimeJobStatus::Failed => EpiphanyCrrcResultStatus::Failed, + EpiphanyRuntimeJobStatus::Cancelled => EpiphanyCrrcResultStatus::Cancelled, + }) } fn keyed_reorientation_recommendation( @@ -989,20 +387,20 @@ fn keyed_reorientation_recommendation( }; if let Some(work) = work { return match work.action { - epiphany_core::EpiphanyAgentPassContinuationAction::Launch => build( + EpiphanyAgentPassContinuationAction::Launch => build( EpiphanyCrrcAction::LaunchReorientWorker, Some(EpiphanyCrrcSceneAction::ReorientLaunch), - "A keyed Mind continuity request has no live attempt; launch its exact sealed projection.", + "The exact keyed continuity request has no live attempt.", ), - epiphany_core::EpiphanyAgentPassContinuationAction::Wait => build( + EpiphanyAgentPassContinuationAction::Wait => build( EpiphanyCrrcAction::WaitForReorientWorker, Some(EpiphanyCrrcSceneAction::ReorientResult), - "The exact keyed reorientation attempt is still live.", + "The exact keyed continuity attempt is still live.", ), - epiphany_core::EpiphanyAgentPassContinuationAction::Review => build( + EpiphanyAgentPassContinuationAction::Review => build( EpiphanyCrrcAction::ReviewReorientResult, Some(EpiphanyCrrcSceneAction::ReorientResult), - "The exact keyed reorientation pass has a terminal decision or model-backed failure to review.", + "The exact keyed continuity result awaits admission.", ), }; } @@ -1010,14 +408,14 @@ fn keyed_reorientation_recommendation( return build( EpiphanyCrrcAction::LaunchReorientWorker, Some(EpiphanyCrrcSceneAction::ReorientLaunch), - "Context pressure requires a new keyed continuity request over the current Mind projection.", + "Context pressure requires a new keyed continuity request.", ); } if accepted.is_some_and(|decision| decision.mode == "regather") { return build( EpiphanyCrrcAction::RegatherManually, Some(EpiphanyCrrcSceneAction::Reorient), - "The accepted keyed continuity decision requires explicit regather work.", + "The accepted keyed continuity decision requires explicit regather.", ); } build( @@ -1038,37 +436,20 @@ fn keyed_reorientation_result( .unwrap_or(Value::Null)); }; let Some(job_id) = work.job_id.as_deref() else { - return Ok(json!({ - "status": "unlaunched", - "requestId": work.request.request_id, - })); + return Ok(json!({"status": "unlaunched", "requestId": work.request.request_id})); }; let snapshot = runtime_job_snapshot(runtime_store, job_id)? .ok_or_else(|| anyhow!("keyed reorientation work lost its runtime job"))?; - let result = epiphany_core::runtime_reorient_worker_result(runtime_store, job_id)?; Ok(json!({ "status": format!("{:?}", snapshot.job.status).to_ascii_lowercase(), "requestId": work.request.request_id, "jobId": job_id, - "result": result, + "result": epiphany_core::runtime_reorient_worker_result(runtime_store, job_id)?, })) } -fn map_runtime_job_status(status: EpiphanyRuntimeJobStatus) -> EpiphanyJobStatus { - match status { - EpiphanyRuntimeJobStatus::Queued => EpiphanyJobStatus::Pending, - EpiphanyRuntimeJobStatus::Running | EpiphanyRuntimeJobStatus::WaitingForReview => { - EpiphanyJobStatus::Running - } - EpiphanyRuntimeJobStatus::Completed => EpiphanyJobStatus::Completed, - EpiphanyRuntimeJobStatus::Failed => EpiphanyJobStatus::Failed, - EpiphanyRuntimeJobStatus::Cancelled => EpiphanyJobStatus::Cancelled, - } -} - fn native_tool_invocation_surface(runtime_store: &Path) -> Result { let spine_status = epiphany_core::runtime_spine_status(runtime_store)?; - let invocations = epiphany_core::runtime_tool_invocation_statuses(runtime_store)?; Ok(json!({ "source": "native", "runtimeStore": runtime_store.display().to_string(), @@ -1078,7 +459,7 @@ fn native_tool_invocation_surface(runtime_store: &Path) -> Result { "pendingCount": spine_status.pending_tool_invocations, "receiptCount": spine_status.tool_invocation_receipts, }, - "invocations": invocations, + "invocations": epiphany_core::runtime_tool_invocation_statuses(runtime_store)?, })) } @@ -1096,13 +477,6 @@ fn coordinator_status_json(status: &EpiphanyCoordinatorStatus) -> Result Ok(value) } -fn crrc_state_status_text(status: EpiphanyCrrcStateStatus) -> &'static str { - match status { - EpiphanyCrrcStateStatus::Missing => "missing", - EpiphanyCrrcStateStatus::Ready => "ready", - } -} - fn role_job_status(status: epiphany_core::EpiphanyJobStatus) -> EpiphanyRoleBoardJobStatus { match status { epiphany_core::EpiphanyJobStatus::Idle => EpiphanyRoleBoardJobStatus::Idle, @@ -1118,231 +492,43 @@ fn role_job_status(status: epiphany_core::EpiphanyJobStatus) -> EpiphanyRoleBoar } pub fn render_status(status: &Value) -> String { - let scene = &status["scene"]["scene"]; - let pressure = &status["pressure"]["pressure"]; - let reorient = &status["reorient"]["decision"]; - let result = &status["reorientResult"]; - let recommendation = &status["crrc"]["recommendation"]; + let read = &status["read"]; let coordinator = &status["coordinator"]; - let heartbeat = &status["heartbeat"]; - let persona = &status["persona"]; - let planning_response = &status["planning"]; - let planning_summary = &planning_response["summary"]; - let checkpoint = &scene["investigationCheckpoint"]; - let latest_heartbeat = heartbeat["latestEvent"].clone(); - let latest_persona = persona["artifacts"] - .as_array() - .and_then(|items| items.first()) - .cloned() - .unwrap_or_else(|| json!({})); - + let current = &status["currentWork"]; let mut lines = vec![ - "Epiphany MVP Status".to_string(), - format!("Thread: {}", text(&status["threadId"])), - format!( - "State: {} rev {} ({})", - text(&scene["stateStatus"]), - maybe(&scene["revision"], "none"), - text(&scene["source"]) - ), + "Epiphany Status".to_string(), + format!("Mind: {}", if read["mindPresent"].as_bool() == Some(true) { "ready" } else { "missing" }), + format!("Projection: {}", maybe(&read["projectionDigest"], "none")), + format!("Coordinator: {}", maybe(&coordinator["action"], "none")), + format!("Reason: {}", maybe(&coordinator["reason"], "none")), + format!("Hands ready: {}", current["handsFrontierReady"].as_bool().unwrap_or(false)), String::new(), - "Recommendation".to_string(), - format!("- action: {}", text(&recommendation["action"])), - format!( - "- scene action: {}", - maybe(&recommendation["recommendedSceneAction"], "none") - ), - format!("- reason: {}", text(&recommendation["reason"])), - format!( - "- coordinator: {} ({})", - maybe(&coordinator["action"], "none"), - maybe(&coordinator["targetRole"], "none") - ), - String::new(), - "Continuity".to_string(), - format!( - "- pressure: {} ({}, prepare={})", - text(&pressure["level"]), - text(&pressure["status"]), - bool_text(&pressure["shouldPrepareCompaction"]) - ), - format!( - "- reorient: {} via {}", - text(&reorient["action"]), - list_text(&reorient["reasons"], "none") - ), - format!("- next: {}", text(&reorient["nextAction"])), - format!( - "- result: {} for {}", - text(&result["status"]), - text(&result["bindingId"]) - ), - String::new(), - "Heartbeat".to_string(), - format!( - "- status: {}; clock {}; rate {}", - maybe(&heartbeat["status"], "none"), - maybe(&heartbeat["sceneClock"], "none"), - maybe(&heartbeat["targetHeartbeatRate"], "none") - ), - format!( - "- latest: {} / {} / {}", - maybe(&latest_heartbeat["selectedRole"], "none"), - maybe(&latest_heartbeat["actionType"], "none"), - maybe(&latest_heartbeat["coordinatorAction"], "none") - ), - String::new(), - "Persona".to_string(), - format!( - "- latest artifact: {} / {}", - maybe(&latest_persona["kind"], "none"), - maybe(&latest_persona["lifecycle"], "none") - ), - format!( - "- artifact path: {}", - maybe(&latest_persona["path"], "none") - ), - String::new(), - "Planning".to_string(), - format!( - "- state: {} rev {}", - maybe(&planning_response["stateStatus"], "none"), - maybe(&planning_response["stateRevision"], "none") - ), - format!( - "- captures: {} (pending {}, github {})", - maybe(&planning_summary["captureCount"], "0"), - maybe(&planning_summary["pendingCaptureCount"], "0"), - maybe(&planning_summary["githubIssueCaptureCount"], "0") - ), - format!( - "- backlog: {} (ready {})", - maybe(&planning_summary["backlogItemCount"], "0"), - maybe(&planning_summary["readyBacklogItemCount"], "0") - ), - format!( - "- roadmap streams: {}; objective drafts: {} (draft {})", - maybe(&planning_summary["roadmapStreamCount"], "0"), - maybe(&planning_summary["objectiveDraftCount"], "0"), - maybe(&planning_summary["draftObjectiveCount"], "0") - ), - format!( - "- active objective: {}", - maybe(&planning_summary["activeObjective"], "none") - ), - format!("- note: {}", maybe(&planning_summary["note"], "none")), - String::new(), - "Role Lanes".to_string(), + "Role lanes".to_string(), ]; if let Some(roles) = status["roles"]["roles"].as_array() { for lane in roles { lines.push(format!( - "- {}: {} ({}) - {}", - text(&lane["title"]), - text(&lane["status"]), - text(&lane["ownerRole"]), - text(&lane["note"]) + "- {}: {} — {}", + maybe(&lane["title"], "unknown"), + maybe(&lane["status"], "unknown"), + maybe(&lane["note"], "") )); } } - lines.extend([String::new(), "Role Findings".to_string()]); - for (role_id, label) in [ - ("imagination", "Imagination / Planning"), - ("research", "Eyes / Research"), - ("modeling", "Modeling / Checkpoint"), - ("verification", "Verification / Review"), - ] { - let role_result = &status["roleResults"][role_id]; - lines.push(format!( - "- {}: {} for {}", - label, - maybe(&role_result["status"], "none"), - maybe(&role_result["bindingId"], "none") - )); - } - lines.extend([ - String::new(), - "Checkpoint".to_string(), - format!("- id: {}", maybe(&checkpoint["checkpointId"], "none")), - format!( - "- disposition: {}", - maybe(&checkpoint["disposition"], "none") - ), - format!("- focus: {}", maybe(&checkpoint["focus"], "none")), - format!("- next: {}", maybe(&checkpoint["nextAction"], "none")), - String::new(), - "Jobs".to_string(), - ]); - if let Some(jobs) = status["jobs"]["jobs"].as_array() { - if jobs.is_empty() { - lines.push("- none".to_string()); - } else { - for job in jobs { - lines.push(format!( - "- {}: {} {}, {} [{}]", - text(&job["id"]), - text(&job["status"]), - text(&job["kind"]), - text(&job["ownerRole"]), - text(&job["scope"]) - )); - } - } - } - let tools = &status["tools"]; - let tool_summary = &tools["summary"]; - lines.extend([ - String::new(), - "Tools".to_string(), - format!( - "- intents: {} pending: {} receipts: {}", - maybe(&tool_summary["intentCount"], "0"), - maybe(&tool_summary["pendingCount"], "0"), - maybe(&tool_summary["receiptCount"], "0") - ), - format!("- runtime store: {}", maybe(&tools["runtimeStore"], "none")), - ]); - if let Some(invocations) = tools["invocations"].as_array() { - if invocations.is_empty() { - lines.push("- latest: none".to_string()); - } else { - for invocation in invocations.iter().rev().take(5) { - lines.push(format!( - "- {}: {} {}/{} ({})", - maybe(&invocation["intentId"], "unknown"), - maybe(&invocation["status"], "unknown"), - maybe(&invocation["server"], "unknown"), - maybe(&invocation["toolName"], "unknown"), - maybe(&invocation["adapter"], "unknown") - )); - } - } - } - lines.extend([ - String::new(), - "Available Actions".to_string(), - format!("- {}", list_text(&scene["availableActions"], "none")), - ]); - format!("{}\n", lines.join("\n")) + lines.push(String::new()); + lines.join("\n") } pub fn sanitize_for_operator(value: Value) -> Value { match value { - Value::Object(map) => { + Value::Object(values) => { let mut sanitized = serde_json::Map::new(); - for (key, item) in map { - if SEALED_DIRECT_THOUGHT_KEYS - .iter() - .any(|candidate| candidate == &key) - { - sanitized.insert(key.clone(), sealed_direct_thought(&key, &item)); - } else if SEALED_LONG_TEXT_KEYS - .iter() - .any(|candidate| candidate == &key) - && let Some(text) = item.as_str() - && text.chars().count() > MAX_OPERATOR_TEXT_CHARS - { - sanitized.insert(key.clone(), sealed_long_text(&key, text)); + for (key, item) in values { + if SEALED_DIRECT_THOUGHT_KEYS.contains(&key.as_str()) { + continue; + } + if SEALED_LONG_TEXT_KEYS.contains(&key.as_str()) { + sanitized.insert(key, truncate_json_text(item)); } else { sanitized.insert(key, sanitize_for_operator(item)); } @@ -1354,199 +540,72 @@ pub fn sanitize_for_operator(value: Value) -> Value { } } -fn sealed_direct_thought(key: &str, value: &Value) -> Value { - let size = match value { - Value::String(text) => Some(text.chars().count()), - Value::Array(items) => Some(items.len()), - Value::Object(map) => Some(map.len()), - _ => None, +fn truncate_json_text(value: Value) -> Value { + let Value::String(text) = value else { + return sanitize_for_operator(value); }; - let mut sealed = json!({ - "sealed": true, - "key": key, - "reason": "Operator-safe dogfood views use projected findings and audit receipts; direct agent transcript/thought payloads stay sealed unless the user explicitly requests forensic debugging.", - }); - if let Some(size) = size { - sealed["size"] = json!(size); + let mut chars = text.chars(); + let truncated = chars.by_ref().take(MAX_OPERATOR_TEXT_CHARS).collect::(); + if chars.next().is_some() { + Value::String(format!("{truncated}…")) + } else { + Value::String(text) } - sealed } -fn sealed_long_text(key: &str, text: &str) -> Value { - let preview: String = text.chars().take(240).collect(); - json!({ - "sealed": true, - "key": key, - "reason": "Long operator note sealed to keep status artifacts readable; inspect the sealed transcript or prompt source only during explicit forensic debugging.", - "size": text.chars().count(), - "preview": preview, - }) +fn maybe(value: &Value, fallback: &str) -> String { + value + .as_str() + .map(str::to_string) + .unwrap_or_else(|| fallback.to_string()) } -pub fn native_json(bin_name: &str, args: &[&str]) -> Result { - let sibling = env::current_exe() - .ok() - .and_then(|path| path.parent().map(Path::to_path_buf)) - .map(|path| path.join(format!("{bin_name}.exe"))); - let configured = PathBuf::from( - env::var("CARGO_TARGET_DIR").unwrap_or_else(|_| DEFAULT_CARGO_TARGET_DIR.to_string()), - ) - .join("debug") - .join(format!("{bin_name}.exe")); - let exe = sibling.filter(|path| path.exists()).unwrap_or(configured); - if !exe.exists() { - return Err(anyhow!( - "optional projection executable is absent: {}", - exe.display() - )); - } - let output = Command::new(&exe) - .args(args) - .output() - .with_context(|| format!("failed to run {bin_name}"))?; - if !output.status.success() { - return Err(anyhow!( - "{} failed: {}{}", - bin_name, - String::from_utf8_lossy(&output.stderr), - String::from_utf8_lossy(&output.stdout) - )); - } - serde_json::from_slice(&output.stdout) - .with_context(|| format!("{bin_name} returned invalid JSON")) -} - -fn take_string(args: &mut impl Iterator, name: &str) -> Result { +fn take_string(args: &mut impl Iterator, flag: &str) -> Result { args.next() - .ok_or_else(|| anyhow!("{name} requires a value")) + .ok_or_else(|| anyhow!("{flag} requires a value")) } -fn take_path(args: &mut impl Iterator, name: &str) -> Result { - Ok(PathBuf::from(take_string(args, name)?)) -} - -#[cfg(test)] -mod native_interrupt_tests { - use super::*; - use epiphany_state_model::{EpiphanyJobBinding, EpiphanyJobKind}; - - #[test] - fn operator_projection_has_no_build_authority() { - let source = include_str!("epiphany-mvp-status.rs"); - let native_json = source - .split("pub fn native_json") - .nth(1) - .expect("native_json source"); - let native_json = native_json - .split("fn take_string") - .next() - .expect("native_json boundary"); - assert!(!native_json.contains("Command::new(\"cargo\")")); - assert!(source.contains("\"--coordinator-only\"")); - } - - #[test] - fn native_operator_contract_has_one_store_and_no_codex_state_field() { - let source = include_str!("epiphany-mvp-status.rs"); - let production = source.split("#[cfg(test)]").next().unwrap_or(source); - let compatibility_field = ["epiphany", "State"].concat(); - assert!(!production.contains(&compatibility_field)); - assert!(!production.contains("--thread-state-store")); - assert!(!production.contains("--runtime-store")); - assert!(production.contains("--store")); - } - - #[test] - fn default_status_interrupt_uses_native_coordinator_state() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("status-interrupt.cc"); - let service = epiphany_core::EpiphanyCoordinatorService::new(&store); - service.apply_state_update( - "thread-1", - epiphany_core::EpiphanyStateUpdate { - expected_revision: Some(0), - job_bindings: Some(vec![EpiphanyJobBinding { - id: "modeling-worker".to_string(), - kind: EpiphanyJobKind::Specialist, - scope: "model".to_string(), - owner_role: "modeling".to_string(), - authority_scope: Some("model".to_string()), - linked_subgoal_ids: Vec::new(), - linked_graph_node_ids: Vec::new(), - blocking_reason: None, - }]), - ..Default::default() - }, - None, - )?; - let args = Args { - thread_id: Some("thread-1".to_string()), - cwd: temp.path().to_path_buf(), - store, - ephemeral: true, - json: true, - result: None, - transcript: PathBuf::new(), - stderr: PathBuf::new(), - interrupt_binding: Some("modeling-worker".to_string()), - interrupt_reason: Some("native status proof".to_string()), - include_auxiliary_status: false, - }; - let result = run_status(&args)?; - assert_eq!(result["source"], "native"); - assert_eq!(result["cancelRequested"], false); - assert_eq!( - result["state"]["job_bindings"][0]["blocking_reason"], - "native status proof" - ); - Ok(()) - } +fn take_path(args: &mut impl Iterator, flag: &str) -> Result { + Ok(PathBuf::from(take_string(args, flag)?)) } pub fn absolute_path(path: &Path) -> Result { if path.is_absolute() { - Ok(path.to_path_buf()) - } else { - Ok(env::current_dir() - .context("failed to resolve current directory")? - .join(path)) + return Ok(path.to_path_buf()); } + Ok(env::current_dir() + .context("failed to resolve current directory")? + .join(path)) } -fn text(value: &Value) -> String { - value - .as_str() - .map(ToString::to_string) - .unwrap_or_else(|| value.to_string()) -} +#[cfg(test)] +mod tests { + use super::*; -fn maybe(value: &Value, fallback: &str) -> String { - if value.is_null() { - return fallback.to_string(); + #[test] + fn operator_projection_removes_direct_thought() { + let sanitized = sanitize_for_operator(json!({ + "rawResult": "private", + "decision": {"action": "continue"}, + })); + assert!(sanitized.get("rawResult").is_none()); + assert_eq!(sanitized["decision"]["action"], "continue"); } - if let Some(text) = value.as_str() { - if text.is_empty() { - return fallback.to_string(); + + #[test] + fn source_has_no_thread_aggregate_or_generic_interrupt() { + let source = include_str!("epiphany-mvp-status.rs"); + let production = source.split("#[cfg(test)]").next().unwrap_or(source); + for forbidden in [ + "EpiphanyThreadState", + "read_accepted_coordinator_state", + "latest_runtime_job_id_for_binding", + "derive_coordinator_finding_signals", + "expected_revision", + "interrupt_job", + "stateRevision", + ] { + assert!(!production.contains(forbidden)); } - return text.to_string(); - } - value.to_string() -} - -fn bool_text(value: &Value) -> &'static str { - if value.as_bool().unwrap_or(false) { - "true" - } else { - "false" } } - -fn list_text(value: &Value, fallback: &str) -> String { - let Some(items) = value.as_array() else { - return fallback.to_string(); - }; - if items.is_empty() { - return fallback.to_string(); - } - items.iter().map(text).collect::>().join(", ") -} diff --git a/epiphany-core/src/current_work.rs b/epiphany-core/src/current_work.rs index 76dbc7ab..258ccace 100644 --- a/epiphany-core/src/current_work.rs +++ b/epiphany-core/src/current_work.rs @@ -16,6 +16,7 @@ pub const BODY_MODELING_LAUNCH_BINDING_SCHEMA_VERSION: &str = "epiphany.runtime.body_modeling_launch.v1"; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] pub struct EpiphanyCurrentWorkProjection { pub mind_projection_digest: String, pub body_modeling: Option, @@ -26,6 +27,9 @@ pub struct EpiphanyCurrentWorkProjection { pub frontier_verdict_modeling: Option, pub verification: Option, pub reorientation: Option, + pub imagination_considerations: Vec, + pub admitted_model_direction_consideration: + Option, pub hands_frontier_ready: bool, } @@ -38,6 +42,7 @@ pub enum EpiphanyAgentPassContinuationAction { } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] pub struct EpiphanyProposalModelingWorkProjection { pub request: RepoFrontierProposalModelingRequest, pub action: EpiphanyAgentPassContinuationAction, @@ -45,6 +50,7 @@ pub struct EpiphanyProposalModelingWorkProjection { } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] pub struct EpiphanyFrontierVerdictModelingWorkProjection { pub request: crate::RepoFrontierModelingRequest, pub action: EpiphanyAgentPassContinuationAction, @@ -52,6 +58,7 @@ pub struct EpiphanyFrontierVerdictModelingWorkProjection { } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] pub struct EpiphanyVerificationWorkProjection { pub request: crate::RepoFrontierVerificationRequest, pub action: EpiphanyAgentPassContinuationAction, @@ -59,6 +66,23 @@ pub struct EpiphanyVerificationWorkProjection { } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct EpiphanyImaginationConsiderationWorkProjection { + pub request: crate::ImaginationConsiderationRequest, + pub action: EpiphanyAgentPassContinuationAction, + pub job_id: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct EpiphanyAdmittedModelDirectionConsiderationWorkProjection { + pub request: crate::AdmittedModelDirectionConsiderationRequest, + pub action: EpiphanyAgentPassContinuationAction, + pub job_id: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] pub struct EpiphanyBodyModelingWorkProjection { pub work_id: String, pub runtime_id: String, @@ -330,6 +354,15 @@ pub fn project_current_work(store_path: impl AsRef) -> Result) -> Result Result<(EpiphanyAgentPassContinuationAction, Option)> { + let Some(job_id) = job_ids.last() else { + return Ok((EpiphanyAgentPassContinuationAction::Launch, None)); + }; + let job = cache + .get::(job_id)? + .ok_or_else(|| anyhow!("consideration launch lost its runtime job"))?; + let action = match job.status { + crate::EpiphanyRuntimeJobStatus::Failed | crate::EpiphanyRuntimeJobStatus::Cancelled => { + EpiphanyAgentPassContinuationAction::Launch + } + _ => EpiphanyAgentPassContinuationAction::Wait, + }; + Ok((action, Some(job_id.clone()))) +} + +fn consideration_attempt_ordinal(request_id: &str, job_id: &str) -> Result { + let prefix = format!("consideration-{request_id}-attempt-"); + job_id + .strip_prefix(&prefix) + .ok_or_else(|| anyhow!("consideration job identity is not canonical"))? + .parse::() + .map_err(|_| anyhow!("consideration attempt ordinal is invalid")) +} + +fn current_imagination_consideration_work( + cache: &CultCache, +) -> Result> { + let model_basis = + crate::repo_model_documents::assemble_repo_model_view_from_cache(cache)?.reasoning_basis(); + let candidates = cache.get_all::()?; + let bindings = cache.get_all::()?; + let mut requests = cache.get_all::()?; + requests.sort_by(|left, right| left.request_id.cmp(&right.request_id)); + let mut work = Vec::new(); + for request in requests { + if request.model_projection_digest != model_basis.projection_digest + || request.model_source_documents != model_basis.source_documents + || candidates + .iter() + .any(|candidate| candidate.request_id == request.request_id) + { + continue; + } + crate::validate_current_imagination_consideration_request(cache, &request)?; + let mut launches = bindings + .iter() + .filter(|binding| binding.request_id == request.request_id) + .map(|binding| { + Ok(( + consideration_attempt_ordinal(&request.request_id, &binding.job_id)?, + binding.job_id.clone(), + )) + }) + .collect::>>()?; + launches.sort_by_key(|(ordinal, _)| *ordinal); + let launches = launches + .into_iter() + .map(|(_, job_id)| job_id) + .collect::>(); + let (action, job_id) = consideration_attempt_action(cache, &launches)?; + work.push(EpiphanyImaginationConsiderationWorkProjection { + request, + action, + job_id, + }); + } + Ok(work) +} + +fn current_admitted_model_direction_consideration_work( + cache: &CultCache, +) -> Result> { + let model_basis = + crate::repo_model_documents::assemble_repo_model_view_from_cache(cache)?.reasoning_basis(); + let results = cache.get_all::()?; + let launches = cache.get_all::()?; + let mut requests = cache.get_all::()?; + requests.sort_by(|left, right| left.request_id.cmp(&right.request_id)); + for request in requests.into_iter().rev() { + if request.model_projection_digest != model_basis.projection_digest + || request.model_source_documents != model_basis.source_documents + || results + .iter() + .any(|result| result.request_id == request.request_id && result.terminal) + { + continue; + } + crate::validate_current_admitted_model_direction_consideration_request(cache, &request)?; + let mut job_ids = launches + .iter() + .filter(|launch| { + launch + .admitted_model_direction_consideration_request_id + .as_deref() + == Some(request.request_id.as_str()) + }) + .map(|launch| { + Ok(( + consideration_attempt_ordinal(&request.request_id, &launch.job_id)?, + launch.job_id.clone(), + )) + }) + .collect::>>()?; + job_ids.sort_by_key(|(ordinal, _)| *ordinal); + let job_ids = job_ids + .into_iter() + .map(|(_, job_id)| job_id) + .collect::>(); + let (action, job_id) = consideration_attempt_action(cache, &job_ids)?; + return Ok(Some( + EpiphanyAdmittedModelDirectionConsiderationWorkProjection { + request, + action, + job_id, + }, + )); + } + Ok(None) +} + fn verification_attempt_ordinal(request_id: &str, job_id: &str) -> Result { let prefix = format!("frontier-verification-{request_id}-attempt-"); job_id @@ -666,6 +825,11 @@ pub fn current_body_modeling_review_job_id(store_path: impl AsRef) -> Resu { return Ok(None); } + current_body_modeling_job_id(store_path) +} + +pub fn current_body_modeling_job_id(store_path: impl AsRef) -> Result> { + let store_path = store_path.as_ref(); let mut cache = crate::runtime_spine_cache(store_path)?; cache.pull_all_backing_stores()?; let work = current_body_modeling_work(store_path)?; @@ -2155,6 +2319,306 @@ pub(crate) fn commit_current_work_launch( Ok(()) } +#[derive(Clone, Copy)] +enum ConsiderationLaunch<'a> { + PersonaFeedback(&'a crate::ImaginationConsiderationRequest), + AdmittedModelDirection(&'a crate::AdmittedModelDirectionConsiderationRequest), +} + +impl ConsiderationLaunch<'_> { + fn request_id(&self) -> &str { + match self { + Self::PersonaFeedback(request) => &request.request_id, + Self::AdmittedModelDirection(request) => &request.request_id, + } + } + + fn model_source_documents(&self) -> &[EpiphanyMindDocumentVersion] { + match self { + Self::PersonaFeedback(request) => &request.model_source_documents, + Self::AdmittedModelDirection(request) => &request.model_source_documents, + } + } +} + +fn exact_mind_source_envelopes( + cache: &CultCache, + sources: &[EpiphanyMindDocumentVersion], +) -> Result> { + let snapshot = cache.snapshot_envelopes(); + sources + .iter() + .map(|source| { + let envelope = snapshot + .iter() + .find(|envelope| { + envelope.r#type == source.document_type && envelope.key == source.document_key + }) + .ok_or_else(|| anyhow!("consideration launch lost exact Mind source"))?; + if EpiphanyMindDocumentVersion::from_envelope("epiphany-mind", envelope)? != *source { + return Err(anyhow!("consideration launch Mind source changed")); + } + Ok(envelope.clone()) + }) + .collect() +} + +fn launch_consideration_work( + store_path: &Path, + launch: ConsiderationLaunch<'_>, + created_at: &str, +) -> Result { + chrono::DateTime::parse_from_rfc3339(created_at) + .map_err(|_| anyhow!("consideration launch time is invalid"))?; + let mut cache = crate::runtime_spine_cache(store_path)?; + cache.pull_all_backing_stores()?; + let identity = cache + .get::(crate::RUNTIME_IDENTITY_KEY)? + .ok_or_else(|| anyhow!("consideration launch requires runtime identity"))?; + let model = crate::repo_model_documents::assemble_repo_model_view_from_cache(&cache)?; + let (attempt_ordinal, dynamic_prompt_context, imagination_context, direction_context) = + match launch { + ConsiderationLaunch::PersonaFeedback(request) => { + crate::validate_current_imagination_consideration_request(&cache, request)?; + let current = current_imagination_consideration_work(&cache)? + .into_iter() + .find(|work| work.request.request_id == request.request_id) + .ok_or_else(|| anyhow!("Persona feedback consideration is not current"))?; + if current.action != EpiphanyAgentPassContinuationAction::Launch { + return Err(anyhow!("Persona feedback consideration is not launchable")); + } + let ordinal = cache + .get_all::()? + .into_iter() + .filter(|binding| binding.request_id == request.request_id) + .count(); + ( + ordinal, + crate::render_imagination_consideration_prompt(request)?, + Some(crate::ImaginationConsiderationContextProjection::new( + request, &model, + )), + None, + ) + } + ConsiderationLaunch::AdmittedModelDirection(request) => { + crate::validate_current_admitted_model_direction_consideration_request( + &cache, request, + )?; + let current = current_admitted_model_direction_consideration_work(&cache)? + .filter(|work| work.request.request_id == request.request_id) + .ok_or_else(|| { + anyhow!("admitted model direction consideration is not current") + })?; + if current.action != EpiphanyAgentPassContinuationAction::Launch { + return Err(anyhow!( + "admitted model direction consideration is not launchable" + )); + } + let ordinal = cache + .get_all::()? + .into_iter() + .filter(|worker| { + worker + .admitted_model_direction_consideration_request_id + .as_deref() + == Some(request.request_id.as_str()) + }) + .count(); + ( + ordinal, + crate::render_admitted_model_direction_consideration_prompt(request), + None, + Some( + crate::AdmittedModelDirectionConsiderationContextProjection::new( + request, &model, + ), + ), + ) + } + }; + let request_id = launch.request_id().to_string(); + let job_id = format!("consideration-{request_id}-attempt-{attempt_ordinal}"); + let launch_document = + crate::EpiphanyWorkerLaunchDocument::Role(crate::EpiphanyRoleWorkerLaunchDocument { + thread_id: job_id.clone(), + role_id: "imagination".into(), + state_revision: 0, + objective: None, + dynamic_prompt_context: Some(dynamic_prompt_context), + repository_body_observation_basis: None, + proposal_modeling_context: None, + frontier_verdict_modeling_context: None, + frontier_planning_context: None, + frontier_research_context: None, + frontier_verification_context: None, + frontier_plan_mind_context: None, + imagination_consideration_context: imagination_context, + admitted_model_direction_consideration_context: direction_context, + active_subgoal_id: None, + active_subgoals: Vec::new(), + active_graph_node_ids: Vec::new(), + investigation_checkpoint: None, + scratch: None, + invariants: Vec::new(), + graphs: None, + recent_evidence: Vec::new(), + recent_observations: Vec::new(), + graph_frontier: None, + graph_checkpoint: None, + planning: None, + churn: None, + }); + let authority_scope = if matches!(launch, ConsiderationLaunch::PersonaFeedback(_)) { + "epiphany.imagination.persona_feedback_consideration.proposal_only" + } else { + "epiphany.imagination.admitted_model_direction_consideration.proposal_only" + } + .to_string(); + let output_contract_id = launch_document.output_contract_id().to_string(); + let is_feedback = matches!(launch, ConsiderationLaunch::PersonaFeedback(_)); + let prepared = crate::prepare_runtime_spine_heartbeat_job( + &cache, + crate::RuntimeSpineHeartbeatJobOptions { + runtime_id: identity.runtime_id, + display_name: "Epiphany Local".into(), + session_id: crate::EPIPHANY_RUNTIME_ROOT_SESSION_ID.into(), + objective: "Consider one exact typed proposal-only obligation".into(), + coordinator_note: "Consideration current-work launch opened this attempt.".into(), + job_id: job_id.clone(), + role: crate::EPIPHANY_IMAGINATION_OWNER_ROLE.into(), + binding_id: crate::EPIPHANY_IMAGINATION_ROLE_BINDING_ID.into(), + authority_scope: authority_scope.clone(), + instruction: "Act as Epiphany Imagination for one exact proposal-only typed consideration pass and return only its dedicated terminal contract.".into(), + launch_document, + output_contract_id: output_contract_id.clone(), + organ_launch_contract: crate::default_launch_organ_contract( + &authority_scope, + "role", + &output_contract_id, + ), + proposal_modeling_request_id: None, + frontier_planning_request_id: None, + frontier_plan_mind_request_id: None, + imagination_consideration_request_id: is_feedback.then_some(request_id.clone()), + admitted_model_direction_consideration_request_id: (!is_feedback) + .then_some(request_id.clone()), + repo_frontier_modeling_request_id: None, + repo_frontier_research_request_id: None, + repo_frontier_verification_request_id: None, + created_at: created_at.into(), + }, + )?; + let mut expected = vec![ + cache + .snapshot_envelopes() + .into_iter() + .find(|envelope| { + envelope.key == request_id && { + matches!( + launch, + ConsiderationLaunch::PersonaFeedback(_) + if envelope.r#type == crate::ImaginationConsiderationRequest::TYPE + ) || matches!( + launch, + ConsiderationLaunch::AdmittedModelDirection(_) + if envelope.r#type + == crate::AdmittedModelDirectionConsiderationRequest::TYPE + ) + } + }) + .ok_or_else(|| anyhow!("consideration launch lost its request envelope"))?, + ]; + expected.extend(exact_mind_source_envelopes( + &cache, + launch.model_source_documents(), + )?); + let mut companions = Vec::new(); + if let ConsiderationLaunch::PersonaFeedback(request) = launch { + let worker = prepared + .envelopes + .iter() + .find(|envelope| { + envelope.r#type == crate::EpiphanyRuntimeWorkerLaunchRequest::TYPE + && envelope.key == job_id + }) + .ok_or_else(|| anyhow!("consideration launch preparation lost its worker"))?; + let worker: crate::EpiphanyRuntimeWorkerLaunchRequest = + rmp_serde::from_slice(&worker.payload)?; + let binding_record_id = format!( + "imagination-consideration-launch-{}-attempt-{attempt_ordinal}", + request.request_id + ); + companions.push( + cache + .prepare_entry( + &binding_record_id, + &crate::ImaginationConsiderationLaunchBinding { + schema_version: + crate::IMAGINATION_CONSIDERATION_LAUNCH_BINDING_SCHEMA_VERSION.into(), + binding_record_id: binding_record_id.clone(), + request_id: request.request_id.clone(), + job_id: job_id.clone(), + binding_id: crate::EPIPHANY_IMAGINATION_ROLE_BINDING_ID.into(), + runtime_id: request.runtime_id.clone(), + thread_id: request.thread_id.clone(), + launched_at: created_at.into(), + worker_launch_document_sha256: format!( + "{:x}", + Sha256::digest(&worker.launch_document_msgpack) + ), + }, + )? + .0, + ); + } + commit_current_work_launch( + store_path, + &cache, + expected, + prepared.envelopes, + companions, + "consideration", + )?; + Ok(job_id) +} + +pub fn launch_current_imagination_consideration_work( + store_path: impl AsRef, + request_id: &str, + created_at: &str, +) -> Result { + let store_path = store_path.as_ref(); + let mut cache = crate::runtime_spine_cache(store_path)?; + cache.pull_all_backing_stores()?; + let request = cache + .get::(request_id)? + .ok_or_else(|| anyhow!("Persona feedback consideration request does not exist"))?; + launch_consideration_work( + store_path, + ConsiderationLaunch::PersonaFeedback(&request), + created_at, + ) +} + +pub fn launch_current_admitted_model_direction_consideration_work( + store_path: impl AsRef, + request_id: &str, + created_at: &str, +) -> Result { + let store_path = store_path.as_ref(); + let mut cache = crate::runtime_spine_cache(store_path)?; + cache.pull_all_backing_stores()?; + let request = cache + .get::(request_id)? + .ok_or_else(|| anyhow!("admitted model direction request does not exist"))?; + launch_consideration_work( + store_path, + ConsiderationLaunch::AdmittedModelDirection(&request), + created_at, + ) +} + pub fn launch_current_body_modeling_work( store_path: impl AsRef, options: EpiphanyBodyModelingLaunchOptions, diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index 2a76d596..c7b298d2 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -1216,14 +1216,11 @@ pub use surfaces::EpiphanyCoordinatorAction; pub use surfaces::EpiphanyCoordinatorAutomationAction; pub use surfaces::EpiphanyCoordinatorCrrcRecommendation; pub use surfaces::EpiphanyCoordinatorDecision; -pub use surfaces::EpiphanyCoordinatorFindingSignals; pub use surfaces::EpiphanyCoordinatorInput; pub use surfaces::EpiphanyCoordinatorRoleId; -pub use surfaces::EpiphanyCoordinatorRoleLane; pub use surfaces::EpiphanyCoordinatorRoleResultStatus; pub use surfaces::EpiphanyCoordinatorRoleStatus; pub use surfaces::EpiphanyCoordinatorSceneAction; -pub use surfaces::EpiphanyCoordinatorSignals; pub use surfaces::EpiphanyCoordinatorSourceSignals; pub use surfaces::EpiphanyCoordinatorStatus; pub use surfaces::EpiphanyCoordinatorStatusInput; @@ -1266,12 +1263,10 @@ pub use surfaces::EpiphanyReorientWorkerLaunchDocument; pub use surfaces::EpiphanyRetrievalFreshness; pub use surfaces::EpiphanyRetrievalFreshnessStatus; pub use surfaces::EpiphanyRoleAcceptanceFinding; -pub use surfaces::EpiphanyRoleBoardCheckpointSummary; pub use surfaces::EpiphanyRoleBoardInput; pub use surfaces::EpiphanyRoleBoardJob; pub use surfaces::EpiphanyRoleBoardJobStatus; pub use surfaces::EpiphanyRoleBoardLane; -pub use surfaces::EpiphanyRoleBoardPlanningSummary; pub use surfaces::EpiphanyRoleFindingInterpretation; pub use surfaces::EpiphanyRoleResultRoleId; pub use surfaces::EpiphanyRoleSelfPersistenceReview; @@ -1333,7 +1328,6 @@ pub use surfaces::interpret_runtime_role_worker_result; pub use surfaces::modeling_role_state_patch_policy_errors; pub use surfaces::recommend_crrc_action; pub use surfaces::render_role_board_note; -pub use surfaces::reorientation_role_status; pub use surfaces::research_role_state_patch_policy_errors; pub use surfaces::review_role_self_patch_document; pub use surfaces::role_board_job_status_to_role_status; diff --git a/epiphany-core/src/runtime_spine.rs b/epiphany-core/src/runtime_spine.rs index 12532feb..d4cd722c 100644 --- a/epiphany-core/src/runtime_spine.rs +++ b/epiphany-core/src/runtime_spine.rs @@ -4982,10 +4982,12 @@ pub fn put_runtime_role_worker_result( let bindings = cache .get_all::()? .into_iter() - .filter(|binding| binding.request_id == request_id) + .filter(|binding| binding.request_id == request_id && binding.job_id == result.job_id) .collect::>(); if bindings.len() != 1 { - return Err(anyhow!("consideration result requires one launch binding")); + return Err(anyhow!( + "consideration result requires one exact attempt binding" + )); } let binding = &bindings[0]; let worker = cache diff --git a/epiphany-core/src/surfaces/coordinator.rs b/epiphany-core/src/surfaces/coordinator.rs index 3a1e6b90..3397ae6c 100644 --- a/epiphany-core/src/surfaces/coordinator.rs +++ b/epiphany-core/src/surfaces/coordinator.rs @@ -1,104 +1,50 @@ -use epiphany_core::EpiphanyAgentPassContinuationAction; -use epiphany_core::EpiphanyCrrcAction; -use epiphany_core::EpiphanyCrrcSceneAction; -use epiphany_core::EpiphanyCrrcStateStatus; -use epiphany_core::EpiphanyReorientFindingInterpretation; -use epiphany_core::EpiphanyRoleBoardLane; -use epiphany_core::EpiphanyRoleFindingInterpretation; -use epiphany_core::RepoFrontierPlanningLifecycleStage; -use epiphany_core::RepoFrontierResearchContinuationAction; -use epiphany_core::modeling_role_state_patch_policy_errors; -use epiphany_core::research_role_state_patch_policy_errors; -use epiphany_state_model::EpiphanyThreadState; -use std::collections::HashSet; +use epiphany_core::{ + EpiphanyAgentPassContinuationAction, EpiphanyCoordinatorAction, + EpiphanyCoordinatorAutomationAction, EpiphanyCoordinatorCrrcRecommendation, + EpiphanyCoordinatorDecision, EpiphanyCoordinatorInput, EpiphanyCoordinatorRoleId, + EpiphanyCoordinatorSceneAction, EpiphanyCoordinatorSourceSignals, + EpiphanyCoordinatorStatus, EpiphanyCoordinatorStatusInput, EpiphanyCrrcAction, + EpiphanyCrrcSceneAction, RepoFrontierPlanningLifecycleStage, + RepoFrontierResearchContinuationAction, +}; -use epiphany_core::EpiphanyCoordinatorAction; -use epiphany_core::EpiphanyCoordinatorAutomationAction; -use epiphany_core::EpiphanyCoordinatorCrrcRecommendation; -use epiphany_core::EpiphanyCoordinatorDecision; -use epiphany_core::EpiphanyCoordinatorFindingSignals; -use epiphany_core::EpiphanyCoordinatorInput; -use epiphany_core::EpiphanyCoordinatorRoleId; -use epiphany_core::EpiphanyCoordinatorRoleLane; -use epiphany_core::EpiphanyCoordinatorRoleResultStatus; -use epiphany_core::EpiphanyCoordinatorRoleStatus; -use epiphany_core::EpiphanyCoordinatorSceneAction; -use epiphany_core::EpiphanyCoordinatorSignals; -use epiphany_core::EpiphanyCoordinatorSourceSignals; -use epiphany_core::EpiphanyCoordinatorStatus; -use epiphany_core::EpiphanyCoordinatorStatusInput; pub fn crrc_scene_action_to_coordinator_scene_action( action: EpiphanyCrrcSceneAction, ) -> EpiphanyCoordinatorSceneAction { match action { EpiphanyCrrcSceneAction::Update => EpiphanyCoordinatorSceneAction::Update, EpiphanyCrrcSceneAction::Reorient => EpiphanyCoordinatorSceneAction::Reorient, - EpiphanyCrrcSceneAction::ReorientLaunch => EpiphanyCoordinatorSceneAction::ReorientLaunch, - EpiphanyCrrcSceneAction::ReorientResult => EpiphanyCoordinatorSceneAction::ReorientResult, - EpiphanyCrrcSceneAction::ReorientAccept => EpiphanyCoordinatorSceneAction::ReorientAccept, + EpiphanyCrrcSceneAction::ReorientLaunch => { + EpiphanyCoordinatorSceneAction::ReorientLaunch + } + EpiphanyCrrcSceneAction::ReorientResult => { + EpiphanyCoordinatorSceneAction::ReorientResult + } + EpiphanyCrrcSceneAction::ReorientAccept => { + EpiphanyCoordinatorSceneAction::ReorientAccept + } } } -pub fn derive_coordinator_status( - input: EpiphanyCoordinatorStatusInput, -) -> EpiphanyCoordinatorStatus { +pub fn derive_coordinator_status(input: EpiphanyCoordinatorStatusInput) -> EpiphanyCoordinatorStatus { let source_signals = EpiphanyCoordinatorSourceSignals { pressure_level: input.pressure.level, should_prepare_compaction: input.pressure.should_prepare_compaction, reorient_action: input.reorient_action, crrc_action: input.recommendation.action, - research_result_status: input.research_result_status, - modeling_result_status: input.modeling_result_status, - verification_result_status: input.verification_result_status, reorient_result_status: input.reorient_result_status, }; - let coordinator_roles = input - .roles - .iter() - .map(coordinator_role_lane_from_role_board) - .collect(); - let routing_recommendation = routing_crrc_recommendation(&input.recommendation); let decision = recommend_coordinator_action(EpiphanyCoordinatorInput { - state_status: input.state_status, - checkpoint_present: input.checkpoint_present, + mind_present: input.mind_present, should_prepare_compaction: input.pressure.should_prepare_compaction, - recommendation: routing_recommendation, - roles: coordinator_roles, - signals: EpiphanyCoordinatorSignals { - research_result_status: input.research_result_status, - modeling_result_status: input.modeling_result_status, - verification_result_status: input.verification_result_status, + recommendation: EpiphanyCoordinatorCrrcRecommendation { + action: input.recommendation.action, + recommended_scene_action: input + .recommendation + .recommended_scene_action + .map(crrc_scene_action_to_coordinator_scene_action), }, - research_result_accepted: input.research_result_accepted, - research_result_reviewable: input.research_result_reviewable, - research_result_failure_reviewed: input.research_result_failure_reviewed, - modeling_result_accepted_after_research: input.modeling_result_accepted_after_research, - modeling_result_requests_regather: input.modeling_result_requests_regather, - modeling_result_accepted: input.modeling_result_accepted, - modeling_result_reviewable: input.modeling_result_reviewable, - modeling_result_failure_reviewed: input.modeling_result_failure_reviewed, - modeling_result_proposal_bound: input.modeling_result_proposal_bound, - modeling_result_accepted_after_verification: input - .modeling_result_accepted_after_verification, - implementation_evidence_after_verification: input - .implementation_evidence_after_verification, - verification_result_cites_implementation_evidence: input - .verification_result_cites_implementation_evidence, - verification_result_covers_current_modeling: input - .verification_result_covers_current_modeling, - verification_result_accepted: input.verification_result_accepted, - verification_result_failure_reviewed: input.verification_result_failure_reviewed, - verification_result_allows_implementation: input.verification_result_allows_implementation, - verification_result_needs_evidence: input.verification_result_needs_evidence, - reorient_finding_accepted: input.reorient_finding_accepted, - hands_frontier_ready: input.hands_frontier_ready, - research_continuation_action: input.research_continuation_action, - frontier_planning_stage: input.frontier_planning_stage, - proposal_modeling_action: input.proposal_modeling_action, - frontier_verdict_modeling_action: input.frontier_verdict_modeling_action, - verification_action: input.verification_action, - body_modeling_work_ready: input.body_modeling_work_ready, - body_modeling_review_ready: input.body_modeling_review_ready, + current_work: input.current_work, }); EpiphanyCoordinatorStatus { decision, @@ -107,881 +53,289 @@ pub fn derive_coordinator_status( } } -fn routing_crrc_recommendation( - recommendation: &epiphany_core::EpiphanyCrrcRecommendation, -) -> EpiphanyCoordinatorCrrcRecommendation { - EpiphanyCoordinatorCrrcRecommendation { - action: recommendation.action, - recommended_scene_action: recommendation - .recommended_scene_action - .map(crrc_scene_action_to_coordinator_scene_action), +pub fn recommend_coordinator_action(input: EpiphanyCoordinatorInput) -> EpiphanyCoordinatorDecision { + if !input.mind_present { + return decision( + EpiphanyCoordinatorAction::PrepareCheckpoint, + None, + Some(EpiphanyCoordinatorSceneAction::Update), + false, + false, + "Canonical keyed Mind is missing; admit an explicit operator objective before coordination continues.", + ); } -} -pub fn derive_coordinator_finding_signals( - state: Option<&EpiphanyThreadState>, - research_finding: Option<&EpiphanyRoleFindingInterpretation>, - modeling_finding: Option<&EpiphanyRoleFindingInterpretation>, - verification_finding: Option<&EpiphanyRoleFindingInterpretation>, - reorient_finding: Option<&EpiphanyReorientFindingInterpretation>, -) -> EpiphanyCoordinatorFindingSignals { - let research_result_accepted = research_finding.as_ref().is_some_and(|finding| { - state.is_some_and(|state| { - role_finding_already_accepted(state, EpiphanyCoordinatorRoleId::Research, finding) - }) - }); - let research_result_reviewable = - research_finding.is_some_and(research_finding_has_reviewable_state_patch); - let research_result_failure_reviewed = research_finding.as_ref().is_some_and(|finding| { - state.is_some_and(|state| { - role_finding_failure_reviewed(state, EpiphanyCoordinatorRoleId::Research, finding) - }) - }); - let modeling_result_accepted = modeling_finding.as_ref().is_some_and(|finding| { - state.is_some_and(|state| { - role_finding_already_accepted(state, EpiphanyCoordinatorRoleId::Modeling, finding) - }) - }); - let modeling_result_reviewable = - modeling_finding.is_some_and(modeling_finding_has_reviewable_repo_model_mutation); - let modeling_result_requests_regather = - modeling_finding.is_some_and(modeling_finding_requests_regather); - let modeling_result_failure_reviewed = modeling_finding.as_ref().is_some_and(|finding| { - state.is_some_and(|state| { - role_finding_failure_reviewed(state, EpiphanyCoordinatorRoleId::Modeling, finding) - }) - }); - let modeling_result_proposal_bound = - modeling_finding.is_some_and(|finding| finding.proposal_modeling_request_id.is_some()); - let verification_result_accepted = verification_finding.as_ref().is_some_and(|finding| { - state.is_some_and(|state| { - role_finding_already_accepted(state, EpiphanyCoordinatorRoleId::Verification, finding) - }) - }); - let verification_result_failure_reviewed = - verification_finding.as_ref().is_some_and(|finding| { - state.is_some_and(|state| { - role_finding_failure_reviewed( - state, - EpiphanyCoordinatorRoleId::Verification, - finding, - ) - }) - }); - let verification_result_cites_implementation_evidence = state.is_some_and(|state| { - role_finding_cites_implementation_evidence(state, verification_finding) - }); - let verification_result_covers_current_modeling = state.is_none_or(|state| { - verification_finding_covers_current_modeling( - state, - modeling_result_accepted, - modeling_finding, - verification_finding, - ) || verification_result_cites_implementation_evidence - }); - let modeling_result_accepted_after_verification = state.is_some_and(|state| { - role_finding_accepted_after( - state, - EpiphanyCoordinatorRoleId::Modeling, - modeling_finding, + if let Some(work) = input.current_work.reorientation.as_ref() { + return continuation_decision( + work.action, + EpiphanyCoordinatorAction::LaunchReorientWorker, + EpiphanyCoordinatorAction::WaitForReorientWorker, + EpiphanyCoordinatorAction::ReviewReorientResult, + EpiphanyCoordinatorRoleId::Reorientation, + "continuity", + ); + } + + if input.should_prepare_compaction { + return decision( + EpiphanyCoordinatorAction::CompactRehydrateReorient, + Some(EpiphanyCoordinatorRoleId::Reorientation), + Some(EpiphanyCoordinatorSceneAction::Reorient), + false, + true, + "Context pressure requires a new continuity obligation over the current keyed Mind.", + ); + } + + if input.recommendation.action == EpiphanyCrrcAction::RegatherManually { + return decision( + EpiphanyCoordinatorAction::RegatherManually, + Some(EpiphanyCoordinatorRoleId::Research), + Some(EpiphanyCoordinatorSceneAction::Reorient), + true, + false, + "The accepted continuity decision requires explicit operator regather.", + ); + } + + if let Some(result) = planning_decision(input.current_work.frontier_planning_stage) { + return result; + } + + if let Some(work) = input.current_work.proposal_modeling.as_ref() { + return modeling_decision(work.action, "proposal Modeling"); + } + if let Some(action) = input.current_work.body_modeling_action { + return modeling_decision(action, "Body Modeling"); + } + if let Some(work) = input.current_work.frontier_verdict_modeling.as_ref() { + return modeling_decision(work.action, "frontier-verdict Modeling"); + } + if let Some(work) = input.current_work.verification.as_ref() { + return continuation_decision( + work.action, + EpiphanyCoordinatorAction::LaunchVerification, + EpiphanyCoordinatorAction::ReviewVerificationResult, + EpiphanyCoordinatorAction::ReviewVerificationResult, EpiphanyCoordinatorRoleId::Verification, - verification_finding, - ) - }); - let modeling_result_accepted_after_research = state.is_some_and(|state| { - role_finding_accepted_after( - state, - EpiphanyCoordinatorRoleId::Modeling, - modeling_finding, - EpiphanyCoordinatorRoleId::Research, - research_finding, - ) - }); - let implementation_evidence_after_verification = state.is_some_and(|state| { - implementation_evidence_after_role_finding( - state, - EpiphanyCoordinatorRoleId::Verification, - verification_finding, - ) - }); - let verification_result_allows_implementation = verification_result_accepted - && verification_finding.is_some_and(verification_finding_allows_implementation); - let verification_result_needs_evidence = verification_result_accepted - && verification_finding.is_some_and(verification_finding_needs_evidence); - let reorient_finding_accepted = reorient_finding.as_ref().is_some_and(|finding| { - state.is_some_and(|state| reorient_finding_already_accepted(state, finding)) - }); - - EpiphanyCoordinatorFindingSignals { - research_result_accepted, - research_result_reviewable, - research_result_failure_reviewed, - modeling_result_accepted_after_research, - modeling_result_requests_regather, - modeling_result_accepted, - modeling_result_reviewable, - modeling_result_failure_reviewed, - modeling_result_proposal_bound, - modeling_result_accepted_after_verification, - implementation_evidence_after_verification, - verification_result_cites_implementation_evidence, - verification_result_covers_current_modeling, - verification_result_accepted, - verification_result_failure_reviewed, - verification_result_allows_implementation, - verification_result_needs_evidence, - reorient_finding_accepted, + "Verification", + ); } -} - -pub fn reorient_finding_already_accepted( - state: &EpiphanyThreadState, - finding: &EpiphanyReorientFindingInterpretation, -) -> bool { - if let Some(result_id) = finding.runtime_result_id.clone() - && state.acceptance_receipts.iter().any(|receipt| { - receipt.result_id == result_id - && receipt.status == "accepted" - && receipt.surface == "reorientAccept" - }) - { - return true; + if let Some(action) = input.current_work.research_continuation_action { + return match action { + RepoFrontierResearchContinuationAction::LaunchResearch => decision( + EpiphanyCoordinatorAction::LaunchResearch, + Some(EpiphanyCoordinatorRoleId::Research), + Some(EpiphanyCoordinatorSceneAction::RoleLaunch), + false, + true, + "The exact external-evidence obligation requires an Eyes attempt.", + ), + RepoFrontierResearchContinuationAction::ReviewResearchResult => decision( + EpiphanyCoordinatorAction::ReviewResearchResult, + Some(EpiphanyCoordinatorRoleId::Research), + Some(EpiphanyCoordinatorSceneAction::RoleResult), + true, + false, + "The exact Eyes result awaits Mind admission.", + ), + }; } - false -} - -fn modeling_finding_has_reviewable_repo_model_mutation( - finding: &EpiphanyRoleFindingInterpretation, -) -> bool { - finding.item_error.is_none() - && finding.job_error.is_none() - && (finding.repo_model_mutation_proposal.is_some() - || finding.verdict.as_deref().is_some_and(|verdict| { - verdict.eq_ignore_ascii_case("checkpoint-ready") - || verdict.eq_ignore_ascii_case("regather-needed") - })) - && finding - .state_patch - .as_ref() - .is_none_or(|patch| modeling_role_state_patch_policy_errors(patch).is_empty()) -} - -fn research_finding_has_reviewable_state_patch( - finding: &EpiphanyRoleFindingInterpretation, -) -> bool { - finding - .state_patch + if let Some(work) = input.current_work.imagination_considerations.first() { + return continuation_decision( + work.action, + EpiphanyCoordinatorAction::LaunchImaginationConsideration, + EpiphanyCoordinatorAction::WaitForImaginationConsideration, + EpiphanyCoordinatorAction::WaitForImaginationConsideration, + EpiphanyCoordinatorRoleId::Imagination, + "Persona-feedback Imagination consideration", + ); + } + if let Some(work) = input + .current_work + .admitted_model_direction_consideration .as_ref() - .is_some_and(|patch| research_role_state_patch_policy_errors(patch).is_empty()) -} - -fn modeling_finding_requests_regather(finding: &EpiphanyRoleFindingInterpretation) -> bool { - finding - .verdict - .as_deref() - .is_some_and(|verdict| verdict.eq_ignore_ascii_case("regather-needed")) -} - -fn role_finding_already_accepted( - state: &EpiphanyThreadState, - role_id: EpiphanyCoordinatorRoleId, - finding: &EpiphanyRoleFindingInterpretation, -) -> bool { - role_finding_accepted_index(state, role_id, finding).is_some() -} - -fn role_finding_failure_reviewed( - state: &EpiphanyThreadState, - role_id: EpiphanyCoordinatorRoleId, - finding: &EpiphanyRoleFindingInterpretation, -) -> bool { - let Some(result_id) = finding.runtime_result_id.as_deref() else { - return false; - }; - state.acceptance_receipts.iter().any(|receipt| { - receipt.result_id == result_id - && receipt.status == "superseded" - && receipt.surface == "roleFailureReview" - && receipt.role_id == coordinator_role_label(role_id) - }) -} - -fn role_finding_accepted_evidence_id( - state: &EpiphanyThreadState, - role_id: EpiphanyCoordinatorRoleId, - finding: &EpiphanyRoleFindingInterpretation, -) -> Option { - role_finding_acceptance_receipt(state, role_id, finding) - .and_then(|receipt| receipt.accepted_evidence_id.clone()) -} - -fn verification_finding_covers_current_modeling( - state: &EpiphanyThreadState, - modeling_result_accepted: bool, - modeling_finding: Option<&EpiphanyRoleFindingInterpretation>, - verification_finding: Option<&EpiphanyRoleFindingInterpretation>, -) -> bool { - if !modeling_result_accepted { - return true; + { + return continuation_decision( + work.action, + EpiphanyCoordinatorAction::LaunchAdmittedModelDirectionConsideration, + EpiphanyCoordinatorAction::WaitForAdmittedModelDirectionConsideration, + EpiphanyCoordinatorAction::WaitForAdmittedModelDirectionConsideration, + EpiphanyCoordinatorRoleId::Imagination, + "admitted-model direction consideration", + ); } - let Some(modeling_finding) = modeling_finding else { - return true; - }; - let Some(verification_finding) = verification_finding else { - return false; - }; - let mut modeling_evidence_ids: HashSet = - modeling_finding.evidence_ids.iter().cloned().collect(); - if let Some(accepted_id) = role_finding_accepted_evidence_id( - state, - EpiphanyCoordinatorRoleId::Modeling, - modeling_finding, - ) { - modeling_evidence_ids.insert(accepted_id); + if input.current_work.hands_frontier_ready { + return decision( + EpiphanyCoordinatorAction::ContinueImplementation, + Some(EpiphanyCoordinatorRoleId::Implementation), + None, + false, + false, + "Mind has an exact actionable Hands frontier route.", + ); } - if modeling_evidence_ids.is_empty() { - return true; - } - verification_finding - .evidence_ids - .iter() - .any(|id| modeling_evidence_ids.contains(id)) + + decision( + EpiphanyCoordinatorAction::AwaitFrontierProposal, + Some(EpiphanyCoordinatorRoleId::Imagination), + None, + false, + false, + "No unresolved typed work obligation exists; await a new Body, evidence, proposal, or continuity mutation.", + ) } -fn role_finding_accepted_after( - state: &EpiphanyThreadState, - later_role_id: EpiphanyCoordinatorRoleId, - later: Option<&EpiphanyRoleFindingInterpretation>, - earlier_role_id: EpiphanyCoordinatorRoleId, - earlier: Option<&EpiphanyRoleFindingInterpretation>, -) -> bool { - let Some(later) = later else { - return false; - }; - let Some(later_index) = role_finding_accepted_order_index(state, later_role_id, later) else { - return false; - }; - let Some(earlier) = earlier else { - return true; - }; - let Some(earlier_index) = role_finding_accepted_order_index(state, earlier_role_id, earlier) - else { - return true; - }; - later_index < earlier_index -} - -fn implementation_evidence_after_role_finding( - state: &EpiphanyThreadState, - role_id: EpiphanyCoordinatorRoleId, - earlier: Option<&EpiphanyRoleFindingInterpretation>, -) -> bool { - let earlier_index = - earlier.and_then(|finding| role_finding_accepted_index(state, role_id, finding)); - state - .recent_evidence - .iter() - .enumerate() - .find(|(index, evidence)| { - evidence.kind == "implementation-audit" - && earlier_index.is_none_or(|earlier_index| *index < earlier_index) - }) - .is_some_and(|(_, evidence)| evidence.status == "ok") -} - -fn role_finding_cites_implementation_evidence( - state: &EpiphanyThreadState, - finding: Option<&EpiphanyRoleFindingInterpretation>, -) -> bool { - let Some(finding) = finding else { - return false; - }; - if role_finding_cites_complete_hands_receipt_chain(finding) { - return true; - } - finding.evidence_ids.iter().any(|id| { - state.recent_evidence.iter().any(|evidence| { - evidence.id == *id && evidence.kind == "implementation-audit" && evidence.status == "ok" - }) - }) -} - -fn role_finding_cites_complete_hands_receipt_chain( - finding: &EpiphanyRoleFindingInterpretation, -) -> bool { - let has_patch = finding - .evidence_ids - .iter() - .any(|id| id.starts_with("hands-patch-")); - let has_command = finding - .evidence_ids - .iter() - .any(|id| id.starts_with("hands-command-")); - let has_commit = finding - .evidence_ids - .iter() - .any(|id| id.starts_with("hands-commit-")); - has_patch && has_command && has_commit -} - -fn role_finding_accepted_index( - state: &EpiphanyThreadState, - role_id: EpiphanyCoordinatorRoleId, - finding: &EpiphanyRoleFindingInterpretation, -) -> Option { - if let Some(receipt) = role_finding_acceptance_receipt(state, role_id, finding) { - return receipt - .accepted_evidence_id - .as_ref() - .and_then(|id| { - state - .recent_evidence - .iter() - .position(|evidence| evidence.id == *id) - }) - .or(Some(0)); - } - None -} - -fn role_finding_accepted_order_index( - state: &EpiphanyThreadState, - role_id: EpiphanyCoordinatorRoleId, - finding: &EpiphanyRoleFindingInterpretation, -) -> Option { - role_finding_acceptance_receipt_index(state, role_id, finding) -} - -fn role_finding_acceptance_receipt<'a>( - state: &'a EpiphanyThreadState, - role_id: EpiphanyCoordinatorRoleId, - finding: &EpiphanyRoleFindingInterpretation, -) -> Option<&'a epiphany_state_model::EpiphanyAcceptanceReceipt> { - let result_id = finding.runtime_result_id.clone()?; - state.acceptance_receipts.iter().find(|receipt| { - receipt.result_id == result_id - && receipt.status == "accepted" - && receipt.surface == "roleAccept" - && receipt.role_id == coordinator_role_label(role_id) - }) -} - -fn role_finding_acceptance_receipt_index( - state: &EpiphanyThreadState, - role_id: EpiphanyCoordinatorRoleId, - finding: &EpiphanyRoleFindingInterpretation, -) -> Option { - let result_id = finding.runtime_result_id.clone()?; - state.acceptance_receipts.iter().position(|receipt| { - receipt.result_id == result_id - && receipt.status == "accepted" - && receipt.surface == "roleAccept" - && receipt.role_id == coordinator_role_label(role_id) - }) -} - -fn coordinator_role_label(role_id: EpiphanyCoordinatorRoleId) -> &'static str { - match role_id { - EpiphanyCoordinatorRoleId::Implementation => "implementation", - EpiphanyCoordinatorRoleId::Imagination => "imagination", - EpiphanyCoordinatorRoleId::Research => "research", - EpiphanyCoordinatorRoleId::Modeling => "modeling", - EpiphanyCoordinatorRoleId::Verification => "verification", - EpiphanyCoordinatorRoleId::Reorientation => "reorientation", - } -} - -fn verification_finding_allows_implementation(finding: &EpiphanyRoleFindingInterpretation) -> bool { - finding - .verdict - .as_deref() - .is_some_and(|verdict| verdict.eq_ignore_ascii_case("pass")) -} - -fn verification_finding_needs_evidence(finding: &EpiphanyRoleFindingInterpretation) -> bool { - finding - .verdict - .as_deref() - .is_some_and(|verdict| verdict.eq_ignore_ascii_case("needs-evidence")) -} - -fn coordinator_role_lane_from_role_board( - lane: &EpiphanyRoleBoardLane, -) -> EpiphanyCoordinatorRoleLane { - EpiphanyCoordinatorRoleLane { - id: lane.id, - status: lane.status, - } -} - -pub fn recommend_coordinator_action( - input: EpiphanyCoordinatorInput, +fn decision( + action: EpiphanyCoordinatorAction, + target_role: Option, + recommended_scene_action: Option, + requires_review: bool, + can_auto_run: bool, + reason: &str, ) -> EpiphanyCoordinatorDecision { - let build = |action, - target_role, - recommended_scene_action, - requires_review, - can_auto_run, - reason: &str| EpiphanyCoordinatorDecision { + EpiphanyCoordinatorDecision { action, target_role, recommended_scene_action, requires_review, can_auto_run, reason: reason.to_string(), - }; - - if input.state_status == EpiphanyCrrcStateStatus::Missing { - return build( - EpiphanyCoordinatorAction::PrepareCheckpoint, - Some(EpiphanyCoordinatorRoleId::Modeling), - Some(EpiphanyCoordinatorSceneAction::Update), - false, - false, - "Authoritative state is missing; accept an explicit operator objective before coordination can continue.", - ); } +} - match input.recommendation.action { - EpiphanyCrrcAction::WaitForReorientWorker => { - return build( - EpiphanyCoordinatorAction::WaitForReorientWorker, - Some(EpiphanyCoordinatorRoleId::Reorientation), - Some(EpiphanyCoordinatorSceneAction::ReorientResult), - false, - false, - "A CRRC reorient worker is already in flight; wait for the bounded result.", - ); - } - EpiphanyCrrcAction::AcceptReorientResult | EpiphanyCrrcAction::ReviewReorientResult => { - return build( - EpiphanyCoordinatorAction::ReviewReorientResult, - Some(EpiphanyCoordinatorRoleId::Reorientation), - input.recommendation.recommended_scene_action, - true, - false, - "A CRRC reorientation finding needs human review before continuation.", - ); - } - EpiphanyCrrcAction::PrepareCheckpoint - | EpiphanyCrrcAction::LaunchReorientWorker - | EpiphanyCrrcAction::RegatherManually - | EpiphanyCrrcAction::Continue => {} - } +fn modeling_decision( + action: EpiphanyAgentPassContinuationAction, + label: &str, +) -> EpiphanyCoordinatorDecision { + continuation_decision( + action, + EpiphanyCoordinatorAction::LaunchModeling, + EpiphanyCoordinatorAction::WaitForModelingResult, + EpiphanyCoordinatorAction::ReviewModelingResult, + EpiphanyCoordinatorRoleId::Modeling, + label, + ) +} - if input.should_prepare_compaction - && !(input.reorient_finding_accepted - && input.recommendation.action == EpiphanyCrrcAction::Continue) - { - return build( - EpiphanyCoordinatorAction::CompactRehydrateReorient, - Some(EpiphanyCoordinatorRoleId::Reorientation), - Some(EpiphanyCoordinatorSceneAction::Reorient), - false, - true, - "Context pressure crossed the preparation threshold; compact, rehydrate, and reorient before more implementation work.", - ); - } - - if input.recommendation.action == EpiphanyCrrcAction::LaunchReorientWorker { - return build( - EpiphanyCoordinatorAction::LaunchReorientWorker, - Some(EpiphanyCoordinatorRoleId::Reorientation), - Some(EpiphanyCoordinatorSceneAction::ReorientLaunch), - false, - true, - "CRRC says continuity needs a bounded reorient worker before safe continuation.", - ); - } - - match input.frontier_planning_stage { - RepoFrontierPlanningLifecycleStage::Ready => { - return build( - EpiphanyCoordinatorAction::StartFrontierPlanning, - Some(EpiphanyCoordinatorRoleId::Imagination), - None, - false, - true, - "Mind has admitted one actionable Imagination frontier; commit its typed planning request before launching a worker.", - ); - } - RepoFrontierPlanningLifecycleStage::ImaginationLaunchReady => { - return build( - EpiphanyCoordinatorAction::LaunchImagination, - Some(EpiphanyCoordinatorRoleId::Imagination), - Some(EpiphanyCoordinatorSceneAction::RoleLaunch), - false, - true, - "A current frontier planning request is committed; launch Imagination against that exact authority.", - ); - } - RepoFrontierPlanningLifecycleStage::ImaginationRunning => { - return build( - EpiphanyCoordinatorAction::WaitForImaginationResult, - Some(EpiphanyCoordinatorRoleId::Imagination), - Some(EpiphanyCoordinatorSceneAction::RoleResult), - false, - false, - "The frontier-bound Imagination worker is running; wait for its typed result.", - ); - } - RepoFrontierPlanningLifecycleStage::ImaginationFailed => { - return build( - EpiphanyCoordinatorAction::ReviewFrontierPlanningFailure, - Some(EpiphanyCoordinatorRoleId::Imagination), - Some(EpiphanyCoordinatorSceneAction::RoleResult), - true, - false, - "The frontier-bound Imagination worker terminated without a valid typed candidate; review the immutable failure before creating new authority.", - ); - } - RepoFrontierPlanningLifecycleStage::ImaginationResultReady => { - return build( - EpiphanyCoordinatorAction::RequestMindPlanReview, - None, - None, - false, - true, - "Imagination produced a typed frontier plan; commit the dedicated Mind review request without adopting it.", - ); - } - RepoFrontierPlanningLifecycleStage::MindLaunchReady => { - return build( - EpiphanyCoordinatorAction::LaunchMindPlanReview, - None, - Some(EpiphanyCoordinatorSceneAction::RoleLaunch), - false, - true, - "The typed Mind review request is committed; launch the dedicated admission reviewer.", - ); - } - RepoFrontierPlanningLifecycleStage::MindRunning => { - return build( - EpiphanyCoordinatorAction::WaitForMindPlanResult, - None, - Some(EpiphanyCoordinatorSceneAction::RoleResult), - false, - false, - "Mind is reviewing the proposed frontier plan; wait for its typed decision result.", - ); - } - RepoFrontierPlanningLifecycleStage::MindFailed => { - return build( - EpiphanyCoordinatorAction::ReviewFrontierPlanningFailure, - None, - Some(EpiphanyCoordinatorSceneAction::RoleResult), - true, - false, - "The dedicated Mind reviewer terminated without a valid typed judgment; review the immutable failure before any plan decision.", - ); - } - RepoFrontierPlanningLifecycleStage::MindResultReady => { - return build( - EpiphanyCoordinatorAction::CommitFrontierPlanDecision, - None, - None, - false, - true, - "Mind returned a typed frontier-plan judgment; atomically commit that decision as the sole adoption authority.", - ); - } - RepoFrontierPlanningLifecycleStage::Unavailable - | RepoFrontierPlanningLifecycleStage::Terminal => {} - } - - if let Some(action) = input.proposal_modeling_action { - return match action { - EpiphanyAgentPassContinuationAction::Launch => build( - EpiphanyCoordinatorAction::LaunchModeling, - Some(EpiphanyCoordinatorRoleId::Modeling), - Some(EpiphanyCoordinatorSceneAction::RoleLaunch), - false, - true, - "The oldest unresolved proposal request is ready for its exact Modeling attempt.", - ), - EpiphanyAgentPassContinuationAction::Wait => build( - EpiphanyCoordinatorAction::WaitForModelingResult, - Some(EpiphanyCoordinatorRoleId::Modeling), - Some(EpiphanyCoordinatorSceneAction::RoleResult), - false, - false, - "The exact proposal Modeling attempt is still running.", - ), - EpiphanyAgentPassContinuationAction::Review => build( - EpiphanyCoordinatorAction::ReviewModelingResult, - Some(EpiphanyCoordinatorRoleId::Modeling), - Some(EpiphanyCoordinatorSceneAction::RoleResult), - true, - false, - "The exact proposal Modeling result awaits keyed Mind admission.", - ), - }; - } - - if input.body_modeling_review_ready { - return build( - EpiphanyCoordinatorAction::ReviewModelingResult, - Some(EpiphanyCoordinatorRoleId::Modeling), - Some(EpiphanyCoordinatorSceneAction::RoleResult), - true, - false, - "The exact Body Modeling attempt has a terminal typed result awaiting keyed Mind admission.", - ); - } - - if input.body_modeling_work_ready { - return build( - EpiphanyCoordinatorAction::LaunchModeling, - Some(EpiphanyCoordinatorRoleId::Modeling), +fn continuation_decision( + action: EpiphanyAgentPassContinuationAction, + launch: EpiphanyCoordinatorAction, + wait: EpiphanyCoordinatorAction, + review: EpiphanyCoordinatorAction, + role: EpiphanyCoordinatorRoleId, + label: &str, +) -> EpiphanyCoordinatorDecision { + match action { + EpiphanyAgentPassContinuationAction::Launch => decision( + launch, + Some(role), Some(EpiphanyCoordinatorSceneAction::RoleLaunch), false, true, - "The admitted repository Body has unresolved Modeling work; launch it from the keyed Mind obligation.", - ); - } - - if let Some(action) = input.frontier_verdict_modeling_action { - return match action { - EpiphanyAgentPassContinuationAction::Launch => build( - EpiphanyCoordinatorAction::LaunchModeling, - Some(EpiphanyCoordinatorRoleId::Modeling), - Some(EpiphanyCoordinatorSceneAction::RoleLaunch), - false, - true, - "An exact Soul verdict has unresolved keyed frontier Modeling work.", - ), - EpiphanyAgentPassContinuationAction::Wait => build( - EpiphanyCoordinatorAction::WaitForModelingResult, - Some(EpiphanyCoordinatorRoleId::Modeling), - Some(EpiphanyCoordinatorSceneAction::RoleResult), - false, - false, - "The exact frontier verdict Modeling attempt is still running.", - ), - EpiphanyAgentPassContinuationAction::Review => build( - EpiphanyCoordinatorAction::ReviewModelingResult, - Some(EpiphanyCoordinatorRoleId::Modeling), - Some(EpiphanyCoordinatorSceneAction::RoleResult), - true, - false, - "The exact frontier verdict Modeling result awaits keyed Mind admission.", - ), - }; - } - - if let Some(action) = input.verification_action { - return match action { - EpiphanyAgentPassContinuationAction::Launch => build( - EpiphanyCoordinatorAction::LaunchVerification, - Some(EpiphanyCoordinatorRoleId::Verification), - Some(EpiphanyCoordinatorSceneAction::RoleLaunch), - false, - true, - "An exact Hands consequence has unresolved keyed Verification work.", - ), - EpiphanyAgentPassContinuationAction::Wait => build( - EpiphanyCoordinatorAction::ReviewVerificationResult, - Some(EpiphanyCoordinatorRoleId::Verification), - Some(EpiphanyCoordinatorSceneAction::RoleResult), - false, - false, - "The exact frontier Verification attempt is still running.", - ), - EpiphanyAgentPassContinuationAction::Review => build( - EpiphanyCoordinatorAction::ReviewVerificationResult, - Some(EpiphanyCoordinatorRoleId::Verification), - Some(EpiphanyCoordinatorSceneAction::RoleResult), - true, - false, - "The exact frontier Verification result awaits Soul admission.", - ), - }; - } - - if let Some(action) = input.research_continuation_action { - return match action { - RepoFrontierResearchContinuationAction::LaunchResearch => build( - EpiphanyCoordinatorAction::LaunchResearch, - Some(EpiphanyCoordinatorRoleId::Research), - Some(EpiphanyCoordinatorSceneAction::RoleLaunch), - false, - true, - "The exact frontier Research lifecycle requires another bounded attempt.", - ), - RepoFrontierResearchContinuationAction::ReviewResearchResult => build( - EpiphanyCoordinatorAction::ReviewResearchResult, - Some(EpiphanyCoordinatorRoleId::Research), - Some(EpiphanyCoordinatorSceneAction::RoleResult), - true, - false, - "The exact frontier Research lifecycle has one terminal result awaiting review.", - ), - }; - } - - if input.signals.modeling_result_status == EpiphanyCoordinatorRoleResultStatus::Completed - && !input.modeling_result_accepted - && !(input.modeling_result_failure_reviewed && input.hands_frontier_ready) - { - if input.modeling_result_failure_reviewed { - if input.modeling_result_proposal_bound && !input.hands_frontier_ready { - return build( - EpiphanyCoordinatorAction::AwaitFrontierProposal, - Some(EpiphanyCoordinatorRoleId::Imagination), - None, - true, - false, - "The proposal-bound Modeling result was rejected and its immutable selection request is consumed; await a fresh typed proposal instead of replaying old authority.", - ); - } - if !input.modeling_result_proposal_bound { - return build( - EpiphanyCoordinatorAction::LaunchModeling, - Some(EpiphanyCoordinatorRoleId::Modeling), - Some(EpiphanyCoordinatorSceneAction::RoleLaunch), - false, - true, - "The completed Modeling result was rejected by admission and superseded; relaunch Modeling against current typed authority.", - ); - } - } - if !input.modeling_result_reviewable { - return build( - EpiphanyCoordinatorAction::ReviewModelingResult, - Some(EpiphanyCoordinatorRoleId::Modeling), - Some(EpiphanyCoordinatorSceneAction::RoleResult), - false, - false, - "The completed Modeling finding has no acceptable RepoModel proposal; inspect the finding instead of relaunching the same lane.", - ); - } - return build( - EpiphanyCoordinatorAction::ReviewModelingResult, - Some(EpiphanyCoordinatorRoleId::Modeling), + &format!("The exact {label} obligation has no live attempt."), + ), + EpiphanyAgentPassContinuationAction::Wait => decision( + wait, + Some(role), + Some(EpiphanyCoordinatorSceneAction::RoleResult), + false, + false, + &format!("The exact {label} attempt is still live."), + ), + EpiphanyAgentPassContinuationAction::Review => decision( + review, + Some(role), Some(EpiphanyCoordinatorSceneAction::RoleResult), true, false, - "A modeling/checkpoint finding is complete and must be reviewed before verification or implementation continues.", - ); + &format!("The exact {label} result awaits its family admission owner."), + ), } +} - if input.signals.modeling_result_status == EpiphanyCoordinatorRoleResultStatus::Failed - && !input.modeling_result_accepted - { - if input.modeling_result_failure_reviewed { - return build( - EpiphanyCoordinatorAction::LaunchModeling, - Some(EpiphanyCoordinatorRoleId::Modeling), - Some(EpiphanyCoordinatorSceneAction::RoleLaunch), - false, - true, - "The failed modeling/checkpoint result was reviewed and superseded; relaunch Modeling before verification or implementation continues.", - ); - } - return build( - EpiphanyCoordinatorAction::ReviewModelingResult, - Some(EpiphanyCoordinatorRoleId::Modeling), - Some(EpiphanyCoordinatorSceneAction::RoleResult), - false, - false, - "The modeling/checkpoint worker failed; inspect the failed result before verification or implementation continues.", - ); - } - - if matches!( - input.signals.modeling_result_status, - EpiphanyCoordinatorRoleResultStatus::Pending | EpiphanyCoordinatorRoleResultStatus::Running - ) { - return build( - EpiphanyCoordinatorAction::ReviewModelingResult, - Some(EpiphanyCoordinatorRoleId::Modeling), - Some(EpiphanyCoordinatorSceneAction::RoleResult), - false, - false, - "A modeling/checkpoint specialist is already running; wait for its result before reviewing stale verification output.", - ); - } - - if input.hands_frontier_ready { - return build( - EpiphanyCoordinatorAction::ContinueImplementation, - Some(EpiphanyCoordinatorRoleId::Implementation), - None, - false, - false, - "Mind has admitted the current RepoModel and Self has an actionable Hands frontier route.", - ); - } - - if input.recommendation.action == EpiphanyCrrcAction::RegatherManually - && role_status(&input.roles, EpiphanyCoordinatorRoleId::Implementation) - == Some(EpiphanyCoordinatorRoleStatus::Blocked) - { - return build( - EpiphanyCoordinatorAction::RegatherManually, - Some(EpiphanyCoordinatorRoleId::Research), - Some(EpiphanyCoordinatorSceneAction::RoleResult), - true, - false, - "CRRC says regather is required and the implementation lane is blocked; review or repair Eyes evidence before another coding turn.", - ); - } - - if role_status(&input.roles, EpiphanyCoordinatorRoleId::Modeling).is_some_and(|status| { - matches!( - status, - EpiphanyCoordinatorRoleStatus::Ready | EpiphanyCoordinatorRoleStatus::Needed - ) - }) && matches!( - input.signals.modeling_result_status, - EpiphanyCoordinatorRoleResultStatus::MissingBinding - | EpiphanyCoordinatorRoleResultStatus::BackendUnavailable - | EpiphanyCoordinatorRoleResultStatus::BackendMissing - | EpiphanyCoordinatorRoleResultStatus::Cancelled - | EpiphanyCoordinatorRoleResultStatus::Failed - ) { - return build( - EpiphanyCoordinatorAction::LaunchModeling, - Some(EpiphanyCoordinatorRoleId::Modeling), - Some(EpiphanyCoordinatorSceneAction::RoleLaunch), - false, - true, - "The modeling/checkpoint lane is ready and no current modeling finding is available.", - ); - } - - if input.recommendation.action == EpiphanyCrrcAction::RegatherManually { - return build( - EpiphanyCoordinatorAction::RegatherManually, - Some(EpiphanyCoordinatorRoleId::Research), - Some(EpiphanyCoordinatorSceneAction::RoleResult), - true, - false, - "CRRC requires explicit operator regather; only an exact external-evidence obligation may launch Eyes.", - ); - } - - if input.modeling_result_accepted && !input.hands_frontier_ready { - return build( - EpiphanyCoordinatorAction::AwaitFrontierProposal, +fn planning_decision( + stage: RepoFrontierPlanningLifecycleStage, +) -> Option { + let value = match stage { + RepoFrontierPlanningLifecycleStage::Ready => decision( + EpiphanyCoordinatorAction::StartFrontierPlanning, Some(EpiphanyCoordinatorRoleId::Imagination), None, + false, + true, + "An exact frontier planning obligation is ready to become a typed request.", + ), + RepoFrontierPlanningLifecycleStage::ImaginationLaunchReady => decision( + EpiphanyCoordinatorAction::LaunchImagination, + Some(EpiphanyCoordinatorRoleId::Imagination), + Some(EpiphanyCoordinatorSceneAction::RoleLaunch), + false, + true, + "The exact frontier planning request awaits Imagination.", + ), + RepoFrontierPlanningLifecycleStage::ImaginationRunning => decision( + EpiphanyCoordinatorAction::WaitForImaginationResult, + Some(EpiphanyCoordinatorRoleId::Imagination), + Some(EpiphanyCoordinatorSceneAction::RoleResult), + false, + false, + "The exact frontier Imagination attempt is still live.", + ), + RepoFrontierPlanningLifecycleStage::ImaginationFailed => decision( + EpiphanyCoordinatorAction::ReviewFrontierPlanningFailure, + Some(EpiphanyCoordinatorRoleId::Imagination), + Some(EpiphanyCoordinatorSceneAction::RoleResult), true, false, - "Mind accepted the current model, but no actionable Hands frontier exists; await a typed user or Imagination proposal selection instead of relaunching Modeling without mutation authority.", - ); - } - - build( - EpiphanyCoordinatorAction::LaunchModeling, - Some(EpiphanyCoordinatorRoleId::Modeling), - Some(EpiphanyCoordinatorSceneAction::RoleLaunch), - false, - true, - "No admitted current RepoModel frontier item is actionable by Hands; route Modeling to establish or reconcile the machine map.", - ) + "The exact frontier Imagination attempt failed.", + ), + RepoFrontierPlanningLifecycleStage::ImaginationResultReady => decision( + EpiphanyCoordinatorAction::RequestMindPlanReview, + None, + None, + false, + true, + "The exact Imagination candidate awaits a typed Mind request.", + ), + RepoFrontierPlanningLifecycleStage::MindLaunchReady => decision( + EpiphanyCoordinatorAction::LaunchMindPlanReview, + None, + Some(EpiphanyCoordinatorSceneAction::RoleLaunch), + false, + true, + "The exact Mind plan request has no live attempt.", + ), + RepoFrontierPlanningLifecycleStage::MindRunning => decision( + EpiphanyCoordinatorAction::WaitForMindPlanResult, + None, + Some(EpiphanyCoordinatorSceneAction::RoleResult), + false, + false, + "The exact Mind plan attempt is still live.", + ), + RepoFrontierPlanningLifecycleStage::MindFailed => decision( + EpiphanyCoordinatorAction::ReviewFrontierPlanningFailure, + None, + Some(EpiphanyCoordinatorSceneAction::RoleResult), + true, + false, + "The exact Mind plan attempt failed.", + ), + RepoFrontierPlanningLifecycleStage::MindResultReady => decision( + EpiphanyCoordinatorAction::CommitFrontierPlanDecision, + None, + None, + false, + true, + "The exact Mind judgment awaits atomic plan admission.", + ), + RepoFrontierPlanningLifecycleStage::Unavailable + | RepoFrontierPlanningLifecycleStage::Terminal => return None, + }; + Some(value) } pub fn coordinator_automation_action( @@ -997,1220 +351,85 @@ pub fn coordinator_automation_action( EpiphanyCoordinatorAction::LaunchReorientWorker => { EpiphanyCoordinatorAutomationAction::LaunchReorientWorker } - EpiphanyCoordinatorAction::PrepareCheckpoint - | EpiphanyCoordinatorAction::WaitForReorientWorker - | EpiphanyCoordinatorAction::ReviewReorientResult - | EpiphanyCoordinatorAction::RegatherManually - | EpiphanyCoordinatorAction::LaunchResearch - | EpiphanyCoordinatorAction::ReviewResearchResult - | EpiphanyCoordinatorAction::LaunchModeling - | EpiphanyCoordinatorAction::WaitForModelingResult - | EpiphanyCoordinatorAction::ReviewModelingResult - | EpiphanyCoordinatorAction::LaunchVerification - | EpiphanyCoordinatorAction::ReviewVerificationResult - | EpiphanyCoordinatorAction::ContinueImplementation - | EpiphanyCoordinatorAction::AwaitFrontierProposal - | EpiphanyCoordinatorAction::StartFrontierPlanning - | EpiphanyCoordinatorAction::LaunchImagination - | EpiphanyCoordinatorAction::WaitForImaginationResult - | EpiphanyCoordinatorAction::RequestMindPlanReview - | EpiphanyCoordinatorAction::LaunchMindPlanReview - | EpiphanyCoordinatorAction::WaitForMindPlanResult - | EpiphanyCoordinatorAction::CommitFrontierPlanDecision - | EpiphanyCoordinatorAction::ReviewFrontierPlanningFailure => { - EpiphanyCoordinatorAutomationAction::None - } + _ => EpiphanyCoordinatorAutomationAction::None, } } -pub fn select_coordinator_automation_action( - decision: &EpiphanyCoordinatorDecision, - force_checkpoint_compaction: bool, -) -> EpiphanyCoordinatorAutomationAction { - if force_checkpoint_compaction { - return EpiphanyCoordinatorAutomationAction::CompactRehydrateReorient; - } - coordinator_automation_action(decision) -} - -fn role_status( - roles: &[EpiphanyCoordinatorRoleLane], - role_id: EpiphanyCoordinatorRoleId, -) -> Option { - roles - .iter() - .find(|role| role.id == role_id) - .map(|role| role.status) -} - #[cfg(test)] mod tests { use super::*; - use epiphany_state_model::EpiphanyAcceptanceReceipt; - use epiphany_state_model::EpiphanyEvidenceRecord; - fn base_roles() -> Vec { - vec![ - role( - EpiphanyCoordinatorRoleId::Implementation, - EpiphanyCoordinatorRoleStatus::Ready, - ), - role( - EpiphanyCoordinatorRoleId::Imagination, - EpiphanyCoordinatorRoleStatus::Ready, - ), - role( - EpiphanyCoordinatorRoleId::Research, - EpiphanyCoordinatorRoleStatus::Ready, - ), - role( - EpiphanyCoordinatorRoleId::Modeling, - EpiphanyCoordinatorRoleStatus::Ready, - ), - role( - EpiphanyCoordinatorRoleId::Verification, - EpiphanyCoordinatorRoleStatus::Ready, - ), - role( - EpiphanyCoordinatorRoleId::Reorientation, - EpiphanyCoordinatorRoleStatus::Ready, - ), - ] - } - - fn role( - id: EpiphanyCoordinatorRoleId, - status: EpiphanyCoordinatorRoleStatus, - ) -> EpiphanyCoordinatorRoleLane { - EpiphanyCoordinatorRoleLane { id, status } - } - - fn recommendation(action: EpiphanyCrrcAction) -> EpiphanyCoordinatorCrrcRecommendation { - EpiphanyCoordinatorCrrcRecommendation { - action, - recommended_scene_action: Some(EpiphanyCoordinatorSceneAction::Reorient), + fn current_work() -> epiphany_core::EpiphanyCurrentWorkProjection { + epiphany_core::EpiphanyCurrentWorkProjection { + mind_projection_digest: "sha256:mind".into(), + body_modeling: None, + body_modeling_action: None, + research_continuation_action: None, + frontier_planning_stage: RepoFrontierPlanningLifecycleStage::Terminal, + proposal_modeling: None, + frontier_verdict_modeling: None, + verification: None, + reorientation: None, + imagination_considerations: Vec::new(), + admitted_model_direction_consideration: None, + hands_frontier_ready: false, } } fn input() -> EpiphanyCoordinatorInput { EpiphanyCoordinatorInput { - state_status: EpiphanyCrrcStateStatus::Ready, - checkpoint_present: true, + mind_present: true, should_prepare_compaction: false, - recommendation: recommendation(EpiphanyCrrcAction::Continue), - roles: base_roles(), - signals: EpiphanyCoordinatorSignals { - research_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - modeling_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - verification_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - }, - research_result_accepted: false, - research_result_reviewable: false, - research_result_failure_reviewed: false, - modeling_result_accepted_after_research: false, - modeling_result_requests_regather: false, - modeling_result_accepted: false, - modeling_result_reviewable: false, - modeling_result_failure_reviewed: false, - modeling_result_proposal_bound: false, - modeling_result_accepted_after_verification: false, - implementation_evidence_after_verification: false, - verification_result_cites_implementation_evidence: false, - verification_result_covers_current_modeling: true, - verification_result_accepted: false, - verification_result_failure_reviewed: false, - verification_result_allows_implementation: false, - verification_result_needs_evidence: false, - reorient_finding_accepted: false, - hands_frontier_ready: false, - research_continuation_action: None, - frontier_planning_stage: RepoFrontierPlanningLifecycleStage::Unavailable, - proposal_modeling_action: None, - frontier_verdict_modeling_action: None, - verification_action: None, - body_modeling_work_ready: false, - body_modeling_review_ready: false, - } - } - - #[test] - fn typed_frontier_planning_lifecycle_preempts_generic_regather() { - let cases = [ - ( - RepoFrontierPlanningLifecycleStage::Ready, - EpiphanyCoordinatorAction::StartFrontierPlanning, - Some(EpiphanyCoordinatorRoleId::Imagination), - true, - ), - ( - RepoFrontierPlanningLifecycleStage::ImaginationLaunchReady, - EpiphanyCoordinatorAction::LaunchImagination, - Some(EpiphanyCoordinatorRoleId::Imagination), - true, - ), - ( - RepoFrontierPlanningLifecycleStage::ImaginationRunning, - EpiphanyCoordinatorAction::WaitForImaginationResult, - Some(EpiphanyCoordinatorRoleId::Imagination), - false, - ), - ( - RepoFrontierPlanningLifecycleStage::ImaginationFailed, - EpiphanyCoordinatorAction::ReviewFrontierPlanningFailure, - Some(EpiphanyCoordinatorRoleId::Imagination), - false, - ), - ( - RepoFrontierPlanningLifecycleStage::ImaginationResultReady, - EpiphanyCoordinatorAction::RequestMindPlanReview, - None, - true, - ), - ( - RepoFrontierPlanningLifecycleStage::MindLaunchReady, - EpiphanyCoordinatorAction::LaunchMindPlanReview, - None, - true, - ), - ( - RepoFrontierPlanningLifecycleStage::MindRunning, - EpiphanyCoordinatorAction::WaitForMindPlanResult, - None, - false, - ), - ( - RepoFrontierPlanningLifecycleStage::MindFailed, - EpiphanyCoordinatorAction::ReviewFrontierPlanningFailure, - None, - false, - ), - ( - RepoFrontierPlanningLifecycleStage::MindResultReady, - EpiphanyCoordinatorAction::CommitFrontierPlanDecision, - None, - true, - ), - ]; - - for (stage, expected_action, expected_role, can_auto_run) in cases { - let decision = recommend_coordinator_action(EpiphanyCoordinatorInput { - recommendation: recommendation(EpiphanyCrrcAction::RegatherManually), - frontier_planning_stage: stage, - ..input() - }); - assert_eq!(decision.action, expected_action); - assert_eq!(decision.target_role, expected_role); - assert_eq!(decision.can_auto_run, can_auto_run); - } - } - - #[test] - fn selected_user_proposal_preempts_generic_regather() { - let decision = recommend_coordinator_action(EpiphanyCoordinatorInput { - recommendation: recommendation(EpiphanyCrrcAction::RegatherManually), - proposal_modeling_action: Some(EpiphanyAgentPassContinuationAction::Launch), - ..input() - }); - assert_eq!(decision.action, EpiphanyCoordinatorAction::LaunchModeling); - assert_eq!( - decision.target_role, - Some(EpiphanyCoordinatorRoleId::Modeling) - ); - assert!(decision.can_auto_run); - } - - #[test] - fn unresolved_body_work_routes_modeling_without_research_or_thread_state() { - let decision = recommend_coordinator_action(EpiphanyCoordinatorInput { - body_modeling_work_ready: true, - ..input() - }); - assert_eq!(decision.action, EpiphanyCoordinatorAction::LaunchModeling); - assert_eq!( - decision.target_role, - Some(EpiphanyCoordinatorRoleId::Modeling) - ); - assert!(decision.can_auto_run); - } - - #[test] - fn terminal_body_work_routes_keyed_mind_review() { - let decision = recommend_coordinator_action(EpiphanyCoordinatorInput { - body_modeling_review_ready: true, - ..input() - }); - assert_eq!( - decision.action, - EpiphanyCoordinatorAction::ReviewModelingResult - ); - assert_eq!( - decision.target_role, - Some(EpiphanyCoordinatorRoleId::Modeling) - ); - assert!(decision.requires_review); - assert!(!decision.can_auto_run); - } - - fn finding( - runtime_result_id: &str, - runtime_job_id: &str, - evidence_ids: Vec, - ) -> EpiphanyRoleFindingInterpretation { - EpiphanyRoleFindingInterpretation { - verdict: Some("needs-evidence".to_string()), - summary: Some("test finding".to_string()), - next_safe_move: Some("continue".to_string()), - checkpoint_summary: None, - scratch_summary: None, - files_inspected: Vec::new(), - frontier_node_ids: Vec::new(), - evidence_ids, - artifact_refs: Vec::new(), - runtime_result_id: Some(runtime_result_id.to_string()), - runtime_job_id: Some(runtime_job_id.to_string()), - open_questions: Vec::new(), - evidence_gaps: Vec::new(), - risks: Vec::new(), - state_patch: None, - repo_model_mutation_proposal: None, - self_patch: None, - self_persistence: None, - job_error: None, - item_error: None, - verification_request_id: None, - frontier_route_id: None, - proposal_modeling_request_id: None, - } - } - - #[test] - fn finding_signals_preserve_proposal_modeling_authority() { - let mut modeling = finding("result-modeling", "job-modeling", Vec::new()); - modeling.proposal_modeling_request_id = Some("proposal-request-1".to_string()); - - let signals = derive_coordinator_finding_signals( - Some(&EpiphanyThreadState::default()), - None, - Some(&modeling), - None, - None, - ); - - assert!(signals.modeling_result_proposal_bound); - } - - #[test] - fn implementation_evidence_lets_verification_cover_post_modeling_work() { - let mut state = EpiphanyThreadState::default(); - state.recent_evidence.push(EpiphanyEvidenceRecord { - id: "ev-implementation".to_string(), - kind: "implementation-audit".to_string(), - status: "ok".to_string(), - summary: "Hands pass evidence.".to_string(), - code_refs: Vec::new(), - }); - state.acceptance_receipts.push(EpiphanyAcceptanceReceipt { - id: "accept-modeling".to_string(), - result_id: "result-modeling".to_string(), - job_id: "job-modeling".to_string(), - binding_id: "modeling-checkpoint-worker".to_string(), - surface: "roleAccept".to_string(), - role_id: "modeling".to_string(), - status: "accepted".to_string(), - accepted_at: "2026-06-13T00:00:00Z".to_string(), - accepted_observation_id: None, - accepted_evidence_id: Some("ev-modeling".to_string()), - summary: None, - }); - let modeling = finding( - "result-modeling", - "job-modeling", - vec!["ev-modeling".to_string()], - ); - let verification = finding( - "result-verification", - "job-verification", - vec!["ev-implementation".to_string()], - ); - - let signals = derive_coordinator_finding_signals( - Some(&state), - None, - Some(&modeling), - Some(&verification), - None, - ); - - assert!(signals.modeling_result_accepted); - assert!(signals.verification_result_cites_implementation_evidence); - assert!(signals.verification_result_covers_current_modeling); - } - - #[test] - fn complete_hands_receipt_chain_lets_verification_cover_current_modeling() { - let mut state = EpiphanyThreadState::default(); - state.acceptance_receipts.push(EpiphanyAcceptanceReceipt { - id: "accept-modeling".to_string(), - result_id: "result-modeling".to_string(), - job_id: "job-modeling".to_string(), - binding_id: "modeling-checkpoint-worker".to_string(), - surface: "roleAccept".to_string(), - role_id: "modeling".to_string(), - status: "accepted".to_string(), - accepted_at: "2026-06-13T00:00:00Z".to_string(), - accepted_observation_id: None, - accepted_evidence_id: Some("ev-modeling".to_string()), - summary: None, - }); - let modeling = finding( - "result-modeling", - "job-modeling", - vec!["ev-modeling".to_string()], - ); - let verification = finding( - "result-verification", - "job-verification", - vec![ - "hands-patch-1".to_string(), - "hands-command-1".to_string(), - "hands-commit-1".to_string(), - ], - ); - - let signals = derive_coordinator_finding_signals( - Some(&state), - None, - Some(&modeling), - Some(&verification), - None, - ); - - assert!(signals.modeling_result_accepted); - assert!(signals.verification_result_cites_implementation_evidence); - assert!(signals.verification_result_covers_current_modeling); - } - - #[test] - fn derives_reviewed_failed_verification_from_supersession_receipt() { - let mut state = EpiphanyThreadState::default(); - state.acceptance_receipts.push(EpiphanyAcceptanceReceipt { - id: "failure-review".to_string(), - result_id: "result-verification".to_string(), - job_id: "job-verification".to_string(), - binding_id: "verification-review-worker".to_string(), - surface: "roleFailureReview".to_string(), - role_id: "verification".to_string(), - status: "superseded".to_string(), - accepted_at: "2026-06-13T00:00:00Z".to_string(), - accepted_observation_id: None, - accepted_evidence_id: None, - summary: Some("Old failed Soul result reviewed before relaunch.".to_string()), - }); - let verification = finding("result-verification", "job-verification", Vec::new()); - - let signals = - derive_coordinator_finding_signals(Some(&state), None, None, Some(&verification), None); - - assert!(signals.verification_result_failure_reviewed); - assert!(!signals.verification_result_accepted); - } - - #[test] - fn legacy_failed_research_cannot_relaunch_eyes() { - let mut state = EpiphanyThreadState::default(); - state.acceptance_receipts.push(EpiphanyAcceptanceReceipt { - id: "failure-review-research".to_string(), - result_id: "result-research".to_string(), - job_id: "job-research".to_string(), - binding_id: "research-source-gather-worker".to_string(), - surface: "roleFailureReview".to_string(), - role_id: "research".to_string(), - status: "superseded".to_string(), - accepted_at: "2026-07-16T00:00:00Z".to_string(), - accepted_observation_id: None, - accepted_evidence_id: None, - summary: Some("Malformed Eyes result reviewed.".to_string()), - }); - let research = finding("result-research", "job-research", Vec::new()); - let signals = - derive_coordinator_finding_signals(Some(&state), Some(&research), None, None, None); - assert!(signals.research_result_failure_reviewed); - - let base = input(); - let decision = recommend_coordinator_action(EpiphanyCoordinatorInput { - signals: EpiphanyCoordinatorSignals { - research_result_status: EpiphanyCoordinatorRoleResultStatus::Failed, - ..base.signals - }, - research_result_failure_reviewed: true, - ..base - }); - assert_eq!(decision.action, EpiphanyCoordinatorAction::LaunchModeling); - } - - #[test] - fn routes_missing_checkpoint_to_modeling_owner() { - let decision = recommend_coordinator_action(EpiphanyCoordinatorInput { - checkpoint_present: false, - recommendation: recommendation(EpiphanyCrrcAction::PrepareCheckpoint), - ..input() - }); - - assert_eq!(decision.action, EpiphanyCoordinatorAction::LaunchModeling); - assert_eq!( - decision.target_role, - Some(EpiphanyCoordinatorRoleId::Modeling) - ); - assert!(decision.can_auto_run); - } - - #[test] - fn missing_state_still_requires_explicit_intake() { - let decision = recommend_coordinator_action(EpiphanyCoordinatorInput { - state_status: EpiphanyCrrcStateStatus::Missing, - checkpoint_present: false, - ..input() - }); - - assert_eq!( - decision.action, - EpiphanyCoordinatorAction::PrepareCheckpoint - ); - assert!(!decision.can_auto_run); - } - - #[test] - fn compacts_at_pressure_threshold() { - let decision = recommend_coordinator_action(EpiphanyCoordinatorInput { - should_prepare_compaction: true, - ..input() - }); - - assert_eq!( - decision.action, - EpiphanyCoordinatorAction::CompactRehydrateReorient - ); - assert_eq!( - coordinator_automation_action(&decision), - EpiphanyCoordinatorAutomationAction::CompactRehydrateReorient - ); - } - - #[test] - fn does_not_recompact_after_accepted_resume_reorient() { - let decision = recommend_coordinator_action(EpiphanyCoordinatorInput { - should_prepare_compaction: true, - roles: Vec::new(), - signals: EpiphanyCoordinatorSignals { - research_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - modeling_result_status: EpiphanyCoordinatorRoleResultStatus::BackendMissing, - verification_result_status: EpiphanyCoordinatorRoleResultStatus::BackendMissing, - }, - reorient_finding_accepted: true, - ..input() - }); - - assert_eq!(decision.action, EpiphanyCoordinatorAction::LaunchModeling); - } - - #[test] - fn launches_reorient_worker_from_crrc() { - let decision = recommend_coordinator_action(EpiphanyCoordinatorInput { - recommendation: recommendation(EpiphanyCrrcAction::LaunchReorientWorker), - ..input() - }); - - assert_eq!( - decision.action, - EpiphanyCoordinatorAction::LaunchReorientWorker - ); - assert_eq!( - coordinator_automation_action(&decision), - EpiphanyCoordinatorAutomationAction::LaunchReorientWorker - ); - } - - #[test] - fn reviews_reorient_result() { - let decision = recommend_coordinator_action(EpiphanyCoordinatorInput { recommendation: EpiphanyCoordinatorCrrcRecommendation { - action: EpiphanyCrrcAction::AcceptReorientResult, - recommended_scene_action: Some(EpiphanyCoordinatorSceneAction::ReorientAccept), + action: EpiphanyCrrcAction::Continue, + recommended_scene_action: None, }, - ..input() - }); - - assert_eq!( - decision.action, - EpiphanyCoordinatorAction::ReviewReorientResult - ); - assert!(decision.requires_review); - assert_eq!( - coordinator_automation_action(&decision), - EpiphanyCoordinatorAutomationAction::None - ); + current_work: current_work(), + } } #[test] - fn exact_work_preempts_but_cannot_be_invented_by_manual_regather() { - let launch_modeling = recommend_coordinator_action(EpiphanyCoordinatorInput { - recommendation: recommendation(EpiphanyCrrcAction::RegatherManually), - signals: EpiphanyCoordinatorSignals { - research_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - modeling_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - verification_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - }, - reorient_finding_accepted: true, - ..input() - }); + fn absent_work_waits_instead_of_manufacturing_modeling() { assert_eq!( - launch_modeling.action, - EpiphanyCoordinatorAction::LaunchModeling - ); - - let review_modeling = recommend_coordinator_action(EpiphanyCoordinatorInput { - recommendation: recommendation(EpiphanyCrrcAction::RegatherManually), - signals: EpiphanyCoordinatorSignals { - research_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - modeling_result_status: EpiphanyCoordinatorRoleResultStatus::Completed, - verification_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - }, - modeling_result_reviewable: true, - reorient_finding_accepted: true, - ..input() - }); - assert_eq!( - review_modeling.action, - EpiphanyCoordinatorAction::ReviewModelingResult - ); - - let blocked_regather = recommend_coordinator_action(EpiphanyCoordinatorInput { - recommendation: recommendation(EpiphanyCrrcAction::RegatherManually), - roles: vec![role( - EpiphanyCoordinatorRoleId::Implementation, - EpiphanyCoordinatorRoleStatus::Blocked, - )], - signals: EpiphanyCoordinatorSignals { - research_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - modeling_result_status: EpiphanyCoordinatorRoleResultStatus::Completed, - verification_result_status: EpiphanyCoordinatorRoleResultStatus::Completed, - }, - modeling_result_accepted: true, - modeling_result_accepted_after_verification: true, - verification_result_accepted: true, - verification_result_needs_evidence: true, - reorient_finding_accepted: true, - ..input() - }); - assert_eq!( - blocked_regather.action, - EpiphanyCoordinatorAction::RegatherManually - ); - } - - #[test] - fn accepted_eyes_alone_cannot_manufacture_modeling_work() { - let base = EpiphanyCoordinatorInput { - recommendation: recommendation(EpiphanyCrrcAction::RegatherManually), - roles: vec![role( - EpiphanyCoordinatorRoleId::Implementation, - EpiphanyCoordinatorRoleStatus::Blocked, - )], - signals: EpiphanyCoordinatorSignals { - research_result_status: EpiphanyCoordinatorRoleResultStatus::Completed, - modeling_result_status: EpiphanyCoordinatorRoleResultStatus::Completed, - verification_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - }, - research_result_accepted: true, - modeling_result_accepted: true, - reorient_finding_accepted: true, - ..input() - }; - let without_obligation = recommend_coordinator_action(base.clone()); - assert_eq!( - without_obligation.action, - EpiphanyCoordinatorAction::RegatherManually - ); - - let exact_modeling_work = recommend_coordinator_action(EpiphanyCoordinatorInput { - frontier_verdict_modeling_action: Some(EpiphanyAgentPassContinuationAction::Launch), - verification_action: None, - ..base.clone() - }); - assert_eq!( - exact_modeling_work.action, - EpiphanyCoordinatorAction::LaunchModeling - ); - assert_eq!( - exact_modeling_work.target_role, - Some(EpiphanyCoordinatorRoleId::Modeling) - ); - - let current_hands_route = recommend_coordinator_action(EpiphanyCoordinatorInput { - hands_frontier_ready: true, - ..base.clone() - }); - assert_eq!( - current_hands_route.action, - EpiphanyCoordinatorAction::ContinueImplementation - ); - } - - #[test] - fn hands_consequence_routes_to_soul_without_eyes_authority() { - let decision = recommend_coordinator_action(EpiphanyCoordinatorInput { - recommendation: recommendation(EpiphanyCrrcAction::RegatherManually), - roles: vec![role( - EpiphanyCoordinatorRoleId::Implementation, - EpiphanyCoordinatorRoleStatus::Blocked, - )], - signals: EpiphanyCoordinatorSignals { - research_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - modeling_result_status: EpiphanyCoordinatorRoleResultStatus::Completed, - verification_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - }, - modeling_result_failure_reviewed: true, - implementation_evidence_after_verification: true, - reorient_finding_accepted: true, - ..input() - }); - - assert_eq!( - decision.action, - EpiphanyCoordinatorAction::LaunchVerification - ); - assert_eq!( - decision.target_role, - Some(EpiphanyCoordinatorRoleId::Verification) - ); - assert!(decision.reason.contains("Hands consequence")); - } - - #[test] - fn modeling_regather_hint_cannot_create_eyes_work() { - let decision = recommend_coordinator_action(EpiphanyCoordinatorInput { - signals: EpiphanyCoordinatorSignals { - research_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - modeling_result_status: EpiphanyCoordinatorRoleResultStatus::Completed, - verification_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - }, - modeling_result_requests_regather: true, - modeling_result_reviewable: false, - ..input() - }); - - assert_eq!( - decision.action, - EpiphanyCoordinatorAction::ReviewModelingResult - ); - assert_eq!( - decision.target_role, - Some(EpiphanyCoordinatorRoleId::Modeling) - ); - assert!(decision.reason.contains("no acceptable RepoModel proposal")); - } - - #[test] - fn routes_hands_to_soul_to_modeling_before_next_hands_turn() { - let launch_modeling = recommend_coordinator_action(input()); - assert_eq!( - launch_modeling.action, - EpiphanyCoordinatorAction::LaunchModeling - ); - assert_eq!( - coordinator_automation_action(&launch_modeling), - EpiphanyCoordinatorAutomationAction::None - ); - - let review_modeling = recommend_coordinator_action(EpiphanyCoordinatorInput { - signals: EpiphanyCoordinatorSignals { - research_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - modeling_result_status: EpiphanyCoordinatorRoleResultStatus::Completed, - verification_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - }, - modeling_result_reviewable: true, - ..input() - }); - assert_eq!( - review_modeling.action, - EpiphanyCoordinatorAction::ReviewModelingResult - ); - assert!(review_modeling.requires_review); - - let wait_for_modeling = recommend_coordinator_action(EpiphanyCoordinatorInput { - signals: EpiphanyCoordinatorSignals { - research_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - modeling_result_status: EpiphanyCoordinatorRoleResultStatus::Running, - verification_result_status: EpiphanyCoordinatorRoleResultStatus::Completed, - }, - ..input() - }); - assert_eq!( - wait_for_modeling.action, - EpiphanyCoordinatorAction::ReviewModelingResult - ); - assert!(wait_for_modeling.reason.contains("stale verification")); - - let review_failed_modeling = recommend_coordinator_action(EpiphanyCoordinatorInput { - signals: EpiphanyCoordinatorSignals { - research_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - modeling_result_status: EpiphanyCoordinatorRoleResultStatus::Failed, - verification_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - }, - ..input() - }); - assert_eq!( - review_failed_modeling.action, - EpiphanyCoordinatorAction::ReviewModelingResult - ); - assert!(!review_failed_modeling.can_auto_run); - - let review_unreviewable_modeling = recommend_coordinator_action(EpiphanyCoordinatorInput { - signals: EpiphanyCoordinatorSignals { - research_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - modeling_result_status: EpiphanyCoordinatorRoleResultStatus::Completed, - verification_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - }, - ..input() - }); - assert_eq!( - review_unreviewable_modeling.action, - EpiphanyCoordinatorAction::ReviewModelingResult - ); - assert!(!review_unreviewable_modeling.can_auto_run); - - let relaunch_superseded_modeling = recommend_coordinator_action(EpiphanyCoordinatorInput { - signals: EpiphanyCoordinatorSignals { - research_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - modeling_result_status: EpiphanyCoordinatorRoleResultStatus::Completed, - verification_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - }, - modeling_result_failure_reviewed: true, - modeling_result_reviewable: true, - ..input() - }); - assert_eq!( - relaunch_superseded_modeling.action, - EpiphanyCoordinatorAction::LaunchModeling - ); - assert!(relaunch_superseded_modeling.can_auto_run); - assert!( - relaunch_superseded_modeling - .reason - .contains("rejected by admission") - ); - - let await_fresh_proposal_after_rejected_selection = - recommend_coordinator_action(EpiphanyCoordinatorInput { - signals: EpiphanyCoordinatorSignals { - research_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - modeling_result_status: EpiphanyCoordinatorRoleResultStatus::Completed, - verification_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - }, - modeling_result_failure_reviewed: true, - modeling_result_reviewable: true, - modeling_result_proposal_bound: true, - ..input() - }); - assert_eq!( - await_fresh_proposal_after_rejected_selection.action, + recommend_coordinator_action(input()).action, EpiphanyCoordinatorAction::AwaitFrontierProposal ); - assert!(!await_fresh_proposal_after_rejected_selection.can_auto_run); - assert!( - await_fresh_proposal_after_rejected_selection - .reason - .contains("selection request is consumed") - ); + } - let current_hands_route_survives_rejected_stale_proposal = - recommend_coordinator_action(EpiphanyCoordinatorInput { - signals: EpiphanyCoordinatorSignals { - research_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - modeling_result_status: EpiphanyCoordinatorRoleResultStatus::Completed, - verification_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - }, - modeling_result_failure_reviewed: true, - modeling_result_reviewable: true, - modeling_result_proposal_bound: true, - hands_frontier_ready: true, - ..input() - }); + #[test] + fn exact_body_obligation_routes_modeling() { + let mut input = input(); + input.current_work.body_modeling_action = + Some(EpiphanyAgentPassContinuationAction::Launch); assert_eq!( - current_hands_route_survives_rejected_stale_proposal.action, - EpiphanyCoordinatorAction::ContinueImplementation - ); - - let await_proposal_without_hands_frontier = - recommend_coordinator_action(EpiphanyCoordinatorInput { - signals: EpiphanyCoordinatorSignals { - research_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - modeling_result_status: EpiphanyCoordinatorRoleResultStatus::Completed, - verification_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - }, - modeling_result_accepted: true, - modeling_result_reviewable: true, - ..input() - }); - assert_eq!( - await_proposal_without_hands_frontier.action, - EpiphanyCoordinatorAction::AwaitFrontierProposal - ); - - let review_failed_verification = recommend_coordinator_action(EpiphanyCoordinatorInput { - signals: EpiphanyCoordinatorSignals { - research_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - modeling_result_status: EpiphanyCoordinatorRoleResultStatus::Completed, - verification_result_status: EpiphanyCoordinatorRoleResultStatus::Failed, - }, - modeling_result_accepted: true, - modeling_result_reviewable: true, - ..input() - }); - assert_eq!( - review_failed_verification.action, - EpiphanyCoordinatorAction::ReviewVerificationResult - ); - assert!(!review_failed_verification.can_auto_run); - - let superseded_failed_verification = - recommend_coordinator_action(EpiphanyCoordinatorInput { - signals: EpiphanyCoordinatorSignals { - research_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - modeling_result_status: EpiphanyCoordinatorRoleResultStatus::Completed, - verification_result_status: EpiphanyCoordinatorRoleResultStatus::Failed, - }, - modeling_result_accepted: true, - modeling_result_reviewable: true, - verification_result_failure_reviewed: true, - ..input() - }); - assert_eq!( - superseded_failed_verification.action, - EpiphanyCoordinatorAction::LaunchVerification - ); - assert!(superseded_failed_verification.can_auto_run); - - let verification_done = EpiphanyCoordinatorSignals { - research_result_status: EpiphanyCoordinatorRoleResultStatus::MissingBinding, - modeling_result_status: EpiphanyCoordinatorRoleResultStatus::Completed, - verification_result_status: EpiphanyCoordinatorRoleResultStatus::Completed, - }; - - let stale_verification = recommend_coordinator_action(EpiphanyCoordinatorInput { - signals: verification_done, - modeling_result_accepted: true, - modeling_result_reviewable: true, - verification_result_covers_current_modeling: false, - ..input() - }); - assert_eq!( - stale_verification.action, - EpiphanyCoordinatorAction::LaunchVerification - ); - - let implementation_covered_verification = - recommend_coordinator_action(EpiphanyCoordinatorInput { - signals: verification_done, - modeling_result_accepted: true, - modeling_result_reviewable: true, - verification_result_covers_current_modeling: true, - verification_result_cites_implementation_evidence: true, - ..input() - }); - assert_eq!( - implementation_covered_verification.action, - EpiphanyCoordinatorAction::ReviewVerificationResult - ); - - let review_verification = recommend_coordinator_action(EpiphanyCoordinatorInput { - signals: verification_done, - modeling_result_accepted: true, - modeling_result_reviewable: true, - ..input() - }); - assert_eq!( - review_verification.action, - EpiphanyCoordinatorAction::ReviewVerificationResult - ); - - let accepted_non_pass = recommend_coordinator_action(EpiphanyCoordinatorInput { - signals: verification_done, - modeling_result_accepted: true, - modeling_result_reviewable: true, - verification_result_accepted: true, - ..input() - }); - assert_eq!( - accepted_non_pass.action, + recommend_coordinator_action(input).action, EpiphanyCoordinatorAction::LaunchModeling ); - - let needs_evidence = recommend_coordinator_action(EpiphanyCoordinatorInput { - signals: verification_done, - modeling_result_accepted: true, - modeling_result_reviewable: true, - verification_result_accepted: true, - verification_result_needs_evidence: true, - hands_frontier_ready: true, - ..input() - }); - assert_eq!( - needs_evidence.action, - EpiphanyCoordinatorAction::ContinueImplementation - ); - - let rejected_current_model = recommend_coordinator_action(EpiphanyCoordinatorInput { - signals: verification_done, - modeling_result_accepted: true, - modeling_result_reviewable: true, - verification_result_accepted: true, - verification_result_cites_implementation_evidence: true, - verification_result_covers_current_modeling: true, - hands_frontier_ready: true, - ..input() - }); - assert_eq!( - rejected_current_model.action, - EpiphanyCoordinatorAction::LaunchModeling - ); - - let implementation_after_verification = - recommend_coordinator_action(EpiphanyCoordinatorInput { - signals: verification_done, - modeling_result_accepted: true, - modeling_result_reviewable: true, - implementation_evidence_after_verification: true, - verification_result_accepted: true, - verification_result_needs_evidence: true, - ..input() - }); - assert_eq!( - implementation_after_verification.action, - EpiphanyCoordinatorAction::LaunchVerification - ); - - let accepted_pass = recommend_coordinator_action(EpiphanyCoordinatorInput { - signals: verification_done, - modeling_result_accepted: true, - modeling_result_reviewable: true, - verification_result_accepted: true, - verification_result_allows_implementation: true, - ..input() - }); - assert_eq!( - accepted_pass.action, - EpiphanyCoordinatorAction::LaunchModeling - ); - - let modeled_after_pass = recommend_coordinator_action(EpiphanyCoordinatorInput { - signals: verification_done, - modeling_result_accepted: true, - modeling_result_reviewable: true, - modeling_result_accepted_after_verification: true, - verification_result_accepted: true, - verification_result_allows_implementation: true, - hands_frontier_ready: true, - ..input() - }); - assert_eq!( - modeled_after_pass.action, - EpiphanyCoordinatorAction::ContinueImplementation - ); } #[test] - fn clear_crrc_refuses_hands_without_an_actionable_frontier() { - let decision = recommend_coordinator_action(EpiphanyCoordinatorInput { - roles: Vec::new(), - signals: EpiphanyCoordinatorSignals { - research_result_status: EpiphanyCoordinatorRoleResultStatus::BackendMissing, - modeling_result_status: EpiphanyCoordinatorRoleResultStatus::BackendMissing, - verification_result_status: EpiphanyCoordinatorRoleResultStatus::BackendMissing, - }, - ..input() - }); - - assert_eq!(decision.action, EpiphanyCoordinatorAction::LaunchModeling); - assert_ne!( - decision.target_role, - Some(EpiphanyCoordinatorRoleId::Implementation) - ); - assert!(decision.reason.contains("admitted current RepoModel")); - } - - #[test] - fn pending_soul_preempts_regather_hands_frontier() { - let mut roles = base_roles(); - roles - .iter_mut() - .find(|role| role.id == EpiphanyCoordinatorRoleId::Implementation) - .expect("implementation lane") - .status = EpiphanyCoordinatorRoleStatus::Blocked; - let decision = recommend_coordinator_action(EpiphanyCoordinatorInput { - recommendation: recommendation(EpiphanyCrrcAction::RegatherManually), - roles, - signals: EpiphanyCoordinatorSignals { - research_result_status: EpiphanyCoordinatorRoleResultStatus::Completed, - modeling_result_status: EpiphanyCoordinatorRoleResultStatus::Completed, - verification_result_status: EpiphanyCoordinatorRoleResultStatus::Pending, - }, - research_result_accepted: true, - modeling_result_reviewable: true, - modeling_result_failure_reviewed: true, - hands_frontier_ready: true, - ..input() - }); - + fn exact_eyes_obligation_routes_research() { + let mut input = input(); + input.current_work.research_continuation_action = + Some(RepoFrontierResearchContinuationAction::LaunchResearch); assert_eq!( - decision.action, - EpiphanyCoordinatorAction::ReviewVerificationResult - ); - assert_eq!( - decision.target_role, - Some(EpiphanyCoordinatorRoleId::Verification) - ); - assert!(!decision.can_auto_run); - } - - #[test] - fn accepted_soul_preempts_regather_hands_frontier() { - let mut roles = base_roles(); - roles - .iter_mut() - .find(|role| role.id == EpiphanyCoordinatorRoleId::Implementation) - .expect("implementation lane") - .status = EpiphanyCoordinatorRoleStatus::Blocked; - let decision = recommend_coordinator_action(EpiphanyCoordinatorInput { - recommendation: recommendation(EpiphanyCrrcAction::RegatherManually), - roles, - signals: EpiphanyCoordinatorSignals { - research_result_status: EpiphanyCoordinatorRoleResultStatus::Completed, - modeling_result_status: EpiphanyCoordinatorRoleResultStatus::Completed, - verification_result_status: EpiphanyCoordinatorRoleResultStatus::Completed, - }, - research_result_accepted: true, - modeling_result_reviewable: true, - modeling_result_failure_reviewed: true, - verification_result_accepted: true, - verification_result_allows_implementation: true, - hands_frontier_ready: true, - ..input() - }); - - assert_eq!(decision.action, EpiphanyCoordinatorAction::LaunchModeling); - assert_eq!( - decision.target_role, - Some(EpiphanyCoordinatorRoleId::Modeling) - ); - assert!(decision.can_auto_run); - } - - #[test] - fn accepted_model_routes_to_hands_before_post_consequence_soul() { - let modeling_done = EpiphanyCoordinatorSignals { - research_result_status: EpiphanyCoordinatorRoleResultStatus::BackendMissing, - modeling_result_status: EpiphanyCoordinatorRoleResultStatus::Completed, - verification_result_status: EpiphanyCoordinatorRoleResultStatus::BackendMissing, - }; - let ready = recommend_coordinator_action(EpiphanyCoordinatorInput { - signals: modeling_done, - modeling_result_accepted: true, - modeling_result_reviewable: true, - hands_frontier_ready: true, - ..input() - }); - assert_eq!( - ready.action, - EpiphanyCoordinatorAction::ContinueImplementation - ); - - let stale_rejected_modeling = recommend_coordinator_action(EpiphanyCoordinatorInput { - signals: modeling_done, - modeling_result_accepted: false, - modeling_result_reviewable: true, - modeling_result_failure_reviewed: true, - hands_frontier_ready: true, - ..input() - }); - assert_eq!( - stale_rejected_modeling.action, - EpiphanyCoordinatorAction::ContinueImplementation - ); - - let no_frontier = recommend_coordinator_action(EpiphanyCoordinatorInput { - signals: modeling_done, - modeling_result_accepted: true, - modeling_result_reviewable: true, - hands_frontier_ready: false, - ..input() - }); - assert_eq!( - no_frontier.action, - EpiphanyCoordinatorAction::AwaitFrontierProposal - ); - assert!(!no_frontier.can_auto_run); - assert!(no_frontier.reason.contains("proposal selection")); - - let eyes_frontier = recommend_coordinator_action(EpiphanyCoordinatorInput { - signals: EpiphanyCoordinatorSignals { - research_result_status: EpiphanyCoordinatorRoleResultStatus::Completed, - ..modeling_done - }, - research_result_accepted: false, - research_result_reviewable: true, - research_result_failure_reviewed: true, - modeling_result_accepted: true, - modeling_result_reviewable: true, - hands_frontier_ready: false, - research_continuation_action: Some( - RepoFrontierResearchContinuationAction::LaunchResearch, - ), - ..input() - }); - assert_eq!( - eyes_frontier.action, + recommend_coordinator_action(input).action, EpiphanyCoordinatorAction::LaunchResearch ); - assert_eq!( - eyes_frontier.target_role, - Some(EpiphanyCoordinatorRoleId::Research) - ); - assert!(eyes_frontier.can_auto_run); - assert!(eyes_frontier.reason.contains("Research lifecycle")); - - let consequences_exist = recommend_coordinator_action(EpiphanyCoordinatorInput { - signals: modeling_done, - modeling_result_accepted: true, - modeling_result_reviewable: true, - implementation_evidence_after_verification: true, - hands_frontier_ready: true, - ..input() - }); - assert_eq!( - consequences_exist.action, - EpiphanyCoordinatorAction::LaunchVerification - ); } #[test] - fn forced_checkpoint_compaction_overrides_decision() { - let decision = EpiphanyCoordinatorDecision { - action: EpiphanyCoordinatorAction::ContinueImplementation, - target_role: Some(EpiphanyCoordinatorRoleId::Implementation), - recommended_scene_action: None, - requires_review: false, - can_auto_run: false, - reason: "ordinary coordinator would continue".to_string(), - }; - - assert_eq!( - coordinator_automation_action(&decision), - EpiphanyCoordinatorAutomationAction::None - ); - assert_eq!( - select_coordinator_automation_action(&decision, true), - EpiphanyCoordinatorAutomationAction::CompactRehydrateReorient - ); + fn source_has_no_aggregate_or_latest_lane_routing() { + let source = include_str!("coordinator.rs"); + let production = source.split("#[cfg(test)]").next().unwrap_or(source); + for forbidden in [ + "EpiphanyThreadState", + "accepted_after", + "latest_result", + "finding_signals", + "state_revision", + ] { + assert!(!production.contains(forbidden)); + } } } diff --git a/epiphany-core/src/surfaces/coordinator_contract.rs b/epiphany-core/src/surfaces/coordinator_contract.rs index ff1df20d..55afc019 100644 --- a/epiphany-core/src/surfaces/coordinator_contract.rs +++ b/epiphany-core/src/surfaces/coordinator_contract.rs @@ -1,15 +1,10 @@ -use super::EpiphanyCrrcAction; -use super::EpiphanyCrrcRecommendation; -use super::EpiphanyCrrcResultStatus; -use super::EpiphanyCrrcStateStatus; -use super::EpiphanyPressure; -use super::EpiphanyPressureLevel; -use super::EpiphanyReorientAction; -use super::EpiphanyRoleBoardLane; -use crate::EpiphanyAgentPassContinuationAction; -use crate::RepoFrontierPlanningLifecycleStage; -use crate::RepoFrontierResearchContinuationAction; +use super::{ + EpiphanyCrrcAction, EpiphanyCrrcResultStatus, EpiphanyPressure, EpiphanyPressureLevel, + EpiphanyReorientAction, EpiphanyRoleBoardLane, +}; +use crate::EpiphanyCurrentWorkProjection; use serde::{Deserialize, Serialize}; + #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum EpiphanyCoordinatorRoleId { @@ -74,6 +69,10 @@ pub enum EpiphanyCoordinatorAction { WaitForMindPlanResult, CommitFrontierPlanDecision, ReviewFrontierPlanningFailure, + LaunchImaginationConsideration, + WaitForImaginationConsideration, + LaunchAdmittedModelDirectionConsideration, + WaitForAdmittedModelDirectionConsideration, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] @@ -103,78 +102,12 @@ pub struct EpiphanyCoordinatorCrrcRecommendation { pub recommended_scene_action: Option, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct EpiphanyCoordinatorSignals { - pub research_result_status: EpiphanyCoordinatorRoleResultStatus, - pub modeling_result_status: EpiphanyCoordinatorRoleResultStatus, - pub verification_result_status: EpiphanyCoordinatorRoleResultStatus, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct EpiphanyCoordinatorSourceSignals { - pub pressure_level: EpiphanyPressureLevel, - pub should_prepare_compaction: bool, - pub reorient_action: EpiphanyReorientAction, - pub crrc_action: EpiphanyCrrcAction, - pub research_result_status: EpiphanyCoordinatorRoleResultStatus, - pub modeling_result_status: EpiphanyCoordinatorRoleResultStatus, - pub verification_result_status: EpiphanyCoordinatorRoleResultStatus, - pub reorient_result_status: EpiphanyCrrcResultStatus, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct EpiphanyCoordinatorRoleLane { - pub id: EpiphanyCoordinatorRoleId, - pub status: EpiphanyCoordinatorRoleStatus, -} - #[derive(Debug, Clone, PartialEq, Eq)] pub struct EpiphanyCoordinatorInput { - pub state_status: EpiphanyCrrcStateStatus, - pub checkpoint_present: bool, + pub mind_present: bool, pub should_prepare_compaction: bool, pub recommendation: EpiphanyCoordinatorCrrcRecommendation, - pub roles: Vec, - pub signals: EpiphanyCoordinatorSignals, - pub research_result_accepted: bool, - pub research_result_reviewable: bool, - pub research_result_failure_reviewed: bool, - pub modeling_result_accepted_after_research: bool, - pub modeling_result_requests_regather: bool, - pub modeling_result_accepted: bool, - pub modeling_result_reviewable: bool, - pub modeling_result_failure_reviewed: bool, - pub modeling_result_proposal_bound: bool, - pub modeling_result_accepted_after_verification: bool, - pub implementation_evidence_after_verification: bool, - pub verification_result_cites_implementation_evidence: bool, - pub verification_result_covers_current_modeling: bool, - pub verification_result_accepted: bool, - pub verification_result_failure_reviewed: bool, - pub verification_result_allows_implementation: bool, - pub verification_result_needs_evidence: bool, - pub reorient_finding_accepted: bool, - /// True only when the canonical runtime RepoModel has exactly one current - /// admission and an Active, dependency-ready Hands frontier item. - pub hands_frontier_ready: bool, - /// Exact next action projected by the current frontier Research lifecycle. - /// Legacy role-lane status remains observable but cannot override it. - pub research_continuation_action: Option, - /// Read-only projection of the single typed Imagination -> Mind planning - /// lifecycle. Self may advance it, but only Mind's result can decide adoption. - pub frontier_planning_stage: RepoFrontierPlanningLifecycleStage, - /// Exact current action for the oldest unresolved proposal Modeling request. - pub proposal_modeling_action: Option, - /// Exact current action for one Soul-verdict-bound Modeling request. - pub frontier_verdict_modeling_action: Option, - /// Exact current action for one Hands-consequence-bound Verification request. - /// Role lanes, timestamps, and latest-result slots are display-only. - pub verification_action: Option, - pub body_modeling_work_ready: bool, - pub body_modeling_review_ready: bool, + pub current_work: EpiphanyCurrentWorkProjection, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -190,42 +123,23 @@ pub struct EpiphanyCoordinatorDecision { #[derive(Debug, Clone, PartialEq, Eq)] pub struct EpiphanyCoordinatorStatusInput { - pub state_status: EpiphanyCrrcStateStatus, - pub checkpoint_present: bool, + pub mind_present: bool, pub pressure: EpiphanyPressure, - pub recommendation: EpiphanyCrrcRecommendation, + pub recommendation: crate::EpiphanyCrrcRecommendation, pub roles: Vec, pub reorient_action: EpiphanyReorientAction, - pub research_result_status: EpiphanyCoordinatorRoleResultStatus, - pub modeling_result_status: EpiphanyCoordinatorRoleResultStatus, - pub verification_result_status: EpiphanyCoordinatorRoleResultStatus, pub reorient_result_status: EpiphanyCrrcResultStatus, - pub research_result_accepted: bool, - pub research_result_reviewable: bool, - pub research_result_failure_reviewed: bool, - pub modeling_result_accepted_after_research: bool, - pub modeling_result_requests_regather: bool, - pub modeling_result_accepted: bool, - pub modeling_result_reviewable: bool, - pub modeling_result_failure_reviewed: bool, - pub modeling_result_proposal_bound: bool, - pub modeling_result_accepted_after_verification: bool, - pub implementation_evidence_after_verification: bool, - pub verification_result_cites_implementation_evidence: bool, - pub verification_result_covers_current_modeling: bool, - pub verification_result_accepted: bool, - pub verification_result_failure_reviewed: bool, - pub verification_result_allows_implementation: bool, - pub verification_result_needs_evidence: bool, - pub reorient_finding_accepted: bool, - pub hands_frontier_ready: bool, - pub research_continuation_action: Option, - pub frontier_planning_stage: RepoFrontierPlanningLifecycleStage, - pub proposal_modeling_action: Option, - pub frontier_verdict_modeling_action: Option, - pub verification_action: Option, - pub body_modeling_work_ready: bool, - pub body_modeling_review_ready: bool, + pub current_work: EpiphanyCurrentWorkProjection, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct EpiphanyCoordinatorSourceSignals { + pub pressure_level: EpiphanyPressureLevel, + pub should_prepare_compaction: bool, + pub reorient_action: EpiphanyReorientAction, + pub crrc_action: EpiphanyCrrcAction, + pub reorient_result_status: EpiphanyCrrcResultStatus, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -235,25 +149,3 @@ pub struct EpiphanyCoordinatorStatus { pub source_signals: EpiphanyCoordinatorSourceSignals, pub roles: Vec, } - -#[derive(Debug, Clone, PartialEq, Eq, Default)] -pub struct EpiphanyCoordinatorFindingSignals { - pub research_result_accepted: bool, - pub research_result_reviewable: bool, - pub research_result_failure_reviewed: bool, - pub modeling_result_accepted_after_research: bool, - pub modeling_result_requests_regather: bool, - pub modeling_result_accepted: bool, - pub modeling_result_reviewable: bool, - pub modeling_result_failure_reviewed: bool, - pub modeling_result_proposal_bound: bool, - pub modeling_result_accepted_after_verification: bool, - pub implementation_evidence_after_verification: bool, - pub verification_result_cites_implementation_evidence: bool, - pub verification_result_covers_current_modeling: bool, - pub verification_result_accepted: bool, - pub verification_result_failure_reviewed: bool, - pub verification_result_allows_implementation: bool, - pub verification_result_needs_evidence: bool, - pub reorient_finding_accepted: bool, -} diff --git a/epiphany-core/src/surfaces/jobs.rs b/epiphany-core/src/surfaces/jobs.rs index df5e26b9..92ae1355 100644 --- a/epiphany-core/src/surfaces/jobs.rs +++ b/epiphany-core/src/surfaces/jobs.rs @@ -1,12 +1,5 @@ -use super::freshness::graph_freshness; -use epiphany_state_model::EpiphanyJobBinding; use epiphany_state_model::EpiphanyJobKind; -use epiphany_state_model::EpiphanyRetrievalState; -use epiphany_state_model::EpiphanyRetrievalStatus; -use epiphany_state_model::EpiphanyRuntimeLink; -use epiphany_state_model::EpiphanyThreadState; -use serde::Deserialize; -use serde::Serialize; +use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -54,310 +47,157 @@ pub struct EpiphanyJobView { #[derive(Debug, Clone, Copy)] pub struct EpiphanyJobsInput<'a> { - pub state: Option<&'a EpiphanyThreadState>, - pub retrieval_override: Option<&'a EpiphanyRetrievalState>, + pub mind: Option<&'a crate::EpiphanyMindView>, } pub fn derive_jobs(input: EpiphanyJobsInput<'_>) -> Vec { - let mut jobs = vec![ - index_job(input.state, input.retrieval_override), - remap_job(input.state), - verification_job(input.state), - ]; - - let Some(state) = input.state else { - return jobs; - }; - - for binding in &state.job_bindings { - let runtime_link = latest_runtime_link_for_binding(state, binding.id.as_str()); - let replacement = if let Some(existing) = jobs.iter().find(|job| job.id == binding.id) { - overlay_job_binding(existing.clone(), binding, runtime_link) - } else { - bound_job(binding, runtime_link) - }; - - if let Some(existing) = jobs.iter_mut().find(|job| job.id == binding.id) { - *existing = replacement; - } else { - jobs.push(replacement); - } - } - - jobs + vec![ + body_observation_job(input.mind), + repo_model_job(input.mind), + verification_job(input.mind), + ] } -fn bound_job( - binding: &EpiphanyJobBinding, - runtime_link: Option<&EpiphanyRuntimeLink>, -) -> EpiphanyJobView { - overlay_job_binding( - EpiphanyJobView { - id: binding.id.clone(), - kind: binding.kind, - scope: binding.scope.clone(), - owner_role: binding.owner_role.clone(), - authority_scope: binding.authority_scope.clone(), - runtime_job_id: runtime_link.map(|link| link.runtime_job_id.clone()), - status: if binding.blocking_reason.is_some() { - EpiphanyJobStatus::Blocked - } else { - EpiphanyJobStatus::Idle - }, - items_processed: None, - items_total: None, - progress_note: None, - last_checkpoint_at_unix_seconds: None, - blocking_reason: None, - active_thread_ids: Vec::new(), - linked_subgoal_ids: binding.linked_subgoal_ids.clone(), - linked_graph_node_ids: binding.linked_graph_node_ids.clone(), - }, - binding, - runtime_link, - ) -} - -fn overlay_job_binding( - mut job: EpiphanyJobView, - binding: &EpiphanyJobBinding, - runtime_link: Option<&EpiphanyRuntimeLink>, -) -> EpiphanyJobView { - job.kind = binding.kind; - job.scope = binding.scope.clone(); - job.owner_role = binding.owner_role.clone(); - job.authority_scope = binding.authority_scope.clone(); - job.runtime_job_id = runtime_link.map(|link| link.runtime_job_id.clone()); - if !binding.linked_subgoal_ids.is_empty() { - job.linked_subgoal_ids = binding.linked_subgoal_ids.clone(); - } - if !binding.linked_graph_node_ids.is_empty() { - job.linked_graph_node_ids = binding.linked_graph_node_ids.clone(); - } - if let Some(blocking_reason) = binding.blocking_reason.clone() { - job.blocking_reason = Some(blocking_reason); - } - if binding.blocking_reason.is_some() { - job.status = EpiphanyJobStatus::Blocked; - return job; - } - - if runtime_link.is_some_and(|link| link.runtime_result_id.is_none()) { - job.status = EpiphanyJobStatus::Pending; - job.blocking_reason = None; - job.progress_note = - Some("Queued for Epiphany heartbeat activation through runtime_links.".to_string()); - return job; - } - - if runtime_link.is_some() { - job.status = EpiphanyJobStatus::Completed; - job.blocking_reason = None; - job.progress_note = - Some("Epiphany heartbeat runtime result is ready for review.".to_string()); - return job; - } - - job -} - -fn index_job( - state: Option<&EpiphanyThreadState>, - retrieval_override: Option<&EpiphanyRetrievalState>, -) -> EpiphanyJobView { - let retrieval = state - .and_then(|state| state.retrieval.as_ref()) - .or(retrieval_override); - let linked_subgoal_ids = active_subgoal_ids(state); - let linked_graph_node_ids = active_graph_node_ids(state); - - let Some(retrieval) = retrieval else { - return EpiphanyJobView { - id: "retrieval-index".to_string(), - kind: EpiphanyJobKind::Indexing, - scope: "workspace".to_string(), - owner_role: "epiphany-core".to_string(), - authority_scope: None, - runtime_job_id: None, - status: EpiphanyJobStatus::Unavailable, - items_processed: None, - items_total: None, - progress_note: None, - last_checkpoint_at_unix_seconds: None, - blocking_reason: Some("Retrieval state is unavailable for this thread.".to_string()), - active_thread_ids: Vec::new(), - linked_subgoal_ids, - linked_graph_node_ids, - }; - }; - - let dirty_path_count = retrieval.dirty_paths.len(); - let progress_note = match retrieval.status { - EpiphanyRetrievalStatus::Ready if dirty_path_count == 0 => { - "Retrieval catalog is ready.".to_string() - } - EpiphanyRetrievalStatus::Ready => { - format!("Retrieval catalog is ready with {dirty_path_count} dirty path(s) noted.") - } - EpiphanyRetrievalStatus::Stale => { - format!("Retrieval catalog is stale; {dirty_path_count} dirty path(s) need refresh.") - } - EpiphanyRetrievalStatus::Indexing => "Retrieval catalog is indexing.".to_string(), - EpiphanyRetrievalStatus::Unavailable => "Retrieval catalog is unavailable.".to_string(), - }; - - EpiphanyJobView { - id: "retrieval-index".to_string(), - kind: EpiphanyJobKind::Indexing, - scope: retrieval.workspace_root.display().to_string(), - owner_role: "unowned-legacy-projection".to_string(), - authority_scope: None, - runtime_job_id: None, - status: job_status_from_retrieval_status(retrieval.status), - items_processed: retrieval.indexed_file_count, - items_total: None, - progress_note: Some(progress_note), - last_checkpoint_at_unix_seconds: retrieval.last_indexed_at_unix_seconds, - blocking_reason: matches!( - retrieval.status, - EpiphanyRetrievalStatus::Ready | EpiphanyRetrievalStatus::Unavailable - ) - .then(|| { - "No Body-bound workspace coverage owner is installed; legacy retrieval state cannot authorize readiness.".to_string() - }), - active_thread_ids: Vec::new(), - linked_subgoal_ids, - linked_graph_node_ids, - } -} - -fn job_status_from_retrieval_status(status: EpiphanyRetrievalStatus) -> EpiphanyJobStatus { - match status { - EpiphanyRetrievalStatus::Ready => EpiphanyJobStatus::Unavailable, - EpiphanyRetrievalStatus::Stale => EpiphanyJobStatus::Needed, - EpiphanyRetrievalStatus::Indexing => EpiphanyJobStatus::Running, - EpiphanyRetrievalStatus::Unavailable => EpiphanyJobStatus::Unavailable, - } -} - -fn remap_job(state: Option<&EpiphanyThreadState>) -> EpiphanyJobView { - let Some(state) = state else { - return blocked_state_job( - "graph-remap", - EpiphanyJobKind::Remap, - "architecture/dataflow graphs", - "Epiphany state is missing, so there is no graph to remap.", - ); - }; - - let freshness = graph_freshness(Some(state)); - // The legacy thread projection has no Body-generation witness and therefore - // cannot authorize a completed remap. Canonical readiness belongs to the - // future joined RepoModel/Body/retrieval authority. - EpiphanyJobView { - id: "graph-remap".to_string(), - kind: EpiphanyJobKind::Remap, - scope: "architecture/dataflow graphs".to_string(), - owner_role: "epiphany-core".to_string(), - authority_scope: None, - runtime_job_id: None, - status: EpiphanyJobStatus::Needed, - items_processed: None, - items_total: None, - progress_note: Some(freshness.note), - last_checkpoint_at_unix_seconds: None, - blocking_reason: None, - active_thread_ids: Vec::new(), - linked_subgoal_ids: active_subgoal_ids(Some(state)), - linked_graph_node_ids: active_graph_node_ids(Some(state)), - } -} - -fn verification_job(state: Option<&EpiphanyThreadState>) -> EpiphanyJobView { - let Some(state) = state else { - return blocked_state_job( - "verification", - EpiphanyJobKind::Verification, - "invariants/evidence", - "Epiphany state is missing, so there are no invariants to verify.", - ); - }; - - let total = state.invariants.len() as u32; - let verified = state - .invariants - .iter() - .filter(|invariant| invariant_status_is_accepting(&invariant.status)) - .count() as u32; - let status = if total > 0 && verified < total { - EpiphanyJobStatus::Needed - } else { - EpiphanyJobStatus::Idle - }; - let progress_note = if total == 0 { - "No invariants are recorded yet.".to_string() - } else if verified == total { - format!("All {total} invariant(s) are currently accepting.") - } else { - format!("{verified} of {total} invariant(s) are currently accepting.") - }; - - EpiphanyJobView { - id: "verification".to_string(), - kind: EpiphanyJobKind::Verification, - scope: "invariants/evidence".to_string(), - owner_role: "epiphany-harness".to_string(), - authority_scope: None, - runtime_job_id: None, - status, - items_processed: Some(verified), - items_total: Some(total), - progress_note: Some(progress_note), - last_checkpoint_at_unix_seconds: None, - blocking_reason: None, - active_thread_ids: Vec::new(), - linked_subgoal_ids: active_subgoal_ids(Some(state)), - linked_graph_node_ids: active_graph_node_ids(Some(state)), - } -} - -fn blocked_state_job( +fn base_job( id: &str, kind: EpiphanyJobKind, scope: &str, - blocking_reason: &str, + owner_role: &str, + status: EpiphanyJobStatus, ) -> EpiphanyJobView { EpiphanyJobView { - id: id.to_string(), + id: id.into(), kind, - scope: scope.to_string(), - owner_role: "epiphany-harness".to_string(), + scope: scope.into(), + owner_role: owner_role.into(), authority_scope: None, runtime_job_id: None, - status: EpiphanyJobStatus::Blocked, + status, items_processed: None, items_total: None, progress_note: None, last_checkpoint_at_unix_seconds: None, - blocking_reason: Some(blocking_reason.to_string()), + blocking_reason: None, active_thread_ids: Vec::new(), linked_subgoal_ids: Vec::new(), linked_graph_node_ids: Vec::new(), } } -fn active_subgoal_ids(state: Option<&EpiphanyThreadState>) -> Vec { - state - .and_then(|state| state.active_subgoal_id.clone()) +fn body_observation_job(mind: Option<&crate::EpiphanyMindView>) -> EpiphanyJobView { + let body = mind.and_then(|mind| mind.repository_body_observation.as_ref()); + let mut job = base_job( + "repository-body-observation", + EpiphanyJobKind::Indexing, + "repository Body", + "epiphany-body-observer", + if body.is_some() { + EpiphanyJobStatus::Completed + } else { + EpiphanyJobStatus::Needed + }, + ); + job.linked_subgoal_ids = active_subgoal_ids(mind); + job.progress_note = Some(match body { + Some(body) => format!( + "Mind contains exact Body observation {} at generation {}.", + body.observation_id, body.generation + ), + None => "Mind has no admitted repository Body observation.".into(), + }); + job +} + +fn repo_model_job(mind: Option<&crate::EpiphanyMindView>) -> EpiphanyJobView { + let model = mind.and_then(|mind| mind.repo_model.as_ref()); + let mut job = base_job( + "repo-model", + EpiphanyJobKind::Remap, + "keyed RepoModel", + "epiphany-modeling", + if model.is_some() { + EpiphanyJobStatus::Idle + } else { + EpiphanyJobStatus::Blocked + }, + ); + job.linked_subgoal_ids = active_subgoal_ids(mind); + job.linked_graph_node_ids = active_graph_node_ids(mind); + job.progress_note = model.map(|model| { + format!( + "Keyed RepoModel projects {} node(s), {} edge(s), and {} frontier item(s).", + model.nodes.len(), + model.edges.len(), + model.frontier.len() + ) + }); + if model.is_none() { + job.blocking_reason = Some("Mind has no keyed RepoModel identity.".into()); + } + job +} + +fn verification_job(mind: Option<&crate::EpiphanyMindView>) -> EpiphanyJobView { + let Some(mind) = mind else { + let mut job = base_job( + "verification", + EpiphanyJobKind::Verification, + "invariants/evidence", + "epiphany-soul", + EpiphanyJobStatus::Blocked, + ); + job.blocking_reason = Some("Mind is missing.".into()); + return job; + }; + let total = mind.invariants.len() as u32; + let verified = mind + .invariants + .iter() + .filter(|invariant| invariant_status_is_accepting(&invariant.status)) + .count() as u32; + let mut job = base_job( + "verification", + EpiphanyJobKind::Verification, + "invariants/evidence", + "epiphany-soul", + if total > verified { + EpiphanyJobStatus::Needed + } else { + EpiphanyJobStatus::Idle + }, + ); + job.items_processed = Some(verified); + job.items_total = Some(total); + job.linked_subgoal_ids = active_subgoal_ids(Some(mind)); + job.linked_graph_node_ids = active_graph_node_ids(Some(mind)); + job.progress_note = Some(format!("{verified} of {total} invariant(s) are accepting.")); + job +} + +fn active_subgoal_ids(mind: Option<&crate::EpiphanyMindView>) -> Vec { + mind.and_then(|mind| mind.active_subgoal_id.clone()) .map(|id| vec![id]) .unwrap_or_default() } -fn active_graph_node_ids(state: Option<&EpiphanyThreadState>) -> Vec { - state - .and_then(|state| state.graph_frontier.as_ref()) - .map(|frontier| frontier.active_node_ids.clone()) - .unwrap_or_default() +fn active_graph_node_ids(mind: Option<&crate::EpiphanyMindView>) -> Vec { + let mut ids = mind + .and_then(|mind| mind.repo_model.as_ref()) + .into_iter() + .flat_map(|model| model.frontier.iter()) + .filter(|item| { + matches!( + item.status, + epiphany_state_model::RepoFrontierStatus::Proposed + | epiphany_state_model::RepoFrontierStatus::Active + | epiphany_state_model::RepoFrontierStatus::Blocked + ) + }) + .flat_map(|item| item.target_claim_ids.iter().cloned()) + .collect::>(); + ids.sort(); + ids.dedup(); + ids } fn invariant_status_is_accepting(status: &str) -> bool { @@ -367,222 +207,32 @@ fn invariant_status_is_accepting(status: &str) -> bool { ) } -fn latest_runtime_link_for_binding<'a>( - state: &'a EpiphanyThreadState, - binding_id: &str, -) -> Option<&'a EpiphanyRuntimeLink> { - state - .runtime_links - .iter() - .find(|link| link.binding_id == binding_id && !link.runtime_job_id.trim().is_empty()) -} - #[cfg(test)] mod tests { use super::*; - use epiphany_state_model::EpiphanyChurnState; - use epiphany_state_model::EpiphanyGraphCheckpoint; - use epiphany_state_model::EpiphanyGraphFrontier; - use epiphany_state_model::EpiphanyInvariant; - use std::path::PathBuf; #[test] - fn derives_builtin_jobs_without_state() { - let jobs = derive_jobs(EpiphanyJobsInput { - state: None, - retrieval_override: None, - }); - + fn missing_mind_has_only_derived_blocked_or_needed_jobs() { + let jobs = derive_jobs(EpiphanyJobsInput { mind: None }); assert_eq!(jobs.len(), 3); - assert_eq!(jobs[0].id, "retrieval-index"); - assert_eq!(jobs[0].status, EpiphanyJobStatus::Unavailable); + assert_eq!(jobs[0].status, EpiphanyJobStatus::Needed); assert_eq!(jobs[1].status, EpiphanyJobStatus::Blocked); assert_eq!(jobs[2].status, EpiphanyJobStatus::Blocked); + assert!(jobs.iter().all(|job| job.runtime_job_id.is_none())); } #[test] - fn reflects_retrieval_and_graph_pressure() { - let state = EpiphanyThreadState { - active_subgoal_id: Some("subgoal-1".to_string()), - retrieval: Some(EpiphanyRetrievalState { - workspace_root: PathBuf::from("E:/repo"), - status: EpiphanyRetrievalStatus::Stale, - dirty_paths: vec![PathBuf::from("src/lib.rs")], - indexed_file_count: Some(7), - ..Default::default() - }), - graph_frontier: Some(EpiphanyGraphFrontier { - active_node_ids: vec!["node-1".to_string()], - dirty_paths: vec![PathBuf::from("src/lib.rs")], - open_question_ids: vec!["q-1".to_string()], - ..Default::default() - }), - invariants: vec![ - EpiphanyInvariant { - id: "inv-1".to_string(), - description: "verified".to_string(), - status: "verified".to_string(), - rationale: None, - }, - EpiphanyInvariant { - id: "inv-2".to_string(), - description: "pending".to_string(), - status: "pending".to_string(), - rationale: None, - }, - ], - ..Default::default() - }; - - let jobs = derive_jobs(EpiphanyJobsInput { - state: Some(&state), - retrieval_override: None, - }); - - let retrieval = jobs.iter().find(|job| job.id == "retrieval-index").unwrap(); - assert_eq!(retrieval.status, EpiphanyJobStatus::Needed); - assert_eq!(retrieval.items_processed, Some(7)); - assert_eq!(retrieval.linked_subgoal_ids, vec!["subgoal-1".to_string()]); - - let remap = jobs.iter().find(|job| job.id == "graph-remap").unwrap(); - assert_eq!(remap.status, EpiphanyJobStatus::Needed); - assert_eq!(remap.linked_graph_node_ids, vec!["node-1".to_string()]); - - let verification = jobs.iter().find(|job| job.id == "verification").unwrap(); - assert_eq!(verification.status, EpiphanyJobStatus::Needed); - assert_eq!(verification.items_processed, Some(1)); - assert_eq!(verification.items_total, Some(2)); - } - - #[test] - fn remap_job_refuses_legacy_graph_readiness_authority() { - let incomplete = EpiphanyThreadState::default(); - let jobs = derive_jobs(EpiphanyJobsInput { - state: Some(&incomplete), - retrieval_override: None, - }); - assert_eq!( - jobs.iter() - .find(|job| job.id == "graph-remap") - .unwrap() - .status, - EpiphanyJobStatus::Needed - ); - - let forged_legacy_ready = EpiphanyThreadState { - graph_checkpoint: Some(EpiphanyGraphCheckpoint { - checkpoint_id: "graph-1".to_string(), - ..Default::default() - }), - churn: Some(EpiphanyChurnState { - ..Default::default() - }), - ..Default::default() - }; - let jobs = derive_jobs(EpiphanyJobsInput { - state: Some(&forged_legacy_ready), - retrieval_override: None, - }); - assert_eq!( - jobs.iter() - .find(|job| job.id == "graph-remap") - .unwrap() - .status, - EpiphanyJobStatus::Needed - ); - } - - #[test] - fn overlays_binding_with_runtime_link() { - let state = EpiphanyThreadState { - job_bindings: vec![EpiphanyJobBinding { - id: "binding-1".to_string(), - kind: EpiphanyJobKind::Specialist, - scope: "modeling".to_string(), - owner_role: "body".to_string(), - authority_scope: Some("epiphany.role.modeling".to_string()), - linked_subgoal_ids: vec!["subgoal-1".to_string()], - linked_graph_node_ids: vec!["node-1".to_string()], - blocking_reason: None, - }], - runtime_links: vec![EpiphanyRuntimeLink { - id: "link-1".to_string(), - binding_id: "binding-1".to_string(), - surface: "role".to_string(), - role_id: "modeling".to_string(), - authority_scope: "epiphany.role.modeling".to_string(), - runtime_job_id: "runtime-job-1".to_string(), - runtime_result_id: None, - linked_subgoal_ids: Vec::new(), - linked_graph_node_ids: Vec::new(), - }], - ..Default::default() - }; - - let jobs = derive_jobs(EpiphanyJobsInput { - state: Some(&state), - retrieval_override: None, - }); - - let binding = jobs.iter().find(|job| job.id == "binding-1").unwrap(); - assert_eq!(binding.status, EpiphanyJobStatus::Pending); - assert_eq!(binding.runtime_job_id.as_deref(), Some("runtime-job-1")); - assert_eq!( - binding.progress_note.as_deref(), - Some("Queued for Epiphany heartbeat activation through runtime_links.") - ); - } - - #[test] - fn terminal_runtime_link_owns_binding_over_stale_active_history() { - let state = EpiphanyThreadState { - job_bindings: vec![EpiphanyJobBinding { - id: "binding-1".to_string(), - kind: EpiphanyJobKind::Specialist, - scope: "modeling".to_string(), - owner_role: "body".to_string(), - authority_scope: Some("epiphany.role.modeling".to_string()), - linked_subgoal_ids: Vec::new(), - linked_graph_node_ids: Vec::new(), - blocking_reason: None, - }], - runtime_links: vec![ - EpiphanyRuntimeLink { - id: "link-terminal".to_string(), - binding_id: "binding-1".to_string(), - surface: "runtimeResult".to_string(), - role_id: "modeling".to_string(), - authority_scope: "epiphany.role.modeling".to_string(), - runtime_job_id: "runtime-job-1".to_string(), - runtime_result_id: Some("result-1".to_string()), - linked_subgoal_ids: Vec::new(), - linked_graph_node_ids: Vec::new(), - }, - EpiphanyRuntimeLink { - id: "link-stale-active".to_string(), - binding_id: "binding-1".to_string(), - surface: "jobLaunch".to_string(), - role_id: "modeling".to_string(), - authority_scope: "epiphany.role.modeling".to_string(), - runtime_job_id: "runtime-job-1".to_string(), - runtime_result_id: None, - linked_subgoal_ids: Vec::new(), - linked_graph_node_ids: Vec::new(), - }, - ], - ..Default::default() - }; - - let jobs = derive_jobs(EpiphanyJobsInput { - state: Some(&state), - retrieval_override: None, - }); - - let binding = jobs.iter().find(|job| job.id == "binding-1").unwrap(); - assert_eq!(binding.status, EpiphanyJobStatus::Completed); - assert_eq!( - binding.progress_note.as_deref(), - Some("Epiphany heartbeat runtime result is ready for review.") - ); + fn source_contains_no_aggregate_job_or_runtime_link_owner() { + let source = include_str!("jobs.rs"); + let production = source.split("#[cfg(test)]").next().unwrap_or(source); + for forbidden in [ + "EpiphanyThreadState", + "EpiphanyJobBinding", + "EpiphanyRuntimeLink", + "latest_runtime_link", + "state_revision", + ] { + assert!(!production.contains(forbidden)); + } } } diff --git a/epiphany-core/src/surfaces/mod.rs b/epiphany-core/src/surfaces/mod.rs index 1741dc28..f64ee3ff 100644 --- a/epiphany-core/src/surfaces/mod.rs +++ b/epiphany-core/src/surfaces/mod.rs @@ -61,15 +61,12 @@ pub use pressure::EpiphanyPressureStatus; pub use pressure::EpiphanyTokenUsageSnapshot; pub use pressure::derive_pressure_view; pub use reorient::EpiphanyReorientAction; -pub use role_board::EpiphanyRoleBoardCheckpointSummary; pub use role_board::EpiphanyRoleBoardInput; pub use role_board::EpiphanyRoleBoardJob; pub use role_board::EpiphanyRoleBoardJobStatus; pub use role_board::EpiphanyRoleBoardLane; -pub use role_board::EpiphanyRoleBoardPlanningSummary; pub use role_board::derive_role_board; pub use role_board::render_role_board_note; -pub use role_board::reorientation_role_status; pub use role_board::role_board_job_status_to_role_status; pub use role_result::EpiphanyAcceptanceBundle; pub use role_result::EpiphanyReorientAcceptanceBundle; diff --git a/epiphany-core/src/surfaces/planning.rs b/epiphany-core/src/surfaces/planning.rs index c123f95c..e2c29313 100644 --- a/epiphany-core/src/surfaces/planning.rs +++ b/epiphany-core/src/surfaces/planning.rs @@ -1,5 +1,4 @@ use epiphany_state_model::EpiphanyPlanningState; -use epiphany_state_model::EpiphanyThreadState; use serde::Deserialize; use serde::Serialize; @@ -29,16 +28,16 @@ pub struct EpiphanyPlanningSummary { #[serde(rename_all = "camelCase")] pub struct EpiphanyPlanningView { pub state_status: EpiphanyPlanningStateStatus, - pub state_revision: Option, + pub projection_digest: Option, pub planning: EpiphanyPlanningState, pub summary: EpiphanyPlanningSummary, } -pub fn derive_planning_view(state: Option<&EpiphanyThreadState>) -> EpiphanyPlanningView { - let Some(state) = state else { +pub fn derive_planning_view(mind: Option<&crate::EpiphanyMindView>) -> EpiphanyPlanningView { + let Some(mind) = mind else { return EpiphanyPlanningView { state_status: EpiphanyPlanningStateStatus::Missing, - state_revision: None, + projection_digest: None, planning: EpiphanyPlanningState::default(), summary: EpiphanyPlanningSummary { capture_count: 0, @@ -55,7 +54,7 @@ pub fn derive_planning_view(state: Option<&EpiphanyThreadState>) -> EpiphanyPlan }; }; - let planning = state.planning.clone(); + let planning = mind.planning.clone(); let pending_capture_count = planning .captures .iter() @@ -85,7 +84,7 @@ pub fn derive_planning_view(state: Option<&EpiphanyThreadState>) -> EpiphanyPlan EpiphanyPlanningView { state_status: EpiphanyPlanningStateStatus::Ready, - state_revision: Some(state.revision), + projection_digest: Some(mind.projection_digest.clone()), planning: planning.clone(), summary: EpiphanyPlanningSummary { capture_count: planning.captures.len() as u32, @@ -96,7 +95,7 @@ pub fn derive_planning_view(state: Option<&EpiphanyThreadState>) -> EpiphanyPlan roadmap_stream_count: planning.roadmap_streams.len() as u32, objective_draft_count: planning.objective_drafts.len() as u32, draft_objective_count, - active_objective: state.objective.clone(), + active_objective: mind.objective.clone(), note, }, } @@ -113,16 +112,29 @@ mod tests { let view = derive_planning_view(None); assert_eq!(view.state_status, EpiphanyPlanningStateStatus::Missing); - assert_eq!(view.state_revision, None); + assert_eq!(view.projection_digest, None); assert_eq!(view.summary.capture_count, 0); assert!(view.planning.is_empty()); } #[test] fn summarizes_planning_counts_without_adopting_objective() { - let state = EpiphanyThreadState { - revision: 3, + let mind = crate::EpiphanyMindView { + schema_epoch: crate::MIND_SCHEMA_EPOCH.into(), + runtime_id: "runtime-1".into(), + projection_digest: "sha256:mind-3".into(), + source_documents: Vec::new(), objective: Some("active objective".to_string()), + active_subgoal_id: None, + subgoals: Vec::new(), + invariants: Vec::new(), + observations: Vec::new(), + evidence: Vec::new(), + verification_audits: Vec::new(), + reorientation_decisions: Vec::new(), + reorientation_failures: Vec::new(), + investigation_checkpoint: None, + mode: None, planning: EpiphanyPlanningState { captures: vec![ EpiphanyPlanningCapture { @@ -151,13 +163,14 @@ mod tests { ], ..Default::default() }, - ..Default::default() + repository_body_observation: None, + repo_model: None, }; - let view = derive_planning_view(Some(&state)); + let view = derive_planning_view(Some(&mind)); assert_eq!(view.state_status, EpiphanyPlanningStateStatus::Ready); - assert_eq!(view.state_revision, Some(3)); + assert_eq!(view.projection_digest.as_deref(), Some("sha256:mind-3")); assert_eq!(view.summary.capture_count, 2); assert_eq!(view.summary.pending_capture_count, 1); assert_eq!(view.summary.github_issue_capture_count, 1); diff --git a/epiphany-core/src/surfaces/role_board.rs b/epiphany-core/src/surfaces/role_board.rs index bfec614b..6b7eb5e6 100644 --- a/epiphany-core/src/surfaces/role_board.rs +++ b/epiphany-core/src/surfaces/role_board.rs @@ -1,8 +1,10 @@ -use super::EpiphanyCoordinatorRoleId; -use super::EpiphanyCoordinatorRoleStatus; -use super::EpiphanyCoordinatorSceneAction; -use super::EpiphanyCrrcAction; -use super::EpiphanyCrrcResultStatus; +use super::{ + EpiphanyCoordinatorRoleId, EpiphanyCoordinatorRoleStatus, EpiphanyCoordinatorSceneAction, +}; +use crate::{ + EpiphanyAgentPassContinuationAction, EpiphanyCurrentWorkProjection, + RepoFrontierPlanningLifecycleStage, RepoFrontierResearchContinuationAction, +}; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] @@ -29,44 +31,11 @@ pub struct EpiphanyRoleBoardJob { pub blocking_reason: Option, } -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct EpiphanyRoleBoardPlanningSummary { - pub capture_count: usize, - pub backlog_item_count: usize, - pub roadmap_stream_count: usize, - pub objective_draft_count: usize, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct EpiphanyRoleBoardCheckpointSummary { - pub disposition: Option, - pub next_action: Option, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] +#[derive(Debug, Clone, PartialEq, Eq)] pub struct EpiphanyRoleBoardInput { - pub state_present: bool, - pub planning: EpiphanyRoleBoardPlanningSummary, - pub checkpoint: Option, - pub reorient_next_action: String, + pub mind_present: bool, + pub current_work: EpiphanyCurrentWorkProjection, pub jobs: Vec, - pub crrc_action: EpiphanyCrrcAction, - pub crrc_recommended_scene_action: Option, - pub crrc_reason: String, - pub reorient_decision_action: String, - pub pressure_level: String, - pub reorient_result_status: EpiphanyCrrcResultStatus, - pub reorient_job: Option, - pub imagination_binding_id: String, - pub research_binding_id: String, - pub modeling_binding_id: String, - pub verification_binding_id: String, - pub reorient_owner_role: String, - pub imagination_owner_role: String, - pub research_owner_role: String, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -83,228 +52,228 @@ pub struct EpiphanyRoleBoardLane { } pub fn derive_role_board(input: EpiphanyRoleBoardInput) -> Vec { - let state_present = input.state_present; - let checkpoint_present = input.checkpoint.is_some(); - let imagination_jobs = input - .jobs - .iter() - .filter(|job| job.id == input.imagination_binding_id) - .cloned() - .collect::>(); - let imagination_bound_job = imagination_jobs - .iter() - .find(|job| job.id == input.imagination_binding_id); - let imagination_has_bound_job = imagination_bound_job.is_some(); - let imagination_status = imagination_bound_job - .map(|job| role_board_job_status_to_role_status(job.status)) - .unwrap_or_else(|| imagination_role_status(state_present, &input.planning)); - let imagination_note = imagination_bound_job - .and_then(job_note) - .unwrap_or_else(|| render_imagination_role_note(state_present, &input.planning)); - let imagination_recommended_action = if imagination_has_bound_job { - Some(EpiphanyCoordinatorSceneAction::RoleResult) - } else if state_present { - Some(EpiphanyCoordinatorSceneAction::RoleLaunch) - } else { - Some(EpiphanyCoordinatorSceneAction::Update) - }; + let missing = !input.mind_present; + let lane = + |id, title: &str, owner_role: &str, status, note: &str, scope: &str, recommended_action| { + EpiphanyRoleBoardLane { + id, + title: title.into(), + owner_role: owner_role.into(), + status: if missing { + EpiphanyCoordinatorRoleStatus::Blocked + } else { + status + }, + note: if missing { + "Canonical keyed Mind is missing.".into() + } else { + note.into() + }, + jobs: input + .jobs + .iter() + .filter(|job| job.owner_role == owner_role) + .cloned() + .collect(), + authority_scopes: vec![scope.into()], + recommended_action, + } + }; - let modeling_jobs = input - .jobs - .iter() - .filter(|job| job.id == input.modeling_binding_id || job.id == "graph-remap") - .cloned() - .collect::>(); - let modeling_bound_job = modeling_jobs - .iter() - .find(|job| job.id == input.modeling_binding_id); - let modeling_has_bound_job = modeling_bound_job.is_some(); - let modeling_status = modeling_role_status( - checkpoint_present, - modeling_bound_job.or_else(|| modeling_jobs.first()), - ); - let modeling_recommended_action = if modeling_has_bound_job { - Some(EpiphanyCoordinatorSceneAction::RoleResult) - } else if state_present { - Some(EpiphanyCoordinatorSceneAction::RoleLaunch) - } else { - Some(EpiphanyCoordinatorSceneAction::Update) - }; - - let research_jobs = input - .jobs - .iter() - .filter(|job| job.id == input.research_binding_id) - .cloned() - .collect::>(); - let research_bound_job = research_jobs - .iter() - .find(|job| job.id == input.research_binding_id); - let research_has_bound_job = research_bound_job.is_some(); - let research_status = research_bound_job - .map(|job| role_board_job_status_to_role_status(job.status)) - .unwrap_or(if state_present { - EpiphanyCoordinatorRoleStatus::Ready - } else { - EpiphanyCoordinatorRoleStatus::Blocked - }); - let research_note = research_bound_job.and_then(job_note).unwrap_or_else(|| { - "Gather citable source evidence before Modeling models from it.".to_string() - }); - let research_recommended_action = if research_has_bound_job { - Some(EpiphanyCoordinatorSceneAction::RoleResult) - } else if state_present { - Some(EpiphanyCoordinatorSceneAction::RoleLaunch) - } else { - Some(EpiphanyCoordinatorSceneAction::Update) - }; - - let verification_jobs = input - .jobs - .iter() - .filter(|job| job.id == input.verification_binding_id || job.id == "verification") - .cloned() - .collect::>(); - let verification_bound_job = verification_jobs - .iter() - .find(|job| job.id == input.verification_binding_id); - let verification_has_bound_job = verification_bound_job.is_some(); - let verification_primary_job = verification_bound_job.or_else(|| verification_jobs.first()); - let verification_status = verification_primary_job - .map(|job| role_board_job_status_to_role_status(job.status)) - .unwrap_or(EpiphanyCoordinatorRoleStatus::Unavailable); - let verification_note = verification_primary_job - .and_then(job_note) - .unwrap_or_else(|| { - "Review evidence, worker findings, and verifier results before promotion.".to_string() - }); - let verification_recommended_action = if verification_has_bound_job { - Some(EpiphanyCoordinatorSceneAction::RoleResult) - } else if state_present { - Some(EpiphanyCoordinatorSceneAction::RoleLaunch) - } else { - None - }; - let reorientation_jobs = input.reorient_job.clone().into_iter().collect::>(); + let modeling_action = input + .current_work + .proposal_modeling + .as_ref() + .map(|work| work.action) + .or(input.current_work.body_modeling_action) + .or(input + .current_work + .frontier_verdict_modeling + .as_ref() + .map(|work| work.action)); + let imagination_action = consideration_action(&input.current_work); vec![ - EpiphanyRoleBoardLane { - id: EpiphanyCoordinatorRoleId::Implementation, - title: "Implementation".to_string(), - owner_role: "coding-agent".to_string(), - status: if input.crrc_action == EpiphanyCrrcAction::Continue { + lane( + EpiphanyCoordinatorRoleId::Implementation, + "Hands / Implementation", + "epiphany-hands", + if input.current_work.hands_frontier_ready { EpiphanyCoordinatorRoleStatus::Ready } else { EpiphanyCoordinatorRoleStatus::Blocked }, - note: if input.crrc_action == EpiphanyCrrcAction::Continue { - "Continue the bounded coding task.".to_string() + if input.current_work.hands_frontier_ready { + "An adopted plan has an exact actionable Hands route." } else { - format!("Wait for CRRC action: {:?}.", input.crrc_action) + "No exact actionable Hands route exists." }, - jobs: input - .jobs - .iter() - .filter(|job| { - matches!( - job.owner_role.as_str(), - "coding-agent" | "implementation" | "epiphany-implementation" - ) - }) - .cloned() - .collect(), - authority_scopes: Vec::new(), - recommended_action: if input.crrc_action == EpiphanyCrrcAction::Continue { - None - } else { - input.crrc_recommended_scene_action - }, - }, - EpiphanyRoleBoardLane { - id: EpiphanyCoordinatorRoleId::Imagination, - title: "Imagination / Planning".to_string(), - owner_role: input.imagination_owner_role, - status: imagination_status, - note: imagination_note, - jobs: imagination_jobs, - authority_scopes: vec![ - "epiphany.coordinator.role.launch".to_string(), - "epiphany.coordinator.role.result.read".to_string(), - "epiphany.coordinator.role.accept".to_string(), - "epiphany.coordinator.state.update".to_string(), - ], - recommended_action: imagination_recommended_action, - }, - EpiphanyRoleBoardLane { - id: EpiphanyCoordinatorRoleId::Research, - title: "Eyes / Research".to_string(), - owner_role: input.research_owner_role, - status: research_status, - note: research_note, - jobs: research_jobs, - authority_scopes: vec![ - "epiphany.coordinator.role.launch".to_string(), - "epiphany.coordinator.role.result.read".to_string(), - "epiphany.coordinator.role.accept".to_string(), - "epiphany.coordinator.state.update".to_string(), - ], - recommended_action: research_recommended_action, - }, - EpiphanyRoleBoardLane { - id: EpiphanyCoordinatorRoleId::Modeling, - title: "Modeling / Checkpoint".to_string(), - owner_role: "epiphany-modeler".to_string(), - status: modeling_status, - note: render_modeling_role_note(input.checkpoint.as_ref(), &input.reorient_next_action), - jobs: modeling_jobs, - authority_scopes: vec![ - "epiphany.coordinator.role.launch".to_string(), - "epiphany.coordinator.role.result.read".to_string(), - "epiphany.coordinator.role.accept".to_string(), - "epiphany.coordinator.state.update".to_string(), - ], - recommended_action: modeling_recommended_action, - }, - EpiphanyRoleBoardLane { - id: EpiphanyCoordinatorRoleId::Verification, - title: "Verification / Review".to_string(), - owner_role: "epiphany-verifier".to_string(), - status: verification_status, - note: verification_note, - jobs: verification_jobs, - authority_scopes: vec![ - "epiphany.coordinator.role.launch".to_string(), - "epiphany.coordinator.role.result.read".to_string(), - "epiphany.coordinator.role.accept".to_string(), - "epiphany.mind.distill".to_string(), - "epiphany.mind.propose".to_string(), - "epiphany.mind.promote".to_string(), - ], - recommended_action: verification_recommended_action, - }, - EpiphanyRoleBoardLane { - id: EpiphanyCoordinatorRoleId::Reorientation, - title: "Reorientation".to_string(), - owner_role: input.reorient_owner_role, - status: reorientation_role_status(input.crrc_action, input.reorient_result_status), - note: format!( - "{} verdict, result {:?}, pressure {}. {}", - input.reorient_decision_action, - input.reorient_result_status, - input.pressure_level, - input.crrc_reason + "epiphany.hands.route", + None, + ), + lane( + EpiphanyCoordinatorRoleId::Imagination, + "Imagination / Planning", + "epiphany-imagination", + planning_or_consideration_status( + input.current_work.frontier_planning_stage, + imagination_action, ), - jobs: reorientation_jobs, - authority_scopes: vec![ - "epiphany.coordinator.reorient.launch".to_string(), - "epiphany.coordinator.reorient.result.read".to_string(), - "epiphany.coordinator.reorient.accept".to_string(), - ], - recommended_action: input.crrc_recommended_scene_action, - }, + "Status derives from exact planning and consideration obligations.", + "epiphany.imagination.current_work", + action_scene(imagination_action), + ), + lane( + EpiphanyCoordinatorRoleId::Research, + "Eyes / Research", + "epiphany-eyes", + research_status(input.current_work.research_continuation_action), + "Eyes runs only for an explicit external-evidence obligation.", + "epiphany.eyes.current_work", + input + .current_work + .research_continuation_action + .map(|action| match action { + RepoFrontierResearchContinuationAction::LaunchResearch => { + EpiphanyCoordinatorSceneAction::RoleLaunch + } + RepoFrontierResearchContinuationAction::ReviewResearchResult => { + EpiphanyCoordinatorSceneAction::RoleResult + } + }), + ), + lane( + EpiphanyCoordinatorRoleId::Modeling, + "Modeling / Body Map", + "epiphany-modeling", + continuation_status(modeling_action), + "Status derives from exact Body, proposal, or Soul-verdict Modeling work.", + "epiphany.modeling.current_work", + action_scene(modeling_action), + ), + lane( + EpiphanyCoordinatorRoleId::Verification, + "Soul / Verification", + "epiphany-soul", + continuation_status( + input + .current_work + .verification + .as_ref() + .map(|work| work.action), + ), + "Verification consumes exact Hands consequences and invariant obligations.", + "epiphany.soul.current_work", + action_scene( + input + .current_work + .verification + .as_ref() + .map(|work| work.action), + ), + ), + lane( + EpiphanyCoordinatorRoleId::Reorientation, + "Continuity / Reorientation", + "epiphany-continuity", + continuation_status( + input + .current_work + .reorientation + .as_ref() + .map(|work| work.action), + ), + "Status derives from the exact keyed continuity obligation.", + "epiphany.continuity.current_work", + action_scene( + input + .current_work + .reorientation + .as_ref() + .map(|work| work.action), + ), + ), ] } +fn consideration_action( + work: &EpiphanyCurrentWorkProjection, +) -> Option { + work.imagination_considerations + .first() + .map(|item| item.action) + .or(work + .admitted_model_direction_consideration + .as_ref() + .map(|item| item.action)) +} + +fn continuation_status( + action: Option, +) -> EpiphanyCoordinatorRoleStatus { + match action { + Some(EpiphanyAgentPassContinuationAction::Launch) => EpiphanyCoordinatorRoleStatus::Needed, + Some(EpiphanyAgentPassContinuationAction::Wait) => EpiphanyCoordinatorRoleStatus::Running, + Some(EpiphanyAgentPassContinuationAction::Review) => EpiphanyCoordinatorRoleStatus::Review, + None => EpiphanyCoordinatorRoleStatus::Ready, + } +} + +fn action_scene( + action: Option, +) -> Option { + match action { + Some(EpiphanyAgentPassContinuationAction::Launch) => { + Some(EpiphanyCoordinatorSceneAction::RoleLaunch) + } + Some(EpiphanyAgentPassContinuationAction::Wait) + | Some(EpiphanyAgentPassContinuationAction::Review) => { + Some(EpiphanyCoordinatorSceneAction::RoleResult) + } + None => None, + } +} + +fn research_status( + action: Option, +) -> EpiphanyCoordinatorRoleStatus { + match action { + Some(RepoFrontierResearchContinuationAction::LaunchResearch) => { + EpiphanyCoordinatorRoleStatus::Needed + } + Some(RepoFrontierResearchContinuationAction::ReviewResearchResult) => { + EpiphanyCoordinatorRoleStatus::Review + } + None => EpiphanyCoordinatorRoleStatus::Ready, + } +} + +fn planning_or_consideration_status( + stage: RepoFrontierPlanningLifecycleStage, + consideration: Option, +) -> EpiphanyCoordinatorRoleStatus { + if !matches!( + stage, + RepoFrontierPlanningLifecycleStage::Unavailable + | RepoFrontierPlanningLifecycleStage::Terminal + ) { + return match stage { + RepoFrontierPlanningLifecycleStage::ImaginationRunning + | RepoFrontierPlanningLifecycleStage::MindRunning => { + EpiphanyCoordinatorRoleStatus::Running + } + RepoFrontierPlanningLifecycleStage::ImaginationFailed + | RepoFrontierPlanningLifecycleStage::MindFailed + | RepoFrontierPlanningLifecycleStage::ImaginationResultReady + | RepoFrontierPlanningLifecycleStage::MindResultReady => { + EpiphanyCoordinatorRoleStatus::Review + } + _ => EpiphanyCoordinatorRoleStatus::Needed, + }; + } + continuation_status(consideration) +} + pub fn role_board_job_status_to_role_status( status: EpiphanyRoleBoardJobStatus, ) -> EpiphanyCoordinatorRoleStatus { @@ -322,243 +291,39 @@ pub fn role_board_job_status_to_role_status( } } -pub fn reorientation_role_status( - action: EpiphanyCrrcAction, - result_status: EpiphanyCrrcResultStatus, -) -> EpiphanyCoordinatorRoleStatus { - match result_status { - EpiphanyCrrcResultStatus::Pending | EpiphanyCrrcResultStatus::Running => { - return EpiphanyCoordinatorRoleStatus::Waiting; - } - EpiphanyCrrcResultStatus::Failed - | EpiphanyCrrcResultStatus::Cancelled - | EpiphanyCrrcResultStatus::BackendUnavailable - | EpiphanyCrrcResultStatus::BackendMissing => { - return EpiphanyCoordinatorRoleStatus::Blocked; - } - _ => {} - } - - match action { - EpiphanyCrrcAction::Continue => EpiphanyCoordinatorRoleStatus::Ready, - EpiphanyCrrcAction::PrepareCheckpoint - | EpiphanyCrrcAction::LaunchReorientWorker - | EpiphanyCrrcAction::RegatherManually => EpiphanyCoordinatorRoleStatus::Needed, - EpiphanyCrrcAction::WaitForReorientWorker => EpiphanyCoordinatorRoleStatus::Waiting, - EpiphanyCrrcAction::ReviewReorientResult | EpiphanyCrrcAction::AcceptReorientResult => { - EpiphanyCoordinatorRoleStatus::Review - } - } -} - pub fn render_role_board_note( roles: &[EpiphanyRoleBoardLane], state_status: &str, - recommendation: EpiphanyCrrcAction, + recommendation: crate::EpiphanyCrrcAction, ) -> String { - let blocked_count = roles + let active = roles .iter() - .filter(|role| { - matches!( - role.status, - EpiphanyCoordinatorRoleStatus::Blocked | EpiphanyCoordinatorRoleStatus::Needed + .filter(|lane| { + !matches!( + lane.status, + EpiphanyCoordinatorRoleStatus::Ready | EpiphanyCoordinatorRoleStatus::Completed ) }) .count(); format!( - "Role ownership is derived read-only from Epiphany state, jobs, and CRRC. State: {state_status}; recommendation: {recommendation:?}; blocked-or-needed lanes: {blocked_count}.", + "Mind {state_status}; {active} role lane(s) carry current work; continuity recommendation {recommendation:?}." ) } -fn imagination_role_status( - state_present: bool, - planning: &EpiphanyRoleBoardPlanningSummary, -) -> EpiphanyCoordinatorRoleStatus { - if !state_present { - return EpiphanyCoordinatorRoleStatus::Blocked; - } - if planning.capture_count == 0 - && planning.backlog_item_count == 0 - && planning.roadmap_stream_count == 0 - && planning.objective_draft_count == 0 - { - EpiphanyCoordinatorRoleStatus::Needed - } else { - EpiphanyCoordinatorRoleStatus::Ready - } -} - -fn render_imagination_role_note( - state_present: bool, - planning: &EpiphanyRoleBoardPlanningSummary, -) -> String { - if !state_present { - return "No authoritative Epiphany state exists for planning synthesis.".to_string(); - } - if planning.capture_count == 0 - && planning.backlog_item_count == 0 - && planning.roadmap_stream_count == 0 - && planning.objective_draft_count == 0 - { - return "Planning substrate is empty; capture or import backlog material before synthesis." - .to_string(); - } - format!( - "Planning material ready: {} captures, {} backlog items, {} roadmap streams, {} objective drafts.", - planning.capture_count, - planning.backlog_item_count, - planning.roadmap_stream_count, - planning.objective_draft_count - ) -} - -fn modeling_role_status( - checkpoint_present: bool, - graph_remap_job: Option<&EpiphanyRoleBoardJob>, -) -> EpiphanyCoordinatorRoleStatus { - if let Some(job) = graph_remap_job - && matches!( - job.status, - EpiphanyRoleBoardJobStatus::Pending | EpiphanyRoleBoardJobStatus::Running - ) - { - return EpiphanyCoordinatorRoleStatus::Running; - } - if checkpoint_present { - EpiphanyCoordinatorRoleStatus::Ready - } else { - EpiphanyCoordinatorRoleStatus::Needed - } -} - -fn render_modeling_role_note( - checkpoint: Option<&EpiphanyRoleBoardCheckpointSummary>, - reorient_next_action: &str, -) -> String { - let Some(checkpoint) = checkpoint else { - return format!("Checkpoint missing: {reorient_next_action}"); - }; - let next_action = checkpoint - .next_action - .as_deref() - .unwrap_or(reorient_next_action); - let disposition = checkpoint.disposition.as_deref().unwrap_or("unknown"); - format!("{disposition}: {next_action}") -} - -fn job_note(job: &EpiphanyRoleBoardJob) -> Option { - job.blocking_reason - .clone() - .or_else(|| job.progress_note.clone()) -} - #[cfg(test)] mod tests { - use super::*; - - fn input() -> EpiphanyRoleBoardInput { - EpiphanyRoleBoardInput { - state_present: true, - planning: EpiphanyRoleBoardPlanningSummary { - capture_count: 0, - backlog_item_count: 0, - roadmap_stream_count: 0, - objective_draft_count: 0, - }, - checkpoint: Some(EpiphanyRoleBoardCheckpointSummary { - disposition: Some("resume_ready".to_string()), - next_action: Some("keep cutting".to_string()), - }), - reorient_next_action: "regather".to_string(), - jobs: Vec::new(), - crrc_action: EpiphanyCrrcAction::Continue, - crrc_recommended_scene_action: Some(EpiphanyCoordinatorSceneAction::Reorient), - crrc_reason: "continue".to_string(), - reorient_decision_action: "Resume".to_string(), - pressure_level: "Low".to_string(), - reorient_result_status: EpiphanyCrrcResultStatus::MissingBinding, - reorient_job: None, - imagination_binding_id: "imagination-synthesis-worker".to_string(), - research_binding_id: "research-source-gather-worker".to_string(), - modeling_binding_id: "modeling-checkpoint-worker".to_string(), - verification_binding_id: "verification-review-worker".to_string(), - reorient_owner_role: "epiphany-reorienter".to_string(), - imagination_owner_role: "epiphany-imagination".to_string(), - research_owner_role: "epiphany-eyes".to_string(), - } - } - #[test] - fn projects_mvp_lanes() { - let roles = derive_role_board(EpiphanyRoleBoardInput { - jobs: vec![EpiphanyRoleBoardJob { - id: "verification".to_string(), - owner_role: "epiphany-verifier".to_string(), - status: EpiphanyRoleBoardJobStatus::Needed, - progress_note: None, - blocking_reason: None, - }], - ..input() - }); - - assert_eq!(roles.len(), 6); - assert_eq!(roles[0].id, EpiphanyCoordinatorRoleId::Implementation); - assert_eq!(roles[0].status, EpiphanyCoordinatorRoleStatus::Ready); - assert_eq!(roles[1].status, EpiphanyCoordinatorRoleStatus::Needed); - assert_eq!(roles[2].status, EpiphanyCoordinatorRoleStatus::Ready); - assert_eq!(roles[3].status, EpiphanyCoordinatorRoleStatus::Ready); - assert_eq!(roles[4].status, EpiphanyCoordinatorRoleStatus::Needed); - assert_eq!(roles[5].status, EpiphanyCoordinatorRoleStatus::Ready); - } - - #[test] - fn blocks_implementation_when_crrc_blocks() { - let roles = derive_role_board(EpiphanyRoleBoardInput { - crrc_action: EpiphanyCrrcAction::LaunchReorientWorker, - crrc_recommended_scene_action: Some(EpiphanyCoordinatorSceneAction::ReorientLaunch), - ..input() - }); - - assert_eq!(roles[0].status, EpiphanyCoordinatorRoleStatus::Blocked); - assert_eq!( - roles[0].recommended_action, - Some(EpiphanyCoordinatorSceneAction::ReorientLaunch) - ); - } - - #[test] - fn reorientation_waits_for_running_worker() { - assert_eq!( - reorientation_role_status( - EpiphanyCrrcAction::Continue, - EpiphanyCrrcResultStatus::Running - ), - EpiphanyCoordinatorRoleStatus::Waiting - ); - } - - #[test] - fn authority_scopes_name_live_typed_capabilities() { - let roles = derive_role_board(input()); - let scopes = roles - .iter() - .flat_map(|role| role.authority_scopes.iter()) - .collect::>(); - assert!(!scopes.is_empty()); - assert!( - scopes - .iter() - .all(|scope| scope.starts_with("epiphany.") && !scope.contains('/')) - ); - for required in [ + fn source_has_no_generic_lane_or_aggregate_authority() { + let source = include_str!("role_board.rs"); + let production = source.split("#[cfg(test)]").next().unwrap_or(source); + for forbidden in [ + "EpiphanyThreadState", + "binding_id", + "acceptance_receipt", + "state_revision", "epiphany.coordinator.role.launch", - "epiphany.coordinator.role.result.read", - "epiphany.coordinator.role.accept", - "epiphany.coordinator.reorient.launch", - "epiphany.coordinator.reorient.result.read", - "epiphany.coordinator.reorient.accept", ] { - assert!(scopes.iter().any(|scope| scope.as_str() == required)); + assert!(!production.contains(forbidden)); } } } diff --git a/epiphany-core/src/surfaces/scene.rs b/epiphany-core/src/surfaces/scene.rs index 043dafe0..40cc4d47 100644 --- a/epiphany-core/src/surfaces/scene.rs +++ b/epiphany-core/src/surfaces/scene.rs @@ -1,6 +1,6 @@ use epiphany_state_model::EpiphanyInvestigationDisposition; use epiphany_state_model::EpiphanyRetrievalStatus; -use epiphany_state_model::EpiphanyThreadState; +use epiphany_state_model::{EpiphanyMemoryProfile, RepoFrontierStatus}; use serde::Deserialize; use serde::Serialize; use std::collections::BTreeMap; @@ -34,11 +34,6 @@ pub enum EpiphanySceneAction { Jobs, Roles, Coordinator, - RoleLaunch, - RoleResult, - RoleAccept, - JobLaunch, - JobInterrupt, Freshness, Pressure, Reorient, @@ -46,9 +41,6 @@ pub enum EpiphanySceneAction { ReorientLaunch, ReorientResult, ReorientAccept, - Propose, - Promote, - Update, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -144,7 +136,7 @@ pub struct EpiphanySceneChurn { pub struct EpiphanyScene { pub state_status: EpiphanySceneStateStatus, pub source: EpiphanySceneSource, - pub revision: Option, + pub projection_digest: Option, pub objective: Option, pub active_subgoal: Option, pub subgoals: Vec, @@ -160,9 +152,9 @@ pub struct EpiphanyScene { #[derive(Debug, Clone, Copy)] pub struct EpiphanySceneInput<'a> { - pub state: Option<&'a EpiphanyThreadState>, + pub mind: Option<&'a crate::EpiphanyMindView>, pub loaded: bool, - pub reorient_binding_id: &'a str, + pub reorientation_work_present: bool, } pub fn derive_scene(input: EpiphanySceneInput<'_>) -> EpiphanyScene { @@ -171,25 +163,19 @@ pub fn derive_scene(input: EpiphanySceneInput<'_>) -> EpiphanyScene { } else { EpiphanySceneSource::Stored }; - let state = input.state; + let mind = input.mind; let available_actions = scene_available_actions( input.loaded, - state.is_some(), - state - .and_then(|state| state.investigation_checkpoint.as_ref()) + mind.is_some(), + mind.and_then(|mind| mind.investigation_checkpoint.as_ref()) .is_some(), - state.is_some_and(|state| { - state - .job_bindings - .iter() - .any(|binding| binding.id == input.reorient_binding_id) - }), + input.reorientation_work_present, ); - let Some(state) = state else { + let Some(mind) = mind else { return EpiphanyScene { state_status: EpiphanySceneStateStatus::Missing, source, - revision: None, + projection_digest: None, objective: None, active_subgoal: None, subgoals: Vec::new(), @@ -204,34 +190,22 @@ pub fn derive_scene(input: EpiphanySceneInput<'_>) -> EpiphanyScene { }; }; - let subgoals = scene_subgoals(state); + let subgoals = scene_subgoals(mind); let active_subgoal = subgoals.iter().find(|subgoal| subgoal.active).cloned(); EpiphanyScene { state_status: EpiphanySceneStateStatus::Ready, source, - revision: Some(state.revision), - objective: state.objective.clone(), + projection_digest: Some(mind.projection_digest.clone()), + objective: mind.objective.clone(), active_subgoal, subgoals, invariant_status_counts: status_counts( - state.invariants.iter().map(|item| item.status.as_str()), + mind.invariants.iter().map(|item| item.status.as_str()), ), - graph: scene_graph(state), - retrieval: state - .retrieval - .as_ref() - .map(|retrieval| EpiphanySceneRetrieval { - workspace_root: retrieval.workspace_root.clone(), - status: retrieval.status, - semantic_available: retrieval.semantic_available, - index_revision: retrieval.index_revision.clone(), - indexed_file_count: retrieval.indexed_file_count, - indexed_chunk_count: retrieval.indexed_chunk_count, - shard_count: retrieval.shards.len() as u32, - dirty_path_count: retrieval.dirty_paths.len() as u32, - }), - investigation_checkpoint: state.investigation_checkpoint.as_ref().map(|checkpoint| { + graph: scene_graph(mind), + retrieval: None, + investigation_checkpoint: mind.investigation_checkpoint.as_ref().map(|checkpoint| { EpiphanySceneInvestigationCheckpoint { checkpoint_id: checkpoint.checkpoint_id.clone(), kind: checkpoint.kind.clone(), @@ -246,8 +220,8 @@ pub fn derive_scene(input: EpiphanySceneInput<'_>) -> EpiphanyScene { } }), observations: EpiphanySceneRecords { - total_count: state.observations.len() as u32, - latest: state + total_count: mind.observations.len() as u32, + latest: mind .observations .iter() .take(EPIPHANY_SCENE_RECORD_LIMIT) @@ -261,9 +235,9 @@ pub fn derive_scene(input: EpiphanySceneInput<'_>) -> EpiphanyScene { .collect(), }, evidence: EpiphanySceneRecords { - total_count: state.recent_evidence.len() as u32, - latest: state - .recent_evidence + total_count: mind.evidence.len() as u32, + latest: mind + .evidence .iter() .take(EPIPHANY_SCENE_RECORD_LIMIT) .map(|evidence| EpiphanySceneRecord { @@ -275,12 +249,7 @@ pub fn derive_scene(input: EpiphanySceneInput<'_>) -> EpiphanyScene { }) .collect(), }, - churn: state.churn.as_ref().map(|churn| EpiphanySceneChurn { - understanding_status: churn.understanding_status.clone(), - diff_pressure: churn.diff_pressure.clone(), - warning: churn.warning.clone(), - unexplained_writes: churn.unexplained_writes, - }), + churn: None, available_actions, } } @@ -305,10 +274,6 @@ fn scene_available_actions( EpiphanySceneAction::Jobs, EpiphanySceneAction::Roles, EpiphanySceneAction::Coordinator, - EpiphanySceneAction::RoleLaunch, - EpiphanySceneAction::RoleResult, - EpiphanySceneAction::RoleAccept, - EpiphanySceneAction::JobLaunch, EpiphanySceneAction::Freshness, EpiphanySceneAction::Pressure, EpiphanySceneAction::Reorient, @@ -321,19 +286,13 @@ fn scene_available_actions( actions.push(EpiphanySceneAction::ReorientResult); actions.push(EpiphanySceneAction::ReorientAccept); } - actions.push(EpiphanySceneAction::Update); - if state_present { - actions.push(EpiphanySceneAction::JobInterrupt); - actions.push(EpiphanySceneAction::Propose); - actions.push(EpiphanySceneAction::Promote); - } + let _ = state_present; actions } -fn scene_subgoals(state: &EpiphanyThreadState) -> Vec { - let active_id = state.active_subgoal_id.as_deref(); - state - .subgoals +fn scene_subgoals(mind: &crate::EpiphanyMindView) -> Vec { + let active_id = mind.active_subgoal_id.as_deref(); + mind.subgoals .iter() .map(|subgoal| EpiphanySceneSubgoal { id: subgoal.id.clone(), @@ -345,32 +304,63 @@ fn scene_subgoals(state: &EpiphanyThreadState) -> Vec { .collect() } -fn scene_graph(state: &EpiphanyThreadState) -> EpiphanySceneGraph { - let frontier = state.graph_frontier.as_ref(); - let checkpoint = state.graph_checkpoint.as_ref(); +fn scene_graph(mind: &crate::EpiphanyMindView) -> EpiphanySceneGraph { + let Some(model) = mind.repo_model.as_ref() else { + return EpiphanySceneGraph::default(); + }; + let active = model + .frontier + .iter() + .filter(|item| { + matches!( + item.status, + RepoFrontierStatus::Proposed + | RepoFrontierStatus::Active + | RepoFrontierStatus::Blocked + ) + }) + .collect::>(); EpiphanySceneGraph { - architecture_node_count: state.graphs.architecture.nodes.len() as u32, - architecture_edge_count: state.graphs.architecture.edges.len() as u32, - dataflow_node_count: state.graphs.dataflow.nodes.len() as u32, - dataflow_edge_count: state.graphs.dataflow.edges.len() as u32, - link_count: state.graphs.links.len() as u32, - active_node_ids: frontier - .map(|frontier| frontier.active_node_ids.clone()) - .unwrap_or_default(), - active_edge_ids: frontier - .map(|frontier| frontier.active_edge_ids.clone()) - .unwrap_or_default(), - open_question_count: frontier - .map(|frontier| frontier.open_question_ids.len() as u32) - .unwrap_or_default(), - open_gap_count: frontier - .map(|frontier| frontier.open_gap_ids.len() as u32) - .unwrap_or_default(), - dirty_paths: frontier - .map(|frontier| frontier.dirty_paths.clone()) - .unwrap_or_default(), - checkpoint_id: checkpoint.map(|checkpoint| checkpoint.checkpoint_id.clone()), - checkpoint_summary: checkpoint.and_then(|checkpoint| checkpoint.summary.clone()), + architecture_node_count: model + .nodes + .iter() + .filter(|node| node.profile == EpiphanyMemoryProfile::RepoArchitecture) + .count() as u32, + architecture_edge_count: model + .edges + .iter() + .filter(|edge| edge.profile == EpiphanyMemoryProfile::RepoArchitecture) + .count() as u32, + dataflow_node_count: model + .nodes + .iter() + .filter(|node| node.profile == EpiphanyMemoryProfile::RepoDataflow) + .count() as u32, + dataflow_edge_count: model + .edges + .iter() + .filter(|edge| edge.profile == EpiphanyMemoryProfile::RepoDataflow) + .count() as u32, + link_count: model.edges.len() as u32, + active_node_ids: active + .iter() + .flat_map(|item| item.target_claim_ids.iter().cloned()) + .collect(), + active_edge_ids: Vec::new(), + open_question_count: active.len() as u32, + open_gap_count: active + .iter() + .filter(|item| item.status == RepoFrontierStatus::Blocked) + .count() as u32, + dirty_paths: Vec::new(), + checkpoint_id: mind + .investigation_checkpoint + .as_ref() + .map(|checkpoint| checkpoint.checkpoint_id.clone()), + checkpoint_summary: mind + .investigation_checkpoint + .as_ref() + .and_then(|checkpoint| checkpoint.summary.clone()), } } @@ -389,16 +379,15 @@ fn status_counts<'a>(statuses: impl Iterator) -> Vec