Skip to main content

lean_ctx/core/
memory_archive.rs

1//! Multi-store, lossless memory archive (#995 Phase 1).
2//!
3//! Every memory store — facts, history, procedures, patterns — archives the
4//! items it evicts here *before* dropping them, so capacity management is never
5//! lossy and anything reclaimed can be restored. This is the single archive
6//! subsystem behind the memory-capacity module and the recall-miss
7//! rehydrate path.
8//!
9//! ## On-disk layout
10//! - Facts keep their legacy global location `memory/archive/archive-*.json`
11//!   for backward compatibility (pre-#995 archives stay readable).
12//! - Every other store lives under `memory/archive/<store>/<scope>/archive-*.json`,
13//!   where `<scope>` is the per-project hash so a restore lands in the right
14//!   project.
15//!
16//! ## Format
17//! A single envelope ([`ArchiveEnvelope`]) is used for all stores. The item
18//! collection serializes as `items`; the `facts` alias keeps legacy facts
19//! archives (which used that key) deserializable.
20
21use chrono::{DateTime, Utc};
22use serde::{Deserialize, Serialize, de::DeserializeOwned};
23use std::path::{Path, PathBuf};
24
25/// Retention bound on archive files, kept well above the rehydrate reach so a
26/// recall miss can still find recently-evicted items. Overridable via
27/// `LEAN_CTX_ARCHIVE_MAX_FILES`.
28const DEFAULT_MAX_ARCHIVE_FILES: usize = 16;
29
30/// Which memory store an archive belongs to. Drives the on-disk path only — the
31/// archive is generic over the item type, so this stays decoupled from the
32/// concrete fact/insight/procedure/pattern structs.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum MemoryStore {
35    Facts,
36    History,
37    Procedures,
38    Patterns,
39}
40
41impl MemoryStore {
42    pub fn as_str(self) -> &'static str {
43        match self {
44            MemoryStore::Facts => "facts",
45            MemoryStore::History => "history",
46            MemoryStore::Procedures => "procedures",
47            MemoryStore::Patterns => "patterns",
48        }
49    }
50
51    pub fn parse(s: &str) -> Option<Self> {
52        match s.trim().to_lowercase().as_str() {
53            "facts" | "fact" => Some(MemoryStore::Facts),
54            "history" | "insights" => Some(MemoryStore::History),
55            "procedures" | "procedure" | "procs" => Some(MemoryStore::Procedures),
56            "patterns" | "pattern" => Some(MemoryStore::Patterns),
57            _ => None,
58        }
59    }
60
61    /// All stores, for cross-store iteration (restore, reporting).
62    pub fn all() -> [MemoryStore; 4] {
63        [
64            MemoryStore::Facts,
65            MemoryStore::History,
66            MemoryStore::Procedures,
67            MemoryStore::Patterns,
68        ]
69    }
70
71    /// Subdirectory under `memory/archive`. Facts return `None` (legacy root).
72    fn subdir(self) -> Option<&'static str> {
73        match self {
74            MemoryStore::Facts => None,
75            other => Some(other.as_str()),
76        }
77    }
78}
79
80/// Tunable archive bounds. `rehydrate_reach` is how many of the newest archives
81/// the recall-miss path scans; it defaults to `max_files` so every retained
82/// archive is actually reachable (closing the pre-#995 16-retained / 4-reachable
83/// gap). Both are overridable via env for ops tuning.
84#[derive(Debug, Clone, Copy)]
85pub struct ArchiveConfig {
86    pub max_files: usize,
87    pub rehydrate_reach: usize,
88}
89
90impl Default for ArchiveConfig {
91    fn default() -> Self {
92        Self {
93            max_files: DEFAULT_MAX_ARCHIVE_FILES,
94            rehydrate_reach: DEFAULT_MAX_ARCHIVE_FILES,
95        }
96    }
97}
98
99impl ArchiveConfig {
100    /// Read overrides from the environment. `rehydrate_reach` defaults to
101    /// `max_files` and is clamped to it (cannot reach more files than retained).
102    pub fn from_env() -> Self {
103        let mut cfg = Self::default();
104        if let Ok(v) = std::env::var("LEAN_CTX_ARCHIVE_MAX_FILES")
105            && let Ok(n) = v.parse::<usize>()
106            && n > 0
107        {
108            cfg.max_files = n;
109            cfg.rehydrate_reach = n;
110        }
111        if let Ok(v) = std::env::var("LEAN_CTX_ARCHIVE_REHYDRATE_REACH")
112            && let Ok(n) = v.parse::<usize>()
113            && n > 0
114        {
115            cfg.rehydrate_reach = n;
116        }
117        cfg.rehydrate_reach = cfg.rehydrate_reach.min(cfg.max_files);
118        cfg
119    }
120}
121
122/// Unified archive envelope for reading every store. The collection is keyed
123/// `items`; the `facts` alias keeps legacy facts archives (which used that key)
124/// deserializable.
125#[derive(Debug, Deserialize)]
126pub struct ArchiveEnvelope<T> {
127    pub archived_at: DateTime<Utc>,
128    #[serde(default)]
129    pub store: String,
130    #[serde(default)]
131    pub scope: Option<String>,
132    #[serde(rename = "items", alias = "facts")]
133    pub items: Vec<T>,
134}
135
136/// Borrowed write-side envelope, so archiving never has to clone the evicted
137/// slice. Mirrors [`ArchiveEnvelope`]'s on-disk shape exactly.
138#[derive(Serialize)]
139struct ArchiveEnvelopeRef<'a, T: Serialize> {
140    archived_at: DateTime<Utc>,
141    store: &'a str,
142    #[serde(skip_serializing_if = "Option::is_none")]
143    scope: Option<&'a str>,
144    items: &'a [T],
145}
146
147fn effective_scope(scope: Option<&str>) -> Result<Option<String>, String> {
148    let root = crate::core::policy::diagnostics::project().ok_or("archive project unavailable")?;
149    let root = root.to_string_lossy();
150    if crate::core::knowledge::protection::current(&root)?.is_some() {
151        let expected = crate::core::project_hash::hash_project_root(&root);
152        if scope.is_some_and(|given| given != expected) {
153            return Err("archive scope does not match protected project".into());
154        }
155        Ok(Some(expected))
156    } else {
157        Ok(scope.map(str::to_owned))
158    }
159}
160
161fn archive_dir(store: MemoryStore, scope: Option<&str>) -> Result<PathBuf, String> {
162    let base = crate::core::data_dir::lean_ctx_data_dir()?
163        .join("memory")
164        .join("archive");
165    let scope = effective_scope(scope)?;
166    let root = crate::core::policy::diagnostics::project().ok_or("archive project unavailable")?;
167    let protected = crate::core::knowledge::protection::current(&root.to_string_lossy())?.is_some();
168    let dir = match (store.subdir(), scope.as_deref()) {
169        (None, Some(s)) if protected => base.join("facts").join(sanitize_scope(s)),
170        (None, _) => base,                   // legacy global facts
171        (Some(sub), None) => base.join(sub), // store-global
172        (Some(sub), Some(s)) => base.join(sub).join(sanitize_scope(s)),
173    };
174    Ok(dir)
175}
176
177/// Scopes are project hashes (hex). Guard against path traversal regardless,
178/// so a malformed scope can never escape the archive root.
179fn sanitize_scope(scope: &str) -> String {
180    scope
181        .chars()
182        .map(|c| {
183            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
184                c
185            } else {
186                '_'
187            }
188        })
189        .collect()
190}
191
192/// Archive `items` for `store`/`scope`, then prune the directory to
193/// `cfg.max_files` newest. Returns the written path, or `None` when there was
194/// nothing to archive. Best-effort prune: a prune failure never fails the write.
195pub fn archive_items<T: Serialize>(
196    store: MemoryStore,
197    scope: Option<&str>,
198    items: &[T],
199    cfg: &ArchiveConfig,
200) -> Result<Option<PathBuf>, String> {
201    if items.is_empty() {
202        return Ok(None);
203    }
204    let scope = effective_scope(scope)?;
205    let scope = scope.as_deref();
206    let dir = archive_dir(store, scope)?;
207    std::fs::create_dir_all(&dir).map_err(|e| format!("{e}"))?;
208
209    // Sub-second suffix avoids same-second filename collisions that would
210    // otherwise silently overwrite a prior archive in the same wall-clock second.
211    let now = Utc::now();
212    let suffix = now.timestamp_subsec_nanos() % 1_000_000;
213    let filename = format!("archive-{}-{suffix:06}.json", now.format("%Y%m%d-%H%M%S"));
214    let path = dir.join(filename);
215
216    let envelope = ArchiveEnvelopeRef {
217        archived_at: now,
218        store: store.as_str(),
219        scope,
220        items,
221    };
222    let original = serde_json::to_value(&envelope).map_err(|_| "archive cannot be inspected")?;
223    let safe = inspect_archive(&original)?;
224    let json = serde_json::to_string_pretty(&safe).map_err(|_| "archive serialization failed")?;
225    if inspect_archive(&safe)? != safe {
226        return Err("archive rules changed before publication".into());
227    }
228    use std::io::Write;
229    let mut file = tempfile::NamedTempFile::new_in(&dir).map_err(|_| "archive staging failed")?;
230    file.write_all(json.as_bytes())
231        .map_err(|_| "archive write failed")?;
232    // A clock collision must never overwrite an existing recovery artifact.
233    file.persist_noclobber(&path)
234        .map_err(|_| "archive publication failed")?;
235
236    let archives = list_archives(store, scope);
237    if archives.len() > cfg.max_files {
238        for old in &archives[..archives.len() - cfg.max_files] {
239            let _ = std::fs::remove_file(old);
240        }
241    }
242    Ok(Some(path))
243}
244
245/// All archive files for `store`/`scope`, sorted ascending (lexical ==
246/// chronological for the zero-padded timestamp filename prefix).
247pub fn list_archives(store: MemoryStore, scope: Option<&str>) -> Vec<PathBuf> {
248    let Ok(dir) = archive_dir(store, scope) else {
249        return Vec::new();
250    };
251    if !dir.exists() {
252        return Vec::new();
253    }
254    let mut archives: Vec<PathBuf> = std::fs::read_dir(&dir)
255        .into_iter()
256        .flatten()
257        .flatten()
258        .map(|e| e.path())
259        .filter(|p| p.is_file() && p.extension().is_some_and(|ext| ext == "json"))
260        .collect();
261    archives.sort();
262    archives
263}
264
265/// The newest `cfg.rehydrate_reach` archives for `store`/`scope` — the set a
266/// recall miss should scan. Aligned with retention so nothing retained is
267/// unreachable.
268pub fn reachable_archives(
269    store: MemoryStore,
270    scope: Option<&str>,
271    cfg: &ArchiveConfig,
272) -> Vec<PathBuf> {
273    let mut archives = list_archives(store, scope);
274    if archives.len() > cfg.rehydrate_reach {
275        archives = archives[archives.len() - cfg.rehydrate_reach..].to_vec();
276    }
277    archives
278}
279
280/// Restore the items from a single archive file.
281pub fn restore_items<T: DeserializeOwned>(path: &Path) -> Result<Vec<T>, String> {
282    let data = crate::core::policy::diagnostics::Target::read_file(path)
283        .ok_or("archive is unavailable or uninspectable")?;
284    let original: serde_json::Value = serde_json::from_str(&data).map_err(|_| "invalid archive")?;
285    let root = crate::core::policy::diagnostics::project().ok_or("archive project unavailable")?;
286    if crate::core::knowledge::protection::current(&root.to_string_lossy())?.is_some() {
287        let kind = match original["store"].as_str() {
288            Some("facts") => MemoryStore::Facts,
289            Some("history") => MemoryStore::History,
290            Some("procedures") => MemoryStore::Procedures,
291            Some("patterns") => MemoryStore::Patterns,
292            _ => return Err("archive store identity unavailable".into()),
293        };
294        let scope = original["scope"]
295            .as_str()
296            .ok_or("archive has no protected scope")?;
297        let expected = archive_dir(kind, Some(scope))?;
298        let canonical = |p: &Path| crate::core::pathutil::safe_canonicalize_bounded(p, 2000);
299        if path.parent().map(canonical) != Some(canonical(&expected)) {
300            return Err("archive belongs to a different storage scope".into());
301        }
302    }
303    let safe = inspect_archive(&original)?;
304    let envelope: ArchiveEnvelope<T> = serde_json::from_value(safe)
305        .map_err(|_| "archive policy result is structurally invalid")?;
306    Ok(envelope.items)
307}
308
309fn inspect_archive(original: &serde_json::Value) -> Result<serde_json::Value, String> {
310    let root = crate::core::policy::diagnostics::project().ok_or("archive project unavailable")?;
311    let active = crate::core::knowledge::protection::current(&root.to_string_lossy())?;
312    let safe = crate::core::policy::diagnostics::inspect(original, active.as_deref())
313        .ok_or("archive withheld by current policy")?;
314    for field in ["store", "scope", "archived_at"] {
315        if safe[field] != original[field] {
316            return Err("archive identity cannot be rewritten".into());
317        }
318    }
319    let before_items = original.get("items").or_else(|| original.get("facts"));
320    let after_items = safe.get("items").or_else(|| safe.get("facts"));
321    if let (Some(before), Some(after)) = (
322        before_items.and_then(serde_json::Value::as_array),
323        after_items.and_then(serde_json::Value::as_array),
324    ) {
325        for (a, b) in before.iter().zip(after) {
326            for field in [
327                "id",
328                "key",
329                "category",
330                "source_session",
331                "supersedes",
332                "from_sessions",
333                "pattern_type",
334            ] {
335                if a.get(field) != b.get(field) {
336                    return Err("archived item identity cannot be rewritten".into());
337                }
338            }
339        }
340    }
341    Ok(safe)
342}
343
344#[cfg(test)]
345pub mod tests {
346    use super::*;
347
348    fn with_temp_data_dir<T>(f: impl FnOnce() -> T) -> T {
349        let _lock = crate::core::data_dir::test_env_lock();
350        let dir = std::env::temp_dir().join(format!(
351            "lctx-archive-{}-{}",
352            std::process::id(),
353            Utc::now().timestamp_nanos_opt().unwrap_or(0)
354        ));
355        let _ = std::fs::create_dir_all(&dir);
356        crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());
357        let out = f();
358        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
359        let _ = std::fs::remove_dir_all(&dir);
360        out
361    }
362
363    #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
364    struct Item {
365        id: u32,
366        label: String,
367    }
368
369    fn items(n: u32) -> Vec<Item> {
370        (0..n)
371            .map(|i| Item {
372                id: i,
373                label: format!("item-{i}"),
374            })
375            .collect()
376    }
377
378    #[test]
379    fn round_trip_each_store() {
380        with_temp_data_dir(|| {
381            let cfg = ArchiveConfig::default();
382            for store in MemoryStore::all() {
383                let scope = if store == MemoryStore::Facts {
384                    None
385                } else {
386                    Some("projhash")
387                };
388                let path = archive_items(store, scope, &items(3), &cfg)
389                    .unwrap()
390                    .expect("wrote an archive");
391                let restored: Vec<Item> = restore_items(&path).unwrap();
392                assert_eq!(restored, items(3), "round-trip for {}", store.as_str());
393            }
394        });
395    }
396
397    #[test]
398    fn empty_archive_is_noop() {
399        with_temp_data_dir(|| {
400            let cfg = ArchiveConfig::default();
401            let res =
402                archive_items(MemoryStore::History, Some("p"), &Vec::<Item>::new(), &cfg).unwrap();
403            assert!(res.is_none());
404            assert!(list_archives(MemoryStore::History, Some("p")).is_empty());
405        });
406    }
407
408    #[test]
409    fn facts_use_legacy_root_other_stores_are_scoped() {
410        with_temp_data_dir(|| {
411            let base = crate::core::data_dir::lean_ctx_data_dir()
412                .unwrap()
413                .join("memory")
414                .join("archive");
415            assert_eq!(archive_dir(MemoryStore::Facts, None).unwrap(), base);
416            assert_eq!(
417                archive_dir(MemoryStore::History, Some("h")).unwrap(),
418                base.join("history").join("h")
419            );
420        });
421    }
422
423    #[test]
424    fn legacy_facts_field_alias_still_deserializes() {
425        with_temp_data_dir(|| {
426            let dir = archive_dir(MemoryStore::Facts, None).unwrap();
427            std::fs::create_dir_all(&dir).unwrap();
428            // A pre-#995 facts archive used the `facts` key, no store/scope.
429            let legacy =
430                r#"{"archived_at":"2026-01-01T00:00:00Z","facts":[{"id":7,"label":"old"}]}"#;
431            let path = dir.join("archive-20260101-000000-000000.json");
432            std::fs::write(&path, legacy).unwrap();
433            let restored: Vec<Item> = restore_items(&path).unwrap();
434            assert_eq!(
435                restored,
436                vec![Item {
437                    id: 7,
438                    label: "old".into()
439                }]
440            );
441        });
442    }
443
444    #[test]
445    fn prune_keeps_newest_max_files() {
446        with_temp_data_dir(|| {
447            let cfg = ArchiveConfig {
448                max_files: 3,
449                rehydrate_reach: 3,
450            };
451            for _ in 0..6 {
452                // Distinct filenames require distinct sub-second suffixes; a tiny
453                // sleep guarantees monotonic timestamps on fast machines.
454                archive_items(MemoryStore::Patterns, Some("p"), &items(1), &cfg).unwrap();
455                std::thread::sleep(std::time::Duration::from_millis(2));
456            }
457            let archives = list_archives(MemoryStore::Patterns, Some("p"));
458            assert!(
459                archives.len() <= 3,
460                "prune should bound to max_files, got {}",
461                archives.len()
462            );
463        });
464    }
465
466    #[test]
467    fn reachable_is_bounded_and_aligns_with_retention_by_default() {
468        let cfg = ArchiveConfig::default();
469        assert_eq!(cfg.rehydrate_reach, cfg.max_files);
470    }
471
472    #[test]
473    fn from_env_reach_clamped_to_max() {
474        let _lock = crate::core::data_dir::test_env_lock();
475        crate::test_env::set_var("LEAN_CTX_ARCHIVE_MAX_FILES", "5");
476        crate::test_env::set_var("LEAN_CTX_ARCHIVE_REHYDRATE_REACH", "99");
477        let cfg = ArchiveConfig::from_env();
478        assert_eq!(cfg.max_files, 5);
479        assert_eq!(cfg.rehydrate_reach, 5, "reach clamped to max_files");
480        crate::test_env::remove_var("LEAN_CTX_ARCHIVE_MAX_FILES");
481        crate::test_env::remove_var("LEAN_CTX_ARCHIVE_REHYDRATE_REACH");
482    }
483
484    #[test]
485    fn store_parse_round_trips() {
486        for store in MemoryStore::all() {
487            assert_eq!(MemoryStore::parse(store.as_str()), Some(store));
488        }
489        assert_eq!(MemoryStore::parse("nope"), None);
490    }
491}