Skip to main content

vtcode_memory/
query.rs

1//! Read-only queries across sessions for analytics and long-term learning.
2
3use std::collections::HashMap;
4use std::path::Path;
5use std::sync::Mutex;
6use std::time::SystemTime;
7
8use chrono::{DateTime, Utc};
9use lru::LruCache;
10
11use crate::error::SessionStoreError;
12use crate::sessions_root;
13
14const MANIFEST_CACHE_CAPACITY: usize = 200;
15const MANIFEST_CACHE_NONZERO_CAPACITY: std::num::NonZeroUsize =
16    std::num::NonZeroUsize::new(MANIFEST_CACHE_CAPACITY).unwrap();
17static MANIFEST_CACHE: std::sync::OnceLock<Mutex<LruCache<String, CachedManifest>>> = std::sync::OnceLock::new();
18
19#[derive(Debug, Clone)]
20struct CachedManifest {
21    summary: SessionSummary,
22    signature: ManifestSignature,
23}
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26struct ManifestSignature {
27    modified: Option<SystemTime>,
28    len: u64,
29}
30
31fn manifest_signature(path: &Path) -> Option<ManifestSignature> {
32    let metadata = std::fs::symlink_metadata(path).ok()?;
33    Some(ManifestSignature {
34        modified: metadata.modified().ok(),
35        len: metadata.len(),
36    })
37}
38
39/// Invalidate a cached manifest after an atomic replacement.
40pub(crate) fn invalidate_manifest_cache(path: &Path) {
41    if let Some(cache) = MANIFEST_CACHE.get()
42        && let Ok(mut cache) = cache.lock()
43    {
44        let key = path.to_string_lossy();
45        cache.pop(key.as_ref());
46    }
47}
48
49/// Lightweight summary of a single session, read from its `manifest.json`.
50#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
51pub struct SessionSummary {
52    /// Session identifier (directory name).
53    pub session_id: String,
54    /// Number of completed turns.
55    pub turn_count: u64,
56    /// Total events recorded.
57    pub event_count: u64,
58    /// Lifecycle status.
59    pub status: String,
60    /// RFC3339 last-update timestamp (used for ordering).
61    pub updated_at: String,
62}
63
64/// A single grounded fact drawn from a session's memory envelope.
65#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
66pub struct FactRecord {
67    /// The fact text.
68    pub fact: String,
69    /// Session the fact originated from.
70    pub session_id: String,
71}
72
73/// One result returned from a memory search.
74///
75/// Mirrors the shape used by the grok-build memory subsystem so that
76/// higher-level consumers (tool bridge, context injection) can share
77/// formatting logic once a richer backend is available.
78#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
79pub struct MemorySearchResult {
80    /// Stable identifier for this chunk (session_id + fact index).
81    chunk_id: String,
82    /// Source memory file path.
83    path: String,
84    /// 0-based start line in the source file (0 for derived facts).
85    start_line: usize,
86    /// 0-based end line in the source file (0 for derived facts).
87    end_line: usize,
88    /// Relevance score (higher = more relevant).
89    score: f64,
90    /// Text snippet from the chunk.
91    snippet: String,
92    /// Source scope: `"session"` for per-session memory files.
93    source: String,
94    /// Unix timestamp (seconds) when the source memory was created.
95    created_at: Option<i64>,
96}
97
98/// List up to `n` most-recently-updated sessions.
99#[must_use]
100pub fn recent_sessions(workspace: &Path, n: usize) -> Vec<SessionSummary> {
101    let root = sessions_root(workspace);
102    if !root.exists() {
103        return Vec::new();
104    }
105    let mut out = Vec::new();
106    let entries = match std::fs::read_dir(&root) {
107        Ok(e) => e,
108        Err(_) => return Vec::new(),
109    };
110    let mut cache = MANIFEST_CACHE
111        .get_or_init(|| Mutex::new(LruCache::new(MANIFEST_CACHE_NONZERO_CAPACITY)))
112        .lock()
113        .unwrap_or_else(std::sync::PoisonError::into_inner);
114    for entry in entries.filter_map(Result::ok) {
115        let manifest = entry.path().join("manifest.json");
116        let key = manifest.to_string_lossy().into_owned();
117        let signature = manifest_signature(&manifest);
118        if let Some(cached) = cache.get(&key)
119            && signature == Some(cached.signature)
120        {
121            out.push(cached.summary.clone());
122            continue;
123        }
124        if let Ok(bytes) = std::fs::read(&manifest)
125            && let Ok(s) = serde_json::from_slice::<SessionSummary>(&bytes)
126        {
127            if let Some(signature) = signature.or_else(|| manifest_signature(&manifest)) {
128                cache.put(key, CachedManifest { summary: s.clone(), signature });
129            }
130            out.push(s);
131        }
132    }
133    out.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));
134    out.truncate(n);
135    out
136}
137
138/// List summaries of sessions with a live process attached, most-recently-updated first.
139///
140/// Liveness is the flock-backed `session.lock` check, not the manifest
141/// `status` string, so crashed sessions that never emitted `thread.completed`
142/// are excluded. Used by peer-messaging discovery (`list_sessions`).
143#[must_use]
144pub fn live_sessions(workspace: &Path) -> Vec<SessionSummary> {
145    recent_sessions(workspace, usize::MAX)
146        .into_iter()
147        .filter(|summary| crate::retention::session_dir_is_live(&crate::session_dir(workspace, &summary.session_id)))
148        .collect()
149}
150
151/// Cross-session long-term-learning query: collect grounded facts from every
152/// session's derived memory envelope. This is how the agent learns across
153/// sessions without loading any history into context.
154pub fn query_facts(workspace: &Path, limit: usize) -> Result<Vec<FactRecord>, SessionStoreError> {
155    let root = sessions_root(workspace);
156    if !root.exists() {
157        return Ok(Vec::new());
158    }
159    let mut facts: Vec<FactRecord> = Vec::new();
160    let entries = std::fs::read_dir(&root).map_err(|e| SessionStoreError::io(root.clone(), e))?;
161    for entry in entries.filter_map(Result::ok) {
162        let memory = entry.path().join(crate::DERIVED_DIR).join("memory.json");
163        let Ok(bytes) = std::fs::read(&memory) else {
164            continue;
165        };
166        let Ok(value) = serde_json::from_slice::<serde_json::Value>(&bytes) else {
167            continue;
168        };
169        let session_id = entry.file_name().to_string_lossy().into_owned();
170        if let Some(arr) = value.get("grounded_facts").and_then(|v| v.as_array()) {
171            for item in arr {
172                if let Some(fact) = item.get("fact").and_then(|f| f.as_str()) {
173                    facts.push(FactRecord {
174                        fact: fact.to_string(),
175                        session_id: session_id.clone(),
176                    });
177                }
178            }
179        }
180    }
181    facts.truncate(limit);
182    Ok(facts)
183}
184
185/// Cross-session memory search: scan every session's derived memory envelope
186/// for facts matching `query`. Returns up to `max_results` results with
187/// score >= `min_score`, sorted by descending relevance.
188///
189/// Scoring uses BM25 (`k1=1.2`, `b=0.75`) over tokenized facts. Ties are
190/// deterministic by the stable `session_id:index` chunk identifier.
191pub fn search_memory(
192    workspace: &Path,
193    query: &str,
194    max_results: usize,
195    min_score: f64,
196) -> Result<Vec<MemorySearchResult>, SessionStoreError> {
197    if query.is_empty() {
198        return Ok(Vec::new());
199    }
200
201    let root = sessions_root(workspace);
202    if !root.exists() {
203        return Ok(Vec::new());
204    }
205
206    let query_terms = tokenize(query);
207    if query_terms.is_empty() {
208        return Ok(Vec::new());
209    }
210    let mut results: Vec<MemorySearchResult> = Vec::new();
211    let session_source = String::from("session");
212    let mut documents = Vec::new();
213
214    let entries = std::fs::read_dir(&root).map_err(|e| SessionStoreError::io(root.clone(), e))?;
215    for entry in entries.filter_map(Result::ok) {
216        let session_dir = entry.path();
217        let memory = session_dir.join(crate::DERIVED_DIR).join("memory.json");
218        let Ok(bytes) = std::fs::read(&memory) else {
219            continue;
220        };
221        let Ok(value) = serde_json::from_slice::<serde_json::Value>(&bytes) else {
222            continue;
223        };
224        let session_id = entry.file_name().to_string_lossy().into_owned();
225        let memory_path = memory.to_string_lossy().into_owned();
226        let created_at = value
227            .get("created_at")
228            .and_then(parse_timestamp)
229            .or_else(|| value.get("updated_at").and_then(parse_timestamp));
230
231        if let Some(arr) = value.get("grounded_facts").and_then(|v| v.as_array()) {
232            for (idx, item) in arr.iter().enumerate() {
233                let Some(fact) = item.get("fact").and_then(|f| f.as_str()) else {
234                    continue;
235                };
236                documents.push((
237                    format!("{session_id}:{idx}"),
238                    memory_path.clone(),
239                    fact.to_owned(),
240                    tokenize(fact),
241                    created_at,
242                ));
243            }
244        }
245    }
246
247    let document_count = documents.len();
248    if document_count == 0 {
249        return Ok(Vec::new());
250    }
251    let average_length =
252        documents.iter().map(|(_, _, _, terms, _)| terms.len() as f64).sum::<f64>() / document_count as f64;
253    let mut document_frequency: HashMap<String, usize> = HashMap::new();
254    for (_, _, _, terms, _) in &documents {
255        let mut seen = std::collections::HashSet::new();
256        for term in terms {
257            if seen.insert(term.as_str()) {
258                *document_frequency.entry(term.clone()).or_insert(0) += 1;
259            }
260        }
261    }
262    let k1 = 1.2;
263    let b = 0.75;
264    let now = Utc::now();
265    for (chunk_id, path, fact, terms, created_at) in documents {
266        let length = terms.len() as f64;
267        let mut term_frequency = HashMap::<&str, usize>::new();
268        for term in &terms {
269            *term_frequency.entry(term.as_str()).or_insert(0) += 1;
270        }
271        let mut score = 0.0;
272        for query_term in &query_terms {
273            let Some(&frequency) = term_frequency.get(query_term.as_str()) else {
274                continue;
275            };
276            let Some(&frequency_in_documents) = document_frequency.get(query_term) else {
277                continue;
278            };
279            let idf = (((document_count - frequency_in_documents) as f64 + 0.5)
280                / (frequency_in_documents as f64 + 0.5)
281                + 1.0)
282                .ln();
283            let denominator = frequency as f64 + k1 * (1.0 - b + b * length / average_length.max(1.0));
284            score += idf * (frequency as f64 * (k1 + 1.0)) / denominator;
285        }
286        if score <= 0.0 {
287            continue;
288        }
289        // A mild recency preference helps current session facts win close BM25
290        // matches without allowing recency to create a result that did not
291        // match the query. Missing or malformed timestamps deliberately keep
292        // the neutral multiplier of 1.0.
293        score *= recency_multiplier(created_at, now);
294        if score < min_score {
295            continue;
296        }
297        results.push(MemorySearchResult {
298            chunk_id,
299            path,
300            start_line: 0,
301            end_line: 0,
302            score,
303            snippet: fact,
304            source: session_source.clone(),
305            created_at,
306        });
307    }
308
309    results.sort_by(|a, b| {
310        b.score
311            .partial_cmp(&a.score)
312            .unwrap_or(std::cmp::Ordering::Equal)
313            .then_with(|| a.chunk_id.cmp(&b.chunk_id))
314    });
315    results.truncate(max_results);
316    Ok(results)
317}
318
319fn parse_timestamp(value: &serde_json::Value) -> Option<i64> {
320    if let Some(timestamp) = value.as_i64() {
321        return DateTime::<Utc>::from_timestamp(timestamp, 0).map(|_| timestamp);
322    }
323    let text = value.as_str()?.trim();
324    if let Ok(timestamp) = text.parse::<i64>() {
325        return DateTime::<Utc>::from_timestamp(timestamp, 0).map(|_| timestamp);
326    }
327    DateTime::parse_from_rfc3339(text).ok().map(|timestamp| timestamp.timestamp())
328}
329
330fn recency_multiplier(created_at: Option<i64>, now: DateTime<Utc>) -> f64 {
331    let Some(created_at) = created_at.and_then(|timestamp| DateTime::<Utc>::from_timestamp(timestamp, 0)) else {
332        return 1.0;
333    };
334    let age_days = (now - created_at).num_seconds().max(0) as f64 / 86_400.0;
335    1.0 + 0.15 * 0.5_f64.powf(age_days / 30.0)
336}
337
338/// Return the configured default for `max_results` in search queries.
339pub fn default_search_max_results() -> usize {
340    6
341}
342
343/// Return the configured default for `min_score` in search queries.
344pub fn default_search_min_score() -> f64 {
345    0.0
346}
347
348fn count_substring_matches(text: &str, lowered_query: &str) -> usize {
349    if lowered_query.is_empty() {
350        return 0;
351    }
352    let lowered = text.to_ascii_lowercase();
353    let mut count = 0;
354    let mut start = 0;
355    while let Some(pos) = lowered[start..].find(lowered_query) {
356        count += 1;
357        start += pos + lowered_query.len();
358    }
359    count
360}
361
362fn tokenize(text: &str) -> Vec<String> {
363    let mut tokens = Vec::new();
364    let mut current = String::new();
365    for character in text.chars() {
366        if character.is_alphanumeric() {
367            current.extend(character.to_lowercase());
368        } else if !current.is_empty() {
369            tokens.push(std::mem::take(&mut current));
370        }
371    }
372    if !current.is_empty() {
373        tokens.push(current);
374    }
375    tokens
376}
377
378/// Minimal per-session memory view persisted into `derived/memory.json`.
379///
380/// The serialized shape is compatible with the legacy
381/// `SessionMemoryEnvelope` layout (`grounded_facts: [{fact: …}]`) so
382/// `query_facts`, `search_memory`, and the legacy migration importer all read
383/// the same file format.
384#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
385pub struct SessionMemoryView {
386    /// Short session summary (may be empty when unknown).
387    pub summary: String,
388    /// Grounded facts extracted from the session, in extraction order.
389    pub facts: Vec<String>,
390}
391
392/// Persist a session's derived memory view to
393/// `<session>/derived/memory.json` (atomic, private permissions).
394///
395/// This is the live producer for the per-session memory file: cross-session
396/// queries (`query_facts`, `search_memory`) and the batch memory pipeline
397/// observe sessions through it. Fails when the session directory cannot be
398/// created or the file cannot be written; it never mutates `events.jsonl`.
399pub fn write_session_memory_view(
400    workspace: &Path,
401    session_id: &str,
402    view: &SessionMemoryView,
403) -> Result<(), SessionStoreError> {
404    let dir = crate::session_dir(workspace, session_id);
405    crate::ensure_private_directory(&dir)?;
406    crate::ensure_private_directory(&dir.join(crate::DERIVED_DIR))?;
407
408    let envelope = serde_json::json!({
409        "session_id": session_id,
410        "schema_version": 3,
411        "summary": view.summary,
412        "grounded_facts": view
413            .facts
414            .iter()
415            .map(|fact| serde_json::json!({ "fact": fact }))
416            .collect::<Vec<_>>(),
417        "touched_files": [],
418        "generated_at": Utc::now().to_rfc3339(),
419    });
420    let bytes = serde_json::to_vec_pretty(&envelope)
421        .map_err(|error| SessionStoreError::io(dir.clone(), std::io::Error::other(error)))?;
422    let dest = dir.join(crate::DERIVED_DIR).join("memory.json");
423    vtcode_commons::VtCodePaths::write_private_file_atomic(&dest, &bytes)
424        .map_err(|error| SessionStoreError::io(dest, std::io::Error::other(error)))?;
425    invalidate_manifest_cache(&dir.join("manifest.json"));
426    Ok(())
427}
428
429/// Read one session's grounded facts from its derived memory view.
430///
431/// Returns an empty list when the view has not been written yet; unlike
432/// [`query_facts`] this never scans sibling sessions.
433pub fn session_memory_facts(
434    workspace: &Path,
435    session_id: &str,
436    limit: usize,
437) -> Result<Vec<FactRecord>, SessionStoreError> {
438    let memory = crate::session_dir(workspace, session_id)
439        .join(crate::DERIVED_DIR)
440        .join("memory.json");
441    let Ok(bytes) = std::fs::read(&memory) else {
442        return Ok(Vec::new());
443    };
444    let Ok(value) = serde_json::from_slice::<serde_json::Value>(&bytes) else {
445        return Ok(Vec::new());
446    };
447    let mut facts = Vec::new();
448    if let Some(arr) = value.get("grounded_facts").and_then(|v| v.as_array()) {
449        for item in arr {
450            if let Some(fact) = item.get("fact").and_then(|f| f.as_str()) {
451                facts.push(FactRecord {
452                    fact: fact.to_string(),
453                    session_id: session_id.to_string(),
454                });
455                if facts.len() >= limit {
456                    break;
457                }
458            }
459        }
460    }
461    Ok(facts)
462}
463
464#[cfg(test)]
465mod tests {
466    use super::*;
467    use tempfile::TempDir;
468
469    #[test]
470    fn count_substring_matches_counts_overlapping() {
471        assert_eq!(count_substring_matches("aaaa", "aa"), 2);
472        assert_eq!(count_substring_matches("ababa", "aba"), 1);
473        assert_eq!(count_substring_matches("hello world", "ll"), 1);
474        assert_eq!(count_substring_matches("", "x"), 0);
475    }
476
477    #[test]
478    fn search_memory_returns_matching_facts() {
479        let dir = TempDir::new().expect("tempdir");
480        let sess = crate::session_dir(dir.path(), "s1");
481        std::fs::create_dir_all(sess.join(crate::DERIVED_DIR)).expect("mkdir");
482        let memory = serde_json::json!({
483            "grounded_facts": [
484                {"fact": "the widget is blue"},
485                {"fact": "the server runs on port 8080"},
486                {"fact": "use PostgreSQL for persistence"},
487            ]
488        });
489        std::fs::write(sess.join(crate::DERIVED_DIR).join("memory.json"), serde_json::to_string(&memory).expect("ser"))
490            .expect("write");
491
492        let results = search_memory(dir.path(), "blue", 10, 0.0).expect("search");
493        assert_eq!(results.len(), 1);
494        assert_eq!(results[0].snippet, "the widget is blue");
495        assert_eq!(results[0].chunk_id, "s1:0");
496        assert!(results[0].score > 0.0);
497    }
498
499    #[test]
500    fn search_memory_scores_multiple_matches() {
501        let dir = TempDir::new().expect("tempdir");
502        let sess = crate::session_dir(dir.path(), "s2");
503        std::fs::create_dir_all(sess.join(crate::DERIVED_DIR)).expect("mkdir");
504        let memory = serde_json::json!({
505            "grounded_facts": [
506                {"fact": "rust uses rustc and cargo"},
507                {"fact": "cargo is the rust build tool"},
508            ]
509        });
510        std::fs::write(sess.join(crate::DERIVED_DIR).join("memory.json"), serde_json::to_string(&memory).expect("ser"))
511            .expect("write");
512
513        let results = search_memory(dir.path(), "cargo", 10, 0.0).expect("search");
514        assert_eq!(results.len(), 2);
515        assert!(results.iter().all(|r| r.score > 0.0));
516    }
517
518    #[test]
519    fn search_memory_respects_min_score() {
520        let dir = TempDir::new().expect("tempdir");
521        let sess = crate::session_dir(dir.path(), "s3");
522        std::fs::create_dir_all(sess.join(crate::DERIVED_DIR)).expect("mkdir");
523        let memory = serde_json::json!({
524            "grounded_facts": [
525                {"fact": "alpha beta gamma"},
526            ]
527        });
528        std::fs::write(sess.join(crate::DERIVED_DIR).join("memory.json"), serde_json::to_string(&memory).expect("ser"))
529            .expect("write");
530
531        let results = search_memory(dir.path(), "beta", 10, 2.0).expect("search");
532        assert!(results.is_empty());
533    }
534
535    #[test]
536    fn search_memory_empty_query_returns_empty() {
537        let dir = TempDir::new().expect("tempdir");
538        let results = search_memory(dir.path(), "", 10, 0.0).expect("search");
539        assert!(results.is_empty());
540    }
541
542    #[test]
543    fn search_memory_sorts_by_score_descending() {
544        let dir = TempDir::new().expect("tempdir");
545        for i in 0..3 {
546            let sess = crate::session_dir(dir.path(), &format!("s{i}"));
547            std::fs::create_dir_all(sess.join(crate::DERIVED_DIR)).expect("mkdir");
548            let memory = serde_json::json!({
549                "grounded_facts": [
550                    {"fact": format!("fact {i} appears twice twice")},
551                ]
552            });
553            std::fs::write(
554                sess.join(crate::DERIVED_DIR).join("memory.json"),
555                serde_json::to_string(&memory).expect("ser"),
556            )
557            .expect("write");
558        }
559
560        let results = search_memory(dir.path(), "twice", 10, 0.0).expect("search");
561        assert_eq!(results.len(), 3);
562        assert!(results.windows(2).all(|w| w[0].score >= w[1].score));
563    }
564
565    #[test]
566    fn search_memory_uses_bm25_term_coverage_and_deterministic_ties() {
567        let dir = TempDir::new().expect("tempdir");
568        for (session_id, facts) in [
569            ("s1", vec!["rust cargo tool", "unrelated note"]),
570            ("s2", vec!["cargo build tool"]),
571        ] {
572            let session = crate::session_dir(dir.path(), session_id);
573            std::fs::create_dir_all(session.join(crate::DERIVED_DIR)).expect("mkdir");
574            let memory = serde_json::json!({
575                "grounded_facts": facts.into_iter().map(|fact| serde_json::json!({"fact": fact})).collect::<Vec<_>>()
576            });
577            std::fs::write(
578                session.join(crate::DERIVED_DIR).join("memory.json"),
579                serde_json::to_string(&memory).expect("serialize"),
580            )
581            .expect("write");
582        }
583
584        let results = search_memory(dir.path(), "rust cargo", 10, 0.0).expect("search");
585        assert_eq!(results.first().map(|result| result.chunk_id.as_str()), Some("s1:0"));
586        assert!(results[0].score > results[1].score);
587    }
588
589    #[test]
590    fn search_memory_applies_recency_to_valid_rfc3339_timestamps() {
591        let dir = TempDir::new().expect("tempdir");
592        for (session_id, timestamp) in [("old", "2020-01-01T00:00:00Z"), ("new", "2099-01-01T00:00:00Z")] {
593            let session = crate::session_dir(dir.path(), session_id);
594            std::fs::create_dir_all(session.join(crate::DERIVED_DIR)).expect("mkdir");
595            let memory = serde_json::json!({
596                "created_at": timestamp,
597                "grounded_facts": [{"fact": "shared search fact"}]
598            });
599            std::fs::write(
600                session.join(crate::DERIVED_DIR).join("memory.json"),
601                serde_json::to_vec(&memory).expect("serialize"),
602            )
603            .expect("write");
604        }
605
606        let results = search_memory(dir.path(), "shared", 10, 0.0).expect("search");
607        assert_eq!(results.len(), 2);
608        assert_eq!(results[0].chunk_id, "new:0");
609        assert!(results[0].score > results[1].score);
610    }
611
612    #[test]
613    fn search_memory_does_not_boost_missing_or_invalid_timestamps() {
614        let dir = TempDir::new().expect("tempdir");
615        for (session_id, timestamp) in [
616            ("missing", serde_json::Value::Null),
617            ("invalid", serde_json::json!("not-a-date")),
618        ] {
619            let session = crate::session_dir(dir.path(), session_id);
620            std::fs::create_dir_all(session.join(crate::DERIVED_DIR)).expect("mkdir");
621            let mut memory = serde_json::json!({"grounded_facts": [{"fact": "neutral search fact"}]});
622            if !timestamp.is_null() {
623                memory["created_at"] = timestamp;
624            }
625            std::fs::write(
626                session.join(crate::DERIVED_DIR).join("memory.json"),
627                serde_json::to_vec(&memory).expect("serialize"),
628            )
629            .expect("write");
630        }
631
632        let results = search_memory(dir.path(), "neutral", 10, 0.0).expect("search");
633        assert_eq!(results.len(), 2);
634        assert!((results[0].score - results[1].score).abs() < f64::EPSILON);
635        assert_eq!(results[0].created_at, None);
636        assert_eq!(results[1].created_at, None);
637    }
638
639    #[test]
640    fn recency_multiplier_matches_thirty_day_half_life() {
641        let now = DateTime::parse_from_rfc3339("2026-01-31T00:00:00Z")
642            .expect("timestamp")
643            .with_timezone(&Utc);
644        let thirty_days_ago = now - chrono::Duration::days(30);
645        let multiplier = recency_multiplier(Some(thirty_days_ago.timestamp()), now);
646        assert!((multiplier - 1.075).abs() < 1e-12);
647        assert!((recency_multiplier(None, now) - 1.0).abs() < f64::EPSILON);
648    }
649
650    #[test]
651    fn recent_sessions_invalidates_manifest_cache_after_replacement() {
652        let dir = TempDir::new().expect("tempdir");
653        let session = crate::session_dir(dir.path(), "cache-session");
654        std::fs::create_dir_all(&session).expect("mkdir");
655        let manifest = serde_json::json!({
656            "session_id": "cache-session",
657            "schema_version": 1,
658            "created_at": "2026-01-01T00:00:00Z",
659            "updated_at": "2026-01-01T00:00:00Z",
660            "turn_count": 1,
661            "event_count": 1,
662            "status": "active"
663        });
664        let path = session.join("manifest.json");
665        std::fs::write(&path, serde_json::to_vec(&manifest).expect("serialize")).expect("write");
666        assert_eq!(recent_sessions(dir.path(), 1)[0].updated_at, "2026-01-01T00:00:00Z");
667
668        let mut replaced = manifest;
669        replaced["updated_at"] = serde_json::json!("2099-01-01T00:00:00Z");
670        std::fs::write(&path, serde_json::to_vec(&replaced).expect("serialize")).expect("replace");
671        assert_eq!(recent_sessions(dir.path(), 1)[0].updated_at, "2099-01-01T00:00:00Z");
672    }
673
674    #[test]
675    fn session_memory_view_round_trips_through_queries() {
676        let dir = TempDir::new().expect("tempdir");
677        let view = SessionMemoryView {
678            summary: "Implemented the frobnicator".to_string(),
679            facts: vec![
680                "Uses tokio for async runtime".to_string(),
681                "Prefers anyhow errors".to_string(),
682            ],
683        };
684        write_session_memory_view(dir.path(), "view-session", &view).expect("write view");
685
686        let facts = session_memory_facts(dir.path(), "view-session", 10).expect("read facts");
687        assert_eq!(facts.len(), 2);
688        assert_eq!(facts[0].session_id, "view-session");
689        assert_eq!(facts[0].fact, "Uses tokio for async runtime");
690
691        let all = query_facts(dir.path(), 10).expect("query facts");
692        assert_eq!(all.len(), 2);
693        assert!(all.iter().all(|record| record.session_id == "view-session"));
694
695        let results = search_memory(dir.path(), "tokio", 5, 0.0).expect("search");
696        assert_eq!(results.len(), 1);
697        assert!(results[0].snippet.contains("tokio"));
698    }
699
700    #[test]
701    fn session_memory_facts_respects_limit_and_missing_files() {
702        let dir = TempDir::new().expect("tempdir");
703        assert!(
704            session_memory_facts(dir.path(), "missing-session", 5)
705                .expect("missing")
706                .is_empty()
707        );
708
709        let view = SessionMemoryView {
710            summary: String::new(),
711            facts: (0..5).map(|index| format!("fact-{index}")).collect(),
712        };
713        write_session_memory_view(dir.path(), "limited", &view).expect("write");
714        let limited = session_memory_facts(dir.path(), "limited", 3).expect("read");
715        assert_eq!(limited.len(), 3);
716        assert_eq!(limited[2].fact, "fact-2");
717    }
718}