Delete aggregate thread state authority

This commit is contained in:
Meta Vens 2026-08-18 04:29:44 +02:00
commit 07d891ba6c
19 changed files with 112 additions and 5441 deletions

View file

@ -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")?,
)?;

View file

@ -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::<EpiphanyThreadStateEntry>(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::<EpiphanyThreadStateEntry>(THREAD_STATE_KEY)?
.context("fixture runtime lost launched thread state")?
.state()?;
EpiphanyCoordinatorService::new(&runtime_store).interrupt_job(
"fixture-thread",
&current,
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",

View file

@ -78,29 +78,78 @@ fn prepare_authority_family(store: &Path) -> Result<EpiphanyToolInvocationIntent
created_at: "2026-08-13T00:00:00Z".into(),
},
)?;
let state = EpiphanyThreadState::default();
let launch = build_epiphany_role_launch_request(
"public-source-no-grant-thread",
EpiphanyRoleResultRoleId::Research,
Some(state.revision),
Some(60),
&state,
)
.map_err(anyhow::Error::msg)?;
let plan = plan_coordinator_job_launch(
&state,
&launch,
let launch_document = EpiphanyWorkerLaunchDocument::Role(EpiphanyRoleWorkerLaunchDocument {
thread_id: "public-source-no-grant-thread".into(),
role_id: "research".into(),
state_revision: 0,
objective: Some("Prove the exact public-source grant boundary.".into()),
dynamic_prompt_context: None,
repository_body_observation_basis: None,
proposal_modeling_context: None,
frontier_verdict_modeling_context: None,
frontier_planning_context: None,
frontier_research_context: None,
frontier_verification_context: None,
frontier_plan_mind_context: None,
imagination_consideration_context: None,
admitted_model_direction_consideration_context: None,
active_subgoal_id: None,
active_subgoals: Vec::new(),
active_graph_node_ids: Vec::new(),
investigation_checkpoint: None,
scratch: None,
invariants: Vec::new(),
graphs: None,
recent_evidence: Vec::new(),
recent_observations: Vec::new(),
graph_frontier: None,
graph_checkpoint: None,
planning: None,
churn: None,
});
let authority_scope = "epiphany.eyes.public_source_gate_probe";
open_runtime_spine_heartbeat_job(
store,
"public-source-no-grant-launcher".into(),
WORKER_JOB_ID.into(),
RuntimeSpineHeartbeatJobOptions {
runtime_id: "public-source-no-grant-probe".into(),
display_name: "Public source no-grant probe".into(),
session_id: EPIPHANY_RUNTIME_ROOT_SESSION_ID.into(),
objective: "Prove the exact public-source grant boundary.".into(),
coordinator_note: "isolated gate probe".into(),
job_id: WORKER_JOB_ID.into(),
role: EPIPHANY_RESEARCH_OWNER_ROLE.into(),
binding_id: EPIPHANY_RESEARCH_ROLE_BINDING_ID.into(),
authority_scope: authority_scope.into(),
instruction: "Attempt one immutable public source lookup.".into(),
output_contract_id: ROLE_WORKER_OUTPUT_CONTRACT_ID.into(),
organ_launch_contract: default_launch_organ_contract(
authority_scope,
"role",
ROLE_WORKER_OUTPUT_CONTRACT_ID,
),
launch_document,
proposal_modeling_request_id: None,
frontier_planning_request_id: None,
frontier_plan_mind_request_id: None,
imagination_consideration_request_id: None,
admitted_model_direction_consideration_request_id: None,
repo_frontier_modeling_request_id: None,
repo_frontier_research_request_id: None,
repo_frontier_verification_request_id: None,
created_at: "2026-08-13T00:00:01Z".into(),
},
)?;
commit_coordinator_job_launch(
store,
"public-source-no-grant-thread",
&state,
&launch,
&plan,
"2026-08-13T00:00:01Z".into(),
runtime_spine_cache(store)?.put(
&format!("substrate-grant-{WORKER_JOB_ID}"),
&substrate_gate_repo_access_grant_for_worker(
format!("substrate-grant-{WORKER_JOB_ID}"),
WORKER_JOB_ID.into(),
EPIPHANY_RESEARCH_ROLE_BINDING_ID.into(),
EPIPHANY_RESEARCH_OWNER_ROLE.into(),
authority_scope.into(),
true,
"2026-08-13T00:00:01Z".into(),
),
)?;
let mut model_request = EpiphanyModelRequest::new(

View file

@ -1,706 +0,0 @@
use crate::coordinator_results::latest_runtime_link;
use crate::coordinator_state::changed_fields;
use crate::*;
use epiphany_state_model::EpiphanyThreadState;
use std::path::Path;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EpiphanyCoordinatorAdmissionError {
InvalidRequest(String),
Store(String),
}
impl std::fmt::Display for EpiphanyCoordinatorAdmissionError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> 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<EpiphanyStateUpdatedField>,
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<u64>,
reference_turn_id: Option<String>,
accepted_at: String,
nonce: &str,
) -> anyhow::Result<EpiphanyNativeRoleAcceptance> {
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<EpiphanyRoleFindingInterpretation, EpiphanyCoordinatorAdmissionError> {
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<EpiphanyLaunchOrganContract, EpiphanyCoordinatorAdmissionError> {
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<EpiphanyLaunchOrganContract, EpiphanyCoordinatorAdmissionError> {
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<EpiphanyReceiptEffectKind> {
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<String> {
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<CultCache> {
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<Option<EpiphanyThreadState>> {
let cache = coordinator_acceptance_cache(store_path)?;
cache
.get::<EpiphanyThreadStateEntry>(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<EpiphanyThreadState> {
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<u64>,
role_id: EpiphanyRoleResultRoleId,
binding_id: &str,
finding: &EpiphanyRoleFindingInterpretation,
accepted_evidence_id: String,
accepted_observation_id: String,
accepted_at: String,
) -> Result<EpiphanyRoleAcceptanceUpdate, String> {
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<u64>,
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<u64>,
patch: EpiphanyRoleStatePatchDocument,
) -> EpiphanyStateUpdate {
state_update_from_patch(expected_revision, patch)
}
fn changed_fields_from_patch(
patch: &EpiphanyRoleStatePatchDocument,
) -> Vec<EpiphanyStateUpdatedField> {
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::<EpiphanyThreadStateEntry>(THREAD_STATE_KEY)?
.state()?
.objective
.as_deref(),
Some("Atomic acceptance")
);
assert_eq!(
cache.get_required::<MindGatewayReview>("mind-review-7")?,
review
);
assert_eq!(
cache.get_required::<MindStateCommitReceipt>("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::<ContinuityRecoveryReceipt>("continuity-9")?,
continuity
);
assert!(
cache
.get::<EpiphanyThreadStateEntry>(THREAD_STATE_KEY)?
.is_some()
);
assert!(cache.get::<MindStateCommitReceipt>("commit-9")?.is_some());
Ok(())
}
}

View file

@ -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<EpiphanyJobInterruptResult> {
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(())
}
}

View file

@ -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<EpiphanyJobLaunchResult> {
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<RepositoryBodyObservationBasis>,
injected_envelopes: Vec<CultCacheEnvelope>,
) -> Result<EpiphanyJobLaunchResult> {
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::EpiphanyThreadStateEntry>(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::<EpiphanyRuntimeIdentity>(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::<ImaginationConsiderationLaunchBinding>(&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<EpiphanyCoordinatorJobLaunchPlan> {
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::<ImaginationConsiderationRequest>(request_id)?
.ok_or_else(|| anyhow!("consideration request does not exist"))?;
validate_current_imagination_consideration_request(cache, &request)?;
let identity = cache
.get::<EpiphanyRuntimeIdentity>(RUNTIME_IDENTITY_KEY)?
.ok_or_else(|| anyhow!("consideration requires runtime identity"))?;
let persisted = cache
.get::<crate::EpiphanyThreadStateEntry>(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::<ImaginationConsiderationLaunchBinding>()?
.iter()
.filter(|binding| binding.request_id == request_id)
.cloned()
.collect::<Vec<_>>();
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::<ImaginationConsiderationLaunchBinding>()?
.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<AdmittedModelDirectionConsiderationRequest> {
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::<AdmittedModelDirectionConsiderationRequest>(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::<EpiphanyRuntimeIdentity>(RUNTIME_IDENTITY_KEY)?
.ok_or_else(|| anyhow!("model direction consideration requires runtime identity"))?;
let persisted = cache
.get::<crate::EpiphanyThreadStateEntry>(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::<EpiphanyRuntimeWorkerLaunchRequest>()?
.iter()
.filter(|worker| {
worker
.admitted_model_direction_consideration_request_id
.as_deref()
== Some(request_id)
})
.cloned()
.collect::<Vec<_>>();
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<bool> {
cache
.get::<crate::EpiphanyRuntimeWorkerProcessClaim>(&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<Option<EpiphanyRuntimeLink>> {
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))
}

View file

@ -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::<EpiphanyThreadStateEntry>()?.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);

View file

@ -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<EpiphanyReorientFindingInterpretation>,
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>,

View file

@ -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<PathBuf>) -> 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::RepoFrontierWorkProposal> {
crate::intake_user_repo_frontier_proposal(&self.store, input)
}
pub fn intake_user_objective(
&self,
input: crate::UserObjectiveIntakeInput,
) -> Result<crate::UserObjectiveIntakeApplied> {
crate::intake_user_objective(&self.store, input)
}
pub fn select_repo_frontier_proposal_for_modeling(
&self,
proposal_id: &str,
selected_at: &str,
) -> Result<crate::RepoFrontierProposalModelingRequest> {
crate::select_repo_frontier_work_proposal_for_modeling(
&self.store,
proposal_id,
selected_at,
)
}
pub fn state(&self) -> Result<Option<EpiphanyThreadState>> {
read_coordinator_state(&self.store)
}
pub fn role_result(
&self,
role_id: EpiphanyRoleResultRoleId,
binding_id: &str,
) -> Result<EpiphanyCoordinatorRoleResultSnapshot> {
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<EpiphanyCoordinatorReorientResultSnapshot> {
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<String>,
) -> Result<EpiphanyCoordinatorStateApplied> {
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<String>,
) -> Result<EpiphanyCoordinatorStateApplied> {
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<EpiphanyJobLaunchResult> {
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<u64>,
reference_turn_id: Option<String>,
accepted_at: String,
nonce: &str,
) -> Result<EpiphanyNativeRoleAcceptance> {
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<EpiphanyJobInterruptResult> {
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:?}"
);
}
}
}

View file

@ -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<EpiphanyStateUpdatedField>,
pub state: EpiphanyThreadState,
}
pub fn read_coordinator_state(store: &Path) -> Result<Option<EpiphanyThreadState>> {
read_accepted_coordinator_state(store)
}
pub fn apply_coordinator_state_update(
store: &Path,
thread_id: &str,
update: EpiphanyStateUpdate,
reference_turn_id: Option<String>,
) -> Result<EpiphanyCoordinatorStateApplied> {
let current = read_coordinator_state(store)?.unwrap_or_default();
apply_coordinator_state_update_from_state(store, thread_id, &current, 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<String>,
) -> Result<EpiphanyCoordinatorStateApplied> {
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<String>,
) -> Result<EpiphanyThreadState> {
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<EpiphanyStateUpdatedField> {
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(())
}
}

View file

@ -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<CultCacheEnvelope>,
expected_state_envelope: Option<CultCacheEnvelope>,
}
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<CoordinatorStateTransaction> {
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<CultCacheEnvelope>,
captured_replacements: Vec<CultCacheEnvelope>,
) -> Result<EpiphanyThreadState> {
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::<Vec<_>>();
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<CultCacheEnvelope> {
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::<EpiphanyThreadStateEntry>("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::<Vec<_>>();
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"));
}
}

View file

@ -3376,8 +3376,9 @@ mod tests {
scheduled_cache.pull_all_backing_stores()?;
assert!(
scheduled_cache
.get::<crate::EpiphanyThreadStateEntry>(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::EpiphanyThreadStateEntry>(crate::THREAD_STATE_KEY)?
.is_none()
.snapshot_envelopes()
.iter()
.all(|envelope| envelope.r#type != "epiphany.thread_state")
);
let proposal_runtime_launch = final_cache
.get::<crate::EpiphanyRuntimeWorkerLaunchRequest>(&proposal_launch.job_id)?
@ -3770,8 +3772,9 @@ mod tests {
accepted_cache.pull_all_backing_stores()?;
assert!(
accepted_cache
.get::<crate::EpiphanyThreadStateEntry>(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::EpiphanyThreadStateEntry>(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::EpiphanyThreadStateEntry>(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::EpiphanyThreadStateEntry>(crate::THREAD_STATE_KEY)?
.is_none()
.snapshot_envelopes()
.iter()
.all(|envelope| envelope.r#type != "epiphany.thread_state")
);
let research_launch = research_cache
.get::<crate::EpiphanyRuntimeWorkerLaunchRequest>(&research_job)?

View file

@ -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;

File diff suppressed because it is too large Load diff

View file

@ -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::EpiphanyThreadStateEntry>(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)?;

View file

@ -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<bool> {
let mut runtime = crate::runtime_spine_cache(runtime_store)?;
runtime.pull_all_backing_stores()?;
let entry = runtime.get::<crate::EpiphanyThreadStateEntry>(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<bool> {
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 => {

View file

@ -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<Path>) -> Result<CultCache> {
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::<crate::EpiphanyThreadStateEntry>()?;
cache.register_entry_type::<crate::UserObjectiveIntake>()?;
cache.register_entry_type::<EpiphanyRuntimeIdentity>()?;
cache.register_entry_type::<crate::RuntimeStoreMigrationReceipt>()?;
@ -13733,17 +13730,6 @@ fn epiphany_mutation_contracts() -> Vec<CultNetDocumentMutationContract> {
"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,

File diff suppressed because it is too large Load diff

View file

@ -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<u8>,
}
impl EpiphanyThreadStateEntry {
pub fn from_state(thread_id: impl Into<String>, state: &EpiphanyThreadState) -> Result<Self> {
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<EpiphanyThreadState> {
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<Path>) -> Result<CultCache> {
let mut cache = CultCache::new();
cache.register_entry_type::<EpiphanyThreadStateEntry>()?;
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<Path>,
) -> Result<Option<EpiphanyThreadStateEntry>> {
let cache = thread_state_cache(store_path)?;
cache.get::<EpiphanyThreadStateEntry>(THREAD_STATE_KEY)
}
pub fn load_thread_state(store_path: impl AsRef<Path>) -> Result<Option<EpiphanyThreadState>> {
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(())
}
}