diff --git a/epiphany-core/src/mind_documents.rs b/epiphany-core/src/mind_documents.rs index 869bae71..c9d4c300 100644 --- a/epiphany-core/src/mind_documents.rs +++ b/epiphany-core/src/mind_documents.rs @@ -188,6 +188,45 @@ impl EpiphanyMindPersonaMemoryDocument { } } +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache( + type = "epiphany.mind.persona_pass_input.v1", + schema = "EpiphanyMindPersonaPassInputDocument" +)] +pub struct EpiphanyMindPersonaPassInputDocument { + #[cultcache(key = 0)] + pub turn_id: String, + #[cultcache(key = 1)] + pub projector_input: crate::PersonaProjectorInput, + #[cultcache(key = 2)] + pub transcript: Vec, + #[cultcache(key = 3)] + pub allowed_channel_ids: Vec, + #[cultcache(key = 4)] + pub dynamic_semantic_memory_recall: String, + #[cultcache(key = 5)] + pub observed_sources: Vec, + #[cultcache(key = 6)] + pub admitted_at: String, +} + +impl EpiphanyMindPersonaPassInputDocument { + pub fn validate(&self) -> Result<()> { + if self.turn_id.trim().is_empty() + || self.projector_input.identity.identity_id.trim().is_empty() + || self.admitted_at.trim().is_empty() + { + return Err(anyhow!("Mind Persona pass input is incomplete")); + } + chrono::DateTime::parse_from_rfc3339(&self.admitted_at) + .map_err(|error| anyhow!("Mind Persona pass input time is invalid: {error}"))?; + for source in &self.observed_sources { + source.validate()?; + } + Ok(()) + } +} + #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] #[cultcache( type = "epiphany.mind.verification_audit.v1", @@ -332,6 +371,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::()?; @@ -452,6 +492,11 @@ pub(crate) fn validate_mind_write_envelope(envelope: &CultCacheEnvelope) -> Resu let value: EpiphanyMindPersonaMemoryDocument = rmp_serde::from_slice(&envelope.payload)?; value.validate()?; value.memory_id + } else if envelope.r#type == EpiphanyMindPersonaPassInputDocument::TYPE { + let value: EpiphanyMindPersonaPassInputDocument = + rmp_serde::from_slice(&envelope.payload)?; + value.validate()?; + value.turn_id } else if envelope.r#type == EpiphanyMindVerificationAuditDocument::TYPE { let value: EpiphanyMindVerificationAuditDocument = rmp_serde::from_slice(&envelope.payload)?; @@ -671,7 +716,6 @@ 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 4853a092..d2ed9b29 100644 --- a/epiphany-core/src/persona_conversation.rs +++ b/epiphany-core/src/persona_conversation.rs @@ -33,6 +33,49 @@ pub const PERSONA_EFFECT_EXECUTION_INTENT_SCHEMA_VERSION: &str = pub const PERSONA_CONVERSATION_STORE_RETIREMENT_RECEIPT_SCHEMA_VERSION: &str = "epiphany.persona_conversation_store_retirement_receipt.v0"; +pub fn admit_persona_pass_input( + runtime_store: &Path, + provenance: crate::EpiphanyMindDocumentVersion, + document: &crate::EpiphanyMindPersonaPassInputDocument, +) -> Result { + document.validate()?; + if !document.observed_sources.contains(&provenance) { + return Err(anyhow!( + "Persona pass input provenance is absent from its observed sources" + )); + } + let cache = runtime_spine_cache(runtime_store)?; + let write = crate::mind_documents::prepare_mind_document( + &cache, + &document.turn_id, + document, + )?; + match crate::reasoning_context::commit_external_typed_observation_mind_mutation( + runtime_store, + "Persona", + provenance, + "Persona.pass_input", + Vec::new(), + vec![write], + &document.admitted_at, + )? { + crate::EpiphanyMindCommitOutcome::Committed(_) => {} + crate::EpiphanyMindCommitOutcome::Conflict { + document_identities, + } => { + return Err(anyhow!( + "Persona pass input identity conflicted: {document_identities:?}" + )); + } + } + let mut cache = runtime_spine_cache(runtime_store)?; + cache.pull_all_backing_stores()?; + let envelope = cache + .get_envelope::(&document.turn_id)? + .ok_or_else(|| anyhow!("Persona pass input commit lost its document"))?; + crate::EpiphanyMindDocumentVersion::from_envelope("epiphany-mind", &envelope) +} + #[derive(Clone, Debug, PartialEq, DatabaseEntry)] #[cultcache( type = "epiphany.persona_effect_execution_intent.v0", @@ -1576,6 +1619,56 @@ mod tests { Ok(()) } + #[test] + fn persona_pass_input_is_admitted_once_and_substitution_refuses_byte_identically() -> Result<()> { + let temp = tempfile::tempdir()?; + let runtime = temp.path().join("runtime.cc"); + crate::initialize_runtime_spine( + &runtime, + crate::RuntimeSpineInitOptions { + runtime_id: "persona-pass-input".into(), + display_name: "Persona pass input".into(), + created_at: "2026-08-18T02:00:00Z".into(), + }, + )?; + let identity = SingleFileMessagePackBackingStore::new(&runtime) + .pull_all()? + .into_iter() + .find(|entry| entry.r#type == crate::RUNTIME_IDENTITY_TYPE) + .expect("runtime identity provenance"); + let provenance = crate::EpiphanyMindDocumentVersion::from_envelope( + "epiphany-heartbeat", + &identity, + )?; + let document = crate::EpiphanyMindPersonaPassInputDocument { + turn_id: "persona-pass-1".into(), + projector_input: crate::PersonaProjectorInput { + identity: crate::PersonaIdentity { + identity_id: "epiphany.Persona".into(), + display_name: "Epiphany".into(), + ..Default::default() + }, + ..Default::default() + }, + transcript: Vec::new(), + allowed_channel_ids: vec!["aquarium".into()], + dynamic_semantic_memory_recall: String::new(), + observed_sources: vec![provenance.clone()], + admitted_at: "2026-08-18T02:00:01Z".into(), + }; + let first = admit_persona_pass_input(&runtime, provenance.clone(), &document)?; + assert_eq!( + admit_persona_pass_input(&runtime, provenance.clone(), &document)?, + first + ); + let before = SingleFileMessagePackBackingStore::new(&runtime).pull_all()?; + let mut substituted = document; + substituted.allowed_channel_ids = vec!["elsewhere".into()]; + assert!(admit_persona_pass_input(&runtime, provenance, &substituted).is_err()); + assert_eq!(SingleFileMessagePackBackingStore::new(&runtime).pull_all()?, before); + 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 9e6ba769..97e96157 100644 --- a/epiphany-openai-runtime/src/bin/epiphany-persona-service.rs +++ b/epiphany-openai-runtime/src/bin/epiphany-persona-service.rs @@ -1,12 +1,16 @@ -use std::{env, net::SocketAddr, path::PathBuf, process::Command, thread, time::Duration}; +use std::{env, net::SocketAddr, path::PathBuf, thread, time::Duration}; use anyhow::{Context, Result, anyhow}; +use cultcache_rs::{CacheBackingStore, DatabaseEntry, SingleFileMessagePackBackingStore}; use epiphany_core::{ - PersonaIdentity, PersonaProjectorInput, PersonaRepoActivity, PersonaSocialAffordance, - PersonaTranscriptMessage, PersonaTurnTerminalOptions, complete_persona_turn_request_store, - default_organ_dependencies_for, exchange_persona_discord_delivery_rudp, - load_agent_memory_entry_for_role, load_epiphany_cultmesh_swarm_brake, - load_heartbeat_state_entry, load_persona_discord_receipt_anchor, + EpiphanyAgentMemoryEntry, EpiphanyHeartbeatStateEntry, EpiphanyMindDocumentVersion, + EpiphanyMindPersonaPassInputDocument, PersonaIdentity, PersonaProjectorInput, + PersonaRepoActivity, PersonaSocialAffordance, PersonaTranscriptMessage, + PersonaTurnTerminalOptions, admit_persona_pass_input, assemble_mind_view, + complete_persona_turn_request_store, default_organ_dependencies_for, + exchange_persona_discord_delivery_rudp, load_agent_memory_entry_for_role, + load_epiphany_cultmesh_swarm_brake, load_heartbeat_state_entry, + load_persona_discord_receipt_anchor, load_persona_discord_service_anchor, open_persona_discord_request_identity, pending_persona_discord_delivery_request_for_turn, persona_delivery_receipt_exists_for_turn, persona_model_terminal_exists, poll_persona_discord_crossing, @@ -127,22 +131,65 @@ async fn poll_once(options: &Options) -> Result { recent_message_ids: vec![mention.message_id.clone()], }) .collect(); - let plan = PersonaModelExecutionPlan { + let mind = assemble_mind_view(&options.runtime_store)?; + let repo_activity = mind + .repository_body_observation + .as_ref() + .map(|body| PersonaRepoActivity { + repo_name: options.repo_name.clone(), + summary: format!( + "Typed repository Body generation {} at manifest {}.", + body.generation, body.manifest_root_sha256 + ), + refs: vec![body.observation_id.clone()], + }) + .into_iter() + .collect(); + let has_memory = memory.is_some(); + let projector_input = PersonaProjectorInput { + identity, + memory, + semantic_memory_recall: semantic_recall.clone(), + pending_mentions: request.mentions.clone(), + repo_activity, + social_affordances, + organ_dependencies: vec![default_organ_dependencies_for("Persona")], + }; + let mut observed_sources = Vec::new(); + let heartbeat_envelope = SingleFileMessagePackBackingStore::new(&options.heartbeat_store) + .pull_all()? + .into_iter() + .find(|entry| entry.r#type == EpiphanyHeartbeatStateEntry::TYPE) + .ok_or_else(|| anyhow!("Persona pass input lost its heartbeat source"))?; + observed_sources.push(EpiphanyMindDocumentVersion::from_envelope( + "epiphany-heartbeat", + &heartbeat_envelope, + )?); + if has_memory { + let agent_envelope = SingleFileMessagePackBackingStore::new(&options.agent_store) + .pull_all()? + .into_iter() + .find(|entry| { + entry.r#type == EpiphanyAgentMemoryEntry::TYPE && entry.key == request.role_id + }) + .ok_or_else(|| anyhow!("Persona pass input lost its agent-memory source"))?; + observed_sources.push(EpiphanyMindDocumentVersion::from_envelope( + "epiphany-agent-memory", + &agent_envelope, + )?); + } + if let Some(source) = mind.source_documents.iter().find(|source| { + source.document_type + == epiphany_core::EpiphanyMindRepositoryBodyObservationDocument::TYPE + && mind.repository_body_observation.as_ref().is_some_and(|body| { + source.document_key == body.observation_id + }) + }) { + observed_sources.push(source.clone()); + } + let observed_pass_input = EpiphanyMindPersonaPassInputDocument { turn_id: request.request_id.clone(), - provider: options.provider.clone(), - model: options.model.clone(), - projector_input: PersonaProjectorInput { - identity, - memory, - semantic_memory_recall: semantic_recall.clone(), - pending_mentions: request.mentions.clone(), - repo_activity: vec![observe_repo_activity( - &options.repo_root, - &options.repo_name, - )?], - social_affordances, - organ_dependencies: vec![default_organ_dependencies_for("Persona")], - }, + projector_input, transcript, allowed_channel_ids: request .mentions @@ -150,6 +197,39 @@ async fn poll_once(options: &Options) -> Result { .map(|mention| mention.channel_id.clone()) .collect(), dynamic_semantic_memory_recall: semantic_recall, + observed_sources, + admitted_at: request.reserved_at.clone(), + }; + let mut runtime_cache = epiphany_core::runtime_spine_cache(&options.runtime_store)?; + runtime_cache.pull_all_backing_stores()?; + let (pass_input, source) = if let Some(existing) = runtime_cache + .get::(&request.request_id)? + { + existing.validate()?; + let envelope = runtime_cache + .get_envelope::(&request.request_id)? + .ok_or_else(|| anyhow!("Persona pass input lost its exact envelope"))?; + ( + existing, + EpiphanyMindDocumentVersion::from_envelope("epiphany-mind", &envelope)?, + ) + } else { + let source = admit_persona_pass_input( + &options.runtime_store, + observed_pass_input.observed_sources[0].clone(), + &observed_pass_input, + )?; + (observed_pass_input, source) + }; + let plan = PersonaModelExecutionPlan { + turn_id: request.request_id.clone(), + provider: options.provider.clone(), + model: options.model.clone(), + projector_input: pass_input.projector_input, + transcript: pass_input.transcript, + allowed_channel_ids: pass_input.allowed_channel_ids, + dynamic_semantic_memory_recall: pass_input.dynamic_semantic_memory_recall, + source_documents: vec![source], cultmesh_store: options.cultmesh_store.clone(), runtime_id: options.runtime_id.clone(), }; @@ -242,7 +322,7 @@ struct Options { repo_name: String, persona_name: String, persona_description: String, - repo_root: PathBuf, + _repo_root: PathBuf, mouth_request_store: PathBuf, mouth_receipt_store: PathBuf, mouth_identity_store: PathBuf, @@ -282,7 +362,7 @@ impl Options { agent_store: path("--agent-store")?, cultmesh_store: path("--cultmesh-store")?, codex_home: path("--codex-home")?, - repo_root: path("--repo-root")?, + _repo_root: path("--repo-root")?, mouth_request_store: path("--mouth-request-store")?, mouth_receipt_store: path("--mouth-receipt-store")?, mouth_identity_store: path("--mouth-identity-store")?, @@ -316,33 +396,3 @@ impl Options { fn value(values: &std::collections::BTreeMap, key: &str, default: &str) -> String { values.get(key).cloned().unwrap_or_else(|| default.into()) } - -fn observe_repo_activity(repo_root: &PathBuf, repo_name: &str) -> Result { - let head = Command::new("git") - .arg("-C") - .arg(repo_root) - .args(["log", "-1", "--format=%H %s"]) - .output() - .context("failed to inspect Persona home-repo head")?; - let status = Command::new("git") - .arg("-C") - .arg(repo_root) - .args(["status", "--short"]) - .output() - .context("failed to inspect Persona home-repo status")?; - if !head.status.success() || !status.status.success() { - return Err(anyhow!("Persona home-repo activity is unavailable")); - } - let head_text = String::from_utf8(head.stdout)?.trim().to_string(); - let changed = String::from_utf8(status.stdout)?.lines().count(); - Ok(PersonaRepoActivity { - repo_name: repo_name.into(), - summary: format!("Current body head: {head_text}; {changed} worktree path(s) changed."), - refs: head_text - .split_whitespace() - .next() - .map(|value| format!("git:{value}")) - .into_iter() - .collect(), - }) -} diff --git a/epiphany-openai-runtime/src/persona_executor.rs b/epiphany-openai-runtime/src/persona_executor.rs index 9fc7300a..12bc92e4 100644 --- a/epiphany-openai-runtime/src/persona_executor.rs +++ b/epiphany-openai-runtime/src/persona_executor.rs @@ -4,6 +4,7 @@ use std::pin::Pin; use anyhow::{Context, Result, anyhow}; use chrono::SecondsFormat; +use cultcache_rs::DatabaseEntry; use epiphany_core::{ PERSONA_INTERPRETER_EFFECT_DOCUMENT_SCHEMA_VERSION, PERSONA_MODEL_STAGE_RECEIPT_SCHEMA_VERSION, PERSONA_MODEL_TERMINAL_RECEIPT_SCHEMA_VERSION, PersonaInterpreterEffectDocument, @@ -28,6 +29,7 @@ pub struct PersonaModelExecutionPlan { pub transcript: Vec, pub allowed_channel_ids: Vec, pub dynamic_semantic_memory_recall: String, + pub source_documents: Vec, pub cultmesh_store: PathBuf, pub runtime_id: String, } @@ -111,6 +113,7 @@ pub async fn execute_persona_model_turn_with_runner( runner: &mut R, ) -> Result { validate_plan(plan)?; + validate_plan_source(store_path, plan)?; let terminal_id = terminal_receipt_id(&plan.turn_id); if let Some(receipt) = load_document::(store_path, &terminal_id)? { validate_terminal_replay(store_path, plan, &receipt)?; @@ -279,7 +282,7 @@ async fn run_stage( &request_id, format!("Persona.{stage}"), format!("epiphany.reasoning_projection.persona.{stage}.v1"), - Vec::new(), + plan.source_documents.clone(), projection, )? .with_predecessor_contexts(predecessor_decision_context_ids)?; @@ -322,12 +325,47 @@ fn validate_plan(plan: &PersonaModelExecutionPlan) -> Result<()> { "Persona model execution requires turn, provider, and model ids" )); } + if plan.source_documents.len() != 1 + || plan.source_documents[0].document_type + != epiphany_core::EpiphanyMindPersonaPassInputDocument::TYPE + || plan.source_documents[0].document_key != plan.turn_id + { + return Err(anyhow!( + "Persona execution requires one exact admitted Mind pass input" + )); + } if plan.projector_input.identity.identity_id.trim().is_empty() { return Err(anyhow!("Persona model execution requires an identity id")); } Ok(()) } +fn validate_plan_source(store_path: &PathBuf, plan: &PersonaModelExecutionPlan) -> Result<()> { + let source = &plan.source_documents[0]; + let document = load_document::( + store_path, + &plan.turn_id, + )? + .ok_or_else(|| anyhow!("Persona execution lost its admitted Mind pass input"))?; + let mut cache = epiphany_core::runtime_spine_cache(store_path)?; + cache.pull_all_backing_stores()?; + let envelope = cache + .get_envelope::(&plan.turn_id)? + .ok_or_else(|| anyhow!("Persona execution lost its pass input envelope"))?; + if epiphany_core::EpiphanyMindDocumentVersion::from_envelope("epiphany-mind", &envelope)? + != *source + || document.projector_input != plan.projector_input + || document.transcript != plan.transcript + || document.allowed_channel_ids != plan.allowed_channel_ids + || document.dynamic_semantic_memory_recall != plan.dynamic_semantic_memory_recall + { + return Err(anyhow!( + "Persona execution plan diverges from its admitted Mind input" + )); + } + Ok(()) +} + fn require_persona_execution_unbraked(plan: &PersonaModelExecutionPlan) -> Result<()> { let brake = epiphany_core::load_epiphany_cultmesh_swarm_brake(&plan.cultmesh_store, &plan.runtime_id)? @@ -530,8 +568,8 @@ mod tests { } } - fn plan(cultmesh_store: PathBuf) -> PersonaModelExecutionPlan { - PersonaModelExecutionPlan { + fn plan(store: &PathBuf, cultmesh_store: PathBuf) -> Result { + let mut plan = PersonaModelExecutionPlan { turn_id: "turn-1".into(), provider: "test".into(), model: "test-model".into(), @@ -548,9 +586,39 @@ mod tests { transcript: vec![], allowed_channel_ids: vec!["aquarium".into()], dynamic_semantic_memory_recall: String::new(), + source_documents: Vec::new(), cultmesh_store, runtime_id: "epiphany-test".into(), + }; + let document = epiphany_core::EpiphanyMindPersonaPassInputDocument { + turn_id: plan.turn_id.clone(), + projector_input: plan.projector_input.clone(), + transcript: plan.transcript.clone(), + allowed_channel_ids: plan.allowed_channel_ids.clone(), + dynamic_semantic_memory_recall: plan.dynamic_semantic_memory_recall.clone(), + observed_sources: Vec::new(), + admitted_at: "2026-08-14T00:00:00Z".into(), + }; + if load_document::( + store, + &document.turn_id, + )? + .is_none() + { + put_new_document(store, &document.turn_id, &document)?; } + let mut cache = epiphany_core::runtime_spine_cache(store)?; + cache.pull_all_backing_stores()?; + let envelope = cache + .get_envelope::(&document.turn_id)? + .expect("test Persona pass input"); + plan.source_documents = vec![ + epiphany_core::EpiphanyMindDocumentVersion::from_envelope( + "epiphany-mind", + &envelope, + )?, + ]; + Ok(plan) } fn release_brake(path: &PathBuf) -> Result<()> { @@ -570,11 +638,11 @@ mod tests { release_brake(&cultmesh)?; let mut runner = FakeRunner { calls: vec![] }; let first = - execute_persona_model_turn_with_runner(&store, &plan(cultmesh.clone()), &mut runner) + execute_persona_model_turn_with_runner(&store, &plan(&store, cultmesh.clone())?, &mut runner) .await?; assert_eq!(runner.calls, ["projector", "persona", "interpreter"]); let second = - execute_persona_model_turn_with_runner(&store, &plan(cultmesh), &mut runner).await?; + execute_persona_model_turn_with_runner(&store, &plan(&store, cultmesh)?, &mut runner).await?; assert_eq!(first, second); assert_eq!(runner.calls.len(), 3); let effects = @@ -592,7 +660,7 @@ mod tests { let cultmesh = dir.path().join("cultmesh.cc"); release_brake(&cultmesh)?; let mut runner = FakeRunner { calls: vec![] }; - let mut escaped = plan(cultmesh); + let mut escaped = plan(&store, cultmesh)?; escaped.allowed_channel_ids = vec!["elsewhere".into()]; assert!( execute_persona_model_turn_with_runner(&store, &escaped, &mut runner) @@ -631,7 +699,7 @@ mod tests { put_new_document(&store, &poisoned.receipt_id, &poisoned)?; let mut runner = FakeRunner { calls: vec![] }; - let error = execute_persona_model_turn_with_runner(&store, &plan(cultmesh), &mut runner) + let error = execute_persona_model_turn_with_runner(&store, &plan(&store, cultmesh)?, &mut runner) .await .unwrap_err(); assert!(error.to_string().contains("replay binding is invalid"));