Skip to main content

aidaemon_memory/
scoring.rs

1//! Retrieval scoring: the replaceable [`Scorer`] and its default,
2//! [`HybridScorer`] (port of the daemon's `memory/hybrid.rs`, the fact
3//! thresholds in `state/sqlite/facts.rs`, and `memory/scoring.rs`).
4
5use std::collections::HashSet;
6
7use chrono::{DateTime, Utc};
8
9use crate::types::{Episode, Fact, Score, Signals};
10
11/// Weights of the fused score. Defaults are the daemon's calibrated values
12/// and sum to 1.0.
13#[derive(Debug, Clone, Copy, PartialEq)]
14pub struct HybridWeights {
15    pub semantic: f32,
16    pub lexical: f32,
17    /// Entity-graph match, from [`crate::MemoryStore::fact_graph_scores`].
18    /// Stays 0 for a store with no graph.
19    pub graph: f32,
20    pub freshness: f32,
21    pub confidence: f32,
22    pub provenance: f32,
23}
24
25impl Default for HybridWeights {
26    fn default() -> Self {
27        Self {
28            semantic: 0.45,
29            lexical: 0.30,
30            graph: 0.10,
31            freshness: 0.10,
32            confidence: 0.03,
33            provenance: 0.02,
34        }
35    }
36}
37
38impl HybridWeights {
39    /// Fuse independently bounded signals; inputs are clamped to 0..=1.
40    pub fn fuse(&self, s: &Signals) -> f32 {
41        self.semantic * s.semantic.clamp(0.0, 1.0)
42            + self.lexical * s.lexical.clamp(0.0, 1.0)
43            + self.graph * s.graph.clamp(0.0, 1.0)
44            + self.freshness * s.freshness.clamp(0.0, 1.0)
45            + self.confidence * s.confidence.clamp(0.0, 1.0)
46            + self.provenance * s.provenance.clamp(0.0, 1.0)
47    }
48}
49
50/// Tunables for [`HybridScorer`].
51#[derive(Debug, Clone, Copy, PartialEq)]
52pub struct ScoringConfig {
53    pub weights: HybridWeights,
54    /// A candidate is kept when its semantic similarity is above this...
55    pub semantic_min: f32,
56    /// ...or its lexical score is above this. Both 0.3 in the daemon. The
57    /// freshness/confidence/provenance signals only order candidates; they
58    /// never let an irrelevant one through.
59    pub lexical_min: f32,
60    /// Freshness falls linearly from 1 to 0 over this window (7 days).
61    pub freshness_window: chrono::Duration,
62    /// Provenance signal for a fact with / without a supporting excerpt.
63    pub provenance_with_excerpt: f32,
64    pub provenance_without_excerpt: f32,
65    /// Drop candidates whose fused score is at or below this (default 0).
66    pub min_score: f32,
67}
68
69impl Default for ScoringConfig {
70    fn default() -> Self {
71        Self {
72            weights: HybridWeights::default(),
73            semantic_min: 0.3,
74            lexical_min: 0.3,
75            freshness_window: chrono::Duration::days(7),
76            provenance_with_excerpt: 1.0,
77            provenance_without_excerpt: 0.3,
78            min_score: 0.0,
79        }
80    }
81}
82
83/// Turns retrieval signals into a ranking score, or drops the candidate.
84///
85/// [`crate::Memory`] gathers the raw signals (cosine similarity from the
86/// embedder, the store's lexical score) and asks the scorer. Replace it to
87/// change ranking without touching storage; a store that ranks on its own
88/// can bypass scoring entirely through [`crate::MemoryStore::search_facts`].
89pub trait Scorer: Send + Sync {
90    /// `semantic` is `None` when either side has no usable embedding.
91    /// Return `None` to drop the fact.
92    fn score_fact(
93        &self,
94        fact: &Fact,
95        semantic: Option<f32>,
96        lexical: f32,
97        now: DateTime<Utc>,
98    ) -> Option<Score>;
99
100    /// [`Scorer::score_fact`] with the fact's graph relation to the query's
101    /// other hits (0.0-1.0). The default ignores it, so a scorer written
102    /// before this signal existed keeps ranking as it did.
103    fn score_fact_with_graph(
104        &self,
105        fact: &Fact,
106        semantic: Option<f32>,
107        lexical: f32,
108        _graph: f32,
109        now: DateTime<Utc>,
110    ) -> Option<Score> {
111        self.score_fact(fact, semantic, lexical, now)
112    }
113
114    fn score_episode(
115        &self,
116        episode: &Episode,
117        semantic: Option<f32>,
118        lexical: f32,
119        now: DateTime<Utc>,
120    ) -> Option<Score>;
121}
122
123/// The daemon's hybrid ranking: weighted semantic + lexical + graph +
124/// freshness + confidence + provenance, gated on relevance thresholds.
125#[derive(Debug, Clone, Default)]
126pub struct HybridScorer {
127    pub config: ScoringConfig,
128}
129
130impl HybridScorer {
131    pub fn new(config: ScoringConfig) -> Self {
132        Self { config }
133    }
134
135    /// 1.0 when just updated, 0.0 at or beyond the freshness window.
136    pub fn freshness(&self, now: DateTime<Utc>, updated_at: DateTime<Utc>) -> f32 {
137        let window = self.config.freshness_window.num_seconds().max(1) as f32;
138        let age = (now - updated_at).num_seconds().max(0) as f32;
139        (1.0 - age / window).clamp(0.0, 1.0)
140    }
141
142    fn relevant(&self, semantic: Option<f32>, lexical: f32) -> bool {
143        semantic.is_some_and(|s| s > self.config.semantic_min) || lexical > self.config.lexical_min
144    }
145}
146
147impl Scorer for HybridScorer {
148    fn score_fact(
149        &self,
150        fact: &Fact,
151        semantic: Option<f32>,
152        lexical: f32,
153        now: DateTime<Utc>,
154    ) -> Option<Score> {
155        self.score_fact_with_graph(fact, semantic, lexical, 0.0, now)
156    }
157
158    /// The graph signal orders relevant facts; like freshness, it never lets
159    /// an irrelevant one through.
160    fn score_fact_with_graph(
161        &self,
162        fact: &Fact,
163        semantic: Option<f32>,
164        lexical: f32,
165        graph: f32,
166        now: DateTime<Utc>,
167    ) -> Option<Score> {
168        if !self.relevant(semantic, lexical) {
169            return None;
170        }
171        let signals = Signals {
172            semantic: semantic.unwrap_or(0.0).clamp(0.0, 1.0),
173            lexical: lexical.clamp(0.0, 1.0),
174            graph: graph.clamp(0.0, 1.0),
175            freshness: self.freshness(now, fact.updated_at),
176            confidence: fact.confidence.clamp(0.0, 1.0),
177            provenance: if fact.source.excerpt.is_some() {
178                self.config.provenance_with_excerpt
179            } else {
180                self.config.provenance_without_excerpt
181            },
182        };
183        let value = self.config.weights.fuse(&signals);
184        (value > self.config.min_score).then_some(Score { value, signals })
185    }
186
187    /// Episodes rank on relevance plus a small importance term, boosted by
188    /// recall count. Age is deliberately absent (daemon `scoring.rs`): an
189    /// old conversation must stay discoverable.
190    fn score_episode(
191        &self,
192        episode: &Episode,
193        semantic: Option<f32>,
194        lexical: f32,
195        _now: DateTime<Utc>,
196    ) -> Option<Score> {
197        if !self.relevant(semantic, lexical) {
198            return None;
199        }
200        let signals = Signals {
201            semantic: semantic.unwrap_or(0.0).clamp(0.0, 1.0),
202            lexical: lexical.clamp(0.0, 1.0),
203            confidence: episode.importance.clamp(0.0, 1.0),
204            provenance: 1.0,
205            ..Signals::default()
206        };
207        let value = self.config.weights.fuse(&signals) * episode_recall_boost(episode.recall_count);
208        (value > self.config.min_score).then_some(Score { value, signals })
209    }
210}
211
212/// Bounded reinforcement for often-recalled episodes: at most +16%.
213pub fn episode_recall_boost(recall_count: u32) -> f32 {
214    1.0 + ((recall_count as f32 + 1.0).ln() * 0.04).min(0.16)
215}
216
217/// Episode importance from typed session features (port of the daemon's
218/// `calculate_episode_importance`). Base 0.5, clamped to 0.1..=1.0.
219pub fn episode_importance(
220    message_count: usize,
221    has_errors: bool,
222    has_decisions: bool,
223    has_goals: bool,
224    emotional_intensity: f32,
225) -> f32 {
226    let mut importance = 0.5;
227    if message_count > 20 {
228        importance += 0.2;
229    } else if message_count > 10 {
230        importance += 0.1;
231    }
232    if has_errors {
233        importance += 0.15;
234    }
235    if has_decisions {
236        importance += 0.1;
237    }
238    if has_goals {
239        importance += 0.1;
240    }
241    let intensity = if emotional_intensity.is_finite() {
242        emotional_intensity.clamp(0.0, 1.0)
243    } else {
244        0.0
245    };
246    importance += intensity * 0.2;
247    importance.clamp(0.1, 1.0)
248}
249
250/// Function words that carry no retrieval signal. Used only to tokenize
251/// for lexical overlap and hashing, never to decide what is remembered.
252pub(crate) fn is_stopword(token: &str) -> bool {
253    matches!(
254        token,
255        "a" | "an"
256            | "and"
257            | "are"
258            | "as"
259            | "at"
260            | "be"
261            | "did"
262            | "do"
263            | "does"
264            | "for"
265            | "from"
266            | "how"
267            | "i"
268            | "in"
269            | "is"
270            | "it"
271            | "me"
272            | "my"
273            | "of"
274            | "on"
275            | "or"
276            | "please"
277            | "tell"
278            | "that"
279            | "the"
280            | "to"
281            | "was"
282            | "we"
283            | "were"
284            | "what"
285            | "when"
286            | "where"
287            | "who"
288            | "why"
289            | "you"
290            | "your"
291    )
292}
293
294/// Lowercase alphanumeric words, stopwords removed. Splits on `_` too, so
295/// `favorite_color` yields `favorite` and `color`.
296pub fn tokens(text: &str) -> Vec<String> {
297    text.to_lowercase()
298        .split(|c: char| !c.is_alphanumeric())
299        .filter(|t| !t.is_empty() && !is_stopword(t))
300        .map(str::to_owned)
301        .collect()
302}
303
304/// Fraction of distinct query tokens that occur as words in `text`
305/// (0.0-1.0). The in-memory store's lexical signal.
306pub fn term_overlap(query: &str, text: &str) -> f32 {
307    let query: HashSet<String> = tokens(query).into_iter().collect();
308    if query.is_empty() {
309        return 0.0;
310    }
311    let text: HashSet<String> = tokens(text).into_iter().collect();
312    query.intersection(&text).count() as f32 / query.len() as f32
313}
314
315/// Distinct words two texts share over the words they have between them
316/// (0.0-1.0), stopwords removed.
317pub fn text_similarity(a: &str, b: &str) -> f32 {
318    let a: HashSet<String> = tokens(a).into_iter().collect();
319    let b: HashSet<String> = tokens(b).into_iter().collect();
320    let total = a.union(&b).count();
321    if total == 0 {
322        return 0.0;
323    }
324    a.intersection(&b).count() as f32 / total as f32
325}
326
327/// A conversation turn's importance (0.1-1.0) from structure only: its role
328/// (system prompts are not memories; tool output counts less than what the
329/// user says) and its length. Nothing is inferred from the words used;
330/// deciding what is durable is the extraction model's job.
331pub fn turn_importance(role: &str, content: Option<&str>) -> f32 {
332    let base: f32 = match role {
333        "system" => return 0.0,
334        "tool" => 0.3,
335        "assistant" => 0.5,
336        "user" => 0.6,
337        _ => 0.5,
338    };
339    let length = content.map_or(0, str::len);
340    let adjust = if length > 200 {
341        0.2
342    } else if length < 20 {
343        -0.2
344    } else {
345        0.0
346    };
347    (base + adjust).clamp(0.1, 1.0)
348}
349
350/// Fraction of distinct query words that occur as words in `text`
351/// (0.0-1.0), counting every word, stopwords included. Unlike
352/// [`term_overlap`], a short query such as "who is she" keeps all its words:
353/// the signal for ranking when no embedder is available.
354pub fn word_overlap(query: &str, text: &str) -> f32 {
355    let words = |value: &str| {
356        value
357            .to_lowercase()
358            .split(|c: char| !c.is_alphanumeric())
359            .filter(|word| !word.is_empty())
360            .map(str::to_owned)
361            .collect::<HashSet<_>>()
362    };
363    let query = words(query);
364    if query.is_empty() {
365        return 0.0;
366    }
367    query.intersection(&words(text)).count() as f32 / query.len() as f32
368}
369
370#[cfg(test)]
371mod tests {
372    use super::*;
373
374    #[test]
375    fn turn_importance_reads_role_and_length_only() {
376        assert_eq!(turn_importance("system", Some("anything")), 0.0);
377        assert!(
378            turn_importance("user", Some(&"a".repeat(300)))
379                > turn_importance("user", Some("a medium length message"))
380        );
381        assert!(
382            turn_importance("user", Some("ok"))
383                < turn_importance("user", Some("a medium length message"))
384        );
385        assert!(
386            turn_importance("tool", Some("output of some length"))
387                < turn_importance("user", Some("output of some length"))
388        );
389        // Wording does not matter, only structure.
390        assert_eq!(
391            turn_importance("user", Some("please remember this one")),
392            turn_importance("user", Some("the weather is mild today"))
393        );
394    }
395
396    #[test]
397    fn word_overlap_counts_every_word() {
398        assert_eq!(word_overlap("who is she", "she is here"), 2.0 / 3.0);
399        assert_eq!(word_overlap("", "anything"), 0.0);
400        assert_eq!(word_overlap("Mia", "mia and zoe"), 1.0);
401    }
402
403    #[test]
404    fn corroborated_result_beats_single_weak_signal() {
405        let w = HybridWeights::default();
406        let corroborated = w.fuse(&Signals {
407            semantic: 0.55,
408            lexical: 0.8,
409            graph: 1.0,
410            confidence: 1.0,
411            provenance: 1.0,
412            ..Default::default()
413        });
414        let vector_only = w.fuse(&Signals {
415            semantic: 0.7,
416            ..Default::default()
417        });
418        assert!(corroborated > vector_only);
419        let max = w.fuse(&Signals {
420            semantic: 2.0,
421            lexical: 2.0,
422            graph: 2.0,
423            freshness: 2.0,
424            confidence: 2.0,
425            provenance: 2.0,
426        });
427        assert!((max - 1.0).abs() < 1e-6);
428    }
429
430    #[test]
431    fn importance_and_boost_are_bounded() {
432        assert_eq!(episode_importance(3, false, false, false, 0.0), 0.5);
433        assert_eq!(episode_importance(30, true, true, true, 1.0), 1.0);
434        assert!(episode_importance(12, true, false, false, 0.0) > 0.7);
435        assert_eq!(episode_recall_boost(0), 1.0);
436        assert!(episode_recall_boost(1_000_000) <= 1.16 + 1e-6);
437    }
438
439    #[test]
440    fn overlap_counts_words_not_substrings() {
441        assert_eq!(term_overlap("dog", "dodger stadium"), 0.0);
442        assert_eq!(
443            term_overlap("favorite color", "preference favorite_color: blue"),
444            1.0
445        );
446        assert_eq!(term_overlap("the", "the"), 0.0);
447    }
448}