From 7c2ebd81de6f85d791f2348d8959e273023024d9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 18 Aug 2026 06:49:15 +0200 Subject: [PATCH] Move Persona memory admission into Mind --- epiphany-core/src/current_work.rs | 84 ++++++- epiphany-core/src/mind_documents.rs | 56 +++++ epiphany-core/src/persona_conversation.rs | 218 ++++++++++++------ .../src/bin/epiphany-persona-service.rs | 2 - 4 files changed, 284 insertions(+), 76 deletions(-) diff --git a/epiphany-core/src/current_work.rs b/epiphany-core/src/current_work.rs index df11a450..1d8a7e98 100644 --- a/epiphany-core/src/current_work.rs +++ b/epiphany-core/src/current_work.rs @@ -3860,7 +3860,89 @@ mod tests { "Committed the exact bounded consequence.".into(), "2026-08-17T00:00:14.600Z".into(), ); - crate::put_hands_commit_receipt(&store, &hands_commit)?; + let persona_cultmesh = temp.path().join("persona-concurrency-cultmesh.cc"); + crate::write_epiphany_cultmesh_swarm_brake( + &persona_cultmesh, + "runtime", + crate::default_epiphany_cultmesh_swarm_brake("2026-08-17T00:00:14.550Z"), + )?; + let persona_request = crate::PersonaTurnRequest { + request_id: "persona-concurrent-with-hands".into(), + role_id: "Persona".into(), + agent_id: "epiphany.Persona".into(), + ..Default::default() + }; + let persona_basis = crate::EpiphanyReasoningBasis::new( + "persona:concurrent-with-hands:interpreter", + "Persona.interpreter", + "epiphany.reasoning_projection.persona.interpreter.v1", + Vec::new(), + crate::EpiphanyReasoningProjection::PersonaInterpreter( + crate::PersonaInterpreterInput::default(), + ), + )?; + accepted_cache.put(&persona_basis.basis_id, &persona_basis)?; + let mut persona_native = epiphany_model_adapter::EpiphanyModelRequest::new( + "persona:concurrent-with-hands:interpreter", + "persona-turn-concurrent-with-hands", + "openai-codex", + "gpt-test", + "interpret", + ); + persona_native.reasoning_basis_id = Some(persona_basis.basis_id.clone()); + let persona_provider = epiphany_openai_adapter::request_from_native(&persona_native); + let persona_context = crate::EpiphanyDecisionContext::new( + &persona_basis, + persona_native, + persona_provider, + Vec::new(), + )?; + accepted_cache.put(&persona_context.context_id, &persona_context)?; + let persona_effect = crate::PersonaInterpreterEffectDocument { + schema_version: crate::PERSONA_INTERPRETER_EFFECT_DOCUMENT_SCHEMA_VERSION.into(), + document_id: "persona-effects:concurrent-with-hands".into(), + turn_id: persona_request.request_id.clone(), + identity_id: persona_request.agent_id.clone(), + interpreter_request_id: "persona:concurrent-with-hands:interpreter".into(), + created_at: "2026-08-17T00:00:14.600Z".into(), + effects: vec![crate::PersonaInterpreterEffect::StateNote { + memory_kind: "social_read".into(), + subject_id: Some("operator".into()), + summary: "Persona and Hands own disjoint consequences.".into(), + confidence: Some(0.9), + }], + private_state_exposed: false, + decision_context_id: persona_context.context_id, + }; + let barrier = std::sync::Arc::new(std::sync::Barrier::new(2)); + let (hands_outcome, persona_outcome) = std::thread::scope(|scope| { + let hands_barrier = barrier.clone(); + let hands_store = store.clone(); + let hands_commit = hands_commit.clone(); + let hands = scope.spawn(move || { + hands_barrier.wait(); + crate::put_hands_commit_receipt(&hands_store, &hands_commit) + }); + let persona_barrier = barrier.clone(); + let persona_store = store.clone(); + let persona_cultmesh = persona_cultmesh.clone(); + let persona = scope.spawn(move || { + persona_barrier.wait(); + crate::persona_conversation::admit_persona_state_notes( + &persona_store, + &persona_cultmesh, + "runtime", + &persona_request, + &persona_effect, + ) + }); + ( + hands.join().expect("concurrent Hands consequence"), + persona.join().expect("concurrent Persona Mind admission"), + ) + }); + hands_outcome?; + assert_eq!(persona_outcome?, ("admitted".into(), Vec::new())); accepted_cache.pull_all_backing_stores()?; let mut verification_requests = accepted_cache diff --git a/epiphany-core/src/mind_documents.rs b/epiphany-core/src/mind_documents.rs index ee8d472d..869bae71 100644 --- a/epiphany-core/src/mind_documents.rs +++ b/epiphany-core/src/mind_documents.rs @@ -138,6 +138,56 @@ pub struct EpiphanyMindEvidenceDocument { pub value: EpiphanyEvidenceRecord, } +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache( + type = "epiphany.mind.persona_memory.v1", + schema = "EpiphanyMindPersonaMemoryDocument" +)] +pub struct EpiphanyMindPersonaMemoryDocument { + #[cultcache(key = 0)] + pub memory_id: String, + #[cultcache(key = 1)] + pub agent_id: String, + #[cultcache(key = 2)] + pub memory_kind: String, + #[cultcache(key = 3)] + pub summary: String, + #[cultcache(key = 4)] + pub salience: f64, + #[cultcache(key = 5)] + pub confidence: f64, + #[cultcache(key = 6)] + pub linked_event_ids: Vec, + #[cultcache(key = 7)] + pub linked_relationship_id: Option, + #[cultcache(key = 8)] + pub effect_document_id: String, + #[cultcache(key = 9)] + pub decision_context_id: String, +} + +impl EpiphanyMindPersonaMemoryDocument { + pub fn validate(&self) -> Result<()> { + if [ + self.memory_id.as_str(), + self.agent_id.as_str(), + self.memory_kind.as_str(), + self.summary.as_str(), + self.effect_document_id.as_str(), + self.decision_context_id.as_str(), + ] + .into_iter() + .any(str::is_empty) + || !matches!(self.memory_kind.as_str(), "memory" | "social_read" | "bond") + || !(0.0..=1.0).contains(&self.salience) + || !(0.0..=1.0).contains(&self.confidence) + { + return Err(anyhow!("Mind Persona memory document is invalid")); + } + Ok(()) + } +} + #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] #[cultcache( type = "epiphany.mind.verification_audit.v1", @@ -281,6 +331,7 @@ 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::()?; @@ -397,6 +448,10 @@ pub(crate) fn validate_mind_write_envelope(envelope: &CultCacheEnvelope) -> Resu rmp_serde::from_slice::(&envelope.payload)? .value .id + } else if envelope.r#type == EpiphanyMindPersonaMemoryDocument::TYPE { + let value: EpiphanyMindPersonaMemoryDocument = rmp_serde::from_slice(&envelope.payload)?; + value.validate()?; + value.memory_id } else if envelope.r#type == EpiphanyMindVerificationAuditDocument::TYPE { let value: EpiphanyMindVerificationAuditDocument = rmp_serde::from_slice(&envelope.payload)?; @@ -616,6 +671,7 @@ fn canonical_mind_versions( | EpiphanyMindInvariantDocument::TYPE | EpiphanyMindObservationDocument::TYPE | EpiphanyMindEvidenceDocument::TYPE + | EpiphanyMindPersonaMemoryDocument::TYPE | EpiphanyMindVerificationAuditDocument::TYPE | crate::EpiphanyMindReorientationDecisionDocument::TYPE | crate::EpiphanyMindReorientationPassFailureDocument::TYPE diff --git a/epiphany-core/src/persona_conversation.rs b/epiphany-core/src/persona_conversation.rs index b5eb86a1..4853a092 100644 --- a/epiphany-core/src/persona_conversation.rs +++ b/epiphany-core/src/persona_conversation.rs @@ -8,7 +8,6 @@ use cultcache_rs::{ use cultnet_rs::{GameCultServiceTrustAnchorRecord, ServiceIdentitySigner}; use sha2::{Digest, Sha256}; -use crate::agent_memory::SelfPatchMemory; use crate::heartbeat_state::{ PERSONA_CONVERSATION_RETENTION_HEAD_SCHEMA_VERSION, PERSONA_CONVERSATION_RETENTION_PLAN_SCHEMA_VERSION, PersonaConversationRetentionEnvelope, @@ -17,10 +16,9 @@ use crate::heartbeat_state::{ load_heartbeat_state_transaction, }; use crate::{ - AgentSelfPatch, EpiphanyDecisionContext, EpiphanyPersonaDeliveryRequestIdentity, - EpiphanyReasoningBasis, PersonaInterpreterEffect, PersonaInterpreterEffectDocument, - PersonaModelStageReceipt, PersonaModelTerminalReceipt, PersonaTurnRequest, - PersonaTurnTerminalOptions, apply_agent_self_patch_document, + EpiphanyDecisionContext, EpiphanyPersonaDeliveryRequestIdentity, EpiphanyReasoningBasis, + PersonaInterpreterEffect, PersonaInterpreterEffectDocument, PersonaModelStageReceipt, + PersonaModelTerminalReceipt, PersonaTurnRequest, PersonaTurnTerminalOptions, complete_persona_turn_request_store, insert_persona_discord_delivery_request, load_persona_discord_delivery_receipt, runtime_spine_cache, sign_persona_discord_delivery_request, verify_persona_discord_delivery_receipt, @@ -129,7 +127,6 @@ pub struct PersonaConversationExecutionReceipt { pub fn poll_persona_discord_crossing( runtime_store: &Path, heartbeat_store: &Path, - agent_store: &Path, cultmesh_store: &Path, runtime_id: &str, request_store: &Path, @@ -170,9 +167,8 @@ pub fn poll_persona_discord_crossing( }); let Some((index, channel_id, reply_to_message_id, content)) = say else { // Non-speech turns retain the existing typed state-admission path. - let (state_status, reasons) = match admit_state_notes( + let (state_status, reasons) = match admit_persona_state_notes( runtime_store, - agent_store, cultmesh_store, runtime_id, &request, @@ -232,9 +228,8 @@ pub fn poll_persona_discord_crossing( { existing } else { - if let Err(error) = admit_state_notes( + if let Err(error) = admit_persona_state_notes( runtime_store, - agent_store, cultmesh_store, runtime_id, &request, @@ -1001,18 +996,16 @@ fn digest_value(value: &T) -> Result { )) } -fn admit_state_notes( +pub(crate) fn admit_persona_state_notes( runtime_store: &Path, - agent_store: &Path, cultmesh_store: &Path, runtime_id: &str, request: &PersonaTurnRequest, document: &PersonaInterpreterEffectDocument, ) -> Result<(String, Vec)> { - let mut semantic = Vec::new(); - let mut relationships = Vec::new(); - let mut pending = Vec::new(); - let mut journals = Vec::new(); + let mut cache = runtime_spine_cache(runtime_store)?; + cache.pull_all_backing_stores()?; + let mut writes = Vec::new(); for (index, effect) in document.effects.iter().enumerate() { let PersonaInterpreterEffect::StateNote { memory_kind, @@ -1023,73 +1016,45 @@ fn admit_state_notes( else { continue; }; - let journal = begin_effect(runtime_store, request, document, index, "state_note")?; - if journal.status == "completed" { - continue; - } - journals.push(journal); - let memory = SelfPatchMemory { + let memory = crate::EpiphanyMindPersonaMemoryDocument { memory_id: stable_memory_id(&document.document_id, index), + agent_id: request.agent_id.clone(), + memory_kind: memory_kind.clone(), summary: summary.clone(), salience: 0.7, confidence: confidence.unwrap_or(0.7), - linked_event_ids: Some(vec![document.document_id.clone()]), + linked_event_ids: vec![document.document_id.clone()], linked_relationship_id: None, + effect_document_id: document.document_id.clone(), + decision_context_id: document.decision_context_id.clone(), }; - match memory_kind.as_str() { - "memory" => semantic.push(memory), - "social_read" | "bond" => relationships.push(memory), - other => pending.push(format!( - "state_note kind {other:?} awaits a coherent typed Persona-state mapping" - )), - } + memory.validate()?; + writes.push(crate::mind_documents::prepare_mind_document( + &cache, + &memory.memory_id, + &memory, + )?); } - if semantic.is_empty() && relationships.is_empty() { - for journal in &mut journals { - finish_effect(runtime_store, journal)?; - } - return Ok(( - if pending.is_empty() { - "none" - } else { - "pending" - } - .into(), - pending, - )); + if writes.is_empty() { + return Ok(("none".into(), Vec::new())); } - let patch = AgentSelfPatch { - agent_id: Some(request.agent_id.clone()), - reason: Some( - "Persona Interpreter proposed bounded memory effects after a completed natural turn." - .into(), - ), - evidence_ids: Some(vec![document.document_id.clone()]), - semantic_memories: (!semantic.is_empty()).then_some(semantic), - relationship_memories: (!relationships.is_empty()).then_some(relationships), - ..Default::default() - }; require_persona_effects_unbraked(cultmesh_store, runtime_id)?; - let review = apply_agent_self_patch_document(&request.role_id, patch, agent_store)?; - if review.status == "accepted" && review.applied == Some(true) { - for journal in &mut journals { - finish_effect(runtime_store, journal)?; + match crate::commit_mind_mutation( + runtime_store, + &document.decision_context_id, + "Persona.state_note", + Vec::new(), + writes, + &document.created_at, + )? { + crate::EpiphanyMindCommitOutcome::Committed(_) => { + Ok(("admitted".into(), Vec::new())) } - Ok(( - if pending.is_empty() { - "admitted" - } else { - "partially_admitted" - } - .into(), - pending, - )) - } else { - pending.extend(review.reasons); - for journal in &mut journals { - finish_effect(runtime_store, journal)?; - } - Ok(("pending".into(), pending)) + crate::EpiphanyMindCommitOutcome::Conflict { + document_identities, + } => Err(anyhow!( + "Persona state-note admission conflicted with exact memory identities: {document_identities:?}" + )), } } @@ -1504,6 +1469,113 @@ mod tests { Ok(()) } + #[test] + fn persona_state_notes_commit_as_keyed_mind_documents_and_replay_exactly() -> Result<()> { + let temp = tempfile::tempdir()?; + let runtime = temp.path().join("runtime.cc"); + let cultmesh = temp.path().join("cultmesh.cc"); + crate::initialize_runtime_spine( + &runtime, + crate::RuntimeSpineInitOptions { + runtime_id: "persona-mind-test".into(), + display_name: "Persona Mind test".into(), + created_at: "2026-08-18T01:00:00Z".into(), + }, + )?; + crate::write_epiphany_cultmesh_swarm_brake( + &cultmesh, + "persona-mind-test", + crate::default_epiphany_cultmesh_swarm_brake("2026-08-18T01:00:00Z"), + )?; + let request = PersonaTurnRequest { + request_id: "turn-mind-notes".into(), + role_id: "Persona".into(), + agent_id: "epiphany.Persona".into(), + ..Default::default() + }; + let mut document = PersonaInterpreterEffectDocument { + schema_version: crate::PERSONA_INTERPRETER_EFFECT_DOCUMENT_SCHEMA_VERSION.into(), + document_id: "persona-effects:turn-mind-notes".into(), + turn_id: request.request_id.clone(), + identity_id: request.agent_id.clone(), + interpreter_request_id: "persona:turn-mind-notes:interpreter".into(), + created_at: "2026-08-18T01:00:01Z".into(), + effects: vec![ + PersonaInterpreterEffect::StateNote { + memory_kind: "memory".into(), + summary: "A durable decision belongs in keyed Mind state.".into(), + confidence: Some(0.9), + subject_id: None, + }, + PersonaInterpreterEffect::StateNote { + memory_kind: "social_read".into(), + summary: "Persona state must not serialize Hands.".into(), + confidence: Some(0.8), + subject_id: Some("person-1".into()), + }, + ], + private_state_exposed: false, + decision_context_id: String::new(), + }; + let basis = crate::EpiphanyReasoningBasis::new( + &document.interpreter_request_id, + "Persona.interpreter", + "epiphany.reasoning_projection.persona.interpreter.v1", + Vec::new(), + crate::EpiphanyReasoningProjection::PersonaInterpreter( + crate::PersonaInterpreterInput::default(), + ), + )?; + put_runtime_document(&runtime, &basis.basis_id, &basis)?; + let mut native = epiphany_model_adapter::EpiphanyModelRequest::new( + &document.interpreter_request_id, + "persona-turn-turn-mind-notes", + "openai-codex", + "test", + "fixture", + ); + native.reasoning_basis_id = Some(basis.basis_id.clone()); + let provider = epiphany_openai_adapter::request_from_native(&native); + let context = crate::EpiphanyDecisionContext::new(&basis, native, provider, Vec::new())?; + put_runtime_document(&runtime, &context.context_id, &context)?; + document.decision_context_id = context.context_id; + + assert_eq!( + admit_persona_state_notes( + &runtime, + &cultmesh, + "persona-mind-test", + &request, + &document, + )?, + ("admitted".into(), Vec::new()) + ); + let mut cache = crate::runtime_spine_cache(&runtime)?; + cache.pull_all_backing_stores()?; + let first = cache.get_all::()?; + assert_eq!(first.len(), 1); + let memories = cache.get_all::()?; + assert_eq!(memories.len(), 2); + assert!(memories.iter().all(|memory| { + memory.agent_id == request.agent_id + && memory.decision_context_id == document.decision_context_id + })); + + assert_eq!( + admit_persona_state_notes( + &runtime, + &cultmesh, + "persona-mind-test", + &request, + &document, + )?, + ("admitted".into(), Vec::new()) + ); + cache.pull_all_backing_stores()?; + assert_eq!(cache.get_all::()?, first); + Ok(()) + } + #[test] fn terminal_retention_bounds_detail_and_leaves_an_irreversible_replay_frontier() -> Result<()> { let temp = tempfile::tempdir()?; diff --git a/epiphany-openai-runtime/src/bin/epiphany-persona-service.rs b/epiphany-openai-runtime/src/bin/epiphany-persona-service.rs index b8e1c77d..9e6ba769 100644 --- a/epiphany-openai-runtime/src/bin/epiphany-persona-service.rs +++ b/epiphany-openai-runtime/src/bin/epiphany-persona-service.rs @@ -186,7 +186,6 @@ async fn poll_once(options: &Options) -> Result { let mut result = poll_persona_discord_crossing( &options.runtime_store, &options.heartbeat_store, - &options.agent_store, &options.cultmesh_store, &options.runtime_id, &options.mouth_request_store, @@ -215,7 +214,6 @@ async fn poll_once(options: &Options) -> Result { result = poll_persona_discord_crossing( &options.runtime_store, &options.heartbeat_store, - &options.agent_store, &options.cultmesh_store, &options.runtime_id, &options.mouth_request_store,