From 71505941089f0fc1f4945d41d4de1e533dfafa0a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 14 Aug 2026 11:20:56 +0200 Subject: [PATCH] Add keyed concurrent Mind document foundation --- .../src/coordinator_launch_context.rs | 4 +- epiphany-core/src/lib.rs | 2 + epiphany-core/src/mind_documents.rs | 363 ++++++++++++++++++ epiphany-core/src/reasoning_context.rs | 27 +- epiphany-core/src/runtime_spine.rs | 36 +- 5 files changed, 417 insertions(+), 15 deletions(-) create mode 100644 epiphany-core/src/mind_documents.rs diff --git a/epiphany-core/src/coordinator_launch_context.rs b/epiphany-core/src/coordinator_launch_context.rs index 79240127..dccba01c 100644 --- a/epiphany-core/src/coordinator_launch_context.rs +++ b/epiphany-core/src/coordinator_launch_context.rs @@ -1716,8 +1716,8 @@ mod tests { open_runtime_spine_heartbeat_job( &runtime_store, RuntimeSpineHeartbeatJobOptions { - runtime_id: EPIPHANY_LOCAL_VERSE_RUNTIME_ID.to_string(), - display_name: "Epiphany Local".to_string(), + runtime_id: "launch-context-runtime".to_string(), + display_name: "Launch context test".to_string(), session_id: "epiphany-main".to_string(), objective: "Test persisted launch context.".to_string(), coordinator_note: "Bridge launch-context smoke.".to_string(), diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index 910369a7..298097de 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -23,6 +23,7 @@ mod idunn_runtime_health; mod imagination_consideration; mod memory_graph; mod mind_gateway; +mod mind_documents; mod operator_command; mod operator_command_service; mod organ_dependencies; @@ -991,6 +992,7 @@ pub use resident_readiness::*; pub use resident_self::*; pub use runtime_spine::ARCHIVED_RUNTIME_SESSION_SCHEMA_VERSION; pub use reasoning_context::*; +pub use mind_documents::*; pub use runtime_spine::ARCHIVED_RUNTIME_SESSION_TYPE; pub use runtime_spine::COORDINATOR_RUN_RECEIPT_SCHEMA_VERSION; pub use runtime_spine::COORDINATOR_RUN_RECEIPT_TYPE; diff --git a/epiphany-core/src/mind_documents.rs b/epiphany-core/src/mind_documents.rs new file mode 100644 index 00000000..acfb0871 --- /dev/null +++ b/epiphany-core/src/mind_documents.rs @@ -0,0 +1,363 @@ +use std::path::Path; + +use anyhow::{Result, anyhow}; +use cultcache_rs::{CultCache, CultCacheEnvelope, DatabaseEntry}; +use epiphany_state_model::{ + EpiphanyBacklogItem, EpiphanyEvidenceRecord, EpiphanyInvestigationCheckpoint, + EpiphanyInvariant, EpiphanyModeState, EpiphanyObjectiveDraft, EpiphanyObservation, + EpiphanyPlanningCapture, EpiphanyPlanningState, EpiphanyRoadmapStream, EpiphanySubgoal, +}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +use crate::{EpiphanyMindDocumentVersion, runtime_spine_cache}; + +pub const MIND_SCHEMA_EPOCH: &str = "epiphany.mind.epoch.v1"; +pub const MIND_OBJECTIVE_KEY: &str = "objective"; +pub const MIND_FOCUS_KEY: &str = "focus"; +pub const MIND_MODE_KEY: &str = "mode"; + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache(type = "epiphany.mind.identity.v1", schema = "EpiphanyMindIdentity")] +pub struct EpiphanyMindIdentity { + #[cultcache(key = 0)] + pub schema_epoch: String, + #[cultcache(key = 1)] + pub runtime_id: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache(type = "epiphany.mind.objective.v1", schema = "EpiphanyMindObjectiveDocument")] +pub struct EpiphanyMindObjectiveDocument { + #[cultcache(key = 0)] + pub objective: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache(type = "epiphany.mind.focus.v1", schema = "EpiphanyMindFocusDocument")] +pub struct EpiphanyMindFocusDocument { + #[cultcache(key = 0)] + pub active_subgoal_id: Option, + #[cultcache(key = 1)] + pub investigation_checkpoint_id: Option, +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache(type = "epiphany.mind.mode.v1", schema = "EpiphanyMindModeDocument")] +pub struct EpiphanyMindModeDocument { + #[cultcache(key = 0)] + pub mode: EpiphanyModeState, +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache(type = "epiphany.mind.subgoal.v1", schema = "EpiphanyMindSubgoalDocument")] +pub struct EpiphanyMindSubgoalDocument { + #[cultcache(key = 0)] + pub value: EpiphanySubgoal, +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache(type = "epiphany.mind.invariant.v1", schema = "EpiphanyMindInvariantDocument")] +pub struct EpiphanyMindInvariantDocument { + #[cultcache(key = 0)] + pub value: EpiphanyInvariant, +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache(type = "epiphany.mind.observation.v1", schema = "EpiphanyMindObservationDocument")] +pub struct EpiphanyMindObservationDocument { + #[cultcache(key = 0)] + pub value: EpiphanyObservation, +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache(type = "epiphany.mind.evidence.v1", schema = "EpiphanyMindEvidenceDocument")] +pub struct EpiphanyMindEvidenceDocument { + #[cultcache(key = 0)] + pub value: EpiphanyEvidenceRecord, +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache( + type = "epiphany.mind.investigation_checkpoint.v1", + schema = "EpiphanyMindInvestigationCheckpointDocument" +)] +pub struct EpiphanyMindInvestigationCheckpointDocument { + #[cultcache(key = 0)] + pub value: EpiphanyInvestigationCheckpoint, +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache(type = "epiphany.mind.planning_capture.v1", schema = "EpiphanyMindPlanningCaptureDocument")] +pub struct EpiphanyMindPlanningCaptureDocument { + #[cultcache(key = 0)] + pub value: EpiphanyPlanningCapture, +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache(type = "epiphany.mind.backlog_item.v1", schema = "EpiphanyMindBacklogItemDocument")] +pub struct EpiphanyMindBacklogItemDocument { + #[cultcache(key = 0)] + pub value: EpiphanyBacklogItem, +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache(type = "epiphany.mind.roadmap_stream.v1", schema = "EpiphanyMindRoadmapStreamDocument")] +pub struct EpiphanyMindRoadmapStreamDocument { + #[cultcache(key = 0)] + pub value: EpiphanyRoadmapStream, +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache(type = "epiphany.mind.objective_draft.v1", schema = "EpiphanyMindObjectiveDraftDocument")] +pub struct EpiphanyMindObjectiveDraftDocument { + #[cultcache(key = 0)] + pub value: EpiphanyObjectiveDraft, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct EpiphanyMindView { + pub projection_digest: String, + pub source_documents: Vec, + pub objective: Option, + pub active_subgoal_id: Option, + pub subgoals: Vec, + pub invariants: Vec, + pub observations: Vec, + pub evidence: Vec, + pub investigation_checkpoint: Option, + pub mode: Option, + pub planning: EpiphanyPlanningState, +} + +pub(crate) fn register_mind_document_types(cache: &mut CultCache) -> Result<()> { + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + Ok(()) +} + +pub(crate) fn validate_mind_write_envelope(envelope: &CultCacheEnvelope) -> Result<()> { + let expected_key = if envelope.r#type == EpiphanyMindIdentity::TYPE { + let value: EpiphanyMindIdentity = rmp_serde::from_slice(&envelope.payload)?; + if value.schema_epoch != MIND_SCHEMA_EPOCH || value.runtime_id.trim().is_empty() { + return Err(anyhow!("Mind identity write is invalid")); + } + MIND_SCHEMA_EPOCH.to_string() + } else if envelope.r#type == EpiphanyMindObjectiveDocument::TYPE { + let value: EpiphanyMindObjectiveDocument = rmp_serde::from_slice(&envelope.payload)?; + if value.objective.trim().is_empty() { + return Err(anyhow!("Mind objective cannot be empty")); + } + MIND_OBJECTIVE_KEY.to_string() + } else if envelope.r#type == EpiphanyMindFocusDocument::TYPE { + let _: EpiphanyMindFocusDocument = rmp_serde::from_slice(&envelope.payload)?; + MIND_FOCUS_KEY.to_string() + } else if envelope.r#type == EpiphanyMindModeDocument::TYPE { + let _: EpiphanyMindModeDocument = rmp_serde::from_slice(&envelope.payload)?; + MIND_MODE_KEY.to_string() + } else if envelope.r#type == EpiphanyMindSubgoalDocument::TYPE { + rmp_serde::from_slice::(&envelope.payload)?.value.id + } else if envelope.r#type == EpiphanyMindInvariantDocument::TYPE { + rmp_serde::from_slice::(&envelope.payload)?.value.id + } else if envelope.r#type == EpiphanyMindObservationDocument::TYPE { + rmp_serde::from_slice::(&envelope.payload)?.value.id + } else if envelope.r#type == EpiphanyMindEvidenceDocument::TYPE { + rmp_serde::from_slice::(&envelope.payload)?.value.id + } else if envelope.r#type == EpiphanyMindInvestigationCheckpointDocument::TYPE { + rmp_serde::from_slice::(&envelope.payload)? + .value + .checkpoint_id + } else if envelope.r#type == EpiphanyMindPlanningCaptureDocument::TYPE { + rmp_serde::from_slice::(&envelope.payload)?.value.id + } else if envelope.r#type == EpiphanyMindBacklogItemDocument::TYPE { + rmp_serde::from_slice::(&envelope.payload)?.value.id + } else if envelope.r#type == EpiphanyMindRoadmapStreamDocument::TYPE { + rmp_serde::from_slice::(&envelope.payload)?.value.id + } else if envelope.r#type == EpiphanyMindObjectiveDraftDocument::TYPE { + rmp_serde::from_slice::(&envelope.payload)?.value.id + } else { + return Err(anyhow!( + "Mind mutation cannot write non-canonical document type {:?}", + envelope.r#type + )); + }; + if expected_key.trim().is_empty() || envelope.key != expected_key { + return Err(anyhow!( + "Mind document semantic identity does not match its envelope key" + )); + } + Ok(()) +} + +pub fn assemble_mind_view(store_path: impl AsRef) -> Result { + let mut cache = runtime_spine_cache(store_path.as_ref())?; + cache.pull_all_backing_stores()?; + let identity = cache + .get::(MIND_SCHEMA_EPOCH)? + .ok_or_else(|| anyhow!("writable Mind store has no v1 identity"))?; + if identity.schema_epoch != MIND_SCHEMA_EPOCH { + return Err(anyhow!("writable Mind store has an unsupported schema epoch")); + } + + let objective = cache + .get::(MIND_OBJECTIVE_KEY)? + .map(|document| document.objective); + let focus = cache.get::(MIND_FOCUS_KEY)?; + let mode = cache + .get::(MIND_MODE_KEY)? + .map(|document| document.mode); + let mut subgoals = values::(&cache, |value| value.value)?; + let mut invariants = values::(&cache, |value| value.value)?; + let mut observations = + values::(&cache, |value| value.value)?; + let mut evidence = values::(&cache, |value| value.value)?; + let checkpoints = values::( + &cache, + |value| value.value, + )?; + let mut captures = + values::(&cache, |value| value.value)?; + let mut backlog_items = + values::(&cache, |value| value.value)?; + let mut roadmap_streams = + values::(&cache, |value| value.value)?; + let mut objective_drafts = + values::(&cache, |value| value.value)?; + subgoals.sort_by(|left, right| left.id.cmp(&right.id)); + invariants.sort_by(|left, right| left.id.cmp(&right.id)); + observations.sort_by(|left, right| left.id.cmp(&right.id)); + evidence.sort_by(|left, right| left.id.cmp(&right.id)); + captures.sort_by(|left, right| left.id.cmp(&right.id)); + backlog_items.sort_by(|left, right| left.id.cmp(&right.id)); + roadmap_streams.sort_by(|left, right| left.id.cmp(&right.id)); + objective_drafts.sort_by(|left, right| left.id.cmp(&right.id)); + let investigation_checkpoint = match focus + .as_ref() + .and_then(|document| document.investigation_checkpoint_id.as_deref()) + { + Some(id) => Some( + checkpoints + .into_iter() + .find(|checkpoint| checkpoint.checkpoint_id == id) + .ok_or_else(|| anyhow!("Mind focus cites a missing investigation checkpoint"))?, + ), + None => None, + }; + let mut source_documents = canonical_mind_versions(&cache.snapshot_envelopes())?; + source_documents.sort_by(|left, right| { + (&left.document_type, &left.document_key).cmp(&( + &right.document_type, + &right.document_key, + )) + }); + let projection_digest = digest_versions(&source_documents)?; + Ok(EpiphanyMindView { + projection_digest, + source_documents, + objective, + active_subgoal_id: focus.and_then(|document| document.active_subgoal_id), + subgoals, + invariants, + observations, + evidence, + investigation_checkpoint, + mode, + planning: EpiphanyPlanningState { + workspace_root: None, + captures, + backlog_items, + roadmap_streams, + objective_drafts, + }, + }) +} + +fn values(cache: &CultCache, take: impl Fn(T) -> V) -> Result> +where + T: DatabaseEntry, +{ + Ok(cache.get_all::()?.into_iter().map(take).collect()) +} + +fn canonical_mind_versions( + envelopes: &[CultCacheEnvelope], +) -> Result> { + envelopes + .iter() + .filter(|envelope| envelope.r#type.starts_with("epiphany.mind.")) + .map(|envelope| EpiphanyMindDocumentVersion::from_envelope("epiphany-mind", envelope)) + .collect() +} + +fn digest_versions(versions: &[EpiphanyMindDocumentVersion]) -> Result { + let mut digest = Sha256::new(); + digest.update(b"epiphany.mind_view.v1\0"); + digest.update(rmp_serde::to_vec_named(versions)?); + Ok(format!("sha256:{:x}", digest.finalize())) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{RuntimeSpineInitOptions, initialize_runtime_spine}; + + #[test] + fn keyed_mind_view_is_deterministic_and_has_no_global_revision() -> Result<()> { + let temp = tempfile::tempdir()?; + let store = temp.path().join("mind.cc"); + initialize_runtime_spine( + &store, + RuntimeSpineInitOptions { + runtime_id: "mind-view".into(), + display_name: "Mind view".into(), + created_at: "2026-08-14T00:00:00Z".into(), + }, + )?; + let mut cache = runtime_spine_cache(&store)?; + cache.put( + MIND_OBJECTIVE_KEY, + &EpiphanyMindObjectiveDocument { + objective: "Build a concurrent Mind".into(), + }, + )?; + for id in ["subgoal-b", "subgoal-a"] { + cache.put( + id, + &EpiphanyMindSubgoalDocument { + value: EpiphanySubgoal { + id: id.into(), + title: id.into(), + status: "active".into(), + summary: None, + }, + }, + )?; + } + let first = assemble_mind_view(&store)?; + let second = assemble_mind_view(&store)?; + assert_eq!(first, second); + assert_eq!(first.objective.as_deref(), Some("Build a concurrent Mind")); + assert_eq!( + first + .subgoals + .iter() + .map(|subgoal| subgoal.id.as_str()) + .collect::>(), + ["subgoal-a", "subgoal-b"] + ); + assert!(first.projection_digest.starts_with("sha256:")); + Ok(()) + } + +} diff --git a/epiphany-core/src/reasoning_context.rs b/epiphany-core/src/reasoning_context.rs index d0ba3d38..a861c8d5 100644 --- a/epiphany-core/src/reasoning_context.rs +++ b/epiphany-core/src/reasoning_context.rs @@ -566,6 +566,9 @@ pub fn commit_mind_mutation( if writes.is_empty() { return Err(anyhow!("Mind mutation requires at least one write")); } + for write in &writes { + crate::mind_documents::validate_mind_write_envelope(write)?; + } validate_unique_envelope_identities(&strong_reads, "strong read")?; validate_unique_envelope_identities(&writes, "write")?; let expected_ids = strong_reads @@ -973,18 +976,17 @@ mod tests { let backing = SingleFileMessagePackBackingStore::new(&store); let make = |key: &str, summary: &str| -> Result { let cache = runtime_spine_cache(&store)?; - let event = crate::EpiphanyRuntimeEvent { - schema_version: crate::runtime_spine::RUNTIME_SPINE_SCHEMA_VERSION.into(), - event_id: key.into(), - occurred_at: "2026-08-14T00:00:01Z".into(), - event_type: "test.mind.mutation".into(), - source: "reasoning-context-test".into(), - session_id: None, - job_id: None, - summary: summary.into(), - metadata: Default::default(), + let document = crate::EpiphanyMindObservationDocument { + value: epiphany_state_model::EpiphanyObservation { + id: key.into(), + summary: summary.into(), + source_kind: "test".into(), + status: "accepted".into(), + code_refs: Vec::new(), + evidence_ids: Vec::new(), + }, }; - Ok(cache.prepare_entry(key, &event)?.0) + Ok(cache.prepare_entry(key, &document)?.0) }; assert!(matches!( commit_mind_mutation( @@ -1012,7 +1014,8 @@ mod tests { .pull_all()? .into_iter() .find(|entry| { - entry.r#type == crate::EpiphanyRuntimeEvent::TYPE && entry.key == "persona" + entry.r#type == crate::EpiphanyMindObservationDocument::TYPE + && entry.key == "persona" }) .unwrap(); assert!(matches!( diff --git a/epiphany-core/src/runtime_spine.rs b/epiphany-core/src/runtime_spine.rs index 3c136dcf..004d5d05 100644 --- a/epiphany-core/src/runtime_spine.rs +++ b/epiphany-core/src/runtime_spine.rs @@ -1114,6 +1114,7 @@ pub struct EpiphanyRuntimeJobSnapshot { pub fn runtime_spine_cache(store_path: impl AsRef) -> Result { let store_path = store_path.as_ref(); let mut cache = CultCache::new(); + crate::mind_documents::register_mind_document_types(&mut cache)?; cache.register_entry_type::()?; cache.register_entry_type::()?; cache.register_entry_type::()?; @@ -1227,6 +1228,18 @@ pub fn initialize_runtime_spine( let mut cache = runtime_spine_cache(store_path)?; cache.pull_all_backing_stores()?; let existing = cache.get::(RUNTIME_IDENTITY_KEY)?; + let existing_mind = cache.get::(crate::MIND_SCHEMA_EPOCH)?; + if existing.is_some() != existing_mind.is_some() { + return Err(anyhow!( + "runtime and Mind schema identities are split across epochs" + )); + } + if existing + .as_ref() + .is_some_and(|identity| identity.runtime_id != options.runtime_id) + { + return Err(anyhow!("runtime identity cannot change during initialization")); + } let created_at = existing .as_ref() .map(|identity| identity.created_at.clone()) @@ -1241,7 +1254,28 @@ pub fn initialize_runtime_spine( supported_document_types: runtime_registered_document_types(), metadata: BTreeMap::from([("codexEvacuationBridge".to_string(), "temporary".to_string())]), }; - cache.put(RUNTIME_IDENTITY_KEY, &identity)?; + let mind_identity = crate::EpiphanyMindIdentity { + schema_epoch: crate::MIND_SCHEMA_EPOCH.to_string(), + runtime_id: identity.runtime_id.clone(), + }; + if let Some(existing_mind) = existing_mind { + if existing_mind != mind_identity { + return Err(anyhow!("Mind schema identity collision")); + } + cache.put(RUNTIME_IDENTITY_KEY, &identity)?; + return Ok(identity); + } + let runtime_envelope = cache.prepare_entry(RUNTIME_IDENTITY_KEY, &identity)?.0; + let mind_envelope = cache + .prepare_entry(crate::MIND_SCHEMA_EPOCH, &mind_identity)? + .0; + if !runtime_spine_backing_store(store_path)? + .compare_and_swap_batch(&[], vec![runtime_envelope, mind_envelope])? + { + return Err(anyhow!( + "runtime and Mind schema identities lost their atomic initialization" + )); + } Ok(identity) }