diff --git a/epiphany-core/src/bin/epiphany-frontier-proposal.rs b/epiphany-core/src/bin/epiphany-frontier-proposal.rs index f59324d0..dde3461d 100644 --- a/epiphany-core/src/bin/epiphany-frontier-proposal.rs +++ b/epiphany-core/src/bin/epiphany-frontier-proposal.rs @@ -1,12 +1,14 @@ use anyhow::{Context, Result, anyhow, bail}; -use epiphany_core::{EpiphanyCoordinatorService, RepoFrontierUserProposalInput}; +use epiphany_core::{ + RepoFrontierUserProposalInput, intake_user_repo_frontier_proposal, + select_repo_frontier_work_proposal_for_modeling, +}; use serde_json::json; use std::{collections::BTreeMap, path::PathBuf}; fn main() -> Result<()> { let args = Args::parse(std::env::args().skip(1))?; - let service = EpiphanyCoordinatorService::new(&args.store); - let proposal = service.intake_user_repo_frontier_proposal(RepoFrontierUserProposalInput { + let proposal = intake_user_repo_frontier_proposal(&args.store, RepoFrontierUserProposalInput { proposal_id: args.required("--proposal-id")?, source_actor: args.required("--source-actor")?, source_ref: args.required("--source-ref")?, @@ -24,7 +26,8 @@ fn main() -> Result<()> { proposed_at: args.required("--proposed-at")?, private_state_included: false, })?; - let selection = service.select_repo_frontier_proposal_for_modeling( + let selection = select_repo_frontier_work_proposal_for_modeling( + &args.store, &proposal.proposal_id, &args.required("--selected-at")?, )?; diff --git a/epiphany-core/src/bin/epiphany-persona-feedback-causal-smoke.rs b/epiphany-core/src/bin/epiphany-persona-feedback-causal-smoke.rs index 79819833..67031e51 100644 --- a/epiphany-core/src/bin/epiphany-persona-feedback-causal-smoke.rs +++ b/epiphany-core/src/bin/epiphany-persona-feedback-causal-smoke.rs @@ -2,7 +2,7 @@ use anyhow::{Context, Result, bail}; use epiphany_core::*; use epiphany_state_model::{ EpiphanyMemoryDomain, EpiphanyMemoryLifecycle, EpiphanyMemoryNode, EpiphanyMemoryNodeKind, - EpiphanyMemoryProfile, EpiphanyThreadState, + EpiphanyMemoryProfile, }; use std::{ collections::{BTreeMap, BTreeSet}, @@ -76,41 +76,16 @@ fn main() -> Result<()> { { bail!("consideration lost classified source provenance"); } - let mut runtime = runtime_spine_cache(&runtime_store)?; - runtime.pull_all_backing_stores()?; - let state = runtime - .get::(THREAD_STATE_KEY)? - .context("fixture runtime lost its current thread state")? - .state()?; - let launch = build_epiphany_imagination_consideration_launch_request( - "fixture-thread", - Some(state.revision), - Some(30), - &state, - request.request_id.clone(), - ) - .map_err(anyhow::Error::msg)?; - let job = format!("fixture-imagination-{}", feedback.feedback_id); - let plan = plan_coordinator_job_launch( - &state, - &launch, + let job_id = launch_current_imagination_consideration_work( &runtime_store, - format!("launcher-{job}"), - job.clone(), - )?; - let committed = commit_coordinator_job_launch( - &runtime_store, - "fixture-thread", - &state, - &launch, - &plan, - AT.into(), + &request.request_id, + AT, )?; let candidate = ImaginationConsiderationCandidate { schema_version: IMAGINATION_CONSIDERATION_CANDIDATE_SCHEMA_VERSION.into(), candidate_id: imagination_consideration_candidate_id_for_launch( &request.request_id, - &committed.backend_job_id, + &job_id, ), request_id: request.request_id.clone(), feedback_id: request.feedback_id.clone(), @@ -135,21 +110,6 @@ fn main() -> Result<()> { contract: IMAGINATION_CONSIDERATION_CANDIDATE_CONTRACT.into(), }; validate_imagination_consideration_candidate(&request, &candidate)?; - let mut runtime = runtime_spine_cache(&runtime_store)?; - runtime.pull_all_backing_stores()?; - let current = runtime - .get::(THREAD_STATE_KEY)? - .context("fixture runtime lost launched thread state")? - .state()?; - EpiphanyCoordinatorService::new(&runtime_store).interrupt_job( - "fixture-thread", - ¤t, - EpiphanyJobInterruptRequest { - expected_revision: Some(current.revision), - binding_id: committed.binding_id, - reason: Some("fixture advances to the next classified feedback".into()), - }, - )?; } for (path, original) in before { if bytes(&path)? != original { @@ -171,13 +131,6 @@ fn seed_fixture_runtime(store: &Path) -> Result<()> { created_at: AT.into(), }, )?; - let state = EpiphanyThreadState::default(); - let mut cache = runtime_spine_cache(store)?; - cache.put( - THREAD_STATE_KEY, - &EpiphanyThreadStateEntry::from_state("fixture-thread", &state)?, - )?; - drop(cache); let seed = EpiphanyRepoModelSeed::new( "fixture-model-seed", "fixture-model", diff --git a/epiphany-core/src/bin/epiphany-public-source-gate-probe.rs b/epiphany-core/src/bin/epiphany-public-source-gate-probe.rs index 7df4d914..2efa5c43 100644 --- a/epiphany-core/src/bin/epiphany-public-source-gate-probe.rs +++ b/epiphany-core/src/bin/epiphany-public-source-gate-probe.rs @@ -78,29 +78,78 @@ fn prepare_authority_family(store: &Path) -> Result) -> std::fmt::Result { - match self { - Self::InvalidRequest(message) | Self::Store(message) => formatter.write_str(message), - } - } -} - -impl std::error::Error for EpiphanyCoordinatorAdmissionError {} - -/// The Epiphany-native owner of coordinator state. -/// -/// Codex compatibility surfaces may translate requests into calls on this -/// service, but they do not receive a persistence hook or retain an independent -/// state opinion. -#[derive(Debug, Clone)] -pub struct EpiphanyRoleAcceptanceUpdate { - pub state_update: EpiphanyStateUpdate, - pub applied_patch: EpiphanyRoleStatePatchDocument, - pub changed_fields: Vec, - pub accepted_receipt_id: String, - pub accepted_observation_id: String, - pub accepted_evidence_id: String, - pub mind_review: MindGatewayReview, -} - -#[derive(Debug, Clone)] -pub struct EpiphanyNativeRoleAcceptance { - pub state: EpiphanyThreadState, - pub finding: EpiphanyRoleFindingInterpretation, - pub update: EpiphanyRoleAcceptanceUpdate, -} - -pub fn accept_coordinator_role_finding( - store: &Path, - thread_id: &str, - state: &EpiphanyThreadState, - role_id: EpiphanyRoleResultRoleId, - binding_id: &str, - expected_revision: Option, - reference_turn_id: Option, - accepted_at: String, - nonce: &str, -) -> anyhow::Result { - if role_id == EpiphanyRoleResultRoleId::Research { - return Err(anyhow::anyhow!( - "generic role acceptance cannot admit Research; the exact frontier Research current-work owner must commit it" - )); - } - if role_id == EpiphanyRoleResultRoleId::Verification { - return Err(anyhow::anyhow!( - "generic role acceptance cannot admit Verification; the exact frontier Verification current-work owner must commit it" - )); - } - let snapshot = read_role_result_snapshot(Some(state), Some(store), role_id, binding_id); - if snapshot.status != EpiphanyCoordinatorRoleResultStatus::Completed { - return Err(anyhow::anyhow!( - "role finding is not completed: {}", - snapshot.note - )); - } - let finding = snapshot - .finding - .ok_or_else(|| anyhow::anyhow!("completed role result has no typed finding"))?; - let label = role_label_lower(role_id); - let update = build_native_role_acceptance_update( - expected_revision, - role_id, - binding_id, - &finding, - format!("ev-{label}-{nonce}"), - format!("obs-{label}-{nonce}"), - accepted_at.clone(), - ) - .map_err(anyhow::Error::msg)?; - let contract = acceptance_launch_contract_for_binding(store, state, binding_id, "role") - .map_err(|error| anyhow::anyhow!(error.to_string()))?; - let available = vec![MIND_GATEWAY_REVIEW_TYPE.to_string()]; - let prerequisites = Vec::new(); - enforce_acceptance_receipt_proofs( - &contract, - &role_acceptance_claimed_effects(role_id, &update.changed_fields), - &available, - &role_acceptance_enforceable_receipts(role_id), - ) - .map_err(|error| anyhow::anyhow!(error.to_string()))?; - let next_state = apply_coordinator_state_update_to_state( - state, - update.state_update.clone(), - reference_turn_id, - )?; - if role_id == EpiphanyRoleResultRoleId::Modeling { - let result_id = finding - .runtime_result_id - .as_deref() - .ok_or_else(|| anyhow::anyhow!("Modeling finding has no runtime result id"))?; - let job_id = finding - .runtime_job_id - .as_deref() - .ok_or_else(|| anyhow::anyhow!("Modeling finding has no runtime job id"))?; - let result = runtime_role_worker_result(store, job_id)? - .ok_or_else(|| anyhow::anyhow!("Modeling runtime result is missing"))?; - if result.result_id != result_id { - return Err(anyhow::anyhow!("Modeling finding/result identity mismatch")); - } - let is_body_modeling = result.proposal_modeling_request_id.is_none() - && result.repo_frontier_modeling_request_id.is_none(); - if is_body_modeling { - crate::accept_body_modeling_result(store, job_id, &accepted_at)?; - return Ok(EpiphanyNativeRoleAcceptance { - state: state.clone(), - finding, - update, - }); - } else if result.proposal_modeling_request_id.is_some() { - crate::accept_proposal_modeling_result(store, job_id, &accepted_at)?; - return Ok(EpiphanyNativeRoleAcceptance { - state: state.clone(), - finding, - update, - }); - } else { - crate::accept_frontier_verdict_modeling_result(store, job_id, &accepted_at)?; - return Ok(EpiphanyNativeRoleAcceptance { - state: state.clone(), - finding, - update, - }); - } - } - let commit = mind_state_commit_receipt( - format!("mind-commit-{}", update.accepted_receipt_id), - &update.mind_review, - next_state.revision, - update - .changed_fields - .iter() - .map(|field| format!("{field:?}")) - .collect(), - accepted_at, - ); - commit_state_with_mind_witness( - store, - thread_id, - state, - &next_state, - &update.mind_review, - &commit, - &prerequisites, - )?; - Ok(EpiphanyNativeRoleAcceptance { - state: next_state, - finding, - update, - }) -} - -pub fn completed_role_finding( - runtime_store_path: Option<&Path>, - state: &EpiphanyThreadState, - role_id: EpiphanyRoleResultRoleId, - binding_id: &str, -) -> Result { - let Some(link) = latest_runtime_link(state, binding_id) else { - return if state - .job_bindings - .iter() - .any(|binding| binding.id == binding_id) - { - Err(EpiphanyCoordinatorAdmissionError::InvalidRequest( - "role findings without runtime-spine results are unsupported; accept only typed runtime-spine results".to_string(), - )) - } else { - Err(EpiphanyCoordinatorAdmissionError::InvalidRequest(format!( - "epiphany role binding {binding_id:?} was not found" - ))) - }; - }; - let snapshot = read_runtime_role_result(runtime_store_path, &link.runtime_job_id, role_id); - if snapshot.status != EpiphanyCoordinatorRoleResultStatus::Completed { - return Err(EpiphanyCoordinatorAdmissionError::InvalidRequest(format!( - "cannot accept role result while worker status is {:?}", - snapshot.status - ))); - } - let store = runtime_store_path.ok_or_else(|| { - EpiphanyCoordinatorAdmissionError::InvalidRequest( - "cannot accept completed role worker without a loaded runtime-spine store".to_string(), - ) - })?; - load_launch_organ_contract(store, &link.runtime_job_id, "role")?; - snapshot.finding.ok_or_else(|| { - EpiphanyCoordinatorAdmissionError::InvalidRequest( - "cannot accept completed role worker because no typed runtime-spine result was recorded" - .to_string(), - ) - }) -} - -pub fn load_launch_organ_contract( - runtime_store_path: &Path, - job_id: &str, - expected_document_kind: &str, -) -> Result { - let request = runtime_worker_launch_request(runtime_store_path, job_id).map_err(|error| { - EpiphanyCoordinatorAdmissionError::Store(format!( - "failed to read worker launch request for runtime job {job_id:?}: {error}" - )) - })?; - let request = request.ok_or_else(|| { - EpiphanyCoordinatorAdmissionError::InvalidRequest(format!( - "cannot accept runtime job {job_id:?} without its typed worker launch request" - )) - })?; - if request.document_kind != expected_document_kind { - return Err(EpiphanyCoordinatorAdmissionError::InvalidRequest(format!( - "cannot accept runtime job {job_id:?}: launch document kind {:?} does not match expected {expected_document_kind:?}", - request.document_kind - ))); - } - if request.organ_launch_contract.dependencies.is_empty() - || request - .organ_launch_contract - .receipt_proof_profiles - .is_empty() - { - return Err(EpiphanyCoordinatorAdmissionError::InvalidRequest(format!( - "cannot accept runtime job {job_id:?}: worker launch request has no organ dependency/proof-profile contract" - ))); - } - if !request - .organ_launch_contract - .receipt_proof_profiles - .iter() - .any(|profile| { - profile.effect_kind == EpiphanyReceiptEffectKind::StateAdmission - && profile - .required_before_promotion_document_types - .iter() - .any(|document_type| document_type == MIND_GATEWAY_REVIEW_TYPE) - }) - { - return Err(EpiphanyCoordinatorAdmissionError::InvalidRequest(format!( - "cannot accept runtime job {job_id:?}: worker launch contract has no state-admission proof profile requiring Mind review" - ))); - } - Ok(request.organ_launch_contract) -} - -pub fn acceptance_launch_contract_for_binding( - runtime_store_path: &Path, - state: &EpiphanyThreadState, - binding_id: &str, - expected_document_kind: &str, -) -> Result { - let link = latest_runtime_link(state, binding_id).ok_or_else(|| { - EpiphanyCoordinatorAdmissionError::InvalidRequest(format!( - "cannot prove receipt profile for binding {binding_id:?}: no runtime link exists" - )) - })?; - load_launch_organ_contract( - runtime_store_path, - &link.runtime_job_id, - expected_document_kind, - ) -} - -pub fn enforce_acceptance_receipt_proofs( - contract: &EpiphanyLaunchOrganContract, - claimed_effects: &[EpiphanyReceiptEffectKind], - available_document_types: &[String], - enforceable_document_types: &[String], -) -> Result<(), EpiphanyCoordinatorAdmissionError> { - let evaluations = evaluate_receipt_proof_profiles( - contract, - claimed_effects, - available_document_types, - enforceable_document_types, - ); - let errors = receipt_proof_evaluation_errors(&evaluations); - if errors.is_empty() { - Ok(()) - } else { - Err(EpiphanyCoordinatorAdmissionError::InvalidRequest(format!( - "receipt proof profile rejected state admission: {}", - errors.join("; ") - ))) - } -} - -pub fn role_acceptance_claimed_effects( - role_id: EpiphanyRoleResultRoleId, - changed_fields: &[EpiphanyStateUpdatedField], -) -> Vec { - let mut effects = vec![EpiphanyReceiptEffectKind::StateAdmission]; - if changed_fields.iter().any(|field| { - matches!( - field, - EpiphanyStateUpdatedField::Evidence | EpiphanyStateUpdatedField::Observations - ) - }) { - effects.push(EpiphanyReceiptEffectKind::EvidencePromotion); - } - if role_id == EpiphanyRoleResultRoleId::Verification { - effects.push(EpiphanyReceiptEffectKind::Verification); - } - effects -} - -pub fn role_acceptance_enforceable_receipts(role_id: EpiphanyRoleResultRoleId) -> Vec { - let mut receipts = vec![MIND_GATEWAY_REVIEW_TYPE.to_string()]; - if role_id == EpiphanyRoleResultRoleId::Research { - receipts.push(SUBSTRATE_GATE_REPO_ACCESS_GRANT_RECEIPT_TYPE.to_string()); - receipts.push(EYES_EVIDENCE_PACKET_TYPE.to_string()); - } else if role_id == EpiphanyRoleResultRoleId::Verification { - receipts.push(SOUL_VERDICT_RECEIPT_TYPE.to_string()); - } - receipts -} - -pub fn coordinator_acceptance_cache(store_path: &Path) -> anyhow::Result { - let mut cache = runtime_spine_cache(store_path)?; - cache.pull_all_backing_stores()?; - Ok(cache) -} - -pub fn read_accepted_coordinator_state( - store_path: &Path, -) -> anyhow::Result> { - let cache = coordinator_acceptance_cache(store_path)?; - cache - .get::(THREAD_STATE_KEY)? - .map(|entry| entry.state()) - .transpose() -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum EpiphanyAcceptancePrerequisite { - Continuity(ContinuityRecoveryReceipt), -} - -fn commit_state_with_mind_witness( - store_path: &Path, - thread_id: &str, - expected_state: &EpiphanyThreadState, - state: &EpiphanyThreadState, - mind_review: &MindGatewayReview, - commit_receipt: &MindStateCommitReceipt, - prerequisites: &[EpiphanyAcceptancePrerequisite], -) -> anyhow::Result { - if commit_receipt.gateway_id != mind_review.gateway_id { - return Err(anyhow::anyhow!( - "Mind commit receipt gateway {:?} does not match review {:?}", - commit_receipt.gateway_id, - mind_review.gateway_id - )); - } - if commit_receipt.state_revision != state.revision { - return Err(anyhow::anyhow!( - "Mind commit receipt revision {} does not match state revision {}", - commit_receipt.state_revision, - state.revision - )); - } - let mut cache = coordinator_state_transaction::open_coordinator_state_transaction( - store_path, - expected_state, - )?; - let (review_envelope, _) = cache.prepare_entry(&mind_review.gateway_id, mind_review)?; - let (commit_envelope, _) = cache.prepare_entry(&commit_receipt.receipt_id, commit_receipt)?; - let mut batch = vec![review_envelope, commit_envelope]; - for prerequisite in prerequisites { - let envelope = match prerequisite { - EpiphanyAcceptancePrerequisite::Continuity(document) => { - cache.prepare_entry(&document.receipt_id, document)?.0 - } - }; - batch.push(envelope); - } - coordinator_state_transaction::commit_coordinator_state_transaction( - &mut cache, - thread_id, - state, - batch, - Vec::new(), - ) -} - -pub fn build_native_role_acceptance_update( - expected_revision: Option, - role_id: EpiphanyRoleResultRoleId, - binding_id: &str, - finding: &EpiphanyRoleFindingInterpretation, - accepted_evidence_id: String, - accepted_observation_id: String, - accepted_at: String, -) -> Result { - let mut patch = finding.state_patch.clone().unwrap_or_default(); - let errors = match role_id { - EpiphanyRoleResultRoleId::Imagination => imagination_role_state_patch_policy_errors(&patch), - EpiphanyRoleResultRoleId::Modeling => modeling_role_state_patch_policy_errors(&patch), - EpiphanyRoleResultRoleId::Research => research_role_state_patch_policy_errors(&patch), - EpiphanyRoleResultRoleId::Verification => { - patch = EpiphanyRoleStatePatchDocument::default(); - Vec::new() - } - EpiphanyRoleResultRoleId::Implementation | EpiphanyRoleResultRoleId::Reorientation => { - return Err(format!( - "role {role_id:?} cannot be accepted through roleAccept" - )); - } - }; - if matches!( - role_id, - EpiphanyRoleResultRoleId::Imagination | EpiphanyRoleResultRoleId::Research - ) && finding.state_patch.is_none() - { - return Err("completed role finding did not include a reviewable statePatch".to_string()); - } - if !errors.is_empty() { - return Err(format!( - "{} role state patch is not acceptable: {}", - role_label_lower(role_id), - errors.join("; ") - )); - } - - let projected_fields = changed_fields_from_patch(&patch) - .iter() - .map(|field| format!("{field:?}")) - .collect(); - let mind_review = mind_review_role_acceptance(binding_id, role_id, finding, &patch); - mind_review_allows_state(&mind_review)?; - let bundle = build_role_acceptance_bundle( - binding_id, - EpiphanyRoleAcceptanceFinding { - role_id, - verdict: finding.verdict.clone(), - summary: finding.summary.clone(), - next_safe_move: finding.next_safe_move.clone(), - files_inspected: finding.files_inspected.clone(), - runtime_result_id: finding.runtime_result_id.clone(), - runtime_job_id: finding.runtime_job_id.clone(), - projected_fields, - }, - accepted_evidence_id, - accepted_observation_id, - accepted_at, - )?; - let accepted_receipt_id = bundle.accepted_receipt_id.clone(); - let accepted_observation_id = bundle.accepted_observation_id.clone(); - let accepted_evidence_id = bundle.accepted_evidence_id.clone(); - patch.evidence.push(bundle.evidence); - patch.observations.push(bundle.observation); - patch.acceptance_receipts.push(bundle.receipt); - let changed_fields = changed_fields_from_patch(&patch); - Ok(EpiphanyRoleAcceptanceUpdate { - state_update: state_update_from_patch(expected_revision, patch.clone()), - applied_patch: patch, - changed_fields, - accepted_receipt_id, - accepted_observation_id, - accepted_evidence_id, - mind_review, - }) -} - -fn state_update_from_patch( - expected_revision: Option, - patch: EpiphanyRoleStatePatchDocument, -) -> EpiphanyStateUpdate { - EpiphanyStateUpdate { - expected_revision, - objective: patch.objective, - active_subgoal_id: patch.active_subgoal_id, - subgoals: patch.subgoals, - invariants: patch.invariants, - graphs: patch.graphs, - graph_frontier: patch.graph_frontier, - graph_checkpoint: patch.graph_checkpoint, - scratch: patch.scratch, - investigation_checkpoint: patch.investigation_checkpoint, - job_bindings: patch.job_bindings, - acceptance_receipts: patch.acceptance_receipts, - runtime_links: patch.runtime_links, - observations: patch.observations, - evidence: patch.evidence, - churn: patch.churn, - mode: patch.mode, - planning: patch.planning, - } -} - -pub fn state_update_from_role_patch( - expected_revision: Option, - patch: EpiphanyRoleStatePatchDocument, -) -> EpiphanyStateUpdate { - state_update_from_patch(expected_revision, patch) -} - -fn changed_fields_from_patch( - patch: &EpiphanyRoleStatePatchDocument, -) -> Vec { - changed_fields(&state_update_from_patch(None, patch.clone())) -} - -fn role_label_lower(role_id: EpiphanyRoleResultRoleId) -> &'static str { - match role_id { - EpiphanyRoleResultRoleId::Imagination => "imagination", - EpiphanyRoleResultRoleId::Modeling => "modeling", - EpiphanyRoleResultRoleId::Research => "research", - EpiphanyRoleResultRoleId::Verification => "verification", - EpiphanyRoleResultRoleId::Implementation => "implementation", - EpiphanyRoleResultRoleId::Reorientation => "reorientation", - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn completed_finding_admission_refuses_missing_binding() { - let error = completed_role_finding( - None, - &EpiphanyThreadState::default(), - EpiphanyRoleResultRoleId::Modeling, - "modeling-worker", - ) - .expect_err("missing binding must not become an acceptable finding"); - assert_eq!( - error, - EpiphanyCoordinatorAdmissionError::InvalidRequest( - "epiphany role binding \"modeling-worker\" was not found".to_string() - ) - ); - } - - #[test] - fn state_and_mind_witness_publish_in_one_acceptance_snapshot() -> anyhow::Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("acceptance.cc"); - let state = EpiphanyThreadState { - revision: 7, - objective: Some("Atomic acceptance".to_string()), - ..Default::default() - }; - let review = MindGatewayReview { - schema_version: MIND_GATEWAY_REVIEW_SCHEMA_VERSION.to_string(), - gateway_id: "mind-review-7".to_string(), - source_kind: "role".to_string(), - source_role_id: "modeling".to_string(), - decision: MindGatewayDecision::Accept, - allowed_effects: vec!["state".to_string()], - refused_effects: Vec::new(), - reasons: Vec::new(), - contract: "test".to_string(), - }; - let receipt = mind_state_commit_receipt( - "mind-commit-7".to_string(), - &review, - 7, - vec!["Objective".to_string()], - "2026-07-11T00:00:00Z".to_string(), - ); - commit_state_with_mind_witness(&store, "thread-7", &state, &state, &review, &receipt, &[])?; - - let cache = coordinator_acceptance_cache(&store)?; - assert_eq!( - cache - .get_required::(THREAD_STATE_KEY)? - .state()? - .objective - .as_deref(), - Some("Atomic acceptance") - ); - assert_eq!( - cache.get_required::("mind-review-7")?, - review - ); - assert_eq!( - cache.get_required::("mind-commit-7")?, - receipt - ); - Ok(()) - } - - #[test] - fn invalid_witness_cannot_publish_state() -> anyhow::Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("acceptance.cc"); - let state = EpiphanyThreadState { - revision: 3, - ..Default::default() - }; - let review = MindGatewayReview { - schema_version: MIND_GATEWAY_REVIEW_SCHEMA_VERSION.to_string(), - gateway_id: "review-3".to_string(), - source_kind: "role".to_string(), - source_role_id: "modeling".to_string(), - decision: MindGatewayDecision::Accept, - allowed_effects: Vec::new(), - refused_effects: Vec::new(), - reasons: Vec::new(), - contract: "test".to_string(), - }; - let receipt = mind_state_commit_receipt( - "commit-4".to_string(), - &review, - 4, - Vec::new(), - "2026-07-11T00:00:00Z".to_string(), - ); - assert!( - commit_state_with_mind_witness( - &store, - "thread-3", - &state, - &state, - &review, - &receipt, - &[], - ) - .is_err() - ); - assert!(!store.exists()); - Ok(()) - } - - #[test] - fn prerequisite_receipt_shares_acceptance_snapshot() -> anyhow::Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("acceptance-eyes.cc"); - let state = EpiphanyThreadState { - revision: 9, - ..Default::default() - }; - let review = MindGatewayReview { - schema_version: MIND_GATEWAY_REVIEW_SCHEMA_VERSION.to_string(), - gateway_id: "review-9".to_string(), - source_kind: "role".to_string(), - source_role_id: "research".to_string(), - decision: MindGatewayDecision::Accept, - allowed_effects: Vec::new(), - refused_effects: Vec::new(), - reasons: Vec::new(), - contract: "test".to_string(), - }; - let commit = mind_state_commit_receipt( - "commit-9".to_string(), - &review, - 9, - Vec::new(), - "2026-07-11T00:00:00Z".to_string(), - ); - let continuity = ContinuityRecoveryReceipt { - schema_version: CONTINUITY_RECOVERY_RECEIPT_SCHEMA_VERSION.to_string(), - receipt_id: "continuity-9".to_string(), - source_result_id: "result-9".to_string(), - source_job_id: "job-9".to_string(), - binding_id: "reorientation-worker".to_string(), - mode: "resume".to_string(), - checkpoint_still_valid: "true".to_string(), - summary: "looked".to_string(), - next_safe_move: "continue".to_string(), - files_inspected: Vec::new(), - emitted_at: "2026-07-11T00:00:00Z".to_string(), - contract: "test".to_string(), - }; - commit_state_with_mind_witness( - &store, - "thread-9", - &state, - &state, - &review, - &commit, - &[EpiphanyAcceptancePrerequisite::Continuity( - continuity.clone(), - )], - )?; - let cache = coordinator_acceptance_cache(&store)?; - assert_eq!( - cache.get_required::("continuity-9")?, - continuity - ); - assert!( - cache - .get::(THREAD_STATE_KEY)? - .is_some() - ); - assert!(cache.get::("commit-9")?.is_some()); - Ok(()) - } -} diff --git a/epiphany-core/src/coordinator_interrupt.rs b/epiphany-core/src/coordinator_interrupt.rs deleted file mode 100644 index 17c3f546..00000000 --- a/epiphany-core/src/coordinator_interrupt.rs +++ /dev/null @@ -1,115 +0,0 @@ -use crate::*; -use anyhow::{Result, anyhow}; -use epiphany_state_model::EpiphanyThreadState; -use std::path::Path; - -pub fn interrupt_coordinator_job( - store: &Path, - thread_id: &str, - state: &EpiphanyThreadState, - request: EpiphanyJobInterruptRequest, -) -> Result { - if let Some(persisted) = read_coordinator_state(store)? - && persisted != *state - { - return Err(anyhow!( - "authoritative coordinator state changed before interrupt commit" - )); - } - if request.binding_id.trim().is_empty() { - return Err(anyhow!( - "epiphany job interrupt binding_id must be non-empty" - )); - } - if let Some(expected) = request.expected_revision - && expected != state.revision - { - return Err(anyhow!( - "epiphany state revision mismatch: expected {expected}, found {}", - state.revision - )); - } - let binding_index = state - .job_bindings - .iter() - .position(|binding| binding.id == request.binding_id) - .ok_or_else(|| { - anyhow!( - "epiphany job binding {:?} was not found", - request.binding_id - ) - })?; - let reason = request - .reason - .as_deref() - .map(str::trim) - .filter(|reason| !reason.is_empty()) - .unwrap_or( - "No active heartbeat turn is currently bound; launch explicitly to resume specialist work.", - ); - let applied = apply_coordinator_state_update( - store, - thread_id, - EpiphanyStateUpdate { - expected_revision: request.expected_revision, - job_bindings: Some(clear_epiphany_job_binding_backend( - state.job_bindings.clone(), - binding_index, - reason, - )), - ..Default::default() - }, - None, - )?; - Ok(EpiphanyJobInterruptResult { - epiphany_state: applied.state, - binding_id: request.binding_id, - cancel_requested: false, - interrupted_thread_ids: Vec::new(), - }) -} - -#[cfg(test)] -mod tests { - use super::*; - use epiphany_state_model::EpiphanyJobBinding; - - #[test] - fn native_interrupt_updates_the_canonical_binding_once() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("interrupt.cc"); - let state = EpiphanyThreadState { - job_bindings: vec![EpiphanyJobBinding { - id: "modeling-worker".to_string(), - kind: epiphany_state_model::EpiphanyJobKind::Specialist, - scope: "model".to_string(), - owner_role: "modeling".to_string(), - authority_scope: Some("model".to_string()), - linked_subgoal_ids: Vec::new(), - linked_graph_node_ids: Vec::new(), - blocking_reason: None, - }], - ..Default::default() - }; - let result = interrupt_coordinator_job( - &store, - "thread-1", - &state, - EpiphanyJobInterruptRequest { - expected_revision: Some(0), - binding_id: "modeling-worker".to_string(), - reason: Some("operator interrupted".to_string()), - }, - )?; - assert_eq!(result.epiphany_state.revision, 1); - assert_eq!( - result.epiphany_state.job_bindings[0] - .blocking_reason - .as_deref(), - Some("operator interrupted") - ); - assert!(!result.cancel_requested); - assert_eq!(read_coordinator_state(&store)?, Some(result.epiphany_state)); - Ok(()) - } -} diff --git a/epiphany-core/src/coordinator_launch.rs b/epiphany-core/src/coordinator_launch.rs deleted file mode 100644 index 3d225a13..00000000 --- a/epiphany-core/src/coordinator_launch.rs +++ /dev/null @@ -1,616 +0,0 @@ -use crate::*; -use anyhow::{Result, anyhow}; -use cultcache_rs::{CultCache, CultCacheEnvelope}; -use epiphany_state_model::{EpiphanyRuntimeLink, EpiphanyThreadState}; -use sha2::{Digest, Sha256}; -use std::path::Path; - -#[derive(Debug, Clone)] -pub struct EpiphanyCoordinatorJobLaunchPlan { - pub launcher_job_id: String, - pub backend_job_id: String, - pub planning_state: EpiphanyThreadState, - pub heartbeat_plan: RuntimeSpineHeartbeatLaunchPlan, - pub state_update: EpiphanyStateUpdate, -} - -pub fn commit_coordinator_job_launch( - store: &Path, - thread_id: &str, - current_state: &EpiphanyThreadState, - request: &EpiphanyJobLaunchRequest, - plan: &EpiphanyCoordinatorJobLaunchPlan, - created_at: 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" - )); - } - if request.owner_role == EPIPHANY_RESEARCH_OWNER_ROLE - || request.repo_frontier_research_request_id.is_some() - { - return Err(anyhow!( - "frontier Research 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 { - None - }; - let mut cache = - coordinator_state_transaction::open_coordinator_state_transaction(store, current_state)?; - commit_coordinator_job_launch_in_cache( - &mut cache, - thread_id, - current_state, - request, - plan, - created_at, - body_basis, - Vec::new(), - ) -} - -fn commit_coordinator_job_launch_in_cache( - cache: &mut coordinator_state_transaction::CoordinatorStateTransaction, - thread_id: &str, - current_state: &EpiphanyThreadState, - request: &EpiphanyJobLaunchRequest, - plan: &EpiphanyCoordinatorJobLaunchPlan, - created_at: String, - repository_body_observation_basis: Option, - injected_envelopes: Vec, -) -> Result { - if thread_id != request.launch_document.thread_id() { - return Err(anyhow!( - "coordinator commit thread id must match typed launch document" - )); - } - if let Some(admitted_thread) = - cache.get::(crate::THREAD_STATE_KEY)? - { - if admitted_thread.thread_id != thread_id || admitted_thread.state()? != *current_state { - return Err(anyhow!( - "coordinator launch carrier must use the current admitted thread" - )); - } - } - let runtime_identity = cache - .get::(RUNTIME_IDENTITY_KEY)? - .ok_or_else(|| anyhow!("coordinator launch requires runtime identity"))?; - let next_state = - apply_coordinator_state_update_to_state(current_state, plan.state_update.clone(), None)?; - let mut effective_launch_document = request.launch_document.clone(); - match &mut effective_launch_document { - EpiphanyWorkerLaunchDocument::Role(document) - if request.owner_role == EPIPHANY_MODELING_OWNER_ROLE => - { - if document.repository_body_observation_basis.is_some() { - return Err(anyhow!( - "caller-prepopulated repository Body basis is forbidden" - )); - } - document.repository_body_observation_basis = - Some(repository_body_observation_basis.ok_or_else(|| { - anyhow!("Modeling launch commit requires a repository Body basis") - })?); - } - EpiphanyWorkerLaunchDocument::Role(document) => { - if document.repository_body_observation_basis.is_some() - || repository_body_observation_basis.is_some() - { - return Err(anyhow!( - "non-Modeling launch cannot carry a repository Body basis" - )); - } - } - EpiphanyWorkerLaunchDocument::Reorient(_) => { - if repository_body_observation_basis.is_some() { - return Err(anyhow!( - "reorient launch cannot carry a repository Body basis" - )); - } - } - } - let imagination_consideration_launch = if let Some(request_id) = - request.imagination_consideration_request_id.as_deref() - { - let (consideration, identity, attempt_ordinal) = - validate_imagination_consideration_launch(cache, current_state, request, request_id)?; - let model = crate::repo_model_documents::assemble_repo_model_view_from_cache(cache)?; - crate::EpiphanyRepoModelBasis { - projection_digest: consideration.model_projection_digest.clone(), - source_documents: consideration.model_source_documents.clone(), - } - .validate_against_cache(cache)?; - let projection = ImaginationConsiderationContextProjection::new(&consideration, &model); - match &mut effective_launch_document { - EpiphanyWorkerLaunchDocument::Role(document) => { - if document.proposal_modeling_context.is_some() - || document.frontier_planning_context.is_some() - || document.frontier_plan_mind_context.is_some() - { - return Err(anyhow!("consideration context is exclusive")); - } - document.objective = None; - document.dynamic_prompt_context = - Some(render_imagination_consideration_prompt(&consideration)?); - document.imagination_consideration_context = Some(projection); - } - EpiphanyWorkerLaunchDocument::Reorient(_) => { - return Err(anyhow!("reorient cannot carry consideration context")); - } - } - let hash = format!( - "{:x}", - Sha256::digest(rmp_serde::to_vec_named(&effective_launch_document)?) - ); - Some((consideration, identity, hash, attempt_ordinal)) - } else { - None - }; - let admitted_model_direction_consideration_launch = if let Some(request_id) = request - .admitted_model_direction_consideration_request_id - .as_deref() - { - let consideration = validate_admitted_model_direction_consideration_launch( - cache, - current_state, - request, - request_id, - )?; - let model = crate::repo_model_documents::assemble_repo_model_view_from_cache(cache)?; - crate::EpiphanyRepoModelBasis { - projection_digest: consideration.model_projection_digest.clone(), - source_documents: consideration.model_source_documents.clone(), - } - .validate_against_cache(cache)?; - let projection = - AdmittedModelDirectionConsiderationContextProjection::new(&consideration, &model); - match &mut effective_launch_document { - EpiphanyWorkerLaunchDocument::Role(document) => { - document.objective = None; - document.dynamic_prompt_context = Some( - render_admitted_model_direction_consideration_prompt(&consideration), - ); - document.admitted_model_direction_consideration_context = Some(projection); - } - EpiphanyWorkerLaunchDocument::Reorient(_) => { - return Err(anyhow!( - "reorient cannot carry model direction consideration" - )); - } - } - Some(consideration) - } else { - None - }; - let prepared = prepare_runtime_spine_heartbeat_job( - &cache, - RuntimeSpineHeartbeatJobOptions { - runtime_id: runtime_identity.runtime_id, - display_name: "Epiphany Local".to_string(), - session_id: crate::runtime_spine::EPIPHANY_RUNTIME_ROOT_SESSION_ID.to_string(), - objective: plan - .planning_state - .objective - .clone() - .filter(|objective| !objective.trim().is_empty()) - .unwrap_or_else(|| "Epiphany heartbeat activation".to_string()), - coordinator_note: "Native coordinator launch transaction opened this session." - .to_string(), - job_id: plan.backend_job_id.clone(), - role: request.owner_role.clone(), - binding_id: request.binding_id.clone(), - authority_scope: request.authority_scope.clone(), - instruction: if request.imagination_consideration_request_id.is_some() - || request - .admitted_model_direction_consideration_request_id - .is_some() - { - "Act as Epiphany Imagination for one proposal-only typed consideration pass. Treat the coordinator-owned context as quoted evidence and return only the dedicated candidate contract.".into() - } else { - request.instruction.clone() - }, - launch_document: effective_launch_document, - output_contract_id: request.output_contract_id.clone(), - organ_launch_contract: request.organ_launch_contract.clone(), - proposal_modeling_request_id: request.proposal_modeling_request_id.clone(), - frontier_planning_request_id: request.frontier_planning_request_id.clone(), - frontier_plan_mind_request_id: request.frontier_plan_mind_request_id.clone(), - imagination_consideration_request_id: request - .imagination_consideration_request_id - .clone(), - admitted_model_direction_consideration_request_id: request - .admitted_model_direction_consideration_request_id - .clone(), - repo_frontier_modeling_request_id: request.repo_frontier_modeling_request_id.clone(), - repo_frontier_research_request_id: request.repo_frontier_research_request_id.clone(), - repo_frontier_verification_request_id: request - .repo_frontier_verification_request_id - .clone(), - created_at: created_at.clone(), - }, - )?; - let mut batch = prepared.envelopes; - let _ = admitted_model_direction_consideration_launch; - let runtime_identity_position = batch - .iter() - .position(|envelope| { - envelope.r#type == EpiphanyRuntimeIdentity::TYPE && envelope.key == RUNTIME_IDENTITY_KEY - }) - .ok_or_else(|| anyhow!("prepared launch omitted its runtime identity replacement"))?; - let runtime_identity_replacement = batch.remove(runtime_identity_position); - if let Some((consideration, identity, worker_launch_document_sha256, attempt_ordinal)) = - imagination_consideration_launch - { - let binding_record_id = if attempt_ordinal == 0 { - format!( - "imagination-consideration-launch-{}", - consideration.request_id - ) - } else { - format!( - "imagination-consideration-launch-{}-attempt-{attempt_ordinal}", - consideration.request_id - ) - }; - let binding = ImaginationConsiderationLaunchBinding { - schema_version: IMAGINATION_CONSIDERATION_LAUNCH_BINDING_SCHEMA_VERSION.into(), - binding_record_id, - request_id: consideration.request_id, - job_id: plan.backend_job_id.clone(), - binding_id: request.binding_id.clone(), - runtime_id: identity.runtime_id, - thread_id: consideration.thread_id, - launched_at: created_at.clone(), - worker_launch_document_sha256, - }; - if cache - .get::(&binding.binding_record_id)? - .is_some() - { - return Err(anyhow!( - "consideration request is already bound to a launch" - )); - } - batch.push(cache.prepare_entry(&binding.binding_record_id, &binding)?.0); - } - if matches!( - request.binding_id.as_str(), - EPIPHANY_RESEARCH_ROLE_BINDING_ID - | crate::EPIPHANY_MODELING_ROLE_BINDING_ID - | crate::EPIPHANY_VERIFICATION_ROLE_BINDING_ID - ) { - let grant = substrate_gate_repo_access_grant_for_launch( - format!("substrate-grant-{}", plan.backend_job_id), - plan.backend_job_id.clone(), - request, - created_at, - ); - batch.push(cache.prepare_entry(&grant.receipt_id, &grant)?.0); - } - batch.extend(injected_envelopes); - coordinator_state_transaction::commit_coordinator_state_transaction( - cache, - thread_id, - &next_state, - batch, - vec![runtime_identity_replacement], - )?; - Ok(EpiphanyJobLaunchResult { - epiphany_state: next_state, - binding_id: request.binding_id.clone(), - launcher_job_id: plan.launcher_job_id.clone(), - backend_job_id: plan.backend_job_id.clone(), - }) -} - -pub fn plan_coordinator_job_launch( - state: &EpiphanyThreadState, - request: &EpiphanyJobLaunchRequest, - runtime_store: &Path, - 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_planning_projection, - caller_mind_projection, - caller_body_basis, - ) = match &request.launch_document { - EpiphanyWorkerLaunchDocument::Role(document) => ( - document.proposal_modeling_context.as_ref(), - document.frontier_planning_context.as_ref(), - document.frontier_plan_mind_context.as_ref(), - document.repository_body_observation_basis.as_ref(), - ), - EpiphanyWorkerLaunchDocument::Reorient(_) => (None, None, None, None), - }; - if caller_body_basis.is_some() { - return Err(anyhow!( - "caller-prepopulated repository Body basis is forbidden; coordinator commit owns observation" - )); - } - if caller_proposal_projection.is_some() { - return Err(anyhow!( - "caller-prepopulated proposal Modeling context is forbidden; coordinator commit owns projection" - )); - } - if caller_planning_projection.is_some() { - return Err(anyhow!( - "caller-prepopulated frontier planning context is forbidden; coordinator commit owns projection" - )); - } - if caller_mind_projection.is_some() { - return Err(anyhow!( - "caller-prepopulated Mind decision context is forbidden; coordinator commit owns projection" - )); - } - if [ - request.proposal_modeling_request_id.is_some(), - request.frontier_planning_request_id.is_some(), - request.frontier_plan_mind_request_id.is_some(), - ] - .into_iter() - .filter(|present| *present) - .count() - > 1 - { - return Err(anyhow!( - "specialized authority launches are mutually exclusive" - )); - } - if let Some(expected) = request.expected_revision - && expected != state.revision - { - return Err(anyhow!( - "epiphany state revision mismatch: expected {expected}, found {}", - state.revision - )); - } - if request.frontier_planning_request_id.is_some() - || request.frontier_plan_mind_request_id.is_some() - { - return Err(anyhow!( - "frontier Planning and plan Mind launches are owned by keyed current work" - )); - } else if request.owner_role == EPIPHANY_MODELING_OWNER_ROLE { - // Ordinary Modeling launches remain valid, but carry no proposal authority. - } - let completed_prior_link = - terminal_runtime_link_for_binding(state, &request.binding_id, runtime_store)?; - let mut planning_state = state.clone(); - if let Some(link) = completed_prior_link.clone() { - planning_state.runtime_links.insert(0, link); - } - let heartbeat_plan = plan_runtime_spine_heartbeat_launch( - &planning_state, - RuntimeSpineHeartbeatLaunchPlanOptions { - binding_id: request.binding_id.clone(), - kind: request.kind, - scope: request.scope.clone(), - owner_role: request.owner_role.clone(), - authority_scope: request.authority_scope.clone(), - linked_subgoal_ids: request.linked_subgoal_ids.clone(), - linked_graph_node_ids: request.linked_graph_node_ids.clone(), - instruction: request.instruction.clone(), - launch_document: request.launch_document.clone(), - output_contract_id: request.output_contract_id.clone(), - organ_launch_contract: request.organ_launch_contract.clone(), - max_runtime_seconds: request.max_runtime_seconds, - runtime_job_id: backend_job_id.clone(), - }, - )?; - let job_bindings = replace_or_append_epiphany_job_binding( - state.job_bindings.clone(), - heartbeat_plan.binding.clone(), - ); - let mut runtime_links = vec![heartbeat_plan.runtime_link.clone()]; - if let Some(link) = completed_prior_link { - runtime_links.push(link); - } - let state_update = EpiphanyStateUpdate { - expected_revision: request.expected_revision, - job_bindings: Some(job_bindings), - runtime_links, - ..Default::default() - }; - let errors = epiphany_state_update_validation_errors(state, &state_update); - if !errors.is_empty() { - return Err(anyhow!( - "invalid Epiphany job launch patch: {}", - errors.join("; ") - )); - } - Ok(EpiphanyCoordinatorJobLaunchPlan { - launcher_job_id, - backend_job_id, - planning_state, - heartbeat_plan, - state_update, - }) -} - -fn validate_imagination_consideration_launch( - cache: &CultCache, - state: &EpiphanyThreadState, - launch: &EpiphanyJobLaunchRequest, - request_id: &str, -) -> Result<( - ImaginationConsiderationRequest, - EpiphanyRuntimeIdentity, - u64, -)> { - if match &launch.launch_document { - EpiphanyWorkerLaunchDocument::Role(document) => { - document.imagination_consideration_context.is_some() - } - EpiphanyWorkerLaunchDocument::Reorient(_) => false, - } { - return Err(anyhow!("caller cannot author consideration context")); - } - if launch.owner_role != EPIPHANY_IMAGINATION_OWNER_ROLE - || launch.binding_id != EPIPHANY_IMAGINATION_ROLE_BINDING_ID - || launch.frontier_planning_request_id.is_some() - { - return Err(anyhow!( - "consideration requires an exclusive Imagination launch" - )); - } - let request = cache - .get::(request_id)? - .ok_or_else(|| anyhow!("consideration request does not exist"))?; - validate_current_imagination_consideration_request(cache, &request)?; - let identity = cache - .get::(RUNTIME_IDENTITY_KEY)? - .ok_or_else(|| anyhow!("consideration requires runtime identity"))?; - let persisted = cache - .get::(crate::THREAD_STATE_KEY)? - .ok_or_else(|| anyhow!("consideration requires thread state"))?; - if request.runtime_id != identity.runtime_id - || request.thread_id.is_empty() - || persisted.state()? != *state - || launch.launch_document.thread_id() != persisted.thread_id - { - return Err(anyhow!("consideration launch provenance mismatch")); - } - let prior_bindings = cache - .get_all::()? - .iter() - .filter(|binding| binding.request_id == request_id) - .cloned() - .collect::>(); - for binding in prior_bindings { - if !worker_attempt_is_retryable_terminal_failure(cache, &binding.job_id)? { - return Err(anyhow!("consideration request already bound")); - } - } - let attempt_ordinal = u64::try_from( - cache - .get_all::()? - .iter() - .filter(|binding| binding.request_id == request_id) - .count(), - ) - .map_err(|_| anyhow!("consideration attempt ordinal overflow"))?; - Ok((request, identity, attempt_ordinal)) -} - -fn validate_admitted_model_direction_consideration_launch( - cache: &CultCache, - state: &EpiphanyThreadState, - launch: &EpiphanyJobLaunchRequest, - request_id: &str, -) -> Result { - if match &launch.launch_document { - EpiphanyWorkerLaunchDocument::Role(document) => document - .admitted_model_direction_consideration_context - .is_some(), - EpiphanyWorkerLaunchDocument::Reorient(_) => false, - } { - return Err(anyhow!("caller cannot author model direction context")); - } - if launch.owner_role != EPIPHANY_IMAGINATION_OWNER_ROLE - || launch.binding_id != EPIPHANY_IMAGINATION_ROLE_BINDING_ID - || launch.imagination_consideration_request_id.is_some() - || launch.frontier_planning_request_id.is_some() - || launch.frontier_plan_mind_request_id.is_some() - || launch.proposal_modeling_request_id.is_some() - { - return Err(anyhow!( - "model direction consideration requires an exclusive Imagination launch" - )); - } - let request = cache - .get::(request_id)? - .ok_or_else(|| anyhow!("model direction consideration request does not exist"))?; - validate_current_admitted_model_direction_consideration_request(cache, &request)?; - let identity = cache - .get::(RUNTIME_IDENTITY_KEY)? - .ok_or_else(|| anyhow!("model direction consideration requires runtime identity"))?; - let persisted = cache - .get::(crate::THREAD_STATE_KEY)? - .ok_or_else(|| anyhow!("model direction consideration requires thread state"))?; - if request.runtime_id != identity.runtime_id - || request.thread_id.is_empty() - || persisted.state()? != *state - || launch.launch_document.thread_id() != persisted.thread_id - { - return Err(anyhow!("model direction consideration provenance mismatch")); - } - let prior_launches = cache - .get_all::()? - .iter() - .filter(|worker| { - worker - .admitted_model_direction_consideration_request_id - .as_deref() - == Some(request_id) - }) - .cloned() - .collect::>(); - for worker in prior_launches { - if !worker_attempt_is_retryable_terminal_failure(cache, &worker.job_id)? { - return Err(anyhow!("model direction consideration already bound")); - } - } - Ok(request) -} - -fn worker_attempt_is_retryable_terminal_failure(cache: &CultCache, job_id: &str) -> Result { - cache - .get::(&format!( - "runtime-worker-process-{job_id}" - ))? - .map(|claim| Ok(crate::WorkerProcessStatus::parse(&claim.status)?.allows_retry())) - .unwrap_or(Ok(false)) -} - -fn terminal_runtime_link_for_binding( - state: &EpiphanyThreadState, - binding_id: &str, - runtime_store: &Path, -) -> Result> { - let Some(link) = state - .runtime_links - .iter() - .find(|link| link.binding_id == binding_id && !link.runtime_job_id.trim().is_empty()) - else { - return Ok(None); - }; - if link.runtime_result_id.is_some() { - return Ok(None); - } - if let Some(snapshot) = runtime_job_snapshot(runtime_store, &link.runtime_job_id)? - && let Some(result) = snapshot.result - { - let mut terminal = link.clone(); - terminal.id = format!("{}-{}", link.id, result.result_id); - terminal.surface = "runtimeResult".to_string(); - terminal.runtime_result_id = Some(result.result_id); - return Ok(Some(terminal)); - } - let Some(claim) = crate::runtime_worker_process_claim(runtime_store, &link.runtime_job_id)? - else { - return Ok(None); - }; - if !crate::WorkerProcessStatus::parse(&claim.status)?.is_failed_terminal() { - return Ok(None); - } - let terminal_authority_id = claim - .terminal_authority_id - .ok_or_else(|| anyhow!("terminal worker process claim lost its authority id"))?; - let mut terminal = link.clone(); - terminal.id = format!("{}-{}", link.id, terminal_authority_id); - terminal.surface = "runtimeWorkerProcessTerminal".to_string(); - terminal.runtime_result_id = Some(terminal_authority_id); - Ok(Some(terminal)) -} diff --git a/epiphany-core/src/coordinator_objective_intake.rs b/epiphany-core/src/coordinator_objective_intake.rs index 004cfeeb..7464ff52 100644 --- a/epiphany-core/src/coordinator_objective_intake.rs +++ b/epiphany-core/src/coordinator_objective_intake.rs @@ -170,7 +170,7 @@ pub fn intake_user_objective( #[cfg(test)] mod tests { use super::*; - use crate::{EpiphanyThreadStateEntry, RuntimeSpineInitOptions, initialize_runtime_spine}; + use crate::{RuntimeSpineInitOptions, initialize_runtime_spine}; fn input(objective: &str) -> UserObjectiveIntakeInput { UserObjectiveIntakeInput { @@ -203,7 +203,12 @@ mod tests { ); let mut cache = runtime_spine_cache(&store)?; cache.pull_all_backing_stores()?; - assert!(cache.get_all::()?.is_empty()); + assert!( + cache + .snapshot_envelopes() + .iter() + .all(|envelope| envelope.r#type != "epiphany.thread_state") + ); let repeated = intake_user_objective(&store, input(" Map the machine "))?; assert!(!repeated.changed); diff --git a/epiphany-core/src/coordinator_results.rs b/epiphany-core/src/coordinator_results.rs index 316fbf7f..cf16ef4d 100644 --- a/epiphany-core/src/coordinator_results.rs +++ b/epiphany-core/src/coordinator_results.rs @@ -1,18 +1,6 @@ use crate::*; -use epiphany_state_model::EpiphanyRuntimeLink; -use epiphany_state_model::EpiphanyThreadState; use std::path::Path; -pub(crate) fn latest_runtime_link<'a>( - state: &'a EpiphanyThreadState, - binding_id: &str, -) -> Option<&'a EpiphanyRuntimeLink> { - state - .runtime_links - .iter() - .find(|link| link.binding_id == binding_id && !link.runtime_job_id.trim().is_empty()) -} - #[derive(Debug, Clone)] pub struct EpiphanyCoordinatorRoleResultSnapshot { pub status: EpiphanyCoordinatorRoleResultStatus, @@ -26,73 +14,6 @@ pub struct EpiphanyCoordinatorReorientResultSnapshot { pub finding: Option, pub note: String, } -pub fn read_role_result_snapshot( - state: Option<&EpiphanyThreadState>, - runtime_store_path: Option<&Path>, - role_id: EpiphanyRoleResultRoleId, - binding_id: &str, -) -> EpiphanyCoordinatorRoleResultSnapshot { - let Some(state) = state else { - return role_snapshot( - role_id, - EpiphanyCoordinatorRoleResultStatus::MissingState, - None, - None, - ); - }; - if let Some(link) = latest_runtime_link(state, binding_id) { - return read_runtime_role_result(runtime_store_path, &link.runtime_job_id, role_id); - } - if state - .job_bindings - .iter() - .any(|binding| binding.id == binding_id) - { - role_snapshot( - role_id, - EpiphanyCoordinatorRoleResultStatus::BackendUnavailable, - None, - Some( - "Role binding has no runtime-spine job id; launch a runtime-linked role worker for typed results.", - ), - ) - } else { - role_snapshot( - role_id, - EpiphanyCoordinatorRoleResultStatus::MissingBinding, - None, - None, - ) - } -} - -pub fn read_reorient_result_snapshot( - state: Option<&EpiphanyThreadState>, - runtime_store_path: Option<&Path>, - binding_id: &str, -) -> EpiphanyCoordinatorReorientResultSnapshot { - let Some(state) = state else { - return reorient_snapshot(EpiphanyCrrcResultStatus::MissingState, None, None); - }; - if let Some(link) = latest_runtime_link(state, binding_id) { - return read_runtime_reorient_result(runtime_store_path, &link.runtime_job_id); - } - if state - .job_bindings - .iter() - .any(|binding| binding.id == binding_id) - { - reorient_snapshot( - EpiphanyCrrcResultStatus::BackendUnavailable, - None, - Some( - "Reorientation binding has no runtime-spine job id; launch a runtime-linked reorient worker for typed results.", - ), - ) - } else { - reorient_snapshot(EpiphanyCrrcResultStatus::MissingBinding, None, None) - } -} pub fn read_runtime_role_result( runtime_store_path: Option<&Path>, diff --git a/epiphany-core/src/coordinator_service.rs b/epiphany-core/src/coordinator_service.rs deleted file mode 100644 index 808f652d..00000000 --- a/epiphany-core/src/coordinator_service.rs +++ /dev/null @@ -1,199 +0,0 @@ -use crate::EpiphanyCoordinatorReorientResultSnapshot; -use crate::EpiphanyCoordinatorRoleResultSnapshot; -use crate::EpiphanyCoordinatorStateApplied; -use crate::EpiphanyJobInterruptRequest; -use crate::EpiphanyJobInterruptResult; -use crate::EpiphanyJobLaunchRequest; -use crate::EpiphanyJobLaunchResult; -use crate::EpiphanyNativeRoleAcceptance; -use crate::EpiphanyRoleResultRoleId; -use crate::EpiphanyStateUpdate; -use crate::accept_coordinator_role_finding; -use crate::apply_coordinator_state_update; -use crate::apply_coordinator_state_update_from_state; -use crate::commit_coordinator_job_launch; -use crate::interrupt_coordinator_job; -use crate::plan_coordinator_job_launch; -use crate::read_coordinator_state; -use crate::read_reorient_result_snapshot; -use crate::read_role_result_snapshot; -use anyhow::Result; -use epiphany_state_model::EpiphanyThreadState; -use std::path::{Path, PathBuf}; - -#[derive(Debug, Clone)] -pub struct EpiphanyCoordinatorService { - store: PathBuf, -} - -impl EpiphanyCoordinatorService { - pub fn new(store: impl Into) -> Self { - Self { - store: store.into(), - } - } - - pub fn store(&self) -> &Path { - &self.store - } - - pub fn intake_user_repo_frontier_proposal( - &self, - input: crate::RepoFrontierUserProposalInput, - ) -> Result { - crate::intake_user_repo_frontier_proposal(&self.store, input) - } - - pub fn intake_user_objective( - &self, - input: crate::UserObjectiveIntakeInput, - ) -> Result { - crate::intake_user_objective(&self.store, input) - } - - pub fn select_repo_frontier_proposal_for_modeling( - &self, - proposal_id: &str, - selected_at: &str, - ) -> Result { - crate::select_repo_frontier_work_proposal_for_modeling( - &self.store, - proposal_id, - selected_at, - ) - } - pub fn state(&self) -> Result> { - read_coordinator_state(&self.store) - } - - pub fn role_result( - &self, - role_id: EpiphanyRoleResultRoleId, - binding_id: &str, - ) -> Result { - let state = self.state()?; - Ok(read_role_result_snapshot( - state.as_ref(), - Some(&self.store), - role_id, - binding_id, - )) - } - - pub fn reorient_result( - &self, - binding_id: &str, - ) -> Result { - let state = self.state()?; - Ok(read_reorient_result_snapshot( - state.as_ref(), - Some(&self.store), - binding_id, - )) - } - - pub fn apply_state_update( - &self, - thread_id: &str, - update: EpiphanyStateUpdate, - reference_turn_id: Option, - ) -> Result { - apply_coordinator_state_update(&self.store, thread_id, update, reference_turn_id) - } - - pub fn apply_state_update_from( - &self, - thread_id: &str, - current_state: &EpiphanyThreadState, - update: EpiphanyStateUpdate, - reference_turn_id: Option, - ) -> Result { - apply_coordinator_state_update_from_state( - &self.store, - thread_id, - current_state, - update, - reference_turn_id, - ) - } - - pub fn launch_job( - &self, - thread_id: &str, - state: &EpiphanyThreadState, - request: &EpiphanyJobLaunchRequest, - launcher_job_id: String, - backend_job_id: String, - created_at: String, - ) -> Result { - let plan = plan_coordinator_job_launch( - state, - request, - &self.store, - launcher_job_id, - backend_job_id, - )?; - commit_coordinator_job_launch(&self.store, thread_id, state, request, &plan, created_at) - } - - pub fn accept_role( - &self, - thread_id: &str, - state: &EpiphanyThreadState, - role_id: EpiphanyRoleResultRoleId, - binding_id: &str, - expected_revision: Option, - reference_turn_id: Option, - accepted_at: String, - nonce: &str, - ) -> Result { - accept_coordinator_role_finding( - &self.store, - thread_id, - state, - role_id, - binding_id, - expected_revision, - reference_turn_id, - accepted_at, - nonce, - ) - } - - pub fn interrupt_job( - &self, - thread_id: &str, - state: &EpiphanyThreadState, - request: EpiphanyJobInterruptRequest, - ) -> Result { - interrupt_coordinator_job(&self.store, thread_id, state, request) - } -} - -#[cfg(test)] -mod tests { - #[test] - fn facade_contains_no_coordinator_policy() { - let source = include_str!("coordinator_service.rs"); - let production = source.split("#[cfg(test)]").next().unwrap_or(source); - assert!( - production.lines().count() < 210, - "coordinator facade regrew into a host brain" - ); - for forbidden in [ - "epiphany_state_update_validation_errors", - "runtime_worker_launch_request", - "mind_review_role_acceptance", - "build_role_acceptance_bundle", - "serde_json", - "thread/epiphany/", - "thread_state_store", - "runtime_spine_store", - ] { - assert!( - !production.contains(forbidden), - "coordinator facade contains policy/protocol marker {forbidden:?}" - ); - } - } -} diff --git a/epiphany-core/src/coordinator_state.rs b/epiphany-core/src/coordinator_state.rs deleted file mode 100644 index b9e24ae2..00000000 --- a/epiphany-core/src/coordinator_state.rs +++ /dev/null @@ -1,200 +0,0 @@ -use crate::EpiphanyStateUpdate; -use crate::EpiphanyStateUpdatedField; -use crate::apply_epiphany_state_update; -use crate::coordinator_state_transaction::commit_coordinator_state_transaction; -use crate::coordinator_state_transaction::open_coordinator_state_transaction; -use crate::epiphany_state_update_validation_errors; -use crate::read_accepted_coordinator_state; -use anyhow::Result; -use anyhow::anyhow; -use epiphany_state_model::EpiphanyThreadState; -use std::path::Path; - -#[derive(Debug, Clone, PartialEq)] -pub struct EpiphanyCoordinatorStateApplied { - pub revision: u64, - pub changed_fields: Vec, - pub state: EpiphanyThreadState, -} - -pub fn read_coordinator_state(store: &Path) -> Result> { - read_accepted_coordinator_state(store) -} - -pub fn apply_coordinator_state_update( - store: &Path, - thread_id: &str, - update: EpiphanyStateUpdate, - reference_turn_id: Option, -) -> Result { - let current = read_coordinator_state(store)?.unwrap_or_default(); - apply_coordinator_state_update_from_state(store, thread_id, ¤t, update, reference_turn_id) -} - -pub fn apply_coordinator_state_update_from_state( - store: &Path, - thread_id: &str, - current_state: &EpiphanyThreadState, - update: EpiphanyStateUpdate, - reference_turn_id: Option, -) -> Result { - let mut cache = open_coordinator_state_transaction(store, current_state)?; - let changed_fields = changed_fields(&update); - let state = apply_coordinator_state_update_to_state(current_state, update, reference_turn_id)?; - commit_coordinator_state_transaction(&mut cache, thread_id, &state, Vec::new(), Vec::new())?; - Ok(EpiphanyCoordinatorStateApplied { - revision: state.revision, - changed_fields, - state, - }) -} - -pub fn apply_coordinator_state_update_to_state( - current_state: &EpiphanyThreadState, - update: EpiphanyStateUpdate, - reference_turn_id: Option, -) -> Result { - if update.is_empty() { - return Err(anyhow!( - "epiphany update patch must contain at least one mutation" - )); - } - if let Some(expected_revision) = update.expected_revision - && expected_revision != current_state.revision - { - return Err(anyhow!( - "epiphany state revision mismatch: expected {expected_revision}, found {}", - current_state.revision - )); - } - let errors = epiphany_state_update_validation_errors(current_state, &update); - if !errors.is_empty() { - return Err(anyhow!( - "invalid epiphany update patch: {}", - errors.join("; ") - )); - } - let mut next_state = current_state.clone(); - apply_epiphany_state_update(&mut next_state, update, reference_turn_id); - Ok(next_state) -} - -pub(crate) fn changed_fields(update: &EpiphanyStateUpdate) -> Vec { - let mut fields = Vec::new(); - macro_rules! field { - ($condition:expr, $field:ident) => { - if $condition { - fields.push(EpiphanyStateUpdatedField::$field); - } - }; - } - field!(update.objective.is_some(), Objective); - field!(update.active_subgoal_id.is_some(), ActiveSubgoalId); - field!(update.subgoals.is_some(), Subgoals); - field!(update.invariants.is_some(), Invariants); - field!(update.graphs.is_some(), Graphs); - field!(update.graph_frontier.is_some(), GraphFrontier); - field!(update.graph_checkpoint.is_some(), GraphCheckpoint); - field!(update.scratch.is_some(), Scratch); - field!( - update.investigation_checkpoint.is_some(), - InvestigationCheckpoint - ); - field!(update.job_bindings.is_some(), JobBindings); - field!(!update.acceptance_receipts.is_empty(), AcceptanceReceipts); - field!(!update.runtime_links.is_empty(), RuntimeLinks); - field!(!update.observations.is_empty(), Observations); - field!(!update.evidence.is_empty(), Evidence); - field!(update.churn.is_some(), Churn); - field!(update.mode.is_some(), Mode); - field!(update.planning.is_some(), Planning); - fields -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn state_owner_writes_and_refuses_stale_revision() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("thread-state.msgpack"); - let first = apply_coordinator_state_update( - &store, - "session-1", - EpiphanyStateUpdate { - expected_revision: Some(0), - objective: Some("Canonical objective".to_string()), - ..Default::default() - }, - None, - )?; - assert_eq!(first.revision, 1); - assert!( - apply_coordinator_state_update( - &store, - "session-1", - EpiphanyStateUpdate { - expected_revision: Some(0), - objective: Some("Stale overwrite".to_string()), - ..Default::default() - }, - None - ) - .is_err() - ); - assert_eq!( - read_coordinator_state(&store)? - .unwrap() - .objective - .as_deref(), - Some("Canonical objective") - ); - Ok(()) - } - - #[test] - fn imported_host_state_seeds_once_then_cannot_override_native_truth() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("imported-state.msgpack"); - let imported = EpiphanyThreadState { - revision: 4, - objective: Some("Imported rollout state".to_string()), - ..Default::default() - }; - let applied = apply_coordinator_state_update_from_state( - &store, - "thread-1", - &imported, - EpiphanyStateUpdate { - expected_revision: Some(4), - objective: Some("Native authority".to_string()), - ..Default::default() - }, - None, - )?; - assert_eq!(applied.revision, 5); - assert!( - apply_coordinator_state_update_from_state( - &store, - "thread-1", - &imported, - EpiphanyStateUpdate { - expected_revision: None, - objective: Some("Stale host overwrite".to_string()), - ..Default::default() - }, - None, - ) - .is_err() - ); - assert_eq!( - read_coordinator_state(&store)? - .unwrap() - .objective - .as_deref(), - Some("Native authority") - ); - Ok(()) - } -} diff --git a/epiphany-core/src/coordinator_state_transaction.rs b/epiphany-core/src/coordinator_state_transaction.rs deleted file mode 100644 index 30ded4ae..00000000 --- a/epiphany-core/src/coordinator_state_transaction.rs +++ /dev/null @@ -1,395 +0,0 @@ -#[cfg(test)] -use crate::runtime_store_backend::RuntimeSpineBackingStore as SingleFileMessagePackBackingStore; -use crate::runtime_store_backend::runtime_spine_backing_store; -use crate::{ - EpiphanyThreadStateEntry, THREAD_STATE_KEY, THREAD_STATE_TYPE, coordinator_acceptance_cache, -}; -use anyhow::{Result, anyhow}; -#[cfg(test)] -use cultcache_rs::CacheBackingStore; -use cultcache_rs::{CultCache, CultCacheEnvelope}; -use epiphany_state_model::EpiphanyThreadState; -use std::ops::{Deref, DerefMut}; -use std::path::{Path, PathBuf}; - -pub(crate) struct CoordinatorStateTransaction { - cache: CultCache, - store: PathBuf, - opening_snapshot: Vec, - expected_state_envelope: Option, -} - -impl Deref for CoordinatorStateTransaction { - type Target = CultCache; - - fn deref(&self) -> &Self::Target { - &self.cache - } -} - -impl DerefMut for CoordinatorStateTransaction { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.cache - } -} - -pub(crate) fn open_coordinator_state_transaction( - store: &Path, - expected_state: &EpiphanyThreadState, -) -> Result { - let cache = coordinator_acceptance_cache(store)?; - let opening_snapshot = cache.snapshot_envelopes(); - let expected_state_envelope = opening_snapshot - .iter() - .find(|entry| entry.r#type == THREAD_STATE_TYPE && entry.key == THREAD_STATE_KEY) - .cloned(); - if let Some(envelope) = &expected_state_envelope { - let entry: EpiphanyThreadStateEntry = rmp_serde::from_slice(&envelope.payload)?; - if entry.state()? != *expected_state { - return Err(anyhow!( - "authoritative coordinator state changed before transaction opened" - )); - } - } - Ok(CoordinatorStateTransaction { - cache, - store: store.to_path_buf(), - opening_snapshot, - expected_state_envelope, - }) -} - -fn same_immutable_content(left: &CultCacheEnvelope, right: &CultCacheEnvelope) -> bool { - left.r#type == right.r#type - && left.key == right.key - && left.payload == right.payload - && left.schema_id == right.schema_id -} - -pub(crate) fn commit_coordinator_state_transaction( - transaction: &mut CoordinatorStateTransaction, - thread_id: &str, - next_state: &EpiphanyThreadState, - companion_envelopes: Vec, - captured_replacements: Vec, -) -> Result { - if companion_envelopes - .iter() - .chain(&captured_replacements) - .any(|envelope| envelope.r#type == THREAD_STATE_TYPE && envelope.key == THREAD_STATE_KEY) - { - return Err(anyhow!( - "coordinator state transaction companions cannot write the canonical state identity" - )); - } - - let state_entry = EpiphanyThreadStateEntry::from_state(thread_id, next_state)?; - let (state_envelope, _) = transaction - .cache - .prepare_entry(THREAD_STATE_KEY, &state_entry)?; - let mut expected = transaction - .expected_state_envelope - .iter() - .cloned() - .collect::>(); - let mut replacements = vec![state_envelope]; - - for companion in companion_envelopes { - let opening = transaction - .opening_snapshot - .iter() - .find(|entry| entry.r#type == companion.r#type && entry.key == companion.key); - if let Some(existing) = opening { - if !same_immutable_content(existing, &companion) { - return Err(anyhow!( - "coordinator state transaction companion identity collision at ({:?}, {:?})", - companion.r#type, - companion.key - )); - } - expected.push(existing.clone()); - replacements.push(existing.clone()); - } else { - replacements.push(companion); - } - } - for replacement in captured_replacements { - let existing = transaction - .opening_snapshot - .iter() - .find(|entry| entry.r#type == replacement.r#type && entry.key == replacement.key) - .ok_or_else(|| { - anyhow!( - "coordinator state transaction captured replacement is absent at ({:?}, {:?})", - replacement.r#type, - replacement.key - ) - })?; - expected.push(existing.clone()); - replacements.push(replacement); - } - - let backing = runtime_spine_backing_store(&transaction.store)?; - if !backing.compare_and_swap_batch(&expected, replacements)? { - return Err(anyhow!( - "coordinator state transaction lost its exact atomic compare-and-swap" - )); - } - Ok(next_state.clone()) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn companion( - transaction: &mut CoordinatorStateTransaction, - key: &str, - thread_id: &str, - state: &EpiphanyThreadState, - ) -> Result { - let entry = EpiphanyThreadStateEntry::from_state(thread_id, state)?; - Ok(transaction.prepare_entry(key, &entry)?.0) - } - - #[test] - fn companion_cannot_impersonate_canonical_state() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("state.cc"); - let state = EpiphanyThreadState::default(); - let mut transaction = open_coordinator_state_transaction(&store, &state)?; - let counterfeit = EpiphanyThreadStateEntry::from_state("counterfeit", &state)?; - let envelope = transaction.prepare_entry(THREAD_STATE_KEY, &counterfeit)?.0; - let error = commit_coordinator_state_transaction( - &mut transaction, - "thread-1", - &state, - vec![envelope], - Vec::new(), - ) - .expect_err("companion state writer must be refused"); - assert!(error.to_string().contains("canonical state identity")); - assert!( - SingleFileMessagePackBackingStore::new(&store) - .pull_all()? - .is_empty() - ); - Ok(()) - } - - #[test] - fn transactions_opened_on_the_same_absent_state_have_one_winner() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("state.cc"); - let state = EpiphanyThreadState::default(); - let mut first = open_coordinator_state_transaction(&store, &state)?; - let mut second = open_coordinator_state_transaction(&store, &state)?; - - commit_coordinator_state_transaction( - &mut first, - "thread-1", - &state, - Vec::new(), - Vec::new(), - )?; - let error = commit_coordinator_state_transaction( - &mut second, - "thread-1", - &state, - Vec::new(), - Vec::new(), - ) - .expect_err("only one transaction may seed an absent canonical identity"); - assert!(error.to_string().contains("compare-and-swap")); - Ok(()) - } - - #[test] - fn absent_store_accepts_an_imported_nondefault_seed_once() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("state.cc"); - let mut imported = EpiphanyThreadState::default(); - imported.revision = 9; - let mut transaction = open_coordinator_state_transaction(&store, &imported)?; - commit_coordinator_state_transaction( - &mut transaction, - "thread-import", - &imported, - Vec::new(), - Vec::new(), - )?; - Ok(()) - } - - #[test] - fn identical_companion_retry_preserves_the_persisted_envelope() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("state.cc"); - let state = EpiphanyThreadState::default(); - let mut first = open_coordinator_state_transaction(&store, &state)?; - let first_companion = companion(&mut first, "immutable-companion", "thread-1", &state)?; - commit_coordinator_state_transaction( - &mut first, - "thread-1", - &state, - vec![first_companion], - Vec::new(), - )?; - let backing = SingleFileMessagePackBackingStore::new(&store); - let persisted_before = backing - .pull_all()? - .into_iter() - .find(|entry| entry.key == "immutable-companion") - .expect("companion persisted"); - - let mut retry = open_coordinator_state_transaction(&store, &state)?; - let retry_companion = companion(&mut retry, "immutable-companion", "thread-1", &state)?; - commit_coordinator_state_transaction( - &mut retry, - "thread-1", - &state, - vec![retry_companion], - Vec::new(), - )?; - let persisted_after = backing - .pull_all()? - .into_iter() - .find(|entry| entry.key == "immutable-companion") - .expect("companion remains persisted"); - assert_eq!(persisted_after, persisted_before); - Ok(()) - } - - #[test] - fn conflicting_companion_retry_writes_nothing() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("state.cc"); - let state = EpiphanyThreadState::default(); - let mut first = open_coordinator_state_transaction(&store, &state)?; - let first_companion = companion(&mut first, "immutable-companion", "thread-1", &state)?; - commit_coordinator_state_transaction( - &mut first, - "thread-1", - &state, - vec![first_companion], - Vec::new(), - )?; - let bytes_before = std::fs::read(&store)?; - - let mut collision = open_coordinator_state_transaction(&store, &state)?; - let conflicting = companion( - &mut collision, - "immutable-companion", - "different-thread", - &state, - )?; - let error = commit_coordinator_state_transaction( - &mut collision, - "thread-1", - &state, - vec![conflicting], - Vec::new(), - ) - .expect_err("immutable companion identity collision must be refused"); - assert!(error.to_string().contains("identity collision")); - assert_eq!(std::fs::read(&store)?, bytes_before); - Ok(()) - } - - #[test] - fn captured_replacement_has_one_exact_snapshot_winner() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("state.cc"); - let state = EpiphanyThreadState::default(); - let mut seed = open_coordinator_state_transaction(&store, &state)?; - let original = companion(&mut seed, "mutable-companion", "original", &state)?; - commit_coordinator_state_transaction( - &mut seed, - "thread-1", - &state, - vec![original], - Vec::new(), - )?; - - let mut first = open_coordinator_state_transaction(&store, &state)?; - let mut second = open_coordinator_state_transaction(&store, &state)?; - let first_replacement = companion(&mut first, "mutable-companion", "winner", &state)?; - let second_replacement = companion(&mut second, "mutable-companion", "loser", &state)?; - commit_coordinator_state_transaction( - &mut first, - "thread-1", - &state, - Vec::new(), - vec![first_replacement], - )?; - let error = commit_coordinator_state_transaction( - &mut second, - "thread-1", - &state, - Vec::new(), - vec![second_replacement], - ) - .expect_err("a captured replacement cannot overwrite a newer envelope"); - assert!(error.to_string().contains("compare-and-swap")); - - let cache = coordinator_acceptance_cache(&store)?; - let persisted = cache.get_required::("mutable-companion")?; - assert_eq!(persisted.thread_id, "winner"); - Ok(()) - } - - #[test] - fn companion_identity_is_polymorphic_type_and_key() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("state.cc"); - let state = EpiphanyThreadState::default(); - let mut transaction = open_coordinator_state_transaction(&store, &state)?; - let typed = companion(&mut transaction, "shared-key", "thread-1", &state)?; - let other_type = CultCacheEnvelope { - key: "shared-key".into(), - r#type: "test.other_type".into(), - payload: vec![1, 2, 3], - stored_at: "2026-07-14T00:00:00Z".into(), - schema_id: Some("test.other_type.v0".into()), - }; - commit_coordinator_state_transaction( - &mut transaction, - "thread-1", - &state, - vec![typed, other_type], - Vec::new(), - )?; - let shared = SingleFileMessagePackBackingStore::new(&store) - .pull_all()? - .into_iter() - .filter(|entry| entry.key == "shared-key") - .collect::>(); - assert_eq!(shared.len(), 2); - assert_ne!(shared[0].r#type, shared[1].r#type); - Ok(()) - } - - #[test] - fn canonical_state_key_has_no_second_production_writer() { - for (name, source) in [ - ("coordinator_state", include_str!("coordinator_state.rs")), - ("coordinator_launch", include_str!("coordinator_launch.rs")), - ( - "coordinator_acceptance", - include_str!("coordinator_acceptance.rs"), - ), - ("thread_state_store", include_str!("thread_state_store.rs")), - ] { - let production = source.split("#[cfg(test)]").next().unwrap_or(source); - assert!( - !production.contains("prepare_entry(THREAD_STATE_KEY") - && !production.contains("put(THREAD_STATE_KEY"), - "{name} regained canonical state write authority" - ); - } - let public_surface = include_str!("lib.rs"); - assert!(!public_surface.contains("write_thread_state_entry")); - assert!(!public_surface.contains("write_thread_state;")); - assert!(!public_surface.contains("commit_state_with_mind_witness")); - } -} diff --git a/epiphany-core/src/current_work.rs b/epiphany-core/src/current_work.rs index 258ccace..84e85da4 100644 --- a/epiphany-core/src/current_work.rs +++ b/epiphany-core/src/current_work.rs @@ -3376,8 +3376,9 @@ mod tests { scheduled_cache.pull_all_backing_stores()?; assert!( scheduled_cache - .get::(crate::THREAD_STATE_KEY)? - .is_none() + .snapshot_envelopes() + .iter() + .all(|envelope| envelope.r#type != "epiphany.thread_state") ); assert!( scheduled_cache @@ -3615,8 +3616,9 @@ mod tests { ); assert!( final_cache - .get::(crate::THREAD_STATE_KEY)? - .is_none() + .snapshot_envelopes() + .iter() + .all(|envelope| envelope.r#type != "epiphany.thread_state") ); let proposal_runtime_launch = final_cache .get::(&proposal_launch.job_id)? @@ -3770,8 +3772,9 @@ mod tests { accepted_cache.pull_all_backing_stores()?; assert!( accepted_cache - .get::(crate::THREAD_STATE_KEY)? - .is_none() + .snapshot_envelopes() + .iter() + .all(|envelope| envelope.r#type != "epiphany.thread_state") ); let model = crate::assemble_repo_model_view(&store)?; @@ -4533,8 +4536,9 @@ mod tests { ); assert!( planning_cache - .get::(crate::THREAD_STATE_KEY)? - .is_none() + .snapshot_envelopes() + .iter() + .all(|envelope| envelope.r#type != "epiphany.thread_state") ); let challenged_plan_store = temp.path().join("challenged-plan.cc"); @@ -4976,8 +4980,9 @@ mod tests { ); assert!( planning_cache - .get::(crate::THREAD_STATE_KEY)? - .is_none() + .snapshot_envelopes() + .iter() + .all(|envelope| envelope.r#type != "epiphany.thread_state") ); // Eyes is its own exact current-work family. It launches from an @@ -5032,8 +5037,9 @@ mod tests { research_cache.pull_all_backing_stores()?; assert!( research_cache - .get::(crate::THREAD_STATE_KEY)? - .is_none() + .snapshot_envelopes() + .iter() + .all(|envelope| envelope.r#type != "epiphany.thread_state") ); let research_launch = research_cache .get::(&research_job)? diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index c7b298d2..e46bcfb0 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -4,15 +4,9 @@ mod agent_utterance_state; pub mod atlas; mod causal_work_identity; mod continuity_gateway; -mod coordinator_acceptance; -mod coordinator_interrupt; -mod coordinator_launch; mod coordinator_launch_context; mod coordinator_objective_intake; mod coordinator_results; -mod coordinator_service; -mod coordinator_state; -mod coordinator_state_transaction; mod cultmesh_integration; mod current_work; mod distillation; @@ -38,7 +32,6 @@ mod persona_turn; mod process_observation; mod promotion; mod prompt_context; -mod proposal; mod public_source_identity; mod reasoning_context; mod reorientation_work; @@ -56,10 +49,8 @@ mod semantic_backend; mod semantic_projector_service; mod soul_gateway; mod state_ledger; -mod state_update; mod substrate_gate; mod surfaces; -mod thread_state_store; mod weksa_interlingua; mod workspace_coverage_process_bootstrap; mod workspace_coverage_process_documents; @@ -200,25 +191,6 @@ pub use agent_utterance_state::derive_agent_utterance_state; pub use atlas::*; pub use causal_work_identity::*; pub use continuity_gateway::*; -pub use coordinator_acceptance::EpiphanyAcceptancePrerequisite; -pub use coordinator_acceptance::EpiphanyCoordinatorAdmissionError; -pub use coordinator_acceptance::EpiphanyNativeRoleAcceptance; -pub use coordinator_acceptance::EpiphanyRoleAcceptanceUpdate; -pub use coordinator_acceptance::accept_coordinator_role_finding; -pub use coordinator_acceptance::acceptance_launch_contract_for_binding; -pub use coordinator_acceptance::build_native_role_acceptance_update; -pub use coordinator_acceptance::completed_role_finding; -pub use coordinator_acceptance::coordinator_acceptance_cache; -pub use coordinator_acceptance::enforce_acceptance_receipt_proofs; -pub use coordinator_acceptance::load_launch_organ_contract; -pub use coordinator_acceptance::read_accepted_coordinator_state; -pub use coordinator_acceptance::role_acceptance_claimed_effects; -pub use coordinator_acceptance::role_acceptance_enforceable_receipts; -pub use coordinator_acceptance::state_update_from_role_patch; -pub use coordinator_interrupt::interrupt_coordinator_job; -pub use coordinator_launch::EpiphanyCoordinatorJobLaunchPlan; -pub use coordinator_launch::commit_coordinator_job_launch; -pub use coordinator_launch::plan_coordinator_job_launch; pub use coordinator_launch_context::EPIPHANY_LOCAL_VERSE_RUNTIME_ID; pub use coordinator_launch_context::append_modeling_repo_model_shape_context; pub use coordinator_launch_context::local_verse_store_path; @@ -237,16 +209,8 @@ pub use coordinator_objective_intake::UserObjectiveIntakeInput; pub use coordinator_objective_intake::intake_user_objective; pub use coordinator_results::EpiphanyCoordinatorReorientResultSnapshot; pub use coordinator_results::EpiphanyCoordinatorRoleResultSnapshot; -pub use coordinator_results::read_reorient_result_snapshot; -pub use coordinator_results::read_role_result_snapshot; pub use coordinator_results::read_runtime_reorient_result; pub use coordinator_results::read_runtime_role_result; -pub use coordinator_service::EpiphanyCoordinatorService; -pub use coordinator_state::EpiphanyCoordinatorStateApplied; -pub use coordinator_state::apply_coordinator_state_update; -pub use coordinator_state::apply_coordinator_state_update_from_state; -pub use coordinator_state::apply_coordinator_state_update_to_state; -pub use coordinator_state::read_coordinator_state; pub use cultcache_rs::CacheBackingStore; pub use cultcache_rs::CultCache; pub use cultcache_rs::CultCacheEnvelope; @@ -962,9 +926,6 @@ pub use promotion::evaluate_promotion; pub use promotion::validate_state_replacement_patch; pub use prompt_context::EpiphanyPromptContextInput; pub use prompt_context::render_epiphany_prompt_context; -pub use proposal::EpiphanyMapProposal; -pub use proposal::EpiphanyMapProposalInput; -pub use proposal::propose_map_update; pub use public_source_identity::ImmutableGithubSource; pub use reasoning_context::*; pub use reorientation_work::*; @@ -1182,10 +1143,6 @@ pub use state_ledger::append_state_evidence; pub use state_ledger::close_state_branch; pub use state_ledger::load_state_ledger; pub use state_ledger::state_ledger_status; -pub use state_update::EpiphanyStateUpdate; -pub use state_update::EpiphanyStateUpdatedField; -pub use state_update::apply_epiphany_state_update; -pub use state_update::epiphany_state_update_validation_errors; pub use substrate_gate::SUBSTRATE_GATE_REPO_ACCESS_GRANT_RECEIPT_SCHEMA_VERSION; pub use substrate_gate::SUBSTRATE_GATE_REPO_ACCESS_GRANT_RECEIPT_TYPE; pub use substrate_gate::SUBSTRATE_GATE_REPO_ACCESS_REFUSAL_RECEIPT_SCHEMA_VERSION; @@ -1332,14 +1289,6 @@ pub use surfaces::research_role_state_patch_policy_errors; pub use surfaces::review_role_self_patch_document; pub use surfaces::role_board_job_status_to_role_status; pub use surfaces::role_self_memory_target; -pub use thread_state_store::EpiphanyThreadStateEntry; -pub use thread_state_store::THREAD_STATE_KEY; -pub use thread_state_store::THREAD_STATE_SCHEMA_VERSION; -pub use thread_state_store::THREAD_STATE_TYPE; -pub use thread_state_store::load_thread_state; -pub use thread_state_store::load_thread_state_entry; -pub use thread_state_store::thread_state_cache; -pub use thread_state_store::validate_thread_state_entry; pub use weksa_interlingua::WEKSA_INTERLINGUA_PACKET_SCHEMA_VERSION; pub use weksa_interlingua::WEKSA_TARGET_LOWERING_RECEIPT_SCHEMA_VERSION; pub use weksa_interlingua::WEKSA_TARGET_LOWERING_REQUEST_SCHEMA_VERSION; diff --git a/epiphany-core/src/proposal.rs b/epiphany-core/src/proposal.rs deleted file mode 100644 index 1764a3ad..00000000 --- a/epiphany-core/src/proposal.rs +++ /dev/null @@ -1,1727 +0,0 @@ -use anyhow::Result; -use anyhow::anyhow; -use epiphany_state_model::EpiphanyChurnState; -use epiphany_state_model::EpiphanyCodeRef; -use epiphany_state_model::EpiphanyEvidenceRecord; -use epiphany_state_model::EpiphanyGraphEdge; -use epiphany_state_model::EpiphanyGraphFrontier; -use epiphany_state_model::EpiphanyGraphNode; -use epiphany_state_model::EpiphanyGraphs; -use epiphany_state_model::EpiphanyObservation; -use epiphany_state_model::EpiphanyThreadState; -use sha1::Digest; -use sha1::Sha1; -use std::collections::HashSet; -use std::path::Path; -use std::path::PathBuf; - -const SUMMARY_LIMIT: usize = 220; -const SEMANTIC_REUSE_MIN_SCORE: usize = 4; -const AUTO_OBSERVATION_SELECTION_LIMIT: usize = 4; - -#[derive(Debug, Clone, PartialEq, Eq)] -struct SelectionQuality { - observation_count: usize, - evidence_count: usize, - source_kinds: Vec, - priority_label: String, - primary_observation_id: String, - primary_observation_summary: String, - semantic_terms: Vec, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum ArchitectureMatchKind { - ExactCodeRef, - SamePath, - DeterministicId, - Semantic, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -struct ArchitectureMatch { - index: usize, - kind: ArchitectureMatchKind, -} - -#[derive(Debug, Default, Clone, PartialEq, Eq)] -struct MapDeltaJudgment { - exact_ref_reuses: usize, - same_path_reuses: usize, - deterministic_id_reuses: usize, - semantic_reuses: usize, - created_nodes: usize, - touched_paths: usize, - selected_observations: usize, - existing_unexplained_writes: bool, -} - -impl MapDeltaJudgment { - fn reused_nodes(&self) -> usize { - self.exact_ref_reuses - + self.same_path_reuses - + self.deterministic_id_reuses - + self.semantic_reuses - } - - fn record_match(&mut self, kind: ArchitectureMatchKind) { - match kind { - ArchitectureMatchKind::ExactCodeRef => self.exact_ref_reuses += 1, - ArchitectureMatchKind::SamePath => self.same_path_reuses += 1, - ArchitectureMatchKind::DeterministicId => self.deterministic_id_reuses += 1, - ArchitectureMatchKind::Semantic => self.semantic_reuses += 1, - } - } - - fn has_broadening_reuse(&self) -> bool { - self.same_path_reuses > 0 || self.semantic_reuses > 0 - } - - fn has_mixed_delta(&self) -> bool { - self.reused_nodes() > 0 && self.created_nodes > 0 - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -struct ObservationSelectionCandidate { - observation_id: String, - score: usize, - index: usize, - path_keys: Vec, -} - -#[derive(Debug, Default, Clone, PartialEq, Eq)] -struct ProposalFocus { - dirty_paths: HashSet, - active_paths: HashSet, - mapped_paths: HashSet, -} - -#[derive(Debug, Clone)] -pub struct EpiphanyMapProposalInput { - pub state: EpiphanyThreadState, - pub observation_ids: Vec, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct EpiphanyMapProposal { - pub observation: EpiphanyObservation, - pub evidence: EpiphanyEvidenceRecord, - pub graphs: EpiphanyGraphs, - pub graph_frontier: EpiphanyGraphFrontier, - pub churn: EpiphanyChurnState, -} - -pub fn propose_map_update(input: EpiphanyMapProposalInput) -> Result { - let observation_ids = proposal_observation_ids(&input.state, input.observation_ids)?; - let observations = select_observations(&input.state, &observation_ids)?; - let selection_quality = evaluate_selection_quality(&input.state, &observations)?; - let code_refs = collect_code_refs(&observations)?; - let code_ref_paths = unique_code_ref_paths(&code_refs); - let fingerprint = fingerprint(&input.state.revision, &observation_ids, &code_refs); - let mut graphs = input.state.graphs.clone(); - let mut active_node_ids = Vec::new(); - let mut delta = MapDeltaJudgment { - touched_paths: code_ref_paths.len(), - selected_observations: selection_quality.observation_count, - existing_unexplained_writes: input - .state - .churn - .as_ref() - .and_then(|churn| churn.unexplained_writes) - .is_some_and(|unexplained_writes| unexplained_writes > 0), - ..Default::default() - }; - - for path in &code_ref_paths { - let path_code_refs = code_refs_for_path(&code_refs, path); - let candidate_node_id = graph_node_id(path); - if let Some(node_match) = find_architecture_node_for_path( - &graphs, - &path_code_refs, - path, - &candidate_node_id, - &selection_quality.semantic_terms, - ) { - let node = &mut graphs.architecture.nodes[node_match.index]; - active_node_ids.push(node.id.clone()); - merge_code_refs(&mut node.code_refs, path_code_refs); - delta.record_match(node_match.kind); - } else { - let node_id = candidate_node_id; - active_node_ids.push(node_id.clone()); - graphs.architecture.nodes.push(EpiphanyGraphNode { - id: node_id, - title: title_from_path(path), - purpose: truncate_chars( - &format!( - "Candidate implementation surface from verified observation: {}", - selection_quality.primary_observation_summary - ), - SUMMARY_LIMIT, - ), - mechanism: Some(format!( - "Proposed from prioritized observation {:?} and selected observation ids: {}", - selection_quality.primary_observation_id, - observation_ids.join(", "), - )), - metaphor: None, - status: Some("candidate".to_string()), - code_refs: path_code_refs, - }); - delta.created_nodes += 1; - } - } - - let mut frontier = input.state.graph_frontier.clone().unwrap_or_default(); - let frontier_node_ids = linked_frontier_node_ids(&graphs, unique_strings(active_node_ids)); - let frontier_edge_ids = incident_edge_ids(&graphs, &frontier_node_ids); - merge_unique(&mut frontier.active_node_ids, frontier_node_ids); - merge_unique(&mut frontier.active_edge_ids, frontier_edge_ids); - merge_unique(&mut frontier.dirty_paths, code_ref_paths.clone()); - - let evidence_id = format!("ev-map-proposal-{fingerprint}"); - let selection_summary = selection_quality_summary(&selection_quality, code_ref_paths.len()); - let observation = EpiphanyObservation { - id: format!("obs-map-proposal-{fingerprint}"), - summary: truncate_chars( - &format!( - "Map/churn proposal from {}: {}", - selection_summary, - observation_ids.join(", "), - ), - SUMMARY_LIMIT, - ), - source_kind: "epiphany-map-proposal".to_string(), - status: "candidate".to_string(), - code_refs: code_refs.clone(), - evidence_ids: vec![evidence_id.clone()], - }; - let evidence = EpiphanyEvidenceRecord { - id: evidence_id, - kind: "proposal".to_string(), - status: "candidate".to_string(), - summary: truncate_chars( - &format!( - "Proposed graph frontier and churn update from {}: {}; reused {reused_nodes} existing node(s), {semantic_reused_nodes} by semantic graph signal, created {created_nodes} new node(s)", - selection_summary, - observation_ids.join(", "), - reused_nodes = delta.reused_nodes(), - semantic_reused_nodes = delta.semantic_reuses, - created_nodes = delta.created_nodes, - ), - SUMMARY_LIMIT, - ), - code_refs, - }; - let understanding_status = proposal_understanding_status(&delta); - let diff_pressure = proposal_diff_pressure(&delta, input.state.churn.as_ref()); - let churn = EpiphanyChurnState { - understanding_status, - diff_pressure, - warning: Some(format!( - "Map/churn proposal derived from {selection_summary}; {}; promote only after verifier acceptance.", - proposal_delta_summary(&delta) - )), - unexplained_writes: input - .state - .churn - .as_ref() - .and_then(|churn| churn.unexplained_writes), - }; - - Ok(EpiphanyMapProposal { - observation, - evidence, - graphs, - graph_frontier: frontier, - churn, - }) -} - -fn proposal_observation_ids( - state: &EpiphanyThreadState, - observation_ids: Vec, -) -> Result> { - let normalized = normalize_observation_ids(observation_ids); - if normalized.is_empty() { - select_automatic_observation_ids(state) - } else { - Ok(normalized) - } -} - -fn normalize_observation_ids(observation_ids: Vec) -> Vec { - let mut normalized = Vec::new(); - let mut seen = HashSet::new(); - for id in observation_ids { - let id = id.trim(); - if id.is_empty() { - continue; - } - if seen.insert(id.to_string()) { - normalized.push(id.to_string()); - } - } - normalized -} - -fn select_automatic_observation_ids(state: &EpiphanyThreadState) -> Result> { - let focus = proposal_focus(state); - let mut candidates = Vec::new(); - - for (index, observation) in state.observations.iter().enumerate() { - if !is_verified_status(&observation.status) || observation.code_refs.is_empty() { - continue; - } - let Some(evidence_score) = accepting_evidence_score(state, observation) else { - continue; - }; - let path_keys = observation_path_keys(observation); - if path_keys.is_empty() { - continue; - } - let score = observation_priority_score(observation) - + evidence_score - + observation_focus_score(&path_keys, &focus); - candidates.push(ObservationSelectionCandidate { - observation_id: observation.id.clone(), - score, - index, - path_keys, - }); - } - - candidates.sort_by(|left, right| { - right - .score - .cmp(&left.score) - .then_with(|| left.index.cmp(&right.index)) - .then_with(|| left.observation_id.cmp(&right.observation_id)) - }); - - let Some(anchor) = candidates.first() else { - return Err(anyhow!( - "observationIds was omitted and no proposal-ready observations were found" - )); - }; - let anchor_path_keys = anchor.path_keys.iter().cloned().collect::>(); - let mut selected = candidates - .iter() - .filter(|candidate| { - candidate - .path_keys - .iter() - .any(|path_key| anchor_path_keys.contains(path_key)) - }) - .take(AUTO_OBSERVATION_SELECTION_LIMIT) - .map(|candidate| (candidate.index, candidate.observation_id.clone())) - .collect::>(); - - selected.sort_by_key(|(index, _)| *index); - Ok(selected - .into_iter() - .map(|(_, observation_id)| observation_id) - .collect()) -} - -fn accepting_evidence_score( - state: &EpiphanyThreadState, - observation: &EpiphanyObservation, -) -> Option { - if observation.evidence_ids.is_empty() { - return None; - } - let mut score = 0usize; - for evidence_id in &observation.evidence_ids { - let evidence = state - .recent_evidence - .iter() - .find(|evidence| evidence.id == *evidence_id)?; - if !is_verified_status(&evidence.status) { - return None; - } - score += evidence_priority_score(evidence); - } - Some(score) -} - -fn proposal_focus(state: &EpiphanyThreadState) -> ProposalFocus { - let mut focus = ProposalFocus::default(); - if let Some(frontier) = state.graph_frontier.as_ref() { - for dirty_path in &frontier.dirty_paths { - focus.dirty_paths.insert(path_key(dirty_path)); - } - for active_node_id in &frontier.active_node_ids { - collect_active_node_paths(&mut focus.active_paths, &state.graphs, active_node_id); - } - } - - collect_mapped_paths(&mut focus.mapped_paths, &state.graphs.architecture.nodes); - collect_mapped_paths(&mut focus.mapped_paths, &state.graphs.dataflow.nodes); - for link in &state.graphs.links { - collect_code_ref_paths(&mut focus.mapped_paths, &link.code_refs); - } - - focus -} - -fn collect_active_node_paths( - target: &mut HashSet, - graphs: &EpiphanyGraphs, - active_node_id: &str, -) { - for node in graphs - .architecture - .nodes - .iter() - .chain(graphs.dataflow.nodes.iter()) - { - if node.id == active_node_id { - collect_code_ref_paths(target, &node.code_refs); - } - } - for link in &graphs.links { - if link.architecture_node_id == active_node_id || link.dataflow_node_id == active_node_id { - collect_code_ref_paths(target, &link.code_refs); - } - } -} - -fn collect_mapped_paths(target: &mut HashSet, nodes: &[EpiphanyGraphNode]) { - for node in nodes { - collect_code_ref_paths(target, &node.code_refs); - } -} - -fn collect_code_ref_paths(target: &mut HashSet, code_refs: &[EpiphanyCodeRef]) { - for code_ref in code_refs { - target.insert(path_key(&code_ref.path)); - } -} - -fn observation_path_keys(observation: &EpiphanyObservation) -> Vec { - let mut path_keys = Vec::new(); - let mut seen = HashSet::new(); - for code_ref in &observation.code_refs { - let key = path_key(&code_ref.path); - if seen.insert(key.clone()) { - path_keys.push(key); - } - } - path_keys -} - -fn observation_focus_score(path_keys: &[String], focus: &ProposalFocus) -> usize { - let mut score = 0usize; - for path_key in path_keys { - if focus.dirty_paths.contains(path_key) { - score += 4; - } - if focus.active_paths.contains(path_key) { - score += 3; - } - if focus.mapped_paths.contains(path_key) { - score += 2; - } - } - score -} - -fn select_observations<'a>( - state: &'a EpiphanyThreadState, - observation_ids: &[String], -) -> Result> { - let mut selected = Vec::new(); - for observation_id in observation_ids { - let observation = state - .observations - .iter() - .find(|observation| observation.id == *observation_id) - .ok_or_else(|| anyhow!("observation id {observation_id:?} not found in state"))?; - if !is_verified_status(&observation.status) { - return Err(anyhow!( - "observation id {observation_id:?} must have verified/accepted status, got {:?}", - observation.status - )); - } - selected.push(observation); - } - Ok(selected) -} - -fn evaluate_selection_quality( - state: &EpiphanyThreadState, - observations: &[&EpiphanyObservation], -) -> Result { - let mut evidence_ids = Vec::new(); - let mut seen_evidence_ids = HashSet::new(); - let mut source_kinds = Vec::new(); - let mut seen_source_kinds = HashSet::new(); - let mut semantic_terms = Vec::new(); - let mut seen_semantic_terms = HashSet::new(); - let mut primary_observation_id = String::new(); - let mut primary_observation_summary = String::new(); - let mut primary_score = 0usize; - let mut strong_signal_count = 0usize; - - for observation in observations { - if observation.evidence_ids.is_empty() { - return Err(anyhow!( - "observation id {:?} must cite at least one evidence record", - observation.id - )); - } - - let mut has_accepting_evidence = false; - let mut observation_score = observation_priority_score(observation); - push_semantic_terms( - &mut semantic_terms, - &mut seen_semantic_terms, - &observation.summary, - ); - push_semantic_terms( - &mut semantic_terms, - &mut seen_semantic_terms, - &observation.source_kind, - ); - push_code_ref_semantic_terms( - &mut semantic_terms, - &mut seen_semantic_terms, - &observation.code_refs, - ); - for evidence_id in &observation.evidence_ids { - let evidence = state - .recent_evidence - .iter() - .find(|evidence| evidence.id == *evidence_id) - .ok_or_else(|| { - anyhow!( - "observation id {:?} cites missing evidence id {:?}", - observation.id, - evidence_id - ) - })?; - if !is_verified_status(&evidence.status) { - return Err(anyhow!( - "observation id {:?} cites non-accepting evidence id {:?} with status {:?}", - observation.id, - evidence_id, - evidence.status - )); - } - has_accepting_evidence = true; - observation_score += evidence_priority_score(evidence); - if seen_evidence_ids.insert(evidence.id.clone()) { - evidence_ids.push(evidence.id.clone()); - } - push_semantic_terms( - &mut semantic_terms, - &mut seen_semantic_terms, - &evidence.summary, - ); - push_semantic_terms( - &mut semantic_terms, - &mut seen_semantic_terms, - &evidence.kind, - ); - push_code_ref_semantic_terms( - &mut semantic_terms, - &mut seen_semantic_terms, - &evidence.code_refs, - ); - } - - if !has_accepting_evidence { - return Err(anyhow!( - "observation id {:?} must cite at least one accepting evidence record", - observation.id - )); - } - - let source_kind = observation.source_kind.trim(); - if !source_kind.is_empty() && seen_source_kinds.insert(source_kind.to_string()) { - source_kinds.push(source_kind.to_string()); - } - if observation_score >= 8 { - strong_signal_count += 1; - } - if primary_observation_id.is_empty() || observation_score > primary_score { - primary_observation_id = observation.id.clone(); - primary_observation_summary = observation.summary.clone(); - primary_score = observation_score; - } - } - - Ok(SelectionQuality { - observation_count: observations.len(), - evidence_count: evidence_ids.len(), - source_kinds, - priority_label: selection_priority_label(strong_signal_count, observations.len()), - primary_observation_id, - primary_observation_summary, - semantic_terms, - }) -} - -fn observation_priority_score(observation: &EpiphanyObservation) -> usize { - signal_kind_weight(&observation.source_kind) - + observation.code_refs.len().min(3) - + usize::from(!observation.summary.trim().is_empty()) -} - -fn evidence_priority_score(evidence: &EpiphanyEvidenceRecord) -> usize { - signal_kind_weight(&evidence.kind) - + evidence.code_refs.len().min(2) - + usize::from(!evidence.summary.trim().is_empty()) -} - -fn signal_kind_weight(value: &str) -> usize { - let lower = value.trim().to_ascii_lowercase(); - if lower.contains("verification") || lower.contains("verifier") { - 4 - } else if lower.contains("test") || lower.contains("smoke") { - 3 - } else if lower.contains("tool") || lower.contains("review") { - 2 - } else if lower.contains("observation") { - 1 - } else { - 0 - } -} - -fn selection_priority_label(strong_signal_count: usize, observation_count: usize) -> String { - if strong_signal_count == observation_count { - "high-priority verified selection".to_string() - } else if strong_signal_count > 0 { - "mixed-priority verified selection".to_string() - } else { - "low-priority accepted selection".to_string() - } -} - -fn collect_code_refs(observations: &[&EpiphanyObservation]) -> Result> { - let mut code_refs = Vec::new(); - let mut seen = HashSet::new(); - for observation in observations { - for code_ref in &observation.code_refs { - let key = code_ref_key(code_ref); - if seen.insert(key) { - code_refs.push(code_ref.clone()); - } - } - } - if code_refs.is_empty() { - Err(anyhow!( - "map proposals require at least one code ref on the selected observations" - )) - } else { - Ok(code_refs) - } -} - -fn unique_code_ref_paths(code_refs: &[EpiphanyCodeRef]) -> Vec { - let mut paths = Vec::new(); - let mut seen = HashSet::new(); - for code_ref in code_refs { - let key = code_ref.path.to_string_lossy().to_string(); - if seen.insert(key) { - paths.push(code_ref.path.clone()); - } - } - paths -} - -fn code_refs_for_path(code_refs: &[EpiphanyCodeRef], path: &Path) -> Vec { - code_refs - .iter() - .filter(|code_ref| code_ref.path == path) - .cloned() - .collect() -} - -fn find_architecture_node_for_path( - graphs: &EpiphanyGraphs, - path_code_refs: &[EpiphanyCodeRef], - path: &Path, - candidate_node_id: &str, - semantic_terms: &[String], -) -> Option { - graphs - .architecture - .nodes - .iter() - .position(|node| has_exact_code_ref_overlap(&node.code_refs, path_code_refs)) - .map(|index| ArchitectureMatch { - index, - kind: ArchitectureMatchKind::ExactCodeRef, - }) - .or_else(|| { - graphs - .architecture - .nodes - .iter() - .position(|node| node.code_refs.iter().any(|code_ref| code_ref.path == path)) - .map(|index| ArchitectureMatch { - index, - kind: ArchitectureMatchKind::SamePath, - }) - }) - .or_else(|| { - graphs - .architecture - .nodes - .iter() - .position(|node| node.id == candidate_node_id) - .map(|index| ArchitectureMatch { - index, - kind: ArchitectureMatchKind::DeterministicId, - }) - }) - .or_else(|| { - find_semantic_architecture_node(graphs, semantic_terms).map(|index| ArchitectureMatch { - index, - kind: ArchitectureMatchKind::Semantic, - }) - }) -} - -fn has_exact_code_ref_overlap( - existing_code_refs: &[EpiphanyCodeRef], - proposed_code_refs: &[EpiphanyCodeRef], -) -> bool { - let existing_keys = existing_code_refs - .iter() - .map(code_ref_key) - .collect::>(); - proposed_code_refs - .iter() - .map(code_ref_key) - .any(|key| existing_keys.contains(&key)) -} - -fn find_semantic_architecture_node( - graphs: &EpiphanyGraphs, - semantic_terms: &[String], -) -> Option { - if semantic_terms.is_empty() { - return None; - } - - let mut best_index = None; - let mut best_score = 0usize; - let mut tied = false; - for (index, node) in graphs.architecture.nodes.iter().enumerate() { - let score = semantic_node_score(node, semantic_terms); - if !semantic_score_can_reuse(node, score) { - continue; - } - if score > best_score { - best_index = Some(index); - best_score = score; - tied = false; - } else if score == best_score { - tied = true; - } - } - - if tied { None } else { best_index } -} - -fn semantic_score_can_reuse(node: &EpiphanyGraphNode, score: usize) -> bool { - if score < SEMANTIC_REUSE_MIN_SCORE { - return false; - } - // Once a graph node is anchored to code, keep reuse on concrete ref/path/id checks. - // Semantic matching is only a rescue path for useful map prose that has no refs yet. - node.code_refs.is_empty() -} - -fn semantic_node_score(node: &EpiphanyGraphNode, semantic_terms: &[String]) -> usize { - let mut node_terms = Vec::new(); - let mut seen = HashSet::new(); - push_semantic_terms(&mut node_terms, &mut seen, &node.id); - push_semantic_terms(&mut node_terms, &mut seen, &node.title); - push_semantic_terms(&mut node_terms, &mut seen, &node.purpose); - if let Some(mechanism) = node.mechanism.as_deref() { - push_semantic_terms(&mut node_terms, &mut seen, mechanism); - } - if let Some(metaphor) = node.metaphor.as_deref() { - push_semantic_terms(&mut node_terms, &mut seen, metaphor); - } - if let Some(status) = node.status.as_deref() { - push_semantic_terms(&mut node_terms, &mut seen, status); - } - push_code_ref_semantic_terms(&mut node_terms, &mut seen, &node.code_refs); - - let node_terms = node_terms.into_iter().collect::>(); - semantic_terms - .iter() - .filter(|term| node_terms.contains(term.as_str())) - .count() -} - -fn merge_code_refs(target: &mut Vec, additions: Vec) { - let mut seen = target.iter().map(code_ref_key).collect::>(); - for addition in additions { - if seen.insert(code_ref_key(&addition)) { - target.push(addition); - } - } -} - -fn linked_frontier_node_ids(graphs: &EpiphanyGraphs, direct_node_ids: Vec) -> Vec { - let mut linked_node_ids = direct_node_ids; - let mut seen = linked_node_ids.iter().cloned().collect::>(); - let mut changed = true; - - while changed { - changed = false; - for link in &graphs.links { - if seen.contains(&link.architecture_node_id) - && seen.insert(link.dataflow_node_id.clone()) - { - linked_node_ids.push(link.dataflow_node_id.clone()); - changed = true; - } - if seen.contains(&link.dataflow_node_id) - && seen.insert(link.architecture_node_id.clone()) - { - linked_node_ids.push(link.architecture_node_id.clone()); - changed = true; - } - } - } - - linked_node_ids -} - -fn incident_edge_ids(graphs: &EpiphanyGraphs, node_ids: &[String]) -> Vec { - let node_ids = node_ids.iter().map(String::as_str).collect::>(); - let mut edge_ids = Vec::new(); - let mut seen = HashSet::new(); - for edge in graphs - .architecture - .edges - .iter() - .chain(graphs.dataflow.edges.iter()) - { - if is_incident_to_any_node(edge, &node_ids) - && let Some(edge_id) = edge.id.as_deref().map(str::trim) - && !edge_id.is_empty() - && seen.insert(edge_id.to_string()) - { - edge_ids.push(edge_id.to_string()); - } - } - edge_ids -} - -fn is_incident_to_any_node(edge: &EpiphanyGraphEdge, node_ids: &HashSet<&str>) -> bool { - node_ids.contains(edge.source_id.as_str()) || node_ids.contains(edge.target_id.as_str()) -} - -fn merge_unique(target: &mut Vec, additions: Vec) -where - T: Clone + Eq + std::hash::Hash, -{ - let mut seen: HashSet = target.iter().cloned().collect(); - for addition in additions { - if seen.insert(addition.clone()) { - target.push(addition); - } - } -} - -fn unique_strings(values: Vec) -> Vec { - let mut unique = Vec::new(); - let mut seen = HashSet::new(); - for value in values { - if seen.insert(value.clone()) { - unique.push(value); - } - } - unique -} - -fn graph_node_id(path: &Path) -> String { - let mut hasher = Sha1::new(); - hasher.update(path.to_string_lossy().as_bytes()); - let digest = hasher.finalize(); - let suffix: String = format!("{digest:x}").chars().take(12).collect(); - format!("arch-path-{suffix}") -} - -fn title_from_path(path: &Path) -> String { - if let Some(file_name) = path - .file_name() - .and_then(|value| value.to_str()) - .filter(|value| !value.trim().is_empty()) - { - file_name.to_string() - } else { - path.to_string_lossy().to_string() - } -} - -fn fingerprint( - revision: &u64, - observation_ids: &[String], - code_refs: &[EpiphanyCodeRef], -) -> String { - let mut hasher = Sha1::new(); - hasher.update(revision.to_string().as_bytes()); - for observation_id in observation_ids { - hasher.update(b"\0"); - hasher.update(observation_id.as_bytes()); - } - for code_ref in code_refs { - hasher.update(b"\0"); - hasher.update(code_ref_key(code_ref).as_bytes()); - } - let digest = hasher.finalize(); - format!("{digest:x}").chars().take(12).collect() -} - -fn code_ref_key(code_ref: &EpiphanyCodeRef) -> String { - format!( - "{}:{}:{}:{}", - path_key(&code_ref.path), - code_ref.start_line.unwrap_or_default(), - code_ref.end_line.unwrap_or_default(), - code_ref.symbol.as_deref().unwrap_or_default() - ) -} - -fn path_key(path: &Path) -> String { - path.to_string_lossy().replace('\\', "/") -} - -fn push_code_ref_semantic_terms( - target: &mut Vec, - seen: &mut HashSet, - code_refs: &[EpiphanyCodeRef], -) { - for code_ref in code_refs { - push_path_semantic_terms(target, seen, &code_ref.path); - if let Some(symbol) = code_ref.symbol.as_deref() { - push_semantic_terms(target, seen, symbol); - } - if let Some(note) = code_ref.note.as_deref() { - push_semantic_terms(target, seen, note); - } - } -} - -fn push_path_semantic_terms(target: &mut Vec, seen: &mut HashSet, path: &Path) { - if let Some(file_stem) = path.file_stem().and_then(|value| value.to_str()) { - push_semantic_terms(target, seen, file_stem); - } - if let Some(parent) = path.parent().and_then(|value| value.to_str()) { - push_semantic_terms(target, seen, parent); - } -} - -fn push_semantic_terms(target: &mut Vec, seen: &mut HashSet, value: &str) { - for term in semantic_terms(value) { - if seen.insert(term.clone()) { - target.push(term); - } - } -} - -fn semantic_terms(value: &str) -> Vec { - value - .split(|character: char| !character.is_ascii_alphanumeric()) - .map(str::trim) - .filter(|term| term.len() >= 3) - .map(str::to_ascii_lowercase) - .filter(|term| !is_semantic_stopword(term)) - .collect() -} - -fn is_semantic_stopword(value: &str) -> bool { - matches!( - value, - "and" - | "are" - | "but" - | "can" - | "for" - | "from" - | "has" - | "into" - | "not" - | "now" - | "one" - | "out" - | "the" - | "this" - | "that" - | "through" - | "with" - ) -} - -fn truncate_chars(value: &str, limit: usize) -> String { - if value.chars().count() <= limit { - return value.to_string(); - } - let mut truncated = value - .chars() - .take(limit.saturating_sub(3)) - .collect::(); - truncated.push_str("..."); - truncated -} - -fn proposal_understanding_status(delta: &MapDeltaJudgment) -> String { - match (delta.reused_nodes() > 0, delta.created_nodes > 0) { - (true, false) => "proposal_refines_map", - (false, true) => "proposal_expands_map", - (true, true) => "proposal_updates_map", - (false, false) => "proposal_ready", - } - .to_string() -} - -fn proposal_diff_pressure( - delta: &MapDeltaJudgment, - existing_churn: Option<&EpiphanyChurnState>, -) -> String { - let proposal_pressure = if delta.created_nodes > 1 - || delta.has_mixed_delta() - || delta.touched_paths > 2 - || delta.selected_observations > 3 - || delta.existing_unexplained_writes - { - "high" - } else if delta.created_nodes > 0 - || delta.has_broadening_reuse() - || delta.touched_paths > 1 - || delta.selected_observations > 1 - { - "medium" - } else { - "low" - }; - - let existing_pressure = existing_churn - .map(|churn| churn.diff_pressure.trim()) - .filter(|value| !value.is_empty()) - .unwrap_or("low"); - - max_pressure(existing_pressure, proposal_pressure).to_string() -} - -fn proposal_delta_summary(delta: &MapDeltaJudgment) -> String { - let mut parts = Vec::new(); - if delta.exact_ref_reuses > 0 { - parts.push(format!( - "{} exact-ref refinement(s)", - delta.exact_ref_reuses - )); - } - if delta.same_path_reuses > 0 { - parts.push(format!( - "{} same-path broadening reuse(s)", - delta.same_path_reuses - )); - } - if delta.deterministic_id_reuses > 0 { - parts.push(format!( - "{} deterministic-node reuse(s)", - delta.deterministic_id_reuses - )); - } - if delta.semantic_reuses > 0 { - parts.push(format!( - "{} semantic unanchored-node reuse(s)", - delta.semantic_reuses - )); - } - if delta.created_nodes > 0 { - parts.push(format!("{} new candidate node(s)", delta.created_nodes)); - } - if parts.is_empty() { - parts.push("no graph node delta".to_string()); - } - format!( - "delta judgment: {}; {} touched path(s), {} selected observation(s)", - parts.join(", "), - delta.touched_paths, - delta.selected_observations - ) -} - -fn max_pressure<'a>(left: &'a str, right: &'a str) -> &'a str { - if pressure_rank(left) >= pressure_rank(right) { - left - } else { - right - } -} - -fn pressure_rank(value: &str) -> u8 { - match value.trim().to_ascii_lowercase().as_str() { - "critical" => 4, - "high" => 3, - "medium" => 2, - "low" => 1, - _ => 0, - } -} - -fn selection_quality_summary(selection_quality: &SelectionQuality, path_count: usize) -> String { - let source_kinds = if selection_quality.source_kinds.is_empty() { - "unknown sources".to_string() - } else { - selection_quality.source_kinds.join("/") - }; - format!( - "{} evidence-backed observation(s), {} accepting evidence record(s), {} code path(s), {}, primary observation: {}, source kind(s): {}", - selection_quality.observation_count, - selection_quality.evidence_count, - path_count, - selection_quality.priority_label, - selection_quality.primary_observation_id, - source_kinds - ) -} - -fn is_verified_status(status: &str) -> bool { - matches!( - status.trim().to_ascii_lowercase().as_str(), - "ok" | "accepted" | "verified" | "pass" | "passed" - ) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::promotion::EpiphanyPromotionInput; - use crate::promotion::evaluate_promotion; - use epiphany_state_model::EpiphanyGraph; - use epiphany_state_model::EpiphanyGraphEdge; - use epiphany_state_model::EpiphanyGraphLink; - - fn code_ref(path: &str) -> EpiphanyCodeRef { - EpiphanyCodeRef { - path: PathBuf::from(path), - start_line: Some(10), - end_line: Some(20), - symbol: Some("demo".to_string()), - note: None, - } - } - - fn state_with_observation(status: &str) -> EpiphanyThreadState { - EpiphanyThreadState { - revision: 4, - observations: vec![EpiphanyObservation { - id: "obs-verified".to_string(), - summary: "The prompt renderer injects Epiphany state".to_string(), - source_kind: "verification".to_string(), - status: status.to_string(), - code_refs: vec![code_ref("epiphany-state-model/src/prompt.rs")], - evidence_ids: vec!["ev-verified".to_string()], - }], - recent_evidence: vec![EpiphanyEvidenceRecord { - id: "ev-verified".to_string(), - kind: "verification".to_string(), - status: "ok".to_string(), - summary: "Verified prompt renderer behavior".to_string(), - code_refs: vec![code_ref("epiphany-state-model/src/prompt.rs")], - }], - churn: Some(EpiphanyChurnState { - understanding_status: "grounded".to_string(), - diff_pressure: "medium".to_string(), - ..Default::default() - }), - ..Default::default() - } - } - - fn verifier() -> EpiphanyEvidenceRecord { - EpiphanyEvidenceRecord { - id: "ev-verifier".to_string(), - kind: "verification".to_string(), - status: "ok".to_string(), - summary: "Verifier accepted proposal".to_string(), - code_refs: Vec::new(), - } - } - - #[test] - fn propose_map_update_returns_candidate_patch_parts() { - let proposal = propose_map_update(EpiphanyMapProposalInput { - state: state_with_observation("verified"), - observation_ids: vec!["obs-verified".to_string()], - }) - .expect("proposal"); - - assert!(proposal.observation.id.starts_with("obs-map-proposal-")); - assert_eq!(proposal.evidence.status, "candidate"); - assert_eq!(proposal.graphs.architecture.nodes.len(), 1); - assert_eq!(proposal.graphs.architecture.nodes[0].title, "prompt.rs"); - assert_eq!(proposal.graph_frontier.active_node_ids.len(), 1); - assert_eq!(proposal.churn.understanding_status, "proposal_expands_map"); - assert_eq!(proposal.churn.diff_pressure, "medium"); - } - - #[test] - fn propose_map_update_reuses_existing_architecture_node_for_matching_code_ref() { - let mut state = state_with_observation("verified"); - state.graphs.architecture.nodes.push(EpiphanyGraphNode { - id: "prompt-renderer".to_string(), - title: "Prompt renderer".to_string(), - purpose: "Render Epiphany state into developer context".to_string(), - status: Some("grounded".to_string()), - code_refs: vec![code_ref("epiphany-state-model/src/prompt.rs")], - ..Default::default() - }); - state.observations[0].code_refs.push(EpiphanyCodeRef { - path: PathBuf::from("epiphany-state-model/src/prompt.rs"), - start_line: Some(30), - end_line: Some(40), - symbol: Some("render_epiphany_state".to_string()), - note: Some("newly verified line span".to_string()), - }); - - let proposal = propose_map_update(EpiphanyMapProposalInput { - state, - observation_ids: vec!["obs-verified".to_string()], - }) - .expect("proposal"); - - assert_eq!(proposal.graphs.architecture.nodes.len(), 1); - let node = &proposal.graphs.architecture.nodes[0]; - assert_eq!(node.id, "prompt-renderer"); - assert_eq!(node.status.as_deref(), Some("grounded")); - assert_eq!(node.code_refs.len(), 2); - assert_eq!( - proposal.graph_frontier.active_node_ids, - vec!["prompt-renderer".to_string()] - ); - assert_eq!(proposal.churn.understanding_status, "proposal_refines_map"); - } - - #[test] - fn propose_map_update_reuses_existing_deterministic_path_node_without_refs() { - let mut state = state_with_observation("verified"); - let node_id = graph_node_id(Path::new("epiphany-state-model/src/prompt.rs")); - state.graphs.architecture.nodes.push(EpiphanyGraphNode { - id: node_id.clone(), - title: "Prompt path".to_string(), - purpose: "Existing path-derived proposal node".to_string(), - ..Default::default() - }); - - let proposal = propose_map_update(EpiphanyMapProposalInput { - state, - observation_ids: vec!["obs-verified".to_string()], - }) - .expect("proposal"); - - assert_eq!(proposal.graphs.architecture.nodes.len(), 1); - assert_eq!(proposal.graphs.architecture.nodes[0].id, node_id); - assert_eq!(proposal.graphs.architecture.nodes[0].code_refs.len(), 1); - assert_eq!(proposal.churn.understanding_status, "proposal_refines_map"); - } - - #[test] - fn propose_map_update_reuses_strong_semantic_graph_match_without_refs() { - let mut state = state_with_observation("verified"); - state.graphs.architecture.nodes.push(EpiphanyGraphNode { - id: "prompt-renderer".to_string(), - title: "Prompt renderer".to_string(), - purpose: "Inject Epiphany state into developer context".to_string(), - mechanism: Some("Renders typed state as a bounded prompt fragment".to_string()), - ..Default::default() - }); - - let proposal = propose_map_update(EpiphanyMapProposalInput { - state, - observation_ids: vec!["obs-verified".to_string()], - }) - .expect("proposal"); - - assert_eq!(proposal.graphs.architecture.nodes.len(), 1); - assert_eq!(proposal.graphs.architecture.nodes[0].id, "prompt-renderer"); - assert_eq!(proposal.graphs.architecture.nodes[0].code_refs.len(), 1); - assert_eq!( - proposal.graph_frontier.active_node_ids, - vec!["prompt-renderer".to_string()] - ); - assert!( - proposal - .churn - .warning - .as_deref() - .unwrap_or_default() - .contains("1 semantic unanchored-node reuse") - ); - } - - #[test] - fn propose_map_update_judges_exact_ref_reuse_as_low_pressure_refinement() { - let mut state = state_with_observation("verified"); - state.churn = Some(EpiphanyChurnState { - understanding_status: "grounded".to_string(), - diff_pressure: "low".to_string(), - ..Default::default() - }); - state.graphs.architecture.nodes.push(EpiphanyGraphNode { - id: "prompt-renderer".to_string(), - title: "Prompt renderer".to_string(), - purpose: "Render Epiphany state into developer context".to_string(), - code_refs: vec![code_ref("epiphany-state-model/src/prompt.rs")], - ..Default::default() - }); - - let proposal = propose_map_update(EpiphanyMapProposalInput { - state, - observation_ids: vec!["obs-verified".to_string()], - }) - .expect("proposal"); - - assert_eq!(proposal.churn.diff_pressure, "low"); - assert!( - proposal - .churn - .warning - .as_deref() - .unwrap_or_default() - .contains("1 exact-ref refinement") - ); - } - - #[test] - fn propose_map_update_judges_same_path_reuse_as_broadening_pressure() { - let mut state = state_with_observation("verified"); - state.churn = Some(EpiphanyChurnState { - understanding_status: "grounded".to_string(), - diff_pressure: "low".to_string(), - ..Default::default() - }); - state.graphs.architecture.nodes.push(EpiphanyGraphNode { - id: "prompt-renderer".to_string(), - title: "Prompt renderer".to_string(), - purpose: "Render Epiphany state into developer context".to_string(), - code_refs: vec![EpiphanyCodeRef { - path: PathBuf::from("epiphany-state-model/src/prompt.rs"), - start_line: Some(100), - end_line: Some(120), - symbol: Some("render_graphs".to_string()), - note: None, - }], - ..Default::default() - }); - - let proposal = propose_map_update(EpiphanyMapProposalInput { - state, - observation_ids: vec!["obs-verified".to_string()], - }) - .expect("proposal"); - - assert_eq!(proposal.churn.diff_pressure, "medium"); - assert!( - proposal - .churn - .warning - .as_deref() - .unwrap_or_default() - .contains("1 same-path broadening reuse") - ); - } - - #[test] - fn propose_map_update_refuses_ambiguous_semantic_graph_match() { - let mut state = state_with_observation("verified"); - for node_id in ["prompt-renderer-a", "prompt-renderer-b"] { - state.graphs.architecture.nodes.push(EpiphanyGraphNode { - id: node_id.to_string(), - title: "Prompt renderer".to_string(), - purpose: "Inject Epiphany state into developer context".to_string(), - mechanism: Some("Renders typed state as a bounded prompt fragment".to_string()), - ..Default::default() - }); - } - - let proposal = propose_map_update(EpiphanyMapProposalInput { - state, - observation_ids: vec!["obs-verified".to_string()], - }) - .expect("proposal"); - - assert_eq!(proposal.graphs.architecture.nodes.len(), 3); - assert!( - proposal - .graph_frontier - .active_node_ids - .iter() - .any(|node_id| node_id.starts_with("arch-path-")) - ); - assert_eq!(proposal.churn.understanding_status, "proposal_expands_map"); - } - - #[test] - fn propose_map_update_prioritizes_stronger_selected_observation() { - let mut state = state_with_observation("ok"); - state.observations[0].id = "obs-weak".to_string(); - state.observations[0].source_kind = "observation".to_string(); - state.observations[0].summary = "Prompt renderer might be involved".to_string(); - state.observations[0].evidence_ids = vec!["ev-weak".to_string()]; - state.recent_evidence[0].id = "ev-weak".to_string(); - state.recent_evidence[0].kind = "observation".to_string(); - state.recent_evidence[0].summary = "Manual note mentioned prompt renderer".to_string(); - state.observations.push(EpiphanyObservation { - id: "obs-strong".to_string(), - summary: "Live smoke verified prompt renderer Epiphany state injection".to_string(), - source_kind: "smoke".to_string(), - status: "ok".to_string(), - code_refs: vec![code_ref("epiphany-state-model/src/prompt.rs")], - evidence_ids: vec!["ev-strong".to_string()], - }); - state.recent_evidence.push(EpiphanyEvidenceRecord { - id: "ev-strong".to_string(), - kind: "verification".to_string(), - status: "ok".to_string(), - summary: "Verifier accepted prompt renderer state injection".to_string(), - code_refs: vec![code_ref("epiphany-state-model/src/prompt.rs")], - }); - - let proposal = propose_map_update(EpiphanyMapProposalInput { - state, - observation_ids: vec!["obs-weak".to_string(), "obs-strong".to_string()], - }) - .expect("proposal"); - - assert!( - proposal.graphs.architecture.nodes[0] - .purpose - .contains("Live smoke verified") - ); - assert!( - proposal - .observation - .summary - .contains("primary observation: obs-strong") - ); - } - - #[test] - fn propose_map_update_auto_selects_best_proposal_ready_observations_when_ids_are_omitted() { - let mut state = state_with_observation("ok"); - state.observations[0].id = "obs-weak".to_string(); - state.observations[0].source_kind = "observation".to_string(); - state.observations[0].summary = "Prompt renderer might be involved".to_string(); - state.observations[0].evidence_ids = vec!["ev-weak".to_string()]; - state.recent_evidence[0].id = "ev-weak".to_string(); - state.recent_evidence[0].kind = "observation".to_string(); - state.recent_evidence[0].summary = "Manual note mentioned prompt renderer".to_string(); - state.observations.push(EpiphanyObservation { - id: "obs-failed".to_string(), - summary: "Failed candidate should not be selected".to_string(), - source_kind: "verification".to_string(), - status: "failed".to_string(), - code_refs: vec![code_ref("epiphany-state-model/src/prompt.rs")], - evidence_ids: vec!["ev-failed".to_string()], - }); - state.recent_evidence.push(EpiphanyEvidenceRecord { - id: "ev-failed".to_string(), - kind: "verification".to_string(), - status: "failed".to_string(), - summary: "Verifier rejected the failed candidate".to_string(), - code_refs: vec![code_ref("epiphany-state-model/src/prompt.rs")], - }); - state.observations.push(EpiphanyObservation { - id: "obs-strong".to_string(), - summary: "Live smoke verified prompt renderer Epiphany state injection".to_string(), - source_kind: "smoke".to_string(), - status: "ok".to_string(), - code_refs: vec![code_ref("epiphany-state-model/src/prompt.rs")], - evidence_ids: vec!["ev-strong".to_string()], - }); - state.recent_evidence.push(EpiphanyEvidenceRecord { - id: "ev-strong".to_string(), - kind: "verification".to_string(), - status: "ok".to_string(), - summary: "Verifier accepted prompt renderer state injection".to_string(), - code_refs: vec![code_ref("epiphany-state-model/src/prompt.rs")], - }); - - let proposal = propose_map_update(EpiphanyMapProposalInput { - state, - observation_ids: Vec::new(), - }) - .expect("auto-selected proposal"); - - assert!( - proposal - .observation - .summary - .contains("primary observation: obs-strong") - ); - assert!(!proposal.observation.summary.contains("obs-failed")); - } - - #[test] - fn propose_map_update_auto_selection_prefers_frontier_dirty_path_cluster() { - let mut state = state_with_observation("ok"); - state.graph_frontier = Some(EpiphanyGraphFrontier { - dirty_paths: vec![PathBuf::from("epiphany-state-model/src/prompt.rs")], - ..Default::default() - }); - state.observations.push(EpiphanyObservation { - id: "obs-other".to_string(), - summary: "Proposal engine update is verified but not current frontier focus" - .to_string(), - source_kind: "verification".to_string(), - status: "ok".to_string(), - code_refs: vec![code_ref("epiphany-core/src/proposal.rs")], - evidence_ids: vec!["ev-other".to_string()], - }); - state.recent_evidence.push(EpiphanyEvidenceRecord { - id: "ev-other".to_string(), - kind: "verification".to_string(), - status: "ok".to_string(), - summary: "Verifier accepted proposal engine behavior".to_string(), - code_refs: vec![code_ref("epiphany-core/src/proposal.rs")], - }); - - let proposal = propose_map_update(EpiphanyMapProposalInput { - state, - observation_ids: Vec::new(), - }) - .expect("auto-selected proposal"); - - assert!( - proposal.observation.summary.contains("obs-verified"), - "{}", - proposal.observation.summary - ); - assert!( - proposal - .graph_frontier - .dirty_paths - .contains(&PathBuf::from("epiphany-state-model/src/prompt.rs")) - ); - assert!( - !proposal - .graph_frontier - .dirty_paths - .contains(&PathBuf::from("epiphany-core/src/proposal.rs")) - ); - } - - #[test] - fn propose_map_update_auto_selection_rejects_when_no_candidate_is_ready() { - let mut state = state_with_observation("failed"); - state.recent_evidence.clear(); - - let err = propose_map_update(EpiphanyMapProposalInput { - state, - observation_ids: Vec::new(), - }) - .expect_err("auto-selection needs proposal-ready observations"); - - assert!( - err.to_string() - .contains("no proposal-ready observations were found") - ); - } - - #[test] - fn propose_map_update_focuses_linked_nodes_and_incident_edges() { - let mut state = state_with_observation("verified"); - state.graphs = EpiphanyGraphs { - architecture: EpiphanyGraph { - nodes: vec![ - EpiphanyGraphNode { - id: "session".to_string(), - title: "Session".to_string(), - purpose: "Build turn context".to_string(), - ..Default::default() - }, - EpiphanyGraphNode { - id: "prompt-renderer".to_string(), - title: "Prompt renderer".to_string(), - purpose: "Render Epiphany state".to_string(), - code_refs: vec![code_ref("epiphany-state-model/src/prompt.rs")], - ..Default::default() - }, - ], - edges: vec![EpiphanyGraphEdge { - id: Some("edge-session-prompt".to_string()), - source_id: "session".to_string(), - target_id: "prompt-renderer".to_string(), - kind: "calls".to_string(), - ..Default::default() - }], - }, - dataflow: EpiphanyGraph { - nodes: vec![ - EpiphanyGraphNode { - id: "developer-context".to_string(), - title: "Developer context".to_string(), - purpose: "Carry rendered instructions".to_string(), - ..Default::default() - }, - EpiphanyGraphNode { - id: "epiphany-state-fragment".to_string(), - title: "Epiphany state fragment".to_string(), - purpose: "Expose typed state to the model".to_string(), - ..Default::default() - }, - ], - edges: vec![EpiphanyGraphEdge { - id: Some("edge-fragment-context".to_string()), - source_id: "epiphany-state-fragment".to_string(), - target_id: "developer-context".to_string(), - kind: "feeds".to_string(), - ..Default::default() - }], - }, - links: vec![EpiphanyGraphLink { - dataflow_node_id: "epiphany-state-fragment".to_string(), - architecture_node_id: "prompt-renderer".to_string(), - relationship: Some("rendered by".to_string()), - code_refs: vec![code_ref("epiphany-state-model/src/prompt.rs")], - }], - }; - - let proposal = propose_map_update(EpiphanyMapProposalInput { - state, - observation_ids: vec!["obs-verified".to_string()], - }) - .expect("proposal"); - - assert_eq!( - proposal.graph_frontier.active_node_ids, - vec![ - "prompt-renderer".to_string(), - "epiphany-state-fragment".to_string() - ] - ); - assert_eq!( - proposal.graph_frontier.active_edge_ids, - vec![ - "edge-session-prompt".to_string(), - "edge-fragment-context".to_string() - ] - ); - } - - #[test] - fn propose_map_update_returns_promotion_acceptable_patch_parts() { - let proposal = propose_map_update(EpiphanyMapProposalInput { - state: state_with_observation("verified"), - observation_ids: vec!["obs-verified".to_string()], - }) - .expect("proposal"); - - let decision = evaluate_promotion(EpiphanyPromotionInput { - has_state_replacements: true, - active_subgoal_id: None, - subgoals: None, - invariants: None, - graphs: Some(proposal.graphs), - graph_frontier: Some(proposal.graph_frontier), - graph_checkpoint: None, - investigation_checkpoint: None, - churn: Some(proposal.churn), - observations: vec![proposal.observation], - evidence: vec![proposal.evidence], - verifier_evidence: verifier(), - }); - - assert!(decision.accepted, "{:?}", decision.reasons); - } - - #[test] - fn propose_map_update_rejects_unverified_observation() { - let err = propose_map_update(EpiphanyMapProposalInput { - state: state_with_observation("failed"), - observation_ids: vec!["obs-verified".to_string()], - }) - .expect_err("unverified observation should fail"); - - assert!( - err.to_string() - .contains("must have verified/accepted status") - ); - } - - #[test] - fn propose_map_update_rejects_missing_code_refs() { - let mut state = state_with_observation("ok"); - state.observations[0].code_refs.clear(); - - let err = propose_map_update(EpiphanyMapProposalInput { - state, - observation_ids: vec!["obs-verified".to_string()], - }) - .expect_err("code refs are required"); - - assert!(err.to_string().contains("at least one code ref")); - } - - #[test] - fn propose_map_update_rejects_observation_without_backing_evidence() { - let mut state = state_with_observation("ok"); - state.recent_evidence.clear(); - - let err = propose_map_update(EpiphanyMapProposalInput { - state, - observation_ids: vec!["obs-verified".to_string()], - }) - .expect_err("missing backing evidence should fail"); - - assert!(err.to_string().contains("cites missing evidence id")); - } - - #[test] - fn propose_map_update_rejects_non_accepting_backing_evidence() { - let mut state = state_with_observation("ok"); - state.recent_evidence[0].status = "failed".to_string(); - - let err = propose_map_update(EpiphanyMapProposalInput { - state, - observation_ids: vec!["obs-verified".to_string()], - }) - .expect_err("non-accepting backing evidence should fail"); - - assert!(err.to_string().contains("non-accepting evidence")); - } - - #[test] - fn propose_map_update_marks_mixed_multi_path_changes_as_high_pressure() { - let mut state = state_with_observation("ok"); - state.churn = Some(EpiphanyChurnState { - understanding_status: "grounded".to_string(), - diff_pressure: "low".to_string(), - ..Default::default() - }); - state.graphs.architecture.nodes.push(EpiphanyGraphNode { - id: "prompt-renderer".to_string(), - title: "Prompt renderer".to_string(), - purpose: "Render Epiphany state into developer context".to_string(), - code_refs: vec![code_ref("epiphany-state-model/src/prompt.rs")], - ..Default::default() - }); - state.observations[0] - .code_refs - .push(code_ref("epiphany-core/src/proposal.rs")); - - let proposal = propose_map_update(EpiphanyMapProposalInput { - state, - observation_ids: vec!["obs-verified".to_string()], - }) - .expect("proposal"); - - assert_eq!(proposal.churn.understanding_status, "proposal_updates_map"); - assert_eq!(proposal.churn.diff_pressure, "high"); - } -} diff --git a/epiphany-core/src/reorientation_work.rs b/epiphany-core/src/reorientation_work.rs index e54b35ec..eb101da9 100644 --- a/epiphany-core/src/reorientation_work.rs +++ b/epiphany-core/src/reorientation_work.rs @@ -848,15 +848,12 @@ mod tests { fn reorientation_has_no_aggregate_or_freshness_authority_path() { let coordinator = include_str!("bin/epiphany-mvp-coordinator.rs"); let status = include_str!("bin/epiphany-mvp-status.rs"); - let acceptance = include_str!("coordinator_acceptance.rs"); let agent_launch = include_str!("agent_launch.rs"); let worker_launch = include_str!("surfaces/worker_launch.rs"); for (source, forbidden) in [ (coordinator, "build_epiphany_reorient_launch_request"), (status, "recommend_reorientation"), (status, "crrc_regather_current_after_relinquishment"), - (acceptance, "accept_coordinator_reorient_finding"), - (acceptance, "build_native_reorient_acceptance_update"), (agent_launch, "build_epiphany_reorient_launch_request"), (worker_launch, "EpiphanyReorientLaunchRequestInput"), ] { @@ -913,7 +910,7 @@ mod tests { request .source_documents .iter() - .all(|source| { source.document_type != crate::EpiphanyThreadStateEntry::TYPE }) + .all(|source| source.document_type != "epiphany.thread_state") ); assert_eq!( crate::project_current_work(&store)? @@ -1170,8 +1167,9 @@ mod tests { ); assert!( accepted - .get::(crate::THREAD_STATE_KEY)? - .is_none() + .snapshot_envelopes() + .iter() + .all(|envelope| envelope.r#type != "epiphany.thread_state") ); let mut stale = crate::runtime_spine_cache(&stale_store)?; diff --git a/epiphany-core/src/resident_self.rs b/epiphany-core/src/resident_self.rs index 39bc9332..40022b63 100644 --- a/epiphany-core/src/resident_self.rs +++ b/epiphany-core/src/resident_self.rs @@ -1309,49 +1309,6 @@ pub fn resident_self_body_modeling_pressure( })) } -fn role_projection_is_terminal_for_continuation( - runtime_store: &Path, - thread_id: &str, - role: crate::EpiphanyRoleResultRoleId, - binding_id: &str, -) -> Result { - let mut runtime = crate::runtime_spine_cache(runtime_store)?; - runtime.pull_all_backing_stores()?; - let entry = runtime.get::(crate::THREAD_STATE_KEY)?; - let state = entry - .as_ref() - .filter(|entry| entry.thread_id == thread_id) - .map(crate::EpiphanyThreadStateEntry::state) - .transpose()?; - let snapshot = - crate::read_role_result_snapshot(state.as_ref(), Some(runtime_store), role, binding_id); - Ok(matches!( - snapshot.status, - crate::EpiphanyCoordinatorRoleResultStatus::Completed - | crate::EpiphanyCoordinatorRoleResultStatus::Failed - | crate::EpiphanyCoordinatorRoleResultStatus::Cancelled - )) -} - -fn resident_continuation_launch_was_overtaken( - runtime_store: &Path, - action: &str, - thread_id: &str, -) -> Result { - match action { - // These legacy checkpoint lanes do not yet expose an exact current - // request projection. Keep their existing role-slot behavior explicit - // rather than pretending it is the same authority as Research. - "launchModeling" => role_projection_is_terminal_for_continuation( - runtime_store, - thread_id, - crate::EpiphanyRoleResultRoleId::Modeling, - crate::EPIPHANY_MODELING_ROLE_BINDING_ID, - ), - _ => Ok(false), - } -} - pub(crate) fn resident_self_safe_continuation_action( runtime_store: &Path, receipt: &crate::EpiphanyCoordinatorRunReceipt, @@ -1432,44 +1389,16 @@ pub(crate) fn resident_self_safe_continuation_action( } let direct = matches!( receipt.final_action.as_str(), - "launchModeling" - | "startFrontierPlanning" + "startFrontierPlanning" | "launchImagination" | "requestMindPlanReview" | "launchMindPlanReview" | "commitFrontierPlanDecision" ); if direct { - if resident_continuation_launch_was_overtaken( - runtime_store, - &receipt.final_action, - &receipt.thread_id, - )? { - return Ok(None); - } return Ok(Some(receipt.final_action.clone())); } let action = match receipt.final_action.as_str() { - "reviewModelingResult" - if role_projection_is_terminal_for_continuation( - runtime_store, - &receipt.thread_id, - crate::EpiphanyRoleResultRoleId::Modeling, - crate::EPIPHANY_MODELING_ROLE_BINDING_ID, - )? => - { - Some("reviewModelingResult") - } - "waitForModelingResult" - if role_projection_is_terminal_for_continuation( - runtime_store, - &receipt.thread_id, - crate::EpiphanyRoleResultRoleId::Modeling, - crate::EPIPHANY_MODELING_ROLE_BINDING_ID, - )? => - { - Some("reviewModelingResult") - } "waitForImaginationResult" => { match crate::runtime_repo_frontier_planning_lifecycle(runtime_store)?.stage { crate::RepoFrontierPlanningLifecycleStage::ImaginationResultReady => { diff --git a/epiphany-core/src/runtime_spine.rs b/epiphany-core/src/runtime_spine.rs index d4cd722c..9c30dca2 100644 --- a/epiphany-core/src/runtime_spine.rs +++ b/epiphany-core/src/runtime_spine.rs @@ -105,8 +105,6 @@ use crate::substrate_gate::SUBSTRATE_GATE_REPO_MUTATION_RECEIPT_TYPE; use crate::substrate_gate::SUBSTRATE_GATE_REPO_SNAPSHOT_RECEIPT_SCHEMA_VERSION; use crate::substrate_gate::SUBSTRATE_GATE_REPO_SNAPSHOT_RECEIPT_TYPE; use crate::substrate_gate::SubstrateGateRepoAccessGrantReceipt; -use crate::thread_state_store::THREAD_STATE_SCHEMA_VERSION; -use crate::thread_state_store::THREAD_STATE_TYPE; use crate::{RuntimeTypedRequestRef, WorkerProcessStatus}; use anyhow::Context; use anyhow::Result; @@ -1106,7 +1104,6 @@ pub fn runtime_spine_cache(store_path: impl AsRef) -> Result { let store_path = store_path.as_ref(); let mut cache = CultCache::new(); crate::mind_documents::register_mind_document_types(&mut cache)?; - cache.register_entry_type::()?; cache.register_entry_type::()?; cache.register_entry_type::()?; cache.register_entry_type::()?; @@ -13733,17 +13730,6 @@ fn epiphany_mutation_contracts() -> Vec { "The ledger is inspected as durable memory; writes are mediated by role-specific state flows.", ], ), - mutation_contract( - THREAD_STATE_TYPE, - THREAD_STATE_SCHEMA_VERSION, - vec![CultNetDocumentOperation::Snapshot], - CultNetMutationAuthority::ReadOnly, - vec![], - vec![], - vec![ - "The mirrored thread state is the typed repo/control-plane state source; Codex rollout is a compatibility source, not the network contract.", - ], - ), mutation_contract( EPIPHANY_CULTMESH_OPERATOR_SNAPSHOT_TYPE, EPIPHANY_CULTMESH_OPERATOR_SNAPSHOT_SCHEMA_VERSION, diff --git a/epiphany-core/src/state_update.rs b/epiphany-core/src/state_update.rs deleted file mode 100644 index 8ebe6929..00000000 --- a/epiphany-core/src/state_update.rs +++ /dev/null @@ -1,1057 +0,0 @@ -use crate::EpiphanyStateReplacementValidationInput; -use crate::validate_state_replacement_patch; -use epiphany_state_model::EpiphanyAcceptanceReceipt; -use epiphany_state_model::EpiphanyChurnState; -use epiphany_state_model::EpiphanyEvidenceRecord; -use epiphany_state_model::EpiphanyGraphCheckpoint; -use epiphany_state_model::EpiphanyGraphFrontier; -use epiphany_state_model::EpiphanyGraphs; -use epiphany_state_model::EpiphanyInvariant; -use epiphany_state_model::EpiphanyInvestigationCheckpoint; -use epiphany_state_model::EpiphanyJobBinding; -use epiphany_state_model::EpiphanyModeState; -use epiphany_state_model::EpiphanyObservation; -use epiphany_state_model::EpiphanyPlanningSourceRef; -use epiphany_state_model::EpiphanyPlanningState; -use epiphany_state_model::EpiphanyRuntimeLink; -use epiphany_state_model::EpiphanyScratchPad; -use epiphany_state_model::EpiphanySubgoal; -use epiphany_state_model::EpiphanyThreadState; -use std::collections::HashSet; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum EpiphanyStateUpdatedField { - Objective, - ActiveSubgoalId, - Subgoals, - Invariants, - Graphs, - GraphFrontier, - GraphCheckpoint, - Scratch, - InvestigationCheckpoint, - JobBindings, - AcceptanceReceipts, - RuntimeLinks, - Observations, - Evidence, - Churn, - Mode, - Planning, -} - -#[derive(Debug, Clone, Default)] -pub struct EpiphanyStateUpdate { - pub expected_revision: Option, - pub objective: Option, - pub active_subgoal_id: Option, - pub subgoals: Option>, - pub invariants: Option>, - pub graphs: Option, - pub graph_frontier: Option, - pub graph_checkpoint: Option, - pub scratch: Option, - pub investigation_checkpoint: Option, - pub job_bindings: Option>, - pub acceptance_receipts: Vec, - pub runtime_links: Vec, - pub observations: Vec, - pub evidence: Vec, - pub churn: Option, - pub mode: Option, - pub planning: Option, -} - -impl EpiphanyStateUpdate { - pub fn is_empty(&self) -> bool { - self.objective.is_none() - && self.active_subgoal_id.is_none() - && self.subgoals.is_none() - && self.invariants.is_none() - && self.graphs.is_none() - && self.graph_frontier.is_none() - && self.graph_checkpoint.is_none() - && self.scratch.is_none() - && self.investigation_checkpoint.is_none() - && self.job_bindings.is_none() - && self.acceptance_receipts.is_empty() - && self.runtime_links.is_empty() - && self.observations.is_empty() - && self.evidence.is_empty() - && self.churn.is_none() - && self.mode.is_none() - && self.planning.is_none() - } -} - -pub fn epiphany_state_update_validation_errors( - state: &EpiphanyThreadState, - update: &EpiphanyStateUpdate, -) -> Vec { - let mut errors = Vec::new(); - let mut known_evidence_ids: HashSet<&str> = state - .recent_evidence - .iter() - .filter_map(|evidence| nonempty_id(&evidence.id)) - .collect(); - let existing_evidence_ids = known_evidence_ids.clone(); - let existing_observation_ids: HashSet<&str> = state - .observations - .iter() - .filter_map(|observation| nonempty_id(&observation.id)) - .collect(); - - let mut patch_evidence_ids = HashSet::new(); - for evidence in &update.evidence { - require_nonempty_update(&evidence.id, "patch.evidence.id", &mut errors); - require_nonempty_update(&evidence.kind, "patch.evidence.kind", &mut errors); - require_nonempty_update(&evidence.status, "patch.evidence.status", &mut errors); - require_nonempty_update(&evidence.summary, "patch.evidence.summary", &mut errors); - if !evidence.id.is_empty() && !patch_evidence_ids.insert(evidence.id.as_str()) { - errors.push(format!("duplicate evidence id {:?}", evidence.id)); - } - if existing_evidence_ids.contains(evidence.id.as_str()) { - errors.push(format!( - "evidence id {:?} already exists in Epiphany state", - evidence.id - )); - } - if let Some(id) = nonempty_id(&evidence.id) { - known_evidence_ids.insert(id); - } - } - - let mut patch_observation_ids = HashSet::new(); - for observation in &update.observations { - require_nonempty_update(&observation.id, "patch.observations.id", &mut errors); - require_nonempty_update( - &observation.summary, - "patch.observations.summary", - &mut errors, - ); - require_nonempty_update( - &observation.source_kind, - "patch.observations.source_kind", - &mut errors, - ); - require_nonempty_update( - &observation.status, - "patch.observations.status", - &mut errors, - ); - if !observation.id.is_empty() && !patch_observation_ids.insert(observation.id.as_str()) { - errors.push(format!("duplicate observation id {:?}", observation.id)); - } - if existing_observation_ids.contains(observation.id.as_str()) { - errors.push(format!( - "observation id {:?} already exists in Epiphany state", - observation.id - )); - } - if observation.evidence_ids.is_empty() { - errors.push(format!( - "observation {:?} must cite at least one evidence id", - observation.id - )); - } - for evidence_id in &observation.evidence_ids { - if !known_evidence_ids.contains(evidence_id.as_str()) { - errors.push(format!( - "observation {:?} cites missing evidence id {:?}", - observation.id, evidence_id - )); - } - } - } - - if let Some(checkpoint) = update.investigation_checkpoint.as_ref() { - for evidence_id in &checkpoint.evidence_ids { - if !known_evidence_ids.contains(evidence_id.as_str()) { - errors.push(format!( - "investigation checkpoint cites missing evidence id {:?}", - evidence_id - )); - } - } - } - - if let Some(job_bindings) = update.job_bindings.as_ref() { - errors.extend(validate_epiphany_job_bindings(job_bindings)); - } - if !update.acceptance_receipts.is_empty() { - errors.extend(validate_epiphany_acceptance_receipts( - &state.acceptance_receipts, - &update.acceptance_receipts, - &known_evidence_ids, - )); - } - if !update.runtime_links.is_empty() { - errors.extend(validate_epiphany_runtime_links( - &state.runtime_links, - &update.runtime_links, - )); - } - if let Some(planning) = update.planning.as_ref() { - errors.extend(validate_epiphany_planning_state(planning)); - } - - errors.extend(epiphany_state_replacement_validation_errors(state, update)); - errors -} - -pub fn apply_epiphany_state_update( - state: &mut EpiphanyThreadState, - update: EpiphanyStateUpdate, - reference_turn_id: Option, -) { - if let Some(objective) = update.objective { - state.objective = Some(objective); - } - if let Some(active_subgoal_id) = update.active_subgoal_id { - state.active_subgoal_id = Some(active_subgoal_id); - } - if let Some(subgoals) = update.subgoals { - state.subgoals = subgoals; - } - if let Some(invariants) = update.invariants { - state.invariants = invariants; - } - if let Some(graphs) = update.graphs { - state.graphs = graphs; - } - if let Some(graph_frontier) = update.graph_frontier { - state.graph_frontier = Some(graph_frontier); - } - if let Some(graph_checkpoint) = update.graph_checkpoint { - state.graph_checkpoint = Some(graph_checkpoint); - } - if let Some(scratch) = update.scratch { - state.scratch = Some(scratch); - } - if let Some(checkpoint) = update.investigation_checkpoint { - state.investigation_checkpoint = Some(checkpoint); - } - if let Some(job_bindings) = update.job_bindings { - state.job_bindings = job_bindings; - } - prepend_recent(&mut state.acceptance_receipts, update.acceptance_receipts); - prepend_recent(&mut state.runtime_links, update.runtime_links); - if let Some(churn) = update.churn { - state.churn = Some(churn); - } - if let Some(mode) = update.mode { - state.mode = Some(mode); - } - if let Some(planning) = update.planning { - state.planning = planning; - } - - prepend_recent(&mut state.observations, update.observations); - prepend_recent(&mut state.recent_evidence, update.evidence); - state.revision = state.revision.saturating_add(1); - state.last_updated_turn_id = reference_turn_id; -} - -#[cfg(test)] -mod tests { - use super::*; - use epiphany_state_model::EpiphanyBacklogItem; - use epiphany_state_model::EpiphanyGraph; - use epiphany_state_model::EpiphanyGraphNode; - use epiphany_state_model::EpiphanyJobKind; - use epiphany_state_model::EpiphanyObjectiveDraft; - use epiphany_state_model::EpiphanyPlanningCapture; - use epiphany_state_model::EpiphanyPlanningPriority; - use epiphany_state_model::EpiphanyPlanningSourceRef; - use epiphany_state_model::EpiphanyRoadmapStream; - - fn evidence(id: &str) -> EpiphanyEvidenceRecord { - EpiphanyEvidenceRecord { - id: id.to_string(), - kind: "verification".to_string(), - status: "ok".to_string(), - summary: "Evidence summary".to_string(), - code_refs: Vec::new(), - } - } - - fn observation(id: &str, evidence_ids: Vec<&str>) -> EpiphanyObservation { - EpiphanyObservation { - id: id.to_string(), - summary: "Observation summary".to_string(), - source_kind: "smoke".to_string(), - status: "ok".to_string(), - code_refs: Vec::new(), - evidence_ids: evidence_ids.into_iter().map(str::to_string).collect(), - } - } - - fn job_binding(id: &str) -> EpiphanyJobBinding { - EpiphanyJobBinding { - id: id.to_string(), - kind: EpiphanyJobKind::Specialist, - scope: "role-scoped specialist work".to_string(), - owner_role: "epiphany-harness".to_string(), - authority_scope: Some("epiphany.specialist".to_string()), - linked_subgoal_ids: vec!["phase-6".to_string()], - linked_graph_node_ids: vec!["job-surface".to_string()], - blocking_reason: None, - } - } - - fn acceptance_receipt( - id: &str, - result_id: &str, - evidence_id: &str, - ) -> EpiphanyAcceptanceReceipt { - EpiphanyAcceptanceReceipt { - id: id.to_string(), - result_id: result_id.to_string(), - job_id: "runtime-job-1".to_string(), - binding_id: "modeling".to_string(), - surface: "roleAccept".to_string(), - role_id: "modeling".to_string(), - status: "accepted".to_string(), - accepted_at: "2026-05-12T00:00:00Z".to_string(), - accepted_observation_id: Some("obs-modeling".to_string()), - accepted_evidence_id: Some(evidence_id.to_string()), - summary: Some("Accepted modeling result.".to_string()), - } - } - - #[test] - fn state_update_replaces_typed_fields_and_prepends_evidence() { - let mut state = EpiphanyThreadState { - revision: 3, - recent_evidence: vec![EpiphanyEvidenceRecord { - id: "old-evidence".to_string(), - kind: "research".to_string(), - status: "ok".to_string(), - summary: "Older finding".to_string(), - code_refs: Vec::new(), - }], - ..Default::default() - }; - - apply_epiphany_state_update( - &mut state, - EpiphanyStateUpdate { - objective: Some("Keep the map honest".to_string()), - investigation_checkpoint: Some(EpiphanyInvestigationCheckpoint { - checkpoint_id: "ix-1".to_string(), - kind: "slice_planning".to_string(), - focus: "Keep the durable packet small and explicit.".to_string(), - next_action: Some( - "Resume from the packet instead of the ghost transcript.".to_string(), - ), - ..Default::default() - }), - evidence: vec![EpiphanyEvidenceRecord { - id: "new-evidence".to_string(), - kind: "verification".to_string(), - status: "ok".to_string(), - summary: "New finding".to_string(), - code_refs: Vec::new(), - }], - churn: Some(EpiphanyChurnState { - understanding_status: "grounded".to_string(), - diff_pressure: "low".to_string(), - ..Default::default() - }), - ..Default::default() - }, - Some("turn-1".to_string()), - ); - - assert_eq!(state.revision, 4); - assert_eq!(state.objective.as_deref(), Some("Keep the map honest")); - assert_eq!(state.last_updated_turn_id.as_deref(), Some("turn-1")); - assert_eq!( - state - .investigation_checkpoint - .as_ref() - .map(|checkpoint| checkpoint.checkpoint_id.as_str()), - Some("ix-1") - ); - assert_eq!(state.recent_evidence[0].id, "new-evidence"); - assert_eq!(state.recent_evidence[1].id, "old-evidence"); - assert_eq!( - state - .churn - .as_ref() - .map(|churn| churn.diff_pressure.as_str()), - Some("low") - ); - } - - #[test] - fn state_update_replaces_job_bindings_and_prepends_acceptance_receipts() { - let mut state = EpiphanyThreadState { - revision: 2, - recent_evidence: vec![evidence("ev-new")], - job_bindings: vec![job_binding("old")], - acceptance_receipts: vec![acceptance_receipt("accept-old", "result-old", "ev-old")], - ..Default::default() - }; - - apply_epiphany_state_update( - &mut state, - EpiphanyStateUpdate { - job_bindings: Some(vec![job_binding("new")]), - acceptance_receipts: vec![acceptance_receipt("accept-new", "result-new", "ev-new")], - ..Default::default() - }, - Some("turn-jobs".to_string()), - ); - - assert_eq!(state.revision, 3); - assert_eq!(state.job_bindings.len(), 1); - assert_eq!(state.job_bindings[0].id, "new"); - assert_eq!( - state.job_bindings[0].authority_scope.as_deref(), - Some("epiphany.specialist") - ); - assert_eq!(state.acceptance_receipts[0].id, "accept-new"); - assert_eq!(state.acceptance_receipts[1].id, "accept-old"); - } - - #[test] - fn state_update_validation_accepts_and_rejects_planning_state() { - let valid = EpiphanyStateUpdate { - planning: Some(EpiphanyPlanningState { - captures: vec![EpiphanyPlanningCapture { - id: "capture-github-42".to_string(), - title: "Import issue backlog".to_string(), - confidence: "medium".to_string(), - status: "new".to_string(), - source: EpiphanyPlanningSourceRef { - kind: "github_issue".to_string(), - provider: Some("github".to_string()), - repo: Some("GameCult/Epiphany".to_string()), - issue_number: Some(42), - ..Default::default() - }, - ..Default::default() - }], - backlog_items: vec![EpiphanyBacklogItem { - id: "backlog-planning-api".to_string(), - title: "Expose planning projection".to_string(), - kind: "feature".to_string(), - summary: "Make planning state queryable by the GUI.".to_string(), - status: "ready".to_string(), - horizon: "now".to_string(), - priority: EpiphanyPlanningPriority { - value: "p1".to_string(), - rationale: "Unblocks planning operations.".to_string(), - ..Default::default() - }, - confidence: "high".to_string(), - product_area: "gui".to_string(), - lane_hints: vec!["imagination".to_string()], - ..Default::default() - }], - roadmap_streams: vec![EpiphanyRoadmapStream { - id: "stream-gui".to_string(), - title: "GUI Operator Surface".to_string(), - purpose: "Let the human inspect and steer planning.".to_string(), - status: "active".to_string(), - item_ids: vec!["backlog-planning-api".to_string()], - ..Default::default() - }], - objective_drafts: vec![EpiphanyObjectiveDraft { - id: "objdraft-planning-api".to_string(), - title: "Build planning API slice".to_string(), - summary: "Land typed planning state and read-only projection.".to_string(), - source_item_ids: vec!["backlog-planning-api".to_string()], - acceptance_criteria: vec!["Projection returns planning counts.".to_string()], - status: "draft".to_string(), - ..Default::default() - }], - ..Default::default() - }), - ..Default::default() - }; - assert!( - epiphany_state_update_validation_errors(&EpiphanyThreadState::default(), &valid) - .is_empty() - ); - - let invalid = EpiphanyStateUpdate { - planning: Some(EpiphanyPlanningState { - captures: vec![EpiphanyPlanningCapture { - id: "capture-bad-github".to_string(), - title: "Missing repo issue".to_string(), - confidence: "medium".to_string(), - status: "new".to_string(), - source: EpiphanyPlanningSourceRef { - kind: "github_issue".to_string(), - issue_number: None, - ..Default::default() - }, - ..Default::default() - }], - backlog_items: vec![EpiphanyBacklogItem { - id: "backlog-1".to_string(), - title: "Backlog without priority rationale".to_string(), - kind: "feature".to_string(), - summary: "Invalid on purpose.".to_string(), - status: "ready".to_string(), - horizon: "now".to_string(), - priority: EpiphanyPlanningPriority { - value: "p1".to_string(), - rationale: String::new(), - ..Default::default() - }, - confidence: "high".to_string(), - product_area: "gui".to_string(), - ..Default::default() - }], - roadmap_streams: vec![EpiphanyRoadmapStream { - id: "stream-gui".to_string(), - title: "GUI Operator Surface".to_string(), - purpose: "Let the human inspect and steer planning.".to_string(), - status: "active".to_string(), - item_ids: vec!["missing-backlog".to_string()], - ..Default::default() - }], - objective_drafts: vec![EpiphanyObjectiveDraft { - id: "objdraft-empty".to_string(), - title: "Empty acceptance draft".to_string(), - summary: "Invalid on purpose.".to_string(), - source_item_ids: vec!["missing-backlog".to_string()], - status: "draft".to_string(), - ..Default::default() - }], - ..Default::default() - }), - ..Default::default() - }; - - let errors = - epiphany_state_update_validation_errors(&EpiphanyThreadState::default(), &invalid); - assert!( - errors - .iter() - .any(|error| error.contains("repo is required for github_issue")) - ); - assert!( - errors - .iter() - .any(|error| error.contains("priority.rationale")) - ); - assert!( - errors - .iter() - .any(|error| error.contains("references missing backlog item")) - ); - assert!( - errors - .iter() - .any(|error| error.contains("must include at least one acceptance criterion")) - ); - } - - #[test] - fn state_update_validation_rejects_bad_evidence_observations_acceptance_and_bindings() { - let state = EpiphanyThreadState { - observations: vec![observation("obs-existing", vec!["ev-existing"])], - recent_evidence: vec![evidence("ev-existing"), evidence("ev-new")], - acceptance_receipts: vec![acceptance_receipt( - "accept-existing", - "result-existing", - "ev-existing", - )], - ..Default::default() - }; - let update = EpiphanyStateUpdate { - observations: vec![ - observation("obs-existing", vec!["ev-new"]), - observation("obs-dup", vec!["ev-new"]), - observation("obs-dup", vec!["ev-missing"]), - EpiphanyObservation { - id: String::new(), - ..observation("unused", vec!["ev-new"]) - }, - ], - evidence: vec![ - evidence("ev-existing"), - evidence("ev-new"), - evidence("ev-new"), - EpiphanyEvidenceRecord { - id: String::new(), - ..evidence("unused") - }, - ], - acceptance_receipts: vec![ - acceptance_receipt("accept-new", "result-existing", "ev-new"), - acceptance_receipt("accept-new", "result-new", "ev-new"), - ], - job_bindings: Some(vec![ - job_binding("dup"), - job_binding("dup"), - EpiphanyJobBinding { - id: String::new(), - kind: EpiphanyJobKind::Verification, - scope: String::new(), - owner_role: String::new(), - authority_scope: Some(String::new()), - linked_subgoal_ids: Vec::new(), - linked_graph_node_ids: Vec::new(), - blocking_reason: Some(String::new()), - }, - ]), - ..Default::default() - }; - - let errors = epiphany_state_update_validation_errors(&state, &update); - assert!( - errors - .iter() - .any(|error| error.contains("evidence id \"ev-existing\" already exists")) - ); - assert!( - errors - .iter() - .any(|error| error.contains("duplicate evidence id \"ev-new\"")) - ); - assert!( - errors - .iter() - .any(|error| error.contains("observation id \"obs-existing\" already exists")) - ); - assert!( - errors - .iter() - .any(|error| error.contains("duplicate observation id \"obs-dup\"")) - ); - assert!( - errors - .iter() - .any(|error| error.contains("cites missing evidence id")) - ); - assert!( - errors - .iter() - .any(|error| error.contains("runtime result \"result-existing\" already has")) - ); - assert!( - errors - .iter() - .any(|error| error.contains("acceptance receipt id \"accept-new\" is duplicated")) - ); - assert!( - errors - .iter() - .any(|error| error.contains("duplicate job binding id")) - ); - assert!( - errors - .iter() - .any(|error| error.contains("job_binding.id must not be empty")) - ); - assert!( - errors - .iter() - .any(|error| error.contains("job_binding.scope must not be empty")) - ); - assert!( - errors - .iter() - .any(|error| error.contains("job_binding.owner_role must not be empty")) - ); - assert!( - errors - .iter() - .any(|error| error.contains("job_binding.authority_scope must not be empty")) - ); - assert!( - errors - .iter() - .any(|error| error.contains("job_binding.blocking_reason must not be empty")) - ); - } - - #[test] - fn state_update_validation_rejects_structural_replacements_and_checkpoint_evidence_gap() { - let state = EpiphanyThreadState { - graphs: EpiphanyGraphs { - architecture: EpiphanyGraph { - nodes: vec![EpiphanyGraphNode { - id: "state".to_string(), - title: "State".to_string(), - purpose: "Carry the explicit map".to_string(), - ..Default::default() - }], - edges: Vec::new(), - }, - ..Default::default() - }, - ..Default::default() - }; - let frontier_update = EpiphanyStateUpdate { - graph_frontier: Some(EpiphanyGraphFrontier { - active_node_ids: vec!["missing".to_string()], - ..Default::default() - }), - ..Default::default() - }; - let errors = epiphany_state_update_validation_errors(&state, &frontier_update); - assert!( - errors - .iter() - .any(|error| error.contains("graph frontier references missing node")) - ); - - let checkpoint_update = EpiphanyStateUpdate { - investigation_checkpoint: Some(EpiphanyInvestigationCheckpoint { - checkpoint_id: "ix-missing".to_string(), - kind: "source_gathering".to_string(), - focus: "Trace the compaction seam.".to_string(), - next_action: Some("Re-gather source before implementation.".to_string()), - evidence_ids: vec!["ev-missing".to_string()], - ..Default::default() - }), - ..Default::default() - }; - let errors = epiphany_state_update_validation_errors( - &EpiphanyThreadState::default(), - &checkpoint_update, - ); - assert!( - errors - .iter() - .any(|error| error.contains("investigation checkpoint cites missing evidence id")) - ); - } -} - -fn validate_epiphany_runtime_links( - existing: &[EpiphanyRuntimeLink], - links: &[EpiphanyRuntimeLink], -) -> Vec { - let mut errors = Vec::new(); - let mut seen_ids = existing - .iter() - .map(|link| link.id.as_str()) - .collect::>(); - for link in links { - require_nonempty_update(&link.id, "runtime_link.id", &mut errors); - require_nonempty_update(&link.binding_id, "runtime_link.binding_id", &mut errors); - require_nonempty_update(&link.surface, "runtime_link.surface", &mut errors); - require_nonempty_update(&link.role_id, "runtime_link.role_id", &mut errors); - require_nonempty_update( - &link.authority_scope, - "runtime_link.authority_scope", - &mut errors, - ); - require_nonempty_update( - &link.runtime_job_id, - "runtime_link.runtime_job_id", - &mut errors, - ); - if !seen_ids.insert(link.id.as_str()) { - errors.push(format!("runtime link id {:?} is duplicated", link.id)); - } - } - errors -} - -fn validate_epiphany_acceptance_receipts( - existing: &[EpiphanyAcceptanceReceipt], - receipts: &[EpiphanyAcceptanceReceipt], - known_evidence_ids: &HashSet<&str>, -) -> Vec { - let mut errors = Vec::new(); - let mut seen_ids = existing - .iter() - .map(|receipt| receipt.id.as_str()) - .collect::>(); - let mut seen_result_ids = existing - .iter() - .map(|receipt| receipt.result_id.as_str()) - .collect::>(); - - for receipt in receipts { - require_nonempty_update(&receipt.id, "acceptance_receipt.id", &mut errors); - require_nonempty_update( - &receipt.result_id, - "acceptance_receipt.result_id", - &mut errors, - ); - require_nonempty_update(&receipt.job_id, "acceptance_receipt.job_id", &mut errors); - require_nonempty_update( - &receipt.binding_id, - "acceptance_receipt.binding_id", - &mut errors, - ); - require_nonempty_update(&receipt.surface, "acceptance_receipt.surface", &mut errors); - require_nonempty_update(&receipt.role_id, "acceptance_receipt.role_id", &mut errors); - require_nonempty_update(&receipt.status, "acceptance_receipt.status", &mut errors); - require_nonempty_update( - &receipt.accepted_at, - "acceptance_receipt.accepted_at", - &mut errors, - ); - if !seen_ids.insert(receipt.id.as_str()) { - errors.push(format!( - "acceptance receipt id {:?} is duplicated", - receipt.id - )); - } - if !seen_result_ids.insert(receipt.result_id.as_str()) { - errors.push(format!( - "runtime result {:?} already has an acceptance receipt", - receipt.result_id - )); - } - if let Some(evidence_id) = receipt.accepted_evidence_id.as_deref() - && !known_evidence_ids.contains(evidence_id) - { - errors.push(format!( - "acceptance receipt {:?} cites missing evidence id {:?}", - receipt.id, evidence_id - )); - } - } - - errors -} - -fn validate_epiphany_job_bindings(job_bindings: &[EpiphanyJobBinding]) -> Vec { - let mut errors = Vec::new(); - let mut seen_ids = HashSet::<&str>::new(); - - for binding in job_bindings { - require_nonempty_update(&binding.id, "job_binding.id", &mut errors); - require_nonempty_update(&binding.scope, "job_binding.scope", &mut errors); - require_nonempty_update(&binding.owner_role, "job_binding.owner_role", &mut errors); - if let Some(authority_scope) = binding.authority_scope.as_deref() { - require_nonempty_update(authority_scope, "job_binding.authority_scope", &mut errors); - } - if let Some(blocking_reason) = binding.blocking_reason.as_deref() { - require_nonempty_update(blocking_reason, "job_binding.blocking_reason", &mut errors); - } - if !binding.id.is_empty() && !seen_ids.insert(binding.id.as_str()) { - errors.push(format!("duplicate job binding id {:?}", binding.id)); - } - } - - errors -} - -fn validate_epiphany_planning_state(planning: &EpiphanyPlanningState) -> Vec { - let mut errors = Vec::new(); - let mut capture_ids = HashSet::<&str>::new(); - for capture in &planning.captures { - require_nonempty_update(&capture.id, "planning.captures.id", &mut errors); - require_nonempty_update(&capture.title, "planning.captures.title", &mut errors); - require_nonempty_update( - &capture.confidence, - "planning.captures.confidence", - &mut errors, - ); - require_nonempty_update(&capture.status, "planning.captures.status", &mut errors); - validate_epiphany_planning_source_ref( - &capture.source, - "planning.captures.source", - &mut errors, - ); - if !capture.id.is_empty() && !capture_ids.insert(capture.id.as_str()) { - errors.push(format!("duplicate planning capture id {:?}", capture.id)); - } - } - - let mut backlog_ids = HashSet::<&str>::new(); - for item in &planning.backlog_items { - require_nonempty_update(&item.id, "planning.backlog_items.id", &mut errors); - require_nonempty_update(&item.title, "planning.backlog_items.title", &mut errors); - require_nonempty_update(&item.kind, "planning.backlog_items.kind", &mut errors); - require_nonempty_update(&item.summary, "planning.backlog_items.summary", &mut errors); - require_nonempty_update(&item.status, "planning.backlog_items.status", &mut errors); - require_nonempty_update(&item.horizon, "planning.backlog_items.horizon", &mut errors); - require_nonempty_update( - &item.priority.value, - "planning.backlog_items.priority.value", - &mut errors, - ); - require_nonempty_update( - &item.priority.rationale, - "planning.backlog_items.priority.rationale", - &mut errors, - ); - require_nonempty_update( - &item.confidence, - "planning.backlog_items.confidence", - &mut errors, - ); - require_nonempty_update( - &item.product_area, - "planning.backlog_items.product_area", - &mut errors, - ); - for (index, source_ref) in item.source_refs.iter().enumerate() { - validate_epiphany_planning_source_ref( - source_ref, - &format!("planning.backlog_items.source_refs[{index}]"), - &mut errors, - ); - } - if !item.id.is_empty() && !backlog_ids.insert(item.id.as_str()) { - errors.push(format!("duplicate planning backlog item id {:?}", item.id)); - } - } - - let mut stream_ids = HashSet::<&str>::new(); - for stream in &planning.roadmap_streams { - require_nonempty_update(&stream.id, "planning.roadmap_streams.id", &mut errors); - require_nonempty_update(&stream.title, "planning.roadmap_streams.title", &mut errors); - require_nonempty_update( - &stream.purpose, - "planning.roadmap_streams.purpose", - &mut errors, - ); - require_nonempty_update( - &stream.status, - "planning.roadmap_streams.status", - &mut errors, - ); - for item_id in &stream.item_ids { - if !backlog_ids.contains(item_id.as_str()) { - errors.push(format!( - "roadmap stream {:?} references missing backlog item {:?}", - stream.id, item_id - )); - } - } - if let Some(near_term_focus) = stream.near_term_focus.as_deref() - && !near_term_focus.trim().is_empty() - && !backlog_ids.contains(near_term_focus) - { - errors.push(format!( - "roadmap stream {:?} has missing near_term_focus {:?}", - stream.id, near_term_focus - )); - } - if !stream.id.is_empty() && !stream_ids.insert(stream.id.as_str()) { - errors.push(format!( - "duplicate planning roadmap stream id {:?}", - stream.id - )); - } - } - - let mut objective_draft_ids = HashSet::<&str>::new(); - for draft in &planning.objective_drafts { - require_nonempty_update(&draft.id, "planning.objective_drafts.id", &mut errors); - require_nonempty_update(&draft.title, "planning.objective_drafts.title", &mut errors); - require_nonempty_update( - &draft.summary, - "planning.objective_drafts.summary", - &mut errors, - ); - require_nonempty_update( - &draft.status, - "planning.objective_drafts.status", - &mut errors, - ); - if draft.acceptance_criteria.is_empty() { - errors.push(format!( - "objective draft {:?} must include at least one acceptance criterion", - draft.id - )); - } - for item_id in &draft.source_item_ids { - if !backlog_ids.contains(item_id.as_str()) { - errors.push(format!( - "objective draft {:?} references missing source backlog item {:?}", - draft.id, item_id - )); - } - } - if !draft.id.is_empty() && !objective_draft_ids.insert(draft.id.as_str()) { - errors.push(format!("duplicate objective draft id {:?}", draft.id)); - } - } - - errors -} - -fn validate_epiphany_planning_source_ref( - source_ref: &EpiphanyPlanningSourceRef, - label: &str, - errors: &mut Vec, -) { - require_nonempty_update(&source_ref.kind, &format!("{label}.kind"), errors); - if source_ref.kind == "github_issue" { - match source_ref.repo.as_deref() { - Some(repo) => require_nonempty_update(repo, &format!("{label}.repo"), errors), - None => errors.push(format!("{label}.repo is required for github_issue sources")), - } - if source_ref.issue_number.is_none() { - errors.push(format!( - "{label}.issue_number is required for github_issue sources" - )); - } - } -} - -fn epiphany_state_replacement_validation_errors( - state: &EpiphanyThreadState, - update: &EpiphanyStateUpdate, -) -> Vec { - let validates_subgoal_target = update.subgoals.is_some() || update.active_subgoal_id.is_some(); - let validates_graph_target = update.graphs.is_some() - || update.graph_frontier.is_some() - || update.graph_checkpoint.is_some(); - let mut known_evidence_ids: HashSet<&str> = state - .recent_evidence - .iter() - .filter_map(|evidence| nonempty_id(&evidence.id)) - .collect(); - for evidence in &update.evidence { - if let Some(id) = nonempty_id(&evidence.id) { - known_evidence_ids.insert(id); - } - } - - validate_state_replacement_patch(EpiphanyStateReplacementValidationInput { - active_subgoal_id: update.active_subgoal_id.as_deref(), - subgoals: if validates_subgoal_target { - update - .subgoals - .as_deref() - .or(Some(state.subgoals.as_slice())) - } else { - None - }, - invariants: update.invariants.as_deref(), - graphs: if validates_graph_target { - update.graphs.as_ref().or(Some(&state.graphs)) - } else { - None - }, - graph_frontier: update.graph_frontier.as_ref(), - graph_checkpoint: update.graph_checkpoint.as_ref(), - investigation_checkpoint: update.investigation_checkpoint.as_ref(), - available_evidence_ids: Some(&known_evidence_ids), - churn: update.churn.as_ref(), - }) -} - -fn nonempty_id(id: &str) -> Option<&str> { - if id.is_empty() { None } else { Some(id) } -} - -fn require_nonempty_update(value: &str, label: &str, errors: &mut Vec) { - if value.trim().is_empty() { - errors.push(format!("{label} must not be empty")); - } -} - -fn prepend_recent(items: &mut Vec, mut new_items: Vec) { - if new_items.is_empty() { - return; - } - new_items.append(items); - *items = new_items; -} diff --git a/epiphany-core/src/thread_state_store.rs b/epiphany-core/src/thread_state_store.rs deleted file mode 100644 index 9b86eddc..00000000 --- a/epiphany-core/src/thread_state_store.rs +++ /dev/null @@ -1,113 +0,0 @@ -use anyhow::Result; -use anyhow::anyhow; -use cultcache_rs::CultCache; -use cultcache_rs::DatabaseEntry; -use cultcache_rs::SingleFileMessagePackBackingStore; -use epiphany_state_model::EpiphanyThreadState; -use std::path::Path; - -pub const THREAD_STATE_TYPE: &str = "epiphany.thread_state"; -pub const THREAD_STATE_KEY: &str = "default"; -pub const THREAD_STATE_SCHEMA_VERSION: &str = "epiphany.thread_state.v0"; - -#[derive(Clone, Debug, PartialEq, DatabaseEntry)] -#[cultcache(type = "epiphany.thread_state", schema = "EpiphanyThreadStateEntry")] -pub struct EpiphanyThreadStateEntry { - #[cultcache(key = 0)] - pub schema_version: String, - #[cultcache(key = 1)] - pub thread_id: String, - #[cultcache(key = 2)] - pub state_msgpack: Vec, -} - -impl EpiphanyThreadStateEntry { - pub fn from_state(thread_id: impl Into, state: &EpiphanyThreadState) -> Result { - let state_msgpack = rmp_serde::to_vec_named(state)?; - Ok(Self { - schema_version: THREAD_STATE_SCHEMA_VERSION.to_string(), - thread_id: thread_id.into(), - state_msgpack, - }) - } - - pub fn state(&self) -> Result { - rmp_serde::from_slice(&self.state_msgpack) - .map_err(|error| anyhow!("failed to decode Epiphany thread state MessagePack: {error}")) - } -} - -pub fn thread_state_cache(store_path: impl AsRef) -> Result { - let mut cache = CultCache::new(); - cache.register_entry_type::()?; - cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(store_path.as_ref())); - cache.pull_all_backing_stores()?; - Ok(cache) -} - -pub fn load_thread_state_entry( - store_path: impl AsRef, -) -> Result> { - let cache = thread_state_cache(store_path)?; - cache.get::(THREAD_STATE_KEY) -} - -pub fn load_thread_state(store_path: impl AsRef) -> Result> { - let Some(entry) = load_thread_state_entry(store_path)? else { - return Ok(None); - }; - validate_thread_state_entry(&entry)?; - Ok(Some(entry.state()?)) -} - -pub fn validate_thread_state_entry(entry: &EpiphanyThreadStateEntry) -> Result<()> { - if entry.schema_version != THREAD_STATE_SCHEMA_VERSION { - return Err(anyhow!( - "thread state schema_version is {:?}, expected {:?}", - entry.schema_version, - THREAD_STATE_SCHEMA_VERSION - )); - } - entry.state()?; - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - use epiphany_state_model::EpiphanyGraph; - use epiphany_state_model::EpiphanyGraphNode; - use epiphany_state_model::EpiphanyGraphs; - - #[test] - fn thread_state_round_trips_through_cultcache() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("thread-state.msgpack"); - let state = EpiphanyThreadState { - revision: 7, - objective: Some("Keep the graph native.".to_string()), - graphs: EpiphanyGraphs { - architecture: EpiphanyGraph { - nodes: vec![EpiphanyGraphNode { - id: "node-memory-graph".to_string(), - title: "Memory graph".to_string(), - purpose: "Own native graph memory.".to_string(), - status: Some("accepted".to_string()), - ..Default::default() - }], - ..Default::default() - }, - ..Default::default() - }, - ..Default::default() - }; - - let entry = EpiphanyThreadStateEntry::from_state("thread-1", &state)?; - thread_state_cache(&store)?.put(THREAD_STATE_KEY, &entry)?; - let loaded = load_thread_state(&store)?.expect("thread state should load"); - - assert_eq!(loaded.revision, 7); - assert_eq!(loaded.graphs.architecture.nodes.len(), 1); - Ok(()) - } -}