use std::collections::HashSet;
use anyhow::Result;
use chrono::Utc;
use uuid::Uuid;
use crate::schema::{Memory, RelationType};
use crate::store::Store;
pub const MIN_SIMILARITY: f32 = 0.59;
pub const EXHAUSTED_MIN_SIMILARITY: f32 = 0.56;
pub const PROJECT_AFFINITY_BOOST: f32 = 1.15;
#[derive(Debug, Clone, Copy)]
pub struct BlendWeights {
pub primary: f32,
pub graph: f32,
pub recency: f32,
}
impl Default for BlendWeights {
fn default() -> Self {
Self {
primary: 0.5,
graph: 0.3,
recency: 0.2,
}
}
}
pub fn blend(primary: f32, graph: f32, recency: f32, weights: BlendWeights) -> f32 {
(primary * weights.primary) + (graph * weights.graph) + (recency * weights.recency)
}
pub fn apply_project_affinity(score: f32, memory: &Memory, project_path: Option<&str>) -> f32 {
match project_path {
Some(qp) if memory.project_path.as_deref() == Some(qp) => score * PROJECT_AFFINITY_BOOST,
_ => score,
}
}
pub fn compute_recency(memory: &Memory) -> f32 {
let hours_since_access = Utc::now()
.signed_duration_since(memory.last_accessed)
.num_hours() as f32;
let decay = (-hours_since_access / (24.0 * 30.0)).exp();
let access_boost = (memory.access_count as f32).ln_1p() / 10.0;
(decay + access_boost).min(1.0)
}
pub fn resolve_query_entities<S: Store + ?Sized>(store: &S, names: &[String]) -> HashSet<Uuid> {
let mut ids = HashSet::new();
for name in names {
if let Ok(Some(entity)) = store.find_entity_by_name(name) {
ids.insert(entity.id);
}
}
ids
}
pub fn compute_graph_relevance<S: Store + ?Sized>(
store: &S,
memory: &Memory,
query_entity_ids: &HashSet<Uuid>,
) -> Result<f32> {
let scored_types = [
(RelationType::Reinforces, 0.3_f32),
(RelationType::RelatesTo, 0.2),
(RelationType::DistilledFrom, 0.15),
(RelationType::Mentions, 0.1),
(RelationType::DerivedFrom, 0.05),
(RelationType::Contradicts, -0.1),
(RelationType::Supersedes, -0.2),
];
let mut structural = 0.0_f32;
let mut mention_hits = 0usize;
for (rt, boost) in &scored_types {
if let Ok(rels) = store.get_relations(memory.id, Some(*rt)) {
for rel in &rels {
let b = if *rt == RelationType::RelatesTo {
boost * rel.strength
} else {
*boost
};
structural += b;
if *rt == RelationType::Mentions && query_entity_ids.contains(&rel.to_id) {
mention_hits += 1;
}
}
}
}
let structural = structural.clamp(0.0, 1.0);
if query_entity_ids.is_empty() {
return Ok(structural);
}
let proximity = (mention_hits as f32 / query_entity_ids.len() as f32).min(1.0);
Ok((0.7 * proximity + 0.3 * structural).clamp(0.0, 1.0))
}