1use chrono::{DateTime, Utc};
10use uuid::Uuid;
11
12use crate::{EvidenceLink, MemoryItem, MemoryKind, MemoryStore, MemoryStoreError};
13
14#[derive(Debug, Clone)]
16pub struct SessionEpisode {
17 pub session_id: String,
19 pub entry_id: String,
21 pub turn_index: usize,
23 pub role: String,
25 pub content: String,
27 pub timestamp: DateTime<Utc>,
29}
30
31#[derive(Debug, Clone)]
33pub struct MemoryCandidate {
34 pub kind: MemoryKind,
36 pub key: String,
38 pub content: String,
40 pub confidence: f64,
42 pub source_session_id: String,
44 pub source_entry_id: String,
46 pub source_turn_index: usize,
48}
49
50pub trait EpisodeExtractor {
55 fn extract(&self, episodes: &[SessionEpisode]) -> Vec<MemoryCandidate>;
57}
58
59pub struct RuleBasedExtractor {
64 max_candidates: usize,
66}
67
68impl RuleBasedExtractor {
69 pub fn new() -> Self {
71 Self { max_candidates: 20 }
72 }
73
74 pub fn with_max_candidates(max: usize) -> Self {
76 Self {
77 max_candidates: max,
78 }
79 }
80}
81
82impl Default for RuleBasedExtractor {
83 fn default() -> Self {
84 Self::new()
85 }
86}
87
88impl EpisodeExtractor for RuleBasedExtractor {
89 fn extract(&self, episodes: &[SessionEpisode]) -> Vec<MemoryCandidate> {
90 let mut candidates: Vec<MemoryCandidate> = Vec::new();
91
92 for episode in episodes {
93 if episode.content.len() < 10 {
95 continue;
96 }
97
98 if episode.role == "system" || episode.role == "tool" {
100 continue;
101 }
102
103 if episode.role != "user" && episode.role != "assistant" {
105 continue;
106 }
107
108 let key = derive_key(&episode.content);
110
111 let confidence = compute_confidence(&episode.content, &episode.role);
113
114 candidates.push(MemoryCandidate {
115 kind: MemoryKind::Semantic,
116 key,
117 content: episode.content.clone(),
118 confidence,
119 source_session_id: episode.session_id.clone(),
120 source_entry_id: episode.entry_id.clone(),
121 source_turn_index: episode.turn_index,
122 });
123 }
124
125 candidates.sort_by(|a, b| {
127 b.confidence
128 .partial_cmp(&a.confidence)
129 .unwrap_or(std::cmp::Ordering::Equal)
130 .then_with(|| a.source_turn_index.cmp(&b.source_turn_index))
131 });
132
133 candidates.truncate(self.max_candidates);
135
136 candidates
137 }
138}
139
140fn derive_key(content: &str) -> String {
142 let truncated = content
143 .split_once('\n')
144 .map(|(first, _)| first)
145 .unwrap_or(content);
146 let truncated = truncated.chars().take(40).collect::<String>();
147 truncated.trim().to_string()
148}
149
150fn compute_confidence(content: &str, role: &str) -> f64 {
152 let lower = content.trim_start().to_lowercase();
153
154 let markers = ["remember", "note", "important", "always", "never"];
156 if markers.iter().any(|m| lower.starts_with(m)) {
157 return 0.8;
158 }
159
160 if role == "user" && content.len() > 50 {
162 return 0.6;
163 }
164
165 0.4
167}
168
169#[derive(Debug, Clone)]
171pub struct ConsolidationConfig {
172 pub enabled: bool,
174 pub max_candidates_per_session: usize,
176}
177
178impl Default for ConsolidationConfig {
179 fn default() -> Self {
180 Self {
181 enabled: false,
182 max_candidates_per_session: 20,
183 }
184 }
185}
186
187#[derive(Debug, Clone, Default)]
189pub struct ConsolidationReport {
190 pub candidates_extracted: usize,
192 pub inserted: usize,
194 pub duplicates_skipped: usize,
196 pub evidence_links_created: usize,
198 pub errors: Vec<String>,
200}
201
202pub fn consolidate_episodes(
218 store: &mut MemoryStore,
219 episodes: &[SessionEpisode],
220 extractor: &dyn EpisodeExtractor,
221 config: &ConsolidationConfig,
222) -> Result<ConsolidationReport, MemoryStoreError> {
223 let mut report = ConsolidationReport::default();
224
225 if !config.enabled {
227 return Ok(report);
228 }
229
230 let candidates = extractor.extract(episodes);
232 report.candidates_extracted = candidates.len();
233
234 for candidate in &candidates {
236 if candidate.content.is_empty() || candidate.key.is_empty() {
238 report.errors.push(format!(
239 "skipped malformed candidate: empty content or key (entry_id={})",
240 candidate.source_entry_id
241 ));
242 continue;
243 }
244
245 let now = Utc::now();
246
247 let memory_id = Uuid::new_v4().to_string();
248 let item = MemoryItem {
249 id: memory_id.clone(),
250 kind: candidate.kind,
251 key: candidate.key.clone(),
252 content: candidate.content.clone(),
253 confidence: candidate.confidence,
254 created_at: now,
255 last_reinforced: now,
256 last_accessed: None,
257 contradiction_ref: None,
258 };
259
260 match store.insert(item) {
261 Ok(inserted) => {
262 if inserted {
263 report.inserted += 1;
264
265 let link = EvidenceLink {
266 id: Uuid::new_v4().to_string(),
267 memory_id,
268 source_type: "session".to_string(),
269 source_ref: format!(
270 "{}:{}:{}",
271 candidate.source_session_id,
272 candidate.source_entry_id,
273 candidate.source_turn_index
274 ),
275 created_at: now,
276 };
277
278 if let Err(e) = store.insert_evidence(link) {
279 report
280 .errors
281 .push(format!("failed to insert evidence link: {e}"));
282 } else {
283 report.evidence_links_created += 1;
284 }
285 } else {
286 report.duplicates_skipped += 1;
287 }
288 }
289 Err(e) => {
290 report
291 .errors
292 .push(format!("failed to insert memory item: {e}"));
293 }
294 }
295 }
296
297 Ok(report)
298}
299
300#[cfg(test)]
301mod tests {
302 use super::*;
303
304 fn make_episode(
305 session_id: &str,
306 entry_id: &str,
307 turn_index: usize,
308 role: &str,
309 content: &str,
310 ) -> SessionEpisode {
311 SessionEpisode {
312 session_id: session_id.to_string(),
313 entry_id: entry_id.to_string(),
314 turn_index,
315 role: role.to_string(),
316 content: content.to_string(),
317 timestamp: Utc::now(),
318 }
319 }
320
321 fn make_episodes() -> Vec<SessionEpisode> {
322 vec![
323 make_episode(
324 "sess-1",
325 "entry-1",
326 0,
327 "user",
328 "remember to use Rust edition 2024 for all new projects",
329 ),
330 make_episode(
331 "sess-1",
332 "entry-2",
333 1,
334 "assistant",
335 "I will use Rust edition 2024. It provides improved macro hygiene and async traits.",
336 ),
337 make_episode(
338 "sess-1",
339 "entry-3",
340 2,
341 "system",
342 "Tool call result: success",
343 ),
344 make_episode("sess-1", "entry-4", 3, "user", "short"),
345 make_episode(
346 "sess-1",
347 "entry-5",
348 4,
349 "user",
350 "This is a longer user message that should get medium confidence because it exceeds fifty characters in length",
351 ),
352 ]
353 }
354
355 #[test]
356 fn consolidation_creates_semantic_memory_with_evidence() {
357 let mut store = MemoryStore::open_memory().unwrap();
358 let episodes = make_episodes();
359 let extractor = RuleBasedExtractor::new();
360 let config = ConsolidationConfig {
361 enabled: true,
362 max_candidates_per_session: 20,
363 };
364
365 let report = consolidate_episodes(&mut store, &episodes, &extractor, &config).unwrap();
366
367 assert!(
368 report.inserted > 0,
369 "Should have inserted at least one item"
370 );
371 assert!(
372 report.evidence_links_created > 0,
373 "Should have created evidence links"
374 );
375
376 let results = store.retrieve("Rust", 10).unwrap();
378 assert!(!results.is_empty(), "Should find Rust-related memory");
379
380 let has_valid_evidence = results.iter().any(|r| {
382 r.evidence
383 .iter()
384 .any(|e| e.source_ref.contains("sess-1") && e.source_ref.contains("entry-"))
385 });
386 assert!(
387 has_valid_evidence,
388 "Evidence should reference the source session and entry"
389 );
390 }
391
392 #[test]
393 fn exact_duplicate_dedup_by_content_hash() {
394 let mut store = MemoryStore::open_memory().unwrap();
395 let episodes = make_episodes();
396 let extractor = RuleBasedExtractor::new();
397 let config = ConsolidationConfig {
398 enabled: true,
399 max_candidates_per_session: 20,
400 };
401
402 let report1 = consolidate_episodes(&mut store, &episodes, &extractor, &config).unwrap();
404 let first_inserted = report1.inserted;
405 assert!(first_inserted > 0);
406
407 let report2 = consolidate_episodes(&mut store, &episodes, &extractor, &config).unwrap();
409
410 assert_eq!(
411 report2.inserted, 0,
412 "Second run should insert nothing (all duplicates)"
413 );
414 assert!(
415 report2.duplicates_skipped > 0,
416 "Second run should skip duplicates"
417 );
418 }
419
420 #[test]
421 fn conflicting_same_key_preserved_not_overwritten() {
422 let mut store = MemoryStore::open_memory().unwrap();
423
424 let episodes = vec![
426 make_episode(
427 "sess-2",
428 "entry-a",
429 0,
430 "user",
431 "Python is a dynamically typed programming language with great ecosystem",
432 ),
433 make_episode(
434 "sess-2",
435 "entry-b",
436 1,
437 "user",
438 "Python is a statically typed programming language with strict type checking",
439 ),
440 ];
441
442 let extractor = RuleBasedExtractor::new();
443 let config = ConsolidationConfig {
444 enabled: true,
445 max_candidates_per_session: 20,
446 };
447
448 let report = consolidate_episodes(&mut store, &episodes, &extractor, &config).unwrap();
449
450 assert_eq!(
451 report.inserted, 2,
452 "Both conflicting items should be inserted"
453 );
454 assert_eq!(store.count().unwrap(), 2, "Store should contain both items");
455 }
456
457 #[test]
458 fn malformed_and_empty_sessions_degrade_gracefully() {
459 let mut store = MemoryStore::open_memory().unwrap();
460
461 let episodes = vec![
462 make_episode("sess-3", "entry-1", 0, "user", ""),
464 make_episode("sess-3", "entry-2", 1, "user", "hi"),
466 make_episode(
468 "sess-3",
469 "entry-3",
470 2,
471 "system",
472 "This is a system message with enough content",
473 ),
474 make_episode(
476 "sess-3",
477 "entry-4",
478 3,
479 "tool",
480 "Tool output with enough characters to pass length check",
481 ),
482 ];
483
484 let extractor = RuleBasedExtractor::new();
485 let config = ConsolidationConfig {
486 enabled: true,
487 max_candidates_per_session: 20,
488 };
489
490 let report = consolidate_episodes(&mut store, &episodes, &extractor, &config).unwrap();
492
493 assert_eq!(
496 report.candidates_extracted, 0,
497 "No valid candidates from malformed episodes"
498 );
499 assert_eq!(report.inserted, 0);
500 }
503
504 #[test]
505 fn disabled_config_no_writes() {
506 let mut store = MemoryStore::open_memory().unwrap();
507 let episodes = make_episodes();
508 let extractor = RuleBasedExtractor::new();
509 let config = ConsolidationConfig {
510 enabled: false,
511 max_candidates_per_session: 20,
512 };
513
514 let report = consolidate_episodes(&mut store, &episodes, &extractor, &config).unwrap();
515
516 assert_eq!(report.candidates_extracted, 0);
517 assert_eq!(report.inserted, 0);
518 assert_eq!(report.duplicates_skipped, 0);
519 assert_eq!(report.evidence_links_created, 0);
520 assert!(report.errors.is_empty());
521 assert_eq!(store.count().unwrap(), 0, "Store should be empty");
522 }
523
524 #[test]
525 fn rule_based_extractor_is_deterministic() {
526 let episodes = make_episodes();
527 let extractor = RuleBasedExtractor::new();
528
529 let result1 = extractor.extract(&episodes);
530 let result2 = extractor.extract(&episodes);
531
532 assert_eq!(
533 result1.len(),
534 result2.len(),
535 "Both extractions should produce same number of candidates"
536 );
537
538 for (c1, c2) in result1.iter().zip(result2.iter()) {
539 assert_eq!(c1.key, c2.key, "Keys should match");
540 assert_eq!(c1.confidence, c2.confidence, "Confidence should match");
541 assert_eq!(
542 c1.source_turn_index, c2.source_turn_index,
543 "Turn index should match"
544 );
545 }
546 }
547}