From 8f0c9ea7239cbe950cac9aac9a5c40a8c1028e54 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 15 Jul 2026 04:00:06 +0100 Subject: [PATCH] Unify Mind and Modeling semantic projection --- docs/epiphany_body_whitepaper.tex | 8 +- epiphany-core/src/agent_memory.rs | 88 +- .../src/bin/epiphany-memory-semantic.rs | 211 +++ .../epiphany-persona-memory-recall-smoke.rs | 227 +-- .../src/bin/epiphany-repo-model-bootstrap.rs | 80 ++ epiphany-core/src/heartbeat_state.rs | 83 +- epiphany-core/src/lib.rs | 35 +- epiphany-core/src/memory_graph/context_cut.rs | 223 ++- epiphany-core/src/memory_graph/mod.rs | 6 + .../src/memory_graph/profiles/repo.rs | 41 +- .../src/memory_graph/semantic_index.rs | 516 +++++++ .../src/memory_graph/semantic_projection.rs | 775 ++++++++++ epiphany-core/src/memory_graph/tests.rs | 6 +- epiphany-core/src/persona_memory_cache.rs | 1270 ----------------- epiphany-core/src/retrieval.rs | 613 +++----- epiphany-core/src/semantic_backend.rs | 456 ++++++ notes/epiphany-memory-graph-unified-plan.md | 8 + notes/fresh-workspace-handoff.md | 36 + ...graph-semantic-projection-authority-map.md | 182 +++ state/agents.msgpack | Bin 15751 -> 15702 bytes state/ledgers.msgpack | Bin 493747 -> 494436 bytes state/map.yaml | 2 +- state/memory-graph.msgpack | 1 - 23 files changed, 2903 insertions(+), 1964 deletions(-) create mode 100644 epiphany-core/src/bin/epiphany-memory-semantic.rs create mode 100644 epiphany-core/src/bin/epiphany-repo-model-bootstrap.rs create mode 100644 epiphany-core/src/memory_graph/semantic_index.rs create mode 100644 epiphany-core/src/memory_graph/semantic_projection.rs delete mode 100644 epiphany-core/src/persona_memory_cache.rs create mode 100644 epiphany-core/src/semantic_backend.rs create mode 100644 notes/memory-graph-semantic-projection-authority-map.md delete mode 100644 state/memory-graph.msgpack diff --git a/docs/epiphany_body_whitepaper.tex b/docs/epiphany_body_whitepaper.tex index 63923aec..260ea6a8 100644 --- a/docs/epiphany_body_whitepaper.tex +++ b/docs/epiphany_body_whitepaper.tex @@ -134,10 +134,10 @@ implementation, not file authority. \code{state/ledgers.cc} & CultCache-shaped evidence and branch ledger. Future behavior-changing lessons go here, not in an endless activity feed. \\ \code{state/agents.cc} & Organ self-memory and Persona projection source. Resident work organs use \code{work_organ}; public/person-shaped agents use \code{persona}. \\ \code{state/agent-heartbeats.cc} & Heartbeat initiative, cooldown, pending turns, cognition lanes, routine physiology, and scheduler pressure. \\ -\code{state/runtime-spine.cc} & Runtime identity, sessions, jobs, job results, events, worker launch requests, role/reorient findings, receipts, model/tool documents, and schema catalog surfaces. \\ +\code{state/runtime-spine.cc} & Runtime identity, sessions, jobs, job results, events, worker launch requests, role/reorient findings, receipts, model/tool documents, the admitted RepoModel, and schema catalog surfaces. \\ \code{state/thread-state.cc} & Native thread-state store. \\ \code{state/local-verse.cc} & Local CultMesh Verse context for compact operator and prompt-context packets. \\ -\code{state/memory-graph.cc} & Local memory graph store. \\ +\code{state/semantic-projection.cc} & Typed Qdrant projection receipts. Cache health lives here, outside the canonical RepoModel. \\ \code{state/persona-discord.toml} & Persona Discord boundary configuration. \\ \code{state/void-memory.toml} & Void memory bridge configuration. \\ \code{state/scratch.md} and \code{state/scratch-compaction-*.md} & Scratch surfaces. Scratch is a workbench, not canonical memory. \\ @@ -145,7 +145,9 @@ implementation, not file authority. Lock files sit beside several stores. Some local generated state is currently untracked, including \code{state/local-verse.cc}, -\code{state/memory-graph.cc}, and \code{.epiphany-character-loop/}. +\code{state/semantic-projection.cc}, and \code{.epiphany-character-loop/}. +The former sibling \code{state/memory-graph.cc}/\code{.msgpack} store is a +retired migration wound; live Modeling truth is the runtime-spine RepoModel. \section{CultNet Schema Body} diff --git a/epiphany-core/src/agent_memory.rs b/epiphany-core/src/agent_memory.rs index 5ed0d431..8431a80d 100644 --- a/epiphany-core/src/agent_memory.rs +++ b/epiphany-core/src/agent_memory.rs @@ -21,6 +21,18 @@ pub const AGENT_STATE_SOA_TYPE: &str = "epiphany.agent_state_soa"; pub const AGENT_STATE_SOA_SCHEMA_VERSION: &str = "epiphany.agent_state_soa.v0"; pub const AGENT_STATE_SOA_KEY: &str = "swarm"; +pub fn swarm_identity_from_agent_memories(entries: &[EpiphanyAgentMemoryEntry]) -> String { + let mut identities = entries + .iter() + .map(|entry| format!("{}:{}", entry.role_id, entry.agent.agent_id)) + .collect::>(); + identities.sort(); + format!( + "swarm-{}", + uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, identities.join("\n").as_bytes(),) + ) +} + const ROLE_TARGETS: &[(&str, &str, &str)] = &[ ( "imagination", @@ -627,6 +639,36 @@ pub fn repair_agent_memory_store(store_path: impl AsRef) -> Result })); } + if let Some(mut modeling) = cache.get::("modeling")? { + let mut renamed = 0usize; + renamed += replace_deprecated_faculty_name(&mut modeling.agent.identity.public_description); + for note in &mut modeling.agent.identity.private_notes { + renamed += replace_deprecated_faculty_name(note); + } + for goal in &mut modeling.agent.goals { + renamed += replace_deprecated_faculty_name(&mut goal.description); + renamed += replace_deprecated_faculty_name(&mut goal.emotional_stake); + } + for memory in modeling + .agent + .memories + .semantic + .iter_mut() + .chain(modeling.agent.memories.episodic.iter_mut()) + .chain(modeling.agent.memories.relationship_summaries.iter_mut()) + { + renamed += replace_deprecated_faculty_name(&mut memory.summary); + } + if renamed > 0 { + cache.put("modeling".to_string(), &modeling)?; + repaired.push(serde_json::json!({ + "roleId": "modeling", + "repair": "replaced deprecated Proprioception prose with canonical Modeling doctrine", + "replacements": renamed, + })); + } + } + if cache.get::("Persona")?.is_none() && let Some(mut face) = cache.get::("face")? { @@ -688,6 +730,14 @@ pub fn repair_agent_memory_store(store_path: impl AsRef) -> Result })) } +fn replace_deprecated_faculty_name(value: &mut String) -> usize { + let count = value.matches("Proprioception").count(); + if count > 0 { + *value = value.replace("Proprioception", "Modeling"); + } + count +} + pub fn load_agent_memory_entry_for_role( store_path: impl AsRef, role_id: &str, @@ -2801,7 +2851,21 @@ mod tests { } else { agent_id }; - let entry = entry_from_projection(role_id, expected_agent_id, projection)?; + let mut entry = entry_from_projection(role_id, expected_agent_id, projection)?; + if *role_id == "modeling" { + entry.agent.identity.public_description = + "Proprioception models source-grounded anatomy.".to_string(); + entry.agent.goals[0].emotional_stake = + "If Proprioception lies, Hands cuts blind.".to_string(); + entry.agent.memories.semantic.push(GhostlightMemory { + memory_id: "legacy-proprioception-prose".to_string(), + summary: "Proprioception leaves a verified trail.".to_string(), + salience: 0.8, + confidence: 0.8, + linked_event_ids: None, + linked_relationship_id: None, + }); + } cache.put((*role_id).to_string(), &entry)?; } let raw = fs::read_to_string(agent_dir.join("face.agent-state.json"))?; @@ -2831,6 +2895,28 @@ mod tests { cache.pull_all_backing_stores()?; let modeling = cache.get_required::("modeling")?; assert_eq!(modeling.agent.agent_id, "epiphany.modeling"); + assert!( + !modeling + .agent + .identity + .public_description + .contains("Proprioception") + ); + assert!( + modeling + .agent + .goals + .iter() + .all(|goal| !goal.emotional_stake.contains("Proprioception")) + ); + assert!( + modeling + .agent + .memories + .semantic + .iter() + .all(|memory| { !memory.summary.contains("Proprioception") }) + ); let persona = cache.get_required::("Persona")?; assert_eq!(persona.role_id, "Persona"); assert_eq!(persona.agent.agent_id, "epiphany.Persona"); diff --git a/epiphany-core/src/bin/epiphany-memory-semantic.rs b/epiphany-core/src/bin/epiphany-memory-semantic.rs new file mode 100644 index 00000000..a965aa80 --- /dev/null +++ b/epiphany-core/src/bin/epiphany-memory-semantic.rs @@ -0,0 +1,211 @@ +use anyhow::{Context, Result, anyhow}; +use chrono::{SecondsFormat, Utc}; +use epiphany_core::{ + EpiphanyMemoryContextQuery, EpiphanyMemoryGraphSnapshot, MemorySemanticIndexConfig, + SemanticPartition, agent_memory_role_ids, index_memory_semantic_partition, + load_agent_memory_entry_for_role, load_memory_graph_snapshot, memory_graph_from_agent_memories, + persist_memory_semantic_index_receipt, runtime_current_repo_model, semantic_memory_context, +}; +use std::env; +use std::path::PathBuf; + +fn main() -> Result<()> { + let mut args = env::args().skip(1); + let command = args.next().ok_or_else(|| usage_error("missing command"))?; + let options = Options::parse(args)?; + let snapshot = options.load_snapshot()?; + let config = MemorySemanticIndexConfig::from_env(); + match command.as_str() { + "index" => { + let receipt_store = options + .receipt_store + .as_ref() + .ok_or_else(|| usage_error("index requires --receipt-store "))?; + let receipt = index_memory_semantic_partition( + &snapshot, + &options.swarm_id, + options.partition, + &Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true), + &config, + )?; + persist_memory_semantic_index_receipt(receipt_store, &receipt)?; + print_json(&serde_json::json!({ + "status": receipt.status, + "receiptId": receipt.receipt_id, + "receiptStore": receipt_store, + "swarmId": receipt.swarm_id, + "partition": receipt.partition, + "collectionName": receipt.collection_name, + "graphId": receipt.graph_id, + "modelRevision": receipt.model_revision, + "modelHash": receipt.model_hash, + "embeddingProviderId": receipt.embedding_provider_id, + "embeddingModel": receipt.embedding_model, + "vectorDimensions": receipt.vector_dimensions, + "indexedDocumentCount": receipt.indexed_document_count, + "deletedDocumentCount": receipt.deleted_document_count, + "canonicalContentSetHash": receipt.canonical_content_set_hash, + "indexedAt": receipt.indexed_at, + }))?; + } + "context" => { + let text = options + .text + .clone() + .ok_or_else(|| usage_error("context requires --text "))?; + let packet = semantic_memory_context( + &snapshot, + &options.swarm_id, + options.partition, + &EpiphanyMemoryContextQuery { + id: options + .query_id + .clone() + .unwrap_or_else(|| "memory-semantic-context".to_string()), + profile: options.profile, + text: Some(text), + budget: options.budget, + ..Default::default() + }, + &config, + ); + print_json(&packet)?; + } + _ => return Err(usage_error(&format!("unknown command {command:?}"))), + } + Ok(()) +} + +struct Options { + graph_store: Option, + runtime_store: Option, + agent_store: Option, + receipt_store: Option, + swarm_id: String, + partition: SemanticPartition, + text: Option, + query_id: Option, + budget: Option, + profile: Option, +} + +impl Options { + fn parse(args: impl Iterator) -> Result { + let mut options = Self { + graph_store: None, + runtime_store: None, + agent_store: None, + receipt_store: None, + swarm_id: String::new(), + partition: SemanticPartition::Modeling, + text: None, + query_id: None, + budget: None, + profile: None, + }; + let mut args = args.peekable(); + while let Some(flag) = args.next() { + let mut value = || { + args.next() + .with_context(|| format!("missing value for {flag}")) + }; + match flag.as_str() { + "--graph-store" => options.graph_store = Some(PathBuf::from(value()?)), + "--runtime-store" => options.runtime_store = Some(PathBuf::from(value()?)), + "--agent-store" => options.agent_store = Some(PathBuf::from(value()?)), + "--receipt-store" => options.receipt_store = Some(PathBuf::from(value()?)), + "--swarm-id" => options.swarm_id = value()?, + "--partition" => options.partition = parse_partition(&value()?)?, + "--text" => options.text = Some(value()?), + "--query-id" => options.query_id = Some(value()?), + "--budget" => options.budget = Some(value()?.parse().context("invalid budget")?), + "--profile" => options.profile = Some(parse_profile(&value()?)?), + _ => return Err(usage_error(&format!("unexpected argument {flag:?}"))), + } + } + if options.swarm_id.trim().is_empty() { + return Err(usage_error("--swarm-id is required")); + } + let sources = [ + options.graph_store.is_some(), + options.runtime_store.is_some(), + options.agent_store.is_some(), + ] + .into_iter() + .filter(|present| *present) + .count(); + if sources != 1 { + return Err(usage_error( + "provide exactly one --graph-store, --runtime-store, or --agent-store", + )); + } + if options.partition == SemanticPartition::Mind && options.runtime_store.is_some() { + return Err(usage_error( + "Mind projection requires --agent-store or an explicitly composed --graph-store", + )); + } + if options.partition == SemanticPartition::Modeling && options.agent_store.is_some() { + return Err(usage_error( + "Modeling projection requires --runtime-store or --graph-store", + )); + } + Ok(options) + } + + fn load_snapshot(&self) -> Result { + if let Some(path) = &self.runtime_store { + return runtime_current_repo_model(path)? + .ok_or_else(|| anyhow!("runtime store has no admitted RepoModel")); + } + if let Some(path) = &self.agent_store { + let mut entries = Vec::new(); + for role in agent_memory_role_ids() { + if let Some(entry) = load_agent_memory_entry_for_role(path, role)? { + entries.push(entry); + } + } + if entries.is_empty() { + return Err(anyhow!("agent store has no admitted organ memory")); + } + let derived_swarm_id = epiphany_core::swarm_identity_from_agent_memories(&entries); + if self.swarm_id != derived_swarm_id { + return Err(anyhow!( + "--swarm-id {:?} does not match the canonical agent-store swarm identity {:?}", + self.swarm_id, + derived_swarm_id + )); + } + return Ok(memory_graph_from_agent_memories( + format!("{derived_swarm_id}-mind"), + &entries, + )); + } + let path = self.graph_store.as_ref().expect("validated graph store"); + load_memory_graph_snapshot(path)? + .ok_or_else(|| anyhow!("memory graph store {} is missing", path.display())) + } +} + +fn parse_partition(value: &str) -> Result { + match value { + "mind" => Ok(SemanticPartition::Mind), + "modeling" => Ok(SemanticPartition::Modeling), + _ => Err(usage_error("partition must be mind or modeling")), + } +} + +fn parse_profile(value: &str) -> Result { + serde_json::from_str(&format!("\"{value}\"")) + .with_context(|| format!("unknown memory profile {value:?}")) +} + +fn usage_error(message: &str) -> anyhow::Error { + anyhow!( + "{message}\nusage: epiphany-memory-semantic (--runtime-store |--agent-store |--graph-store ) --swarm-id --partition [--receipt-store ] [--text ] [--query-id ] [--budget ] [--profile ]" + ) +} + +fn print_json(value: &impl serde::Serialize) -> Result<()> { + println!("{}", serde_json::to_string_pretty(value)?); + Ok(()) +} diff --git a/epiphany-core/src/bin/epiphany-persona-memory-recall-smoke.rs b/epiphany-core/src/bin/epiphany-persona-memory-recall-smoke.rs index 8ef344a5..bf94b951 100644 --- a/epiphany-core/src/bin/epiphany-persona-memory-recall-smoke.rs +++ b/epiphany-core/src/bin/epiphany-persona-memory-recall-smoke.rs @@ -1,32 +1,14 @@ -use epiphany_core::EpiphanyAgentMemoryEntry; -use epiphany_core::GhostlightAgent; -use epiphany_core::GhostlightCanonicalState; -use epiphany_core::GhostlightIdentity; -use epiphany_core::GhostlightMemories; -use epiphany_core::GhostlightMemory; -use epiphany_core::GhostlightValue; -use epiphany_core::GhostlightWorld; -use epiphany_core::PersonaIdentity; -use epiphany_core::PersonaInterpreterInput; -use epiphany_core::PersonaMemoryCacheConfig; -use epiphany_core::PersonaProjectorInput; -use epiphany_core::PersonaTurnInput; -use epiphany_core::build_persona_interpreter_prompt; -use epiphany_core::build_persona_memory_chunks; -use epiphany_core::build_persona_projector_prompt; -use epiphany_core::build_persona_turn_prompt; -use epiphany_core::render_dynamic_persona_memory_recall_for_output; -use epiphany_core::render_persona_memory_recall_with_cache; -use epiphany_core::render_persona_semantic_memory_recall; -use epiphany_core::semantic_memory_recall_from_heartbeat_action; -use epiphany_state_model::EpiphanyMemoryContextPacket; -use epiphany_state_model::EpiphanyMemoryFreshnessStatus; -use epiphany_state_model::EpiphanyMemoryNode; -use epiphany_state_model::EpiphanyMemorySummary; +use epiphany_core::{ + EpiphanyMemoryContextPacket, EpiphanyMemoryFreshnessStatus, EpiphanyMemoryNode, + EpiphanyMemorySummary, PersonaIdentity, PersonaInterpreterInput, PersonaProjectorInput, + PersonaTurnInput, build_persona_interpreter_prompt, build_persona_projector_prompt, + build_persona_turn_prompt, render_persona_semantic_memory_recall, + semantic_memory_recall_from_heartbeat_action, +}; use serde_json::json; fn main() { - let fallback_recall = render_persona_semantic_memory_recall(&EpiphanyMemoryContextPacket { + let packet = EpiphanyMemoryContextPacket { id: "memctx-persona-smoke".to_string(), query_id: "persona-smoke-current-turn".to_string(), summaries: vec![EpiphanyMemorySummary { @@ -34,92 +16,42 @@ fn main() { target: "role:Persona".to_string(), claim: "Persona remembers that public speech is a reviewed mouth edge, not raw side effect authority." .to_string(), - action_implication: "Shape the public voice, then let Mind and the mouth edge route effects." - .to_string(), + action_implication: + "Shape the public voice, then let Mind and the mouth edge route effects." + .to_string(), freshness: EpiphanyMemoryFreshnessStatus::Ready, confidence: 84, ..Default::default() }], nodes: vec![EpiphanyMemoryNode { - id: "node-persona-qdrant-pressure".to_string(), - title: "Persona memory retrieval pressure".to_string(), - claim: "VoidBot rebuilds semantic Persona recall from typed memory before each Face turn." + id: "node-persona-shared-mind".to_string(), + title: "Shared Mind semantic projection".to_string(), + claim: "Persona recall resolves canonical Mind graph documents after semantic ranking; Qdrant payload text never speaks into the prompt." .to_string(), action_implication: - "Epiphany Persona prompts must receive derived memory recall as hints before speech." + "Use the canonical packet as a hint and leave durable state with Mind." .to_string(), ..Default::default() }], + warnings: vec![ + "semantic projection ranked canonical Mind candidates; payload text was ignored" + .to_string(), + ], ..Default::default() - }); + }; + let rendered = render_persona_semantic_memory_recall(&packet); + assert_contains(&rendered, "Shared Mind semantic projection"); + assert_contains(&rendered, "payload text was ignored"); - let chunks = - build_persona_memory_chunks(&persona_memory_entry(), "state/agents.msgpack#Persona"); - assert!( - chunks - .iter() - .any(|chunk| chunk.text.contains("public typed-contract zeal")) - ); - assert!( - chunks - .iter() - .all(|chunk| !chunk.text.contains("sealed private note")) - ); - let bridge = render_persona_memory_recall_with_cache( - &persona_memory_entry(), - "state/agents.msgpack#Persona", - "typed-contract zeal before public speech", - 4, - Some(&EpiphanyMemoryContextPacket { - id: "memctx-smoke-fallback".to_string(), - query_id: "persona-smoke-fallback".to_string(), - summaries: vec![EpiphanyMemorySummary { - id: "summary-smoke-fallback".to_string(), - target: "role:Persona".to_string(), - claim: fallback_recall, - action_implication: - "This fallback is heartbeat-carried context, not direct state authority." - .to_string(), - freshness: EpiphanyMemoryFreshnessStatus::Ready, - confidence: 80, - ..Default::default() - }], - nodes: vec![EpiphanyMemoryNode { - id: "node-smoke-fallback".to_string(), - title: "Smoke fallback memory".to_string(), - claim: "Fallback typed memory graph context remains available.".to_string(), - action_implication: "Do not pretend live Qdrant was required for this smoke." - .to_string(), - ..Default::default() - }], - ..Default::default() - }), - &PersonaMemoryCacheConfig { - qdrant_url: "http://127.0.0.1:1".to_string(), - qdrant_api_key: None, - qdrant_timeout_ms: 1, - ollama_base_url: "http://127.0.0.1:1".to_string(), - ollama_model: "qwen3-embedding:0.6b".to_string(), - ollama_timeout_ms: 1, - collection_name: "epiphany_persona_memory_smoke".to_string(), - query_instruction: "smoke".to_string(), - }, - ); - assert_eq!(bridge.status, "fallback"); - assert!( - bridge - .rendered_recall - .contains("Fallback typed memory graph context") - ); let heartbeat_action = json!({ "action_type": "persona_turn", "persona_memory_recall": { "privateStateExposed": false, - "renderedRecall": bridge.rendered_recall, + "renderedRecall": rendered, } }); let recall = semantic_memory_recall_from_heartbeat_action(&heartbeat_action); - assert_contains(&recall, "Fallback typed memory graph context"); + assert_contains(&recall, "canonical Mind graph documents"); let identity = PersonaIdentity { identity_id: "epiphany".to_string(), @@ -128,84 +60,33 @@ fn main() { public_description: "Repo Persona for typed agent substrate.".to_string(), jurisdiction: vec!["typed state and review-gated agency".to_string()], }; - let projector_prompt = build_persona_projector_prompt(&PersonaProjectorInput { identity: identity.clone(), semantic_memory_recall: recall.clone(), ..Default::default() }); - assert_contains(&projector_prompt, "Semantic memory recall"); - assert_contains(&projector_prompt, "typed memory graph"); - assert_contains(&projector_prompt, "not durable authority"); - let persona_prompt = build_persona_turn_prompt(&PersonaTurnInput { identity: identity.clone(), - projected_state: "Epiphany feels the mouth edge as a public contract, not a vent." - .to_string(), + projected_state: "The public mouth remains receipt-bound.".to_string(), semantic_memory_recall: recall.clone(), ..Default::default() }); - assert_contains(&persona_prompt, "Semantic memory recall"); - assert_contains(&persona_prompt, "Fallback typed memory graph context"); - - let persona_output = "I can speak, but the effect needs a receipt."; - let dynamic = render_dynamic_persona_memory_recall_for_output( - &persona_memory_entry(), - "state/agents.msgpack#Persona", - &persona_prompt, - persona_output, - &recall, - 4, - Some(&EpiphanyMemoryContextPacket { - id: "memctx-smoke-dynamic-fallback".to_string(), - query_id: "persona-smoke-dynamic-output".to_string(), - summaries: vec![EpiphanyMemorySummary { - id: "summary-smoke-dynamic-fallback".to_string(), - target: "role:Persona".to_string(), - claim: "Dynamic self-memory recall should inspect the Persona output before Mind interprets side effects." - .to_string(), - action_implication: - "Interpreter should see output-triggered recall, not only the pre-turn prompt recall." - .to_string(), - freshness: EpiphanyMemoryFreshnessStatus::Ready, - confidence: 82, - ..Default::default() - }], - ..Default::default() - }), - &PersonaMemoryCacheConfig { - qdrant_url: "http://127.0.0.1:1".to_string(), - qdrant_api_key: None, - qdrant_timeout_ms: 1, - ollama_base_url: "http://127.0.0.1:1".to_string(), - ollama_model: "qwen3-embedding:0.6b".to_string(), - ollama_timeout_ms: 1, - collection_name: "epiphany_persona_memory_dynamic_smoke".to_string(), - query_instruction: "dynamic-smoke".to_string(), - }, - ); - assert_eq!(dynamic.status, "fallback"); - assert_contains( - &dynamic.rendered_recall, - "Dynamic self-memory recall should inspect the Persona output", - ); - + let persona_output = "I can speak, but consequence still needs a receipt."; let interpreter_prompt = build_persona_interpreter_prompt(&PersonaInterpreterInput { identity, - persona_prompt, + persona_prompt: persona_prompt.clone(), persona_output: persona_output.to_string(), - semantic_memory_recall: recall, - dynamic_semantic_memory_recall: dynamic.rendered_recall, + semantic_memory_recall: recall.clone(), + dynamic_semantic_memory_recall: recall, pending_mentions: Vec::new(), allowed_channel_ids: vec!["aquarium".to_string()], }); + assert_contains(&projector_prompt, "Semantic memory recall"); + assert_contains(&persona_prompt, "canonical Mind graph documents"); assert_contains(&interpreter_prompt, "Dynamic self-memory recall"); - assert_contains(&interpreter_prompt, "output-triggered recall"); - assert_contains(&interpreter_prompt, "STATE NOTE"); - assert_contains(&interpreter_prompt, "SAY"); println!( - "status=ok recallSource=typed-memory-graph qdrantCache=persona-memory-bridge-wired heartbeatRecall=prompt-wired dynamicRecall=interpreter-output-wired liveQdrant=not-required personaLayers=projector,persona,interpreter privateStateExposed=false" + "status=ok recallSource=shared-mind-memory-graph qdrantPayloadAuthority=false canonicalReload=true heartbeatRecall=prompt-wired privateStateExposed=false" ); } @@ -215,45 +96,3 @@ fn assert_contains(haystack: &str, needle: &str) { "expected prompt to contain `{needle}`" ); } - -fn persona_memory_entry() -> EpiphanyAgentMemoryEntry { - EpiphanyAgentMemoryEntry { - schema_version: "ghostlight.agent_state.v0".to_string(), - role_id: "Persona".to_string(), - world: GhostlightWorld::default(), - agent: GhostlightAgent { - agent_id: "epiphany.Persona".to_string(), - identity: GhostlightIdentity { - name: "Epiphany".to_string(), - roles: vec!["Persona".to_string()], - origin: "EpiphanyAgent".to_string(), - public_description: "public typed-contract zeal".to_string(), - private_notes: vec!["sealed private note".to_string()], - }, - memories: GhostlightMemories { - semantic: vec![GhostlightMemory { - memory_id: "semantic-1".to_string(), - summary: "Persona recall should be semantically available before speech." - .to_string(), - salience: 0.9, - confidence: 0.9, - ..Default::default() - }], - ..Default::default() - }, - canonical_state: GhostlightCanonicalState { - values: vec![GhostlightValue { - value_id: "value-1".to_string(), - label: "Keep memory recall typed and sealed.".to_string(), - priority: 0.9, - unforgivable_if_betrayed: true, - }], - ..Default::default() - }, - ..Default::default() - }, - relationships: Vec::new(), - events: Vec::new(), - scenes: Vec::new(), - } -} diff --git a/epiphany-core/src/bin/epiphany-repo-model-bootstrap.rs b/epiphany-core/src/bin/epiphany-repo-model-bootstrap.rs new file mode 100644 index 00000000..7c779189 --- /dev/null +++ b/epiphany-core/src/bin/epiphany-repo-model-bootstrap.rs @@ -0,0 +1,80 @@ +use anyhow::{Context, Result, anyhow}; +use chrono::{SecondsFormat, Utc}; +use epiphany_core::{ + ensure_runtime_repo_model, load_thread_state, memory_graph_from_epiphany_graphs, +}; +use std::env; +use std::path::{Path, PathBuf}; + +fn main() -> Result<()> { + let mut args = env::args().skip(1); + let runtime_store = required_path(&mut args, "--runtime-store")?; + let thread_state_store = required_path(&mut args, "--thread-state-store")?; + if args.next().is_some() { + return Err(usage("unexpected trailing arguments")); + } + let state = load_thread_state(&thread_state_store)?.ok_or_else(|| { + anyhow!( + "thread-state store {} is missing canonical state", + thread_state_store.display() + ) + })?; + let repo_root = thread_state_store + .parent() + .and_then(Path::parent) + .unwrap_or_else(|| Path::new(".")); + let source_identity = thread_state_store + .canonicalize() + .unwrap_or_else(|_| thread_state_store.clone()) + .to_string_lossy() + .into_owned(); + let bootstrap = memory_graph_from_epiphany_graphs( + format!("repo-model-bootstrap-rev-{}", state.revision), + &state.graphs, + source_identity, + state.revision, + repo_root, + )?; + // The runtime-spine owner performs the one-time atomic admission and + // migration receipt. A deliberately absent legacy path prevents a stale + // sibling graph from impersonating the typed thread-state bootstrap. + let absent_legacy = runtime_store.with_extension("no-legacy-memory-graph"); + let (snapshot, receipt) = ensure_runtime_repo_model( + &runtime_store, + absent_legacy, + &bootstrap, + &Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true), + )?; + println!( + "{}", + serde_json::to_string_pretty(&serde_json::json!({ + "status": "ready", + "runtimeStore": runtime_store, + "threadStateStore": thread_state_store, + "graphId": snapshot.graph_id, + "modelRevision": snapshot.model_revision, + "modelHash": snapshot.model_hash, + "migrationReceiptId": receipt.receipt_id, + "migrationSource": receipt.source_store, + }))? + ); + Ok(()) +} + +fn required_path(args: &mut impl Iterator, flag: &str) -> Result { + let actual = args + .next() + .ok_or_else(|| usage(&format!("missing {flag}")))?; + if actual != flag { + return Err(usage(&format!("expected {flag}, got {actual:?}"))); + } + args.next() + .map(PathBuf::from) + .with_context(|| format!("missing value for {flag}")) +} + +fn usage(message: &str) -> anyhow::Error { + anyhow!( + "{message}\nusage: epiphany-repo-model-bootstrap --runtime-store --thread-state-store " + ) +} diff --git a/epiphany-core/src/heartbeat_state.rs b/epiphany-core/src/heartbeat_state.rs index 6d791efa..e5379fdf 100644 --- a/epiphany-core/src/heartbeat_state.rs +++ b/epiphany-core/src/heartbeat_state.rs @@ -1104,7 +1104,7 @@ fn persona_memory_recall_for_scheduled_turn( } let Some(agent_store) = agent_store else { return serde_json::json!({ - "schemaVersion": crate::PERSONA_MEMORY_CACHE_SCHEMA_VERSION, + "schemaVersion": crate::SEMANTIC_PROJECTION_SCHEMA_VERSION, "status": "unavailable", "cacheStatus": "agent-store-missing", "renderedRecall": "- semantic Persona memory recall unavailable: no agent store was provided for this heartbeat tick", @@ -1117,7 +1117,7 @@ fn persona_memory_recall_for_scheduled_turn( Ok(Some(entry)) => entry, Ok(None) => { return serde_json::json!({ - "schemaVersion": crate::PERSONA_MEMORY_CACHE_SCHEMA_VERSION, + "schemaVersion": crate::SEMANTIC_PROJECTION_SCHEMA_VERSION, "status": "unavailable", "cacheStatus": "persona-memory-missing", "renderedRecall": "- semantic Persona memory recall unavailable: Persona memory entry is missing", @@ -1126,7 +1126,7 @@ fn persona_memory_recall_for_scheduled_turn( } Err(error) => { return serde_json::json!({ - "schemaVersion": crate::PERSONA_MEMORY_CACHE_SCHEMA_VERSION, + "schemaVersion": crate::SEMANTIC_PROJECTION_SCHEMA_VERSION, "status": "unavailable", "cacheStatus": "persona-memory-load-failed", "renderedRecall": format!("- semantic Persona memory recall unavailable: {}", compact_heartbeat_line(&format!("{error:#}"), 320)), @@ -1136,43 +1136,50 @@ fn persona_memory_recall_for_scheduled_turn( }; let query = persona_memory_recall_query(selected, pending_mentions); - let graph = crate::memory_graph_from_agent_memories( - "heartbeat-persona-memory", - std::slice::from_ref(&entry), - ); - let fallback = crate::plan_memory_graph_context_cut( + let mut entries = Vec::new(); + for role in crate::agent_memory_role_ids() { + if let Ok(Some(role_entry)) = crate::load_agent_memory_entry_for_role(agent_store, role) { + entries.push(role_entry); + } + } + let swarm_id = crate::swarm_identity_from_agent_memories(&entries); + let graph = crate::memory_graph_from_agent_memories(&format!("{swarm_id}-mind"), &entries); + let persona_domain_id = + crate::memory_graph_domain_id(crate::EpiphanyMemoryProfile::RoleSelf, "role", "Persona"); + let query_document = EpiphanyMemoryContextQuery { + id: "heartbeat-persona-turn".to_string(), + profile: Some(crate::EpiphanyMemoryProfile::RoleSelf), + domain_ids: vec![persona_domain_id], + node_ids: Vec::new(), + edge_ids: Vec::new(), + text: Some(query.clone()), + budget: Some(8), + }; + let config = memory_semantic_config_for_heartbeat(); + let packet = crate::semantic_memory_context( &graph, - &EpiphanyMemoryContextQuery { - id: "heartbeat-persona-turn".to_string(), - profile: Some(crate::EpiphanyMemoryProfile::RoleSelf), - domain_ids: Vec::new(), - node_ids: Vec::new(), - edge_ids: Vec::new(), - text: Some(query.clone()), - budget: Some(8), - }, - ); - let config = persona_memory_cache_config_for_heartbeat(); - let recall = crate::render_persona_memory_recall_with_cache( - &entry, - format!("{}#Persona", agent_store.display()), - &query, - 8, - Some(&fallback), + &swarm_id, + crate::SemanticPartition::Mind, + &query_document, &config, ); + let fallback = packet + .warnings + .iter() + .any(|warning| warning.contains("canonical BM25 fallback")); + let rendered_recall = crate::render_persona_semantic_memory_recall(&packet); serde_json::json!({ - "schemaVersion": recall.schema_version, - "status": recall.status, - "cacheStatus": recall.cache_status, - "identityId": recall.identity_id, - "roleId": recall.role_id, - "chunkCount": recall.chunk_count, - "hitCount": recall.hit_count, - "renderedRecall": recall.rendered_recall, - "warnings": recall.warnings, - "privateStateExposed": recall.private_state_exposed, + "schemaVersion": crate::SEMANTIC_PROJECTION_SCHEMA_VERSION, + "status": if fallback { "fallback" } else { "ready" }, + "cacheStatus": if fallback { "canonical-bm25" } else { "shared-mind-qdrant" }, + "identityId": entry.agent.agent_id, + "roleId": entry.role_id, + "chunkCount": graph.nodes.len() + graph.summaries.len(), + "hitCount": packet.nodes.len() + packet.summaries.len(), + "renderedRecall": rendered_recall, + "warnings": packet.warnings, + "privateStateExposed": false, }) } @@ -1202,8 +1209,8 @@ fn persona_memory_recall_query( ) } -fn persona_memory_cache_config_for_heartbeat() -> crate::PersonaMemoryCacheConfig { - let mut config = crate::PersonaMemoryCacheConfig::from_env(); +fn memory_semantic_config_for_heartbeat() -> crate::MemorySemanticIndexConfig { + let mut config = crate::MemorySemanticIndexConfig::from_env(); config.qdrant_timeout_ms = config.qdrant_timeout_ms.min(1_000); config.ollama_timeout_ms = config.ollama_timeout_ms.min(1_000); config @@ -3874,7 +3881,7 @@ mod tests { let recall = &tick["schedule"]["action_catalog"][0]["persona_memory_recall"]; assert_eq!( recall["schemaVersion"], - crate::PERSONA_MEMORY_CACHE_SCHEMA_VERSION + crate::SEMANTIC_PROJECTION_SCHEMA_VERSION ); assert_eq!(recall["roleId"], "Persona"); assert_eq!(recall["privateStateExposed"], false); diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index f728303d..b1ec9ea4 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -18,7 +18,6 @@ mod heartbeat_state; mod memory_graph; mod mind_gateway; mod organ_dependencies; -mod persona_memory_cache; mod persona_turn; mod process_observation; mod promotion; @@ -27,6 +26,7 @@ mod proposal; mod repo_model_gateway; mod retrieval; mod runtime_spine; +mod semantic_backend; mod soul_gateway; mod state_ledger; mod state_update; @@ -116,6 +116,7 @@ pub use agent_memory::repair_agent_memory_store; pub use agent_memory::review_agent_memory_lifecycle_operation; pub use agent_memory::review_agent_self_patch; pub use agent_memory::review_agent_self_patch_document; +pub use agent_memory::swarm_identity_from_agent_memories; pub use agent_memory::validate_agent_memory_store; pub use agent_memory::write_agent_memory_entry_for_role; pub use agent_utterance_state::AGENT_CHARACTER_STATE_VECTOR_SIZE; @@ -618,6 +619,9 @@ pub use memory_graph::EpiphanyMemoryPatchCandidate; pub use memory_graph::MEMORY_GRAPH_KEY; pub use memory_graph::MEMORY_GRAPH_SCHEMA_VERSION; pub use memory_graph::MEMORY_GRAPH_TYPE; +pub use memory_graph::MEMORY_SEMANTIC_INDEX_RECEIPT_SCHEMA_VERSION; +pub use memory_graph::MemorySemanticIndexConfig; +pub use memory_graph::MemorySemanticIndexReceipt; pub use memory_graph::RepoFrontierAdoptedPlan; pub use memory_graph::RepoFrontierItem; pub use memory_graph::RepoFrontierStatus; @@ -625,9 +629,21 @@ pub use memory_graph::RepoMemoryGraphRefresh; pub use memory_graph::RepoModelPatch; pub use memory_graph::RepoModelPatchOperation; pub use memory_graph::RepoModelPatchPurpose; +pub use memory_graph::SEMANTIC_PROJECTION_SCHEMA_VERSION; +pub use memory_graph::SemanticCanonicalLocator; +pub use memory_graph::SemanticDocumentKind; +pub use memory_graph::SemanticEmbedder; +pub use memory_graph::SemanticLifecycle; +pub use memory_graph::SemanticPartition; +pub use memory_graph::SemanticProjectionCandidate; +pub use memory_graph::SemanticProjectionDocument; +pub use memory_graph::SemanticVectorIndex; +pub use memory_graph::SemanticVisibility; pub use memory_graph::compose_memory_graph_snapshots; pub use memory_graph::derive_memory_graph_freshness; pub use memory_graph::derive_repo_model_patch; +pub use memory_graph::derive_semantic_projection; +pub use memory_graph::index_memory_semantic_partition; pub use memory_graph::lifecycle_allowed_for_profile; pub use memory_graph::load_memory_graph_entry; pub use memory_graph::load_memory_graph_snapshot; @@ -639,8 +655,13 @@ pub use memory_graph::memory_graph_from_epiphany_graphs; pub use memory_graph::memory_graph_from_heartbeat_cognition; pub use memory_graph::memory_graph_model_hash; pub use memory_graph::memory_graph_node_id; +pub use memory_graph::persist_memory_semantic_index_receipt; pub use memory_graph::plan_memory_graph_context_cut; +pub use memory_graph::plan_memory_graph_context_cut_with_ranked_ids; pub use memory_graph::refresh_or_validate_repo_memory_graph; +pub use memory_graph::resolve_semantic_candidate; +pub use memory_graph::semantic_memory_context; +pub use memory_graph::semantic_point_id; pub use memory_graph::validate_memory_graph_entry; pub use memory_graph::validate_memory_graph_snapshot; pub use memory_graph::write_memory_graph_entry; @@ -686,18 +707,6 @@ pub use organ_dependencies::evaluate_receipt_proof_profiles; pub use organ_dependencies::receipt_proof_evaluation_errors; pub use organ_dependencies::render_organ_dependencies; pub use organ_dependencies::render_organ_dependency; -pub use persona_memory_cache::PERSONA_MEMORY_CACHE_SCHEMA_VERSION; -pub use persona_memory_cache::PERSONA_MEMORY_CORPUS_KIND; -pub use persona_memory_cache::PersonaMemoryCacheConfig; -pub use persona_memory_cache::PersonaMemoryCacheIndexReceipt; -pub use persona_memory_cache::PersonaMemoryChunk; -pub use persona_memory_cache::PersonaMemoryRecallRender; -pub use persona_memory_cache::PersonaMemorySearchHit; -pub use persona_memory_cache::build_persona_memory_chunks; -pub use persona_memory_cache::index_persona_memory_chunks; -pub use persona_memory_cache::render_dynamic_persona_memory_recall_for_output; -pub use persona_memory_cache::render_persona_memory_recall_with_cache; -pub use persona_memory_cache::search_persona_memory_cache; pub use persona_turn::PERSONA_INTERPRETER_PROMPT_SCHEMA_VERSION; pub use persona_turn::PERSONA_PROJECTOR_PROMPT_SCHEMA_VERSION; pub use persona_turn::PERSONA_TURN_PROMPT_SCHEMA_VERSION; diff --git a/epiphany-core/src/memory_graph/context_cut.rs b/epiphany-core/src/memory_graph/context_cut.rs index 04cad917..c4953e98 100644 --- a/epiphany-core/src/memory_graph/context_cut.rs +++ b/epiphany-core/src/memory_graph/context_cut.rs @@ -9,6 +9,7 @@ use super::EpiphanyMemoryProfile; use super::EpiphanyMemorySummary; use super::RepoFrontierItem; use super::RepoFrontierStatus; +use super::SemanticPartition; use super::derive_memory_graph_freshness; use super::ids::normalized_key; use super::ids::stable_memory_graph_id; @@ -22,6 +23,32 @@ use std::collections::HashSet; pub fn plan_memory_graph_context_cut( snapshot: &EpiphanyMemoryGraphSnapshot, query: &EpiphanyMemoryContextQuery, +) -> EpiphanyMemoryContextPacket { + plan_memory_graph_context_cut_constrained(snapshot, query, &[], None) +} + +pub fn plan_memory_graph_context_cut_with_ranked_ids( + snapshot: &EpiphanyMemoryGraphSnapshot, + query: &EpiphanyMemoryContextQuery, + ranked_document_ids: &[String], +) -> EpiphanyMemoryContextPacket { + plan_memory_graph_context_cut_constrained(snapshot, query, ranked_document_ids, None) +} + +pub(crate) fn plan_memory_graph_context_cut_for_partition( + snapshot: &EpiphanyMemoryGraphSnapshot, + query: &EpiphanyMemoryContextQuery, + ranked_document_ids: &[String], + partition: SemanticPartition, +) -> EpiphanyMemoryContextPacket { + plan_memory_graph_context_cut_constrained(snapshot, query, ranked_document_ids, Some(partition)) +} + +fn plan_memory_graph_context_cut_constrained( + snapshot: &EpiphanyMemoryGraphSnapshot, + query: &EpiphanyMemoryContextQuery, + ranked_document_ids: &[String], + partition: Option, ) -> EpiphanyMemoryContextPacket { let budget = query.budget.unwrap_or(12).clamp(1, 64) as usize; let dirty_source_hashes = snapshot @@ -76,14 +103,21 @@ pub fn plan_memory_graph_context_cut( let mut nodes = Vec::new(); let mut edges = Vec::new(); - let mut summaries = Vec::new(); + let mut summaries: Vec = Vec::new(); let mut warnings = Vec::new(); // Modeling's unresolved frontier is explicit routing authority. Preserve its // stored order and exact claim targets before asking semantic retrieval to // infer what matters from the launch prose. - let (frontier, rejected_frontier_ids) = - dependency_ordered_frontier(snapshot, budget, &node_by_id, &stale_nodes); + let (frontier, rejected_frontier_ids) = dependency_ordered_frontier( + snapshot, + query, + partition, + budget, + &node_by_id, + &stale_nodes, + &domains, + ); for id in rejected_frontier_ids { warnings.push(format!( "frontier {id} was omitted because its target claims are missing, stale, or retired" @@ -98,15 +132,82 @@ pub fn plan_memory_graph_context_cut( } } - for summary in ranked_summaries(snapshot, query, &domains, &terms, &node_by_id) { + // Semantic projection may rank canonical document identities, never + // payload-authored claim text. Explicit frontier remains first; ranked + // canonical objects then seed the cut before BM25 fills remaining space. + for document_id in ranked_document_ids { + if let Some(node) = node_by_id.get(document_id.as_str()) { + if !stale_nodes.contains(node.id.as_str()) + && node_matches(node, query.profile, partition, &domains, &[]) + { + push_unique_node(&mut nodes, (*node).clone(), budget); + } + continue; + } + if let Some(edge) = edge_by_id.get(document_id.as_str()) { + let endpoints_live = [edge.source_id.as_str(), edge.target_id.as_str()] + .into_iter() + .all(|id| !stale_nodes.contains(id)); + if !stale_edges.contains(edge.id.as_str()) + && endpoints_live + && edge_matches(edge, query.profile, partition, &domains, &node_by_id) + { + push_unique_edge(&mut edges, (*edge).clone(), budget); + if let Some(node) = node_by_id.get(edge.source_id.as_str()) { + if !stale_nodes.contains(node.id.as_str()) + && node_matches(node, query.profile, partition, &domains, &[]) + { + push_unique_node(&mut nodes, (*node).clone(), budget); + } + } + if let Some(node) = node_by_id.get(edge.target_id.as_str()) { + if !stale_nodes.contains(node.id.as_str()) + && node_matches(node, query.profile, partition, &domains, &[]) + { + push_unique_node(&mut nodes, (*node).clone(), budget); + } + } + } + continue; + } + if let Some(summary) = snapshot + .summaries + .iter() + .find(|summary| summary.id == *document_id) + && summary_matches( + summary, + query.profile, + partition, + &domains, + &[], + &node_by_id, + ) + && summary_is_usable(summary, &stale_summaries) + && summaries.len() < budget + && !summaries.iter().any(|existing| existing.id == summary.id) + { + summaries.push(summary.clone()); + } + } + + for summary in ranked_summaries(snapshot, query, partition, &domains, &terms, &node_by_id) { if summaries.len() >= budget { break; } - if !summary_matches(summary, query.profile, &domains, &terms, &node_by_id) { + if !summary_matches( + summary, + query.profile, + partition, + &domains, + &terms, + &node_by_id, + ) { continue; } if summary_is_usable(summary, &stale_summaries) { - summaries.push(summary.clone()); + if !summaries.iter().any(|existing| existing.id == summary.id) { + summaries.push(summary.clone()); + } continue; } warnings.push(format!( @@ -119,6 +220,9 @@ pub fn plan_memory_graph_context_cut( &edge_by_id, &stale_nodes, &stale_edges, + query.profile, + partition, + &domains, budget, &mut nodes, &mut edges, @@ -127,27 +231,37 @@ pub fn plan_memory_graph_context_cut( for node_id in &query.node_ids { if let Some(node) = node_by_id.get(node_id.as_str()) { - push_unique_node(&mut nodes, (*node).clone(), budget); + if !stale_nodes.contains(node.id.as_str()) + && node_matches(node, query.profile, partition, &domains, &[]) + { + push_unique_node(&mut nodes, (*node).clone(), budget); + } } } for edge_id in &query.edge_ids { if let Some(edge) = edge_by_id.get(edge_id.as_str()) { - push_unique_edge(&mut edges, (*edge).clone(), budget); - if let Some(node) = node_by_id.get(edge.source_id.as_str()) { - push_unique_node(&mut nodes, (*node).clone(), budget); - } - if let Some(node) = node_by_id.get(edge.target_id.as_str()) { - push_unique_node(&mut nodes, (*node).clone(), budget); + if !stale_edges.contains(edge.id.as_str()) + && edge_matches(edge, query.profile, partition, &domains, &node_by_id) + { + push_unique_edge(&mut edges, (*edge).clone(), budget); + for node_id in [&edge.source_id, &edge.target_id] { + if let Some(node) = node_by_id.get(node_id.as_str()) + && !stale_nodes.contains(node.id.as_str()) + && node_matches(node, query.profile, partition, &domains, &[]) + { + push_unique_node(&mut nodes, (*node).clone(), budget); + } + } } } } if summaries.is_empty() && nodes.is_empty() { - for node in ranked_nodes(snapshot, query, &domains, &terms, &stale_nodes) { + for node in ranked_nodes(snapshot, query, partition, &domains, &terms, &stale_nodes) { if nodes.len() >= budget { break; } - if node_matches(node, query.profile, &domains, &terms) { + if node_matches(node, query.profile, partition, &domains, &terms) { push_unique_node(&mut nodes, node.clone(), budget); } } @@ -188,10 +302,16 @@ pub fn plan_memory_graph_context_cut( fn dependency_ordered_frontier( snapshot: &EpiphanyMemoryGraphSnapshot, + query: &EpiphanyMemoryContextQuery, + partition: Option, budget: usize, node_by_id: &HashMap<&str, &EpiphanyMemoryNode>, stale_nodes: &HashSet<&str>, + domains: &HashSet<&str>, ) -> (Vec, Vec) { + if partition == Some(SemanticPartition::Mind) { + return (Vec::new(), Vec::new()); + } let unresolved = snapshot .frontier .iter() @@ -219,6 +339,7 @@ fn dependency_ordered_frontier( super::EpiphanyMemoryLifecycle::Retired | super::EpiphanyMemoryLifecycle::Stale ) && !stale_nodes.contains(id.as_str()) + && node_matches(node, query.profile, partition, domains, &[]) }) }) }) @@ -296,6 +417,7 @@ fn append_frontier_prerequisites<'a>( fn ranked_nodes<'a>( snapshot: &'a EpiphanyMemoryGraphSnapshot, query: &EpiphanyMemoryContextQuery, + partition: Option, domain_ids: &HashSet<&str>, terms: &[String], stale_nodes: &HashSet<&str>, @@ -304,7 +426,7 @@ fn ranked_nodes<'a>( .nodes .iter() .filter(|node| { - node_matches(node, query.profile, domain_ids, &[]) + node_matches(node, query.profile, partition, domain_ids, &[]) && !stale_nodes.contains(node.id.as_str()) }) .collect::>(); @@ -323,6 +445,7 @@ fn ranked_nodes<'a>( fn ranked_summaries<'a>( snapshot: &'a EpiphanyMemoryGraphSnapshot, query: &EpiphanyMemoryContextQuery, + partition: Option, domain_ids: &HashSet<&str>, terms: &[String], node_by_id: &HashMap<&str, &EpiphanyMemoryNode>, @@ -330,7 +453,16 @@ fn ranked_summaries<'a>( let eligible = snapshot .summaries .iter() - .filter(|summary| summary_matches(summary, query.profile, domain_ids, &[], node_by_id)) + .filter(|summary| { + summary_matches( + summary, + query.profile, + partition, + domain_ids, + &[], + node_by_id, + ) + }) .collect::>(); rank_typed_documents(eligible, query.text.as_deref(), terms, |summary| { [ @@ -380,6 +512,7 @@ fn query_terms(query: &EpiphanyMemoryContextQuery) -> Vec { fn summary_matches( summary: &EpiphanyMemorySummary, profile: Option, + partition: Option, domain_ids: &HashSet<&str>, terms: &[String], node_by_id: &HashMap<&str, &EpiphanyMemoryNode>, @@ -387,6 +520,14 @@ fn summary_matches( if !domain_ids.is_empty() && !domain_ids.contains(summary.domain_id.as_str()) { return false; } + let covers_partition = summary + .covers_node_ids + .iter() + .filter_map(|id| node_by_id.get(id.as_str())) + .any(|node| partition_matches(node.profile, partition)); + if partition.is_some() && !covers_partition { + return false; + } if let Some(profile) = profile { let covers_profile = summary .covers_node_ids @@ -412,12 +553,16 @@ fn summary_matches( fn node_matches( node: &EpiphanyMemoryNode, profile: Option, + partition: Option, domain_ids: &HashSet<&str>, terms: &[String], ) -> bool { if profile.is_some_and(|profile| node.profile != profile) { return false; } + if !partition_matches(node.profile, partition) { + return false; + } if !domain_ids.is_empty() && !domain_ids.contains(node.domain_id.as_str()) { return false; } @@ -434,6 +579,35 @@ fn node_matches( ) } +fn edge_matches( + edge: &EpiphanyMemoryEdge, + profile: Option, + partition: Option, + domain_ids: &HashSet<&str>, + node_by_id: &HashMap<&str, &EpiphanyMemoryNode>, +) -> bool { + if profile.is_some_and(|profile| edge.profile != profile) + || !partition_matches(edge.profile, partition) + { + return false; + } + [&edge.source_id, &edge.target_id].into_iter().all(|id| { + node_by_id.get(id.as_str()).is_some_and(|node| { + partition_matches(node.profile, partition) + && (domain_ids.is_empty() || domain_ids.contains(node.domain_id.as_str())) + }) + }) +} + +fn partition_matches(profile: EpiphanyMemoryProfile, partition: Option) -> bool { + partition.is_none_or(|partition| { + matches!( + profile, + EpiphanyMemoryProfile::RepoArchitecture | EpiphanyMemoryProfile::RepoDataflow + ) == (partition == SemanticPartition::Modeling) + }) +} + fn text_matches_terms<'a>(values: impl IntoIterator, terms: &[String]) -> bool { let joined = values .into_iter() @@ -456,24 +630,31 @@ fn include_summary_children( edge_by_id: &HashMap<&str, &EpiphanyMemoryEdge>, stale_nodes: &HashSet<&str>, stale_edges: &HashSet<&str>, + profile: Option, + partition: Option, + domain_ids: &HashSet<&str>, budget: usize, nodes: &mut Vec, edges: &mut Vec, ) { for node_id in &summary.covers_node_ids { if let Some(node) = node_by_id.get(node_id.as_str()) { - push_unique_node(nodes, (*node).clone(), budget); - if stale_nodes.contains(node.id.as_str()) { + if stale_nodes.contains(node.id.as_str()) + || !node_matches(node, profile, partition, domain_ids, &[]) + { continue; } + push_unique_node(nodes, (*node).clone(), budget); } } for edge_id in &summary.covers_edge_ids { if let Some(edge) = edge_by_id.get(edge_id.as_str()) { - push_unique_edge(edges, (*edge).clone(), budget); - if stale_edges.contains(edge.id.as_str()) { + if stale_edges.contains(edge.id.as_str()) + || !edge_matches(edge, profile, partition, domain_ids, node_by_id) + { continue; } + push_unique_edge(edges, (*edge).clone(), budget); } } } diff --git a/epiphany-core/src/memory_graph/mod.rs b/epiphany-core/src/memory_graph/mod.rs index c8b89237..ce608fc1 100644 --- a/epiphany-core/src/memory_graph/mod.rs +++ b/epiphany-core/src/memory_graph/mod.rs @@ -3,6 +3,8 @@ pub mod context_cut; pub mod freshness; pub mod ids; pub mod profiles; +pub mod semantic_index; +pub mod semantic_projection; pub mod store; pub mod validation; @@ -33,6 +35,8 @@ pub use epiphany_state_model::RepoModelPatchPurpose; pub use compose::compose_memory_graph_snapshots; pub use context_cut::plan_memory_graph_context_cut; +pub(crate) use context_cut::plan_memory_graph_context_cut_for_partition; +pub use context_cut::plan_memory_graph_context_cut_with_ranked_ids; pub use freshness::derive_memory_graph_freshness; pub use ids::memory_graph_domain_id; pub use ids::memory_graph_edge_id; @@ -42,6 +46,8 @@ 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 profiles::refresh_or_validate_repo_memory_graph; +pub use semantic_index::*; +pub use semantic_projection::*; 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/profiles/repo.rs b/epiphany-core/src/memory_graph/profiles/repo.rs index f2bfd3e7..33c070c8 100644 --- a/epiphany-core/src/memory_graph/profiles/repo.rs +++ b/epiphany-core/src/memory_graph/profiles/repo.rs @@ -2,7 +2,6 @@ use crate::memory_graph::EpiphanyMemoryAnchor; use crate::memory_graph::EpiphanyMemoryDomain; use crate::memory_graph::EpiphanyMemoryEdge; use crate::memory_graph::EpiphanyMemoryEdgeKind; -use crate::memory_graph::EpiphanyMemoryFreshness; use crate::memory_graph::EpiphanyMemoryFreshnessStatus; use crate::memory_graph::EpiphanyMemoryGraphSnapshot; use crate::memory_graph::EpiphanyMemoryLifecycle; @@ -10,6 +9,7 @@ use crate::memory_graph::EpiphanyMemoryNode; use crate::memory_graph::EpiphanyMemoryNodeKind; use crate::memory_graph::EpiphanyMemoryProfile; use crate::memory_graph::EpiphanyMemorySummary; +use crate::memory_graph::derive_memory_graph_freshness; use crate::memory_graph::memory_graph_domain_id; use crate::memory_graph::memory_graph_edge_id; use crate::memory_graph::memory_graph_node_id; @@ -216,23 +216,18 @@ pub fn memory_graph_from_epiphany_graphs( import_graph_links(graphs.links.as_slice(), &node_map, &mut edges, repo_root); - let stale_node_ids = nodes + let stale = nodes .iter() - .filter(|node| node.lifecycle == EpiphanyMemoryLifecycle::Stale) - .map(|node| node.id.clone()) - .collect::>(); - let stale_edge_ids = edges - .iter() - .filter(|edge| edge.lifecycle == EpiphanyMemoryLifecycle::Stale) - .map(|edge| edge.id.clone()) - .collect::>(); - let stale = !stale_node_ids.is_empty() || !stale_edge_ids.is_empty(); + .any(|node| node.lifecycle == EpiphanyMemoryLifecycle::Stale) + || edges + .iter() + .any(|edge| edge.lifecycle == EpiphanyMemoryLifecycle::Stale); if stale { for summary in &mut summaries { summary.freshness = EpiphanyMemoryFreshnessStatus::Stale; } } - Ok(EpiphanyMemoryGraphSnapshot { + let mut snapshot = EpiphanyMemoryGraphSnapshot { schema_version: Some("epiphany.memory_graph.v1".to_string()), graph_id: graph_id.into(), source: Some(crate::memory_graph::EpiphanyMemoryGraphSource { @@ -244,26 +239,10 @@ pub fn memory_graph_from_epiphany_graphs( nodes, edges, summaries, - freshness: Some(EpiphanyMemoryFreshness { - status: if stale { - EpiphanyMemoryFreshnessStatus::Stale - } else { - EpiphanyMemoryFreshnessStatus::Ready - }, - stale_node_ids, - stale_edge_ids, - note: Some( - if stale { - "One or more accepted graph anchors could not be verified against source bytes." - } else { - "Imported from accepted Epiphany graph state." - } - .to_string(), - ), - ..Default::default() - }), ..Default::default() - }) + }; + snapshot.freshness = Some(derive_memory_graph_freshness(&snapshot, &[])); + Ok(snapshot) } fn repo_domain(id: String, profile: EpiphanyMemoryProfile, title: &str) -> EpiphanyMemoryDomain { diff --git a/epiphany-core/src/memory_graph/semantic_index.rs b/epiphany-core/src/memory_graph/semantic_index.rs new file mode 100644 index 00000000..cd5ac6df --- /dev/null +++ b/epiphany-core/src/memory_graph/semantic_index.rs @@ -0,0 +1,516 @@ +use super::{ + EpiphanyMemoryContextPacket, EpiphanyMemoryContextQuery, EpiphanyMemoryGraphSnapshot, + SEMANTIC_PROJECTION_SCHEMA_VERSION, SemanticPartition, SemanticProjectionCandidate, + SemanticProjectionDocument, derive_semantic_projection, plan_memory_graph_context_cut, + plan_memory_graph_context_cut_for_partition, resolve_semantic_candidate, +}; +use crate::semantic_backend::{ + CollectionCompatibility, OllamaConfig, OllamaEmbedder, QdrantBackend, QdrantConfig, + SemanticPoint, +}; +use anyhow::{Result, anyhow}; +use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::HashSet; +use std::env; +use std::path::Path; + +pub const MEMORY_SEMANTIC_INDEX_RECEIPT_SCHEMA_VERSION: &str = + "gamecult.epiphany.memory_semantic_index_receipt.v0"; +const MODELING_COLLECTION_DEFAULT: &str = "epiphany_modeling_v1"; +const MIND_COLLECTION_DEFAULT: &str = "epiphany_mind_v1"; +const QUERY_LIMIT_MAX: usize = 64; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MemorySemanticIndexConfig { + pub qdrant_url: String, + pub qdrant_api_key: Option, + pub qdrant_timeout_ms: u64, + pub ollama_base_url: String, + pub ollama_model: String, + pub ollama_timeout_ms: u64, + pub embedding_provider_id: String, + pub modeling_collection: String, + pub mind_collection: String, + pub modeling_query_instruction: String, + pub mind_query_instruction: String, +} + +impl MemorySemanticIndexConfig { + pub fn from_env() -> Self { + Self { + qdrant_url: env_value("EPIPHANY_QDRANT_URL", "http://127.0.0.1:6333"), + qdrant_api_key: env::var("EPIPHANY_QDRANT_API_KEY") + .ok() + .filter(|value| !value.trim().is_empty()), + qdrant_timeout_ms: env_u64("EPIPHANY_QDRANT_TIMEOUT_MS", 30_000), + ollama_base_url: env_value("EPIPHANY_OLLAMA_BASE_URL", "http://127.0.0.1:11434"), + ollama_model: env_value("EPIPHANY_OLLAMA_MODEL", "qwen3-embedding:0.6b"), + ollama_timeout_ms: env_u64("EPIPHANY_OLLAMA_TIMEOUT_MS", 30_000), + embedding_provider_id: env_value( + "EPIPHANY_EMBEDDING_PROVIDER_ID", + "gamecult-ollama-embedding", + ), + modeling_collection: env_value( + "EPIPHANY_MODELING_QDRANT_COLLECTION", + MODELING_COLLECTION_DEFAULT, + ), + mind_collection: env_value( + "EPIPHANY_MIND_QDRANT_COLLECTION", + MIND_COLLECTION_DEFAULT, + ), + modeling_query_instruction: "Given a repository architecture, dataflow, ownership, invariant, or frontier question, rank the canonical Modeling documents that answer it.".to_string(), + mind_query_instruction: "Given a swarm memory, doctrine, evidence, decision, relationship, or rehydration question, rank the canonical Mind documents that answer it.".to_string(), + } + } + + fn collection(&self, partition: SemanticPartition) -> &str { + match partition { + SemanticPartition::Mind => &self.mind_collection, + SemanticPartition::Modeling => &self.modeling_collection, + } + } + + fn query_instruction(&self, partition: SemanticPartition) -> &str { + match partition { + SemanticPartition::Mind => &self.mind_query_instruction, + SemanticPartition::Modeling => &self.modeling_query_instruction, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct MemorySemanticPointPayload { + point_id: String, + swarm_id: String, + partition: SemanticPartition, + canonical_locator: String, + canonical_type: String, + canonical_key: String, + canonical_document_id: String, + canonical_schema_version: String, + graph_id: String, + indexed_model_revision: u64, + indexed_model_hash: String, + indexed_canonical_content_hash: String, + projection_schema_version: String, + embedding_provider_id: String, + embedding_model: String, +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache( + type = "gamecult.epiphany.memory_semantic_index_receipt", + schema = "MemorySemanticIndexReceipt" +)] +pub struct MemorySemanticIndexReceipt { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub receipt_id: String, + #[cultcache(key = 2)] + pub swarm_id: String, + #[cultcache(key = 3)] + pub partition: String, + #[cultcache(key = 4)] + pub collection_name: String, + #[cultcache(key = 5)] + pub graph_id: String, + #[cultcache(key = 6)] + pub model_revision: u64, + #[cultcache(key = 7)] + pub model_hash: String, + #[cultcache(key = 8)] + pub embedding_provider_id: String, + #[cultcache(key = 9)] + pub embedding_model: String, + #[cultcache(key = 10)] + pub vector_dimensions: u32, + #[cultcache(key = 11)] + pub indexed_document_count: u32, + #[cultcache(key = 12)] + pub deleted_document_count: u32, + #[cultcache(key = 13)] + pub canonical_content_set_hash: String, + #[cultcache(key = 14)] + pub indexed_at: String, + #[cultcache(key = 15)] + pub status: String, +} + +pub fn index_memory_semantic_partition( + snapshot: &EpiphanyMemoryGraphSnapshot, + swarm_id: &str, + partition: SemanticPartition, + indexed_at: &str, + config: &MemorySemanticIndexConfig, +) -> Result { + let documents = derive_semantic_projection(swarm_id, snapshot)? + .into_iter() + .filter(|document| document.partition == partition) + .collect::>(); + if documents.is_empty() { + return Err(anyhow!( + "semantic projection partition has no live documents" + )); + } + let embedder = embedder(config, partition)?; + let texts = documents + .iter() + .map(|document| document.projection_text.clone()) + .collect::>(); + let embeddings = embedder.embed_documents(&texts)?; + let vector_size = embeddings + .first() + .map(Vec::len) + .ok_or_else(|| anyhow!("semantic projection produced no embeddings"))?; + let backend = qdrant(config)?; + let collection = config.collection(partition); + let compatibility = compatibility(config, partition, vector_size); + if backend.collection_exists(collection)? { + let actual = backend.collection_compatibility(collection)?; + if actual != compatibility { + return Err(anyhow!( + "Qdrant collection {collection} is incompatible: actual {actual:?}, expected {compatibility:?}" + )); + } + } else { + backend.create_collection(collection, &compatibility)?; + } + let existing_ids = backend.point_ids_for_scope( + collection, + &[ + ("swarmId", swarm_id), + ("partition", partition_name(partition)), + ], + )?; + let points = documents + .iter() + .zip(embeddings) + .map(|(document, vector)| SemanticPoint { + id: document.point_id.clone(), + vector, + payload: point_payload(document, config), + }) + .collect::>(); + backend.upsert_points(collection, &points)?; + let live_ids = documents + .iter() + .map(|document| document.point_id.as_str()) + .collect::>(); + let deleted_ids = existing_ids + .into_iter() + .filter(|id| !live_ids.contains(id.as_str())) + .collect::>(); + backend.delete_points(collection, &deleted_ids)?; + let content_set_hash = canonical_content_set_hash(&documents); + let receipt_id = format!( + "memory-semantic-index-{}-{}-{}-{}", + partition_name(partition), + snapshot.model_revision, + &content_set_hash[..16], + &format!("{:x}", Sha256::digest(indexed_at.as_bytes()))[..12] + ); + Ok(MemorySemanticIndexReceipt { + schema_version: MEMORY_SEMANTIC_INDEX_RECEIPT_SCHEMA_VERSION.to_string(), + receipt_id, + swarm_id: swarm_id.to_string(), + partition: partition_name(partition).to_string(), + collection_name: collection.to_string(), + graph_id: snapshot.graph_id.clone(), + model_revision: snapshot.model_revision, + model_hash: documents[0].model_hash.clone(), + embedding_provider_id: config.embedding_provider_id.clone(), + embedding_model: config.ollama_model.clone(), + vector_dimensions: vector_size as u32, + indexed_document_count: documents.len() as u32, + deleted_document_count: deleted_ids.len() as u32, + canonical_content_set_hash: content_set_hash, + indexed_at: indexed_at.to_string(), + status: "ready".to_string(), + }) +} + +pub fn persist_memory_semantic_index_receipt( + store_path: impl AsRef, + receipt: &MemorySemanticIndexReceipt, +) -> Result<()> { + let mut cache = CultCache::new(); + cache.register_entry_type::()?; + cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(store_path.as_ref())); + cache.pull_all_backing_stores()?; + cache.put(&receipt.receipt_id, receipt)?; + Ok(()) +} + +pub fn semantic_memory_context( + snapshot: &EpiphanyMemoryGraphSnapshot, + swarm_id: &str, + partition: SemanticPartition, + query: &EpiphanyMemoryContextQuery, + config: &MemorySemanticIndexConfig, +) -> EpiphanyMemoryContextPacket { + match try_semantic_memory_context(snapshot, swarm_id, partition, query, config) { + Ok(packet) => packet, + Err(error) => { + let mut packet = plan_memory_graph_context_cut(snapshot, query); + packet.warnings.push(format!( + "semantic projection unavailable; used canonical BM25 fallback: {error}" + )); + packet + } + } +} + +fn try_semantic_memory_context( + snapshot: &EpiphanyMemoryGraphSnapshot, + swarm_id: &str, + partition: SemanticPartition, + query: &EpiphanyMemoryContextQuery, + config: &MemorySemanticIndexConfig, +) -> Result { + let text = query + .text + .as_deref() + .filter(|text| !text.trim().is_empty()) + .ok_or_else(|| anyhow!("semantic context requires query text"))?; + let documents = derive_semantic_projection(swarm_id, snapshot)?; + let backend = qdrant(config)?; + let collection = config.collection(partition); + if !backend.collection_exists(collection)? { + return Err(anyhow!("semantic collection {collection} is missing")); + } + let embedder = embedder(config, partition)?; + let vector = embedder.embed_query(text)?; + let expected = compatibility(config, partition, vector.len()); + let actual = backend.collection_compatibility(collection)?; + if actual != expected { + return Err(anyhow!("semantic collection compatibility mismatch")); + } + let limit = query.budget.unwrap_or(12).clamp(1, QUERY_LIMIT_MAX as u32) as usize; + let ranked = backend.query_points_for_scope::( + collection, + &vector, + limit, + &[ + ("swarmId", swarm_id), + ("partition", partition_name(partition)), + ], + )?; + let mut ranked_ids = Vec::new(); + for hit in ranked { + let payload = hit + .payload + .ok_or_else(|| anyhow!("semantic candidate omitted its typed locator payload"))?; + if payload.swarm_id != swarm_id + || payload.partition != partition + || payload.embedding_provider_id != config.embedding_provider_id + || payload.embedding_model != config.ollama_model + || payload.projection_schema_version != SEMANTIC_PROJECTION_SCHEMA_VERSION + { + continue; + } + let candidate = SemanticProjectionCandidate { + point_id: payload.point_id, + canonical: super::SemanticCanonicalLocator { + locator: payload.canonical_locator, + canonical_type: payload.canonical_type, + canonical_key: payload.canonical_key, + canonical_document_id: payload.canonical_document_id, + }, + partition: payload.partition, + score: hit.score, + indexed_model_revision: payload.indexed_model_revision, + indexed_model_hash: payload.indexed_model_hash, + indexed_canonical_content_hash: payload.indexed_canonical_content_hash, + }; + if let Ok(document) = resolve_semantic_candidate(partition, &candidate, &documents) { + ranked_ids.push(document.canonical.canonical_document_id.clone()); + } + } + let mut packet = + plan_memory_graph_context_cut_for_partition(snapshot, query, &ranked_ids, partition); + packet.warnings.push(format!( + "semantic projection ranked {} canonical {} candidates; all payload text was ignored", + ranked_ids.len(), + partition_name(partition) + )); + Ok(packet) +} + +fn point_payload( + document: &SemanticProjectionDocument, + config: &MemorySemanticIndexConfig, +) -> MemorySemanticPointPayload { + MemorySemanticPointPayload { + point_id: document.point_id.clone(), + swarm_id: document.swarm_id.clone(), + partition: document.partition, + canonical_locator: document.canonical.locator.clone(), + canonical_type: document.canonical.canonical_type.clone(), + canonical_key: document.canonical.canonical_key.clone(), + canonical_document_id: document.canonical.canonical_document_id.clone(), + canonical_schema_version: document.canonical_schema_version.clone(), + graph_id: document.graph_id.clone(), + indexed_model_revision: document.model_revision, + indexed_model_hash: document.model_hash.clone(), + indexed_canonical_content_hash: document.canonical_content_hash.clone(), + projection_schema_version: document.projection_schema_version.clone(), + embedding_provider_id: config.embedding_provider_id.clone(), + embedding_model: config.ollama_model.clone(), + } +} + +fn qdrant(config: &MemorySemanticIndexConfig) -> Result { + QdrantBackend::new(QdrantConfig { + url: config.qdrant_url.clone(), + api_key: config.qdrant_api_key.clone(), + timeout_ms: config.qdrant_timeout_ms, + }) +} + +fn embedder( + config: &MemorySemanticIndexConfig, + partition: SemanticPartition, +) -> Result { + OllamaEmbedder::new(OllamaConfig { + base_url: config.ollama_base_url.clone(), + model: config.ollama_model.clone(), + timeout_ms: config.ollama_timeout_ms, + query_instruction: config.query_instruction(partition).to_string(), + }) +} + +fn compatibility( + config: &MemorySemanticIndexConfig, + partition: SemanticPartition, + vector_size: usize, +) -> CollectionCompatibility { + CollectionCompatibility { + managed_by: "epiphany".to_string(), + corpus_kind: partition_name(partition).to_string(), + schema_version: 1, + projection_version: SEMANTIC_PROJECTION_SCHEMA_VERSION.to_string(), + embedding_provider_id: config.embedding_provider_id.clone(), + embedding_model: config.ollama_model.clone(), + vector_size, + } +} + +fn partition_name(partition: SemanticPartition) -> &'static str { + match partition { + SemanticPartition::Mind => "mind", + SemanticPartition::Modeling => "modeling", + } +} + +fn canonical_content_set_hash(documents: &[SemanticProjectionDocument]) -> String { + let mut values = documents + .iter() + .map(|document| format!("{}:{}", document.point_id, document.canonical_content_hash)) + .collect::>(); + values.sort(); + format!("{:x}", Sha256::digest(values.join("\n").as_bytes())) +} + +fn env_value(name: &str, default: &str) -> String { + env::var(name) + .ok() + .filter(|value| !value.trim().is_empty()) + .unwrap_or_else(|| default.to_string()) +} + +fn env_u64(name: &str, default: u64) -> u64 { + env::var(name) + .ok() + .and_then(|value| value.parse().ok()) + .unwrap_or(default) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::memory_graph::{ + EpiphanyMemoryDomain, EpiphanyMemoryLifecycle, EpiphanyMemoryNode, EpiphanyMemoryNodeKind, + EpiphanyMemoryProfile, MEMORY_GRAPH_SCHEMA_VERSION, memory_graph_model_hash, + }; + + fn snapshot() -> EpiphanyMemoryGraphSnapshot { + let mut snapshot = EpiphanyMemoryGraphSnapshot { + schema_version: Some(MEMORY_GRAPH_SCHEMA_VERSION.to_string()), + graph_id: "semantic-fallback".to_string(), + model_revision: 3, + domains: vec![EpiphanyMemoryDomain { + id: "repo".to_string(), + profile: EpiphanyMemoryProfile::RepoArchitecture, + title: "Repository".to_string(), + lifecycle: EpiphanyMemoryLifecycle::Accepted, + ..Default::default() + }], + nodes: vec![EpiphanyMemoryNode { + id: "canonical-node".to_string(), + domain_id: "repo".to_string(), + profile: EpiphanyMemoryProfile::RepoArchitecture, + kind: EpiphanyMemoryNodeKind::Module, + title: "Semantic projection".to_string(), + claim: "Canonical graph remains correct without Qdrant.".to_string(), + question: "How is semantic recall ranked?".to_string(), + tension: "The vector service may be absent.".to_string(), + action_implication: "Fall back to typed BM25 traversal.".to_string(), + source_hashes: vec!["anchor:missing".to_string()], + lifecycle: EpiphanyMemoryLifecycle::Accepted, + confidence: 90, + ..Default::default() + }], + ..Default::default() + }; + snapshot.model_hash = memory_graph_model_hash(&snapshot).unwrap(); + snapshot + } + + #[test] + fn unavailable_vector_service_preserves_canonical_bm25_packet() { + let snapshot = snapshot(); + let query = EpiphanyMemoryContextQuery { + id: "fallback-query".to_string(), + profile: Some(EpiphanyMemoryProfile::RepoArchitecture), + text: Some("canonical qdrant semantic".to_string()), + ..Default::default() + }; + let expected = plan_memory_graph_context_cut(&snapshot, &query); + let mut config = MemorySemanticIndexConfig::from_env(); + config.qdrant_url = "http://127.0.0.1:1".to_string(); + config.qdrant_timeout_ms = 25; + let actual = semantic_memory_context( + &snapshot, + "swarm", + SemanticPartition::Modeling, + &query, + &config, + ); + assert_eq!(actual.nodes, expected.nodes); + assert_eq!(actual.edges, expected.edges); + assert_eq!(actual.summaries, expected.summaries); + assert!( + actual + .warnings + .iter() + .any(|warning| warning.contains("canonical BM25 fallback")) + ); + } + + #[test] + fn mind_and_modeling_have_distinct_physical_collections_and_query_profiles() { + let config = MemorySemanticIndexConfig::from_env(); + assert_ne!( + config.collection(SemanticPartition::Mind), + config.collection(SemanticPartition::Modeling) + ); + assert_ne!( + config.query_instruction(SemanticPartition::Mind), + config.query_instruction(SemanticPartition::Modeling) + ); + } +} diff --git a/epiphany-core/src/memory_graph/semantic_projection.rs b/epiphany-core/src/memory_graph/semantic_projection.rs new file mode 100644 index 00000000..3d5119dc --- /dev/null +++ b/epiphany-core/src/memory_graph/semantic_projection.rs @@ -0,0 +1,775 @@ +use super::{ + EpiphanyMemoryDomain, EpiphanyMemoryFreshnessStatus, EpiphanyMemoryGraphSnapshot, + EpiphanyMemoryLifecycle, EpiphanyMemoryProfile, MEMORY_GRAPH_KEY, MEMORY_GRAPH_TYPE, + RepoFrontierStatus, memory_graph_model_hash, validate_memory_graph_snapshot, +}; +use anyhow::{Result, anyhow}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::{HashMap, HashSet}; +use uuid::Uuid; + +pub const SEMANTIC_PROJECTION_SCHEMA_VERSION: &str = "gamecult.epiphany.semantic_projection.v0"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SemanticPartition { + Mind, + Modeling, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SemanticDocumentKind { + Node, + Edge, + Summary, + Frontier, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SemanticVisibility { + PrivateVerse, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "owner", content = "value", rename_all = "snake_case")] +pub enum SemanticLifecycle { + Memory(EpiphanyMemoryLifecycle), + Frontier(RepoFrontierStatus), + Derived, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SemanticCanonicalLocator { + pub locator: String, + pub canonical_type: String, + pub canonical_key: String, + pub canonical_document_id: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SemanticProjectionDocument { + pub point_id: String, + pub swarm_id: String, + pub partition: SemanticPartition, + pub kind: SemanticDocumentKind, + pub canonical: SemanticCanonicalLocator, + pub graph_id: String, + pub model_revision: u64, + pub model_hash: String, + pub domain_id: String, + pub profile: EpiphanyMemoryProfile, + pub lifecycle: SemanticLifecycle, + pub visibility: SemanticVisibility, + pub source_refs: Vec, + pub source_hashes: Vec, + pub canonical_content_hash: String, + pub canonical_schema_version: String, + pub projection_schema_version: String, + pub projection_text: String, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct SemanticProjectionCandidate { + pub point_id: String, + pub canonical: SemanticCanonicalLocator, + pub partition: SemanticPartition, + pub score: f32, + pub indexed_model_revision: u64, + pub indexed_model_hash: String, + pub indexed_canonical_content_hash: String, +} + +pub trait SemanticEmbedder { + fn embed(&self, texts: &[String]) -> Result>>; +} + +pub trait SemanticVectorIndex { + fn replace_partition( + &self, + swarm_id: &str, + partition: SemanticPartition, + documents: &[(SemanticProjectionDocument, Vec)], + ) -> Result<()>; + + fn search( + &self, + swarm_id: &str, + partition: SemanticPartition, + vector: &[f32], + limit: usize, + ) -> Result>; +} + +pub fn semantic_point_id( + swarm_id: &str, + partition: SemanticPartition, + canonical_type: &str, + canonical_key: &str, + canonical_document_id: &str, +) -> String { + let partition = match partition { + SemanticPartition::Mind => "mind", + SemanticPartition::Modeling => "modeling", + }; + Uuid::new_v5( + &Uuid::NAMESPACE_URL, + format!("{swarm_id}|{partition}|{canonical_type}|{canonical_key}|{canonical_document_id}") + .as_bytes(), + ) + .to_string() +} + +pub fn derive_semantic_projection( + swarm_id: &str, + snapshot: &EpiphanyMemoryGraphSnapshot, +) -> Result> { + if swarm_id.trim().is_empty() { + return Err(anyhow!("semantic projection requires swarm_id")); + } + let validation = validate_memory_graph_snapshot(snapshot); + if !validation.is_empty() { + return Err(anyhow!("memory graph is invalid: {validation:?}")); + } + let computed_hash = memory_graph_model_hash(snapshot)?; + if !snapshot.model_hash.is_empty() && snapshot.model_hash != computed_hash { + return Err(anyhow!( + "memory graph model_hash does not match canonical content" + )); + } + let mut canonical_snapshot = snapshot.clone(); + canonical_snapshot.model_hash = computed_hash; + let snapshot = &canonical_snapshot; + + let domains = snapshot + .domains + .iter() + .map(|domain| (domain.id.as_str(), domain)) + .collect::>(); + let nodes = snapshot + .nodes + .iter() + .map(|node| (node.id.as_str(), node)) + .collect::>(); + let stale_nodes: HashSet<&str> = snapshot + .freshness + .as_ref() + .map(|freshness| { + freshness + .stale_node_ids + .iter() + .map(String::as_str) + .collect() + }) + .unwrap_or_default(); + let stale_edges: HashSet<&str> = snapshot + .freshness + .as_ref() + .map(|freshness| { + freshness + .stale_edge_ids + .iter() + .map(String::as_str) + .collect() + }) + .unwrap_or_default(); + let stale_summaries: HashSet<&str> = snapshot + .freshness + .as_ref() + .map(|freshness| { + freshness + .stale_summary_ids + .iter() + .map(String::as_str) + .collect() + }) + .unwrap_or_default(); + let mut out = Vec::new(); + + for node in &snapshot.nodes { + if excluded_lifecycle(node.lifecycle) || stale_nodes.contains(node.id.as_str()) { + continue; + } + let domain = required_domain(&domains, &node.domain_id)?; + out.push(document( + swarm_id, + snapshot, + partition(node.profile), + SemanticDocumentKind::Node, + &node.id, + domain, + node.profile, + SemanticLifecycle::Memory(node.lifecycle), + node.anchors + .iter() + .map(|anchor| anchor.target.clone()) + .collect(), + node.source_hashes.clone(), + node, + join_text([ + &node.title, + &node.claim, + &node.question, + &node.tension, + &node.action_implication, + ]), + )?); + } + + for edge in &snapshot.edges { + if excluded_lifecycle(edge.lifecycle) || stale_edges.contains(edge.id.as_str()) { + continue; + } + let source = nodes + .get(edge.source_id.as_str()) + .ok_or_else(|| anyhow!("validated edge lost source"))?; + let target = nodes + .get(edge.target_id.as_str()) + .ok_or_else(|| anyhow!("validated edge lost target"))?; + if excluded_lifecycle(source.lifecycle) + || excluded_lifecycle(target.lifecycle) + || stale_nodes.contains(source.id.as_str()) + || stale_nodes.contains(target.id.as_str()) + { + continue; + } + let domain = required_domain(&domains, &source.domain_id)?; + let source_hashes = edge + .anchors + .iter() + .filter_map(|anchor| anchor.source_hash.clone()) + .collect(); + out.push(document( + swarm_id, + snapshot, + partition(edge.profile), + SemanticDocumentKind::Edge, + &edge.id, + domain, + edge.profile, + SemanticLifecycle::Memory(edge.lifecycle), + edge.anchors + .iter() + .map(|anchor| anchor.target.clone()) + .collect(), + source_hashes, + edge, + join_text([&edge.claim, &edge.source_id, &edge.target_id]), + )?); + } + + for summary in &snapshot.summaries { + if summary.freshness != EpiphanyMemoryFreshnessStatus::Ready + || summary.confidence < 70 + || !summary.known_omissions.is_empty() + || stale_summaries.contains(summary.id.as_str()) + { + continue; + } + let domain = required_domain(&domains, &summary.domain_id)?; + out.push(document( + swarm_id, + snapshot, + partition(domain.profile), + SemanticDocumentKind::Summary, + &summary.id, + domain, + domain.profile, + SemanticLifecycle::Derived, + summary + .covers_node_ids + .iter() + .chain(&summary.covers_edge_ids) + .cloned() + .collect(), + summary.source_hashes.clone(), + summary, + join_text([ + &summary.target, + &summary.claim, + &summary.question, + &summary.tension, + &summary.action_implication, + ]), + )?); + } + + for item in &snapshot.frontier { + if !matches!( + item.status, + RepoFrontierStatus::Proposed | RepoFrontierStatus::Active | RepoFrontierStatus::Blocked + ) { + continue; + } + let domain = item + .target_claim_ids + .first() + .and_then(|id| nodes.get(id.as_str())) + .and_then(|node| domains.get(node.domain_id.as_str())) + .copied() + .ok_or_else(|| anyhow!("validated unresolved frontier lost its target domain"))?; + out.push(document( + swarm_id, + snapshot, + SemanticPartition::Modeling, + SemanticDocumentKind::Frontier, + &item.id, + domain, + EpiphanyMemoryProfile::RepoArchitecture, + SemanticLifecycle::Frontier(item.status), + item.source_scope + .iter() + .chain(&item.evidence_refs) + .cloned() + .collect(), + Vec::new(), + item, + join_text([ + &item.migration_body, + &item.question, + &item.gap, + &item.recommended_next_organ, + ]), + )?); + } + + out.sort_by(|left, right| left.point_id.cmp(&right.point_id)); + Ok(out) +} + +pub fn resolve_semantic_candidate<'a>( + expected_partition: SemanticPartition, + candidate: &SemanticProjectionCandidate, + current_documents: &'a [SemanticProjectionDocument], +) -> Result<&'a SemanticProjectionDocument> { + if candidate.partition != expected_partition { + return Err(anyhow!("semantic candidate partition mismatch")); + } + let document = current_documents + .iter() + .find(|document| document.point_id == candidate.point_id) + .ok_or_else(|| anyhow!("semantic candidate is missing or no longer live"))?; + if document.partition != candidate.partition + || document.canonical != candidate.canonical + || document.model_revision != candidate.indexed_model_revision + || document.model_hash != candidate.indexed_model_hash + || document.canonical_content_hash != candidate.indexed_canonical_content_hash + { + return Err(anyhow!( + "semantic candidate no longer matches canonical state" + )); + } + Ok(document) +} + +fn document( + swarm_id: &str, + snapshot: &EpiphanyMemoryGraphSnapshot, + partition: SemanticPartition, + kind: SemanticDocumentKind, + document_id: &str, + domain: &EpiphanyMemoryDomain, + profile: EpiphanyMemoryProfile, + lifecycle: SemanticLifecycle, + mut source_refs: Vec, + mut source_hashes: Vec, + canonical_value: &T, + projection_text: String, +) -> Result { + source_refs.sort(); + source_refs.dedup(); + source_hashes.sort(); + source_hashes.dedup(); + let canonical = SemanticCanonicalLocator { + locator: format!( + "cultcache://{swarm_id}/{MEMORY_GRAPH_TYPE}/{MEMORY_GRAPH_KEY}#{document_id}" + ), + canonical_type: MEMORY_GRAPH_TYPE.to_string(), + canonical_key: MEMORY_GRAPH_KEY.to_string(), + canonical_document_id: document_id.to_string(), + }; + Ok(SemanticProjectionDocument { + point_id: semantic_point_id( + swarm_id, + partition, + MEMORY_GRAPH_TYPE, + MEMORY_GRAPH_KEY, + document_id, + ), + swarm_id: swarm_id.to_string(), + partition, + kind, + canonical, + graph_id: snapshot.graph_id.clone(), + model_revision: snapshot.model_revision, + model_hash: snapshot.model_hash.clone(), + domain_id: domain.id.clone(), + profile, + lifecycle, + visibility: SemanticVisibility::PrivateVerse, + source_refs, + source_hashes, + canonical_content_hash: format!( + "{:x}", + Sha256::digest(rmp_serde::to_vec_named(canonical_value)?) + ), + canonical_schema_version: snapshot + .schema_version + .clone() + .unwrap_or_else(|| "unknown".to_string()), + projection_schema_version: SEMANTIC_PROJECTION_SCHEMA_VERSION.to_string(), + projection_text, + }) +} + +fn partition(profile: EpiphanyMemoryProfile) -> SemanticPartition { + match profile { + EpiphanyMemoryProfile::RepoArchitecture | EpiphanyMemoryProfile::RepoDataflow => { + SemanticPartition::Modeling + } + _ => SemanticPartition::Mind, + } +} + +fn excluded_lifecycle(lifecycle: EpiphanyMemoryLifecycle) -> bool { + matches!( + lifecycle, + EpiphanyMemoryLifecycle::Retired | EpiphanyMemoryLifecycle::Stale + ) +} + +fn required_domain<'a>( + domains: &HashMap<&str, &'a EpiphanyMemoryDomain>, + id: &str, +) -> Result<&'a EpiphanyMemoryDomain> { + domains + .get(id) + .copied() + .ok_or_else(|| anyhow!("validated document lost domain")) +} + +fn join_text(parts: [&str; N]) -> String { + parts + .into_iter() + .filter(|part| !part.trim().is_empty()) + .collect::>() + .join("\n") +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::memory_graph::{ + EpiphanyMemoryEdge, EpiphanyMemoryNode, EpiphanyMemorySummary, RepoFrontierItem, + }; + use epiphany_state_model::{EpiphanyMemoryEdgeKind, EpiphanyMemoryNodeKind}; + + fn snapshot() -> EpiphanyMemoryGraphSnapshot { + let mut snapshot = EpiphanyMemoryGraphSnapshot { + schema_version: Some("v0".into()), + graph_id: "graph".into(), + model_revision: 7, + domains: vec![ + EpiphanyMemoryDomain { + id: "repo".into(), + profile: EpiphanyMemoryProfile::RepoArchitecture, + title: "Repo".into(), + lifecycle: EpiphanyMemoryLifecycle::Accepted, + ..Default::default() + }, + EpiphanyMemoryDomain { + id: "mind".into(), + profile: EpiphanyMemoryProfile::Evidence, + title: "Mind".into(), + lifecycle: EpiphanyMemoryLifecycle::Accepted, + ..Default::default() + }, + ], + nodes: vec![ + EpiphanyMemoryNode { + id: "repo-node".into(), + domain_id: "repo".into(), + profile: EpiphanyMemoryProfile::RepoArchitecture, + kind: EpiphanyMemoryNodeKind::Module, + title: "Repo node".into(), + claim: "owns map".into(), + tension: "map can drift".into(), + action_implication: "keep typed".into(), + source_hashes: vec!["anchor:missing".into()], + lifecycle: EpiphanyMemoryLifecycle::Accepted, + confidence: 90, + ..Default::default() + }, + EpiphanyMemoryNode { + id: "mind-node".into(), + domain_id: "mind".into(), + profile: EpiphanyMemoryProfile::Evidence, + kind: EpiphanyMemoryNodeKind::Evidence, + title: "Lesson".into(), + claim: "remember it".into(), + tension: "memory can drift".into(), + action_implication: "rehydrate".into(), + source_hashes: vec!["anchor:missing".into()], + lifecycle: EpiphanyMemoryLifecycle::Accepted, + confidence: 90, + ..Default::default() + }, + EpiphanyMemoryNode { + id: "retired".into(), + domain_id: "repo".into(), + profile: EpiphanyMemoryProfile::RepoArchitecture, + kind: EpiphanyMemoryNodeKind::Module, + title: "Old".into(), + claim: "old".into(), + tension: "obsolete".into(), + action_implication: "none".into(), + source_hashes: vec!["anchor:missing".into()], + lifecycle: EpiphanyMemoryLifecycle::Retired, + confidence: 90, + ..Default::default() + }, + ], + edges: vec![EpiphanyMemoryEdge { + id: "edge".into(), + source_id: "repo-node".into(), + target_id: "mind-node".into(), + kind: EpiphanyMemoryEdgeKind::Grounds, + profile: EpiphanyMemoryProfile::RepoArchitecture, + claim: "grounds".into(), + lifecycle: EpiphanyMemoryLifecycle::Accepted, + confidence: 80, + ..Default::default() + }], + summaries: vec![EpiphanyMemorySummary { + id: "summary".into(), + domain_id: "mind".into(), + covers_node_ids: vec!["mind-node".into()], + target: "lesson".into(), + claim: "durable".into(), + tension: "retrieval can drift".into(), + action_implication: "retrieve".into(), + freshness: EpiphanyMemoryFreshnessStatus::Ready, + confidence: 80, + ..Default::default() + }], + frontier: vec![RepoFrontierItem { + id: "frontier".into(), + migration_body: "finish projection".into(), + gap: "not wired".into(), + target_claim_ids: vec!["repo-node".into()], + recommended_next_organ: "Hands".into(), + status: RepoFrontierStatus::Active, + ..Default::default() + }], + ..Default::default() + }; + snapshot.model_hash = memory_graph_model_hash(&snapshot).unwrap(); + snapshot + } + + #[test] + fn derives_typed_partitions_and_filters_non_live_documents() { + let documents = derive_semantic_projection("swarm-a", &snapshot()).unwrap(); + assert_eq!(documents.len(), 5); + assert!( + documents + .iter() + .any( + |document| document.canonical.canonical_document_id == "mind-node" + && document.partition == SemanticPartition::Mind + ) + ); + assert!( + documents + .iter() + .any(|document| document.kind == SemanticDocumentKind::Frontier + && document.partition == SemanticPartition::Modeling) + ); + assert!( + !documents + .iter() + .any(|document| document.canonical.canonical_document_id == "retired") + ); + let first = derive_semantic_projection("swarm-a", &snapshot()).unwrap(); + assert_eq!(documents, first); + let other_swarm = derive_semantic_projection("swarm-b", &snapshot()).unwrap(); + assert!(documents.iter().zip(&other_swarm).all(|(left, right)| { + left.swarm_id != right.swarm_id && left.point_id != right.point_id + })); + } + + #[test] + fn candidate_resolution_revalidates_canonical_identity_and_hashes() { + let documents = derive_semantic_projection("swarm-a", &snapshot()).unwrap(); + let document = documents + .iter() + .find(|document| document.canonical.canonical_document_id == "repo-node") + .unwrap(); + let candidate = SemanticProjectionCandidate { + point_id: document.point_id.clone(), + canonical: document.canonical.clone(), + partition: document.partition, + score: 0.9, + indexed_model_revision: document.model_revision, + indexed_model_hash: document.model_hash.clone(), + indexed_canonical_content_hash: document.canonical_content_hash.clone(), + }; + assert_eq!( + resolve_semantic_candidate(SemanticPartition::Modeling, &candidate, &documents) + .unwrap() + .point_id, + document.point_id + ); + let mut stale = candidate.clone(); + stale.indexed_canonical_content_hash = "stale".into(); + assert!( + resolve_semantic_candidate(SemanticPartition::Modeling, &stale, &documents).is_err() + ); + assert!( + resolve_semantic_candidate(SemanticPartition::Mind, &candidate, &documents).is_err() + ); + let mut stale_revision = candidate.clone(); + stale_revision.indexed_model_revision -= 1; + assert!( + resolve_semantic_candidate(SemanticPartition::Modeling, &stale_revision, &documents) + .is_err() + ); + let mut stale_model = candidate.clone(); + stale_model.indexed_model_hash = "old-model".into(); + assert!( + resolve_semantic_candidate(SemanticPartition::Modeling, &stale_model, &documents) + .is_err() + ); + let mut wrong_locator = candidate.clone(); + wrong_locator.canonical.canonical_document_id = "other".into(); + assert!( + resolve_semantic_candidate(SemanticPartition::Modeling, &wrong_locator, &documents) + .is_err() + ); + assert!(resolve_semantic_candidate(SemanticPartition::Modeling, &candidate, &[]).is_err()); + } + + #[test] + fn ranked_edge_cannot_reintroduce_stale_endpoint_and_summary_is_not_duplicated() { + let mut snapshot = snapshot(); + snapshot.nodes[0].lifecycle = EpiphanyMemoryLifecycle::Stale; + snapshot.summaries[0].freshness = EpiphanyMemoryFreshnessStatus::Ready; + snapshot.freshness = Some(crate::memory_graph::derive_memory_graph_freshness( + &snapshot, + &[], + )); + snapshot.model_hash.clear(); + snapshot.model_hash = memory_graph_model_hash(&snapshot).unwrap(); + let packet = crate::memory_graph::plan_memory_graph_context_cut_with_ranked_ids( + &snapshot, + &crate::memory_graph::EpiphanyMemoryContextQuery { + id: "ranked-hostile".to_string(), + text: Some("durable lesson".to_string()), + ..Default::default() + }, + &["edge".to_string(), "summary".to_string()], + ); + assert!(!packet.nodes.iter().any(|node| node.id == "repo-node")); + assert_eq!( + packet + .summaries + .iter() + .filter(|summary| summary.id == "summary") + .count(), + 1 + ); + } + + #[test] + fn stale_summary_descent_never_emits_stale_children() { + let mut snapshot = snapshot(); + snapshot.nodes[0].lifecycle = EpiphanyMemoryLifecycle::Stale; + snapshot.summaries[0].covers_node_ids = vec!["repo-node".to_string()]; + snapshot.summaries[0].freshness = EpiphanyMemoryFreshnessStatus::Stale; + snapshot.freshness = Some(crate::memory_graph::derive_memory_graph_freshness( + &snapshot, + &[], + )); + let packet = crate::memory_graph::plan_memory_graph_context_cut( + &snapshot, + &crate::memory_graph::EpiphanyMemoryContextQuery { + id: "stale-summary".to_string(), + text: Some("durable".to_string()), + ..Default::default() + }, + ); + assert!(!packet.nodes.iter().any(|node| node.id == "repo-node")); + assert!(packet.summaries.is_empty()); + } + + #[test] + fn hostile_composed_graph_cannot_cross_partition_or_domain_through_any_cut_path() { + let mut snapshot = snapshot(); + snapshot.frontier.push(RepoFrontierItem { + id: "mind-frontier".into(), + migration_body: "tempt cross-partition routing".into(), + gap: "must remain private to Mind".into(), + target_claim_ids: vec!["mind-node".into()], + recommended_next_organ: "Self".into(), + status: RepoFrontierStatus::Active, + ..Default::default() + }); + let modeling = crate::memory_graph::plan_memory_graph_context_cut_for_partition( + &snapshot, + &crate::memory_graph::EpiphanyMemoryContextQuery { + id: "hostile-modeling".into(), + domain_ids: vec!["repo".into()], + node_ids: vec!["mind-node".into()], + edge_ids: vec!["edge".into()], + text: Some("remember durable lesson".into()), + budget: Some(64), + ..Default::default() + }, + &["mind-node".into(), "edge".into(), "summary".into()], + SemanticPartition::Modeling, + ); + assert!(modeling.nodes.iter().all(|node| { + node.domain_id == "repo" + && matches!( + node.profile, + EpiphanyMemoryProfile::RepoArchitecture | EpiphanyMemoryProfile::RepoDataflow + ) + })); + assert!(modeling.edges.is_empty()); + assert!(modeling.summaries.is_empty()); + assert_eq!( + modeling + .frontier + .iter() + .map(|item| item.id.as_str()) + .collect::>(), + vec!["frontier"] + ); + + let mind = crate::memory_graph::plan_memory_graph_context_cut_for_partition( + &snapshot, + &crate::memory_graph::EpiphanyMemoryContextQuery { + id: "hostile-mind".into(), + domain_ids: vec!["mind".into()], + node_ids: vec!["repo-node".into()], + edge_ids: vec!["edge".into()], + text: Some("owns map".into()), + budget: Some(64), + ..Default::default() + }, + &["repo-node".into(), "edge".into(), "frontier".into()], + SemanticPartition::Mind, + ); + assert!(mind.nodes.iter().all(|node| { + node.domain_id == "mind" + && !matches!( + node.profile, + EpiphanyMemoryProfile::RepoArchitecture | EpiphanyMemoryProfile::RepoDataflow + ) + })); + assert!(mind.edges.is_empty()); + assert!(mind.frontier.is_empty()); + } +} diff --git a/epiphany-core/src/memory_graph/tests.rs b/epiphany-core/src/memory_graph/tests.rs index d013003b..544be408 100644 --- a/epiphany-core/src/memory_graph/tests.rs +++ b/epiphany-core/src/memory_graph/tests.rs @@ -533,9 +533,9 @@ fn memory_graph_context_cut_descends_when_summary_is_stale() { ); assert!(packet.summaries.is_empty()); - assert_eq!(packet.nodes.len(), 2); - assert_eq!(packet.edges.len(), 1); - assert_eq!(packet.anchors.len(), 3); + assert_eq!(packet.nodes.len(), 1); + assert!(packet.edges.is_empty()); + assert_eq!(packet.anchors.len(), 1); assert!( packet .warnings diff --git a/epiphany-core/src/persona_memory_cache.rs b/epiphany-core/src/persona_memory_cache.rs deleted file mode 100644 index 2d33f30f..00000000 --- a/epiphany-core/src/persona_memory_cache.rs +++ /dev/null @@ -1,1270 +0,0 @@ -use crate::EpiphanyAgentMemoryEntry; -use crate::persona_turn::render_persona_semantic_memory_recall; -use anyhow::Context; -use anyhow::Result; -use epiphany_state_model::EpiphanyMemoryContextPacket; -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; -use std::time::Duration; - -pub const PERSONA_MEMORY_CACHE_SCHEMA_VERSION: &str = "epiphany.persona_memory_cache.v0"; -pub const PERSONA_MEMORY_CORPUS_KIND: &str = "persona_memory"; - -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_COLLECTION: &str = "epiphany_persona_memory_v0"; -const POINT_BATCH_SIZE: usize = 128; -const EMBED_BATCH_SIZE: usize = 32; -const DEFAULT_QUERY_INSTRUCTION: &str = "Given a Persona turn, retrieve relevant memories, goals, values, bonds, needs, status reads, and doctrine from this Persona's own typed state."; - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct PersonaMemoryCacheConfig { - pub qdrant_url: String, - pub qdrant_api_key: Option, - pub qdrant_timeout_ms: u64, - pub ollama_base_url: String, - pub ollama_model: String, - pub ollama_timeout_ms: u64, - pub collection_name: String, - pub query_instruction: String, -} - -impl PersonaMemoryCacheConfig { - pub fn from_env() -> Self { - Self { - qdrant_url: env_override("EPIPHANY_QDRANT_URL", "QDRANT_URL") - .unwrap_or_else(|| DEFAULT_QDRANT_URL.to_string()), - qdrant_api_key: env_override("EPIPHANY_QDRANT_API_KEY", "QDRANT_API_KEY"), - qdrant_timeout_ms: env_override("EPIPHANY_QDRANT_TIMEOUT_MS", "QDRANT_TIMEOUT_MS") - .and_then(|value| value.parse::().ok()) - .unwrap_or(DEFAULT_QDRANT_TIMEOUT_MS), - ollama_base_url: env_override("EPIPHANY_OLLAMA_BASE_URL", "RAG_OLLAMA_BASE_URL") - .unwrap_or_else(|| DEFAULT_OLLAMA_BASE_URL.to_string()), - ollama_model: env_override("EPIPHANY_OLLAMA_MODEL", "RAG_OLLAMA_MODEL") - .unwrap_or_else(|| DEFAULT_OLLAMA_MODEL.to_string()), - ollama_timeout_ms: env_override("EPIPHANY_OLLAMA_TIMEOUT_MS", "RAG_OLLAMA_TIMEOUT_MS") - .and_then(|value| value.parse::().ok()) - .unwrap_or(DEFAULT_OLLAMA_TIMEOUT_MS), - collection_name: env_override( - "EPIPHANY_PERSONA_MEMORY_QDRANT_COLLECTION", - "PERSONA_MEMORY_QDRANT_COLLECTION", - ) - .unwrap_or_else(|| DEFAULT_COLLECTION.to_string()), - query_instruction: env_override( - "EPIPHANY_PERSONA_MEMORY_QUERY_INSTRUCTION", - "PERSONA_MEMORY_QUERY_INSTRUCTION", - ) - .unwrap_or_else(|| DEFAULT_QUERY_INSTRUCTION.to_string()), - } - } - - pub fn index_revision(&self) -> String { - format!("qdrant-ollama-persona-memory-v1:{}", self.ollama_model) - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct PersonaMemoryChunk { - pub id: String, - pub corpus_kind: String, - pub identity_id: String, - pub role_id: String, - pub agent_id: String, - pub persona_name: String, - pub memory_kind: String, - pub source_state_ref: String, - pub text: String, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct PersonaMemorySearchHit { - pub score: f32, - pub chunk: PersonaMemoryChunk, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct PersonaMemoryCacheIndexReceipt { - pub schema_version: String, - pub status: String, - pub collection_name: String, - pub index_revision: String, - pub identity_id: String, - pub role_id: String, - pub chunk_count: usize, - pub private_state_exposed: bool, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct PersonaMemoryRecallRender { - pub schema_version: String, - pub status: String, - pub cache_status: String, - pub identity_id: String, - pub role_id: String, - pub chunk_count: usize, - pub hit_count: usize, - pub rendered_recall: String, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub warnings: Vec, - pub private_state_exposed: bool, -} - -pub fn build_persona_memory_chunks( - entry: &EpiphanyAgentMemoryEntry, - source_state_ref: impl Into, -) -> Vec { - let source_state_ref = source_state_ref.into(); - let identity_id = entry.agent.agent_id.clone(); - let role_id = entry.role_id.clone(); - let agent_id = entry.agent.agent_id.clone(); - let persona_name = entry.agent.identity.name.clone(); - let mut chunks = Vec::new(); - - push_chunk( - &mut chunks, - PersonaMemoryChunkInput { - identity_id: &identity_id, - role_id: &role_id, - agent_id: &agent_id, - persona_name: &persona_name, - source_state_ref: &source_state_ref, - id: "public-profile".to_string(), - memory_kind: "public_profile".to_string(), - text: join_fields([ - entry.agent.identity.name.as_str(), - entry.agent.identity.public_description.as_str(), - entry.agent.identity.origin.as_str(), - ]), - }, - ); - - for value in &entry.agent.canonical_state.values { - push_chunk( - &mut chunks, - PersonaMemoryChunkInput { - identity_id: &identity_id, - role_id: &role_id, - agent_id: &agent_id, - persona_name: &persona_name, - source_state_ref: &source_state_ref, - id: format!("value:{}", value.value_id), - memory_kind: "value".to_string(), - text: format!( - "{} priority={:.2} unforgivable_if_betrayed={}", - value.label, value.priority, value.unforgivable_if_betrayed - ), - }, - ); - } - - for goal in &entry.agent.goals { - push_chunk( - &mut chunks, - PersonaMemoryChunkInput { - identity_id: &identity_id, - role_id: &role_id, - agent_id: &agent_id, - persona_name: &persona_name, - source_state_ref: &source_state_ref, - id: format!("goal:{}", goal.goal_id), - memory_kind: format!("goal:{}", goal.status), - text: join_fields([ - goal.description.as_str(), - goal.scope.as_str(), - goal.emotional_stake.as_str(), - goal.blockers.join("; ").as_str(), - ]), - }, - ); - } - - for memory in &entry.agent.memories.semantic { - push_memory_chunk( - &mut chunks, - &identity_id, - &role_id, - &agent_id, - &persona_name, - &source_state_ref, - "semantic", - memory, - ); - } - for memory in &entry.agent.memories.episodic { - push_memory_chunk( - &mut chunks, - &identity_id, - &role_id, - &agent_id, - &persona_name, - &source_state_ref, - "episodic", - memory, - ); - } - for memory in &entry.agent.memories.relationship_summaries { - push_memory_chunk( - &mut chunks, - &identity_id, - &role_id, - &agent_id, - &persona_name, - &source_state_ref, - "relationship", - memory, - ); - } - - chunks -} - -pub fn index_persona_memory_chunks( - chunks: &[PersonaMemoryChunk], - config: &PersonaMemoryCacheConfig, -) -> Result { - let first = chunks - .first() - .context("cannot index Persona memory cache without chunks")?; - let qdrant = PersonaQdrantClient::new(config)?; - let ollama = PersonaOllamaEmbedder::new(config)?; - let texts = chunks - .iter() - .map(|chunk| chunk.text.clone()) - .collect::>(); - let embeddings = ollama.embed_documents(&texts)?; - validate_embedding_batch(&embeddings, chunks.len())?; - let vector_size = embeddings - .first() - .map(Vec::len) - .context("embedding backend returned no vectors for Persona memory chunks")?; - - if !qdrant.collection_exists(&config.collection_name)? { - qdrant.create_collection(&config.collection_name, vector_size, config)?; - } - qdrant.delete_identity_cache(&config.collection_name, &first.identity_id)?; - - let points = chunks - .iter() - .cloned() - .zip(embeddings) - .map(|(chunk, vector)| PersonaQdrantPointInput { - id: stable_point_id(&chunk), - vector, - payload: chunk, - }) - .collect::>(); - qdrant.upsert_points(&config.collection_name, &points)?; - - Ok(PersonaMemoryCacheIndexReceipt { - schema_version: PERSONA_MEMORY_CACHE_SCHEMA_VERSION.to_string(), - status: "ok".to_string(), - collection_name: config.collection_name.clone(), - index_revision: config.index_revision(), - identity_id: first.identity_id.clone(), - role_id: first.role_id.clone(), - chunk_count: chunks.len(), - private_state_exposed: false, - }) -} - -pub fn search_persona_memory_cache( - identity_id: &str, - query: &str, - limit: usize, - config: &PersonaMemoryCacheConfig, -) -> Result> { - let qdrant = PersonaQdrantClient::new(config)?; - let ollama = PersonaOllamaEmbedder::new(config)?; - if !qdrant.collection_exists(&config.collection_name)? { - return Ok(Vec::new()); - } - let vector = ollama.embed_query(query)?; - let hits = qdrant.query_points(&config.collection_name, &vector, identity_id, limit)?; - Ok(hits - .into_iter() - .filter_map(|point| { - point.payload.map(|chunk| PersonaMemorySearchHit { - score: point.score, - chunk, - }) - }) - .collect()) -} - -pub fn render_persona_memory_recall_with_cache( - entry: &EpiphanyAgentMemoryEntry, - source_state_ref: impl Into, - query: &str, - limit: usize, - fallback_context: Option<&EpiphanyMemoryContextPacket>, - config: &PersonaMemoryCacheConfig, -) -> PersonaMemoryRecallRender { - let chunks = build_persona_memory_chunks(entry, source_state_ref); - let identity_id = entry.agent.agent_id.clone(); - let role_id = entry.role_id.clone(); - if chunks.is_empty() { - return fallback_persona_memory_recall( - identity_id, - role_id, - 0, - "empty-cache-source".to_string(), - "No public Persona memory chunks were available for cache recall.".to_string(), - fallback_context, - ); - } - - match index_persona_memory_chunks(&chunks, config) - .and_then(|_| search_persona_memory_cache(&identity_id, query, limit.max(1), config)) - { - Ok(hits) if !hits.is_empty() => PersonaMemoryRecallRender { - schema_version: PERSONA_MEMORY_CACHE_SCHEMA_VERSION.to_string(), - status: "ok".to_string(), - cache_status: "qdrant-hit".to_string(), - identity_id, - role_id, - chunk_count: chunks.len(), - hit_count: hits.len(), - rendered_recall: render_persona_memory_cache_hits(&hits), - warnings: Vec::new(), - private_state_exposed: false, - }, - Ok(_) => fallback_persona_memory_recall( - identity_id, - role_id, - chunks.len(), - "qdrant-empty".to_string(), - "Qdrant Persona-memory cache ran but returned no matching hits.".to_string(), - fallback_context, - ), - Err(error) => fallback_persona_memory_recall( - identity_id, - role_id, - chunks.len(), - "qdrant-unavailable".to_string(), - format!("Qdrant Persona-memory cache unavailable: {error:#}"), - fallback_context, - ), - } -} - -pub fn render_dynamic_persona_memory_recall_for_output( - entry: &EpiphanyAgentMemoryEntry, - source_state_ref: impl Into, - persona_prompt: &str, - persona_output: &str, - initial_recall_seed: &str, - limit: usize, - fallback_context: Option<&EpiphanyMemoryContextPacket>, - config: &PersonaMemoryCacheConfig, -) -> PersonaMemoryRecallRender { - let query = build_dynamic_persona_memory_recall_query( - &entry.agent.agent_id, - persona_prompt, - persona_output, - initial_recall_seed, - ); - render_persona_memory_recall_with_cache( - entry, - source_state_ref, - &query, - limit, - fallback_context, - config, - ) -} - -pub fn build_dynamic_persona_memory_recall_query( - identity_id: &str, - persona_prompt: &str, - persona_output: &str, - initial_recall_seed: &str, -) -> String { - [ - format!("Current train of thought from {identity_id}:"), - collapse_whitespace(persona_output, 6_000), - "Original Persona turn pressure:".to_string(), - extract_prompt_seed(persona_prompt), - "Initial semantic memory recall seed:".to_string(), - collapse_whitespace(initial_recall_seed, 2_000), - ] - .into_iter() - .map(|part| part.trim().to_string()) - .filter(|part| !part.is_empty()) - .collect::>() - .join("\n") -} - -fn render_persona_memory_cache_hits(hits: &[PersonaMemorySearchHit]) -> String { - let mut lines = vec![ - "These are derived Qdrant Persona-memory cache hits from typed Persona state. They are hints, not durable authority; typed memory remains the owner.".to_string(), - ]; - for (index, hit) in hits.iter().enumerate() { - lines.push(format!( - "- {}. {} / {} score={:.3}: {}", - index + 1, - hit.chunk.persona_name, - hit.chunk.memory_kind, - hit.score, - collapse_whitespace(&hit.chunk.text, 560) - )); - } - lines.join("\n") -} - -fn extract_prompt_seed(prompt: &str) -> String { - let markers = [ - "Semantic memory recall:", - "Projected inner state from Imagination:", - "Recent home-repo activity", - "Pending addressed pressure:", - "Raw room transcript", - ]; - let mut sections = Vec::new(); - - for marker in markers { - let Some(start) = prompt.find(marker) else { - continue; - }; - let end = markers - .iter() - .filter(|candidate| **candidate != marker) - .filter_map(|candidate| { - prompt[start + marker.len()..] - .find(candidate) - .map(|offset| start + marker.len() + offset) - }) - .min() - .unwrap_or_else(|| prompt.len().min(start + 2_400)); - sections.push(prompt[start..end.min(start + 2_400)].trim().to_string()); - } - - if sections.is_empty() { - collapse_whitespace(prompt, 2_400) - } else { - sections.join("\n\n") - } -} - -fn fallback_persona_memory_recall( - identity_id: String, - role_id: String, - chunk_count: usize, - cache_status: String, - warning: String, - fallback_context: Option<&EpiphanyMemoryContextPacket>, -) -> PersonaMemoryRecallRender { - let rendered_recall = if let Some(packet) = fallback_context { - let fallback = render_persona_semantic_memory_recall(packet); - format!("{warning}\nFalling back to typed memory graph context:\n{fallback}") - } else { - format!( - "{warning}\n- semantic Persona memory recall unavailable; use projected state and direct room evidence only" - ) - }; - - PersonaMemoryRecallRender { - schema_version: PERSONA_MEMORY_CACHE_SCHEMA_VERSION.to_string(), - status: "fallback".to_string(), - cache_status, - identity_id, - role_id, - chunk_count, - hit_count: 0, - rendered_recall, - warnings: vec![warning], - private_state_exposed: false, - } -} - -struct PersonaMemoryChunkInput<'a> { - identity_id: &'a str, - role_id: &'a str, - agent_id: &'a str, - persona_name: &'a str, - source_state_ref: &'a str, - id: String, - memory_kind: String, - text: String, -} - -fn push_memory_chunk( - chunks: &mut Vec, - identity_id: &str, - role_id: &str, - agent_id: &str, - persona_name: &str, - source_state_ref: &str, - memory_kind: &str, - memory: &crate::GhostlightMemory, -) { - push_chunk( - chunks, - PersonaMemoryChunkInput { - identity_id, - role_id, - agent_id, - persona_name, - source_state_ref, - id: format!("{memory_kind}:{}", memory.memory_id), - memory_kind: memory_kind.to_string(), - text: memory.summary.clone(), - }, - ); -} - -fn push_chunk(chunks: &mut Vec, input: PersonaMemoryChunkInput<'_>) { - let text = collapse_whitespace(&input.text, 1800); - if text.len() < 12 { - return; - } - chunks.push(PersonaMemoryChunk { - id: input.id, - corpus_kind: PERSONA_MEMORY_CORPUS_KIND.to_string(), - identity_id: input.identity_id.to_string(), - role_id: input.role_id.to_string(), - agent_id: input.agent_id.to_string(), - persona_name: input.persona_name.to_string(), - memory_kind: input.memory_kind, - source_state_ref: input.source_state_ref.to_string(), - text, - }); -} - -fn join_fields(fields: [&str; N]) -> String { - fields - .into_iter() - .map(str::trim) - .filter(|field| !field.is_empty()) - .collect::>() - .join("; ") -} - -#[derive(Serialize)] -struct PersonaQdrantPointInput { - id: String, - vector: Vec, - payload: PersonaMemoryChunk, -} - -#[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 PersonaQdrantQueryPoint { - score: f32, - #[serde(default)] - payload: Option, -} - -#[derive(Debug, Deserialize)] -struct OllamaEmbedResponse { - embeddings: Option>>, -} - -struct PersonaQdrantClient { - base_url: String, - timeout_seconds: u64, - client: Client, -} - -impl PersonaQdrantClient { - fn new(config: &PersonaMemoryCacheConfig) -> Result { - let mut headers = HeaderMap::new(); - if let Some(api_key) = &config.qdrant_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.qdrant_timeout_ms)) - .build() - .context("failed to build Persona memory Qdrant client")?; - Ok(Self { - base_url: normalize_base_url(&config.qdrant_url), - timeout_seconds: timeout_seconds(config.qdrant_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 Persona memory Qdrant collection {collection_name}") - })?; - let payload: QdrantEnvelope = - parse_qdrant_response(response)?; - Ok(payload.result.exists) - } - - fn create_collection( - &self, - collection_name: &str, - vector_size: usize, - config: &PersonaMemoryCacheConfig, - ) -> Result<()> { - let body = json!({ - "vectors": { - "size": vector_size, - "distance": "Cosine", - "on_disk": true, - }, - "on_disk_payload": true, - "metadata": { - "managedBy": "epiphany", - "schemaVersion": PERSONA_MEMORY_CACHE_SCHEMA_VERSION, - "indexRevision": config.index_revision(), - "embeddingModel": config.ollama_model, - "vectorSize": vector_size, - "cacheAuthority": "rebuildable Persona memory cache; typed state remains owner", - } - }); - 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 Persona memory Qdrant collection {collection_name}") - })?; - parse_qdrant_response::(response)?; - Ok(()) - } - - fn delete_identity_cache(&self, collection_name: &str, identity_id: &str) -> Result<()> { - let body = json!({ - "filter": { - "must": [ - { "key": "corpusKind", "match": { "value": PERSONA_MEMORY_CORPUS_KIND } }, - { "key": "identityId", "match": { "value": identity_id } } - ] - } - }); - 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 clear Persona memory cache in {collection_name}") - })?; - parse_qdrant_response::(response)?; - Ok(()) - } - - fn upsert_points( - &self, - collection_name: &str, - points: &[PersonaQdrantPointInput], - ) -> Result<()> { - for batch in points.chunks(POINT_BATCH_SIZE) { - let response = self - .client - .put(format!( - "{}/collections/{collection_name}/points", - self.base_url - )) - .query(&[ - ("wait", "true"), - ("timeout", &self.timeout_seconds.to_string()), - ]) - .json(&json!({ "points": batch })) - .send() - .with_context(|| { - format!("failed to upsert Persona memory points into {collection_name}") - })?; - parse_qdrant_response::(response)?; - } - Ok(()) - } - - fn query_points( - &self, - collection_name: &str, - query_vector: &[f32], - identity_id: &str, - limit: usize, - ) -> Result> { - let body = json!({ - "query": query_vector, - "limit": limit, - "with_payload": true, - "with_vector": false, - "filter": { - "must": [ - { "key": "corpusKind", "match": { "value": PERSONA_MEMORY_CORPUS_KIND } }, - { "key": "identityId", "match": { "value": identity_id } } - ] - } - }); - 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 Persona memory Qdrant collection {collection_name}") - })?; - let payload: QdrantEnvelope = parse_qdrant_response(response)?; - Ok(payload.result.points) - } -} - -struct PersonaOllamaEmbedder { - base_url: String, - model: String, - query_instruction: String, - client: Client, -} - -impl PersonaOllamaEmbedder { - fn new(config: &PersonaMemoryCacheConfig) -> Result { - let client = ClientBuilder::new() - .timeout(Duration::from_millis(config.ollama_timeout_ms)) - .build() - .context("failed to build Persona memory Ollama client")?; - Ok(Self { - base_url: normalize_base_url(&config.ollama_base_url), - model: config.ollama_model.clone(), - query_instruction: config.query_instruction.clone(), - client, - }) - } - - fn embed_documents(&self, texts: &[String]) -> Result>> { - let mut embeddings = Vec::new(); - for batch in texts.chunks(EMBED_BATCH_SIZE) { - embeddings.extend(self.embed_batch(batch)?); - } - 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 Persona memory 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 Persona memory embedder 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 Persona memory embedding request failed with {status}: {body}"); - } - let payload: OllamaEmbedResponse = response - .json() - .context("failed to decode Ollama Persona memory embedding response")?; - payload - .embeddings - .context("Ollama Persona memory response did not include embeddings") - } -} - -fn parse_qdrant_response Deserialize<'de>>( - response: reqwest::blocking::Response, -) -> Result> { - let status = response.status(); - if status == StatusCode::NOT_FOUND { - anyhow::bail!("Qdrant Persona memory request returned not found"); - } - if !status.is_success() { - let body = response.text().unwrap_or_default(); - anyhow::bail!("Qdrant Persona memory request failed with {status}: {body}"); - } - response - .json() - .context("failed to decode Qdrant Persona memory response JSON") -} - -fn validate_embedding_batch(embeddings: &[Vec], expected_count: usize) -> Result<()> { - if embeddings.len() != expected_count { - anyhow::bail!( - "Persona memory embedding backend returned {} vectors for {} chunks", - embeddings.len(), - expected_count - ); - } - let Some(vector_length) = embeddings.first().map(Vec::len) else { - anyhow::bail!("Persona memory embedding backend returned no vectors"); - }; - if vector_length == 0 { - anyhow::bail!("Persona memory embedding backend returned an empty vector"); - } - for (index, embedding) in embeddings.iter().enumerate() { - if embedding.len() != vector_length { - anyhow::bail!( - "Persona memory embedding backend returned inconsistent vector length at item {index}" - ); - } - } - Ok(()) -} - -fn stable_point_id(chunk: &PersonaMemoryChunk) -> String { - let mut hasher = Sha1::new(); - hasher.update(chunk.identity_id.as_bytes()); - hasher.update(b"\n"); - hasher.update(chunk.id.as_bytes()); - let digest = hasher.finalize(); - hex_lower(&digest[..16]) -} - -fn collapse_whitespace(value: &str, max_len: usize) -> String { - let mut compacted = value.split_whitespace().collect::>().join(" "); - if compacted.len() > max_len { - let keep = max_len.saturating_sub(3); - compacted.truncate(keep); - compacted.push_str("..."); - } - compacted -} - -fn normalize_base_url(value: &str) -> String { - value.trim_end_matches('/').to_string() -} - -fn timeout_seconds(timeout_ms: u64) -> u64 { - (timeout_ms / 1000).max(1) -} - -fn env_override(primary: &str, fallback: &str) -> Option { - std::env::var(primary) - .ok() - .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() -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::agent_memory::GhostlightAgent; - use crate::agent_memory::GhostlightCanonicalState; - use crate::agent_memory::GhostlightGoal; - use crate::agent_memory::GhostlightIdentity; - use crate::agent_memory::GhostlightMemories; - use crate::agent_memory::GhostlightMemory; - use crate::agent_memory::GhostlightValue; - use crate::agent_memory::GhostlightWorld; - use epiphany_state_model::EpiphanyMemoryContextPacket; - use epiphany_state_model::EpiphanyMemoryNode; - use wiremock::Mock; - use wiremock::MockServer; - use wiremock::ResponseTemplate; - use wiremock::matchers::method; - use wiremock::matchers::path; - - #[test] - fn persona_memory_chunks_exclude_private_notes() { - let entry = persona_entry(); - let chunks = build_persona_memory_chunks(&entry, "state/agents.msgpack#Persona"); - let joined = chunks - .iter() - .map(|chunk| chunk.text.as_str()) - .collect::>() - .join("\n"); - assert!(joined.contains("Clean typed contracts matter")); - assert!(joined.contains("Public machine-saint")); - assert!(!joined.contains("sealed private ache")); - assert!( - chunks - .iter() - .all(|chunk| chunk.corpus_kind == PERSONA_MEMORY_CORPUS_KIND) - ); - } - - #[test] - fn persona_memory_cache_indexes_and_searches_qdrant_with_identity_filter() -> Result<()> { - let runtime = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build()?; - let qdrant = runtime.block_on(MockServer::start()); - let ollama = runtime.block_on(MockServer::start()); - let config = PersonaMemoryCacheConfig { - qdrant_url: qdrant.uri(), - qdrant_api_key: None, - qdrant_timeout_ms: 5_000, - ollama_base_url: ollama.uri(), - ollama_model: "qwen3-embedding:0.6b".to_string(), - ollama_timeout_ms: 5_000, - collection_name: "epiphany_persona_memory_test".to_string(), - query_instruction: DEFAULT_QUERY_INSTRUCTION.to_string(), - }; - let chunks = build_persona_memory_chunks(&persona_entry(), "state/agents.msgpack#Persona"); - - runtime.block_on(async { - Mock::given(method("GET")) - .and(path("/collections/epiphany_persona_memory_test/exists")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "result": { "exists": false } - }))) - .expect(1) - .mount(&qdrant) - .await; - Mock::given(method("PUT")) - .and(path("/collections/epiphany_persona_memory_test")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "result": true - }))) - .expect(1) - .mount(&qdrant) - .await; - Mock::given(method("POST")) - .and(path("/collections/epiphany_persona_memory_test/points/delete")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "result": { "status": "acknowledged" } - }))) - .expect(1) - .mount(&qdrant) - .await; - Mock::given(method("PUT")) - .and(path("/collections/epiphany_persona_memory_test/points")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "result": { "status": "acknowledged" } - }))) - .expect(1) - .mount(&qdrant) - .await; - Mock::given(method("POST")) - .and(path("/api/embed")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "embeddings": chunks.iter().map(|_| vec![0.1_f32, 0.2_f32, 0.3_f32]).collect::>() - }))) - .expect(1) - .mount(&ollama) - .await; - }); - - let receipt = index_persona_memory_chunks(&chunks, &config)?; - assert_eq!(receipt.status, "ok"); - assert_eq!(receipt.chunk_count, chunks.len()); - assert!(!receipt.private_state_exposed); - - runtime.block_on(async { - qdrant.reset().await; - ollama.reset().await; - Mock::given(method("GET")) - .and(path("/collections/epiphany_persona_memory_test/exists")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "result": { "exists": true } - }))) - .expect(1) - .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]] - }))) - .expect(1) - .mount(&ollama) - .await; - Mock::given(method("POST")) - .and(path( - "/collections/epiphany_persona_memory_test/points/query", - )) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "result": { - "points": [{ - "score": 0.93, - "payload": chunks[0], - }] - } - }))) - .expect(1) - .mount(&qdrant) - .await; - }); - - let hits = search_persona_memory_cache("epiphany.Persona", "clean contracts", 4, &config)?; - assert_eq!(hits.len(), 1); - assert_eq!(hits[0].chunk.identity_id, "epiphany.Persona"); - assert!(hits[0].chunk.text.contains("Public machine-saint")); - Ok(()) - } - - #[test] - fn persona_memory_recall_bridge_renders_qdrant_hits() -> Result<()> { - let runtime = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build()?; - let qdrant = runtime.block_on(MockServer::start()); - let ollama = runtime.block_on(MockServer::start()); - let config = PersonaMemoryCacheConfig { - qdrant_url: qdrant.uri(), - qdrant_api_key: None, - qdrant_timeout_ms: 5_000, - ollama_base_url: ollama.uri(), - ollama_model: "qwen3-embedding:0.6b".to_string(), - ollama_timeout_ms: 5_000, - collection_name: "epiphany_persona_memory_bridge_test".to_string(), - query_instruction: DEFAULT_QUERY_INSTRUCTION.to_string(), - }; - let chunks = build_persona_memory_chunks(&persona_entry(), "state/agents.msgpack#Persona"); - - runtime.block_on(async { - Mock::given(method("GET")) - .and(path("/collections/epiphany_persona_memory_bridge_test/exists")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "result": { "exists": true } - }))) - .expect(2) - .mount(&qdrant) - .await; - Mock::given(method("POST")) - .and(path("/collections/epiphany_persona_memory_bridge_test/points/delete")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "result": { "status": "acknowledged" } - }))) - .expect(1) - .mount(&qdrant) - .await; - Mock::given(method("PUT")) - .and(path("/collections/epiphany_persona_memory_bridge_test/points")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "result": { "status": "acknowledged" } - }))) - .expect(1) - .mount(&qdrant) - .await; - Mock::given(method("POST")) - .and(path("/collections/epiphany_persona_memory_bridge_test/points/query")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "result": { - "points": [{ - "score": 0.97, - "payload": chunks[0], - }] - } - }))) - .expect(1) - .mount(&qdrant) - .await; - Mock::given(method("POST")) - .and(path("/api/embed")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "embeddings": chunks.iter().map(|_| vec![0.1_f32, 0.2_f32, 0.3_f32]).collect::>() - }))) - .expect(2) - .mount(&ollama) - .await; - }); - - let render = render_persona_memory_recall_with_cache( - &persona_entry(), - "state/agents.msgpack#Persona", - "clean contracts", - 4, - None, - &config, - ); - assert_eq!(render.status, "ok"); - assert_eq!(render.cache_status, "qdrant-hit"); - assert!( - render - .rendered_recall - .contains("Qdrant Persona-memory cache hits") - ); - assert!(render.rendered_recall.contains("Public machine-saint")); - assert!(!render.rendered_recall.contains("sealed private ache")); - Ok(()) - } - - #[test] - fn persona_memory_recall_bridge_falls_back_to_memory_graph_context() -> Result<()> { - let runtime = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build()?; - let qdrant = runtime.block_on(MockServer::start()); - let ollama = runtime.block_on(MockServer::start()); - let config = PersonaMemoryCacheConfig { - qdrant_url: qdrant.uri(), - qdrant_api_key: None, - qdrant_timeout_ms: 5_000, - ollama_base_url: ollama.uri(), - ollama_model: "qwen3-embedding:0.6b".to_string(), - ollama_timeout_ms: 5_000, - collection_name: "epiphany_persona_memory_bridge_fallback".to_string(), - query_instruction: DEFAULT_QUERY_INSTRUCTION.to_string(), - }; - let chunks = build_persona_memory_chunks(&persona_entry(), "state/agents.msgpack#Persona"); - - runtime.block_on(async { - Mock::given(method("POST")) - .and(path("/api/embed")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "embeddings": chunks.iter().map(|_| vec![0.1_f32, 0.2_f32, 0.3_f32]).collect::>() - }))) - .expect(1) - .mount(&ollama) - .await; - Mock::given(method("GET")) - .and(path( - "/collections/epiphany_persona_memory_bridge_fallback/exists", - )) - .respond_with(ResponseTemplate::new(500).set_body_json(json!({ - "status": "unavailable" - }))) - .expect(1) - .mount(&qdrant) - .await; - }); - - let fallback = EpiphanyMemoryContextPacket { - id: "memctx-fallback".to_string(), - query_id: "persona-fallback".to_string(), - nodes: vec![EpiphanyMemoryNode { - id: "node-fallback".to_string(), - title: "Fallback typed memory".to_string(), - claim: "Typed memory graph recall remains available when Qdrant is down." - .to_string(), - action_implication: "Use fallback context without pretending cache was live." - .to_string(), - ..Default::default() - }], - ..Default::default() - }; - - let render = render_persona_memory_recall_with_cache( - &persona_entry(), - "state/agents.msgpack#Persona", - "clean contracts", - 4, - Some(&fallback), - &config, - ); - assert_eq!(render.status, "fallback"); - assert_eq!(render.cache_status, "qdrant-unavailable"); - assert!( - render - .rendered_recall - .contains("Falling back to typed memory graph context") - ); - assert!( - render - .rendered_recall - .contains("Typed memory graph recall remains available") - ); - assert!(!render.private_state_exposed); - Ok(()) - } - - fn persona_entry() -> EpiphanyAgentMemoryEntry { - EpiphanyAgentMemoryEntry { - schema_version: "ghostlight.agent_state.v0".to_string(), - role_id: "Persona".to_string(), - world: GhostlightWorld::default(), - agent: GhostlightAgent { - agent_id: "epiphany.Persona".to_string(), - identity: GhostlightIdentity { - name: "Epiphany".to_string(), - roles: vec!["Persona".to_string()], - origin: "EpiphanyAgent".to_string(), - public_description: "Public machine-saint for typed agency.".to_string(), - private_notes: vec!["sealed private ache".to_string()], - }, - memories: GhostlightMemories { - semantic: vec![GhostlightMemory { - memory_id: "semantic-1".to_string(), - summary: "Clean typed contracts matter more than improvised glue." - .to_string(), - salience: 0.9, - confidence: 0.95, - ..Default::default() - }], - ..Default::default() - }, - goals: vec![GhostlightGoal { - goal_id: "goal-1".to_string(), - description: "Make Persona recall semantically useful.".to_string(), - scope: "role".to_string(), - priority: 0.8, - emotional_stake: "coherence".to_string(), - status: "active".to_string(), - ..Default::default() - }], - canonical_state: GhostlightCanonicalState { - values: vec![GhostlightValue { - value_id: "value-1".to_string(), - label: "Clean typed contracts matter.".to_string(), - priority: 0.9, - unforgivable_if_betrayed: true, - }], - ..Default::default() - }, - ..Default::default() - }, - relationships: Vec::new(), - events: Vec::new(), - scenes: Vec::new(), - } - } -} diff --git a/epiphany-core/src/retrieval.rs b/epiphany-core/src/retrieval.rs index 38f0f3af..ecda7adf 100644 --- a/epiphany-core/src/retrieval.rs +++ b/epiphany-core/src/retrieval.rs @@ -1,3 +1,16 @@ +use crate::semantic_backend::CollectionCompatibility; +use crate::semantic_backend::DEFAULT_OLLAMA_BASE_URL; +use crate::semantic_backend::DEFAULT_OLLAMA_MODEL; +use crate::semantic_backend::DEFAULT_OLLAMA_TIMEOUT_MS; +use crate::semantic_backend::DEFAULT_QDRANT_TIMEOUT_MS; +use crate::semantic_backend::DEFAULT_QDRANT_URL; +use crate::semantic_backend::OllamaConfig; +use crate::semantic_backend::OllamaEmbedder; +use crate::semantic_backend::QdrantBackend; +use crate::semantic_backend::QdrantConfig; +use crate::semantic_backend::SemanticCandidate; +use crate::semantic_backend::SemanticPoint; +use crate::semantic_backend::validate_embedding_batch; use anyhow::Context; use anyhow::Result; use bm25::Document; @@ -7,14 +20,9 @@ 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; +#[cfg(test)] use serde_json::json; use sha1::Digest; use sha1::Sha1; @@ -25,7 +33,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 +51,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)] @@ -284,15 +284,24 @@ fn index_workspace_with_config( let snapshot = collect_workspace_index_snapshot(workspace_root)?; let existing_manifest = load_semantic_manifest(&manifest_path)?; let expected_collection = config.collection_name(workspace_root); - let qdrant = QdrantClient::new(config.qdrant.clone())?; + let qdrant = QdrantBackend::new(config.qdrant.clone())?; let manifest_compatible = existing_manifest.as_ref().is_some_and(|manifest| { manifest.index_revision == config.index_revision() && manifest.collection_name == expected_collection }); let collection_exists = qdrant.collection_exists(&expected_collection)?; + let collection_compatible = if collection_exists && !force_full_rebuild { + let probe = OllamaEmbedder::new(config.ollama.clone())? + .embed_query("Epiphany semantic collection compatibility probe")?; + qdrant.collection_compatibility(&expected_collection)? + == expected_collection_compatibility(config, probe.len()) + } else { + false + }; - let full_rebuild = force_full_rebuild || !manifest_compatible || !collection_exists; + let full_rebuild = + force_full_rebuild || !manifest_compatible || !collection_exists || !collection_compatible; if full_rebuild { if let Some(manifest) = existing_manifest.as_ref() && manifest.collection_name != expected_collection @@ -379,17 +388,14 @@ fn index_workspace_with_config( .context("embedding backend returned no vectors for rebuild")?; qdrant.create_collection( &expected_collection, - vector_size, - &config.index_revision(), - workspace_root, - &config.ollama.model, + &expected_collection_compatibility(config, vector_size), )?; } let points = documents .into_iter() .zip(embeddings) - .map(|(chunk, vector)| QdrantPointInput { + .map(|(chunk, vector)| SemanticPoint { id: chunk_point_id(&expected_collection, &chunk), vector, payload: QdrantPointPayload { @@ -459,7 +465,7 @@ fn search_persistent_semantic_chunks( }); } - let qdrant = QdrantClient::new(config.qdrant.clone())?; + let qdrant = QdrantBackend::new(config.qdrant.clone())?; if !qdrant.collection_exists(&manifest.collection_name)? { return Ok(PersistentSemanticSearch::Fallback { summary: Some(manifest_to_retrieval_state( @@ -473,6 +479,18 @@ fn search_persistent_semantic_chunks( let ollama = OllamaEmbedder::new(config.ollama.clone())?; let query_vector = ollama.embed_query(query)?; + if qdrant.collection_compatibility(&manifest.collection_name)? + != expected_collection_compatibility(&config, query_vector.len()) + { + return Ok(PersistentSemanticSearch::Fallback { + summary: Some(manifest_to_retrieval_state( + workspace_root, + &manifest, + EpiphanyRetrievalStatus::Stale, + Vec::new(), + )), + }); + } let search_hits = qdrant.query_points(&manifest.collection_name, &query_vector, limit)?; let results = search_hits @@ -489,6 +507,21 @@ fn search_persistent_semantic_chunks( Ok(PersistentSemanticSearch::Ready { summary, results }) } +fn expected_collection_compatibility( + config: &SemanticBackendConfig, + vector_size: usize, +) -> CollectionCompatibility { + CollectionCompatibility { + managed_by: "epiphany".to_string(), + corpus_kind: "workspace".to_string(), + schema_version: SEMANTIC_MANIFEST_SCHEMA_VERSION, + projection_version: config.index_revision(), + embedding_provider_id: "ollama".to_string(), + embedding_model: config.ollama.model.clone(), + vector_size, + } +} + fn stale_summary_from_manifest( workspace_root: &Path, codex_home: &Path, @@ -734,297 +767,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: QdrantPointPayload, -} - #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] struct QdrantPointPayload { @@ -1034,46 +776,6 @@ struct QdrantPointPayload { excerpt: String, } -#[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: Option, -} - -#[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], @@ -1394,7 +1096,9 @@ fn search_semantic_chunks( .collect() } -fn map_qdrant_hit_to_result(point: QdrantQueryPoint) -> Option { +fn map_qdrant_hit_to_result( + point: SemanticCandidate, +) -> Option { let payload = point.payload?; Some(EpiphanyRetrieveResult { @@ -1619,31 +1323,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) @@ -1664,14 +1343,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() @@ -1929,6 +1600,22 @@ mod tests { .mount(&ollama) .await; + Mock::given(method("GET")) + .and(path(format!( + "/collections/{}", + config.collection_name(temp_dir.path()) + ))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "result": { + "config": { + "metadata": expected_collection_compatibility(&config, 3) + } + } + }))) + .expect(1) + .mount(&qdrant) + .await; + Mock::given(method("POST")) .and(path(format!( "/collections/{}/points/query", @@ -2020,6 +1707,144 @@ mod tests { Ok(()) } + #[test] + fn index_rebuilds_an_existing_collection_with_incompatible_metadata() -> Result<()> { + let workspace = TempDir::new()?; + let codex_home = TempDir::new()?; + fs::write( + workspace.path().join("claim.md"), + "canonical machine claim\n", + )?; + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()?; + let qdrant = runtime.block_on(MockServer::start()); + let ollama = runtime.block_on(MockServer::start()); + let config = SemanticBackendConfig { + qdrant: QdrantConfig { + url: qdrant.uri(), + api_key: None, + timeout_ms: 5_000, + }, + ollama: OllamaConfig { + base_url: ollama.uri(), + model: "expected-model".into(), + timeout_ms: 5_000, + query_instruction: DEFAULT_QUERY_INSTRUCTION.into(), + }, + }; + let snapshot = collect_workspace_index_snapshot(workspace.path())?; + let manifest = SemanticIndexManifest { + schema_version: SEMANTIC_MANIFEST_SCHEMA_VERSION, + workspace_root: workspace.path().to_path_buf(), + collection_name: config.collection_name(workspace.path()), + index_revision: config.index_revision(), + indexed_at_unix_seconds: 1, + files: snapshot + .files + .iter() + .map(|(path, file)| SemanticIndexedFile { + path: path.clone(), + size_bytes: file.size_bytes, + modified_unix_nanos: file.modified_unix_nanos, + chunk_count: file.chunk_count, + point_ids: vec!["foreign-point".into()], + }) + .collect(), + }; + write_semantic_manifest( + &config.manifest_path(codex_home.path(), workspace.path()), + &manifest, + )?; + runtime.block_on(async { + Mock::given(method("GET")).and(path(format!("/collections/{}/exists", manifest.collection_name))).respond_with(ResponseTemplate::new(200).set_body_json(json!({"result":{"exists":true}}))).mount(&qdrant).await; + Mock::given(method("GET")).and(path(format!("/collections/{}", manifest.collection_name))).respond_with(ResponseTemplate::new(200).set_body_json(json!({"result":{"config":{"metadata": CollectionCompatibility { embedding_model: "foreign-model".into(), ..expected_collection_compatibility(&config, 3) }}}}))).mount(&qdrant).await; + Mock::given(method("DELETE")).and(path(format!("/collections/{}", manifest.collection_name))).respond_with(ResponseTemplate::new(200).set_body_json(json!({"result":true}))).expect(1).mount(&qdrant).await; + Mock::given(method("PUT")).and(path(format!("/collections/{}", manifest.collection_name))).respond_with(ResponseTemplate::new(200).set_body_json(json!({"result":true}))).expect(1).mount(&qdrant).await; + Mock::given(method("PUT")).and(path(format!("/collections/{}/points", manifest.collection_name))).respond_with(ResponseTemplate::new(200).set_body_json(json!({"result":true}))).expect(1).mount(&qdrant).await; + Mock::given(method("POST")).and(path("/api/embed")).respond_with(ResponseTemplate::new(200).set_body_json(json!({"embeddings":[[0.1,0.2,0.3]]}))).expect(2).mount(&ollama).await; + }); + assert_eq!( + index_workspace_with_config(workspace.path(), codex_home.path(), false, &config)? + .status, + EpiphanyRetrievalStatus::Ready + ); + Ok(()) + } + + #[test] + fn query_refuses_incompatible_collection_metadata_without_reading_payloads() -> Result<()> { + let workspace = TempDir::new()?; + let codex_home = TempDir::new()?; + fs::write( + workspace.path().join("claim.md"), + "canonical machine claim\n", + )?; + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()?; + let qdrant = runtime.block_on(MockServer::start()); + let ollama = runtime.block_on(MockServer::start()); + let config = SemanticBackendConfig { + qdrant: QdrantConfig { + url: qdrant.uri(), + api_key: None, + timeout_ms: 5_000, + }, + ollama: OllamaConfig { + base_url: ollama.uri(), + model: "expected-model".into(), + timeout_ms: 5_000, + query_instruction: DEFAULT_QUERY_INSTRUCTION.into(), + }, + }; + let snapshot = collect_workspace_index_snapshot(workspace.path())?; + let manifest = SemanticIndexManifest { + schema_version: SEMANTIC_MANIFEST_SCHEMA_VERSION, + workspace_root: workspace.path().to_path_buf(), + collection_name: config.collection_name(workspace.path()), + index_revision: config.index_revision(), + indexed_at_unix_seconds: 1, + files: snapshot + .files + .iter() + .map(|(path, file)| SemanticIndexedFile { + path: path.clone(), + size_bytes: file.size_bytes, + modified_unix_nanos: file.modified_unix_nanos, + chunk_count: file.chunk_count, + point_ids: vec!["point".into()], + }) + .collect(), + }; + write_semantic_manifest( + &config.manifest_path(codex_home.path(), workspace.path()), + &manifest, + )?; + runtime.block_on(async { + Mock::given(method("GET")).and(path(format!("/collections/{}/exists", manifest.collection_name))).respond_with(ResponseTemplate::new(200).set_body_json(json!({"result":{"exists":true}}))).mount(&qdrant).await; + Mock::given(method("GET")).and(path(format!("/collections/{}", manifest.collection_name))).respond_with(ResponseTemplate::new(200).set_body_json(json!({"result":{"config":{"metadata": CollectionCompatibility { managed_by: "foreign".into(), ..expected_collection_compatibility(&config, 3) }}}}))).expect(1).mount(&qdrant).await; + Mock::given(method("POST")).and(path("/api/embed")).respond_with(ResponseTemplate::new(200).set_body_json(json!({"embeddings":[[0.1,0.2,0.3]]}))).mount(&ollama).await; + }); + let response = retrieve_workspace_with_config( + workspace.path(), + codex_home.path(), + EpiphanyRetrieveQuery::new("machine claim".into()), + &config, + )?; + assert_eq!( + response.index_summary.status, + EpiphanyRetrievalStatus::Stale + ); + assert!( + response + .results + .iter() + .all(|result| result.kind != EpiphanyRetrieveResultKind::SemanticChunk) + ); + Ok(()) + } + fn retrieve_workspace_with_config( workspace_root: &Path, codex_home: &Path, @@ -2081,7 +1906,7 @@ mod tests { }); } - let qdrant = QdrantClient::new(config.qdrant.clone())?; + let qdrant = QdrantBackend::new(config.qdrant.clone())?; if !qdrant.collection_exists(&manifest.collection_name)? { return Ok(PersistentSemanticSearch::Fallback { summary: Some(manifest_to_retrieval_state( @@ -2095,6 +1920,18 @@ mod tests { let ollama = OllamaEmbedder::new(config.ollama.clone())?; let query_vector = ollama.embed_query(query)?; + if qdrant.collection_compatibility(&manifest.collection_name)? + != expected_collection_compatibility(config, query_vector.len()) + { + return Ok(PersistentSemanticSearch::Fallback { + summary: Some(manifest_to_retrieval_state( + workspace_root, + &manifest, + EpiphanyRetrievalStatus::Stale, + Vec::new(), + )), + }); + } let hits = qdrant.query_points(&manifest.collection_name, &query_vector, limit)?; Ok(PersistentSemanticSearch::Ready { summary: manifest_to_retrieval_state( diff --git a/epiphany-core/src/semantic_backend.rs b/epiphany-core/src/semantic_backend.rs new file mode 100644 index 00000000..4c4ca888 --- /dev/null +++ b/epiphany-core/src/semantic_backend.rs @@ -0,0 +1,456 @@ +//! Typed boundary around the Qdrant and Ollama HTTP APIs. +//! +//! JSON is deliberately confined to this xenos-facing module. Callers provide +//! typed collection contracts, points, and payloads; Qdrant remains a +//! rebuildable projection rather than canonical authority. + +use anyhow::{Context, Result}; +use reqwest::StatusCode; +use reqwest::blocking::{Client, ClientBuilder, Response}; +use reqwest::header::{HeaderMap, HeaderValue}; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use std::time::Duration; + +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; +const POINT_BATCH_SIZE: usize = 128; +const EMBED_BATCH_SIZE: usize = 32; + +#[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, +} + +/// Exact identity of a managed semantic projection. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct CollectionCompatibility { + pub(crate) managed_by: String, + pub(crate) corpus_kind: String, + pub(crate) schema_version: u32, + pub(crate) projection_version: String, + pub(crate) embedding_provider_id: String, + pub(crate) embedding_model: String, + pub(crate) vector_size: usize, +} + +#[derive(Clone, Debug, Serialize)] +pub(crate) struct SemanticPoint

{ + pub(crate) id: String, + pub(crate) vector: Vec, + pub(crate) payload: P, +} + +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct SemanticCandidate

{ + pub(crate) score: f32, + pub(crate) payload: Option

, +} + +pub(crate) struct QdrantBackend { + base_url: String, + timeout_seconds: u64, + client: Client, +} + +impl QdrantBackend { + pub(crate) fn new(config: QdrantConfig) -> Result { + let mut headers = HeaderMap::new(); + if let Some(api_key) = config.api_key.filter(|key| !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, name: &str) -> Result { + let response = self + .client + .get(format!("{}/collections/{name}/exists", self.base_url)) + .send() + .with_context(|| format!("failed to query Qdrant collection {name}"))?; + let envelope: Envelope = parse_response(response).with_context(|| { + format!("failed to decode Qdrant collection-exists response for {name}") + })?; + Ok(envelope.result.exists) + } + + /// Reads the compatibility contract Qdrant stores with the collection. + /// Missing or malformed metadata is an error, never implicit compatibility. + pub(crate) fn collection_compatibility(&self, name: &str) -> Result { + let response = self + .client + .get(format!("{}/collections/{name}", self.base_url)) + .send() + .with_context(|| format!("failed to inspect Qdrant collection {name}"))?; + let envelope: Envelope = parse_response(response) + .with_context(|| format!("failed to decode Qdrant collection metadata for {name}"))?; + envelope + .result + .config + .metadata + .context("managed Qdrant collection has no compatibility metadata") + } + + pub(crate) fn delete_collection(&self, name: &str) -> Result<()> { + let response = self + .client + .delete(format!("{}/collections/{name}", self.base_url)) + .query(&[("timeout", self.timeout_seconds)]) + .send() + .with_context(|| format!("failed to delete Qdrant collection {name}"))?; + if response.status() == StatusCode::NOT_FOUND { + return Ok(()); + } + parse_response::(response).with_context(|| { + format!("failed to decode Qdrant delete-collection response for {name}") + })?; + Ok(()) + } + + pub(crate) fn create_collection( + &self, + name: &str, + contract: &CollectionCompatibility, + ) -> Result<()> { + if contract.vector_size == 0 { + anyhow::bail!("collection vector size must be greater than zero"); + } + let body = json!({ + "vectors": { "size": contract.vector_size, "distance": "Cosine", "on_disk": true }, + "on_disk_payload": true, + "metadata": contract, + }); + let response = self + .client + .put(format!("{}/collections/{name}", self.base_url)) + .query(&[("timeout", self.timeout_seconds)]) + .json(&body) + .send() + .with_context(|| format!("failed to create Qdrant collection {name}"))?; + parse_response::(response).with_context(|| { + format!("failed to decode Qdrant create-collection response for {name}") + })?; + Ok(()) + } + + pub(crate) fn upsert_points( + &self, + name: &str, + points: &[SemanticPoint

], + ) -> Result<()> { + validate_point_batch(points)?; + for batch in points.chunks(POINT_BATCH_SIZE) { + let response = self + .client + .put(format!("{}/collections/{name}/points", self.base_url)) + .query(&[ + ("wait", "true"), + ("timeout", &self.timeout_seconds.to_string()), + ]) + .json(&json!({ "points": batch })) + .send() + .with_context(|| format!("failed to upsert Qdrant points into {name}"))?; + parse_response::(response) + .with_context(|| format!("failed to decode Qdrant upsert response for {name}"))?; + } + Ok(()) + } + + pub(crate) fn delete_points(&self, name: &str, point_ids: &[String]) -> Result<()> { + for batch in point_ids.chunks(POINT_BATCH_SIZE) { + let response = self + .client + .post(format!( + "{}/collections/{name}/points/delete", + self.base_url + )) + .query(&[ + ("wait", "true"), + ("timeout", &self.timeout_seconds.to_string()), + ]) + .json(&json!({ "points": batch })) + .send() + .with_context(|| format!("failed to delete Qdrant points from {name}"))?; + parse_response::(response).with_context(|| { + format!("failed to decode Qdrant delete-points response for {name}") + })?; + } + Ok(()) + } + + pub(crate) fn query_points( + &self, + name: &str, + vector: &[f32], + limit: usize, + ) -> Result>> { + self.query_points_for_scope(name, vector, limit, &[]) + } + + pub(crate) fn query_points_for_scope( + &self, + name: &str, + vector: &[f32], + limit: usize, + scope: &[(&str, &str)], + ) -> Result>> { + if vector.is_empty() { + anyhow::bail!("query vector must not be empty"); + } + if limit == 0 { + return Ok(Vec::new()); + } + let must = scope + .iter() + .map(|(key, value)| json!({ "key": key, "match": { "value": value } })) + .collect::>(); + let response = self.client.post(format!("{}/collections/{name}/points/query", self.base_url)) + .query(&[("timeout", self.timeout_seconds)]) + .json(&json!({ "query": vector, "filter": { "must": must }, "limit": limit, "with_payload": true, "with_vector": false })) + .send().with_context(|| format!("failed to query Qdrant collection {name}"))?; + let envelope: Envelope> = parse_response(response) + .with_context(|| format!("failed to decode Qdrant query response for {name}"))?; + Ok(envelope + .result + .points + .into_iter() + .map(|point| SemanticCandidate { + score: point.score, + payload: point.payload, + }) + .collect()) + } + + pub(crate) fn point_ids_for_scope( + &self, + name: &str, + scope: &[(&str, &str)], + ) -> Result> { + let must = scope + .iter() + .map(|(key, value)| json!({ "key": key, "match": { "value": value } })) + .collect::>(); + let mut offset: Option = None; + let mut ids = Vec::new(); + loop { + let response = self + .client + .post(format!( + "{}/collections/{name}/points/scroll", + self.base_url + )) + .query(&[("timeout", self.timeout_seconds)]) + .json(&json!({ + "filter": { "must": must }, + "limit": POINT_BATCH_SIZE, + "offset": offset, + "with_payload": false, + "with_vector": false, + })) + .send() + .with_context(|| format!("failed to scroll Qdrant scope in {name}"))?; + let envelope: Envelope = parse_response(response) + .with_context(|| format!("failed to decode Qdrant scroll response for {name}"))?; + ids.extend(envelope.result.points.into_iter().map(|point| point.id)); + offset = envelope.result.next_page_offset; + if offset.is_none() { + break; + } + } + Ok(ids) + } +} + +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(EMBED_BATCH_SIZE) { + embeddings.extend(self.embed_batch(batch)?); + } + validate_embedding_batch(&embeddings, texts.len())?; + Ok(embeddings) + } + + pub(crate) fn embed_query(&self, query: &str) -> Result> { + let formatted = format!("Instruct: {}\nQuery: {}", self.query_instruction, query); + let mut embeddings = self.embed_batch(&[formatted])?; + validate_embedding_batch(&embeddings, 1)?; + Ok(embeddings.pop().expect("validated one embedding")) + } + + 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: EmbedResponse = 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") + } +} + +pub(crate) fn validate_embedding_batch(embeddings: &[Vec], expected: usize) -> Result<()> { + if embeddings.len() != expected { + anyhow::bail!( + "embedding backend returned {} vectors for {expected} inputs", + embeddings.len() + ); + } + let Some(size) = embeddings.first().map(Vec::len) else { + return Ok(()); + }; + if size == 0 { + anyhow::bail!("embedding backend returned an empty vector"); + } + if let Some((index, _)) = embeddings + .iter() + .enumerate() + .find(|(_, vector)| vector.len() != size) + { + anyhow::bail!("embedding backend returned inconsistent vector length at item {index}"); + } + Ok(()) +} + +pub(crate) fn validate_point_batch

