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