use chrono::{DateTime, Utc};
use uuid::Uuid;
use crate::{EvidenceLink, MemoryItem, MemoryKind, MemoryStore, MemoryStoreError};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum AdmissionReason {
Admitted,
SensitiveContent,
BelowThreshold,
ExcludedRole,
TooShort,
}
#[derive(Debug, Clone)]
pub struct AdmissionDecision {
pub admit: bool,
pub score: f64,
pub reason: AdmissionReason,
}
const ADMISSION_THRESHOLD: f64 = 0.15;
const SENSITIVE_WORD_TOKENS: &[&str] = &[
"password",
"secret",
"token",
"credential",
"api_key",
"apikey",
];
const SENSITIVE_SUBSTRINGS: &[&str] = &[
"access_token",
"refresh_token",
"authorization:",
"bearer ",
"cookie:",
"set-cookie",
"private_key",
"-----begin",
"sk-ant-",
"sk-proj-",
];
const NOISE_PREFIXES: &[&str] = &[
"can you help",
"how are you",
"thanks",
"thank you",
"that's helpful",
"hello",
"hi,",
"hi!",
"hey ",
"ok,",
"got it",
"i see",
"makes sense",
"understood",
"sounds good",
"let me think",
"i was wondering",
"i've been reading",
"i'm trying to figure out",
"i'm not sure",
"seems like",
];
#[must_use]
pub fn is_sensitive_content(content: &str) -> bool {
let lower = content.to_lowercase();
if SENSITIVE_SUBSTRINGS.iter().any(|p| lower.contains(p)) {
return true;
}
for token in SENSITIVE_WORD_TOKENS {
let mut search_from = 0;
while let Some(pos) = lower[search_from..].find(token) {
let abs_pos = search_from + pos;
let after = abs_pos + token.len();
let before_ok = abs_pos == 0
|| lower
.as_bytes()
.get(abs_pos - 1)
.is_some_and(|&c| !c.is_ascii_alphanumeric());
let after_ok = after >= lower.len()
|| lower
.as_bytes()
.get(after)
.is_some_and(|&c| !c.is_ascii_alphanumeric());
if before_ok && after_ok {
return true;
}
search_from = abs_pos + 1;
}
}
false
}
#[must_use]
fn is_noise_content(content: &str) -> bool {
let lower = content.trim_start().to_lowercase();
NOISE_PREFIXES.iter().any(|p| lower.starts_with(p))
}
#[must_use]
pub fn evaluate_admission(content: &str, role: &str) -> AdmissionDecision {
if role == "system" || role == "tool" {
return AdmissionDecision {
admit: false,
score: 0.0,
reason: AdmissionReason::ExcludedRole,
};
}
if content.len() < 10 {
return AdmissionDecision {
admit: false,
score: 0.0,
reason: AdmissionReason::TooShort,
};
}
if is_sensitive_content(content) {
return AdmissionDecision {
admit: false,
score: 0.0,
reason: AdmissionReason::SensitiveContent,
};
}
if is_noise_content(content) {
return AdmissionDecision {
admit: false,
score: 0.0,
reason: AdmissionReason::BelowThreshold,
};
}
let score = compute_admission_score(content, role);
AdmissionDecision {
admit: score >= ADMISSION_THRESHOLD,
score,
reason: if score >= ADMISSION_THRESHOLD {
AdmissionReason::Admitted
} else {
AdmissionReason::BelowThreshold
},
}
}
fn compute_admission_score(content: &str, _role: &str) -> f64 {
let lower = content.trim_start().to_lowercase();
let novelty: f64 = if lower.starts_with("actually")
|| lower.starts_with("no,")
|| lower.starts_with("correction")
{
0.9 } else if lower.starts_with("note")
|| lower.starts_with("important")
|| lower.contains("fix for")
|| lower.contains("deadlock")
|| lower.contains("caused by")
{
0.8 } else if lower.starts_with("remember")
|| lower.starts_with("always")
|| lower.starts_with("never")
{
0.7 } else if lower.starts_with("prefer") || lower.contains("i prefer") {
0.6 } else {
0.1 };
let utility: f64 = if lower.starts_with("always")
|| lower.starts_with("never")
|| lower.starts_with("remember")
|| lower.starts_with("note")
{
0.9
} else if lower.starts_with("actually")
|| lower.starts_with("no,")
|| lower.contains("was wrong")
|| lower.contains("is wrong")
{
0.85
} else if lower.starts_with("important")
|| lower.contains("fix for")
|| lower.contains("caused by")
|| lower.contains("fixed it")
{
0.8
} else if lower.starts_with("prefer") || lower.contains("i prefer") {
0.7
} else {
0.05 };
novelty * utility
}
#[derive(Debug, Clone)]
pub struct SessionEpisode {
pub session_id: String,
pub entry_id: String,
pub turn_index: usize,
pub role: String,
pub content: String,
pub timestamp: DateTime<Utc>,
}
#[derive(Debug, Clone)]
pub struct MemoryCandidate {
pub kind: MemoryKind,
pub key: String,
pub content: String,
pub confidence: f64,
pub admission_score: f64,
pub source_session_id: String,
pub source_entry_id: String,
pub source_turn_index: usize,
}
pub trait EpisodeExtractor {
fn extract(&self, episodes: &[SessionEpisode]) -> Vec<MemoryCandidate>;
}
pub struct RuleBasedExtractor {
max_candidates: usize,
}
impl RuleBasedExtractor {
pub fn new() -> Self {
Self { max_candidates: 20 }
}
pub fn with_max_candidates(max: usize) -> Self {
Self {
max_candidates: max,
}
}
}
impl Default for RuleBasedExtractor {
fn default() -> Self {
Self::new()
}
}
impl EpisodeExtractor for RuleBasedExtractor {
fn extract(&self, episodes: &[SessionEpisode]) -> Vec<MemoryCandidate> {
let mut candidates: Vec<MemoryCandidate> = Vec::new();
for episode in episodes {
if episode.content.len() < 10 {
continue;
}
if episode.role == "system" || episode.role == "tool" {
continue;
}
if episode.role != "user" && episode.role != "assistant" {
continue;
}
if is_sensitive_content(&episode.content) {
continue;
}
let key = derive_key(&episode.content);
let confidence = compute_confidence(&episode.content, &episode.role);
candidates.push(MemoryCandidate {
kind: MemoryKind::Semantic,
key,
content: episode.content.clone(),
confidence,
admission_score: confidence,
source_session_id: episode.session_id.clone(),
source_entry_id: episode.entry_id.clone(),
source_turn_index: episode.turn_index,
});
}
candidates.sort_by(|a, b| {
b.confidence
.partial_cmp(&a.confidence)
.unwrap_or(std::cmp::Ordering::Equal)
.then_with(|| a.source_turn_index.cmp(&b.source_turn_index))
});
candidates.truncate(self.max_candidates);
candidates
}
}
fn compute_confidence(content: &str, role: &str) -> f64 {
let lower = content.trim_start().to_lowercase();
let markers = ["remember", "note", "important", "always", "never"];
if markers.iter().any(|marker| lower.starts_with(marker)) {
return 0.8;
}
if role == "user" && content.len() > 50 {
return 0.6;
}
0.4
}
fn derive_key(content: &str) -> String {
let truncated = content
.split_once('\n')
.map(|(first, _)| first)
.unwrap_or(content);
let truncated = truncated.chars().take(40).collect::<String>();
truncated.trim().to_string()
}
#[derive(Debug, Clone)]
pub struct ConsolidationConfig {
pub enabled: bool,
pub max_candidates_per_session: usize,
}
impl Default for ConsolidationConfig {
fn default() -> Self {
Self {
enabled: false,
max_candidates_per_session: 20,
}
}
}
#[derive(Debug, Clone, Default)]
pub struct ConsolidationReport {
pub candidates_extracted: usize,
pub inserted: usize,
pub duplicates_skipped: usize,
pub evidence_links_created: usize,
pub errors: Vec<String>,
}
pub fn consolidate_episodes(
store: &mut MemoryStore,
episodes: &[SessionEpisode],
extractor: &dyn EpisodeExtractor,
config: &ConsolidationConfig,
) -> Result<ConsolidationReport, MemoryStoreError> {
let mut report = ConsolidationReport::default();
if !config.enabled {
return Ok(report);
}
let candidates = extractor.extract(episodes);
report.candidates_extracted = candidates.len();
for candidate in &candidates {
if candidate.content.is_empty() || candidate.key.is_empty() {
report.errors.push(format!(
"skipped malformed candidate: empty content or key (entry_id={})",
candidate.source_entry_id
));
continue;
}
let now = Utc::now();
let memory_id = Uuid::new_v4().to_string();
let item = MemoryItem {
id: memory_id.clone(),
kind: candidate.kind,
key: candidate.key.clone(),
content: candidate.content.clone(),
confidence: candidate.confidence,
created_at: now,
last_reinforced: now,
last_accessed: None,
contradiction_ref: None,
};
match store.insert(item) {
Ok(inserted) => {
if inserted {
report.inserted += 1;
let link = EvidenceLink {
id: Uuid::new_v4().to_string(),
memory_id,
source_type: "session".to_string(),
source_ref: format!(
"{}:{}:{}",
candidate.source_session_id,
candidate.source_entry_id,
candidate.source_turn_index
),
created_at: now,
};
if let Err(e) = store.insert_evidence(link) {
report
.errors
.push(format!("failed to insert evidence link: {e}"));
} else {
report.evidence_links_created += 1;
}
} else {
report.duplicates_skipped += 1;
}
}
Err(e) => {
report
.errors
.push(format!("failed to insert memory item: {e}"));
}
}
}
Ok(report)
}
#[cfg(test)]
mod tests {
use super::*;
fn make_episode(
session_id: &str,
entry_id: &str,
turn_index: usize,
role: &str,
content: &str,
) -> SessionEpisode {
SessionEpisode {
session_id: session_id.to_string(),
entry_id: entry_id.to_string(),
turn_index,
role: role.to_string(),
content: content.to_string(),
timestamp: Utc::now(),
}
}
fn make_episodes() -> Vec<SessionEpisode> {
vec![
make_episode(
"sess-1",
"entry-1",
0,
"user",
"remember to use Rust edition 2024 for all new projects",
),
make_episode(
"sess-1",
"entry-2",
1,
"assistant",
"I will use Rust edition 2024. It provides improved macro hygiene and async traits.",
),
make_episode(
"sess-1",
"entry-3",
2,
"system",
"Tool call result: success",
),
make_episode("sess-1", "entry-4", 3, "user", "short"),
make_episode(
"sess-1",
"entry-5",
4,
"user",
"This is a longer user message that should get medium confidence because it exceeds fifty characters in length",
),
]
}
#[test]
fn consolidation_creates_semantic_memory_with_evidence() {
let mut store = MemoryStore::open_memory().expect("test operation should succeed");
let episodes = make_episodes();
let extractor = RuleBasedExtractor::new();
let config = ConsolidationConfig {
enabled: true,
max_candidates_per_session: 20,
};
let report = consolidate_episodes(&mut store, &episodes, &extractor, &config)
.expect("test operation should succeed");
assert!(
report.inserted > 0,
"Should have inserted at least one item"
);
assert!(
report.evidence_links_created > 0,
"Should have created evidence links"
);
let results = store
.retrieve("Rust", 10)
.expect("test operation should succeed");
assert!(!results.is_empty(), "Should find Rust-related memory");
let has_valid_evidence = results.iter().any(|r| {
r.evidence
.iter()
.any(|e| e.source_ref.contains("sess-1") && e.source_ref.contains("entry-"))
});
assert!(
has_valid_evidence,
"Evidence should reference the source session and entry"
);
}
#[test]
fn exact_duplicate_dedup_by_content_hash() {
let mut store = MemoryStore::open_memory().expect("test operation should succeed");
let episodes = make_episodes();
let extractor = RuleBasedExtractor::new();
let config = ConsolidationConfig {
enabled: true,
max_candidates_per_session: 20,
};
let report1 = consolidate_episodes(&mut store, &episodes, &extractor, &config)
.expect("test operation should succeed");
let first_inserted = report1.inserted;
assert!(first_inserted > 0);
let report2 = consolidate_episodes(&mut store, &episodes, &extractor, &config)
.expect("test operation should succeed");
assert_eq!(
report2.inserted, 0,
"Second run should insert nothing (all duplicates)"
);
assert!(
report2.duplicates_skipped > 0,
"Second run should skip duplicates"
);
}
#[test]
fn conflicting_same_key_preserved_not_overwritten() {
let mut store = MemoryStore::open_memory().expect("test operation should succeed");
let episodes = vec![
make_episode(
"sess-2",
"entry-a",
0,
"user",
"Note: Python is a dynamically typed programming language with great ecosystem",
),
make_episode(
"sess-2",
"entry-b",
1,
"user",
"Note: Python is a statically typed programming language with strict type checking",
),
];
let extractor = RuleBasedExtractor::new();
let config = ConsolidationConfig {
enabled: true,
max_candidates_per_session: 20,
};
let report = consolidate_episodes(&mut store, &episodes, &extractor, &config)
.expect("test operation should succeed");
assert_eq!(
report.inserted, 2,
"Both conflicting items should be inserted"
);
assert_eq!(
store.count().expect("test operation should succeed"),
2,
"Store should contain both items"
);
}
#[test]
fn malformed_and_empty_sessions_degrade_gracefully() {
let mut store = MemoryStore::open_memory().expect("test operation should succeed");
let episodes = vec![
make_episode("sess-3", "entry-1", 0, "user", ""),
make_episode("sess-3", "entry-2", 1, "user", "hi"),
make_episode(
"sess-3",
"entry-3",
2,
"system",
"This is a system message with enough content",
),
make_episode(
"sess-3",
"entry-4",
3,
"tool",
"Tool output with enough characters to pass length check",
),
];
let extractor = RuleBasedExtractor::new();
let config = ConsolidationConfig {
enabled: true,
max_candidates_per_session: 20,
};
let report = consolidate_episodes(&mut store, &episodes, &extractor, &config)
.expect("test operation should succeed");
assert_eq!(
report.candidates_extracted, 0,
"No valid candidates from malformed episodes"
);
assert_eq!(report.inserted, 0);
}
#[test]
fn disabled_config_no_writes() {
let mut store = MemoryStore::open_memory().expect("test operation should succeed");
let episodes = make_episodes();
let extractor = RuleBasedExtractor::new();
let config = ConsolidationConfig {
enabled: false,
max_candidates_per_session: 20,
};
let report = consolidate_episodes(&mut store, &episodes, &extractor, &config)
.expect("test operation should succeed");
assert_eq!(report.candidates_extracted, 0);
assert_eq!(report.inserted, 0);
assert_eq!(report.duplicates_skipped, 0);
assert_eq!(report.evidence_links_created, 0);
assert!(report.errors.is_empty());
assert_eq!(
store.count().expect("test operation should succeed"),
0,
"Store should be empty"
);
}
#[test]
fn rule_based_extractor_is_deterministic() {
let episodes = make_episodes();
let extractor = RuleBasedExtractor::new();
let result1 = extractor.extract(&episodes);
let result2 = extractor.extract(&episodes);
assert_eq!(
result1.len(),
result2.len(),
"Both extractions should produce same number of candidates"
);
for (c1, c2) in result1.iter().zip(result2.iter()) {
assert_eq!(c1.key, c2.key, "Keys should match");
assert_eq!(c1.confidence, c2.confidence, "Confidence should match");
assert_eq!(
c1.source_turn_index, c2.source_turn_index,
"Turn index should match"
);
}
}
#[test]
fn sensitive_content_is_rejected_before_write() {
let decision = evaluate_admission("api_key = sk-ant-1234567890abcdef", "user");
assert!(!decision.admit, "api_key content must not be admitted");
assert_eq!(decision.reason, AdmissionReason::SensitiveContent);
let decision2 = evaluate_admission("Authorization: Bearer token123", "user");
assert!(
!decision2.admit,
"Authorization header must not be admitted"
);
assert_eq!(decision2.reason, AdmissionReason::SensitiveContent);
let decision3 = evaluate_admission("password = secret123", "user");
assert!(!decision3.admit, "password content must not be admitted");
assert_eq!(decision3.reason, AdmissionReason::SensitiveContent);
let prose1 = evaluate_admission("my password is hunter2xyz", "user");
assert!(!prose1.admit, "prose-form password must not be admitted");
assert_eq!(prose1.reason, AdmissionReason::SensitiveContent);
let prose2 = evaluate_admission("the deploy secret is prod-live-9f8a", "user");
assert!(!prose2.admit, "prose-form secret must not be admitted");
assert_eq!(prose2.reason, AdmissionReason::SensitiveContent);
let prose3 = evaluate_admission("session token is abc123", "user");
assert!(!prose3.admit, "prose-form token must not be admitted");
let normal1 = evaluate_admission("Always break the task-list into subtasks", "user");
assert!(
normal1.reason != AdmissionReason::SensitiveContent,
"'task-list' must not be flagged as sk- credential"
);
let normal2 = evaluate_admission("Important: the risk-averse policy applies here", "user");
assert!(
normal2.reason != AdmissionReason::SensitiveContent,
"'risk-averse' must not be flagged as sk- credential"
);
let substantive1 = evaluate_admission(
"Note: make sure the deadlock fix lands before release",
"user",
);
assert!(
substantive1.admit,
"'make sure' mid-sentence must not be treated as noise: {:?}",
substantive1.reason
);
let substantive2 =
evaluate_admission("Note: the API returns ok status codes on success", "user");
assert!(
substantive2.admit,
"'ok' mid-sentence must not be treated as noise: {:?}",
substantive2.reason
);
}
#[test]
fn short_correction_is_admitted() {
let decision = evaluate_admission("No, use cargo fmt not rustfmt", "user");
assert!(decision.admit, "short correction should be admitted");
assert_eq!(decision.reason, AdmissionReason::Admitted);
assert!(decision.score > 0.5, "correction should have high score");
}
#[test]
fn long_noise_is_rejected() {
let long_noise = "Can you help me understand how the session lifecycle works? \
I've been reading through the code and trying to figure out the relationship. \
It seems like there's a turn loop that processes events and then calls tools.";
let decision = evaluate_admission(long_noise, "user");
assert!(
!decision.admit,
"routine chatter must be rejected (admit={}), score={}",
decision.admit, decision.score
);
}
#[test]
fn no_go_keeps_memory_candidate_shape_and_baseline_confidence() {
let episodes = vec![SessionEpisode {
session_id: "s1".into(),
entry_id: "e1".into(),
turn_index: 0,
role: "user".into(),
content: "Always run tests before committing".into(),
timestamp: Utc::now(),
}];
let extractor = RuleBasedExtractor::new();
let candidates = extractor.extract(&episodes);
assert!(!candidates.is_empty());
let c = &candidates[0];
assert_eq!(c.confidence, 0.8);
assert_eq!(c.admission_score, c.confidence);
let cloned = c.clone();
assert_eq!(cloned.key, c.key);
assert!(format!("{cloned:?}").contains("MemoryCandidate"));
}
#[test]
fn disabled_mode_admits_nothing() {
let mut store = MemoryStore::open_memory().expect("test operation should succeed");
let episodes = vec![SessionEpisode {
session_id: "s1".into(),
entry_id: "e1".into(),
turn_index: 0,
role: "user".into(),
content: "Always run tests before committing".into(),
timestamp: Utc::now(),
}];
let extractor = RuleBasedExtractor::new();
let config = ConsolidationConfig::default(); let report = consolidate_episodes(&mut store, &episodes, &extractor, &config)
.expect("test operation should succeed");
assert_eq!(
report.inserted, 0,
"disabled consolidation should write nothing"
);
}
#[test]
fn credential_shaped_content_not_in_store() {
let mut store = MemoryStore::open_memory().expect("test operation should succeed");
let episodes = vec![SessionEpisode {
session_id: "s1".into(),
entry_id: "e1".into(),
turn_index: 0,
role: "user".into(),
content: "api_key = sk-ant-test-secret-key-value".into(),
timestamp: Utc::now(),
}];
let extractor = RuleBasedExtractor::new();
let config = ConsolidationConfig {
enabled: true,
max_candidates_per_session: 20,
};
let report = consolidate_episodes(&mut store, &episodes, &extractor, &config)
.expect("test operation should succeed");
assert_eq!(
report.candidates_extracted, 0,
"sensitive content should not be extracted"
);
assert_eq!(
report.inserted, 0,
"sensitive content must not be written to store"
);
let results = store
.retrieve("api_key", 10)
.expect("test operation should succeed");
assert!(results.is_empty(), "no sensitive content in store");
}
}