Skip to main content

talos_memory/
consolidation.rs

1//! Episodic-to-semantic memory consolidation pipeline (ADR-046).
2//!
3//! Reads session episodes, extracts semantic memory candidates via a pluggable
4//! [`EpisodeExtractor`], and writes them to [`MemoryStore`] with evidence links.
5//!
6//! The I137 benchmark selected No-Go, so [`RuleBasedExtractor`] retains the
7//! production baseline. Previously published admission types remain as a
8//! compatibility/benchmark surface only. Sensitive content is rejected before
9//! any memory write. No LLM or network calls are made.
10
11use chrono::{DateTime, Utc};
12use uuid::Uuid;
13
14use crate::{EvidenceLink, MemoryItem, MemoryKind, MemoryStore, MemoryStoreError};
15
16/// Reason codes for memory admission decisions (ADR-046).
17#[derive(Debug, Clone, PartialEq, Eq, Hash)]
18pub enum AdmissionReason {
19    /// Candidate admitted: novelty × utility exceeded threshold.
20    Admitted,
21    /// Rejected: content matches sensitive patterns (credentials, tokens, etc.).
22    SensitiveContent,
23    /// Rejected: novelty × utility below admission threshold.
24    BelowThreshold,
25    /// Rejected: role is system/tool (not original user/assistant content).
26    ExcludedRole,
27    /// Rejected: content too short.
28    TooShort,
29}
30
31/// The result of evaluating a memory candidate for admission (ADR-046).
32///
33/// This is separate from evidence confidence. A candidate may have low
34/// admission score but still be admitted if it meets the threshold.
35#[derive(Debug, Clone)]
36pub struct AdmissionDecision {
37    /// Whether the candidate should be written to the memory store.
38    pub admit: bool,
39    /// The admission score (novelty × committed_utility), [0, 1].
40    pub score: f64,
41    /// Stable reason code explaining the decision.
42    pub reason: AdmissionReason,
43}
44/// Admission threshold: candidates with score below this are rejected.
45/// Set to 0.15 to reject routine chatter.
46const ADMISSION_THRESHOLD: f64 = 0.15;
47
48/// Bare tokens matched as word boundaries to catch prose-form credentials.
49const SENSITIVE_WORD_TOKENS: &[&str] = &[
50    "password",
51    "secret",
52    "token",
53    "credential",
54    "api_key",
55    "apikey",
56];
57
58/// Structured patterns always sensitive (unambiguous multi-char sequences).
59const 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
72/// Leading chatter prefixes. Only matched at START of message to avoid
73/// vetoing substantive content that contains a noise word mid-sentence.
74const 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/// Check if content contains sensitive patterns that must not be persisted.
99///
100/// Uses word-boundary matching for bare tokens (password, secret, token)
101/// to catch prose-form credentials like "my password is hunter2".
102/// Uses substring matching for structured patterns (sk-ant-, bearer, etc.).
103/// Does NOT use bare `sk-` substring (matches task-, risk-, disk-).
104#[must_use]
105pub fn is_sensitive_content(content: &str) -> bool {
106    let lower = content.to_lowercase();
107
108    // Structured patterns: safe substring match.
109    if SENSITIVE_SUBSTRINGS.iter().any(|p| lower.contains(p)) {
110        return true;
111    }
112
113    // Word-boundary tokens: match as whole words.
114    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/// Check if content starts with conversational noise.
140/// Only matches at the START to avoid vetoing substantive content.
141#[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/// Evaluate a memory candidate for admission using ADR-046 policy.
148///
149/// Returns an [`AdmissionDecision`] with the admission score and reason.
150/// The caller must respect `admit == false` and not write the candidate.
151#[must_use]
152pub fn evaluate_admission(content: &str, role: &str) -> AdmissionDecision {
153    // System and tool messages are never admitted.
154    if role == "system" || role == "tool" {
155        return AdmissionDecision {
156            admit: false,
157            score: 0.0,
158            reason: AdmissionReason::ExcludedRole,
159        };
160    }
161
162    // Content too short to be meaningful.
163    if content.len() < 10 {
164        return AdmissionDecision {
165            admit: false,
166            score: 0.0,
167            reason: AdmissionReason::TooShort,
168        };
169    }
170
171    // Sensitive content is always rejected before any write.
172    if is_sensitive_content(content) {
173        return AdmissionDecision {
174            admit: false,
175            score: 0.0,
176            reason: AdmissionReason::SensitiveContent,
177        };
178    }
179
180    // Conversational noise is always rejected.
181    if is_noise_content(content) {
182        return AdmissionDecision {
183            admit: false,
184            score: 0.0,
185            reason: AdmissionReason::BelowThreshold,
186        };
187    }
188
189    // Compute admission score: novelty × committed_utility.
190    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
203/// Compute the admission score (novelty × committed_utility) for content.
204///
205/// Novelty is based on content markers, NOT message length. ADR-046 envisions
206/// novelty computed against existing memory coverage; the current implementation
207/// is a documented keyword-based downgrade.
208fn compute_admission_score(content: &str, _role: &str) -> f64 {
209    let lower = content.trim_start().to_lowercase();
210
211    // Novelty: corrections and technical content are inherently novel.
212    // Length alone is NOT a novelty signal.
213    let novelty: f64 = if lower.starts_with("actually")
214        || lower.starts_with("no,")
215        || lower.starts_with("correction")
216    {
217        0.9 // Corrections are inherently novel
218    } 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 // Technical notes and fixes
225    } else if lower.starts_with("remember")
226        || lower.starts_with("always")
227        || lower.starts_with("never")
228    {
229        0.7 // Directives and explicit memory requests
230    } else if lower.starts_with("prefer") || lower.contains("i prefer") {
231        0.6 // Preferences
232    } else {
233        0.1 // Default: likely not novel
234    };
235
236    // Committed utility: did the information change/guide behavior?
237    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 // Default: low utility (was 0.1)
259    };
260    novelty * utility
261}
262
263/// A single episode read from a session, neutral to the session storage format.
264#[derive(Debug, Clone)]
265pub struct SessionEpisode {
266    /// The session this episode belongs to.
267    pub session_id: String,
268    /// Unique identifier for this episode entry.
269    pub entry_id: String,
270    /// Position of this episode in the session sequence.
271    pub turn_index: usize,
272    /// The role that produced this episode: `"user"`, `"assistant"`, `"system"`, `"tool"`.
273    pub role: String,
274    /// The text content of this episode.
275    pub content: String,
276    /// When this episode was created.
277    pub timestamp: DateTime<Utc>,
278}
279
280/// A memory candidate extracted from session episodes.
281#[derive(Debug, Clone)]
282pub struct MemoryCandidate {
283    /// The kind of memory this candidate represents.
284    pub kind: MemoryKind,
285    /// A key identifying the concept or topic.
286    pub key: String,
287    /// The full content of the memory.
288    pub content: String,
289    /// Confidence score (0.0 to 1.0).
290    pub confidence: f64,
291    /// Compatibility-only admission score published during the I138
292    /// experiment. The production extractor does not use this field for
293    /// admission or ordering after the I137 No-Go correction.
294    pub admission_score: f64,
295    /// The session this candidate was extracted from.
296    pub source_session_id: String,
297    /// The entry ID within the session.
298    pub source_entry_id: String,
299    /// The turn index within the session.
300    pub source_turn_index: usize,
301}
302/// Trait for extracting semantic memory candidates from session episodes.
303///
304/// Implementations must be deterministic: the same input must always produce
305/// the same output.
306pub trait EpisodeExtractor {
307    /// Extract memory candidates from a slice of session episodes.
308    fn extract(&self, episodes: &[SessionEpisode]) -> Vec<MemoryCandidate>;
309}
310
311/// Deterministic rule-based episode extractor (no LLM/provider dependency).
312///
313/// Applies simple heuristics to identify memory-worthy content from session
314/// episodes. Suitable for offline testing and as a baseline extractor.
315pub struct RuleBasedExtractor {
316    /// Maximum number of candidates to return per extraction.
317    max_candidates: usize,
318}
319
320impl RuleBasedExtractor {
321    /// Create a new extractor with the default limit of 20 candidates.
322    pub fn new() -> Self {
323        Self { max_candidates: 20 }
324    }
325
326    /// Create a new extractor with a custom candidate limit.
327    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            // Credential-shaped content is a hard safety rejection independent
355            // of the I137 policy experiment.
356            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        // I137 selected No-Go, so the production extractor retains its
376        // pre-experiment confidence ordering.
377        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
389/// Compute confidence using the production baseline retained by I137 No-Go.
390fn 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
402/// Derive a memory key from content: first 40 chars, truncated at first newline, trimmed.
403fn 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/// Configuration for the consolidation pipeline.
413#[derive(Debug, Clone)]
414pub struct ConsolidationConfig {
415    /// Whether consolidation is enabled. Default: `false` (opt-in for safety).
416    pub enabled: bool,
417    /// Maximum candidates to consider per session.
418    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/// Report from a consolidation run.
431#[derive(Debug, Clone, Default)]
432pub struct ConsolidationReport {
433    /// Number of candidates extracted by the extractor.
434    pub candidates_extracted: usize,
435    /// Number of candidates successfully inserted into the store.
436    pub inserted: usize,
437    /// Number of candidates skipped as exact duplicates.
438    pub duplicates_skipped: usize,
439    /// Number of evidence links created.
440    pub evidence_links_created: usize,
441    /// Errors encountered during consolidation (non-fatal).
442    pub errors: Vec<String>,
443}
444
445/// Run consolidation: extract candidates from episodes and write to the memory store.
446///
447/// ADD-only: exact content-hash duplicates are skipped. Conflicting same-key
448/// entries with different content are preserved as separate rows per ADR-016.
449///
450/// # Arguments
451///
452/// * `store` — The memory store to write to.
453/// * `episodes` — Session episodes to consolidate.
454/// * `extractor` — The extractor to use for candidate extraction.
455/// * `config` — Pipeline configuration.
456///
457/// # Returns
458///
459/// A [`ConsolidationReport`] summarizing the consolidation run.
460pub 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 disabled, return immediately without any writes.
469    if !config.enabled {
470        return Ok(report);
471    }
472
473    // Extract candidates.
474    let candidates = extractor.extract(episodes);
475    report.candidates_extracted = candidates.len();
476
477    // Process each candidate.
478    for candidate in &candidates {
479        // Skip malformed candidates (empty content or key).
480        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        // Verify retrieval works.
621        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        // Verify evidence source_ref contains session_id and entry_id.
627        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        // First run.
649        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        // Second run on same episodes.
655        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        // Two episodes with same key prefix (first 40 chars match) but different content.
673        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            // Empty content.
716            make_episode("sess-3", "entry-1", 0, "user", ""),
717            // Very short content (<10 chars).
718            make_episode("sess-3", "entry-2", 1, "user", "hi"),
719            // System role (should be skipped by extractor).
720            make_episode(
721                "sess-3",
722                "entry-3",
723                2,
724                "system",
725                "This is a system message with enough content",
726            ),
727            // Tool role (should be skipped by extractor).
728            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        // Should not panic.
744        let report = consolidate_episodes(&mut store, &episodes, &extractor, &config)
745            .expect("test operation should succeed");
746
747        // System and tool are skipped by extractor; empty and short are also skipped.
748        // So candidates_extracted should be 0.
749        assert_eq!(
750            report.candidates_extracted, 0,
751            "No valid candidates from malformed episodes"
752        );
753        assert_eq!(report.inserted, 0);
754        // Errors may or may not be populated depending on where skipping happens.
755        // The key assertion is: no panic occurred.
756    }
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    // ── ADR-046 admission tests ──────────────────────────────────────────
808
809    #[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        // Prose-form credentials (review fix)
827        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        // sk- false positive fix: ordinary words must NOT be rejected
839        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        // Noise contains fix: mid-sentence noise words must NOT reject
852        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(); // enabled = false
926        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}