1use chrono::{DateTime, Utc};
12use uuid::Uuid;
13
14use crate::{EvidenceLink, MemoryItem, MemoryKind, MemoryStore, MemoryStoreError};
15
16#[derive(Debug, Clone, PartialEq, Eq, Hash)]
18pub enum AdmissionReason {
19 Admitted,
21 SensitiveContent,
23 BelowThreshold,
25 ExcludedRole,
27 TooShort,
29}
30
31#[derive(Debug, Clone)]
36pub struct AdmissionDecision {
37 pub admit: bool,
39 pub score: f64,
41 pub reason: AdmissionReason,
43}
44const ADMISSION_THRESHOLD: f64 = 0.15;
47
48const SENSITIVE_WORD_TOKENS: &[&str] = &[
50 "password",
51 "secret",
52 "token",
53 "credential",
54 "api_key",
55 "apikey",
56];
57
58const SENSITIVE_SUBSTRINGS: &[&str] = &[
60 "access_token",
61 "refresh_token",
62 "authorization:",
63 "bearer ",
64 "cookie:",
65 "set-cookie",
66 "private_key",
67 "-----begin",
68 "sk-ant-",
69 "sk-proj-",
70];
71
72const NOISE_PREFIXES: &[&str] = &[
75 "can you help",
76 "how are you",
77 "thanks",
78 "thank you",
79 "that's helpful",
80 "hello",
81 "hi,",
82 "hi!",
83 "hey ",
84 "ok,",
85 "got it",
86 "i see",
87 "makes sense",
88 "understood",
89 "sounds good",
90 "let me think",
91 "i was wondering",
92 "i've been reading",
93 "i'm trying to figure out",
94 "i'm not sure",
95 "seems like",
96];
97
98#[must_use]
105pub fn is_sensitive_content(content: &str) -> bool {
106 let lower = content.to_lowercase();
107
108 if SENSITIVE_SUBSTRINGS.iter().any(|p| lower.contains(p)) {
110 return true;
111 }
112
113 for token in SENSITIVE_WORD_TOKENS {
115 let mut search_from = 0;
116 while let Some(pos) = lower[search_from..].find(token) {
117 let abs_pos = search_from + pos;
118 let after = abs_pos + token.len();
119 let before_ok = abs_pos == 0
120 || lower
121 .as_bytes()
122 .get(abs_pos - 1)
123 .is_some_and(|&c| !c.is_ascii_alphanumeric());
124 let after_ok = after >= lower.len()
125 || lower
126 .as_bytes()
127 .get(after)
128 .is_some_and(|&c| !c.is_ascii_alphanumeric());
129 if before_ok && after_ok {
130 return true;
131 }
132 search_from = abs_pos + 1;
133 }
134 }
135
136 false
137}
138
139#[must_use]
142fn is_noise_content(content: &str) -> bool {
143 let lower = content.trim_start().to_lowercase();
144 NOISE_PREFIXES.iter().any(|p| lower.starts_with(p))
145}
146
147#[must_use]
152pub fn evaluate_admission(content: &str, role: &str) -> AdmissionDecision {
153 if role == "system" || role == "tool" {
155 return AdmissionDecision {
156 admit: false,
157 score: 0.0,
158 reason: AdmissionReason::ExcludedRole,
159 };
160 }
161
162 if content.len() < 10 {
164 return AdmissionDecision {
165 admit: false,
166 score: 0.0,
167 reason: AdmissionReason::TooShort,
168 };
169 }
170
171 if is_sensitive_content(content) {
173 return AdmissionDecision {
174 admit: false,
175 score: 0.0,
176 reason: AdmissionReason::SensitiveContent,
177 };
178 }
179
180 if is_noise_content(content) {
182 return AdmissionDecision {
183 admit: false,
184 score: 0.0,
185 reason: AdmissionReason::BelowThreshold,
186 };
187 }
188
189 let score = compute_admission_score(content, role);
191
192 AdmissionDecision {
193 admit: score >= ADMISSION_THRESHOLD,
194 score,
195 reason: if score >= ADMISSION_THRESHOLD {
196 AdmissionReason::Admitted
197 } else {
198 AdmissionReason::BelowThreshold
199 },
200 }
201}
202
203fn compute_admission_score(content: &str, _role: &str) -> f64 {
209 let lower = content.trim_start().to_lowercase();
210
211 let novelty: f64 = if lower.starts_with("actually")
214 || lower.starts_with("no,")
215 || lower.starts_with("correction")
216 {
217 0.9 } else if lower.starts_with("note")
219 || lower.starts_with("important")
220 || lower.contains("fix for")
221 || lower.contains("deadlock")
222 || lower.contains("caused by")
223 {
224 0.8 } else if lower.starts_with("remember")
226 || lower.starts_with("always")
227 || lower.starts_with("never")
228 {
229 0.7 } else if lower.starts_with("prefer") || lower.contains("i prefer") {
231 0.6 } else {
233 0.1 };
235
236 let utility: f64 = if lower.starts_with("always")
238 || lower.starts_with("never")
239 || lower.starts_with("remember")
240 || lower.starts_with("note")
241 {
242 0.9
243 } else if lower.starts_with("actually")
244 || lower.starts_with("no,")
245 || lower.contains("was wrong")
246 || lower.contains("is wrong")
247 {
248 0.85
249 } else if lower.starts_with("important")
250 || lower.contains("fix for")
251 || lower.contains("caused by")
252 || lower.contains("fixed it")
253 {
254 0.8
255 } else if lower.starts_with("prefer") || lower.contains("i prefer") {
256 0.7
257 } else {
258 0.05 };
260 novelty * utility
261}
262
263#[derive(Debug, Clone)]
265pub struct SessionEpisode {
266 pub session_id: String,
268 pub entry_id: String,
270 pub turn_index: usize,
272 pub role: String,
274 pub content: String,
276 pub timestamp: DateTime<Utc>,
278}
279
280#[derive(Debug, Clone)]
282pub struct MemoryCandidate {
283 pub kind: MemoryKind,
285 pub key: String,
287 pub content: String,
289 pub confidence: f64,
291 pub admission_score: f64,
295 pub source_session_id: String,
297 pub source_entry_id: String,
299 pub source_turn_index: usize,
301}
302pub trait EpisodeExtractor {
307 fn extract(&self, episodes: &[SessionEpisode]) -> Vec<MemoryCandidate>;
309}
310
311pub struct RuleBasedExtractor {
316 max_candidates: usize,
318}
319
320impl RuleBasedExtractor {
321 pub fn new() -> Self {
323 Self { max_candidates: 20 }
324 }
325
326 pub fn with_max_candidates(max: usize) -> Self {
328 Self {
329 max_candidates: max,
330 }
331 }
332}
333
334impl Default for RuleBasedExtractor {
335 fn default() -> Self {
336 Self::new()
337 }
338}
339
340impl EpisodeExtractor for RuleBasedExtractor {
341 fn extract(&self, episodes: &[SessionEpisode]) -> Vec<MemoryCandidate> {
342 let mut candidates: Vec<MemoryCandidate> = Vec::new();
343
344 for episode in episodes {
345 if episode.content.len() < 10 {
346 continue;
347 }
348 if episode.role == "system" || episode.role == "tool" {
349 continue;
350 }
351 if episode.role != "user" && episode.role != "assistant" {
352 continue;
353 }
354 if is_sensitive_content(&episode.content) {
357 continue;
358 }
359
360 let key = derive_key(&episode.content);
361 let confidence = compute_confidence(&episode.content, &episode.role);
362
363 candidates.push(MemoryCandidate {
364 kind: MemoryKind::Semantic,
365 key,
366 content: episode.content.clone(),
367 confidence,
368 admission_score: confidence,
369 source_session_id: episode.session_id.clone(),
370 source_entry_id: episode.entry_id.clone(),
371 source_turn_index: episode.turn_index,
372 });
373 }
374
375 candidates.sort_by(|a, b| {
378 b.confidence
379 .partial_cmp(&a.confidence)
380 .unwrap_or(std::cmp::Ordering::Equal)
381 .then_with(|| a.source_turn_index.cmp(&b.source_turn_index))
382 });
383
384 candidates.truncate(self.max_candidates);
385 candidates
386 }
387}
388
389fn compute_confidence(content: &str, role: &str) -> f64 {
391 let lower = content.trim_start().to_lowercase();
392 let markers = ["remember", "note", "important", "always", "never"];
393 if markers.iter().any(|marker| lower.starts_with(marker)) {
394 return 0.8;
395 }
396 if role == "user" && content.len() > 50 {
397 return 0.6;
398 }
399 0.4
400}
401
402fn derive_key(content: &str) -> String {
404 let truncated = content
405 .split_once('\n')
406 .map(|(first, _)| first)
407 .unwrap_or(content);
408 let truncated = truncated.chars().take(40).collect::<String>();
409 truncated.trim().to_string()
410}
411
412#[derive(Debug, Clone)]
414pub struct ConsolidationConfig {
415 pub enabled: bool,
417 pub max_candidates_per_session: usize,
419}
420
421impl Default for ConsolidationConfig {
422 fn default() -> Self {
423 Self {
424 enabled: false,
425 max_candidates_per_session: 20,
426 }
427 }
428}
429
430#[derive(Debug, Clone, Default)]
432pub struct ConsolidationReport {
433 pub candidates_extracted: usize,
435 pub inserted: usize,
437 pub duplicates_skipped: usize,
439 pub evidence_links_created: usize,
441 pub errors: Vec<String>,
443}
444
445pub fn consolidate_episodes(
461 store: &mut MemoryStore,
462 episodes: &[SessionEpisode],
463 extractor: &dyn EpisodeExtractor,
464 config: &ConsolidationConfig,
465) -> Result<ConsolidationReport, MemoryStoreError> {
466 let mut report = ConsolidationReport::default();
467
468 if !config.enabled {
470 return Ok(report);
471 }
472
473 let candidates = extractor.extract(episodes);
475 report.candidates_extracted = candidates.len();
476
477 for candidate in &candidates {
479 if candidate.content.is_empty() || candidate.key.is_empty() {
481 report.errors.push(format!(
482 "skipped malformed candidate: empty content or key (entry_id={})",
483 candidate.source_entry_id
484 ));
485 continue;
486 }
487
488 let now = Utc::now();
489
490 let memory_id = Uuid::new_v4().to_string();
491 let item = MemoryItem {
492 id: memory_id.clone(),
493 kind: candidate.kind,
494 key: candidate.key.clone(),
495 content: candidate.content.clone(),
496 confidence: candidate.confidence,
497 created_at: now,
498 last_reinforced: now,
499 last_accessed: None,
500 contradiction_ref: None,
501 };
502
503 match store.insert(item) {
504 Ok(inserted) => {
505 if inserted {
506 report.inserted += 1;
507
508 let link = EvidenceLink {
509 id: Uuid::new_v4().to_string(),
510 memory_id,
511 source_type: "session".to_string(),
512 source_ref: format!(
513 "{}:{}:{}",
514 candidate.source_session_id,
515 candidate.source_entry_id,
516 candidate.source_turn_index
517 ),
518 created_at: now,
519 };
520
521 if let Err(e) = store.insert_evidence(link) {
522 report
523 .errors
524 .push(format!("failed to insert evidence link: {e}"));
525 } else {
526 report.evidence_links_created += 1;
527 }
528 } else {
529 report.duplicates_skipped += 1;
530 }
531 }
532 Err(e) => {
533 report
534 .errors
535 .push(format!("failed to insert memory item: {e}"));
536 }
537 }
538 }
539
540 Ok(report)
541}
542
543#[cfg(test)]
544mod tests {
545 use super::*;
546
547 fn make_episode(
548 session_id: &str,
549 entry_id: &str,
550 turn_index: usize,
551 role: &str,
552 content: &str,
553 ) -> SessionEpisode {
554 SessionEpisode {
555 session_id: session_id.to_string(),
556 entry_id: entry_id.to_string(),
557 turn_index,
558 role: role.to_string(),
559 content: content.to_string(),
560 timestamp: Utc::now(),
561 }
562 }
563
564 fn make_episodes() -> Vec<SessionEpisode> {
565 vec![
566 make_episode(
567 "sess-1",
568 "entry-1",
569 0,
570 "user",
571 "remember to use Rust edition 2024 for all new projects",
572 ),
573 make_episode(
574 "sess-1",
575 "entry-2",
576 1,
577 "assistant",
578 "I will use Rust edition 2024. It provides improved macro hygiene and async traits.",
579 ),
580 make_episode(
581 "sess-1",
582 "entry-3",
583 2,
584 "system",
585 "Tool call result: success",
586 ),
587 make_episode("sess-1", "entry-4", 3, "user", "short"),
588 make_episode(
589 "sess-1",
590 "entry-5",
591 4,
592 "user",
593 "This is a longer user message that should get medium confidence because it exceeds fifty characters in length",
594 ),
595 ]
596 }
597
598 #[test]
599 fn consolidation_creates_semantic_memory_with_evidence() {
600 let mut store = MemoryStore::open_memory().expect("test operation should succeed");
601 let episodes = make_episodes();
602 let extractor = RuleBasedExtractor::new();
603 let config = ConsolidationConfig {
604 enabled: true,
605 max_candidates_per_session: 20,
606 };
607
608 let report = consolidate_episodes(&mut store, &episodes, &extractor, &config)
609 .expect("test operation should succeed");
610
611 assert!(
612 report.inserted > 0,
613 "Should have inserted at least one item"
614 );
615 assert!(
616 report.evidence_links_created > 0,
617 "Should have created evidence links"
618 );
619
620 let results = store
622 .retrieve("Rust", 10)
623 .expect("test operation should succeed");
624 assert!(!results.is_empty(), "Should find Rust-related memory");
625
626 let has_valid_evidence = results.iter().any(|r| {
628 r.evidence
629 .iter()
630 .any(|e| e.source_ref.contains("sess-1") && e.source_ref.contains("entry-"))
631 });
632 assert!(
633 has_valid_evidence,
634 "Evidence should reference the source session and entry"
635 );
636 }
637
638 #[test]
639 fn exact_duplicate_dedup_by_content_hash() {
640 let mut store = MemoryStore::open_memory().expect("test operation should succeed");
641 let episodes = make_episodes();
642 let extractor = RuleBasedExtractor::new();
643 let config = ConsolidationConfig {
644 enabled: true,
645 max_candidates_per_session: 20,
646 };
647
648 let report1 = consolidate_episodes(&mut store, &episodes, &extractor, &config)
650 .expect("test operation should succeed");
651 let first_inserted = report1.inserted;
652 assert!(first_inserted > 0);
653
654 let report2 = consolidate_episodes(&mut store, &episodes, &extractor, &config)
656 .expect("test operation should succeed");
657
658 assert_eq!(
659 report2.inserted, 0,
660 "Second run should insert nothing (all duplicates)"
661 );
662 assert!(
663 report2.duplicates_skipped > 0,
664 "Second run should skip duplicates"
665 );
666 }
667
668 #[test]
669 fn conflicting_same_key_preserved_not_overwritten() {
670 let mut store = MemoryStore::open_memory().expect("test operation should succeed");
671
672 let episodes = vec![
674 make_episode(
675 "sess-2",
676 "entry-a",
677 0,
678 "user",
679 "Note: Python is a dynamically typed programming language with great ecosystem",
680 ),
681 make_episode(
682 "sess-2",
683 "entry-b",
684 1,
685 "user",
686 "Note: Python is a statically typed programming language with strict type checking",
687 ),
688 ];
689
690 let extractor = RuleBasedExtractor::new();
691 let config = ConsolidationConfig {
692 enabled: true,
693 max_candidates_per_session: 20,
694 };
695
696 let report = consolidate_episodes(&mut store, &episodes, &extractor, &config)
697 .expect("test operation should succeed");
698
699 assert_eq!(
700 report.inserted, 2,
701 "Both conflicting items should be inserted"
702 );
703 assert_eq!(
704 store.count().expect("test operation should succeed"),
705 2,
706 "Store should contain both items"
707 );
708 }
709
710 #[test]
711 fn malformed_and_empty_sessions_degrade_gracefully() {
712 let mut store = MemoryStore::open_memory().expect("test operation should succeed");
713
714 let episodes = vec![
715 make_episode("sess-3", "entry-1", 0, "user", ""),
717 make_episode("sess-3", "entry-2", 1, "user", "hi"),
719 make_episode(
721 "sess-3",
722 "entry-3",
723 2,
724 "system",
725 "This is a system message with enough content",
726 ),
727 make_episode(
729 "sess-3",
730 "entry-4",
731 3,
732 "tool",
733 "Tool output with enough characters to pass length check",
734 ),
735 ];
736
737 let extractor = RuleBasedExtractor::new();
738 let config = ConsolidationConfig {
739 enabled: true,
740 max_candidates_per_session: 20,
741 };
742
743 let report = consolidate_episodes(&mut store, &episodes, &extractor, &config)
745 .expect("test operation should succeed");
746
747 assert_eq!(
750 report.candidates_extracted, 0,
751 "No valid candidates from malformed episodes"
752 );
753 assert_eq!(report.inserted, 0);
754 }
757
758 #[test]
759 fn disabled_config_no_writes() {
760 let mut store = MemoryStore::open_memory().expect("test operation should succeed");
761 let episodes = make_episodes();
762 let extractor = RuleBasedExtractor::new();
763 let config = ConsolidationConfig {
764 enabled: false,
765 max_candidates_per_session: 20,
766 };
767
768 let report = consolidate_episodes(&mut store, &episodes, &extractor, &config)
769 .expect("test operation should succeed");
770
771 assert_eq!(report.candidates_extracted, 0);
772 assert_eq!(report.inserted, 0);
773 assert_eq!(report.duplicates_skipped, 0);
774 assert_eq!(report.evidence_links_created, 0);
775 assert!(report.errors.is_empty());
776 assert_eq!(
777 store.count().expect("test operation should succeed"),
778 0,
779 "Store should be empty"
780 );
781 }
782
783 #[test]
784 fn rule_based_extractor_is_deterministic() {
785 let episodes = make_episodes();
786 let extractor = RuleBasedExtractor::new();
787
788 let result1 = extractor.extract(&episodes);
789 let result2 = extractor.extract(&episodes);
790
791 assert_eq!(
792 result1.len(),
793 result2.len(),
794 "Both extractions should produce same number of candidates"
795 );
796
797 for (c1, c2) in result1.iter().zip(result2.iter()) {
798 assert_eq!(c1.key, c2.key, "Keys should match");
799 assert_eq!(c1.confidence, c2.confidence, "Confidence should match");
800 assert_eq!(
801 c1.source_turn_index, c2.source_turn_index,
802 "Turn index should match"
803 );
804 }
805 }
806
807 #[test]
810 fn sensitive_content_is_rejected_before_write() {
811 let decision = evaluate_admission("api_key = sk-ant-1234567890abcdef", "user");
812 assert!(!decision.admit, "api_key content must not be admitted");
813 assert_eq!(decision.reason, AdmissionReason::SensitiveContent);
814
815 let decision2 = evaluate_admission("Authorization: Bearer token123", "user");
816 assert!(
817 !decision2.admit,
818 "Authorization header must not be admitted"
819 );
820 assert_eq!(decision2.reason, AdmissionReason::SensitiveContent);
821
822 let decision3 = evaluate_admission("password = secret123", "user");
823 assert!(!decision3.admit, "password content must not be admitted");
824 assert_eq!(decision3.reason, AdmissionReason::SensitiveContent);
825
826 let prose1 = evaluate_admission("my password is hunter2xyz", "user");
828 assert!(!prose1.admit, "prose-form password must not be admitted");
829 assert_eq!(prose1.reason, AdmissionReason::SensitiveContent);
830
831 let prose2 = evaluate_admission("the deploy secret is prod-live-9f8a", "user");
832 assert!(!prose2.admit, "prose-form secret must not be admitted");
833 assert_eq!(prose2.reason, AdmissionReason::SensitiveContent);
834
835 let prose3 = evaluate_admission("session token is abc123", "user");
836 assert!(!prose3.admit, "prose-form token must not be admitted");
837
838 let normal1 = evaluate_admission("Always break the task-list into subtasks", "user");
840 assert!(
841 normal1.reason != AdmissionReason::SensitiveContent,
842 "'task-list' must not be flagged as sk- credential"
843 );
844
845 let normal2 = evaluate_admission("Important: the risk-averse policy applies here", "user");
846 assert!(
847 normal2.reason != AdmissionReason::SensitiveContent,
848 "'risk-averse' must not be flagged as sk- credential"
849 );
850
851 let substantive1 = evaluate_admission(
853 "Note: make sure the deadlock fix lands before release",
854 "user",
855 );
856 assert!(
857 substantive1.admit,
858 "'make sure' mid-sentence must not be treated as noise: {:?}",
859 substantive1.reason
860 );
861
862 let substantive2 =
863 evaluate_admission("Note: the API returns ok status codes on success", "user");
864 assert!(
865 substantive2.admit,
866 "'ok' mid-sentence must not be treated as noise: {:?}",
867 substantive2.reason
868 );
869 }
870
871 #[test]
872 fn short_correction_is_admitted() {
873 let decision = evaluate_admission("No, use cargo fmt not rustfmt", "user");
874 assert!(decision.admit, "short correction should be admitted");
875 assert_eq!(decision.reason, AdmissionReason::Admitted);
876 assert!(decision.score > 0.5, "correction should have high score");
877 }
878
879 #[test]
880 fn long_noise_is_rejected() {
881 let long_noise = "Can you help me understand how the session lifecycle works? \
882 I've been reading through the code and trying to figure out the relationship. \
883 It seems like there's a turn loop that processes events and then calls tools.";
884 let decision = evaluate_admission(long_noise, "user");
885 assert!(
886 !decision.admit,
887 "routine chatter must be rejected (admit={}), score={}",
888 decision.admit, decision.score
889 );
890 }
891
892 #[test]
893 fn no_go_keeps_memory_candidate_shape_and_baseline_confidence() {
894 let episodes = vec![SessionEpisode {
895 session_id: "s1".into(),
896 entry_id: "e1".into(),
897 turn_index: 0,
898 role: "user".into(),
899 content: "Always run tests before committing".into(),
900 timestamp: Utc::now(),
901 }];
902 let extractor = RuleBasedExtractor::new();
903 let candidates = extractor.extract(&episodes);
904 assert!(!candidates.is_empty());
905 let c = &candidates[0];
906 assert_eq!(c.confidence, 0.8);
907 assert_eq!(c.admission_score, c.confidence);
908 let cloned = c.clone();
909 assert_eq!(cloned.key, c.key);
910 assert!(format!("{cloned:?}").contains("MemoryCandidate"));
911 }
912
913 #[test]
914 fn disabled_mode_admits_nothing() {
915 let mut store = MemoryStore::open_memory().expect("test operation should succeed");
916 let episodes = vec![SessionEpisode {
917 session_id: "s1".into(),
918 entry_id: "e1".into(),
919 turn_index: 0,
920 role: "user".into(),
921 content: "Always run tests before committing".into(),
922 timestamp: Utc::now(),
923 }];
924 let extractor = RuleBasedExtractor::new();
925 let config = ConsolidationConfig::default(); let report = consolidate_episodes(&mut store, &episodes, &extractor, &config)
927 .expect("test operation should succeed");
928 assert_eq!(
929 report.inserted, 0,
930 "disabled consolidation should write nothing"
931 );
932 }
933
934 #[test]
935 fn credential_shaped_content_not_in_store() {
936 let mut store = MemoryStore::open_memory().expect("test operation should succeed");
937 let episodes = vec![SessionEpisode {
938 session_id: "s1".into(),
939 entry_id: "e1".into(),
940 turn_index: 0,
941 role: "user".into(),
942 content: "api_key = sk-ant-test-secret-key-value".into(),
943 timestamp: Utc::now(),
944 }];
945 let extractor = RuleBasedExtractor::new();
946 let config = ConsolidationConfig {
947 enabled: true,
948 max_candidates_per_session: 20,
949 };
950 let report = consolidate_episodes(&mut store, &episodes, &extractor, &config)
951 .expect("test operation should succeed");
952 assert_eq!(
953 report.candidates_extracted, 0,
954 "sensitive content should not be extracted"
955 );
956 assert_eq!(
957 report.inserted, 0,
958 "sensitive content must not be written to store"
959 );
960 let results = store
961 .retrieve("api_key", 10)
962 .expect("test operation should succeed");
963 assert!(results.is_empty(), "no sensitive content in store");
964 }
965}