1use std::collections::HashSet;
6
7use chrono::{DateTime, Utc};
8
9use crate::types::{Episode, Fact, Score, Signals};
10
11#[derive(Debug, Clone, Copy, PartialEq)]
14pub struct HybridWeights {
15 pub semantic: f32,
16 pub lexical: f32,
17 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 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#[derive(Debug, Clone, Copy, PartialEq)]
52pub struct ScoringConfig {
53 pub weights: HybridWeights,
54 pub semantic_min: f32,
56 pub lexical_min: f32,
60 pub freshness_window: chrono::Duration,
62 pub provenance_with_excerpt: f32,
64 pub provenance_without_excerpt: f32,
65 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
83pub trait Scorer: Send + Sync {
90 fn score_fact(
93 &self,
94 fact: &Fact,
95 semantic: Option<f32>,
96 lexical: f32,
97 now: DateTime<Utc>,
98 ) -> Option<Score>;
99
100 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#[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 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 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 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
212pub 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
217pub 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
250pub(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
294pub 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
304pub 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
315pub 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
327pub 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
350pub 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 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}