diff --git a/epiphany-core/src/bin/epiphany-mvp-coordinator.rs b/epiphany-core/src/bin/epiphany-mvp-coordinator.rs index 363a5744..4a0ebf83 100644 --- a/epiphany-core/src/bin/epiphany-mvp-coordinator.rs +++ b/epiphany-core/src/bin/epiphany-mvp-coordinator.rs @@ -378,7 +378,8 @@ fn run_coordinator(args: &Args) -> Result { startup_events.push(json!({ "type": "operatorObjectiveIntake", "threadId": thread_id, - "revision": intake.state.revision, + "mindProjectionDigest": intake.mind.projection_digest, + "commitReceiptId": intake.commit_receipt.receipt_id, "changed": intake.changed, })); } @@ -2684,14 +2685,23 @@ mod tests { fn operator_objective_intake_creates_once_and_refuses_replacement() -> Result<()> { let temp = tempfile::tempdir()?; let store = temp.path().join("runtime.cc"); + epiphany_core::initialize_runtime_spine( + &store, + epiphany_core::RuntimeSpineInitOptions { + runtime_id: "objective-intake-bin".into(), + display_name: "Objective intake bin".into(), + created_at: "2026-08-14T00:00:00Z".into(), + }, + )?; let first = intake_operator_objective(&store, "thread-1", "Map the machine")?; assert!(first.changed); - assert_eq!(first.state.revision, 1); + assert_eq!(first.mind.objective.as_deref(), Some("Map the machine")); let repeated = intake_operator_objective(&store, "thread-1", " Map the machine ")?; assert!(!repeated.changed); - assert_eq!(repeated.state.revision, first.state.revision); + assert_eq!(repeated.mind.projection_digest, first.mind.projection_digest); + assert_eq!(repeated.commit_receipt, first.commit_receipt); let error = intake_operator_objective(&store, "thread-1", "Replace the machine") .expect_err("objective replacement must require a typed adoption flow"); diff --git a/epiphany-core/src/coordinator_objective_intake.rs b/epiphany-core/src/coordinator_objective_intake.rs index 426c06f3..040a0b24 100644 --- a/epiphany-core/src/coordinator_objective_intake.rs +++ b/epiphany-core/src/coordinator_objective_intake.rs @@ -1,19 +1,16 @@ -use crate::coordinator_state_transaction::{ - commit_coordinator_state_transaction, open_coordinator_state_transaction, -}; use crate::{ - EpiphanyCoordinatorStateApplied, EpiphanyStateUpdate, EpiphanyStateUpdatedField, - apply_coordinator_state_update_to_state, coordinator_acceptance_cache, read_coordinator_state, + EpiphanyMindCommitAuthority, EpiphanyMindCommitOutcome, EpiphanyMindCommitReceipt, + EpiphanyMindDocumentVersion, EpiphanyMindObjectiveDocument, EpiphanyMindView, + MIND_OBJECTIVE_KEY, assemble_mind_view, commit_operator_mind_mutation, runtime_spine_cache, }; use anyhow::{Result, anyhow}; use cultcache_rs::DatabaseEntry; -use epiphany_state_model::EpiphanyThreadState; use sha2::{Digest, Sha256}; use std::path::Path; pub const USER_OBJECTIVE_INTAKE_SCHEMA_VERSION: &str = "gamecult.epiphany.user_objective_intake.v0"; pub const USER_OBJECTIVE_INTAKE_TYPE: &str = "epiphany.coordinator.user_objective_intake"; -pub const USER_OBJECTIVE_INTAKE_CONTRACT: &str = "The human supplies the initial objective. Self records that assertion and the first canonical thread state in one CAS. Repeated identical intake is read-idempotent; replacement requires a separate reviewed adoption flow."; +pub const USER_OBJECTIVE_INTAKE_CONTRACT: &str = "The human supplies the initial objective. Self records that assertion and the canonical keyed Mind objective in one CAS. Thread identity is provenance only. Repeated identical intake is read-idempotent; replacement requires a separate reviewed adoption flow."; #[derive(Debug, Clone)] pub struct UserObjectiveIntakeInput { @@ -53,7 +50,8 @@ pub struct UserObjectiveIntake { #[derive(Debug, Clone)] pub struct UserObjectiveIntakeApplied { pub intake: UserObjectiveIntake, - pub state: EpiphanyCoordinatorStateApplied, + pub mind: EpiphanyMindView, + pub commit_receipt: EpiphanyMindCommitReceipt, pub changed: bool, } @@ -76,40 +74,59 @@ pub fn intake_user_objective( let objective_sha256 = format!("{:x}", Sha256::digest(objective.as_bytes())); let intake_id = format!("user-objective-{:x}", Sha256::digest(thread_id.as_bytes())); - if let Some(state) = read_coordinator_state(store)? { - let cache = coordinator_acceptance_cache(store)?; - let existing = cache - .get::(&intake_id)? - .ok_or_else(|| anyhow!("authoritative state has no typed user-objective intake"))?; + let mut cache = runtime_spine_cache(store)?; + cache.pull_all_backing_stores()?; + if let Some(existing) = cache.get::(&intake_id)? { + let objective_document = cache + .get::(MIND_OBJECTIVE_KEY)? + .ok_or_else(|| anyhow!("typed user-objective intake lost its Mind objective"))?; if existing.thread_id != thread_id || existing.objective != objective || existing.objective_sha256 != objective_sha256 || existing.source_actor != source_actor || existing.source_ref != source_ref - || state.objective.as_deref().map(str::trim) != Some(objective) + || objective_document.objective.trim() != objective { return Err(anyhow!( - "refusing to replace the authoritative coordinator objective; use a typed objective-adoption flow" + "refusing to replace the authoritative Mind objective; use a typed objective-adoption flow" )); } + let provenance = EpiphanyMindDocumentVersion::from_envelope( + "epiphany-operator", + &cache.prepare_entry(&intake_id, &existing)?.0, + )?; + let receipt = cache + .get_all::()? + .into_iter() + .find(|receipt| { + receipt.invariant_owner == "Self.user_objective_intake" + && matches!( + &receipt.authority, + EpiphanyMindCommitAuthority::OperatorProvenance { + provenance: receipt_provenance + } if receipt_provenance == &provenance + ) + && receipt.writes.iter().any(|write| { + write.document_type == EpiphanyMindObjectiveDocument::TYPE + && write.document_key == MIND_OBJECTIVE_KEY + }) + }) + .ok_or_else(|| anyhow!("typed user-objective intake lost its Mind commit receipt"))?; return Ok(UserObjectiveIntakeApplied { intake: existing, - state: EpiphanyCoordinatorStateApplied { - revision: state.revision, - changed_fields: Vec::new(), - state, - }, + mind: assemble_mind_view(store)?, + commit_receipt: receipt, changed: false, }); } - - let current = EpiphanyThreadState::default(); - let update = EpiphanyStateUpdate { - expected_revision: Some(0), - objective: Some(objective.to_string()), - ..Default::default() - }; - let next = apply_coordinator_state_update_to_state(¤t, update, None)?; + if cache + .get::(MIND_OBJECTIVE_KEY)? + .is_some() + { + return Err(anyhow!( + "authoritative Mind objective has no matching typed operator intake" + )); + } let intake = UserObjectiveIntake { schema_version: USER_OBJECTIVE_INTAKE_SCHEMA_VERSION.into(), intake_id: intake_id.clone(), @@ -121,22 +138,32 @@ pub fn intake_user_objective( submitted_at: input.submitted_at, contract: USER_OBJECTIVE_INTAKE_CONTRACT.into(), }; - let mut transaction = open_coordinator_state_transaction(store, ¤t)?; - let envelope = transaction.prepare_entry(&intake_id, &intake)?.0; - commit_coordinator_state_transaction( - &mut transaction, - thread_id, - &next, - vec![envelope], + let provenance = cache.prepare_entry(&intake_id, &intake)?.0; + let objective_write = cache + .prepare_entry( + MIND_OBJECTIVE_KEY, + &EpiphanyMindObjectiveDocument { + objective: objective.to_string(), + }, + )? + .0; + let commit_receipt = match commit_operator_mind_mutation( + store, + provenance, + "Self.user_objective_intake", Vec::new(), - )?; + vec![objective_write], + &intake.submitted_at, + )? { + EpiphanyMindCommitOutcome::Committed(receipt) => receipt, + EpiphanyMindCommitOutcome::Conflict { .. } => { + return Err(anyhow!("user-objective intake lost its atomic Mind commit")); + } + }; Ok(UserObjectiveIntakeApplied { intake, - state: EpiphanyCoordinatorStateApplied { - revision: next.revision, - changed_fields: vec![EpiphanyStateUpdatedField::Objective], - state: next, - }, + mind: assemble_mind_view(store)?, + commit_receipt, changed: true, }) } @@ -144,6 +171,7 @@ pub fn intake_user_objective( #[cfg(test)] mod tests { use super::*; + use crate::{EpiphanyThreadStateEntry, RuntimeSpineInitOptions, initialize_runtime_spine}; fn input(objective: &str) -> UserObjectiveIntakeInput { UserObjectiveIntakeInput { @@ -159,21 +187,35 @@ mod tests { fn intake_is_atomic_idempotent_and_seed_only() -> Result<()> { let temp = tempfile::tempdir()?; let store = temp.path().join("runtime.cc"); + initialize_runtime_spine( + &store, + RuntimeSpineInitOptions { + runtime_id: "objective-intake".into(), + display_name: "Objective intake".into(), + created_at: "2026-07-16T13:59:00Z".into(), + }, + )?; let first = intake_user_objective(&store, input("Map the machine"))?; assert!(first.changed); - assert_eq!(first.state.revision, 1); + assert_eq!(first.mind.objective.as_deref(), Some("Map the machine")); assert_eq!( - first.state.state.objective.as_deref(), - Some("Map the machine") + first.commit_receipt.invariant_owner, + "Self.user_objective_intake" ); + let mut cache = runtime_spine_cache(&store)?; + cache.pull_all_backing_stores()?; + assert!(cache.get_all::()?.is_empty()); let repeated = intake_user_objective(&store, input(" Map the machine "))?; assert!(!repeated.changed); assert_eq!(repeated.intake, first.intake); + assert_eq!(repeated.commit_receipt, first.commit_receipt); + let before = std::fs::read(&store)?; let error = intake_user_objective(&store, input("Replace the machine")) .expect_err("objective replacement must be refused"); assert!(error.to_string().contains("refusing to replace")); + assert_eq!(std::fs::read(&store)?, before); Ok(()) } } diff --git a/epiphany-core/src/reasoning_context.rs b/epiphany-core/src/reasoning_context.rs index a861c8d5..ad03509b 100644 --- a/epiphany-core/src/reasoning_context.rs +++ b/epiphany-core/src/reasoning_context.rs @@ -297,7 +297,7 @@ pub struct EpiphanyMindCommitReceipt { #[cultcache(key = 1)] pub receipt_id: String, #[cultcache(key = 2)] - pub decision_context_id: String, + pub authority: EpiphanyMindCommitAuthority, #[cultcache(key = 3)] pub invariant_owner: String, #[cultcache(key = 4)] @@ -308,6 +308,16 @@ pub struct EpiphanyMindCommitReceipt { pub committed_at: String, } +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum EpiphanyMindCommitAuthority { + ModelDecisionContext { + decision_context_id: String, + }, + OperatorProvenance { + provenance: EpiphanyMindDocumentVersion, + }, +} + #[derive(Clone, Debug, PartialEq, Eq)] pub enum EpiphanyMindCommitOutcome { Committed(EpiphanyMindCommitReceipt), @@ -559,6 +569,62 @@ pub fn commit_mind_mutation( committed_at: &str, ) -> Result { require_non_empty(decision_context_id, "Mind mutation decision context id")?; + let mut cache = runtime_spine_cache(store_path)?; + cache.pull_all_backing_stores()?; + let context = cache + .get::(decision_context_id)? + .ok_or_else(|| anyhow!("Mind mutation decision context does not exist"))?; + let basis = cache + .get::(&context.basis_id)? + .ok_or_else(|| anyhow!("Mind mutation decision context lost its basis"))?; + context.validate(&basis)?; + let authority = EpiphanyMindCommitAuthority::ModelDecisionContext { + decision_context_id: decision_context_id.to_string(), + }; + commit_authorized_mind_mutation( + store_path, + authority, + invariant_owner, + strong_reads, + writes, + Vec::new(), + committed_at, + ) +} + +pub fn commit_operator_mind_mutation( + store_path: &Path, + provenance: CultCacheEnvelope, + invariant_owner: &str, + strong_reads: Vec, + writes: Vec, + committed_at: &str, +) -> Result { + let provenance_version = + EpiphanyMindDocumentVersion::from_envelope("epiphany-operator", &provenance)?; + let authority = EpiphanyMindCommitAuthority::OperatorProvenance { + provenance: provenance_version, + }; + commit_authorized_mind_mutation( + store_path, + authority, + invariant_owner, + strong_reads, + writes, + vec![provenance], + committed_at, + ) +} + +fn commit_authorized_mind_mutation( + store_path: &Path, + authority: EpiphanyMindCommitAuthority, + invariant_owner: &str, + strong_reads: Vec, + writes: Vec, + companions: Vec, + committed_at: &str, +) -> Result { require_non_empty(invariant_owner, "Mind mutation invariant owner")?; require_non_empty(committed_at, "Mind mutation commit time")?; chrono::DateTime::parse_from_rfc3339(committed_at) @@ -571,6 +637,7 @@ pub fn commit_mind_mutation( } validate_unique_envelope_identities(&strong_reads, "strong read")?; validate_unique_envelope_identities(&writes, "write")?; + validate_unique_envelope_identities(&companions, "companion")?; let expected_ids = strong_reads .iter() .map(|entry| (entry.r#type.as_str(), entry.key.as_str())) @@ -584,16 +651,25 @@ pub fn commit_mind_mutation( "Mind mutation must replace every strongly read identity" )); } - let mut cache = runtime_spine_cache(store_path)?; cache.pull_all_backing_stores()?; - let context = cache - .get::(decision_context_id)? - .ok_or_else(|| anyhow!("Mind mutation decision context does not exist"))?; - let basis = cache - .get::(&context.basis_id)? - .ok_or_else(|| anyhow!("Mind mutation decision context lost its basis"))?; - context.validate(&basis)?; + let mut companion_expected = Vec::new(); + let mut companion_replacements = Vec::new(); + for companion in companions { + if let Some(existing) = cache + .snapshot_envelopes() + .into_iter() + .find(|entry| entry.r#type == companion.r#type && entry.key == companion.key) + { + if existing != companion { + return Err(anyhow!("Mind mutation companion identity collision")); + } + companion_expected.push(existing.clone()); + companion_replacements.push(existing); + } else { + companion_replacements.push(companion); + } + } let strong_versions = strong_reads .iter() @@ -604,7 +680,7 @@ pub fn commit_mind_mutation( .map(|entry| EpiphanyMindDocumentVersion::from_envelope("epiphany-mind", entry)) .collect::>>()?; let receipt_id = mind_commit_receipt_id( - decision_context_id, + &authority, invariant_owner, &strong_versions, &write_versions, @@ -612,7 +688,7 @@ pub fn commit_mind_mutation( let receipt = EpiphanyMindCommitReceipt { schema_version: MIND_COMMIT_RECEIPT_SCHEMA_VERSION.to_string(), receipt_id: receipt_id.clone(), - decision_context_id: decision_context_id.to_string(), + authority, invariant_owner: invariant_owner.to_string(), strong_reads: strong_versions, writes: write_versions, @@ -625,10 +701,11 @@ pub fn commit_mind_mutation( return Ok(EpiphanyMindCommitOutcome::Committed(existing)); } let mut replacements = writes; + replacements.extend(companion_replacements); replacements.push(cache.prepare_entry(&receipt_id, &receipt)?.0); - if runtime_spine_backing_store(store_path)? - .compare_and_swap_batch(&strong_reads, replacements)? - { + let mut expected = strong_reads.clone(); + expected.extend(companion_expected); + if runtime_spine_backing_store(store_path)?.compare_and_swap_batch(&expected, replacements)? { return Ok(EpiphanyMindCommitOutcome::Committed(receipt)); } let current = runtime_spine_backing_store(store_path)?.pull_all()?; @@ -786,7 +863,7 @@ fn digest_without_context_id(context: &EpiphanyDecisionContext) -> Result Vec { ], CultNetMutationAuthority::Coordinator, vec![crate::USER_OBJECTIVE_INTAKE_TYPE], - vec![crate::THREAD_STATE_TYPE], + vec![crate::EpiphanyMindCommitReceipt::TYPE], vec![ - "The human owns the initial objective assertion; Self atomically records it with the first canonical thread state.", + "The human owns the initial objective assertion; Self atomically records it with the keyed Mind objective and a typed operator-provenance commit receipt.", + "Thread identity is provenance and does not own objective causality.", "Objective replacement requires a separate reviewed adoption flow.", ], ),