Unify Mind and Modeling semantic projection
This commit is contained in:
parent
f72228fe61
commit
8f0c9ea723
23 changed files with 2903 additions and 1964 deletions
|
|
@ -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}
|
||||
|
||||
|
|
|
|||
|
|
@ -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::<Vec<_>>();
|
||||
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<Path>) -> Result<Value>
|
|||
}));
|
||||
}
|
||||
|
||||
if let Some(mut modeling) = cache.get::<EpiphanyAgentMemoryEntry>("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::<EpiphanyAgentMemoryEntry>("Persona")?.is_none()
|
||||
&& let Some(mut face) = cache.get::<EpiphanyAgentMemoryEntry>("face")?
|
||||
{
|
||||
|
|
@ -688,6 +730,14 @@ pub fn repair_agent_memory_store(store_path: impl AsRef<Path>) -> Result<Value>
|
|||
}))
|
||||
}
|
||||
|
||||
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<Path>,
|
||||
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::<EpiphanyAgentMemoryEntry>("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::<EpiphanyAgentMemoryEntry>("Persona")?;
|
||||
assert_eq!(persona.role_id, "Persona");
|
||||
assert_eq!(persona.agent.agent_id, "epiphany.Persona");
|
||||
|
|
|
|||
211
epiphany-core/src/bin/epiphany-memory-semantic.rs
Normal file
211
epiphany-core/src/bin/epiphany-memory-semantic.rs
Normal file
|
|
@ -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 <path>"))?;
|
||||
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 <query>"))?;
|
||||
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<PathBuf>,
|
||||
runtime_store: Option<PathBuf>,
|
||||
agent_store: Option<PathBuf>,
|
||||
receipt_store: Option<PathBuf>,
|
||||
swarm_id: String,
|
||||
partition: SemanticPartition,
|
||||
text: Option<String>,
|
||||
query_id: Option<String>,
|
||||
budget: Option<u32>,
|
||||
profile: Option<epiphany_core::EpiphanyMemoryProfile>,
|
||||
}
|
||||
|
||||
impl Options {
|
||||
fn parse(args: impl Iterator<Item = String>) -> Result<Self> {
|
||||
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<EpiphanyMemoryGraphSnapshot> {
|
||||
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<SemanticPartition> {
|
||||
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<epiphany_core::EpiphanyMemoryProfile> {
|
||||
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 <index|context> (--runtime-store <path>|--agent-store <path>|--graph-store <path>) --swarm-id <id> --partition <mind|modeling> [--receipt-store <path>] [--text <query>] [--query-id <id>] [--budget <n>] [--profile <profile>]"
|
||||
)
|
||||
}
|
||||
|
||||
fn print_json(value: &impl serde::Serialize) -> Result<()> {
|
||||
println!("{}", serde_json::to_string_pretty(value)?);
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -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(),
|
||||
}
|
||||
}
|
||||
|
|
|
|||
80
epiphany-core/src/bin/epiphany-repo-model-bootstrap.rs
Normal file
80
epiphany-core/src/bin/epiphany-repo-model-bootstrap.rs
Normal file
|
|
@ -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<Item = String>, flag: &str) -> Result<PathBuf> {
|
||||
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 <path> --thread-state-store <path>"
|
||||
)
|
||||
}
|
||||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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<SemanticPartition>,
|
||||
) -> 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<EpiphanyMemorySummary> = 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<SemanticPartition>,
|
||||
budget: usize,
|
||||
node_by_id: &HashMap<&str, &EpiphanyMemoryNode>,
|
||||
stale_nodes: &HashSet<&str>,
|
||||
domains: &HashSet<&str>,
|
||||
) -> (Vec<RepoFrontierItem>, Vec<String>) {
|
||||
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<SemanticPartition>,
|
||||
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::<Vec<_>>();
|
||||
|
|
@ -323,6 +445,7 @@ fn ranked_nodes<'a>(
|
|||
fn ranked_summaries<'a>(
|
||||
snapshot: &'a EpiphanyMemoryGraphSnapshot,
|
||||
query: &EpiphanyMemoryContextQuery,
|
||||
partition: Option<SemanticPartition>,
|
||||
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::<Vec<_>>();
|
||||
rank_typed_documents(eligible, query.text.as_deref(), terms, |summary| {
|
||||
[
|
||||
|
|
@ -380,6 +512,7 @@ fn query_terms(query: &EpiphanyMemoryContextQuery) -> Vec<String> {
|
|||
fn summary_matches(
|
||||
summary: &EpiphanyMemorySummary,
|
||||
profile: Option<EpiphanyMemoryProfile>,
|
||||
partition: Option<SemanticPartition>,
|
||||
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<EpiphanyMemoryProfile>,
|
||||
partition: Option<SemanticPartition>,
|
||||
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<EpiphanyMemoryProfile>,
|
||||
partition: Option<SemanticPartition>,
|
||||
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<SemanticPartition>) -> bool {
|
||||
partition.is_none_or(|partition| {
|
||||
matches!(
|
||||
profile,
|
||||
EpiphanyMemoryProfile::RepoArchitecture | EpiphanyMemoryProfile::RepoDataflow
|
||||
) == (partition == SemanticPartition::Modeling)
|
||||
})
|
||||
}
|
||||
|
||||
fn text_matches_terms<'a>(values: impl IntoIterator<Item = &'a String>, 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<EpiphanyMemoryProfile>,
|
||||
partition: Option<SemanticPartition>,
|
||||
domain_ids: &HashSet<&str>,
|
||||
budget: usize,
|
||||
nodes: &mut Vec<EpiphanyMemoryNode>,
|
||||
edges: &mut Vec<EpiphanyMemoryEdge>,
|
||||
) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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::<Vec<_>>();
|
||||
let stale_edge_ids = edges
|
||||
.iter()
|
||||
.filter(|edge| edge.lifecycle == EpiphanyMemoryLifecycle::Stale)
|
||||
.map(|edge| edge.id.clone())
|
||||
.collect::<Vec<_>>();
|
||||
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 {
|
||||
|
|
|
|||
516
epiphany-core/src/memory_graph/semantic_index.rs
Normal file
516
epiphany-core/src/memory_graph/semantic_index.rs
Normal file
|
|
@ -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<String>,
|
||||
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<MemorySemanticIndexReceipt> {
|
||||
let documents = derive_semantic_projection(swarm_id, snapshot)?
|
||||
.into_iter()
|
||||
.filter(|document| document.partition == partition)
|
||||
.collect::<Vec<_>>();
|
||||
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::<Vec<_>>();
|
||||
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::<Vec<_>>();
|
||||
backend.upsert_points(collection, &points)?;
|
||||
let live_ids = documents
|
||||
.iter()
|
||||
.map(|document| document.point_id.as_str())
|
||||
.collect::<HashSet<_>>();
|
||||
let deleted_ids = existing_ids
|
||||
.into_iter()
|
||||
.filter(|id| !live_ids.contains(id.as_str()))
|
||||
.collect::<Vec<_>>();
|
||||
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<Path>,
|
||||
receipt: &MemorySemanticIndexReceipt,
|
||||
) -> Result<()> {
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_entry_type::<MemorySemanticIndexReceipt>()?;
|
||||
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<EpiphanyMemoryContextPacket> {
|
||||
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::<MemorySemanticPointPayload>(
|
||||
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> {
|
||||
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> {
|
||||
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::<Vec<_>>();
|
||||
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)
|
||||
);
|
||||
}
|
||||
}
|
||||
775
epiphany-core/src/memory_graph/semantic_projection.rs
Normal file
775
epiphany-core/src/memory_graph/semantic_projection.rs
Normal file
|
|
@ -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<String>,
|
||||
pub source_hashes: Vec<String>,
|
||||
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<Vec<Vec<f32>>>;
|
||||
}
|
||||
|
||||
pub trait SemanticVectorIndex {
|
||||
fn replace_partition(
|
||||
&self,
|
||||
swarm_id: &str,
|
||||
partition: SemanticPartition,
|
||||
documents: &[(SemanticProjectionDocument, Vec<f32>)],
|
||||
) -> Result<()>;
|
||||
|
||||
fn search(
|
||||
&self,
|
||||
swarm_id: &str,
|
||||
partition: SemanticPartition,
|
||||
vector: &[f32],
|
||||
limit: usize,
|
||||
) -> Result<Vec<SemanticProjectionCandidate>>;
|
||||
}
|
||||
|
||||
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<Vec<SemanticProjectionDocument>> {
|
||||
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::<HashMap<_, _>>();
|
||||
let nodes = snapshot
|
||||
.nodes
|
||||
.iter()
|
||||
.map(|node| (node.id.as_str(), node))
|
||||
.collect::<HashMap<_, _>>();
|
||||
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<T: Serialize>(
|
||||
swarm_id: &str,
|
||||
snapshot: &EpiphanyMemoryGraphSnapshot,
|
||||
partition: SemanticPartition,
|
||||
kind: SemanticDocumentKind,
|
||||
document_id: &str,
|
||||
domain: &EpiphanyMemoryDomain,
|
||||
profile: EpiphanyMemoryProfile,
|
||||
lifecycle: SemanticLifecycle,
|
||||
mut source_refs: Vec<String>,
|
||||
mut source_hashes: Vec<String>,
|
||||
canonical_value: &T,
|
||||
projection_text: String,
|
||||
) -> Result<SemanticProjectionDocument> {
|
||||
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<const N: usize>(parts: [&str; N]) -> String {
|
||||
parts
|
||||
.into_iter()
|
||||
.filter(|part| !part.trim().is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.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<_>>(),
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
|
@ -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
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -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<String>,
|
||||
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<Self> {
|
||||
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<bool> {
|
||||
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<QdrantCollectionExistsResult> = 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::<bool>(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::<bool>(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::<Value>(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::<Value>(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<Vec<QdrantQueryPoint>> {
|
||||
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<QdrantQueryResultEnvelope> = 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<Self> {
|
||||
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<Vec<Vec<f32>>> {
|
||||
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<Vec<f32>> {
|
||||
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<Vec<Vec<f32>>> {
|
||||
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<f32>,
|
||||
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<T> {
|
||||
result: T,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct QdrantCollectionExistsResult {
|
||||
exists: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct QdrantQueryResultEnvelope {
|
||||
points: Vec<QdrantQueryPoint>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
struct QdrantQueryPoint {
|
||||
score: f32,
|
||||
#[serde(default)]
|
||||
payload: Option<QdrantPointPayload>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct OllamaEmbedResponse {
|
||||
embeddings: Option<Vec<Vec<f32>>>,
|
||||
}
|
||||
|
||||
fn parse_qdrant_response<T: for<'de> Deserialize<'de>>(
|
||||
response: reqwest::blocking::Response,
|
||||
) -> Result<QdrantEnvelope<T>> {
|
||||
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<EpiphanyRetrieveResult> {
|
||||
fn map_qdrant_hit_to_result(
|
||||
point: SemanticCandidate<QdrantPointPayload>,
|
||||
) -> Option<EpiphanyRetrieveResult> {
|
||||
let payload = point.payload?;
|
||||
|
||||
Some(EpiphanyRetrieveResult {
|
||||
|
|
@ -1619,31 +1323,6 @@ fn normalize_payload_path(path: &Path) -> String {
|
|||
.join("/")
|
||||
}
|
||||
|
||||
fn validate_embedding_batch(embeddings: &[Vec<f32>], 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<i64> {
|
||||
Ok(i64::try_from(
|
||||
time.duration_since(UNIX_EPOCH)
|
||||
|
|
@ -1664,14 +1343,6 @@ fn unix_timestamp_nanos(time: SystemTime) -> Result<i64> {
|
|||
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<String> {
|
||||
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(
|
||||
|
|
|
|||
456
epiphany-core/src/semantic_backend.rs
Normal file
456
epiphany-core/src/semantic_backend.rs
Normal file
|
|
@ -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<String>,
|
||||
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<P> {
|
||||
pub(crate) id: String,
|
||||
pub(crate) vector: Vec<f32>,
|
||||
pub(crate) payload: P,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct SemanticCandidate<P> {
|
||||
pub(crate) score: f32,
|
||||
pub(crate) payload: Option<P>,
|
||||
}
|
||||
|
||||
pub(crate) struct QdrantBackend {
|
||||
base_url: String,
|
||||
timeout_seconds: u64,
|
||||
client: Client,
|
||||
}
|
||||
|
||||
impl QdrantBackend {
|
||||
pub(crate) fn new(config: QdrantConfig) -> Result<Self> {
|
||||
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<bool> {
|
||||
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<ExistsResult> = 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<CollectionCompatibility> {
|
||||
let response = self
|
||||
.client
|
||||
.get(format!("{}/collections/{name}", self.base_url))
|
||||
.send()
|
||||
.with_context(|| format!("failed to inspect Qdrant collection {name}"))?;
|
||||
let envelope: Envelope<CollectionInfo> = 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::<bool>(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::<bool>(response).with_context(|| {
|
||||
format!("failed to decode Qdrant create-collection response for {name}")
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn upsert_points<P: Serialize>(
|
||||
&self,
|
||||
name: &str,
|
||||
points: &[SemanticPoint<P>],
|
||||
) -> 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::<Value>(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::<Value>(response).with_context(|| {
|
||||
format!("failed to decode Qdrant delete-points response for {name}")
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn query_points<P: DeserializeOwned>(
|
||||
&self,
|
||||
name: &str,
|
||||
vector: &[f32],
|
||||
limit: usize,
|
||||
) -> Result<Vec<SemanticCandidate<P>>> {
|
||||
self.query_points_for_scope(name, vector, limit, &[])
|
||||
}
|
||||
|
||||
pub(crate) fn query_points_for_scope<P: DeserializeOwned>(
|
||||
&self,
|
||||
name: &str,
|
||||
vector: &[f32],
|
||||
limit: usize,
|
||||
scope: &[(&str, &str)],
|
||||
) -> Result<Vec<SemanticCandidate<P>>> {
|
||||
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::<Vec<_>>();
|
||||
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<QueryResult<P>> = 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<Vec<String>> {
|
||||
let must = scope
|
||||
.iter()
|
||||
.map(|(key, value)| json!({ "key": key, "match": { "value": value } }))
|
||||
.collect::<Vec<_>>();
|
||||
let mut offset: Option<Value> = 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<ScrollResult> = 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<Self> {
|
||||
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<Vec<Vec<f32>>> {
|
||||
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<Vec<f32>> {
|
||||
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<Vec<Vec<f32>>> {
|
||||
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<f32>], 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<P>(points: &[SemanticPoint<P>]) -> 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<T> {
|
||||
result: T,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct ExistsResult {
|
||||
exists: bool,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct CollectionInfo {
|
||||
config: CollectionConfig,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct CollectionConfig {
|
||||
metadata: Option<CollectionCompatibility>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct QueryResult<P> {
|
||||
points: Vec<QueryPoint<P>>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct QueryPoint<P> {
|
||||
score: f32,
|
||||
payload: Option<P>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct ScrollResult {
|
||||
points: Vec<ScrollPoint>,
|
||||
next_page_offset: Option<Value>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct ScrollPoint {
|
||||
id: String,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct EmbedResponse {
|
||||
embeddings: Option<Vec<Vec<f32>>>,
|
||||
}
|
||||
|
||||
fn parse_response<T: DeserializeOwned>(response: Response) -> Result<Envelope<T>> {
|
||||
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)
|
||||
}
|
||||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
182
notes/memory-graph-semantic-projection-authority-map.md
Normal file
182
notes/memory-graph-semantic-projection-authority-map.md
Normal file
|
|
@ -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.
|
||||
Binary file not shown.
Binary file not shown.
|
|
@ -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.
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
Reference in a new issue