diff --git a/epiphany-core/src/bin/epiphany-mvp-coordinator.rs b/epiphany-core/src/bin/epiphany-mvp-coordinator.rs index a0801cf1..6f00d14d 100644 --- a/epiphany-core/src/bin/epiphany-mvp-coordinator.rs +++ b/epiphany-core/src/bin/epiphany-mvp-coordinator.rs @@ -350,6 +350,7 @@ fn run_coordinator(args: &Args) -> Result { "eventId": runtime_event.event_id, })); let run_result = (|| -> Result { + let mut startup_proposal_modeling_job_id = None; if let Some(objective) = args.objective.as_deref() { if let (Some(store), Some(preparation_id), Some(claim)) = ( args.resident_state_store.as_deref(), @@ -509,19 +510,23 @@ fn run_coordinator(args: &Args) -> Result { "typed proposal Modeling requires exclusive objective-free intake" )); } - let state = epiphany_core::EpiphanyCoordinatorService::new(&runtime_store) - .state()? - .ok_or_else(|| anyhow!("proposal Modeling launch requires coordinator state"))?; - let launched = launch_role( + let current = epiphany_core::project_current_work(&runtime_store)? + .proposal_modeling + .filter(|work| { + work.action == epiphany_core::EpiphanyProposalModelingContinuationAction::Launch + }) + .ok_or_else(|| anyhow!("proposal Modeling request is not launchable"))?; + if current.request.request_id != request_id { + return Err(anyhow!( + "explicit proposal Modeling request does not match current keyed work" + )); + } + let binding = epiphany_core::launch_current_proposal_modeling_work( &runtime_store, - &local_verse_store, - &thread_id, - "modeling", - Some(state.revision as i64), - args.max_runtime_seconds, - Some(request_id), + epiphany_core::EpiphanyProposalModelingLaunchOptions { created_at: now() }, )?; - let worker_job_id = worker_job_id_from_launch(&launched)?; + let worker_job_id = binding.job_id.clone(); + startup_proposal_modeling_job_id = Some(worker_job_id.clone()); let worker_run = launch_worker_runtime_detached( &model_runtime_bin, &tool_adapter_bin, @@ -542,7 +547,7 @@ fn run_coordinator(args: &Args) -> Result { "type": "proposalModelingLaunch", "requestId": request_id, "runtimeJobId": worker_job_id, - "launch": status_cli::sanitize_for_operator(launched), + "launch": binding, "worker": worker_run, "authority": "proposal-modeling-only" })); @@ -555,6 +560,13 @@ fn run_coordinator(args: &Args) -> Result { .get("coordinator") .cloned() .unwrap_or_else(|| json!({"action": "regatherManually"})); + if matches!( + coordinator["action"].as_str(), + Some("waitForModelingResult" | "reviewModelingResult") + ) && let Some(job_id) = startup_proposal_modeling_job_id.as_deref() + { + coordinator["runtimeJobId"] = Value::String(job_id.to_string()); + } let mut action = coordinator["action"] .as_str() .unwrap_or("regatherManually") @@ -605,7 +617,7 @@ fn run_coordinator(args: &Args) -> Result { if action == "awaitFrontierProposal" || matches!( action.as_str(), - "waitForImaginationResult" | "waitForMindPlanResult" + "waitForModelingResult" | "waitForImaginationResult" | "waitForMindPlanResult" ) || (action == "reviewFrontierPlanningFailure" && !args.supersede_failed_results) || (is_stop_action(&action) @@ -787,6 +799,43 @@ fn run_coordinator(args: &Args) -> Result { "reviewResearchResult" | "reviewModelingResult" | "reviewVerificationResult" => { let role_id = role_id_for_coordinator_action(&action) .ok_or_else(|| anyhow!("unsupported review action {action}"))?; + if role_id == "modeling" + && let Some(job_id) = + epiphany_core::current_proposal_modeling_review_job_id(&runtime_store)? + { + let result = + epiphany_core::runtime_role_worker_result(&runtime_store, &job_id)? + .ok_or_else(|| { + anyhow!("proposal Modeling review lost its typed result") + })?; + push_event( + &mut step, + json!({"type": "proposalModelingResult", "roleId": role_id, "result": result}), + ); + if !args.auto_review { + final_action = json!({ + "action": "reviewModelingResult", + "reason": "The exact proposal Modeling result awaits keyed Mind admission.", + "runtimeJobId": job_id, + }); + append_operator_step_jsonl(&steps_path, &step)?; + steps.push(step); + break; + } + let accepted = epiphany_core::accept_proposal_modeling_result( + &runtime_store, + &job_id, + &now(), + )?; + push_event( + &mut step, + json!({"type": "proposalModelingAccept", "roleId": role_id, "commit": accepted}), + ); + final_status = collect_coordinator_status(&runtime_store, &thread_id)?; + append_operator_step_jsonl(&steps_path, &step)?; + steps.push(step); + continue; + } if role_id == "modeling" && let Some(job_id) = epiphany_core::current_body_modeling_review_job_id(&runtime_store)? @@ -996,8 +1045,36 @@ fn run_coordinator(args: &Args) -> Result { } else { None }; + let thread_free_modeling = role_id == "modeling" + && (proposal_modeling_request_id.is_some() + || status["currentWork"]["bodyModeling"].is_object()); let launch = if role_id == "modeling" - && proposal_modeling_request_id.is_none() + && let Some(request_id) = proposal_modeling_request_id + { + let current = epiphany_core::project_current_work(&runtime_store)? + .proposal_modeling + .filter(|work| { + work.action + == epiphany_core::EpiphanyProposalModelingContinuationAction::Launch + }) + .ok_or_else(|| anyhow!("proposal Modeling work is not launchable"))?; + if current.request.request_id != request_id { + return Err(anyhow!( + "Self-derived proposal Modeling request changed before launch" + )); + } + let binding = epiphany_core::launch_current_proposal_modeling_work( + &runtime_store, + epiphany_core::EpiphanyProposalModelingLaunchOptions { + created_at: now(), + }, + )?; + json!({ + "bindingId": epiphany_core::EPIPHANY_MODELING_ROLE_BINDING_ID, + "backendJobId": binding.job_id, + "proposalModelingLaunchBinding": binding, + }) + } else if role_id == "modeling" && status["currentWork"]["bodyModeling"].is_object() { let binding = epiphany_core::launch_current_body_modeling_work( @@ -1020,11 +1097,6 @@ fn run_coordinator(args: &Args) -> Result { role_id, revision, args.max_runtime_seconds, - if role_id == "modeling" { - proposal_modeling_request_id - } else { - None - }, )? }; let worker_job_id = worker_job_id_from_launch(&launch)?; @@ -1052,7 +1124,23 @@ fn run_coordinator(args: &Args) -> Result { &mut step, json!({"type": "workerRuntime", "roleId": role_id, "run": worker_run}), ); - let result = read_role_result(&runtime_store, &thread_id, role_id)?; + let result = if thread_free_modeling { + 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 Modeling attempt has not produced a terminal result.", + }), + } + } else { + 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())}), @@ -1578,7 +1666,6 @@ fn launch_role( role_id: &str, expected_revision: Option, max_runtime_seconds: u64, - proposal_modeling_request_id: Option<&str>, ) -> Result { let started = Instant::now(); let service = epiphany_core::EpiphanyCoordinatorService::new(runtime_store); @@ -1631,7 +1718,6 @@ fn launch_role( context, runtime_store, &state, - proposal_modeling_request_id, ) .map_err(anyhow::Error::msg)?; context = modeling_launch_context.context; @@ -1650,7 +1736,6 @@ fn launch_role( Some(context), ) .map_err(anyhow::Error::msg)?; - request.proposal_modeling_request_id = proposal_modeling_request_id.map(str::to_string); request.repo_frontier_modeling_request_id = repo_frontier_modeling_request_id; request.repo_frontier_research_request_id = repo_frontier_research_request .as_ref() diff --git a/epiphany-core/src/bin/epiphany-mvp-status.rs b/epiphany-core/src/bin/epiphany-mvp-status.rs index c94c6554..7d3f9cea 100644 --- a/epiphany-core/src/bin/epiphany-mvp-status.rs +++ b/epiphany-core/src/bin/epiphany-mvp-status.rs @@ -508,7 +508,7 @@ fn run_native_status(args: &Args, include_auxiliary_status: bool) -> Result Result Result Result { + if request.proposal_modeling_request_id.is_some() { + return Err(anyhow!( + "proposal Modeling launch is owned by keyed current work, not the aggregate coordinator transaction" + )); + } let body_basis = if request.owner_role == EPIPHANY_MODELING_OWNER_ROLE { Some(observe_runtime_repository_body_basis(store)?) } else { @@ -102,32 +107,6 @@ fn commit_coordinator_job_launch_in_cache( } } } - let proposal_launch = if let Some(request_id) = request.proposal_modeling_request_id.as_deref() - { - let (selection, proposal, identity) = - validate_proposal_modeling_launch(cache, current_state, request, request_id)?; - let model = crate::repo_model_documents::assemble_repo_model_view_from_cache(cache)?; - let projection = build_proposal_modeling_context_projection(&selection, &proposal, &model)?; - match &mut effective_launch_document { - EpiphanyWorkerLaunchDocument::Role(document) => { - document.proposal_modeling_context = Some(projection); - } - EpiphanyWorkerLaunchDocument::Reorient(_) => { - return Err(anyhow!( - "reorient launch cannot carry proposal Modeling context" - )); - } - } - let bytes = rmp_serde::to_vec_named(&effective_launch_document)?; - Some(( - selection, - proposal, - identity, - format!("{:x}", Sha256::digest(bytes)), - )) - } else { - None - }; let claim_repair_launch = if let Some(request_id) = request.claim_repair_request_id.as_deref() { let (repair, challenge, identity) = validate_claim_repair_launch(cache, current_state, request, request_id)?; @@ -362,38 +341,6 @@ fn commit_coordinator_job_launch_in_cache( }) .ok_or_else(|| anyhow!("prepared launch omitted its runtime identity replacement"))?; let runtime_identity_replacement = batch.remove(runtime_identity_position); - if let Some((selection, proposal, identity, worker_launch_document_sha256)) = proposal_launch { - let launch_binding = RepoFrontierProposalModelingLaunchBinding { - schema_version: REPO_FRONTIER_PROPOSAL_MODELING_LAUNCH_BINDING_SCHEMA_VERSION.into(), - binding_record_id: format!( - "repo-frontier-proposal-modeling-launch-{}", - plan.backend_job_id - ), - proposal_modeling_request_id: selection.request_id, - proposal_id: proposal.proposal_id, - proposal_payload_sha256: proposal.payload_sha256, - job_id: plan.backend_job_id.clone(), - binding_id: request.binding_id.clone(), - runtime_id: identity.runtime_id, - thread_id: selection.thread_id.clone(), - launched_at: created_at.clone(), - worker_launch_document_sha256, - contract: REPO_FRONTIER_PROPOSAL_MODELING_LAUNCH_BINDING_CONTRACT.into(), - }; - if cache - .get::(&launch_binding.binding_record_id)? - .is_some() - { - return Err(anyhow!( - "proposal Modeling launch binding already exists for backend job" - )); - } - batch.push( - cache - .prepare_entry(&launch_binding.binding_record_id, &launch_binding)? - .0, - ); - } if let Some((repair, challenge, identity, worker_launch_document_sha256)) = claim_repair_launch { let launch_binding = RepoModelClaimRepairLaunchBinding { @@ -578,6 +525,11 @@ pub fn plan_coordinator_job_launch( launcher_job_id: String, backend_job_id: String, ) -> Result { + if request.proposal_modeling_request_id.is_some() { + return Err(anyhow!( + "proposal Modeling launch is owned by keyed current work, not the aggregate coordinator transaction" + )); + } let ( caller_proposal_projection, caller_repair_projection, @@ -642,11 +594,7 @@ pub fn plan_coordinator_job_launch( state.revision )); } - if let Some(request_id) = request.proposal_modeling_request_id.as_deref() { - let mut cache = runtime_spine_cache(runtime_store)?; - cache.pull_all_backing_stores()?; - validate_proposal_modeling_launch(&cache, state, request, request_id)?; - } else if let Some(request_id) = request.claim_repair_request_id.as_deref() { + if let Some(request_id) = request.claim_repair_request_id.as_deref() { let mut cache = runtime_spine_cache(runtime_store)?; cache.pull_all_backing_stores()?; validate_claim_repair_launch(&cache, state, request, request_id)?; @@ -1102,130 +1050,6 @@ fn validate_claim_repair_launch( Ok((repair, challenge, identity)) } -fn build_proposal_modeling_context_projection( - request: &RepoFrontierProposalModelingRequest, - proposal: &RepoFrontierWorkProposal, - model: &crate::EpiphanyRepoModelView, -) -> Result { - Ok(RepoFrontierProposalModelingContextProjection { - schema_version: REPO_FRONTIER_PROPOSAL_MODELING_CONTEXT_SCHEMA_VERSION.into(), - contract: REPO_FRONTIER_PROPOSAL_MODELING_CONTEXT_CONTRACT.into(), - request_id: request.request_id.clone(), - proposal_id: proposal.proposal_id.clone(), - proposal_payload_sha256: proposal.payload_sha256.clone(), - runtime_id: request.runtime_id.clone(), - thread_id: request.thread_id.clone(), - repository: request.repository.clone(), - workspace: request.workspace.clone(), - source_kind: proposal.source_kind, - source_actor: proposal.source_actor.clone(), - source_ref: proposal.source_ref.clone(), - title: proposal.title.clone(), - body: proposal.body.clone(), - desired_outcome: proposal.desired_outcome.clone(), - constraints: proposal.constraints.clone(), - scope_hints: proposal.scope_hints.clone(), - evidence_refs: proposal.evidence_refs.clone(), - public_source_refs: proposal.public_source_refs.clone(), - private_state_included: proposal.private_state_included, - model_projection_digest: model.projection_digest.clone(), - model_source_documents: model.source_documents.clone(), - }) -} - -fn validate_proposal_modeling_launch( - cache: &CultCache, - state: &EpiphanyThreadState, - launch: &EpiphanyJobLaunchRequest, - request_id: &str, -) -> Result<( - RepoFrontierProposalModelingRequest, - RepoFrontierWorkProposal, - EpiphanyRuntimeIdentity, -)> { - if match &launch.launch_document { - EpiphanyWorkerLaunchDocument::Role(document) => { - document.proposal_modeling_context.is_some() - } - EpiphanyWorkerLaunchDocument::Reorient(_) => false, - } { - return Err(anyhow!("caller cannot author proposal Modeling context")); - } - if launch.owner_role != EPIPHANY_MODELING_OWNER_ROLE - || launch.binding_id != EPIPHANY_MODELING_ROLE_BINDING_ID - { - return Err(anyhow!( - "proposal selection may only be carried by the Modeling role launch" - )); - } - let selection = cache - .get::(request_id)? - .ok_or_else(|| { - anyhow!("proposal Modeling selection request {request_id:?} does not exist") - })?; - crate::runtime_spine::validate_repo_frontier_proposal_modeling_request(&selection)?; - let proposal = cache - .get::(&selection.proposal_id)? - .ok_or_else(|| anyhow!("proposal Modeling selection references a missing proposal"))?; - crate::runtime_spine::validate_repo_frontier_work_proposal(&proposal)?; - if proposal.source_kind == crate::RepoFrontierProposalSourceKind::Imagination { - crate::runtime_spine::validate_autonomous_proposal_binding(cache, &proposal)?; - } - let prior_bindings = cache - .get_all::()? - .iter() - .filter(|binding| binding.proposal_modeling_request_id == request_id) - .cloned() - .collect::>(); - for binding in prior_bindings { - if !proposal_modeling_launch_was_superseded(cache, &binding)? { - return Err(anyhow!( - "proposal Modeling selection request already has an unsuperseded launch" - )); - } - } - let identity = cache - .get::(RUNTIME_IDENTITY_KEY)? - .ok_or_else(|| anyhow!("proposal Modeling launch requires runtime identity"))?; - let persisted_state = cache - .get::(crate::THREAD_STATE_KEY)? - .ok_or_else(|| anyhow!("proposal Modeling launch requires authoritative thread state"))?; - let persisted_state_value = persisted_state.state()?; - let proposal_payload_sha256 = crate::repo_frontier_proposal_payload_sha256( - &proposal.title, - &proposal.body, - &proposal.desired_outcome, - &proposal.constraints, - &proposal.scope_hints, - &proposal.evidence_refs, - &proposal.public_source_refs, - )?; - if selection.schema_version != REPO_FRONTIER_PROPOSAL_MODELING_REQUEST_SCHEMA_VERSION - || selection.contract != REPO_FRONTIER_PROPOSAL_MODELING_REQUEST_CONTRACT - || selection.request_id != request_id - || selection.proposal_payload_sha256 != proposal.payload_sha256 - || proposal.payload_sha256 != proposal_payload_sha256 - || selection.runtime_id != identity.runtime_id - || selection.runtime_id != proposal.runtime_id - || selection.thread_id != proposal.thread_id - || persisted_state_value != *state - || selection.repository != proposal.repository - || selection.workspace != proposal.workspace - { - return Err(anyhow!( - "proposal Modeling launch provenance binding mismatch" - )); - } - Ok((selection, proposal, identity)) -} - -fn proposal_modeling_launch_was_superseded( - cache: &CultCache, - binding: &RepoFrontierProposalModelingLaunchBinding, -) -> Result { - worker_attempt_is_retryable_terminal_failure(cache, &binding.job_id) -} - fn worker_attempt_is_retryable_terminal_failure(cache: &CultCache, job_id: &str) -> Result { cache .get::(&format!( diff --git a/epiphany-core/src/coordinator_launch_context.rs b/epiphany-core/src/coordinator_launch_context.rs index 7a5105c7..71690197 100644 --- a/epiphany-core/src/coordinator_launch_context.rs +++ b/epiphany-core/src/coordinator_launch_context.rs @@ -843,15 +843,7 @@ pub fn append_modeling_work_loop_telemetry_context( mut context: String, runtime_store_path: &Path, state: &EpiphanyThreadState, - proposal_modeling_request_id: Option<&str>, ) -> Result { - if proposal_modeling_request_id.is_some() { - return Ok(ModelingWorkLoopLaunchContext { - context, - repo_frontier_modeling_request_id: None, - repo_frontier_verdict_modeling_authority: None, - }); - } if accepted_research_is_newest_unmodeled_boundary(state) { context.push_str("\n\n\n"); context.push_str("The current Modeling turn is caused by accepted Eyes evidence newer than the last accepted Modeling boundary. Use the accepted Research finding already present in coordinator context to update the body model. This is not a historical Soul-verdict incorporation turn; do not substitute an older frontier verification route.\n"); @@ -1844,7 +1836,6 @@ mod tests { "ordinary".to_string(), missing_store, &ordinary, - None, ) .expect("ordinary Modeling does not touch verdict authority"), "ordinary" @@ -1872,22 +1863,10 @@ mod tests { "ambiguous".to_string(), missing_store, &ambiguous, - None, ) .expect_err("equal-time accepted results must not be selected by adjacency"); assert!(error.contains("temporally ambiguous")); - assert_eq!( - append_modeling_work_loop_telemetry_context( - "proposal".to_string(), - missing_store, - &ambiguous, - Some("repo-frontier-proposal-modeling-request"), - ) - .expect("explicit proposal authority excludes historical verdict incorporation"), - "proposal" - ); - let accepted = |role_id: &str, accepted_at: &str| EpiphanyAcceptanceReceipt { id: format!("accept-{role_id}"), result_id: format!("result-{role_id}"), @@ -1914,7 +1893,6 @@ mod tests { "eyes".to_string(), missing_store, &eyes_handoff, - None, ) .expect("accepted Eyes handoff must not bind an older Soul route"); assert!(context.contains("accepted_eyes_modeling_handoff")); @@ -2249,7 +2227,6 @@ mod tests { "".to_string(), &runtime_store, &state, - None, ) .map_err(anyhow::Error::msg)?; assert!(modeling_context.contains("")); diff --git a/epiphany-core/src/current_work.rs b/epiphany-core/src/current_work.rs index 574d5084..6d429be5 100644 --- a/epiphany-core/src/current_work.rs +++ b/epiphany-core/src/current_work.rs @@ -22,10 +22,25 @@ pub struct EpiphanyCurrentWorkProjection { pub body_modeling_action: Option, pub research_continuation_action: Option, pub frontier_planning_stage: RepoFrontierPlanningLifecycleStage, - pub proposal_modeling_request: Option, + pub proposal_modeling: Option, pub hands_frontier_ready: bool, } +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum EpiphanyProposalModelingContinuationAction { + Launch, + Wait, + Review, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EpiphanyProposalModelingWorkProjection { + pub request: RepoFrontierProposalModelingRequest, + pub action: EpiphanyProposalModelingContinuationAction, + pub job_id: Option, +} + #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum EpiphanyBodyModelingContinuationAction { @@ -72,6 +87,11 @@ pub struct EpiphanyBodyModelingLaunchOptions { pub created_at: String, } +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct EpiphanyProposalModelingLaunchOptions { + pub created_at: String, +} + #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] #[cultcache( type = "epiphany.mind.body_modeling_decision.v1", @@ -267,6 +287,8 @@ pub fn unresolved_body_modeling_work( pub fn project_current_work(store_path: impl AsRef) -> Result { let store_path = store_path.as_ref(); let mind = crate::assemble_mind_view(store_path)?; + let mut cache = crate::runtime_spine_cache(store_path)?; + cache.pull_all_backing_stores()?; let (body_modeling, body_modeling_action) = match ( mind.repository_body_observation.clone(), mind.repo_model.as_ref(), @@ -277,8 +299,6 @@ pub fn project_current_work(store_path: impl AsRef) -> Result(&work.work_id)?, @@ -308,9 +328,7 @@ pub fn project_current_work(store_path: impl AsRef) -> Result Result> { + let mut requests = cache.get_all::()?; + requests.sort_by(|left, right| { + left.selected_at + .cmp(&right.selected_at) + .then_with(|| left.request_id.cmp(&right.request_id)) + }); + let bindings = cache.get_all::()?; + let receipts = cache.get_all::()?; + for request in requests { + crate::runtime_spine::validate_repo_frontier_proposal_modeling_request(&request)?; + let mut request_bindings = bindings + .iter() + .filter(|binding| binding.proposal_modeling_request_id == request.request_id) + .collect::>(); + request_bindings.sort_by(|left, right| { + left.launched_at + .cmp(&right.launched_at) + .then_with(|| left.job_id.cmp(&right.job_id)) + }); + let Some(binding) = request_bindings.last() else { + return Ok(Some(EpiphanyProposalModelingWorkProjection { + request, + action: EpiphanyProposalModelingContinuationAction::Launch, + job_id: None, + })); + }; + let result = cache.get::(&binding.job_id)?; + if let Some(result) = result.as_ref() { + if result.proposal_modeling_request_id.as_deref() != Some(request.request_id.as_str()) { + return Err(anyhow!( + "proposal Modeling launch result crossed request authority" + )); + } + if receipts.iter().any(|receipt| { + receipt.invariant_owner == "Modeling.proposal_frontier" + && matches!( + &receipt.authority, + crate::EpiphanyMindCommitAuthority::ModelDecisionContext { + decision_context_id + } if decision_context_id == &result.decision_context_id + ) + }) { + continue; + } + } + let job = cache + .get::(&binding.job_id)? + .ok_or_else(|| anyhow!("proposal Modeling launch binding lost its runtime job"))?; + let action = match job.status { + crate::EpiphanyRuntimeJobStatus::Failed + | crate::EpiphanyRuntimeJobStatus::Cancelled => { + EpiphanyProposalModelingContinuationAction::Launch + } + crate::EpiphanyRuntimeJobStatus::Completed if result.is_some() => { + crate::runtime_spine::validate_proposal_modeling_worker_fulfillment( + cache, + result.as_ref().expect("checked terminal result"), + )?; + EpiphanyProposalModelingContinuationAction::Review + } + _ => EpiphanyProposalModelingContinuationAction::Wait, + }; + return Ok(Some(EpiphanyProposalModelingWorkProjection { + request, + action, + job_id: Some(binding.job_id.clone()), + })); + } + Ok(None) +} + pub fn body_modeling_continuation_action_for_job( store_path: impl AsRef, job_id: &str, @@ -399,6 +491,25 @@ pub fn current_body_modeling_review_job_id(store_path: impl AsRef) -> Resu Ok(bindings.last().map(|binding| binding.job_id.clone())) } +pub fn proposal_modeling_continuation_action_for_job( + store_path: impl AsRef, + job_id: &str, +) -> Result> { + Ok(project_current_work(store_path)? + .proposal_modeling + .filter(|work| work.job_id.as_deref() == Some(job_id)) + .map(|work| work.action)) +} + +pub fn current_proposal_modeling_review_job_id( + store_path: impl AsRef, +) -> Result> { + Ok(project_current_work(store_path)? + .proposal_modeling + .filter(|work| work.action == EpiphanyProposalModelingContinuationAction::Review) + .and_then(|work| work.job_id)) +} + pub fn accept_body_modeling_result( store_path: impl AsRef, job_id: &str, @@ -474,6 +585,101 @@ pub fn accept_body_modeling_result( } } +pub fn accept_proposal_modeling_result( + store_path: impl AsRef, + job_id: &str, + accepted_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 job = cache + .get::(job_id)? + .ok_or_else(|| anyhow!("proposal Modeling acceptance lost its runtime job"))?; + if job.status != crate::EpiphanyRuntimeJobStatus::Completed { + return Err(anyhow!("proposal Modeling runtime job is not completed")); + } + let result = cache + .get::(job_id)? + .ok_or_else(|| anyhow!("proposal Modeling acceptance lost its typed result"))?; + let request_id = result + .proposal_modeling_request_id + .as_deref() + .ok_or_else(|| anyhow!("result is not proposal Modeling authority"))?; + if !result.role_id.eq_ignore_ascii_case("modeling") + || result.claim_repair_request_id.is_some() + || result.repo_frontier_modeling_request_id.is_some() + { + return Err(anyhow!("proposal Modeling result crossed family authority")); + } + let evidence = crate::runtime_typed_request_fulfillment( + store_path, + crate::RuntimeTypedRequestRef::ProposalModeling(request_id), + )? + .ok_or_else(|| anyhow!("proposal Modeling result is not exact typed fulfillment"))?; + if evidence.job_id != job_id || evidence.result_id != result.result_id { + return Err(anyhow!("proposal Modeling fulfillment identity mismatch")); + } + let proposal = result + .repo_model_mutation_proposal()? + .ok_or_else(|| anyhow!("proposal Modeling result has no semantic mutation proposal"))?; + if proposal.proposal_id != format!("repo-model-mutation-proposal-{job_id}") { + return Err(anyhow!( + "proposal Modeling mutation proposal identity is not runtime-owned" + )); + } + let plan = crate::plan_repo_model_mutation(store_path, &proposal)?; + match crate::commit_mind_mutation( + store_path, + &result.decision_context_id, + "Modeling.proposal_frontier", + plan.strong_reads, + plan.writes, + accepted_at, + )? { + crate::EpiphanyMindCommitOutcome::Committed(receipt) => Ok(receipt), + crate::EpiphanyMindCommitOutcome::Conflict { + document_identities, + } => Err(anyhow!( + "proposal Modeling admission lost exact keyed reads: {document_identities:?}" + )), + } +} + +fn commit_current_work_launch( + store_path: &Path, + cache: &CultCache, + mut expected: Vec, + mut replacements: Vec, + companions: Vec, + family: &str, +) -> Result<()> { + replacements.extend(companions); + let snapshot = cache.snapshot_envelopes(); + for replacement in &replacements { + if let Some(existing) = snapshot + .iter() + .find(|value| value.r#type == replacement.r#type && value.key == replacement.key) + && !expected.contains(existing) + { + expected.push(existing.clone()); + } + } + for envelope in &expected { + if !replacements.iter().any(|replacement| { + replacement.r#type == envelope.r#type && replacement.key == envelope.key + }) { + replacements.push(envelope.clone()); + } + } + if !crate::runtime_store_backend::runtime_spine_backing_store(store_path)? + .compare_and_swap_batch(&expected, replacements)? + { + return Err(anyhow!("{family} launch lost its exact Mind/runtime CAS")); + } + Ok(()) +} + pub fn launch_current_body_modeling_work( store_path: impl AsRef, options: EpiphanyBodyModelingLaunchOptions, @@ -609,36 +815,235 @@ pub fn launch_current_body_modeling_work( expected.push(envelope.clone()); } } - let mut replacements = prepared.envelopes; - for replacement in &replacements { - if let Some(existing) = snapshot - .iter() - .find(|value| value.r#type == replacement.r#type && value.key == replacement.key) - { - if !expected.contains(existing) { - expected.push(existing.clone()); - } - } - } - replacements.push(cache.prepare_entry(&binding.binding_record_id, &binding)?.0); - replacements.push(cache.prepare_entry(&grant.receipt_id, &grant)?.0); - for envelope in &expected { - if !replacements.iter().any(|replacement| { - replacement.r#type == envelope.r#type && replacement.key == envelope.key - }) { - replacements.push(envelope.clone()); - } - } - if !crate::runtime_store_backend::runtime_spine_backing_store(store_path)? - .compare_and_swap_batch(&expected, replacements)? - { - return Err(anyhow!( - "Body Modeling launch lost its exact Mind/runtime CAS" - )); - } + commit_current_work_launch( + store_path, + &cache, + expected, + prepared.envelopes, + vec![ + cache.prepare_entry(&binding.binding_record_id, &binding)?.0, + cache.prepare_entry(&grant.receipt_id, &grant)?.0, + ], + "Body Modeling", + )?; Ok(binding) } +pub fn launch_current_proposal_modeling_work( + store_path: impl AsRef, + options: EpiphanyProposalModelingLaunchOptions, +) -> Result { + let store_path = store_path.as_ref(); + if chrono::DateTime::parse_from_rfc3339(&options.created_at).is_err() { + return Err(anyhow!("proposal Modeling launch options are invalid")); + } + let work = project_current_work(store_path)? + .proposal_modeling + .filter(|work| work.action == EpiphanyProposalModelingContinuationAction::Launch) + .ok_or_else(|| anyhow!("Mind has no launchable proposal Modeling work"))?; + let mut cache = crate::runtime_spine_cache(store_path)?; + cache.pull_all_backing_stores()?; + let request = work.request; + let proposal = cache + .get::(&request.proposal_id)? + .ok_or_else(|| anyhow!("proposal Modeling launch lost its proposal"))?; + crate::runtime_spine::validate_repo_frontier_work_proposal(&proposal)?; + if proposal.source_kind == crate::RepoFrontierProposalSourceKind::Imagination { + crate::runtime_spine::validate_autonomous_proposal_binding(&cache, &proposal)?; + } + let identity = cache + .get::(crate::RUNTIME_IDENTITY_KEY)? + .ok_or_else(|| anyhow!("proposal Modeling launch requires runtime identity"))?; + if request.runtime_id != identity.runtime_id + || request.runtime_id != proposal.runtime_id + || request.proposal_id != proposal.proposal_id + || request.proposal_payload_sha256 != proposal.payload_sha256 + { + return Err(anyhow!("proposal Modeling launch provenance mismatch")); + } + let mind = crate::assemble_mind_view(store_path)?; + let body_basis = mind + .repository_body_observation + .clone() + .ok_or_else(|| anyhow!("proposal Modeling launch requires admitted Body state"))?; + let model = mind + .repo_model + .as_ref() + .ok_or_else(|| anyhow!("proposal Modeling launch requires keyed RepoModel state"))?; + let proposal_context = build_proposal_modeling_context_projection(&request, &proposal, model)?; + let attempt_ordinal = cache + .get_all::()? + .into_iter() + .filter(|binding| binding.proposal_modeling_request_id == request.request_id) + .count() + + cache + .get_all::()? + .into_iter() + .filter(|attempt| { + attempt.request_kind == "proposal-modeling" + && attempt.request_id == request.request_id + }) + .count(); + let job_id = format!( + "proposal-modeling-{}-attempt-{attempt_ordinal}", + request.request_id + ); + let binding_record_id = format!("repo-frontier-proposal-modeling-launch-{job_id}"); + let launch_document = + crate::EpiphanyWorkerLaunchDocument::Role(crate::EpiphanyRoleWorkerLaunchDocument { + thread_id: request.thread_id.clone(), + role_id: "modeling".into(), + state_revision: 0, + objective: None, + dynamic_prompt_context: None, + repository_body_observation_basis: Some(body_basis), + proposal_modeling_context: Some(proposal_context), + claim_repair_context: None, + frontier_planning_context: None, + frontier_research_context: None, + frontier_plan_mind_context: None, + imagination_consideration_context: None, + admitted_model_direction_consideration_context: None, + 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 worker_launch_document_sha256 = format!( + "{:x}", + Sha256::digest(rmp_serde::to_vec_named(&launch_document)?) + ); + let authority_scope = "epiphany.role.modeling".to_string(); + let output_contract_id = launch_document.output_contract_id().to_string(); + let prepared = crate::prepare_runtime_spine_heartbeat_job( + &cache, + crate::RuntimeSpineHeartbeatJobOptions { + runtime_id: identity.runtime_id.clone(), + display_name: "Epiphany Local".into(), + session_id: crate::EPIPHANY_RUNTIME_ROOT_SESSION_ID.into(), + objective: "Model one admitted proposal against keyed Mind".into(), + coordinator_note: "Proposal current-work launch transaction opened this session." + .into(), + job_id: job_id.clone(), + role: crate::EPIPHANY_MODELING_OWNER_ROLE.into(), + binding_id: crate::EPIPHANY_MODELING_ROLE_BINDING_ID.into(), + authority_scope: authority_scope.clone(), + instruction: "Act as Epiphany Modeling. Evaluate the exact admitted proposal against the sealed keyed Mind projection and return only the proposal Modeling result 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: Some(request.request_id.clone()), + claim_repair_request_id: None, + frontier_planning_request_id: None, + frontier_plan_mind_request_id: None, + imagination_consideration_request_id: None, + admitted_model_direction_consideration_request_id: None, + repo_frontier_modeling_request_id: None, + repo_frontier_research_request_id: None, + repo_frontier_verdict_modeling_authority: None, + created_at: options.created_at.clone(), + }, + )?; + let binding = crate::RepoFrontierProposalModelingLaunchBinding { + schema_version: crate::REPO_FRONTIER_PROPOSAL_MODELING_LAUNCH_BINDING_SCHEMA_VERSION.into(), + binding_record_id, + proposal_modeling_request_id: request.request_id.clone(), + proposal_id: proposal.proposal_id.clone(), + proposal_payload_sha256: proposal.payload_sha256.clone(), + job_id: job_id.clone(), + binding_id: crate::EPIPHANY_MODELING_ROLE_BINDING_ID.into(), + runtime_id: identity.runtime_id, + thread_id: request.thread_id, + launched_at: options.created_at.clone(), + worker_launch_document_sha256, + contract: crate::REPO_FRONTIER_PROPOSAL_MODELING_LAUNCH_BINDING_CONTRACT.into(), + }; + let grant = crate::substrate_gate::substrate_gate_repo_access_grant_for_worker( + format!("substrate-grant-{}", binding.job_id), + binding.job_id.clone(), + crate::EPIPHANY_MODELING_ROLE_BINDING_ID.into(), + crate::EPIPHANY_MODELING_OWNER_ROLE.into(), + authority_scope, + false, + options.created_at, + ); + let snapshot = cache.snapshot_envelopes(); + let mut expected = Vec::new(); + let strong_versions = [ + ( + crate::RepoFrontierProposalModelingRequest::TYPE, + request.request_id.as_str(), + ), + ( + crate::RepoFrontierWorkProposal::TYPE, + proposal.proposal_id.as_str(), + ), + ]; + for (document_type, document_key) in strong_versions { + let envelope = snapshot + .iter() + .find(|value| value.r#type == document_type && value.key == document_key) + .ok_or_else(|| anyhow!("proposal Modeling launch lost a strong source"))?; + expected.push(envelope.clone()); + } + commit_current_work_launch( + store_path, + &cache, + expected, + prepared.envelopes, + vec![ + cache.prepare_entry(&binding.binding_record_id, &binding)?.0, + cache.prepare_entry(&grant.receipt_id, &grant)?.0, + ], + "proposal Modeling", + )?; + Ok(binding) +} + +fn build_proposal_modeling_context_projection( + request: &crate::RepoFrontierProposalModelingRequest, + proposal: &crate::RepoFrontierWorkProposal, + model: &crate::EpiphanyRepoModelView, +) -> Result { + Ok(crate::RepoFrontierProposalModelingContextProjection { + schema_version: crate::REPO_FRONTIER_PROPOSAL_MODELING_CONTEXT_SCHEMA_VERSION.into(), + contract: crate::REPO_FRONTIER_PROPOSAL_MODELING_CONTEXT_CONTRACT.into(), + request_id: request.request_id.clone(), + proposal_id: proposal.proposal_id.clone(), + proposal_payload_sha256: proposal.payload_sha256.clone(), + runtime_id: request.runtime_id.clone(), + thread_id: request.thread_id.clone(), + repository: request.repository.clone(), + workspace: request.workspace.clone(), + source_kind: proposal.source_kind, + source_actor: proposal.source_actor.clone(), + source_ref: proposal.source_ref.clone(), + title: proposal.title.clone(), + body: proposal.body.clone(), + desired_outcome: proposal.desired_outcome.clone(), + constraints: proposal.constraints.clone(), + scope_hints: proposal.scope_hints.clone(), + evidence_refs: proposal.evidence_refs.clone(), + public_source_refs: proposal.public_source_refs.clone(), + private_state_included: proposal.private_state_included, + model_projection_digest: model.projection_digest.clone(), + model_source_documents: model.source_documents.clone(), + }) +} + fn resolve_body_modeling_work( work: EpiphanyBodyModelingWorkProjection, receipt: Option, @@ -668,7 +1073,7 @@ mod tests { use super::*; use epiphany_state_model::{ EpiphanyMemoryDomain, EpiphanyMemoryLifecycle, EpiphanyMemoryNode, EpiphanyMemoryNodeKind, - EpiphanyMemoryProfile, + EpiphanyMemoryProfile, RepoFrontierItem, RepoFrontierStatus, }; fn basis(observation_id: &str, generation: u64) -> RepositoryBodyObservationBasis { @@ -764,7 +1169,7 @@ mod tests { } #[test] - fn body_decision_is_derived_from_the_sealed_role_projection() -> Result<()> { + fn keyed_modeling_lifecycles_ignore_thread_state() -> Result<()> { let temp = tempfile::tempdir()?; let store = temp.path().join("body-decision.cc"); crate::initialize_runtime_spine( @@ -1002,6 +1407,263 @@ mod tests { .is_none() ); assert_eq!(crate::repository_body_read_counters(), (0, 0)); + + let proposal = crate::intake_user_repo_frontier_proposal( + &store, + crate::RepoFrontierUserProposalInput { + proposal_id: "proposal-1".into(), + source_actor: "operator".into(), + source_ref: "operator://proposal-1".into(), + repository: "epiphany".into(), + workspace: "workspace".into(), + thread_id: "creation-provenance-only".into(), + runtime_id: "runtime".into(), + title: "Model one proposal".into(), + body: "Add one typed frontier without touching unrelated Mind state.".into(), + desired_outcome: "One inspectable frontier".into(), + constraints: Vec::new(), + scope_hints: vec!["epiphany-core/src".into()], + evidence_refs: Vec::new(), + public_source_refs: Vec::new(), + proposed_at: "2026-08-17T00:00:06Z".into(), + private_state_included: false, + }, + )?; + let request = crate::select_repo_frontier_work_proposal_for_modeling( + &store, + &proposal.proposal_id, + "2026-08-17T00:00:07Z", + )?; + let proposal_work = project_current_work(&store)? + .proposal_modeling + .expect("selected proposal must become current work"); + assert_eq!(proposal_work.request, request); + assert_eq!( + proposal_work.action, + EpiphanyProposalModelingContinuationAction::Launch + ); + let racers = (0..2) + .map(|_| { + let store = store.clone(); + std::thread::spawn(move || { + launch_current_proposal_modeling_work( + &store, + EpiphanyProposalModelingLaunchOptions { + created_at: "2026-08-17T00:00:08Z".into(), + }, + ) + }) + }) + .collect::>(); + let race_results = racers + .into_iter() + .map(|racer| racer.join().expect("proposal launch racer panicked")) + .collect::>(); + let proposal_launch = race_results + .iter() + .find_map(|result| result.as_ref().ok()) + .cloned() + .expect("one proposal launch racer must commit"); + assert!(race_results.iter().all(|result| { + result + .as_ref() + .map(|binding| binding == &proposal_launch) + .unwrap_or(true) + })); + assert_eq!( + proposal_launch.proposal_modeling_request_id, + request.request_id + ); + assert_eq!( + proposal_launch.job_id, + format!("proposal-modeling-{}-attempt-0", request.request_id) + ); + assert_eq!( + project_current_work(&store)? + .proposal_modeling + .expect("launched proposal remains current") + .action, + EpiphanyProposalModelingContinuationAction::Wait + ); + assert!( + launch_current_proposal_modeling_work( + &store, + EpiphanyProposalModelingLaunchOptions { + created_at: "2026-08-17T00:00:09Z".into(), + }, + ) + .is_err() + ); + let mut final_cache = crate::runtime_spine_cache(&store)?; + final_cache.pull_all_backing_stores()?; + assert_eq!( + final_cache + .get_all::()? + .into_iter() + .filter(|binding| binding.proposal_modeling_request_id == request.request_id) + .count(), + 1 + ); + assert!( + final_cache + .get::(crate::THREAD_STATE_KEY)? + .is_none() + ); + let proposal_runtime_launch = final_cache + .get::(&proposal_launch.job_id)? + .expect("proposal runtime launch"); + let proposal_document = proposal_runtime_launch.launch_document()?; + let crate::EpiphanyWorkerLaunchDocument::Role(proposal_document) = proposal_document else { + panic!("proposal Modeling must be a role pass") + }; + assert_eq!(proposal_document.state_revision, 0); + assert!(proposal_document.proposal_modeling_context.is_some()); + assert!( + proposal_document + .repository_body_observation_basis + .is_some() + ); + + let proposal_reasoning_basis = + crate::worker_reasoning_basis(&store, &proposal_runtime_launch)?; + crate::put_reasoning_basis(&store, &proposal_reasoning_basis)?; + let mut proposal_native = epiphany_model_adapter::EpiphanyModelRequest::new( + "proposal-request", + "proposal-conversation", + "openai-codex", + "gpt-test", + "model", + ); + proposal_native.reasoning_basis_id = Some(proposal_reasoning_basis.basis_id.clone()); + proposal_native.source_worker_job_id = Some(proposal_launch.job_id.clone()); + let proposal_provider = epiphany_openai_adapter::request_from_native(&proposal_native); + let proposal_context = crate::EpiphanyDecisionContext::new( + &proposal_reasoning_basis, + proposal_native, + proposal_provider, + Vec::new(), + )?; + final_cache.put(&proposal_context.context_id, &proposal_context)?; + let result_id = "proposal-result"; + let mutation = crate::EpiphanyRepoModelMutationProposal::new( + format!("repo-model-mutation-proposal-{}", proposal_launch.job_id), + request.request_id.clone(), + result_id, + vec![proposal.proposal_id.clone()], + body.clone(), + vec![crate::EpiphanyRepoModelMutationOperation::PutFrontier { + item: RepoFrontierItem { + id: "proposal-frontier".into(), + migration_body: "epiphany".into(), + question: "Should this proposal advance?".into(), + gap: "The proposal needs an adopted plan.".into(), + target_claim_ids: vec!["body-node".into()], + source_scope: vec!["epiphany-core/src".into()], + recommended_next_organ: "Imagination".into(), + status: RepoFrontierStatus::Active, + evidence_refs: vec![proposal.proposal_id.clone()], + ..Default::default() + }, + }], + )?; + let proposal_result = crate::EpiphanyRuntimeRoleWorkerResult { + schema_version: crate::RUNTIME_ROLE_WORKER_RESULT_SCHEMA_VERSION.into(), + result_id: result_id.into(), + job_id: proposal_launch.job_id.clone(), + role_id: "modeling".into(), + verdict: "checkpoint-update-needed".into(), + summary: "proposal modeled".into(), + next_safe_move: "admit".into(), + checkpoint_summary: None, + scratch_summary: None, + files_inspected: Vec::new(), + frontier_node_ids: vec!["body-node".into()], + evidence_ids: vec![proposal.proposal_id.clone()], + artifact_refs: Vec::new(), + open_questions: Vec::new(), + evidence_gaps: Vec::new(), + risks: Vec::new(), + state_patch_msgpack: None, + self_patch_msgpack: None, + item_error: None, + metadata: Default::default(), + repo_model_mutation_proposal_msgpack: Some(rmp_serde::to_vec_named(&mutation)?), + verification_request_id: None, + frontier_route_id: None, + repo_frontier_modeling_request_id: None, + proposal_modeling_request_id: Some(request.request_id.clone()), + claim_repair_request_id: None, + frontier_planning_request_id: None, + frontier_plan_candidate_msgpack: None, + frontier_plan_mind_request_id: None, + frontier_plan_mind_decision_msgpack: None, + repository_body_observation_basis: Some(body.clone()), + imagination_consideration_request_id: None, + imagination_consideration_candidate_msgpack: None, + admitted_model_direction_consideration_request_id: None, + admitted_model_direction_consideration_result_msgpack: None, + decision_context_id: proposal_context.context_id.clone(), + }; + let process = crate::ProcessInstanceIdentity { + process_id: 42, + creation_token: 7, + created_at_rfc3339: Some("2026-08-17T00:00:10Z".into()), + executable_path: "proposal-worker".into(), + }; + let activation_token = "proposal-activation"; + crate::claim_runtime_worker_process( + &store, + &proposal_launch.job_id, + &process, + &format!("{:x}", Sha256::digest(activation_token.as_bytes())), + "2026-08-17T00:00:10Z", + )?; + crate::activate_runtime_worker_process( + &store, + &proposal_launch.job_id, + &process, + activation_token, + "2026-08-17T00:00:11Z", + )?; + crate::put_runtime_role_worker_result(&store, &proposal_result)?; + crate::complete_runtime_job( + &store, + crate::RuntimeSpineJobResultOptions { + result_id: format!("runtime-result-{}", proposal_launch.job_id), + job_id: proposal_launch.job_id.clone(), + completed_at: "2026-08-17T00:00:12Z".into(), + verdict: proposal_result.verdict.clone(), + summary: proposal_result.summary.clone(), + next_safe_move: proposal_result.next_safe_move.clone(), + evidence_refs: proposal_result.evidence_ids.clone(), + artifact_refs: Vec::new(), + decision_context_id: Some(proposal_context.context_id.clone()), + }, + )?; + assert_eq!( + project_current_work(&store)? + .proposal_modeling + .expect("terminal proposal remains current until admission") + .action, + EpiphanyProposalModelingContinuationAction::Review + ); + let proposal_commit = accept_proposal_modeling_result( + &store, + &proposal_launch.job_id, + "2026-08-17T00:00:13Z", + )?; + assert_eq!( + proposal_commit.invariant_owner, + "Modeling.proposal_frontier" + ); + assert!(project_current_work(&store)?.proposal_modeling.is_none()); + let mut accepted_cache = crate::runtime_spine_cache(&store)?; + accepted_cache.pull_all_backing_stores()?; + assert!( + accepted_cache + .get::(crate::THREAD_STATE_KEY)? + .is_none() + ); Ok(()) } } diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index f85c2baa..a8ebdbae 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -1145,7 +1145,6 @@ pub use runtime_spine::runtime_latest_repo_frontier_relinquishment; pub use runtime_spine::runtime_mind_gateway_review; pub use runtime_spine::runtime_mind_state_commit_receipt; pub use runtime_spine::runtime_modeling_semantic_projection_input; -pub use runtime_spine::runtime_pending_repo_frontier_proposal_modeling_request; pub use runtime_spine::runtime_registered_document_types; pub use runtime_spine::runtime_reorient_worker_result; pub use runtime_spine::runtime_repo_frontier_execution_amendment; diff --git a/epiphany-core/src/resident_self.rs b/epiphany-core/src/resident_self.rs index 1b7a2d2b..5ad71646 100644 --- a/epiphany-core/src/resident_self.rs +++ b/epiphany-core/src/resident_self.rs @@ -1208,8 +1208,10 @@ pub fn ingest_resident_self_domain_pressure( // Runtime request order is the single scheduler: expose pressure only for // its current head, then let that request's exact launch binding reveal // the next one on a later ingestion cycle. - if let Some(selection) = - crate::runtime_pending_repo_frontier_proposal_modeling_request(runtime_store)? + if let Some(selection) = crate::project_current_work(runtime_store)? + .proposal_modeling + .filter(|work| work.action == crate::EpiphanyProposalModelingContinuationAction::Launch) + .map(|work| work.request) { inserted += usize::from(enqueue_resident_self_pressure_idempotent( resident_store, @@ -1365,6 +1367,19 @@ pub(crate) fn resident_self_safe_continuation_action( } }); } + if let Some(action) = + crate::proposal_modeling_continuation_action_for_job(runtime_store, job_id)? + { + return Ok(match action { + crate::EpiphanyProposalModelingContinuationAction::Launch => { + Some("launchModeling".to_string()) + } + crate::EpiphanyProposalModelingContinuationAction::Wait => None, + crate::EpiphanyProposalModelingContinuationAction::Review => { + Some("reviewModelingResult".to_string()) + } + }); + } } } let direct = matches!( @@ -1503,48 +1518,18 @@ fn resident_self_failed_receipt_typed_continuation_action( else { return Ok(None); }; - let mut runtime = crate::runtime_spine_cache(runtime_store)?; - runtime.pull_all_backing_stores()?; - let thread = runtime - .get::(crate::THREAD_STATE_KEY)? - .ok_or_else(|| anyhow!("typed continuation requires authoritative thread state"))?; - let state = thread.state()?; - if thread.thread_id != receipt.thread_id { - return Err(anyhow!( - "failed coordinator receipt typed continuation crossed thread authority" - )); - } - let links = state - .runtime_links - .iter() - .filter(|link| { - link.binding_id == crate::EPIPHANY_MODELING_ROLE_BINDING_ID - && link.runtime_job_id == evidence.job_id - }) - .count(); - if links != 1 { - return Err(anyhow!( - "typed proposal fulfillment does not own exactly one current Modeling job link" - )); - } - let acceptances = state - .acceptance_receipts - .iter() - .filter(|accepted| { - accepted.result_id == evidence.result_id - && accepted.job_id == evidence.job_id - && accepted.binding_id == crate::EPIPHANY_MODELING_ROLE_BINDING_ID - && accepted.surface == "roleAccept" - && accepted.role_id == "modeling" - && accepted.status == "accepted" - }) - .count(); - if acceptances > 1 { - return Err(anyhow!( - "typed proposal fulfillment has multiple Modeling acceptance authorities" - )); - } - Ok((acceptances == 0).then(|| "reviewModelingResult".to_string())) + Ok( + match crate::proposal_modeling_continuation_action_for_job(runtime_store, &evidence.job_id)? + { + Some(crate::EpiphanyProposalModelingContinuationAction::Review) => { + Some("reviewModelingResult".to_string()) + } + Some(crate::EpiphanyProposalModelingContinuationAction::Launch) => { + Some("launchModeling".to_string()) + } + Some(crate::EpiphanyProposalModelingContinuationAction::Wait) | None => None, + }, + ) } pub fn ingest_resident_self_coordinator_continuation_pressure( diff --git a/epiphany-core/src/runtime_spine.rs b/epiphany-core/src/runtime_spine.rs index d1cc332a..a899a66d 100644 --- a/epiphany-core/src/runtime_spine.rs +++ b/epiphany-core/src/runtime_spine.rs @@ -5151,7 +5151,7 @@ pub struct RuntimeTypedFulfillmentEvidence { pub request_id: String, } -fn validate_proposal_modeling_worker_fulfillment( +pub(crate) fn validate_proposal_modeling_worker_fulfillment( cache: &CultCache, result: &EpiphanyRuntimeRoleWorkerResult, ) -> Result<()> { @@ -5774,12 +5774,9 @@ pub fn put_repo_frontier_work_proposal( if identity.runtime_id != proposal.runtime_id { return Err(anyhow!("proposal runtime identity mismatch")); } - let thread = cache - .get::(crate::THREAD_STATE_KEY)? - .ok_or_else(|| anyhow!("proposal intake requires authoritative thread state"))?; - if thread.thread_id != proposal.thread_id { - return Err(anyhow!("proposal thread identity mismatch")); - } + // The proposal's thread is immutable creation provenance. Runtime identity + // owns intake; no mutable coordinator incarnation may admit or reject the + // same semantic proposal. put_immutable_planning_entry(store_path.as_ref(), &proposal.proposal_id, proposal) } @@ -8279,42 +8276,6 @@ pub fn runtime_repo_frontier_planning_eligibility( }) } -/// Returns the oldest selected proposal that has not yet been claimed by a -/// Modeling launch. Selection is already explicit Self authority; several -/// Imagination options may therefore form a queue without asking this -/// projection to prefer one proposal over another. Stable request order owns -/// scheduling only and prevents the CLI from becoming a second routing owner. -pub fn runtime_pending_repo_frontier_proposal_modeling_request( - runtime_store: impl AsRef, -) -> Result> { - let runtime_store = runtime_store.as_ref(); - let mut cache = runtime_spine_cache(runtime_store)?; - cache.pull_all_backing_stores()?; - require_identity(&cache)?; - let launches = cache.get_all::()?; - let mut pending = cache - .get_all::()? - .into_iter() - .filter_map(|request| { - if validate_repo_frontier_proposal_modeling_request(&request).is_err() - || launches - .iter() - .any(|launch| launch.proposal_modeling_request_id == request.request_id) - { - None - } else { - Some(request) - } - }) - .collect::>(); - pending.sort_by(|a, b| { - a.selected_at - .cmp(&b.selected_at) - .then_with(|| a.request_id.cmp(&b.request_id)) - }); - Ok(pending.into_iter().next()) -} - /// Read-only Self projection over the existing typed frontier-planning chain. /// It never creates a request or decision; each mutating stage remains owned by /// its established commit primitive. diff --git a/epiphany-core/src/surfaces/coordinator.rs b/epiphany-core/src/surfaces/coordinator.rs index 1118ddbb..d129b0b0 100644 --- a/epiphany-core/src/surfaces/coordinator.rs +++ b/epiphany-core/src/surfaces/coordinator.rs @@ -1,6 +1,7 @@ use epiphany_core::EpiphanyCrrcAction; use epiphany_core::EpiphanyCrrcSceneAction; use epiphany_core::EpiphanyCrrcStateStatus; +use epiphany_core::EpiphanyProposalModelingContinuationAction; use epiphany_core::EpiphanyReorientFindingInterpretation; use epiphany_core::EpiphanyRoleBoardLane; use epiphany_core::EpiphanyRoleFindingInterpretation; @@ -94,7 +95,7 @@ pub fn derive_coordinator_status( hands_frontier_ready: input.hands_frontier_ready, research_continuation_action: input.research_continuation_action, frontier_planning_stage: input.frontier_planning_stage, - proposal_modeling_request_ready: input.proposal_modeling_request_ready, + proposal_modeling_action: input.proposal_modeling_action, body_modeling_work_ready: input.body_modeling_work_ready, body_modeling_review_ready: input.body_modeling_review_ready, }); @@ -696,15 +697,33 @@ pub fn recommend_coordinator_action( | RepoFrontierPlanningLifecycleStage::Terminal => {} } - if input.proposal_modeling_request_ready { - return build( - EpiphanyCoordinatorAction::LaunchModeling, - Some(EpiphanyCoordinatorRoleId::Modeling), - Some(EpiphanyCoordinatorSceneAction::RoleLaunch), - false, - true, - "An explicitly selected typed user proposal is waiting for its single Modeling launch; route that authority before generic regather or stale lane repair.", - ); + if let Some(action) = input.proposal_modeling_action { + return match action { + EpiphanyProposalModelingContinuationAction::Launch => build( + EpiphanyCoordinatorAction::LaunchModeling, + Some(EpiphanyCoordinatorRoleId::Modeling), + Some(EpiphanyCoordinatorSceneAction::RoleLaunch), + false, + true, + "The oldest unresolved proposal request is ready for its exact Modeling attempt.", + ), + EpiphanyProposalModelingContinuationAction::Wait => build( + EpiphanyCoordinatorAction::WaitForModelingResult, + Some(EpiphanyCoordinatorRoleId::Modeling), + Some(EpiphanyCoordinatorSceneAction::RoleResult), + false, + false, + "The exact proposal Modeling attempt is still running.", + ), + EpiphanyProposalModelingContinuationAction::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 { @@ -1248,6 +1267,7 @@ pub fn coordinator_automation_action( | EpiphanyCoordinatorAction::LaunchResearch | EpiphanyCoordinatorAction::ReviewResearchResult | EpiphanyCoordinatorAction::LaunchModeling + | EpiphanyCoordinatorAction::WaitForModelingResult | EpiphanyCoordinatorAction::ReviewModelingResult | EpiphanyCoordinatorAction::LaunchVerification | EpiphanyCoordinatorAction::ReviewVerificationResult @@ -1388,7 +1408,7 @@ mod tests { hands_frontier_ready: false, research_continuation_action: None, frontier_planning_stage: RepoFrontierPlanningLifecycleStage::Unavailable, - proposal_modeling_request_ready: false, + proposal_modeling_action: None, body_modeling_work_ready: false, body_modeling_review_ready: false, } @@ -1469,7 +1489,7 @@ mod tests { fn selected_user_proposal_preempts_generic_regather() { let decision = recommend_coordinator_action(EpiphanyCoordinatorInput { recommendation: recommendation(EpiphanyCrrcAction::RegatherManually), - proposal_modeling_request_ready: true, + proposal_modeling_action: Some(EpiphanyProposalModelingContinuationAction::Launch), ..input() }); assert_eq!(decision.action, EpiphanyCoordinatorAction::LaunchModeling); diff --git a/epiphany-core/src/surfaces/coordinator_contract.rs b/epiphany-core/src/surfaces/coordinator_contract.rs index 38ae4628..3155b1fe 100644 --- a/epiphany-core/src/surfaces/coordinator_contract.rs +++ b/epiphany-core/src/surfaces/coordinator_contract.rs @@ -6,6 +6,7 @@ use super::EpiphanyPressure; use super::EpiphanyPressureLevel; use super::EpiphanyReorientAction; use super::EpiphanyRoleBoardLane; +use crate::EpiphanyProposalModelingContinuationAction; use crate::RepoFrontierPlanningLifecycleStage; use crate::RepoFrontierResearchContinuationAction; use serde::{Deserialize, Serialize}; @@ -59,6 +60,7 @@ pub enum EpiphanyCoordinatorAction { LaunchResearch, ReviewResearchResult, LaunchModeling, + WaitForModelingResult, ReviewModelingResult, LaunchVerification, ReviewVerificationResult, @@ -164,8 +166,8 @@ pub struct EpiphanyCoordinatorInput { /// 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, - /// True when an explicitly selected user proposal has no Modeling launch. - pub proposal_modeling_request_ready: bool, + /// Exact current action for the oldest unresolved proposal Modeling request. + pub proposal_modeling_action: Option, pub body_modeling_work_ready: bool, pub body_modeling_review_ready: bool, } @@ -218,7 +220,7 @@ pub struct EpiphanyCoordinatorStatusInput { pub hands_frontier_ready: bool, pub research_continuation_action: Option, pub frontier_planning_stage: RepoFrontierPlanningLifecycleStage, - pub proposal_modeling_request_ready: bool, + pub proposal_modeling_action: Option, pub body_modeling_work_ready: bool, pub body_modeling_review_ready: bool, }