Skip to main content

lean_ctx/core/
archive.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use std::path::PathBuf;
4
5use super::data_dir::lean_ctx_data_dir;
6
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct ArchiveEntry {
9    pub id: String,
10    pub tool: String,
11    pub command: String,
12    pub size_chars: usize,
13    pub size_tokens: usize,
14    pub created_at: DateTime<Utc>,
15    pub session_id: Option<String>,
16    #[serde(default, skip_serializing_if = "Option::is_none")]
17    pub protected_until: Option<DateTime<Utc>>,
18    #[serde(default, skip_serializing_if = "Vec::is_empty")]
19    pub aliases: Vec<String>,
20}
21
22fn archive_base_dir() -> PathBuf {
23    lean_ctx_data_dir()
24        .unwrap_or_else(|_| PathBuf::from(".lean-ctx"))
25        .join("archives")
26}
27
28fn entry_dir(id: &str) -> PathBuf {
29    let prefix = if id.len() >= 2 { &id[..2] } else { id };
30    archive_base_dir().join(prefix)
31}
32
33fn content_path(id: &str) -> PathBuf {
34    entry_dir(id).join(format!("{id}.txt"))
35}
36
37fn meta_path(id: &str) -> PathBuf {
38    entry_dir(id).join(format!("{id}.meta.json"))
39}
40
41fn lock_path() -> PathBuf {
42    archive_base_dir().join(".lock")
43}
44
45fn with_archive_lock<T>(f: impl FnOnce() -> T) -> Option<T> {
46    use fs2::FileExt;
47
48    std::fs::create_dir_all(archive_base_dir()).ok()?;
49    let lock = std::fs::OpenOptions::new()
50        .read(true)
51        .write(true)
52        .create(true)
53        .truncate(false)
54        .open(lock_path())
55        .ok()?;
56    #[cfg(unix)]
57    set_private_file_perms(&lock_path());
58    lock.lock_exclusive().ok()?;
59    let result = f();
60    let _ = FileExt::unlock(&lock);
61    Some(result)
62}
63
64#[cfg(unix)]
65fn set_private_file_perms(path: &PathBuf) {
66    use std::os::unix::fs::PermissionsExt;
67    let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
68}
69
70fn compute_id(content: &str) -> String {
71    use std::collections::hash_map::DefaultHasher;
72    use std::hash::{Hash, Hasher};
73    let mut hasher = DefaultHasher::new();
74    content.hash(&mut hasher);
75    let hash = hasher.finish();
76    format!("{hash:016x}")
77}
78
79pub fn is_enabled() -> bool {
80    if let Ok(v) = std::env::var("LEAN_CTX_ARCHIVE") {
81        return !matches!(v.as_str(), "0" | "false" | "off");
82    }
83    super::config::Config::load().archive.enabled
84}
85
86fn threshold_chars() -> usize {
87    if let Ok(v) = std::env::var("LEAN_CTX_ARCHIVE_THRESHOLD")
88        && let Ok(n) = v.parse::<usize>()
89    {
90        return n;
91    }
92    super::config::Config::load().archive.threshold_chars
93}
94
95fn max_age_hours() -> u64 {
96    if let Ok(v) = std::env::var("LEAN_CTX_ARCHIVE_TTL")
97        && let Ok(n) = v.parse::<u64>()
98    {
99        return n;
100    }
101    super::config::Config::load().archive_max_age_hours_effective()
102}
103
104/// Effective on-disk byte budget for archived `.txt`/`.meta.json` content,
105/// derived from `[archive] max_disk_mb` (or the simplified global `max_disk_mb`)
106/// so it matches what `doctor` reports. `0` disables the size cap; the TTL still
107/// applies. This is what bounds the archive store on disk (#417).
108fn max_disk_bytes() -> u64 {
109    super::config::Config::load()
110        .archive_max_disk_mb_effective()
111        .saturating_mul(1024 * 1024)
112}
113
114pub fn should_archive(content: &str) -> bool {
115    is_enabled() && content.len() >= threshold_chars()
116}
117
118const MAX_ARCHIVE_SIZE: usize = 10 * 1024 * 1024; // 10 MB
119const BACKGROUND_RETENTION_HOURS: i64 = 1;
120
121pub fn store(tool: &str, command: &str, content: &str, session_id: Option<&str>) -> Option<String> {
122    store_with_result(tool, command, content, session_id).map(|result| result.id)
123}
124
125#[derive(Debug, Clone, PartialEq, Eq)]
126pub struct ArchiveStoreResult {
127    pub id: String,
128    pub captured_chars: usize,
129    pub archived_chars: usize,
130    pub truncated: bool,
131}
132
133pub fn store_with_result(
134    tool: &str,
135    command: &str,
136    content: &str,
137    session_id: Option<&str>,
138) -> Option<ArchiveStoreResult> {
139    if !is_enabled() || content.is_empty() {
140        return None;
141    }
142
143    let (content, result) = prepared_content(content);
144    let id = result.id.clone();
145    let created = with_archive_lock(|| {
146        let c_path = content_path(&id);
147        if c_path.exists() && meta_path(&id).exists() {
148            return Some(false);
149        }
150        std::fs::create_dir_all(entry_dir(&id)).ok()?;
151        if !c_path.exists() {
152            super::atomic_fs::try_atomic_write(&c_path, content.as_bytes(), None).ok()?;
153            #[cfg(unix)]
154            set_private_file_perms(&c_path);
155        }
156        let entry = new_entry(&id, tool, command, content, session_id, Utc::now());
157        if write_metadata(&entry).is_none() {
158            let _ = std::fs::remove_file(c_path);
159            return None;
160        }
161        Some(true)
162    })
163    .flatten()?;
164    if created {
165        super::archive_fts::index_entry(&id, tool, command, content);
166    }
167    Some(result)
168}
169
170/// Persist a terminal background-shell result and guarantee that lean-ctx's
171/// managed cleanup paths retain it for at least one hour.
172pub fn store_background(
173    tool: &str,
174    job_id: &str,
175    content: &str,
176    session_id: Option<&str>,
177) -> Option<ArchiveStoreResult> {
178    store_background_with_limits(
179        tool,
180        job_id,
181        content,
182        session_id,
183        Utc::now(),
184        max_disk_bytes(),
185    )
186}
187
188fn store_background_with_limits(
189    tool: &str,
190    job_id: &str,
191    content: &str,
192    session_id: Option<&str>,
193    now: DateTime<Utc>,
194    budget_bytes: u64,
195) -> Option<ArchiveStoreResult> {
196    if !is_enabled() || content.is_empty() {
197        return None;
198    }
199
200    let (content, result) = prepared_content(content);
201    let id = result.id.clone();
202    let protected_until = now + chrono::Duration::hours(BACKGROUND_RETENTION_HOURS);
203    let (stored, evicted) = with_archive_lock(|| {
204        let mut entry = read_entry(&id)
205            .unwrap_or_else(|| new_entry(&id, tool, job_id, content, session_id, now));
206        if !entry.aliases.iter().any(|alias| alias == job_id) {
207            entry.aliases.push(job_id.to_string());
208        }
209        entry.protected_until = Some(
210            entry
211                .protected_until
212                .map_or(protected_until, |current| current.max(protected_until)),
213        );
214
215        let metadata = serde_json::to_string_pretty(&entry).ok()?;
216        let existing_bytes = scanned_entries()
217            .into_iter()
218            .find(|candidate| candidate.id == id)
219            .map_or(0, |candidate| candidate.bytes);
220        let required_bytes = content.len() as u64 + metadata.len() as u64;
221        let evicted = admit_locked(&id, existing_bytes, required_bytes, budget_bytes, now)?;
222
223        let c_path = content_path(&id);
224        let content_existed = c_path.exists();
225        if std::fs::create_dir_all(entry_dir(&id)).is_err() {
226            return Some((false, evicted));
227        }
228        if !content_existed {
229            if super::atomic_fs::try_atomic_write(&c_path, content.as_bytes(), None).is_err() {
230                return Some((false, evicted));
231            }
232            #[cfg(unix)]
233            set_private_file_perms(&c_path);
234        }
235        if super::atomic_fs::try_atomic_write(&meta_path(&id), metadata.as_bytes(), None).is_err() {
236            if !content_existed {
237                let _ = std::fs::remove_file(c_path);
238            }
239            return Some((false, evicted));
240        }
241        #[cfg(unix)]
242        set_private_file_perms(&meta_path(&id));
243        Some((true, evicted))
244    })
245    .flatten()?;
246
247    for evicted_id in evicted {
248        super::archive_fts::remove_entry(&evicted_id);
249    }
250    // A content-addressed archive may have been indexed by an earlier generic
251    // store. Protected background output must not remain on the FTS eviction path.
252    super::archive_fts::remove_entry(&id);
253    stored.then_some(result)
254}
255
256fn prepared_content(content: &str) -> (&str, ArchiveStoreResult) {
257    let captured_chars = content.chars().count();
258    let truncated = content.len() > MAX_ARCHIVE_SIZE;
259    let content = if truncated {
260        &content[..content.floor_char_boundary(MAX_ARCHIVE_SIZE)]
261    } else {
262        content
263    };
264    let id = compute_id(content);
265    let result = ArchiveStoreResult {
266        id,
267        captured_chars,
268        archived_chars: content.chars().count(),
269        truncated,
270    };
271    (content, result)
272}
273
274fn new_entry(
275    id: &str,
276    tool: &str,
277    command: &str,
278    content: &str,
279    session_id: Option<&str>,
280    created_at: DateTime<Utc>,
281) -> ArchiveEntry {
282    ArchiveEntry {
283        id: id.to_string(),
284        tool: tool.to_string(),
285        command: command.to_string(),
286        size_chars: content.len(),
287        size_tokens: super::tokens::count_tokens(content),
288        created_at,
289        session_id: session_id.map(std::string::ToString::to_string),
290        protected_until: None,
291        aliases: Vec::new(),
292    }
293}
294
295fn read_entry(id: &str) -> Option<ArchiveEntry> {
296    serde_json::from_str(&std::fs::read_to_string(meta_path(id)).ok()?).ok()
297}
298
299fn write_metadata(entry: &ArchiveEntry) -> Option<()> {
300    let path = meta_path(&entry.id);
301    let json = serde_json::to_string_pretty(entry).ok()?;
302    super::atomic_fs::try_atomic_write(&path, json.as_bytes(), None).ok()?;
303    #[cfg(unix)]
304    set_private_file_perms(&path);
305    Some(())
306}
307
308pub fn retrieve(id: &str) -> Option<String> {
309    let path = content_path(id);
310    std::fs::read_to_string(path).ok()
311}
312
313/// Format a range of lines from content with `{:>6}|` line-number gutter.
314/// Shared by `retrieve_with_range` (archive) and `expand_reference` (ref store).
315pub(crate) fn format_range(content: &str, start: usize, end: usize) -> String {
316    let lines: Vec<&str> = content.lines().collect();
317    let start = start.saturating_sub(1).min(lines.len());
318    let end = end.min(lines.len());
319    if start >= end {
320        return String::new();
321    }
322    lines[start..end]
323        .iter()
324        .enumerate()
325        .map(|(i, line)| format!("{:>6}|{line}", start + i + 1))
326        .collect::<Vec<_>>()
327        .join("\n")
328}
329
330/// Search content for lines matching `pattern` (case-insensitive) and return
331/// gutter-prefixed matches. `label` appears in the result message (e.g. "archive
332/// a1966..." or "reference ref_18bb..."). Shared by archive and ref store paths.
333pub(crate) fn format_search(content: &str, pattern: &str, label: &str) -> String {
334    let pattern_lower = pattern.to_lowercase();
335    let matches: Vec<String> = content
336        .lines()
337        .enumerate()
338        .filter(|(_, line)| line.to_lowercase().contains(&pattern_lower))
339        .map(|(i, line)| format!("{:>6}|{line}", i + 1))
340        .collect();
341    if matches.is_empty() {
342        format!("No matches for \"{pattern}\" in {label}")
343    } else {
344        format!(
345            "{} match(es) for \"{}\":\n{}",
346            matches.len(),
347            pattern,
348            matches.join("\n")
349        )
350    }
351}
352
353/// Describe JSON structure: navigate `path` (dot/slash separated) into parsed
354/// content, then format with `describe_json`. `label` appears in error messages.
355/// Shared by archive and ref store paths.
356pub(crate) fn format_json_keys(content: &str, path: Option<&str>, label: &str) -> Option<String> {
357    let root: serde_json::Value = serde_json::from_str(content.trim()).ok()?;
358    let mut cur = &root;
359    let mut walked = String::from("$");
360    if let Some(p) = path {
361        for seg in p.split(['.', '/']).filter(|s| !s.is_empty()) {
362            let next = if let Ok(idx) = seg.parse::<usize>() {
363                cur.get(idx)
364            } else {
365                cur.get(seg)
366            };
367            match next {
368                Some(v) => {
369                    cur = v;
370                    walked.push('.');
371                    walked.push_str(seg);
372                }
373                None => {
374                    return Some(format!("Path '{p}' not found at '{walked}' in {label}"));
375                }
376            }
377        }
378    }
379    Some(format!("{walked} => {}", describe_json(cur)))
380}
381
382pub fn retrieve_with_range(id: &str, start: usize, end: usize) -> Option<String> {
383    let content = retrieve(id)?;
384    Some(format_range(&content, start, end))
385}
386
387pub fn retrieve_with_search(id: &str, pattern: &str) -> Option<String> {
388    let content = retrieve(id)?;
389    Some(format_search(&content, pattern, &format!("archive {id}")))
390}
391
392/// Retrieve the first `n` lines of an archived entry, with a line-number gutter.
393pub fn retrieve_head(id: &str, n: usize) -> Option<String> {
394    retrieve_with_range(id, 1, n)
395}
396
397/// Retrieve the last `n` lines of an archived entry, with a line-number gutter.
398pub fn retrieve_tail(id: &str, n: usize) -> Option<String> {
399    let content = retrieve(id)?;
400    let total = content.lines().count();
401    let start = if total > n { total - n + 1 } else { 1 };
402    retrieve_with_range(id, start, total)
403}
404
405/// Describe the JSON structure of an archived entry.
406pub fn retrieve_json_keys(id: &str, path: Option<&str>) -> Option<String> {
407    let content = retrieve(id)?;
408    format_json_keys(&content, path, &format!("archive {id}"))
409}
410
411pub(crate) fn json_type_hint(v: &serde_json::Value) -> String {
412    use serde_json::Value;
413    match v {
414        Value::Object(m) => format!("object({})", m.len()),
415        Value::Array(a) => format!("array({})", a.len()),
416        Value::String(s) => {
417            let preview: String = s.chars().take(40).collect();
418            if s.chars().count() > 40 {
419                format!("string \"{preview}…\"")
420            } else {
421                format!("string \"{preview}\"")
422            }
423        }
424        Value::Number(n) => format!("number {n}"),
425        Value::Bool(b) => format!("bool {b}"),
426        Value::Null => "null".to_string(),
427    }
428}
429
430pub(crate) fn describe_json(v: &serde_json::Value) -> String {
431    use serde_json::Value;
432    match v {
433        Value::Object(map) => {
434            let mut keys: Vec<&String> = map.keys().collect();
435            keys.sort();
436            let rendered: Vec<String> = keys
437                .iter()
438                .map(|k| format!("  {k}: {}", json_type_hint(&map[*k])))
439                .collect();
440            format!("object ({} keys)\n{}", map.len(), rendered.join("\n"))
441        }
442        Value::Array(arr) => {
443            let elem = arr.first().map_or("empty", |e| match e {
444                Value::Object(_) => "object",
445                Value::Array(_) => "array",
446                Value::String(_) => "string",
447                Value::Number(_) => "number",
448                Value::Bool(_) => "bool",
449                Value::Null => "null",
450            });
451            let mut out = format!("array ({} items of {elem})", arr.len());
452            if let Some(Value::Object(map)) = arr.first() {
453                let mut keys: Vec<&String> = map.keys().collect();
454                keys.sort();
455                out.push_str(&format!(
456                    "\n  [0] keys: {}",
457                    keys.iter()
458                        .map(|s| s.as_str())
459                        .collect::<Vec<_>>()
460                        .join(", ")
461                ));
462            }
463            out
464        }
465        Value::String(s) => format!("string ({} chars)", s.len()),
466        Value::Number(n) => format!("number ({n})"),
467        Value::Bool(b) => format!("bool ({b})"),
468        Value::Null => "null".to_string(),
469    }
470}
471
472pub fn list_entries(session_id: Option<&str>) -> Vec<ArchiveEntry> {
473    let base = archive_base_dir();
474    if !base.exists() {
475        return Vec::new();
476    }
477    let mut entries = Vec::new();
478    if let Ok(dirs) = std::fs::read_dir(&base) {
479        for dir_entry in dirs.flatten() {
480            if !dir_entry.path().is_dir() {
481                continue;
482            }
483            if let Ok(files) = std::fs::read_dir(dir_entry.path()) {
484                for file in files.flatten() {
485                    let path = file.path();
486                    if path.extension().and_then(|e| e.to_str()) != Some("json") {
487                        continue;
488                    }
489                    if let Ok(data) = std::fs::read_to_string(&path)
490                        && let Ok(entry) = serde_json::from_str::<ArchiveEntry>(&data)
491                    {
492                        if let Some(sid) = session_id
493                            && entry.session_id.as_deref() != Some(sid)
494                        {
495                            continue;
496                        }
497                        entries.push(entry);
498                    }
499                }
500            }
501        }
502    }
503    entries.sort_by_key(|e| std::cmp::Reverse(e.created_at));
504    entries
505}
506
507pub fn resolve_alias(alias: &str) -> Option<String> {
508    list_entries(None)
509        .into_iter()
510        .find(|entry| entry.aliases.iter().any(|candidate| candidate == alias))
511        .map(|entry| entry.id)
512}
513
514pub(crate) fn is_protected(id: &str) -> bool {
515    read_entry(id)
516        .and_then(|entry| entry.protected_until)
517        .is_some_and(|until| until > Utc::now())
518}
519
520/// Remove only the on-disk content + metadata files for an archive id, leaving
521/// the FTS index untouched. Used by the FTS cap-enforcer so the `.txt`/`.meta.json`
522/// blobs of rows it evicts can't outlive their index entry as orphans (#417).
523pub fn remove_files(id: &str) {
524    let _ = with_archive_lock(|| {
525        if !is_protected(id) {
526            remove_files_locked(id);
527        }
528    });
529}
530
531fn remove_files_locked(id: &str) {
532    let _ = std::fs::remove_file(content_path(id));
533    let _ = std::fs::remove_file(meta_path(id));
534}
535
536struct ScannedArchive {
537    id: String,
538    created_at: DateTime<Utc>,
539    protected_until: Option<DateTime<Utc>>,
540    bytes: u64,
541}
542
543fn scanned_entries() -> Vec<ScannedArchive> {
544    list_entries(None)
545        .into_iter()
546        .map(|entry| {
547            let content_bytes = std::fs::metadata(content_path(&entry.id)).map_or(0, |m| m.len());
548            let metadata_bytes = std::fs::metadata(meta_path(&entry.id)).map_or(0, |m| m.len());
549            ScannedArchive {
550                id: entry.id,
551                created_at: entry.created_at,
552                protected_until: entry.protected_until,
553                bytes: content_bytes + metadata_bytes,
554            }
555        })
556        .collect()
557}
558
559fn protected_at(entry: &ScannedArchive, now: DateTime<Utc>) -> bool {
560    entry.protected_until.is_some_and(|until| until > now)
561}
562
563fn admit_locked(
564    new_id: &str,
565    existing_bytes: u64,
566    required_bytes: u64,
567    budget_bytes: u64,
568    now: DateTime<Utc>,
569) -> Option<Vec<String>> {
570    if budget_bytes == 0 {
571        return Some(Vec::new());
572    }
573
574    let mut entries = scanned_entries();
575    let live_bytes: u64 = entries.iter().map(|entry| entry.bytes).sum();
576    let mut projected = live_bytes
577        .saturating_sub(existing_bytes)
578        .saturating_add(required_bytes);
579    if projected <= budget_bytes {
580        return Some(Vec::new());
581    }
582
583    entries.sort_by_key(|entry| entry.created_at);
584    let candidates: Vec<_> = entries
585        .into_iter()
586        .filter(|entry| entry.id != new_id && !protected_at(entry, now))
587        .collect();
588    let reclaimable: u64 = candidates.iter().map(|entry| entry.bytes).sum();
589    if projected.saturating_sub(reclaimable) > budget_bytes {
590        return None;
591    }
592
593    let mut evicted = Vec::new();
594    for entry in candidates {
595        remove_files_locked(&entry.id);
596        projected = projected.saturating_sub(entry.bytes);
597        evicted.push(entry.id);
598        if projected <= budget_bytes {
599            break;
600        }
601    }
602    Some(evicted)
603}
604
605/// Prune archived entries that exceed the age TTL (`max_age_hours`) or that push
606/// the on-disk store past its size budget (`max_disk_mb`). The content file,
607/// metadata, and FTS index are removed together so the two stores stay in sync.
608/// Returns the number of entries removed.
609///
610/// Wired into MCP-start + periodic maintenance (`super::storage_maintenance`)
611/// and `lean-ctx cache prune`; without an enforcer the archive grew unbounded on
612/// disk and starved the host of RAM via the page cache (#417).
613pub fn cleanup() -> u32 {
614    let now = Utc::now();
615    let cutoff = now - chrono::Duration::hours(max_age_hours() as i64);
616    cleanup_with(cutoff, max_disk_bytes(), now)
617}
618
619/// Core of [`cleanup`], parameterized for testing: drop entries older than
620/// `cutoff`, then evict the oldest survivors until the total on-disk footprint is
621/// at or below `budget_bytes` (`0` = no size cap).
622fn cleanup_with(cutoff: DateTime<Utc>, budget_bytes: u64, now: DateTime<Utc>) -> u32 {
623    let base = archive_base_dir();
624    if !base.exists() {
625        return 0;
626    }
627
628    let removed = with_archive_lock(|| {
629        let mut entries = scanned_entries();
630        entries.sort_by_key(|entry| entry.created_at);
631        let mut live_bytes: u64 = entries.iter().map(|entry| entry.bytes).sum();
632        let mut removed = std::collections::HashSet::new();
633
634        for entry in &entries {
635            if entry.created_at < cutoff && !protected_at(entry, now) {
636                remove_files_locked(&entry.id);
637                live_bytes = live_bytes.saturating_sub(entry.bytes);
638                removed.insert(entry.id.clone());
639            }
640        }
641
642        if budget_bytes > 0 {
643            for entry in &entries {
644                if live_bytes <= budget_bytes {
645                    break;
646                }
647                if !removed.contains(&entry.id) && !protected_at(entry, now) {
648                    remove_files_locked(&entry.id);
649                    live_bytes = live_bytes.saturating_sub(entry.bytes);
650                    removed.insert(entry.id.clone());
651                }
652            }
653        }
654        removed
655    })
656    .unwrap_or_default();
657    for id in &removed {
658        super::archive_fts::remove_entry(id);
659    }
660    removed.len() as u32
661}
662
663pub fn disk_usage_bytes() -> u64 {
664    let base = archive_base_dir();
665    if !base.exists() {
666        return 0;
667    }
668    let mut total = 0u64;
669    if let Ok(dirs) = std::fs::read_dir(&base) {
670        for dir_entry in dirs.flatten() {
671            if let Ok(files) = std::fs::read_dir(dir_entry.path()) {
672                for file in files.flatten() {
673                    total += file.metadata().map_or(0, |m| m.len());
674                }
675            }
676        }
677    }
678    total
679}
680
681/// Filesystem path of an archived entry's verbatim content. Exposed so recovery
682/// hints can offer the MCP-free "read this file directly" route alongside
683/// `ctx_expand(id=...)` — the same content is reachable both ways.
684pub fn content_path_str(id: &str) -> String {
685    content_path(id).to_string_lossy().into_owned()
686}
687
688pub fn format_hint(id: &str, size_chars: usize, size_tokens: usize) -> String {
689    // Unified, non-MCP-first recovery grammar (see [`crate::core::recovery`]): the
690    // archived blob is a real file readable with any tool, and `ctx_expand(id)`
691    // reaches the same bytes for surgical slices.
692    let clause = crate::core::recovery::handle_clause(id, Some(&content_path_str(id)));
693    format!("[Archived: {size_chars} chars ({size_tokens} tok). {clause}]")
694}
695
696#[cfg(test)]
697mod tests {
698    use super::*;
699
700    #[test]
701    fn compute_id_deterministic() {
702        let id1 = compute_id("test content");
703        let id2 = compute_id("test content");
704        assert_eq!(id1, id2);
705        let id3 = compute_id("different content");
706        assert_ne!(id1, id3);
707    }
708
709    #[test]
710    fn nonexistent_id_returns_none() {
711        assert!(retrieve("nonexistent_archive_id_xyz").is_none());
712    }
713
714    #[test]
715    fn format_hint_readable() {
716        let hint = format_hint("abc123", 5000, 1200);
717        assert!(hint.contains("5000 chars"));
718        assert!(hint.contains("1200 tok"));
719        assert!(hint.contains("ctx_expand"));
720        assert!(hint.contains("abc123"));
721    }
722
723    fn write_test_entry(id: &str, created_at: DateTime<Utc>, content_bytes: usize) {
724        std::fs::create_dir_all(entry_dir(id)).unwrap();
725        std::fs::write(content_path(id), "x".repeat(content_bytes)).unwrap();
726        let entry = ArchiveEntry {
727            id: id.to_string(),
728            tool: "ctx_shell".to_string(),
729            command: "test".to_string(),
730            size_chars: content_bytes,
731            size_tokens: content_bytes / 4,
732            created_at,
733            session_id: None,
734            protected_until: None,
735            aliases: Vec::new(),
736        };
737        std::fs::write(meta_path(id), serde_json::to_string(&entry).unwrap()).unwrap();
738    }
739
740    #[test]
741    fn cleanup_removes_expired_keeps_fresh() {
742        let _lock = crate::core::data_dir::test_env_lock();
743        let tmp = tempfile::tempdir().unwrap();
744        crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
745
746        let now = Utc::now();
747        write_test_entry("aa_old", now - chrono::Duration::hours(100), 100);
748        write_test_entry("bb_new", now - chrono::Duration::hours(1), 100);
749
750        // Cutoff = 48h ago; budget effectively unlimited so only the TTL applies.
751        let removed = cleanup_with(now - chrono::Duration::hours(48), u64::MAX, now);
752        assert_eq!(removed, 1);
753        assert!(!content_path("aa_old").exists());
754        assert!(!meta_path("aa_old").exists());
755        assert!(content_path("bb_new").exists());
756
757        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
758    }
759
760    #[test]
761    fn cleanup_enforces_disk_budget_oldest_first() {
762        let _lock = crate::core::data_dir::test_env_lock();
763        let tmp = tempfile::tempdir().unwrap();
764        crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
765
766        let now = Utc::now();
767        write_test_entry("c1_oldest", now - chrono::Duration::minutes(30), 10_000);
768        write_test_entry("c2_middle", now - chrono::Duration::minutes(20), 10_000);
769        write_test_entry("c3_newest", now - chrono::Duration::minutes(10), 10_000);
770
771        // Nothing expired (cutoff far in the past). Budget 25 KB holds the two
772        // newest (~20 KB content + meta); the single oldest entry is evicted.
773        let removed = cleanup_with(now - chrono::Duration::days(365), 25_000, now);
774        assert_eq!(removed, 1, "only the oldest over-budget entry is evicted");
775        assert!(!content_path("c1_oldest").exists());
776        assert!(content_path("c2_middle").exists());
777        assert!(content_path("c3_newest").exists());
778
779        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
780    }
781
782    #[test]
783    fn legacy_metadata_defaults_background_retention_fields() {
784        let entry: ArchiveEntry = serde_json::from_value(serde_json::json!({
785            "id": "legacy",
786            "tool": "ctx_shell",
787            "command": "printf legacy",
788            "size_chars": 6,
789            "size_tokens": 2,
790            "created_at": "2026-01-01T00:00:00Z",
791            "session_id": null
792        }))
793        .unwrap();
794
795        assert!(entry.protected_until.is_none());
796        assert!(entry.aliases.is_empty());
797    }
798
799    #[test]
800    fn protected_archive_survives_cleanup_and_direct_fts_removal_path() {
801        let _lock = crate::core::data_dir::test_env_lock();
802        let tmp = tempfile::tempdir().unwrap();
803        crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
804
805        let now = Utc::now();
806        write_test_entry("protected", now - chrono::Duration::hours(100), 100);
807        let mut entry = read_entry("protected").unwrap();
808        entry.protected_until = Some(now + chrono::Duration::hours(1));
809        write_metadata(&entry).unwrap();
810
811        assert_eq!(cleanup_with(now - chrono::Duration::hours(48), 1, now), 0);
812        remove_files("protected");
813        assert!(content_path("protected").exists());
814
815        let later = now + chrono::Duration::hours(2);
816        assert_eq!(cleanup_with(now, 1, later), 1);
817        assert!(!content_path("protected").exists());
818
819        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
820    }
821
822    #[test]
823    fn background_store_refuses_when_protected_entries_fill_budget() {
824        let _lock = crate::core::data_dir::test_env_lock();
825        let tmp = tempfile::tempdir().unwrap();
826        crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
827        crate::test_env::set_var("LEAN_CTX_ARCHIVE", "1");
828
829        let now = Utc::now();
830        let first = store_background_with_limits(
831            "ctx_shell",
832            "shell_first",
833            "first protected output",
834            None,
835            now,
836            u64::MAX,
837        )
838        .unwrap();
839        let budget = scanned_entries()
840            .into_iter()
841            .find(|entry| entry.id == first.id)
842            .unwrap()
843            .bytes;
844
845        assert!(
846            store_background_with_limits(
847                "ctx_shell",
848                "shell_second",
849                "different protected output",
850                None,
851                now,
852                budget,
853            )
854            .is_none()
855        );
856        assert_eq!(resolve_alias("shell_first"), Some(first.id));
857        assert!(resolve_alias("shell_second").is_none());
858
859        crate::test_env::remove_var("LEAN_CTX_ARCHIVE");
860        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
861    }
862
863    #[test]
864    fn concurrent_background_writers_merge_content_aliases() {
865        let _lock = crate::core::data_dir::test_env_lock();
866        let tmp = tempfile::tempdir().unwrap();
867        crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
868        crate::test_env::set_var("LEAN_CTX_ARCHIVE", "1");
869
870        let barrier = std::sync::Arc::new(std::sync::Barrier::new(3));
871        let mut writers = Vec::new();
872        for job_id in ["shell_alpha", "shell_beta"] {
873            let barrier = barrier.clone();
874            writers.push(std::thread::spawn(move || {
875                barrier.wait();
876                store_background_with_limits(
877                    "ctx_shell",
878                    job_id,
879                    "shared terminal output",
880                    None,
881                    Utc::now(),
882                    0,
883                )
884                .unwrap()
885            }));
886        }
887        barrier.wait();
888        let first = writers.remove(0).join().unwrap();
889        let second = writers.remove(0).join().unwrap();
890
891        assert_eq!(first.id, second.id);
892        assert_eq!(resolve_alias("shell_alpha"), Some(first.id.clone()));
893        assert_eq!(resolve_alias("shell_beta"), Some(first.id));
894
895        crate::test_env::remove_var("LEAN_CTX_ARCHIVE");
896        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
897    }
898}