From d1b17da55ee5f72208557900b9b3a9e50346cb79 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 18 May 2026 02:42:46 +0100 Subject: [PATCH] Add memory graph Qdrant cache rebuild --- .../src/bin/epiphany-memory-graph.rs | 54 ++- epiphany-core/src/lib.rs | 4 + epiphany-core/src/memory_graph/mod.rs | 4 + epiphany-core/src/memory_graph/qdrant.rs | 281 ++++++++++++ epiphany-core/src/retrieval.rs | 433 +----------------- epiphany-core/src/semantic_cache.rs | 422 +++++++++++++++++ notes/epiphany-memory-graph-unified-plan.md | 10 +- notes/fresh-workspace-handoff.md | 4 +- state/ledgers.msgpack | Bin 134311 -> 134817 bytes state/map.yaml | 6 +- 10 files changed, 796 insertions(+), 422 deletions(-) create mode 100644 epiphany-core/src/memory_graph/qdrant.rs create mode 100644 epiphany-core/src/semantic_cache.rs diff --git a/epiphany-core/src/bin/epiphany-memory-graph.rs b/epiphany-core/src/bin/epiphany-memory-graph.rs index 43cbebd2..d89ad6de 100644 --- a/epiphany-core/src/bin/epiphany-memory-graph.rs +++ b/epiphany-core/src/bin/epiphany-memory-graph.rs @@ -7,6 +7,7 @@ use epiphany_core::EpiphanyMemoryDomain; use epiphany_core::EpiphanyMemoryEdge; use epiphany_core::EpiphanyMemoryEdgeKind; use epiphany_core::EpiphanyMemoryFreshnessStatus; +use epiphany_core::EpiphanyMemoryGraphEmbeddingCacheRequest; use epiphany_core::EpiphanyMemoryGraphSnapshot; use epiphany_core::EpiphanyMemoryLifecycle; use epiphany_core::EpiphanyMemoryNode; @@ -29,6 +30,7 @@ use epiphany_core::memory_graph_from_epiphany_graphs; use epiphany_core::memory_graph_from_heartbeat_cognition; use epiphany_core::memory_graph_node_id; use epiphany_core::plan_memory_graph_context_cut; +use epiphany_core::rebuild_memory_graph_embedding_cache; use epiphany_core::validate_memory_graph_snapshot; use epiphany_core::write_memory_graph_snapshot; use std::env; @@ -88,6 +90,11 @@ fn main() -> Result<()> { let output = write_memory_graph_embedding_manifest(manifest)?; print_json(&output)?; } + "index" => { + let index = read_index_args(args)?; + let output = rebuild_memory_graph_qdrant_cache(index)?; + print_json(&output)?; + } "smoke" => { let store = optional_path_arg(&mut args, "--store")? .unwrap_or_else(|| scoped_temp_store("epiphany-memory-graph-smoke")); @@ -188,6 +195,12 @@ struct ManifestArgs { vector_dimensions: Option, } +struct IndexArgs { + store: PathBuf, + collection_name: Option, + embedding_model: Option, +} + fn read_compose_args(args: impl Iterator) -> Result { let mut store = None; let mut graph_id = "epiphany-memory-graph".to_string(); @@ -336,6 +349,26 @@ fn read_manifest_args(args: impl Iterator) -> Result) -> Result { + let mut store = None; + let mut collection_name = None; + let mut embedding_model = None; + let mut args = args.peekable(); + while let Some(flag) = args.next() { + match flag.as_str() { + "--store" => store = Some(PathBuf::from(next_value(&mut args, "--store")?)), + "--collection" => collection_name = Some(next_value(&mut args, "--collection")?), + "--model" => embedding_model = Some(next_value(&mut args, "--model")?), + _ => return Err(anyhow!("unexpected index argument {flag:?}")), + } + } + Ok(IndexArgs { + store: store.ok_or_else(|| anyhow!("index requires --store "))?, + collection_name, + embedding_model, + }) +} + fn refresh_memory_graph_store(args: RefreshArgs) -> Result { let mut snapshots = Vec::new(); let mut source_status = Vec::new(); @@ -466,6 +499,25 @@ fn write_memory_graph_embedding_manifest(args: ManifestArgs) -> Result Result { + let mut snapshot = load_memory_graph_snapshot(&args.store)? + .ok_or_else(|| anyhow!("memory graph store {} is missing", args.store.display()))?; + let report = rebuild_memory_graph_embedding_cache( + &mut snapshot, + EpiphanyMemoryGraphEmbeddingCacheRequest { + collection_name: args.collection_name, + embedding_model: args.embedding_model, + }, + )?; + write_memory_graph_snapshot(&args.store, &snapshot)?; + Ok(serde_json::json!({ + "ok": true, + "store": args.store, + "graphId": snapshot.graph_id, + "cache": report, + })) +} + fn snapshot_status( kind: &str, source: &PathBuf, @@ -538,7 +590,7 @@ fn print_json(value: &T) -> Result<()> { fn print_usage() { eprintln!( - "usage: epiphany-memory-graph --store ..." + "usage: epiphany-memory-graph --store ..." ); } diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index 04de3053..ed9e2894 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -7,6 +7,7 @@ mod prompt; mod proposal; mod retrieval; mod runtime_spine; +mod semantic_cache; mod state_ledger; mod state_update; mod surfaces; @@ -91,6 +92,8 @@ pub use memory_graph::EpiphanyMemoryEdgeKind; pub use memory_graph::EpiphanyMemoryEmbeddingDocument; pub use memory_graph::EpiphanyMemoryEmbeddingDocumentKind; pub use memory_graph::EpiphanyMemoryEmbeddingManifest; +pub use memory_graph::EpiphanyMemoryGraphEmbeddingCacheReport; +pub use memory_graph::EpiphanyMemoryGraphEmbeddingCacheRequest; pub use memory_graph::EpiphanyMemoryGraphEntry; pub use memory_graph::EpiphanyMemoryGraphSnapshot; pub use memory_graph::EpiphanyMemoryGraphValidationError; @@ -115,6 +118,7 @@ pub use memory_graph::memory_graph_from_epiphany_graphs; pub use memory_graph::memory_graph_from_heartbeat_cognition; pub use memory_graph::memory_graph_node_id; pub use memory_graph::plan_memory_graph_context_cut; +pub use memory_graph::rebuild_memory_graph_embedding_cache; pub use memory_graph::validate_memory_graph_entry; pub use memory_graph::validate_memory_graph_snapshot; pub use memory_graph::write_memory_graph_entry; diff --git a/epiphany-core/src/memory_graph/mod.rs b/epiphany-core/src/memory_graph/mod.rs index f267c775..4f7285c2 100644 --- a/epiphany-core/src/memory_graph/mod.rs +++ b/epiphany-core/src/memory_graph/mod.rs @@ -4,6 +4,7 @@ pub mod embedding; pub mod freshness; pub mod ids; pub mod profiles; +pub mod qdrant; pub mod store; pub mod validation; @@ -38,6 +39,9 @@ pub use ids::memory_graph_node_id; pub use profiles::memory_graph_from_agent_memories; pub use profiles::memory_graph_from_epiphany_graphs; pub use profiles::memory_graph_from_heartbeat_cognition; +pub use qdrant::EpiphanyMemoryGraphEmbeddingCacheReport; +pub use qdrant::EpiphanyMemoryGraphEmbeddingCacheRequest; +pub use qdrant::rebuild_memory_graph_embedding_cache; pub use store::EpiphanyMemoryGraphEntry; pub use store::MEMORY_GRAPH_KEY; pub use store::MEMORY_GRAPH_SCHEMA_VERSION; diff --git a/epiphany-core/src/memory_graph/qdrant.rs b/epiphany-core/src/memory_graph/qdrant.rs new file mode 100644 index 00000000..50c67088 --- /dev/null +++ b/epiphany-core/src/memory_graph/qdrant.rs @@ -0,0 +1,281 @@ +use super::EpiphanyMemoryEmbeddingManifest; +use super::EpiphanyMemoryGraphSnapshot; +use super::memory_graph_embedding_documents; +use super::memory_graph_embedding_manifest; +use crate::semantic_cache::OllamaConfig; +use crate::semantic_cache::OllamaEmbedder; +use crate::semantic_cache::QdrantClient; +use crate::semantic_cache::QdrantConfig; +use crate::semantic_cache::QdrantPointInput; +use crate::semantic_cache::ollama_config_from_env; +use crate::semantic_cache::qdrant_config_from_env; +use crate::semantic_cache::validate_embedding_batch; +use anyhow::Context; +use anyhow::Result; +use serde::Serialize; +use serde_json::json; +use sha1::Digest; +use sha1::Sha1; +use uuid::Uuid; + +const MEMORY_GRAPH_INDEX_REVISION: &str = "memory-graph-qdrant-v1"; +const DEFAULT_MEMORY_GRAPH_QUERY_INSTRUCTION: &str = + "Given an agent work question, retrieve the most relevant project memory graph records."; + +#[derive(Clone, Debug)] +pub struct EpiphanyMemoryGraphEmbeddingCacheRequest { + pub collection_name: Option, + pub embedding_model: Option, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct EpiphanyMemoryGraphEmbeddingCacheReport { + pub collection_name: String, + pub embedding_model: String, + pub vector_dimensions: Option, + pub indexed_document_count: usize, + pub manifest: EpiphanyMemoryEmbeddingManifest, +} + +pub fn rebuild_memory_graph_embedding_cache( + snapshot: &mut EpiphanyMemoryGraphSnapshot, + request: EpiphanyMemoryGraphEmbeddingCacheRequest, +) -> Result { + let mut ollama_config = ollama_config_from_env(DEFAULT_MEMORY_GRAPH_QUERY_INSTRUCTION); + if let Some(model) = request.embedding_model.clone() { + ollama_config.model = model; + } + rebuild_memory_graph_embedding_cache_with_config( + snapshot, + request, + qdrant_config_from_env(), + ollama_config, + ) +} + +fn rebuild_memory_graph_embedding_cache_with_config( + snapshot: &mut EpiphanyMemoryGraphSnapshot, + request: EpiphanyMemoryGraphEmbeddingCacheRequest, + qdrant_config: QdrantConfig, + ollama_config: OllamaConfig, +) -> Result { + let collection_name = request + .collection_name + .or_else(|| { + snapshot + .embedding_manifest + .as_ref() + .and_then(|manifest| manifest.collection_name.clone()) + }) + .unwrap_or_else(|| default_memory_graph_collection_name(&snapshot.graph_id)); + + let embedding_model = ollama_config.model.clone(); + + let documents = memory_graph_embedding_documents(snapshot); + let qdrant = QdrantClient::new(qdrant_config)?; + qdrant.delete_collection(&collection_name)?; + + let vector_dimensions = if documents.is_empty() { + None + } else { + let texts = documents + .iter() + .map(|document| document.text.clone()) + .collect::>(); + let embeddings = OllamaEmbedder::new(ollama_config)?.embed_documents(&texts)?; + validate_embedding_batch(&embeddings, texts.len())?; + let vector_size = embeddings + .first() + .map(Vec::len) + .context("embedding backend returned no vectors for memory graph rebuild")?; + qdrant.create_collection( + &collection_name, + vector_size, + json!({ + "managedBy": "epiphany", + "schemaVersion": 1, + "indexRevision": MEMORY_GRAPH_INDEX_REVISION, + "graphId": snapshot.graph_id, + "embeddingModel": embedding_model, + "vectorSize": vector_size, + }), + )?; + let points = documents + .iter() + .zip(embeddings) + .map(|(document, vector)| QdrantPointInput { + id: memory_graph_point_id(&collection_name, &document.id), + vector, + payload: json!({ + "graphId": snapshot.graph_id, + "documentId": document.id, + "sourceId": document.source_id, + "documentKind": document.document_kind, + "profile": document.profile, + "lifecycle": document.lifecycle, + "sourceHashes": document.source_hashes, + "text": document.text, + }), + }) + .collect::>(); + qdrant.upsert_points(&collection_name, &points)?; + Some(u32::try_from(vector_size).context("embedding vector dimension overflow")?) + }; + + let manifest = memory_graph_embedding_manifest( + snapshot, + collection_name.clone(), + embedding_model.clone(), + vector_dimensions, + ); + snapshot.embedding_manifest = Some(manifest.clone()); + + Ok(EpiphanyMemoryGraphEmbeddingCacheReport { + collection_name, + embedding_model, + vector_dimensions, + indexed_document_count: documents.len(), + manifest, + }) +} + +fn default_memory_graph_collection_name(graph_id: &str) -> String { + format!("epiphany_memory_graph_{}", short_hash(graph_id)) +} + +fn memory_graph_point_id(collection_name: &str, document_id: &str) -> String { + let key = format!("{collection_name}\n{document_id}"); + Uuid::new_v5(&Uuid::NAMESPACE_URL, key.as_bytes()).to_string() +} + +fn short_hash(value: &str) -> String { + let mut hasher = Sha1::new(); + hasher.update(value.as_bytes()); + let digest = hasher.finalize(); + hex_lower(&digest[..8]) +} + +fn hex_lower(bytes: &[u8]) -> String { + const HEX: &[u8; 16] = b"0123456789abcdef"; + let mut out = String::with_capacity(bytes.len() * 2); + for byte in bytes { + out.push(HEX[(byte >> 4) as usize] as char); + out.push(HEX[(byte & 0x0f) as usize] as char); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::memory_graph::EpiphanyMemoryDomain; + use crate::memory_graph::EpiphanyMemoryLifecycle; + use crate::memory_graph::EpiphanyMemoryNode; + use crate::memory_graph::EpiphanyMemoryNodeKind; + use crate::memory_graph::EpiphanyMemoryProfile; + use wiremock::Mock; + use wiremock::MockServer; + use wiremock::ResponseTemplate; + use wiremock::matchers::method; + use wiremock::matchers::path; + + #[test] + fn memory_graph_qdrant_rebuild_writes_manifest_from_typed_documents() -> Result<()> { + let runtime = tokio::runtime::Runtime::new()?; + let qdrant = runtime.block_on(MockServer::start()); + let ollama = runtime.block_on(MockServer::start()); + + runtime.block_on(async { + Mock::given(method("DELETE")) + .and(path("/collections/test_memory_graph")) + .respond_with(ResponseTemplate::new(404)) + .mount(&qdrant) + .await; + Mock::given(method("POST")) + .and(path("/api/embed")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "embeddings": [[0.1_f32, 0.2_f32, 0.3_f32]] + }))) + .mount(&ollama) + .await; + Mock::given(method("PUT")) + .and(path("/collections/test_memory_graph")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"result": true}))) + .mount(&qdrant) + .await; + Mock::given(method("PUT")) + .and(path("/collections/test_memory_graph/points")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"result": {}}))) + .mount(&qdrant) + .await; + }); + + let mut snapshot = test_snapshot(); + let report = rebuild_memory_graph_embedding_cache_with_config( + &mut snapshot, + EpiphanyMemoryGraphEmbeddingCacheRequest { + collection_name: Some("test_memory_graph".to_string()), + embedding_model: None, + }, + QdrantConfig { + url: qdrant.uri(), + api_key: None, + timeout_ms: 1_000, + }, + OllamaConfig { + base_url: ollama.uri(), + model: "test-embedding".to_string(), + timeout_ms: 1_000, + query_instruction: DEFAULT_MEMORY_GRAPH_QUERY_INSTRUCTION.to_string(), + }, + )?; + + assert_eq!(report.collection_name, "test_memory_graph"); + assert_eq!(report.embedding_model, "test-embedding"); + assert_eq!(report.vector_dimensions, Some(3)); + assert_eq!(report.indexed_document_count, 1); + assert_eq!( + snapshot + .embedding_manifest + .as_ref() + .and_then(|manifest| manifest.collection_name.as_deref()), + Some("test_memory_graph") + ); + + Ok(()) + } + + fn test_snapshot() -> EpiphanyMemoryGraphSnapshot { + EpiphanyMemoryGraphSnapshot { + schema_version: Some("epiphany.memory_graph.v0".to_string()), + graph_id: "graph-for-qdrant-test".to_string(), + domains: vec![EpiphanyMemoryDomain { + id: "repo".to_string(), + profile: EpiphanyMemoryProfile::RepoArchitecture, + title: "Repo".to_string(), + description: None, + lifecycle: EpiphanyMemoryLifecycle::Accepted, + }], + nodes: vec![EpiphanyMemoryNode { + id: "node-auth-spine".to_string(), + domain_id: "repo".to_string(), + profile: EpiphanyMemoryProfile::RepoArchitecture, + kind: EpiphanyMemoryNodeKind::Module, + title: "Auth spine".to_string(), + claim: "Codex owns authentication while Epiphany owns memory.".to_string(), + question: String::new(), + tension: String::new(), + action_implication: String::new(), + anchors: Vec::new(), + source_hashes: vec!["source-a".to_string()], + lifecycle: EpiphanyMemoryLifecycle::Accepted, + salience: 80, + confidence: 90, + created_at: None, + updated_at: None, + }], + ..Default::default() + } + } +} diff --git a/epiphany-core/src/retrieval.rs b/epiphany-core/src/retrieval.rs index 1737fcfe..83631ece 100644 --- a/epiphany-core/src/retrieval.rs +++ b/epiphany-core/src/retrieval.rs @@ -1,3 +1,12 @@ +use crate::semantic_cache::OllamaConfig; +use crate::semantic_cache::OllamaEmbedder; +use crate::semantic_cache::QdrantClient; +use crate::semantic_cache::QdrantConfig; +use crate::semantic_cache::QdrantPointInput; +use crate::semantic_cache::QdrantQueryPoint; +use crate::semantic_cache::ollama_config_from_env; +use crate::semantic_cache::qdrant_config_from_env; +use crate::semantic_cache::validate_embedding_batch; use anyhow::Context; use anyhow::Result; use bm25::Document; @@ -7,14 +16,8 @@ use epiphany_state_model::EpiphanyRetrievalShardSummary; use epiphany_state_model::EpiphanyRetrievalState; use epiphany_state_model::EpiphanyRetrievalStatus; use ignore::WalkBuilder; -use reqwest::StatusCode; -use reqwest::blocking::Client; -use reqwest::blocking::ClientBuilder; -use reqwest::header::HeaderMap; -use reqwest::header::HeaderValue; use serde::Deserialize; use serde::Serialize; -use serde_json::Value; use serde_json::json; use sha1::Digest; use sha1::Sha1; @@ -25,7 +28,6 @@ use std::fs; use std::path::Component; use std::path::Path; use std::path::PathBuf; -use std::time::Duration; use std::time::SystemTime; use std::time::UNIX_EPOCH; use uuid::Uuid; @@ -44,13 +46,6 @@ const CHUNK_LINE_OVERLAP: usize = 8; const WORKSPACE_SHARD_ID: &str = "workspace"; const MANIFESTS_DIR: &str = "epiphany/retrieval/manifests"; const QDRANT_COLLECTION_PREFIX: &str = "epiphany_workspace"; -const QDRANT_POINT_BATCH_SIZE: usize = 128; -const OLLAMA_EMBED_BATCH_SIZE: usize = 32; -const DEFAULT_QDRANT_URL: &str = "http://127.0.0.1:6333"; -const DEFAULT_QDRANT_TIMEOUT_MS: u64 = 30_000; -const DEFAULT_OLLAMA_BASE_URL: &str = "http://127.0.0.1:11434"; -const DEFAULT_OLLAMA_MODEL: &str = "qwen3-embedding:0.6b"; -const DEFAULT_OLLAMA_TIMEOUT_MS: u64 = 30_000; const DEFAULT_QUERY_INSTRUCTION: &str = "Given a source-tree or codebase question, retrieve relevant files and code snippets that answer it."; #[derive(Clone, Debug, PartialEq, Eq)] @@ -380,9 +375,14 @@ fn index_workspace_with_config( qdrant.create_collection( &expected_collection, vector_size, - &config.index_revision(), - workspace_root, - &config.ollama.model, + json!({ + "managedBy": "epiphany", + "schemaVersion": SEMANTIC_MANIFEST_SCHEMA_VERSION, + "indexRevision": config.index_revision(), + "workspaceRoot": workspace_root.to_string_lossy(), + "embeddingModel": config.ollama.model, + "vectorSize": vector_size, + }), )?; } @@ -686,28 +686,8 @@ struct SemanticBackendConfig { impl SemanticBackendConfig { fn from_env() -> Self { Self { - qdrant: QdrantConfig { - url: env_override("EPIPHANY_QDRANT_URL", "QDRANT_URL") - .unwrap_or_else(|| DEFAULT_QDRANT_URL.to_string()), - api_key: env_override("EPIPHANY_QDRANT_API_KEY", "QDRANT_API_KEY"), - timeout_ms: env_override("EPIPHANY_QDRANT_TIMEOUT_MS", "QDRANT_TIMEOUT_MS") - .and_then(|value| value.parse::().ok()) - .unwrap_or(DEFAULT_QDRANT_TIMEOUT_MS), - }, - ollama: OllamaConfig { - base_url: env_override("EPIPHANY_OLLAMA_BASE_URL", "RAG_OLLAMA_BASE_URL") - .unwrap_or_else(|| DEFAULT_OLLAMA_BASE_URL.to_string()), - model: env_override("EPIPHANY_OLLAMA_MODEL", "RAG_OLLAMA_MODEL") - .unwrap_or_else(|| DEFAULT_OLLAMA_MODEL.to_string()), - timeout_ms: env_override("EPIPHANY_OLLAMA_TIMEOUT_MS", "RAG_OLLAMA_TIMEOUT_MS") - .and_then(|value| value.parse::().ok()) - .unwrap_or(DEFAULT_OLLAMA_TIMEOUT_MS), - query_instruction: env_override( - "EPIPHANY_OLLAMA_QUERY_INSTRUCTION", - "RAG_SOURCE_QUERY_INSTRUCTION", - ) - .unwrap_or_else(|| DEFAULT_QUERY_INSTRUCTION.to_string()), - }, + qdrant: qdrant_config_from_env(), + ollama: ollama_config_from_env(DEFAULT_QUERY_INSTRUCTION), } } @@ -734,337 +714,6 @@ impl SemanticBackendConfig { } } -#[derive(Clone, Debug)] -struct QdrantConfig { - url: String, - api_key: Option, - timeout_ms: u64, -} - -#[derive(Clone, Debug)] -struct OllamaConfig { - base_url: String, - model: String, - timeout_ms: u64, - query_instruction: String, -} - -struct QdrantClient { - base_url: String, - timeout_seconds: u64, - client: Client, -} - -impl QdrantClient { - fn new(config: QdrantConfig) -> Result { - let mut headers = HeaderMap::new(); - if let Some(api_key) = config.api_key - && !api_key.is_empty() - { - headers.insert( - "api-key", - HeaderValue::from_str(&api_key).context("invalid Qdrant api key")?, - ); - } - - let client = ClientBuilder::new() - .default_headers(headers) - .timeout(Duration::from_millis(config.timeout_ms)) - .build() - .context("failed to build Qdrant client")?; - - Ok(Self { - base_url: normalize_base_url(&config.url), - timeout_seconds: timeout_seconds(config.timeout_ms), - client, - }) - } - - fn collection_exists(&self, collection_name: &str) -> Result { - let response = self - .client - .get(format!( - "{}/collections/{collection_name}/exists", - self.base_url - )) - .send() - .with_context(|| format!("failed to query Qdrant collection {collection_name}"))?; - - let payload: QdrantEnvelope = parse_qdrant_response(response) - .with_context(|| { - format!("failed to decode Qdrant collection-exists response for {collection_name}") - })?; - Ok(payload.result.exists) - } - - fn delete_collection(&self, collection_name: &str) -> Result<()> { - let response = self - .client - .delete(format!("{}/collections/{collection_name}", self.base_url)) - .query(&[("timeout", self.timeout_seconds)]) - .send() - .with_context(|| format!("failed to delete Qdrant collection {collection_name}"))?; - - if response.status() == StatusCode::NOT_FOUND { - return Ok(()); - } - parse_qdrant_response::(response).with_context(|| { - format!("failed to decode Qdrant delete-collection response for {collection_name}") - })?; - Ok(()) - } - - fn create_collection( - &self, - collection_name: &str, - vector_size: usize, - index_revision: &str, - workspace_root: &Path, - embedding_model: &str, - ) -> Result<()> { - let body = json!({ - "vectors": { - "size": vector_size, - "distance": "Cosine", - "on_disk": true, - }, - "on_disk_payload": true, - "metadata": { - "managedBy": "epiphany", - "schemaVersion": SEMANTIC_MANIFEST_SCHEMA_VERSION, - "indexRevision": index_revision, - "workspaceRoot": workspace_root.to_string_lossy(), - "embeddingModel": embedding_model, - "vectorSize": vector_size, - } - }); - - let response = self - .client - .put(format!("{}/collections/{collection_name}", self.base_url)) - .query(&[("timeout", self.timeout_seconds)]) - .json(&body) - .send() - .with_context(|| format!("failed to create Qdrant collection {collection_name}"))?; - - parse_qdrant_response::(response).with_context(|| { - format!("failed to decode Qdrant create-collection response for {collection_name}") - })?; - Ok(()) - } - - fn upsert_points(&self, collection_name: &str, points: &[QdrantPointInput]) -> Result<()> { - for chunk in points.chunks(QDRANT_POINT_BATCH_SIZE) { - let body = json!({ "points": chunk }); - let response = self - .client - .put(format!( - "{}/collections/{collection_name}/points", - self.base_url - )) - .query(&[ - ("wait", "true"), - ("timeout", &self.timeout_seconds.to_string()), - ]) - .json(&body) - .send() - .with_context(|| { - format!("failed to upsert Qdrant points into {collection_name}") - })?; - - parse_qdrant_response::(response).with_context(|| { - format!("failed to decode Qdrant upsert response for {collection_name}") - })?; - } - Ok(()) - } - - fn delete_points(&self, collection_name: &str, point_ids: &[String]) -> Result<()> { - if point_ids.is_empty() { - return Ok(()); - } - - for batch in point_ids.chunks(QDRANT_POINT_BATCH_SIZE) { - let body = json!({ "points": batch }); - let response = self - .client - .post(format!( - "{}/collections/{collection_name}/points/delete", - self.base_url - )) - .query(&[ - ("wait", "true"), - ("timeout", &self.timeout_seconds.to_string()), - ]) - .json(&body) - .send() - .with_context(|| { - format!("failed to delete Qdrant points from {collection_name}") - })?; - - parse_qdrant_response::(response).with_context(|| { - format!("failed to decode Qdrant delete-points response for {collection_name}") - })?; - } - Ok(()) - } - - fn query_points( - &self, - collection_name: &str, - query_vector: &[f32], - limit: usize, - ) -> Result> { - let body = json!({ - "query": query_vector, - "limit": limit, - "with_payload": true, - "with_vector": false, - }); - - let response = self - .client - .post(format!( - "{}/collections/{collection_name}/points/query", - self.base_url - )) - .query(&[("timeout", self.timeout_seconds)]) - .json(&body) - .send() - .with_context(|| format!("failed to query Qdrant collection {collection_name}"))?; - - let payload: QdrantEnvelope = parse_qdrant_response(response) - .with_context(|| { - format!("failed to decode Qdrant query response for {collection_name}") - })?; - Ok(payload.result.points) - } -} - -struct OllamaEmbedder { - base_url: String, - model: String, - query_instruction: String, - client: Client, -} - -impl OllamaEmbedder { - fn new(config: OllamaConfig) -> Result { - let client = ClientBuilder::new() - .timeout(Duration::from_millis(config.timeout_ms)) - .build() - .context("failed to build Ollama client")?; - - Ok(Self { - base_url: normalize_base_url(&config.base_url), - model: config.model, - query_instruction: config.query_instruction, - client, - }) - } - - fn embed_documents(&self, texts: &[String]) -> Result>> { - let mut embeddings = Vec::new(); - for batch in texts.chunks(OLLAMA_EMBED_BATCH_SIZE) { - let payload = self.embed_batch(batch)?; - embeddings.extend(payload); - } - Ok(embeddings) - } - - fn embed_query(&self, query: &str) -> Result> { - let formatted = format!("Instruct: {}\nQuery: {}", self.query_instruction, query); - let mut payload = self.embed_batch(&[formatted])?; - payload - .pop() - .context("Ollama embedding backend returned no vector for query") - } - - fn embed_batch(&self, texts: &[String]) -> Result>> { - let response = self - .client - .post(format!("{}/api/embed", self.base_url)) - .json(&json!({ - "model": self.model, - "input": texts, - })) - .send() - .with_context(|| { - format!( - "failed to contact Ollama at {} using model {}", - self.base_url, self.model - ) - })?; - - if !response.status().is_success() { - let status = response.status(); - let body = response.text().unwrap_or_default(); - anyhow::bail!( - "Ollama embedding request failed with {status}: {body}. Make sure Ollama is running at {} and model {} is available", - self.base_url, - self.model - ); - } - - let payload: OllamaEmbedResponse = response.json().with_context(|| { - format!( - "failed to decode Ollama embedding response from {}", - self.base_url - ) - })?; - payload - .embeddings - .context("Ollama embedding response did not include embeddings") - } -} - -#[derive(Serialize)] -struct QdrantPointInput { - id: String, - vector: Vec, - payload: Value, -} - -#[derive(Debug, Deserialize)] -struct QdrantEnvelope { - result: T, -} - -#[derive(Debug, Deserialize)] -struct QdrantCollectionExistsResult { - exists: bool, -} - -#[derive(Debug, Deserialize)] -struct QdrantQueryResultEnvelope { - points: Vec, -} - -#[derive(Clone, Debug, Deserialize)] -struct QdrantQueryPoint { - score: f32, - #[serde(default)] - payload: BTreeMap, -} - -#[derive(Debug, Deserialize)] -struct OllamaEmbedResponse { - embeddings: Option>>, -} - -fn parse_qdrant_response Deserialize<'de>>( - response: reqwest::blocking::Response, -) -> Result> { - let status = response.status(); - if !status.is_success() { - let body = response.text().unwrap_or_default(); - anyhow::bail!("Qdrant request failed with {status}: {body}"); - } - response - .json() - .context("failed to decode Qdrant response JSON") -} - fn collect_semantic_corpus( workspace_root: &Path, path_prefixes: &[PathBuf], @@ -1613,31 +1262,6 @@ fn normalize_payload_path(path: &Path) -> String { .join("/") } -fn validate_embedding_batch(embeddings: &[Vec], expected_count: usize) -> Result<()> { - if embeddings.len() != expected_count { - anyhow::bail!( - "embedding backend returned {} vectors for {} chunks", - embeddings.len(), - expected_count - ); - } - - let Some(vector_length) = embeddings.first().map(Vec::len) else { - return Ok(()); - }; - if vector_length == 0 { - anyhow::bail!("embedding backend returned an empty vector"); - } - - for (index, embedding) in embeddings.iter().enumerate() { - if embedding.len() != vector_length { - anyhow::bail!("embedding backend returned inconsistent vector length at item {index}"); - } - } - - Ok(()) -} - fn unix_timestamp_seconds(time: SystemTime) -> Result { Ok(i64::try_from( time.duration_since(UNIX_EPOCH) @@ -1658,25 +1282,6 @@ fn unix_timestamp_nanos(time: SystemTime) -> Result { Ok(i64::try_from(nanos)?) } -fn normalize_base_url(input: &str) -> String { - input.trim_end_matches('/').to_string() -} - -fn timeout_seconds(timeout_ms: u64) -> u64 { - timeout_ms.div_ceil(1000).max(1) -} - -fn env_override(primary: &str, fallback: &str) -> Option { - std::env::var(primary) - .ok() - .filter(|value| !value.trim().is_empty()) - .or_else(|| { - std::env::var(fallback) - .ok() - .filter(|value| !value.trim().is_empty()) - }) -} - fn hex_lower(bytes: &[u8]) -> String { bytes.iter().map(|byte| format!("{byte:02x}")).collect() } diff --git a/epiphany-core/src/semantic_cache.rs b/epiphany-core/src/semantic_cache.rs new file mode 100644 index 00000000..d2239cc6 --- /dev/null +++ b/epiphany-core/src/semantic_cache.rs @@ -0,0 +1,422 @@ +use anyhow::Context; +use anyhow::Result; +use reqwest::StatusCode; +use reqwest::blocking::Client; +use reqwest::blocking::ClientBuilder; +use reqwest::header::HeaderMap; +use reqwest::header::HeaderValue; +use serde::Deserialize; +use serde::Serialize; +use serde_json::Value; +use serde_json::json; +use std::collections::BTreeMap; +use std::time::Duration; + +const QDRANT_POINT_BATCH_SIZE: usize = 128; +const OLLAMA_EMBED_BATCH_SIZE: usize = 32; +pub(crate) const DEFAULT_QDRANT_URL: &str = "http://127.0.0.1:6333"; +pub(crate) const DEFAULT_QDRANT_TIMEOUT_MS: u64 = 30_000; +pub(crate) const DEFAULT_OLLAMA_BASE_URL: &str = "http://127.0.0.1:11434"; +pub(crate) const DEFAULT_OLLAMA_MODEL: &str = "qwen3-embedding:0.6b"; +pub(crate) const DEFAULT_OLLAMA_TIMEOUT_MS: u64 = 30_000; + +#[derive(Clone, Debug)] +pub(crate) struct QdrantConfig { + pub(crate) url: String, + pub(crate) api_key: Option, + pub(crate) timeout_ms: u64, +} + +#[derive(Clone, Debug)] +pub(crate) struct OllamaConfig { + pub(crate) base_url: String, + pub(crate) model: String, + pub(crate) timeout_ms: u64, + pub(crate) query_instruction: String, +} + +pub(crate) fn qdrant_config_from_env() -> QdrantConfig { + QdrantConfig { + url: env_override("EPIPHANY_QDRANT_URL", "QDRANT_URL") + .unwrap_or_else(|| DEFAULT_QDRANT_URL.to_string()), + api_key: env_override("EPIPHANY_QDRANT_API_KEY", "QDRANT_API_KEY"), + timeout_ms: env_override("EPIPHANY_QDRANT_TIMEOUT_MS", "QDRANT_TIMEOUT_MS") + .and_then(|value| value.parse::().ok()) + .unwrap_or(DEFAULT_QDRANT_TIMEOUT_MS), + } +} + +pub(crate) fn ollama_config_from_env(query_instruction: impl Into) -> OllamaConfig { + OllamaConfig { + base_url: env_override("EPIPHANY_OLLAMA_BASE_URL", "RAG_OLLAMA_BASE_URL") + .unwrap_or_else(|| DEFAULT_OLLAMA_BASE_URL.to_string()), + model: env_override("EPIPHANY_OLLAMA_MODEL", "RAG_OLLAMA_MODEL") + .unwrap_or_else(|| DEFAULT_OLLAMA_MODEL.to_string()), + timeout_ms: env_override("EPIPHANY_OLLAMA_TIMEOUT_MS", "RAG_OLLAMA_TIMEOUT_MS") + .and_then(|value| value.parse::().ok()) + .unwrap_or(DEFAULT_OLLAMA_TIMEOUT_MS), + query_instruction: env_override( + "EPIPHANY_OLLAMA_QUERY_INSTRUCTION", + "RAG_SOURCE_QUERY_INSTRUCTION", + ) + .unwrap_or_else(|| query_instruction.into()), + } +} + +pub(crate) struct QdrantClient { + base_url: String, + timeout_seconds: u64, + client: Client, +} + +impl QdrantClient { + pub(crate) fn new(config: QdrantConfig) -> Result { + let mut headers = HeaderMap::new(); + if let Some(api_key) = config.api_key + && !api_key.is_empty() + { + headers.insert( + "api-key", + HeaderValue::from_str(&api_key).context("invalid Qdrant api key")?, + ); + } + + let client = ClientBuilder::new() + .default_headers(headers) + .timeout(Duration::from_millis(config.timeout_ms)) + .build() + .context("failed to build Qdrant client")?; + + Ok(Self { + base_url: normalize_base_url(&config.url), + timeout_seconds: timeout_seconds(config.timeout_ms), + client, + }) + } + + pub(crate) fn collection_exists(&self, collection_name: &str) -> Result { + let response = self + .client + .get(format!( + "{}/collections/{collection_name}/exists", + self.base_url + )) + .send() + .with_context(|| format!("failed to query Qdrant collection {collection_name}"))?; + + let payload: QdrantEnvelope = parse_qdrant_response(response) + .with_context(|| { + format!("failed to decode Qdrant collection-exists response for {collection_name}") + })?; + Ok(payload.result.exists) + } + + pub(crate) fn delete_collection(&self, collection_name: &str) -> Result<()> { + let response = self + .client + .delete(format!("{}/collections/{collection_name}", self.base_url)) + .query(&[("timeout", self.timeout_seconds)]) + .send() + .with_context(|| format!("failed to delete Qdrant collection {collection_name}"))?; + + if response.status() == StatusCode::NOT_FOUND { + return Ok(()); + } + parse_qdrant_response::(response).with_context(|| { + format!("failed to decode Qdrant delete-collection response for {collection_name}") + })?; + Ok(()) + } + + pub(crate) fn create_collection( + &self, + collection_name: &str, + vector_size: usize, + metadata: Value, + ) -> Result<()> { + let body = json!({ + "vectors": { + "size": vector_size, + "distance": "Cosine", + "on_disk": true, + }, + "on_disk_payload": true, + "metadata": metadata, + }); + + let response = self + .client + .put(format!("{}/collections/{collection_name}", self.base_url)) + .query(&[("timeout", self.timeout_seconds)]) + .json(&body) + .send() + .with_context(|| format!("failed to create Qdrant collection {collection_name}"))?; + + parse_qdrant_response::(response).with_context(|| { + format!("failed to decode Qdrant create-collection response for {collection_name}") + })?; + Ok(()) + } + + pub(crate) fn upsert_points( + &self, + collection_name: &str, + points: &[QdrantPointInput], + ) -> Result<()> { + for chunk in points.chunks(QDRANT_POINT_BATCH_SIZE) { + let body = json!({ "points": chunk }); + let response = self + .client + .put(format!( + "{}/collections/{collection_name}/points", + self.base_url + )) + .query(&[ + ("wait", "true"), + ("timeout", &self.timeout_seconds.to_string()), + ]) + .json(&body) + .send() + .with_context(|| { + format!("failed to upsert Qdrant points into {collection_name}") + })?; + + parse_qdrant_response::(response).with_context(|| { + format!("failed to decode Qdrant upsert response for {collection_name}") + })?; + } + Ok(()) + } + + pub(crate) fn delete_points(&self, collection_name: &str, point_ids: &[String]) -> Result<()> { + if point_ids.is_empty() { + return Ok(()); + } + + for batch in point_ids.chunks(QDRANT_POINT_BATCH_SIZE) { + let body = json!({ "points": batch }); + let response = self + .client + .post(format!( + "{}/collections/{collection_name}/points/delete", + self.base_url + )) + .query(&[ + ("wait", "true"), + ("timeout", &self.timeout_seconds.to_string()), + ]) + .json(&body) + .send() + .with_context(|| { + format!("failed to delete Qdrant points from {collection_name}") + })?; + + parse_qdrant_response::(response).with_context(|| { + format!("failed to decode Qdrant delete-points response for {collection_name}") + })?; + } + Ok(()) + } + + pub(crate) fn query_points( + &self, + collection_name: &str, + query_vector: &[f32], + limit: usize, + ) -> Result> { + let body = json!({ + "query": query_vector, + "limit": limit, + "with_payload": true, + "with_vector": false, + }); + + let response = self + .client + .post(format!( + "{}/collections/{collection_name}/points/query", + self.base_url + )) + .query(&[("timeout", self.timeout_seconds)]) + .json(&body) + .send() + .with_context(|| format!("failed to query Qdrant collection {collection_name}"))?; + + let payload: QdrantEnvelope = parse_qdrant_response(response) + .with_context(|| { + format!("failed to decode Qdrant query response for {collection_name}") + })?; + Ok(payload.result.points) + } +} + +pub(crate) struct OllamaEmbedder { + base_url: String, + model: String, + query_instruction: String, + client: Client, +} + +impl OllamaEmbedder { + pub(crate) fn new(config: OllamaConfig) -> Result { + let client = ClientBuilder::new() + .timeout(Duration::from_millis(config.timeout_ms)) + .build() + .context("failed to build Ollama client")?; + + Ok(Self { + base_url: normalize_base_url(&config.base_url), + model: config.model, + query_instruction: config.query_instruction, + client, + }) + } + + pub(crate) fn embed_documents(&self, texts: &[String]) -> Result>> { + let mut embeddings = Vec::new(); + for batch in texts.chunks(OLLAMA_EMBED_BATCH_SIZE) { + let payload = self.embed_batch(batch)?; + embeddings.extend(payload); + } + Ok(embeddings) + } + + pub(crate) fn embed_query(&self, query: &str) -> Result> { + let formatted = format!("Instruct: {}\nQuery: {}", self.query_instruction, query); + let mut payload = self.embed_batch(&[formatted])?; + payload + .pop() + .context("Ollama embedding backend returned no vector for query") + } + + fn embed_batch(&self, texts: &[String]) -> Result>> { + let response = self + .client + .post(format!("{}/api/embed", self.base_url)) + .json(&json!({ + "model": self.model, + "input": texts, + })) + .send() + .with_context(|| { + format!( + "failed to contact Ollama at {} using model {}", + self.base_url, self.model + ) + })?; + + if !response.status().is_success() { + let status = response.status(); + let body = response.text().unwrap_or_default(); + anyhow::bail!( + "Ollama embedding request failed with {status}: {body}. Make sure Ollama is running at {} and model {} is available", + self.base_url, + self.model + ); + } + + let payload: OllamaEmbedResponse = response.json().with_context(|| { + format!( + "failed to decode Ollama embedding response from {}", + self.base_url + ) + })?; + payload + .embeddings + .context("Ollama embedding response did not include embeddings") + } +} + +#[derive(Serialize)] +pub(crate) struct QdrantPointInput { + pub(crate) id: String, + pub(crate) vector: Vec, + pub(crate) payload: Value, +} + +#[derive(Clone, Debug, Deserialize)] +pub(crate) struct QdrantQueryPoint { + pub(crate) score: f32, + #[serde(default)] + pub(crate) payload: BTreeMap, +} + +#[derive(Debug, Deserialize)] +struct QdrantEnvelope { + result: T, +} + +#[derive(Debug, Deserialize)] +struct QdrantCollectionExistsResult { + exists: bool, +} + +#[derive(Debug, Deserialize)] +struct QdrantQueryResultEnvelope { + points: Vec, +} + +#[derive(Debug, Deserialize)] +struct OllamaEmbedResponse { + embeddings: Option>>, +} + +fn parse_qdrant_response Deserialize<'de>>( + response: reqwest::blocking::Response, +) -> Result> { + let status = response.status(); + if !status.is_success() { + let body = response.text().unwrap_or_default(); + anyhow::bail!("Qdrant request failed with {status}: {body}"); + } + response + .json() + .context("failed to decode Qdrant response JSON") +} + +pub(crate) fn normalize_base_url(input: &str) -> String { + input.trim_end_matches('/').to_string() +} + +pub(crate) fn validate_embedding_batch( + embeddings: &[Vec], + expected_count: usize, +) -> Result<()> { + if embeddings.len() != expected_count { + anyhow::bail!( + "embedding backend returned {} vectors for {} documents", + embeddings.len(), + expected_count + ); + } + + let Some(vector_length) = embeddings.first().map(Vec::len) else { + return Ok(()); + }; + if vector_length == 0 { + anyhow::bail!("embedding backend returned an empty vector"); + } + + for (index, embedding) in embeddings.iter().enumerate() { + if embedding.len() != vector_length { + anyhow::bail!("embedding backend returned inconsistent vector length at item {index}"); + } + } + + Ok(()) +} + +fn timeout_seconds(timeout_ms: u64) -> u64 { + timeout_ms.div_ceil(1000).max(1) +} + +fn env_override(primary: &str, fallback: &str) -> Option { + std::env::var(primary) + .ok() + .filter(|value| !value.trim().is_empty()) + .or_else(|| { + std::env::var(fallback) + .ok() + .filter(|value| !value.trim().is_empty()) + }) +} diff --git a/notes/epiphany-memory-graph-unified-plan.md b/notes/epiphany-memory-graph-unified-plan.md index bc97a208..6ae889ff 100644 --- a/notes/epiphany-memory-graph-unified-plan.md +++ b/notes/epiphany-memory-graph-unified-plan.md @@ -374,8 +374,14 @@ Commands should query memory graph status and context packets without Qdrant. Embed shared graph nodes, edges, and summaries. -Qdrant candidate ranking feeds context-cut planning but never emits canonical -memory payloads. +Current landing: `epiphany-core::semantic_cache` owns the shared +Qdrant/Ollama transport cache used by both workspace retrieval and memory graph +indexing. `epiphany-memory-graph index` rebuilds a Qdrant collection from typed +memory graph embedding documents and writes only the resulting +`EpiphanyMemoryEmbeddingManifest` back to the typed graph store. + +Still open: Qdrant candidate ranking should feed context-cut planning but never +emit canonical memory payloads. ### Phase 7: Sleep And Repo Refresh diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 316e8cb2..c2d40aa5 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -39,7 +39,7 @@ remembers doctrine; the branch remembers the blade. - `epiphany-openai-runtime` worker result ingress now parses assistant output directly into typed role/reorient ingress structs selected from the durable launch document, stores nested `statePatch` and `selfPatch` as typed MessagePack in `EpiphanyRuntimeRoleWorkerResult`, and no longer passes worker result data through generic `serde_json::Value`. JSON survives there only as the OpenAI text-output edge before typed deserialization. - Agent self-memory review/application now has typed `AgentSelfPatch` core APIs. JSON-value selfPatch functions are compatibility wrappers for CLI/artifact ingress; native callers should parse once at the edge and then call `review_agent_self_patch_document` / `apply_agent_self_patch_document`. Role-result self-persistence no longer exports a JSON-value reviewer; the live API is `review_role_self_patch_document`. - `epiphany-openai-codex-spine` no longer uses Codex's Responses client, model-provider layer, `codex-api`, `codex-model-provider`, `codex-model-provider-info`, or `codex-protocol` for outbound model requests. It reaches `codex-login` only through `epiphany-openai-auth-spine` so credential loading/refresh stays Codex-compatible while request/status/event/runtime surfaces stay typed Epiphany documents. -- `notes/epiphany-memory-graph-unified-plan.md` is the current memory architecture direction drawn from `Fractal Domains And The Cache That Bites` plus the VoidBot memory scar tissue. The repo semantic architecture/dataflow graph and agent memory are one `EpiphanyMemoryGraph` substrate with repo, role, short-term, incubation, agency, candidate-intervention, and evidence profiles. The first native skeleton is landed: `epiphany-state-model` owns shared graph document types, `epiphany-core::memory_graph` owns stable ids, validation, freshness, context cuts, and CultCache persistence, and `epiphany-memory-graph` can status/validate/context/smoke the store without Qdrant. Qdrant is a contribution cache for typed graph documents, not truth. `notes/repo-fractal-dataflow-cache-plan.md` and `notes/agent-memory-fractal-cache-plan.md` are profile plans, not rival organs. +- `notes/epiphany-memory-graph-unified-plan.md` is the current memory architecture direction drawn from `Fractal Domains And The Cache That Bites` plus the VoidBot memory scar tissue. The repo semantic architecture/dataflow graph and agent memory are one `EpiphanyMemoryGraph` substrate with repo, role, short-term, incubation, agency, candidate-intervention, and evidence profiles. The first native skeleton is landed: `epiphany-state-model` owns shared graph document types, `epiphany-core::memory_graph` owns stable ids, validation, freshness, context cuts, and CultCache persistence, and `epiphany-memory-graph` can status/validate/context/smoke/index the store. `epiphany-core::semantic_cache` now owns the shared Qdrant/Ollama transport used by workspace retrieval and memory graph indexing, so Qdrant remains a rebuildable contribution cache for typed graph documents, not truth. `notes/repo-fractal-dataflow-cache-plan.md` and `notes/agent-memory-fractal-cache-plan.md` are profile plans, not rival organs. - Durable Epiphany state types now live in root crate `epiphany-state-model`. `codex-protocol` re-exports them only so old rollout/API callers keep compiling; do not add new durable `Epiphany*` state structs under `vendor/codex`. `epiphany-core` imports the native model directly and no longer depends on `codex-protocol`. Pressure derives from native `EpiphanyTokenUsageSnapshot`; Codex token telemetry is mapped at the bridge. Codex rollout/event reconstruction now lives in `codex-core::epiphany_rollout`, where the Codex `RolloutItem` / `EventMsg` types belong. Exact retrieval path matching is native to `epiphany-core`, so `epiphany-core` has no direct vendored Codex crate dependency. - State-update contract proof and job launch/interrupt DTO ownership now live in native `epiphany-core`. The old giant `codex_thread.rs` Epiphany state-update test fixture was cut, and `epiphany-codex-bridge` no longer imports Epiphany job launch request types from `codex_core`; vendored `CodexThread` may call the native mutation/launch law for compatibility, but it must not regain ownership of state-update semantics, heartbeat launch-plan policy, or Epiphany DTOs. - MCP remains JSON because MCP is a JSON protocol. The latest processor cut only moved MCP refresh/OAuth/status/resource/tool-call route handling into `codex_message_processor/mcp_routes.rs`, reducing the root processor to about 8,977 lines; it did not claim MCP payloads are CultNet or make MCP an Epiphany-owned runtime contract. @@ -96,7 +96,7 @@ remembers doctrine; the branch remembers the blade. - The heartbeat initiative pass is landed as a bounded tool seam. `state/agent-heartbeats.msgpack` tracks Self, Face, Imagination, Eyes, Body, Hands, Soul, and Life as Ghostlight-style initiative participants with arena, participant kind, speed, next-ready time, reaction bias, interrupt threshold, load, status, constraints, personality cooldown, mood cooldown, effective cooldown, adaptive pacing, history, and pending turns through `epiphany-core::EpiphanyHeartbeatStateEntry` and the native `epiphany-heartbeat-store` binary. Role dossiers set baseline timing; appraisal mood/anxiety bends it through urgency, arousal, thought pressure, guardedness, and reaction intensity, so Hands-like work pressure and high-need anxious lanes recover sooner without being heartbeaten while a prior turn is running. `epiphany-heartbeat-store pump` computes pressure from external urgency, mood/anxiety, reaction intensity, thought pressure, and current pending load, then chooses tempo plus target concurrency: calm can launch zero and sleep slow; alarm can fill most active lanes. Idle turns are for rumination: light thought shuffling, role-quality attention, and candidate selfPatch pressure. Sleep/dream cycle passes are the intended distillation window for durable self-memory and doctrine. JSON heartbeat state and Python wrapper state are gone; general CultCache schema sync, polyglot domain loading, and debug display tools belong in CultLib. This is a callable scheduler seam, not yet an always-on daemon; a heart valve, not a whole circulatory god. - The first Ghostlight-derived timing slice is landed in Epiphany, but Ghostlight is reference lineage rather than a sibling runtime to preserve. `epiphany-heartbeat-store init --profile ghostlight-scene --scene-id --scene-participant ` creates a typed CultCache MessagePack scene heartbeat store whose participants are `arena=scene`, `participantKind=character`; `tick` emits `ghostlight.initiative_schedule.v0` receipts with `scene_turn` actions and local-affordance basis. The generic Epiphany maintenance lanes are not auto-patched into scene stores. - The first Void-derived routine slice is landed in Epiphany, but VoidBot is reference lineage rather than a runtime dependency. `epiphany-heartbeat-store routine --store .\state\agent-heartbeats.msgpack --artifact-dir .\.epiphany-heartbeats --agent-store .\state\agents.msgpack` reads typed role dossiers, computes bounded memory resonance, maintains incubation themes, runs analytic and associative cognition lanes, writes bridge syntheses/saturation/tension, projects the active thought cluster through each role's Ghostlight-shaped personality vectors, derives participant-local reactions, applies personality/mood timing, advances the sleep/dream cycle, updates the typed heartbeat store, and emits an auditable `epiphany.void_routine.v0` receipt. The routine now also carries anti-loop physiology imported from Void's calmer brain: `noveltyToSelf`, `noveltyToRoom`, source coverage, saturation pressure, refractory cooling, and explicit permission to let a live unsaturated thought deepen without forcing novelty theater every pass. This mutates only heartbeat physiology fields: project truth and role memory mutation remain on their reviewed surfaces. -- The next memory foundation must not build separate engines for repo graph and agent mind. Heartbeat cognition, role self-memory, repo architecture/dataflow, evidence scars, incubation, agency pressure, and context packets should converge through `EpiphanyMemoryGraph` profiles so one typed graph owns anchors, lifecycle, summaries, freshness, context cuts, and Qdrant embedding manifests. Repo, agent, and heartbeat profile producers now map accepted graph truth, reviewed role dossier memories/goals/values, and provisional heartbeat short-term/incubation/agency/candidate pressure into memory graph documents without scanner/Qdrant/model work. Heartbeat import deliberately does not mark durable promotion. Compose now merges profile snapshots into one validated graph and rejects duplicate authority; `epiphany-memory-graph compose` writes a composed typed CultCache graph from typed source graph stores; `epiphany-memory-graph refresh` can invoke live agent-memory plus heartbeat-cognition producers from their typed stores into one graph store; `epiphany-core` has a native typed `EpiphanyThreadState` CultCache store seam; the bridge mirrors loaded Codex-thread Epiphany state into `state/thread-state.msgpack`; CultNet advertises logical `EpiphanyThreadState` plus `EpiphanyMemoryGraph` snapshot contracts; memory graph nodes/edges/summaries project into deterministic typed embedding documents; and `epiphany-memory-graph manifest` writes the embedding manifest back to the typed graph store. The next clean slice is a Qdrant embedding cache writer over those documents, treating embeddings as rebuildable manifests, not canonical memory. +- The next memory foundation must not build separate engines for repo graph and agent mind. Heartbeat cognition, role self-memory, repo architecture/dataflow, evidence scars, incubation, agency pressure, and context packets should converge through `EpiphanyMemoryGraph` profiles so one typed graph owns anchors, lifecycle, summaries, freshness, context cuts, and Qdrant embedding manifests. Repo, agent, and heartbeat profile producers now map accepted graph truth, reviewed role dossier memories/goals/values, and provisional heartbeat short-term/incubation/agency/candidate pressure into memory graph documents without scanner/model work. Heartbeat import deliberately does not mark durable promotion. Compose now merges profile snapshots into one validated graph and rejects duplicate authority; `epiphany-memory-graph compose` writes a composed typed CultCache graph from typed source graph stores; `epiphany-memory-graph refresh` can invoke live agent-memory plus heartbeat-cognition producers from their typed stores into one graph store; `epiphany-core` has a native typed `EpiphanyThreadState` CultCache store seam; the bridge mirrors loaded Codex-thread Epiphany state into `state/thread-state.msgpack`; CultNet advertises logical `EpiphanyThreadState` plus `EpiphanyMemoryGraph` snapshot contracts; memory graph nodes/edges/summaries project into deterministic typed embedding documents; `epiphany-memory-graph manifest` writes the embedding manifest back to the typed graph store; and `epiphany-memory-graph index` fully rebuilds a Qdrant cache collection through the shared semantic cache transport. The next clean slice is using Qdrant candidates to accelerate context cuts while keeping typed graph traversal as the source of truth. - Manual Codex-run rumination still has an explicit aftercare rule until Epiphany owns the full sleep consolidator. In the intended Epiphany cycle, sub-agents ruminate when idle and distill when they sleep; in this supervising Codex thread, a heartbeat/routine vigil is only physiology until a separate closing pass reviews the receipts and decides whether map, handoff, evidence, or role self-memory should change. - The Face public-surface pass is landed as a bounded lane. Face's role dossier lives in `state/agents.msgpack`; `epiphany_specialists.toml` gives it a VoidBot-heartbeat-derived prompt stripped of moderation authority; `state/face-discord.toml` and the native `epiphany-face-discord` binary enforce that Face may interact only through #aquarium. Missing channel id or token writes candidate chat artifacts instead of posting elsewhere. If a Face has a persona name/avatar, `post` uses the shared Discord webhook pipe so each Epiphany can speak with its own nickname and avatar without a separate bot identity. - The Void memory bridge is now native enough to keep the useful organs attached. `state/void-memory.toml` and `epiphany-void-memory` can check Void's Docker Postgres state spine, query Qdrant Discord-history and source/lore collections with the configured Ollama embedding model, and fetch raw archive context windows from Void's file-backed Discord archive. Native `epiphany-mvp-status` includes a `voidMemory` block so Aquarium/backend clients can inspect whether the mouth and memory are actually wired. diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index a6cf422df45c8dc8dad4211333cfc4e923c82c88..d217b6024a08f02ebcc27b2e647698c87fc5bfe6 100644 GIT binary patch delta 418 zcmY+Au}T9$5QfpFc?}=LH*haWq17@w%s1aZ@6V05m&U^Z-%LLapBS6m&Ds5&v9CGf-_2@wgKzO( zw|e|xo&M*EQm7z|g|8pXge5J9QphpFnewqbIyFXQ0w@+Ccb-7l>Xq{yrLDs20c4mt zUqb3dJ_aiD2*NBu75gbDCyNX%1+Z=gqr#XHJSK%U3dCvyNM{U6(#}S%cjBJ<`#98D_W)bG0}C6jl?^F$QY??;D*!C^TXFkIeFF@gwyZLY;}~ Q$?CSn_ttyeLAQVT3-BVAR{#J2 delta 42 ycmZ2Dmt*-%jtR<4Jh>ZHr!g{SHSb|;-^0kbeGenkRj%pXd`tpt#s*d