diff --git a/.gitignore b/.gitignore index da5c44da..f2d5ef65 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,7 @@ epiphany-openai-codex-spine/target/ epiphany-openai-codex-spine/Cargo.lock epiphany-openai-runtime/target/ epiphany-openai-runtime/Cargo.lock +epiphany-codex-bridge/Cargo.lock apps/epiphany-gui/node_modules/ apps/epiphany-gui/dist/ apps/epiphany-gui/src-tauri/gen/ @@ -21,5 +22,7 @@ apps/epiphany-gui/src-tauri/target/ .epiphany-run/ .voidbot/ state/agent-heartbeats.json +state/runtime-spine.msgpack +state/thread-state.msgpack state/*.msgpack.lock state/*.projection.json diff --git a/epiphany-codex-bridge/src/runtime_results.rs b/epiphany-codex-bridge/src/runtime_results.rs index 956e040e..a8ddd1ff 100644 --- a/epiphany-codex-bridge/src/runtime_results.rs +++ b/epiphany-codex-bridge/src/runtime_results.rs @@ -5,6 +5,7 @@ use epiphany_core::EpiphanyCrrcResultStatus as CoreEpiphanyCrrcResultStatus; use epiphany_core::EpiphanyReorientFindingInterpretation; use epiphany_core::EpiphanyRoleFindingInterpretation; use epiphany_core::EpiphanyRoleResultRoleId; +use epiphany_core::EpiphanyRuntimeJobResult; use epiphany_core::EpiphanyRuntimeJobSnapshot; use epiphany_core::EpiphanyRuntimeJobStatus; use epiphany_core::MIND_GATEWAY_REVIEW_TYPE; @@ -73,34 +74,43 @@ pub fn load_core_epiphany_role_result_from_runtime_spine_job( } }; let status = map_runtime_role_result_status(&snapshot); - let finding = if status == CoreEpiphanyCoordinatorRoleResultStatus::Completed { - match runtime_role_worker_result(runtime_store_path, job_id) { - Ok(Some(result)) => Some(interpret_runtime_role_worker_result(role_id, &result)), - Ok(None) => { - return EpiphanyRoleResultSnapshot { - status: CoreEpiphanyCoordinatorRoleResultStatus::BackendUnavailable, - finding: None, - note: format!( - "Heartbeat runtime job {:?} completed without an EpiphanyRuntimeRoleWorkerResult typed document; generic lifecycle receipts are not reviewable findings.", - job_id - ), - }; - } - Err(err) => { - return EpiphanyRoleResultSnapshot { - status: CoreEpiphanyCoordinatorRoleResultStatus::BackendUnavailable, - finding: None, - note: format!( - "Failed to read typed role worker result for heartbeat runtime job {:?}: {err}", - job_id - ), - }; + let finding = match status { + CoreEpiphanyCoordinatorRoleResultStatus::Completed => { + match runtime_role_worker_result(runtime_store_path, job_id) { + Ok(Some(result)) => Some(interpret_runtime_role_worker_result(role_id, &result)), + Ok(None) => { + return EpiphanyRoleResultSnapshot { + status: CoreEpiphanyCoordinatorRoleResultStatus::BackendUnavailable, + finding: None, + note: format!( + "Heartbeat runtime job {:?} completed without an EpiphanyRuntimeRoleWorkerResult typed document; generic lifecycle receipts are not reviewable findings.", + job_id + ), + }; + } + Err(err) => { + return EpiphanyRoleResultSnapshot { + status: CoreEpiphanyCoordinatorRoleResultStatus::BackendUnavailable, + finding: None, + note: format!( + "Failed to read typed role worker result for heartbeat runtime job {:?}: {err}", + job_id + ), + }; + } } } - } else { - None + CoreEpiphanyCoordinatorRoleResultStatus::Failed + | CoreEpiphanyCoordinatorRoleResultStatus::Cancelled => snapshot + .result + .as_ref() + .map(interpret_runtime_role_lifecycle_failure), + _ => None, }; - let note = render_core_role_result_note(role_id, status, finding.as_ref(), None); + let item_error = finding + .as_ref() + .and_then(|finding| finding.job_error.as_deref()); + let note = render_core_role_result_note(role_id, status, finding.as_ref(), item_error); EpiphanyRoleResultSnapshot { status, finding, @@ -144,34 +154,42 @@ pub fn load_core_epiphany_reorient_result_from_runtime_spine_job( } }; let status = map_runtime_reorient_result_status(&snapshot); - let finding = if status == CoreEpiphanyCrrcResultStatus::Completed { - match runtime_reorient_worker_result(runtime_store_path, job_id) { - Ok(Some(result)) => Some(interpret_runtime_reorient_worker_result(&result)), - Ok(None) => { - return EpiphanyReorientResultSnapshot { - status: CoreEpiphanyCrrcResultStatus::BackendUnavailable, - finding: None, - note: format!( - "Heartbeat runtime job {:?} completed without an EpiphanyRuntimeReorientWorkerResult typed document; generic lifecycle receipts are not reviewable findings.", - job_id - ), - }; - } - Err(err) => { - return EpiphanyReorientResultSnapshot { - status: CoreEpiphanyCrrcResultStatus::BackendUnavailable, - finding: None, - note: format!( - "Failed to read typed reorientation worker result for heartbeat runtime job {:?}: {err}", - job_id - ), - }; + let finding = match status { + CoreEpiphanyCrrcResultStatus::Completed => { + match runtime_reorient_worker_result(runtime_store_path, job_id) { + Ok(Some(result)) => Some(interpret_runtime_reorient_worker_result(&result)), + Ok(None) => { + return EpiphanyReorientResultSnapshot { + status: CoreEpiphanyCrrcResultStatus::BackendUnavailable, + finding: None, + note: format!( + "Heartbeat runtime job {:?} completed without an EpiphanyRuntimeReorientWorkerResult typed document; generic lifecycle receipts are not reviewable findings.", + job_id + ), + }; + } + Err(err) => { + return EpiphanyReorientResultSnapshot { + status: CoreEpiphanyCrrcResultStatus::BackendUnavailable, + finding: None, + note: format!( + "Failed to read typed reorientation worker result for heartbeat runtime job {:?}: {err}", + job_id + ), + }; + } } } - } else { - None + CoreEpiphanyCrrcResultStatus::Failed | CoreEpiphanyCrrcResultStatus::Cancelled => snapshot + .result + .as_ref() + .map(interpret_runtime_reorient_lifecycle_failure), + _ => None, }; - let note = render_core_reorient_result_note(status, finding.as_ref(), None); + let item_error = finding + .as_ref() + .and_then(|finding| finding.job_error.as_deref()); + let note = render_core_reorient_result_note(status, finding.as_ref(), item_error); EpiphanyReorientResultSnapshot { status, finding, @@ -179,6 +197,55 @@ pub fn load_core_epiphany_reorient_result_from_runtime_spine_job( } } +fn interpret_runtime_role_lifecycle_failure( + result: &EpiphanyRuntimeJobResult, +) -> EpiphanyRoleFindingInterpretation { + EpiphanyRoleFindingInterpretation { + verdict: Some(result.verdict.clone()), + summary: Some(result.summary.clone()), + next_safe_move: empty_string_as_none(&result.next_safe_move), + checkpoint_summary: None, + scratch_summary: None, + files_inspected: Vec::new(), + frontier_node_ids: Vec::new(), + evidence_ids: result.evidence_refs.clone(), + artifact_refs: result.artifact_refs.clone(), + runtime_result_id: Some(result.result_id.clone()), + runtime_job_id: Some(result.job_id.clone()), + open_questions: Vec::new(), + evidence_gaps: Vec::new(), + risks: Vec::new(), + state_patch: None, + self_patch: None, + self_persistence: None, + job_error: Some(result.summary.clone()), + item_error: None, + } +} + +fn interpret_runtime_reorient_lifecycle_failure( + result: &EpiphanyRuntimeJobResult, +) -> EpiphanyReorientFindingInterpretation { + EpiphanyReorientFindingInterpretation { + mode: None, + summary: Some(result.summary.clone()), + next_safe_move: empty_string_as_none(&result.next_safe_move), + checkpoint_still_valid: None, + files_inspected: Vec::new(), + frontier_node_ids: Vec::new(), + evidence_ids: result.evidence_refs.clone(), + artifact_refs: result.artifact_refs.clone(), + runtime_result_id: Some(result.result_id.clone()), + runtime_job_id: Some(result.job_id.clone()), + job_error: Some(result.summary.clone()), + item_error: None, + } +} + +fn empty_string_as_none(value: &str) -> Option { + (!value.trim().is_empty()).then(|| value.to_string()) +} + fn map_runtime_role_result_status( snapshot: &EpiphanyRuntimeJobSnapshot, ) -> CoreEpiphanyCoordinatorRoleResultStatus { @@ -473,7 +540,7 @@ mod tests { #[test] fn role_result_requires_typed_worker_document() { let store = temp_store_path(); - seed_completed_lifecycle_result(&store, "role-job", "modeling"); + seed_lifecycle_result(&store, "role-job", "modeling", "completed"); let result = load_core_epiphany_role_result_from_runtime_spine_job( "role-job", @@ -498,7 +565,7 @@ mod tests { #[test] fn reorient_result_requires_typed_worker_document() { let store = temp_store_path(); - seed_completed_lifecycle_result(&store, "reorient-job", "reorientation"); + seed_lifecycle_result(&store, "reorient-job", "reorientation", "completed"); let result = load_core_epiphany_reorient_result_from_runtime_spine_job( "reorient-job", @@ -519,6 +586,59 @@ mod tests { let _ = fs::remove_file(store); } + #[test] + fn role_result_projects_failed_lifecycle_receipt_as_terminal() { + let store = temp_store_path(); + seed_lifecycle_result(&store, "role-job", "modeling", "failed"); + + let result = load_core_epiphany_role_result_from_runtime_spine_job( + "role-job", + Some(store.as_path()), + EpiphanyRoleResultRoleId::Modeling, + ); + + assert_eq!( + result.status, + CoreEpiphanyCoordinatorRoleResultStatus::Failed + ); + let finding = result.finding.expect("failed receipt should be visible"); + assert_eq!(finding.verdict.as_deref(), Some("failed")); + assert_eq!(finding.runtime_job_id.as_deref(), Some("role-job")); + assert!( + finding + .job_error + .as_deref() + .is_some_and(|error| error.contains("generic lifecycle result")) + ); + assert!(result.note.contains("failed")); + + let _ = fs::remove_file(store); + } + + #[test] + fn reorient_result_projects_failed_lifecycle_receipt_as_terminal() { + let store = temp_store_path(); + seed_lifecycle_result(&store, "reorient-job", "reorientation", "failed"); + + let result = load_core_epiphany_reorient_result_from_runtime_spine_job( + "reorient-job", + Some(store.as_path()), + ); + + assert_eq!(result.status, CoreEpiphanyCrrcResultStatus::Failed); + let finding = result.finding.expect("failed receipt should be visible"); + assert_eq!(finding.runtime_job_id.as_deref(), Some("reorient-job")); + assert!( + finding + .job_error + .as_deref() + .is_some_and(|error| error.contains("generic lifecycle result")) + ); + assert!(result.note.contains("failed")); + + let _ = fs::remove_file(store); + } + fn temp_store_path() -> PathBuf { std::env::temp_dir().join(format!( "epiphany-runtime-results-{}.msgpack", @@ -526,7 +646,7 @@ mod tests { )) } - fn seed_completed_lifecycle_result(store: &Path, job_id: &str, role: &str) { + fn seed_lifecycle_result(store: &Path, job_id: &str, role: &str, verdict: &str) { initialize_runtime_spine( store, RuntimeSpineInitOptions { @@ -564,7 +684,7 @@ mod tests { result_id: format!("result-{job_id}"), job_id: job_id.to_string(), completed_at: NOW.to_string(), - verdict: "completed".to_string(), + verdict: verdict.to_string(), summary: "generic lifecycle result".to_string(), next_safe_move: "do not review generic lifecycle receipts".to_string(), evidence_refs: Vec::new(), diff --git a/epiphany-core/src/bin/epiphany-mvp-status.rs b/epiphany-core/src/bin/epiphany-mvp-status.rs index 74c2a2f5..45d9bb9b 100644 --- a/epiphany-core/src/bin/epiphany-mvp-status.rs +++ b/epiphany-core/src/bin/epiphany-mvp-status.rs @@ -7,6 +7,7 @@ use epiphany_core::EpiphanyCrrcInput; use epiphany_core::EpiphanyCrrcReorientAction; use epiphany_core::EpiphanyCrrcResultStatus; use epiphany_core::EpiphanyCrrcStateStatus; +use epiphany_core::EpiphanyJobStatus; use epiphany_core::EpiphanyJobsInput; use epiphany_core::EpiphanyReorientAction; use epiphany_core::EpiphanyReorientFreshnessStatus; @@ -17,6 +18,8 @@ use epiphany_core::EpiphanyRoleBoardInput; use epiphany_core::EpiphanyRoleBoardJob; use epiphany_core::EpiphanyRoleBoardJobStatus; use epiphany_core::EpiphanyRoleBoardPlanningSummary; +use epiphany_core::EpiphanyRuntimeJobSnapshot; +use epiphany_core::EpiphanyRuntimeJobStatus; use epiphany_core::EpiphanySceneInput; use epiphany_core::EpiphanyTokenUsageSnapshot; use epiphany_core::derive_coordinator_finding_signals; @@ -29,6 +32,8 @@ use epiphany_core::derive_scene; use epiphany_core::load_thread_state_entry; use epiphany_core::recommend_crrc_action; use epiphany_core::recommend_reorientation; +use epiphany_core::runtime_job_snapshot; +use epiphany_state_model::EpiphanyThreadState; use serde_json::Value; use serde_json::json; use std::env; @@ -230,10 +235,11 @@ fn run_native_status(args: &Args) -> Result { watched_root: Some(cwd.clone()), }); let planning = derive_planning_view(state_ref); - let jobs = derive_jobs(EpiphanyJobsInput { + 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 { @@ -243,7 +249,12 @@ fn run_native_status(args: &Args) -> Result { EpiphanyReorientAction::Resume => EpiphanyCrrcReorientAction::Resume, EpiphanyReorientAction::Regather => EpiphanyCrrcReorientAction::Regather, }; - let result_status = EpiphanyCrrcResultStatus::BackendMissing; + let result_status = + native_reorient_result_status(state_ref, &runtime_store_path, REORIENT_BINDING_ID); + let modeling_result_status = + native_role_result_status(state_ref, &runtime_store_path, MODELING_BINDING_ID); + let verification_result_status = + native_role_result_status(state_ref, &runtime_store_path, VERIFICATION_BINDING_ID); let recommendation = recommend_crrc_action(EpiphanyCrrcInput { loaded, state_status, @@ -312,8 +323,8 @@ fn run_native_status(args: &Args) -> Result { recommendation: recommendation.clone(), roles: roles.clone(), reorient_action: reorient_decision.action, - modeling_result_status: EpiphanyCoordinatorRoleResultStatus::BackendMissing, - verification_result_status: EpiphanyCoordinatorRoleResultStatus::BackendMissing, + modeling_result_status, + verification_result_status, reorient_result_status: result_status, modeling_result_accepted: finding_signals.modeling_result_accepted, modeling_result_reviewable: finding_signals.modeling_result_reviewable, @@ -397,16 +408,11 @@ fn run_native_status(args: &Args) -> Result { }, "planning": planning, "roleResults": { - "imagination": native_role_result(IMAGINATION_BINDING_ID), - "modeling": native_role_result(MODELING_BINDING_ID), - "verification": native_role_result(VERIFICATION_BINDING_ID), - }, - "reorientResult": { - "source": "native", - "status": "backendMissing", - "bindingId": REORIENT_BINDING_ID, - "note": "Native status is provider-neutral and does not query model-worker runtime results yet.", + "imagination": native_role_result(state_ref, &runtime_store_path, IMAGINATION_BINDING_ID), + "modeling": native_role_result(state_ref, &runtime_store_path, MODELING_BINDING_ID), + "verification": native_role_result(state_ref, &runtime_store_path, VERIFICATION_BINDING_ID), }, + "reorientResult": native_reorient_result(state_ref, &runtime_store_path, REORIENT_BINDING_ID), "crrc": { "threadId": thread_id, "source": "native", @@ -589,13 +595,313 @@ fn native_auxiliary_status(root: &Path) -> Result { }) } -fn native_role_result(binding_id: &str) -> Value { - json!({ - "source": "native", - "status": "backendMissing", - "bindingId": binding_id, - "note": "Native status is provider-neutral and does not query model-worker runtime results yet.", - }) +fn native_role_result( + state: Option<&EpiphanyThreadState>, + runtime_store: &Path, + binding_id: &str, +) -> 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.", + }); + }; + match runtime_job_snapshot(runtime_store, job_id) { + Ok(Some(snapshot)) => { + let status = map_runtime_role_result_status(&snapshot); + let mut result = json!({ + "source": "native", + "status": status, + "bindingId": binding_id, + "runtimeJobId": job_id, + "note": native_role_result_note(status, &snapshot), + }); + if matches!( + status, + EpiphanyCoordinatorRoleResultStatus::Failed + | EpiphanyCoordinatorRoleResultStatus::Cancelled + ) && let Some(receipt) = snapshot.result + { + result["finding"] = json!({ + "verdict": receipt.verdict, + "summary": receipt.summary, + "nextSafeMove": empty_string_as_null(&receipt.next_safe_move), + "runtimeResultId": receipt.result_id, + "runtimeJobId": receipt.job_id, + "evidenceIds": receipt.evidence_refs, + "artifactRefs": receipt.artifact_refs, + "jobError": receipt.summary, + }); + } + result + } + Ok(None) => json!({ + "source": "native", + "status": "backendMissing", + "bindingId": binding_id, + "runtimeJobId": job_id, + "note": "The linked runtime-spine job is missing.", + }), + Err(error) => json!({ + "source": "native", + "status": "backendUnavailable", + "bindingId": binding_id, + "runtimeJobId": job_id, + "note": format!("Failed to read linked runtime-spine job: {error}"), + }), + } +} + +fn native_reorient_result( + state: Option<&EpiphanyThreadState>, + runtime_store: &Path, + binding_id: &str, +) -> 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 reorientation binding.", + }); + }; + match runtime_job_snapshot(runtime_store, job_id) { + Ok(Some(snapshot)) => { + let status = map_runtime_reorient_result_status(&snapshot); + let mut result = json!({ + "source": "native", + "status": status, + "bindingId": binding_id, + "runtimeJobId": job_id, + "note": native_reorient_result_note(status, &snapshot), + }); + if matches!( + status, + EpiphanyCrrcResultStatus::Failed | EpiphanyCrrcResultStatus::Cancelled + ) && let Some(receipt) = snapshot.result + { + result["finding"] = json!({ + "summary": receipt.summary, + "nextSafeMove": empty_string_as_null(&receipt.next_safe_move), + "runtimeResultId": receipt.result_id, + "runtimeJobId": receipt.job_id, + "evidenceIds": receipt.evidence_refs, + "artifactRefs": receipt.artifact_refs, + "jobError": receipt.summary, + }); + } + result + } + Ok(None) => json!({ + "source": "native", + "status": "backendMissing", + "bindingId": binding_id, + "runtimeJobId": job_id, + "note": "The linked runtime-spine job is missing.", + }), + Err(error) => json!({ + "source": "native", + "status": "backendUnavailable", + "bindingId": binding_id, + "runtimeJobId": job_id, + "note": format!("Failed to read linked runtime-spine job: {error}"), + }), + } +} + +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_reorient_result_status( + state: Option<&EpiphanyThreadState>, + runtime_store: &Path, + binding_id: &str, +) -> EpiphanyCrrcResultStatus { + let Some(job_id) = latest_runtime_job_id_for_binding(state, binding_id) else { + return EpiphanyCrrcResultStatus::BackendMissing; + }; + match runtime_job_snapshot(runtime_store, job_id) { + Ok(Some(snapshot)) => map_runtime_reorient_result_status(&snapshot), + Ok(None) => EpiphanyCrrcResultStatus::BackendMissing, + Err(_) => EpiphanyCrrcResultStatus::BackendUnavailable, + } +} + +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 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_role_result_note( + status: EpiphanyCoordinatorRoleResultStatus, + snapshot: &EpiphanyRuntimeJobSnapshot, +) -> String { + match status { + EpiphanyCoordinatorRoleResultStatus::Failed => { + format!("Role runtime job failed: {}", snapshot.job.summary) + } + EpiphanyCoordinatorRoleResultStatus::Cancelled => { + format!("Role runtime job was cancelled: {}", snapshot.job.summary) + } + EpiphanyCoordinatorRoleResultStatus::Completed => { + "Role runtime job has a terminal lifecycle receipt; use typed worker results for reviewable findings.".to_string() + } + EpiphanyCoordinatorRoleResultStatus::Running => { + "Role runtime job is still running.".to_string() + } + EpiphanyCoordinatorRoleResultStatus::Pending => { + "Role runtime job has not produced a terminal receipt yet.".to_string() + } + EpiphanyCoordinatorRoleResultStatus::BackendUnavailable => { + "The bound runtime backend is unavailable.".to_string() + } + EpiphanyCoordinatorRoleResultStatus::BackendMissing => { + "The bound runtime backend job or item is missing.".to_string() + } + EpiphanyCoordinatorRoleResultStatus::MissingState => { + "No authoritative Epiphany state exists for this thread.".to_string() + } + EpiphanyCoordinatorRoleResultStatus::MissingBinding => { + "No matching Epiphany role specialist binding exists.".to_string() + } + } +} + +fn native_reorient_result_note( + status: EpiphanyCrrcResultStatus, + snapshot: &EpiphanyRuntimeJobSnapshot, +) -> String { + match status { + EpiphanyCrrcResultStatus::Failed => { + format!("Reorientation runtime job failed: {}", snapshot.job.summary) + } + EpiphanyCrrcResultStatus::Cancelled => { + format!("Reorientation runtime job was cancelled: {}", snapshot.job.summary) + } + EpiphanyCrrcResultStatus::Completed => { + "Reorientation runtime job has a terminal lifecycle receipt; use typed worker results for reviewable findings.".to_string() + } + EpiphanyCrrcResultStatus::Running => { + "Reorientation runtime job is still running.".to_string() + } + EpiphanyCrrcResultStatus::Pending => { + "Reorientation runtime job has not produced a terminal receipt yet.".to_string() + } + EpiphanyCrrcResultStatus::BackendUnavailable => { + "The bound runtime backend is unavailable.".to_string() + } + EpiphanyCrrcResultStatus::BackendMissing => { + "The bound runtime backend job or item is missing.".to_string() + } + EpiphanyCrrcResultStatus::MissingState => { + "No authoritative Epiphany state exists for this thread.".to_string() + } + EpiphanyCrrcResultStatus::MissingBinding => { + "No matching Epiphany reorientation binding exists.".to_string() + } + } +} + +fn empty_string_as_null(value: &str) -> Value { + if value.trim().is_empty() { + Value::Null + } else { + json!(value) + } } fn native_tool_invocation_surface(runtime_store: &Path) -> Result { diff --git a/epiphany-openai-runtime/src/bin/epiphany-openai-runtime.rs b/epiphany-openai-runtime/src/bin/epiphany-openai-runtime.rs index 56f3ad34..38faa65f 100644 --- a/epiphany-openai-runtime/src/bin/epiphany-openai-runtime.rs +++ b/epiphany-openai-runtime/src/bin/epiphany-openai-runtime.rs @@ -1,7 +1,13 @@ use std::env; use std::fs; use std::path::PathBuf; +use std::process; use std::process::Command; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; +use std::thread; +use std::time::Duration; use anyhow::Context; use anyhow::Result; @@ -74,12 +80,13 @@ async fn main() -> Result<()> { "run-worker" => { let options = parse_run_worker_options(args.collect())?; require_supported_provider(&options.provider)?; + let timeout_guard = start_run_worker_timeout_watchdog(&options); let timeout_seconds = options.max_runtime_seconds; let timeout_store = options.store_path.clone(); let timeout_job_id = options.job_id.clone(); let summary = if let Some(seconds) = timeout_seconds { match tokio::time::timeout( - std::time::Duration::from_secs(seconds), + Duration::from_secs(seconds), run_worker_options(options), ) .await @@ -107,6 +114,7 @@ async fn main() -> Result<()> { } else { run_worker_options(options).await? }; + timeout_guard.store(true, Ordering::SeqCst); print_json(&summary)?; } "tool-followup" => { @@ -464,6 +472,31 @@ fn default_worker_model() -> String { .unwrap_or_else(|_| "gpt-5.4".to_string()) } +fn start_run_worker_timeout_watchdog(options: &RunWorkerCliOptions) -> Arc { + let completed = Arc::new(AtomicBool::new(false)); + let Some(seconds) = options.max_runtime_seconds else { + return completed; + }; + let completed_for_thread = Arc::clone(&completed); + let store_path = options.store_path.clone(); + let job_id = options.job_id.clone(); + thread::spawn(move || { + thread::sleep(Duration::from_secs(seconds)); + if completed_for_thread.load(Ordering::SeqCst) { + return; + } + let summary = format!("Worker runtime timed out after {seconds} seconds."); + let _ = fail_worker_job( + &store_path, + &job_id, + summary, + "Inspect provider/tool transport before relaunching the worker.".to_string(), + ); + process::exit(124); + }); + completed +} + async fn run_worker_launch_with_tool_continuation( options: RunWorkerCliOptions, ) -> Result { diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 99cd8b10..fd3e506e 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -34,9 +34,10 @@ remembers doctrine; the branch remembers the blade. - Do not copy exact branch or HEAD from this note. Run `git status --short --branch` and `git log --oneline -5`. - The repo now has a one-command local operator path: `.\tools\epiphany_local_run.ps1`. Default mode is `smoke`; it builds the retained Codex app-server compatibility edge, builds native Epiphany operator binaries, runs the coordinator smoke, and writes launcher artifacts under `.epiphany-run/` plus coordinator artifacts under `.epiphany-dogfood/`. `-Mode status` is now Epiphany-native: it builds only Epiphany operator binaries, reads `state/thread-state.msgpack` when present, derives status through `epiphany-core`, and does not start or require `codex-app-server`. Use `-Mode plan` or `-Mode run -MaxSteps 4` for the raw bridge-equipped coordinator entrypoints; use `-Mode mvp -FaceInput "" -MaxSteps 4` for the local product cycle that projects Face's character turn, writes a Face/Aquarium bubble, bootstraps a minimal local checkpoint for fresh threads, runs the coordinator with auto-tools, then runs heartbeat sleep/dream maintenance. Live plan/run/mvp modes use the workspace `state/runtime-spine.msgpack`, because CodexThread launch writes worker requests there; the run bundle remains artifact evidence, not runtime lifecycle authority. Add `-ThreadId ` and `-Workspace ` to inspect or continue an existing thread. `status`, `plan`, and `smoke` do not spend model calls; `run` and `mvp` build and use `epiphany-openai-runtime`. Coordinator workers now launch detached and are polled through runtime-spine instead of blocking the coordinator. MVP runs are non-ephemeral by default so `-ThreadId ` can resume and poll later. `-MaxRuntimeSeconds ` is passed into worker runtime; timeout writes a failed worker receipt and exits. Failed modeling now blocks downstream verification until the failed result is reviewed. +- Current Mom-ready blocker: the normal 180-second MVP pass reaches Face -> coordinator -> detached runtime -> heartbeat sleep, but the modeling worker produces no typed result, no tool intents, and empty stdout/stderr before the runtime watchdog writes `Worker runtime timed out after 180 seconds.` Native status correctly projects that failure through role result, jobs, roles, and coordinator source signals. Next cut should diagnose provider stream/request observability or prompt/request size in `epiphany-model-runtime run-worker --provider openai-codex`, not coordinator scheduling. - Local operator runs now write typed CultMesh intent/receipt documents to `.epiphany-run/cultmesh/operator-runs.ccmp` through `epiphany-operator-run`. The wrapper writes intent before acting and a completion receipt after success; this is the local consent/trace rail, not a hidden scheduler queue. - Status-mode local runs now also write a native CultMesh operator snapshot to `.epiphany-run/cultmesh/operator-snapshots.ccmp` through `epiphany-operator-snapshot`. That snapshot distills the operator-safe MVP status artifact into typed fields such as thread id, state status, coordinator action, CRRC action, reorient action, available actions, and artifact refs; it does not preserve the raw JSON status blob as internal state. -- `epiphany-mvp-status --source native` is the current provider-neutral status boundary. It projects scene, pressure, jobs, roles, planning, reorient, CRRC, and coordinator status from native core surfaces and returns provider/runtime worker results as `backendMissing` placeholders instead of asking Codex for model-worker state. Keep future pluggable model-provider work behind launch/result/runtime documents; do not let provider choice leak into status, prompt authority, scheduler policy, or durable `EpiphanyThreadState`. +- `epiphany-mvp-status --source native` is the current provider-neutral status boundary. It projects scene, pressure, jobs, roles, planning, reorient, CRRC, coordinator status, and runtime-linked worker lifecycle from native core surfaces. It reads runtime-spine job/result receipts for linked jobs so failed workers show as failed in role results, jobs, roles, and coordinator source signals, while successful semantic findings still require typed role/reorient worker result documents. Keep future pluggable model-provider work behind launch/result/runtime documents; do not let provider choice leak into status, prompt authority, scheduler policy, or durable `EpiphanyThreadState`. - `epiphany-model-runtime` is the current provider-neutral executable boundary. It is built by the `epiphany-openai-runtime` crate for now and accepts `--provider openai-codex`; the old `epiphany-openai-runtime` binary, `--openai-runtime-bin`, and `openai-runtime` executor name survive only as compatibility aliases. Coordinator run mode, local wrapper run mode, and repo birth runner should call `--model-runtime-bin` plus `--model-provider`. The runtime default model is `gpt-5.4`, with `EPIPHANY_MODEL` / `CODEX_MODEL` as overrides; `gpt-5.5` was rejected by this Codex-compatible transport as requiring a newer Codex. The typed request/event/receipt contract is now provider-neutral in `epiphany-model-adapter` as `epiphany.model_request.v0`, `epiphany.model_stream_event.v0`, `epiphany.model_receipt.v0`, and `epiphany.model_adapter_status.v0`; OpenAI/Codex documents are adapter evidence behind that boundary, not scheduler/status/state authority. - Epiphany prompt authority is now explicitly Codex-free. Bundled specialist prompts live in `epiphany-codex-bridge/src/prompts/epiphany_specialists.toml`, the app-server boundary has a regression test that fails if any bundled Epiphany agent prompt contains `Codex`, and `epiphany-repo-birth-runner` no longer accepts `codex-exec` or `--codex-bin`. Use `epiphany-model-runtime` for startup-only birth specialists so Codex cannot wrap Epiphany agents in its own prompt machinery. - Coordinator plan/run passes now emit `epiphany.coordinator_run_receipt.v0` into runtime-spine. `coordinator-summary.json` and `coordinator-steps.jsonl` remain useful operator artifacts, but the durable receipt of what the coordinator decided is typed CultCache/CultNet state. diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index a39d590e..05aaab1b 100644 Binary files a/state/ledgers.msgpack and b/state/ledgers.msgpack differ diff --git a/state/map.yaml b/state/map.yaml index d5083b09..38818023 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -72,7 +72,7 @@ active_subgoals: - Use `notes/epiphany-cultmesh-dreaming-roadmap.md` as the design authority for distributed Epiphany dreaming. Public dreams are separately authored typed documents distributed through CultMesh/CultNet; private state remains local and cannot be shared by flipping a visibility flag. Foreign dreams are external thought weather until a reviewed local adoption receipt digests them into memory, planning, doctrine, or governance. - CultMesh is now the preferred ergonomic Rust abstraction over CultCache and CultNet for Epiphany-owned local database surfaces. The Rust substrate is repo-contained under `vendor/cultcache-rs`, `vendor/cultnet-rs`, and `vendor/cultmesh-rs`; the old `E:\Projects\CultLib\crates\*` path is dead in this checkout and must not be reintroduced as a compile-time dependency. Future local Verse/dream/status work should start at CultMesh unless it is explicitly polishing CultMesh internals. Preserve the three-Verse boundary: `epiphany-internal` for private sub-agent typed state, `gamecult-local` for trusted LAN/Yggdrasil-tunnel GameCult project sharing, and `epiphany-global` for untrusted public dreams plus topic-specific threaded public rooms for Face posts. - The active priority is Codex starvation and CultNet liberation. Use `notes/codex-starvation-and-cultnet-liberation-plan.md` as the directive and `notes/codex-auth-spine-inventory.md` as the source-grounded keeper list for the retained OpenAI subscription auth/model transport bridge. Classify all Epiphany-relevant JSON contamination, define the native CultNet runtime boundary, keep worker launch/result/selfPatch cargo as typed documents, evacuate Epiphany operator/state/process authority from Codex JSON-RPC, wrap MCP's unavoidable JSON protocol edge in typed Epiphany intent/result/receipt documents, and keep cutting until Epiphany can run its own state and processes without `codex_message_processor.rs` except for bridge compatibility. - - The next Codex-starvation slice is live exercise and hardening of automatic tool-result continuation in worker runtime. The quarantined Codex MCP spine may execute typed tool intents and emit typed receipts; the model runtime can build and run provider-neutral follow-up turns from those receipts; and coordinator run mode now passes the quarantined tool adapter into worker runtime with auto-tools enabled by default. Codex transports tool calls; it must not inject prompt doctrine or decide what Epiphany agents do with tool results. + - The next Codex-starvation slice is provider-transport diagnosis after the Mom-ready normal pass. The quarantined Codex MCP spine may execute typed tool intents and emit typed receipts; the model runtime can build and run provider-neutral follow-up turns from those receipts; coordinator run mode passes the quarantined tool adapter into worker runtime with auto-tools enabled by default; worker runtime now enforces max-runtime with a failed lifecycle receipt; native status/roles/jobs/coordinator surfaces project failed runtime-linked jobs as terminal without Codex prompt or scheduler authority; and the normal 180-second MVP pass now fails cleanly at the provider/runtime stream seam instead of blocking coordinator or hiding as pending state. - The May 2026 teardown/rebuild migration in `notes/epiphany-ideal-architecture-rebuild-plan.md` is closed unless a concrete regression reopens it. Preserve the new foundation: Epiphany view/coordinator policy lives in `epiphany-core`, runtime-spine owns job/result lifecycle identity through `runtime_links`, duplicate acceptance is receipt-keyed, public findings stay typed/sealed, view expansion requires a core contract, and app-server remains routing/adaptation rather than a second policy throne. - Treat Phase 5 update/distill/propose/promote/read/notification as complete enough unless a concrete regression appears. - Preserve read-only boundaries for retrieve, distill, propose, freshness, context, graphQuery, roleResult, reorientResult, and the canonical view lenses for scene, jobs, roles, planning, pressure, reorient, crrc, and coordinator. @@ -569,4 +569,4 @@ current_status: materializes complete MCP-shaped model tool calls as typed tool invocation intents, and the Codex MCP spine can consume those intents from the mixed runtime-spine store and emit typed success/failure receipts. - next_action: Exercise a normal-timeout live MVP worker pass and harden the next receipt edge that fails: coordinator workers now launch detached, local MVP threads are resumable, worker runtime enforces max-runtime timeout receipts, and failed modeling blocks downstream verification until reviewed. + next_action: Diagnose why `epiphany-model-runtime run-worker --provider openai-codex` produces no typed worker result, no tool intents, and empty worker stdout/stderr before the 180-second watchdog fires in the normal Mom-ready MVP pass. Keep the timeout/status projection repair; the next likely cut is provider stream observability or prompt/request sizing, not coordinator scheduling.