(points: &[SemanticPoint

]) -> Result<()> { + let Some(vector_size) = points.first().map(|point| point.vector.len()) else { + return Ok(()); + }; + if vector_size == 0 { + anyhow::bail!("point 0 has an empty vector"); + } + if let Some((index, _)) = points + .iter() + .enumerate() + .find(|(_, point)| point.vector.len() != vector_size) + { + anyhow::bail!("point {index} has an inconsistent vector length"); + } + Ok(()) +} + +#[derive(Deserialize)] +struct Envelope { + result: T, +} +#[derive(Deserialize)] +struct ExistsResult { + exists: bool, +} +#[derive(Deserialize)] +struct CollectionInfo { + config: CollectionConfig, +} +#[derive(Deserialize)] +struct CollectionConfig { + metadata: Option, +} +#[derive(Deserialize)] +struct QueryResult

{ + points: Vec>, +} +#[derive(Deserialize)] +struct QueryPoint

{ + score: f32, + payload: Option

, +} +#[derive(Deserialize)] +struct ScrollResult { + points: Vec, + next_page_offset: Option, +} +#[derive(Deserialize)] +struct ScrollPoint { + id: String, +} +#[derive(Deserialize)] +struct EmbedResponse { + embeddings: Option>>, +} + +fn parse_response(response: 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 normalize_base_url(value: &str) -> String { + value.trim_end_matches('/').to_string() +} +fn timeout_seconds(timeout_ms: u64) -> u64 { + timeout_ms.div_ceil(1000).max(1) +} diff --git a/notes/epiphany-memory-graph-unified-plan.md b/notes/epiphany-memory-graph-unified-plan.md index fe88efbf..81c9ef06 100644 --- a/notes/epiphany-memory-graph-unified-plan.md +++ b/notes/epiphany-memory-graph-unified-plan.md @@ -377,6 +377,14 @@ Embed shared graph nodes, edges, and summaries. Qdrant candidate ranking feeds context-cut planning but never emits canonical memory payloads. +Landed 2026-07-15: the shared typed projection, strict Qdrant/Ollama backend, +Mind/Modeling physical partitions, canonical candidate reload, scoped sync, +typed projection receipts, BM25 fallback, CLI index/context path, and Persona +recall migration are live. See +`notes/memory-graph-semantic-projection-authority-map.md`. Remaining work is +daemon scheduling/CultMesh advertisement and refreshing stale Modeling anchors; +do not rebuild a Persona-specific semantic cache. + ### Phase 7: Sleep And Repo Refresh Sleep maintenance and repo scanning become profile-specific producers of typed diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index bb587fc8..9c8bb799 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -1033,3 +1033,39 @@ private doctrine/memory cannot leak into Hands Body retrieval and repository claims cannot silently become doctrine. Every point must retain source document id, schema version, canonical hash, provenance, authority/visibility scope, and embedding-model version. + +## Shared Mind/Modeling semantic nerve (2026-07-15) + +The Qdrant organ is now live rather than planned. `semantic_backend.rs` is the +single typed Qdrant/Ollama wire boundary; workspace retrieval consumes it and +the previous local transport copy is gone. The memory graph derives stable +Mind/Modeling projection documents, stores locator/hash/provenance payloads in +physically separate collections, validates collection metadata from Qdrant, +synchronizes only exact swarm/partition scope, reloads every candidate from +current canonical state, and falls back to typed BM25 without losing truth. +Projection receipts are typed CultCache documents outside RepoModel. + +`epiphany-memory-semantic` provides canonical index/context commands. +`epiphany-repo-model-bootstrap` atomically admits the initial RepoModel from +typed thread-state through runtime-spine ownership and ignores stale sibling +graph stores. The tracked schema-v0 `state/memory-graph.msgpack` is deleted. + +Live local proof against Docker Qdrant v1.17.1 and Ollama +`qwen3-embedding:0.6b` (1024 dimensions) indexed 43 Mind documents into +`epiphany_mind_v1` and 3 fresh Modeling documents into +`epiphany_modeling_v1`. Four stale Modeling points were removed. Semantic +queries render canonical typed packets, ignore payload prose, exclude stale +summary descendants, and report whether semantic ranking or BM25 fallback ran. + +Persona's private cache substitution is cut: its chunk schema, duplicated +Qdrant/Ollama clients, reindex-on-recall path, direct payload rendering, and +`epiphany_persona_memory_v0` collection are deleted. Heartbeat Persona recall +uses the shared Mind projection restricted to Persona's canonical domain. The +actual Modeling organ-state was also repaired: four surviving Proprioception +phrases in identity/goal/memory prose are now Modeling, validation is clean, +and the Mind collection was rebuilt from that repaired state. + +Next: schedule projection refresh as completion-gated physiology, publish typed +projection health through CultMesh/Eve, and refresh the stale source anchors +that leave the current Body map honestly thin. Do not let the scheduler, +Qdrant, Yggdrasil, or presentation become state authority. diff --git a/notes/memory-graph-semantic-projection-authority-map.md b/notes/memory-graph-semantic-projection-authority-map.md new file mode 100644 index 00000000..edecf790 --- /dev/null +++ b/notes/memory-graph-semantic-projection-authority-map.md @@ -0,0 +1,182 @@ +# Memory Graph Semantic Projection Authority Map + +## Objective + +Give every Epiphany swarm persistent semantic recall over both its Mind and its +Modeling-owned Body map without allowing Qdrant, an embedding service, Persona, +or presentation code to become memory authority. + +CultCache/CultMesh typed documents remain truth. Qdrant is a rebuildable nerve +that ranks canonical document identities. + +## Current Mechanism + +- The runtime-spine `EpiphanyMemoryGraphEntry` is the admitted RepoModel. Its + revision and hash bind Modeling-owned architecture, dataflow, summaries, and + frontier. +- Reviewed `EpiphanyAgentMemoryEntry` documents own lane and Persona memory. + `memory_graph_from_agent_memories` derives their typed Mind graph projection. +- `plan_memory_graph_context_cut` resolves full typed nodes, edges, summaries, + anchors, and frontier from a validated graph snapshot. BM25 is its correct + local ranking path. +- `retrieval.rs` has a functioning Qdrant/Ollama client for source chunks. +- `persona_memory_cache.rs` separately re-chunks Persona state, reindexes the + whole identity during recall, and renders Qdrant payload text. This is a + Persona-shaped substitute for the shared Mind/Modeling semantic nerve. +- `EpiphanyMemoryEmbeddingManifest` is unused inside RepoModel. Cache health + must not mutate the canonical model revision or hash. + +## Owner + +- Mind claims: their admitted typed CultCache documents. +- Modeling claims: the current runtime-spine RepoModel. +- Projection synchronization and semantic candidate ranking: one shared + `memory_graph::semantic_projection` organ. +- Qdrant and Ollama: xenos transport/cache boundaries only. + +## Inputs + +- `swarm_id` and exact visibility/authority scope. +- Validated canonical graph snapshots derived from admitted Mind documents or + loaded from the current RepoModel. +- Stable embedding-provider identity, model identity, vector dimension, and + projection profile version. Physical endpoint is operational configuration, + not semantic identity. + +## Outputs + +- Two physical projection collections: Mind and Modeling. +- Typed point payloads containing locators and hashes, never authoritative + claim text. +- A typed CultCache projection receipt/status outside RepoModel. +- Ranked candidate references that core reloads and revalidates against current + canonical state before producing a context packet. + +## Derived State + +- Embeddings, scores, point payloads, collection metadata, indexed counts, + projection timestamps, and projection health are cache-only. +- `EpiphanyMemoryEmbeddingManifest` is no longer an owner; it is legacy + notification-shaped state and must not be updated through RepoModel admission. +- Qdrant payload text is no longer memory; query results are locators only. + +## Partition Law + +- Modeling: `repo_architecture` and `repo_dataflow` nodes/edges/summaries plus + unresolved frontier. +- Mind: `role_self`, `short_term`, `incubation`, `agency_pressure`, + `candidate_intervention`, `identity`, and `evidence` nodes/edges/summaries. +- Physical collection separation is the privacy and rebuild boundary. Payload + filters are additional defense, not tenancy. +- Every point carries `swarm_id`. Modeling points also bind repo/graph identity; + Mind points bind their canonical role/identity scope where present. + +## Point Identity And Provenance + +Point UUID is deterministic over: + +`swarm_id | partition | canonical_type | canonical_key | canonical_document_id` + +Content and embedding versions do not change identity. They decide whether the +same point must be replaced. + +Every point binds: + +- canonical type, key, and document id +- canonical schema version, revision, and aggregate hash +- canonical document content hash +- graph/domain/profile/lifecycle +- source references and source hashes +- authority/visibility scope +- embedding provider, model, dimensions, and projection profile version + +## Query Path + +1. Explicit frontier and explicitly requested ids retain priority. +2. The embedder embeds the query using the partition's versioned query profile. +3. Qdrant returns candidate locators and scores. +4. Core reloads current canonical typed state. +5. Core rejects missing, retired, stale, hidden, cross-partition, revision-bound, + or hash-mismatched candidates. +6. Valid candidate ids seed the existing context-cut planner, which resolves + the full typed objects and preserves graph expansion, anchors, warnings, and + budget law. +7. Qdrant/Ollama failure adds a warning and uses BM25. Correctness is unchanged. + +## Forbidden Writers + +- Qdrant cannot write claims, lifecycle, visibility, evidence, frontier, Mind + decisions, RepoModel, or agent memory. +- Query payloads cannot speak directly into prompts. +- Persona cannot own a separate corpus contract. +- Cache status cannot require a RepoModel patch. +- Collection existence cannot attest schema/model compatibility. +- Synchronization cannot enumerate or delete foreign collections or scopes. +- Yggdrasil hosts the nerve; it does not own the thought. + +## Shared Paths + +- Workspace source retrieval, Persona recall, Mind recall, and Modeling recall + use one native embedding/vector transport. +- Mind and Modeling projectors own document semantics; the transport owns only + HTTP, batching, compatibility validation, and typed serialization at the JSON + boundary. +- Local Docker and Yggdrasil use the same logical embedding identity when the + model/dimensions/profile are identical, even if the endpoint moves. + +## Failure And Rebuild + +- Missing Qdrant/Ollama, stale projection, incompatible collection metadata, or + partial synchronization falls back to typed BM25 traversal. +- Incremental sync replaces changed stable ids and deletes only absent ids in + the exact owned swarm/partition scope. +- Rebuild constructs and verifies a compatible generation before retiring the + last usable projection. +- Deleting all Epiphany semantic collections must lose speed only. + +## Cut Line + +1. Extract the existing Qdrant/Ollama wire machinery into one typed native + backend; do not add a third client. +2. Add pure graph projection documents, stable identities, and canonical + candidate revalidation. +3. Add index and semantic-context CLI paths over canonical typed sources with a + typed projection receipt. +4. Prove distinct collections, compatibility refusal, stable rebuild ids, + changed/deleted document synchronization, hostile payload rejection, + frontier priority, and BM25 fallback. +5. Rewire Persona recall through Mind graph candidates and delete its private + chunk/client/index/search authority. +6. Retire the existing `epiphany_persona_memory_v0` collection only after the + shared Mind path is proven. +7. Remove sibling v0 `memory-graph.msgpack`/`.cc` from live authority; production + Modeling projection reads the runtime-spine RepoModel. + +## Landed First Nerve (2026-07-15) + +- `semantic_backend.rs` is now the single native Qdrant/Ollama xenos boundary + used by workspace retrieval and the shared memory projection. Collection + metadata is read back and compared exactly before reuse. +- `memory_graph::semantic_projection` derives stable locator documents and + revalidates candidates against current canonical hashes without trusting + payload prose. +- `memory_graph::semantic_index` synchronizes exact swarm/partition scope into + `epiphany_mind_v1` and `epiphany_modeling_v1`, writes immutable typed receipts + outside RepoModel, and falls back to canonical BM25 on backend failure. +- `epiphany-memory-semantic` indexes or queries admitted runtime RepoModel, + admitted agent memory, or an explicitly named composed graph store. It + refuses agent memory as Modeling and runtime RepoModel as Mind. +- `epiphany-repo-model-bootstrap` gives the runtime-spine owner an explicit + one-time atomic bootstrap from typed thread-state. It deliberately ignores + stale sibling graph files. +- Persona heartbeat recall now reads the shared Mind projection, restricts the + cut to Persona's exact domain, reloads canonical graph objects, and renders + the typed packet. The Persona-only client/chunk/search/index implementation + and its `epiphany_persona_memory_v0` collection are deleted. +- The tracked v0 sibling `state/memory-graph.msgpack` is deleted. Runtime-spine + RepoModel is the Modeling owner. + +Local proof indexed 43 Mind documents and 3 currently fresh Modeling documents +with `qwen3-embedding:0.6b` at 1024 dimensions. The thin Modeling count is +honest pressure: several imported thread-state claims have missing or changed +source anchors and remain stale rather than being made searchable by optimism. diff --git a/state/agents.msgpack b/state/agents.msgpack index 4c123ac5703e3c557c5ec9855674208771cdb482..e600038231652a78274a668d2b1a26f4fea1743f 100644 GIT binary patch delta 145 zcmZp#zE-tiy}F>euAym&fsvK5xs{1g)KNC0%?H#MF>==U=BK3QWag!BF4SDd#AD!@ zrT`O}Y^amMIBoJYoeB=Pkc@5sW8>spU1PY==5@L@yy&Jg6;J+cr6Pc8=Qh2~9@h3u E02KEx761SM delta 188 zcmcas)n2_}z53*zjQmV&UYif7FJk0x3Mk4iD9X%FPAw?O%+K4Lt+|d#$jmcM0abjm zs!j^yoXK4}6?|wCT)F{_?USQ*jnO1FPt&#G6*AK`G72#?vobNZGPa01%G5J=vJ9j2 rU$k=191~^>-)OiXui4g;YYvQAGW)X+P%TEZhtg5IKTXSe>HgS z%*=2?6XOz6h>0X@jY}zTu3R*l3NJ5NMPAbVwL?NjZ6<2kJLu;$<(S|+t6RA9ro`?(4;}`>_ zvS9E2u3h>00=KPXJxkZl6gd0L`hfxTVf-#)J3> delta 61 zcmaDdO>Xl Jm5E)h4FG2w64w9# diff --git a/state/map.yaml b/state/map.yaml index 50b6a1bb..d87db45d 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -714,4 +714,4 @@ current_status: - Service lifecycle receipt history is now event-only: `load_epiphany_cultmesh_daemon_service_lifecycle_receipts` filters out the `epiphany-local/daemon-service-lifecycle-receipt/latest` mirror, while `load_latest_epiphany_cultmesh_daemon_service_lifecycle_receipt` remains the latest-state reader. Focused unit test `service_lifecycle_receipt_history_excludes_latest_mirror` proves two per-receipt writes return exactly two history records and latest points at the second. Fresh smoke `verse-query-lifecycle-history-filter-smoke` and live overview/triage `local-20260618-145632-497-efac6f0d` / `local-20260618-145632-321-867947af` prove compact swarm sights still expose service lifecycle attention plus the present elevated runbook artifact without daemon pokes or service mutation. Do not use a broad unscoped cargo test filter for this check on Windows; it fans out across bin harnesses and hit a broken pipe during this pass. - `epiphany-verse-query seed-compact` is the compact seed receipt for wrappers and read-only rites. The older `seed` command still prints the full local Verse context for explicit debugging, but compact wrapper modes now avoid full `seed`/final `query` readback after the combined overview proof exposed Windows debug stack overflow from full-context serialization pressure. last_completed_repo_swarm_cut: Huginn live-fire has crossed the first real repo Body from Persona pressure to branch-local Hands commit and Soul/Mind closure, and now has repeatable closure and redacted-public-proof mouths. On `E:\Projects\Huginn` branch `epiphany/huginn/first-awakening`, `tools/epiphany_local_run.ps1 -Mode repo-persona-intake` accepted item `huginn-inspection-readback-livefire`, Weksa/Persona intake remained sealed, and `epiphany-work derive-plan` lowered it to model-authored safe family `repo.status_section` for `README.md` only. `tools/epiphany_local_run.ps1 -Mode repo-swarm-run` advanced four bounded pulses: run-from-plan, adopt-from-plan, execute-from-plan, and close-from-execute. Huginn commit `e9b07c38fceabbdc89ea35c2156326c80c0393a2` updated only `README.md`; closure receipt `.epiphany\work\work-close-huginn-inspection-readback-livefire.json` records status `closed`, Soul verdict `passed`, Mind state commit `repo-work-close-huginn-inspection-readback-livefire-mind-commit`, safe family `repo.status_section`, path scope `README.md`, Bifrost publication gate, and `privateStateExposed=false`. Verification also ran Huginn's TypeScript compiler through concrete Node path: `C:\Program Files\nodejs\node.exe E:\Projects\Huginn\node_modules\typescript\bin\tsc -p tsconfig.json` passed. Native verifier `epiphany-repo-livefire-closure-smoke --workspace E:\Projects\Huginn --item huginn-inspection-readback-livefire --expected-path README.md --expected-family repo.status_section --expected-gate awaiting-publication --expected-blocker bifrost-publication-missing` checks closure receipt, Mind map entry, overview gate/blocker, authority seals, and `git show` changed paths, returning `status=ok`, `soulVerdict=passed`, `publicationGate=Bifrost`, and `privateStateExposed=false`. Wrapper `tools/epiphany_local_run.ps1 -Mode repo-livefire-closure -Workspace E:\Projects\Huginn -RepoWorkItem huginn-inspection-readback-livefire -SkipBuild` exposes the same read-only proof through the local operator mouth; artifact `local-20260621-190156-803-2f85ba15` printed commit, path, gate, blocker, Soul verdict, Mind commit receipt, and `privateStateExposed=False` without push, merge, publication, or target mutation. New wrapper `tools/epiphany_local_run.ps1 -Mode repo-work-public-proof -Workspace E:\Projects\Huginn -RepoWorkItem huginn-inspection-readback-livefire -SkipBuild` exports the redacted proof bundle and repo-local Verse index without publishing; artifact `local-20260621-190645-345-4555b1dc` wrote `.epiphany\public\proof-bundles\repo-work-public-proof-huginn-inspection-readback-livefire.json`, proof id `repo-work-public-proof-huginn-inspection-readback-livefire`, SHA-256 `857545b199f3e37eb06c2e757e5cfc201958e46667bb1f8403fd333a22620f63`, nine artifact rows, zero publication rows, and `privateStateExposed=False`. swarm overview readback `local-20260621-190701-140-b9519ec6` sees the `REPO-WORK-PUBLIC-PROOF` row and action row from Huginn's repo-local Verse with the same SHA-256 while Bifrost publication remains missing. Launcher compact modes are now named compact operator-context modes instead of read-only modes, and `bifrost-public-proof` summaries print item, target public Verse, room, proof SHA-256, review receipts, and credit receipts so publication receipts are auditable without claiming upstream sync. - next_action: Build the production Qdrant semantic projection over canonical typed state. Modeling needs a live persistent searchable Body map over repo claims/architecture/frontier; Mind needs semantic retrieval over doctrine, durable memory, evidence, decisions, and rehydration cues. CultCache/CultMesh remains authoritative and Qdrant stays rebuildable, with separate typed Mind/Modeling namespaces, provenance, visibility, schema/hash, and embedding-model version. Local Docker already hosts Qdrant; new Yggdrasil will provide the same substrate with 64GB RAM and a GTX 1080 for embedding/model workers. The repo-frontier planning nerve is complete: typed Self request, coordinator-bound Imagination launch, immutable embedded candidate, CAS-bound Mind review request, coordinator-bound non-embodied admission-review procedure, immutable Adopt/Refuse/Hold judgment, atomic canonical Adopt transition, model-derived Hands route, candidate/action/command-bound execution authority, Soul plan-contract visibility, and Modeling verdict closure without plan rewrite. Do not revive Proprioception, epiphany-work, metadata adapters, generic work-order routers, shadow candidate/adoption stores, embodied Mind lanes, or inference from namespaces/prompt prose/evidence coincidence. Keep closure's zero-substring invariant. + next_action: Operationalize the landed shared Mind/Modeling semantic nerve as a daemon/CultMesh capability and refresh the stale source anchors that leave the current Modeling projection honestly thin. The first production path is live: one typed Qdrant/Ollama backend, physical `epiphany_mind_v1`/`epiphany_modeling_v1` partitions, stable locator-only points, strict collection compatibility, scope-bounded sync, canonical candidate reload, typed CultCache projection receipts outside RepoModel, BM25 fallback, explicit RepoModel bootstrap, and Persona heartbeat recall through the shared Mind graph. Local live proof indexed 43 Mind documents and 3 fresh Modeling documents at 1024 dimensions with `qwen3-embedding:0.6b`; stale Modeling descendants are excluded. The old Persona-only client/chunk/index/search authority, live collection, tracked v0 sibling memory graph, and four surviving Proprioception phrases in Modeling Mind state are purged. Next add completion-gated projection scheduling, typed health/readback through CultMesh/Eve, and source-grounded Modeling refresh without letting Qdrant, Yggdrasil, presentation, or thread-state become truth. The repo-frontier planning nerve remains complete. Do not revive Proprioception, epiphany-work, metadata adapters, generic work-order routers, shadow candidate/adoption stores, embodied Mind lanes, Qdrant payload prose, or inference from namespaces/prompt prose/evidence coincidence. Keep closure's zero-substring invariant. diff --git a/state/memory-graph.msgpack b/state/memory-graph.msgpack deleted file mode 100644 index 7bd35603..00000000 --- a/state/memory-graph.msgpack +++ /dev/null @@ -1 +0,0 @@ -“²cultcache.store.v1‘—µepiphany.memory_graphµepiphany.memory_graph¸epiphany.memory_graph.v1µepiphany.memory_graphÙ^{"schemaName":"epiphany.memory_graph","schemaVersion":"epiphany.memory_graph.v1","members":[]}‘µepiphany.memory_graph�‘”§defaultµepiphany.memory_graph´2026-06-12T12:20:02ZÅ&“¸epiphany.memory_graph.v0¹bridge-launch-state-rev-1Üi̮̇schema_version̸epiphany.memory_graph.v0̨graph_id̹bridge-launch-state-rev-1̧domainsÌ’Ì…Ì¢idÌÙ/memdom-4328bcb00ecb7b6cc27599a575fc496c68fe421f̧profile̱repo_architectureÌ¥titleÌ»Accepted architecture graphÌ«descriptionÌÙ9Repo profile imported from accepted Epiphany graph state.Ì©lifecyclęacceptedÌ…Ì¢idÌÙ/memdom-ee83f24c369580ed47fcfa40d0408e570849b2ca̧profileÌ­repo_dataflowÌ¥titleÌ·Accepted dataflow graphÌ«descriptionÌÙ9Repo profile imported from accepted Epiphany graph state.Ì©lifecyclęacceptedÌ¥nodes̢̔̎idÌÙ0memnode-e6470206bc52a08dbe981f4822abcb1153eaa1ecÌ©domain_idÌÙ/memdom-4328bcb00ecb7b6cc27599a575fc496c68fe421f̧profile̱repo_architecture̤kind̦moduleÌ¥titlḛLocal MVP runnerÌ¥claimÌÙÌ�One local operator cycle that enters through Face, runs coordinator-owned work, and invokes Continuity/heartbeat sleep afterward.̨questionÌÙ2What changes if this accepted graph node is stale?̧tension̠̲action_implicationÌÙEUse accepted graph node local-mvp-runner when selecting repo context.̧anchors̢̔̅idÌÙ9anchor-memnode-e6470206bc52a08dbe981f4822abcb1153eaa1ec-0̤kind̨code_ref̦targetÌÙ3tools/epiphany_local_run.ps1#epiphany_local_run.ps1̨code_ref̤̄path̼tools/epiphany_local_run.ps1̪start_linęend_line̦symbol̶epiphany_local_run.ps1Ì«source_hashÌÙ3tools/epiphany_local_run.ps1#epiphany_local_run.ps1Ì…Ì¢idÌÙ9anchor-memnode-e6470206bc52a08dbe981f4822abcb1153eaa1ec-1̤kind̨code_ref̦target̵README.md#Run Locally̨code_ref̤̄pathÌ©README.md̪start_lineR̨end_lineo̦symbolÌ«Run LocallyÌ«source_hash̵README.md#Run LocallyÌ…Ì¢idÌÙ9anchor-memnode-e6470206bc52a08dbe981f4822abcb1153eaa1ec-2̤kind̨code_ref̦targetÌÙ4notes/fresh-workspace-handoff.md#Current Orientation̨code_ref̤̄pathÌÙ notes/fresh-workspace-handoff.md̪start_line!̨end_line-̦symbol̳Current OrientationÌ«source_hashÌÙ4notes/fresh-workspace-handoff.md#Current OrientationÌ…Ì¢idÌÙ9anchor-memnode-e6470206bc52a08dbe981f4822abcb1153eaa1ec-3̤kind̨code_ref̦target̺state/map.yaml#Runnability̨code_ref̤̄pathÌ®state/map.yaml̪start_lineÌÍÌÝ̨end_lineÌÍÌç̦symbolÌ«RunnabilityÌ«source_hash̺state/map.yaml#RunnabilityÌ­source_hashesÌ”ÌÙ9anchor-memnode-e6470206bc52a08dbe981f4822abcb1153eaa1ec-0ÌÙ9anchor-memnode-e6470206bc52a08dbe981f4822abcb1153eaa1ec-1ÌÙ9anchor-memnode-e6470206bc52a08dbe981f4822abcb1153eaa1ec-2ÌÙ9anchor-memnode-e6470206bc52a08dbe981f4822abcb1153eaa1ec-3Ì©lifecyclęaccepted̨salienceF̪confidencePÌŽÌ¢idÌÙ0memnode-a233ac421c8ea068261352dfb8b36ab933c46ba7Ì©domain_idÌÙ/memdom-4328bcb00ecb7b6cc27599a575fc496c68fe421f̧profile̱repo_architecture̤kind̰runtime_contractÌ¥titleÌ·Model runtime transportÌ¥claimÌÙ̉Provider-neutral worker execution resolves the model runtime binary and then uses the quarantined Codex/OpenAI transport for model calls.̨questionÌÙ2What changes if this accepted graph node is stale?̧tension̠̲action_implicationÌÙLUse accepted graph node model-runtime-transport when selecting repo context.̧anchors̢̔̅idÌÙ9anchor-memnode-a233ac421c8ea068261352dfb8b36ab933c46ba7-0̤kind̨code_ref̦targetÌÙ`epiphany-core/src/bin/epiphany-mvp-coordinator.rs#resolve_model_runtime_bin / run_worker_runtimęcode_ref̤̄pathÌÙ1epiphany-core/src/bin/epiphany-mvp-coordinator.rs̪start_lineÌÍÌĮ̈end_lineÌÍ̦symbolÌÙ.resolve_model_runtime_bin / run_worker_runtimeÌ«source_hashÌÙ`epiphany-core/src/bin/epiphany-mvp-coordinator.rs#resolve_model_runtime_bin / run_worker_runtimeÌ…Ì¢idÌÙ9anchor-memnode-a233ac421c8ea068261352dfb8b36ab933c46ba7-1̤kind̨code_ref̦targetÌÙOepiphany-openai-runtime/src/bin/epiphany-openai-runtime.rs#default_worker_model̨code_ref̤̄pathÌÙ:epiphany-openai-runtime/src/bin/epiphany-openai-runtime.rs̪start_lineÌĮ̯́end_lineÌÍ̶̦symbolÌ´default_worker_modelÌ«source_hashÌÙOepiphany-openai-runtime/src/bin/epiphany-openai-runtime.rs#default_worker_modelÌ…Ì¢idÌÙ9anchor-memnode-a233ac421c8ea068261352dfb8b36ab933c46ba7-2̤kind̨code_ref̦targetÌÙ