1use chrono::{DateTime, Utc};
25use serde::{Deserialize, Serialize, de::DeserializeOwned};
26use std::path::{Path, PathBuf};
27
28const DEFAULT_MAX_ARCHIVE_FILES: usize = 16;
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum MemoryStore {
38 Facts,
39 History,
40 Procedures,
41 Patterns,
42}
43
44impl MemoryStore {
45 pub fn as_str(self) -> &'static str {
46 match self {
47 MemoryStore::Facts => "facts",
48 MemoryStore::History => "history",
49 MemoryStore::Procedures => "procedures",
50 MemoryStore::Patterns => "patterns",
51 }
52 }
53
54 pub fn parse(s: &str) -> Option<Self> {
55 match s.trim().to_lowercase().as_str() {
56 "facts" | "fact" => Some(MemoryStore::Facts),
57 "history" | "insights" => Some(MemoryStore::History),
58 "procedures" | "procedure" | "procs" => Some(MemoryStore::Procedures),
59 "patterns" | "pattern" => Some(MemoryStore::Patterns),
60 _ => None,
61 }
62 }
63
64 pub fn all() -> [MemoryStore; 4] {
66 [
67 MemoryStore::Facts,
68 MemoryStore::History,
69 MemoryStore::Procedures,
70 MemoryStore::Patterns,
71 ]
72 }
73
74 fn subdir(self) -> Option<&'static str> {
76 match self {
77 MemoryStore::Facts => None,
78 other => Some(other.as_str()),
79 }
80 }
81}
82
83#[derive(Debug, Clone, Copy)]
88pub struct ArchiveConfig {
89 pub max_files: usize,
90 pub rehydrate_reach: usize,
91}
92
93impl Default for ArchiveConfig {
94 fn default() -> Self {
95 Self {
96 max_files: DEFAULT_MAX_ARCHIVE_FILES,
97 rehydrate_reach: DEFAULT_MAX_ARCHIVE_FILES,
98 }
99 }
100}
101
102impl ArchiveConfig {
103 pub fn from_env() -> Self {
106 let mut cfg = Self::default();
107 if let Ok(v) = std::env::var("LEAN_CTX_ARCHIVE_MAX_FILES")
108 && let Ok(n) = v.parse::<usize>()
109 && n > 0
110 {
111 cfg.max_files = n;
112 cfg.rehydrate_reach = n;
113 }
114 if let Ok(v) = std::env::var("LEAN_CTX_ARCHIVE_REHYDRATE_REACH")
115 && let Ok(n) = v.parse::<usize>()
116 && n > 0
117 {
118 cfg.rehydrate_reach = n;
119 }
120 cfg.rehydrate_reach = cfg.rehydrate_reach.min(cfg.max_files);
121 cfg
122 }
123}
124
125#[derive(Debug, Deserialize)]
129pub struct ArchiveEnvelope<T> {
130 pub archived_at: DateTime<Utc>,
131 #[serde(default)]
132 pub store: String,
133 #[serde(default)]
134 pub scope: Option<String>,
135 #[serde(default)]
139 pub project_root: Option<String>,
140 #[serde(rename = "items", alias = "facts")]
141 pub items: Vec<T>,
142}
143
144#[derive(Serialize)]
147struct ArchiveEnvelopeRef<'a, T: Serialize> {
148 archived_at: DateTime<Utc>,
149 store: &'a str,
150 #[serde(skip_serializing_if = "Option::is_none")]
151 scope: Option<&'a str>,
152 #[serde(skip_serializing_if = "Option::is_none")]
153 project_root: Option<&'a str>,
154 items: &'a [T],
155}
156
157fn archive_project() -> Option<PathBuf> {
162 match crate::core::policy::runtime::REQUEST_PROJECT.try_with(|slot| slot.borrow().clone()) {
163 Ok(project) => project,
164 Err(_) => std::env::current_dir().ok(),
165 }
166}
167
168fn effective_scope(store: MemoryStore, scope: Option<&str>) -> Result<Option<String>, String> {
172 let root = archive_project().ok_or("archive project unavailable")?;
173 let root = root.to_string_lossy();
174 let expected = crate::core::project_hash::hash_project_root(&root);
175 if crate::core::knowledge::protection::current(&root)?.is_some() {
176 if scope.is_some_and(|given| given != expected) {
177 return Err("archive scope does not match protected project".into());
178 }
179 Ok(Some(expected))
180 } else if store == MemoryStore::Facts {
181 if scope.is_some_and(|given| given != expected) {
182 return Err("facts archive scope does not match the request project".into());
183 }
184 Ok(Some(expected))
185 } else {
186 Ok(scope.map(str::to_owned))
187 }
188}
189
190fn archive_dir(store: MemoryStore, scope: Option<&str>) -> Result<PathBuf, String> {
191 let base = crate::core::data_dir::lean_ctx_data_dir()?
192 .join("memory")
193 .join("archive");
194 let scope = effective_scope(store, scope)?;
195 let dir = match (store.subdir(), scope.as_deref()) {
196 (None, Some(s)) => base.join("facts").join(sanitize_scope(s)),
197 (None, None) => return Err("facts archive requires a project partition".into()),
198 (Some(sub), None) => base.join(sub), (Some(sub), Some(s)) => base.join(sub).join(sanitize_scope(s)),
200 };
201 Ok(dir)
202}
203
204fn sanitize_scope(scope: &str) -> String {
207 scope
208 .chars()
209 .map(|c| {
210 if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
211 c
212 } else {
213 '_'
214 }
215 })
216 .collect()
217}
218
219pub fn archive_items<T: Serialize>(
224 store: MemoryStore,
225 scope: Option<&str>,
226 items: &[T],
227 cfg: &ArchiveConfig,
228) -> Result<Option<PathBuf>, String> {
229 archive_items_at(store, scope, items, cfg, Utc::now())
230}
231
232fn archive_items_at<T: Serialize>(
233 store: MemoryStore,
234 scope: Option<&str>,
235 items: &[T],
236 cfg: &ArchiveConfig,
237 now: DateTime<Utc>,
238) -> Result<Option<PathBuf>, String> {
239 if knowledge_store(store) && !items.is_empty() {
240 let root = archive_project().ok_or("archive project unavailable")?;
241 return crate::core::policy::runtime::with_explicit_project_source_view(
242 &root,
243 |authority| {
244 let admission = crate::core::knowledge::protection::KnowledgeAdmission::capture(
245 &root.to_string_lossy(),
246 )?;
247 archive_items_inner(
248 store,
249 scope,
250 items,
251 cfg,
252 Some((admission.gateway_snapshot(), authority)),
253 Some((&admission, authority)),
254 now,
255 )
256 },
257 )?;
258 }
259 archive_items_inner(store, scope, items, cfg, None, None, now)
260}
261
262pub(crate) fn archive_items_with_authority<T: Serialize>(
263 store: MemoryStore,
264 scope: Option<&str>,
265 items: &[T],
266 cfg: &ArchiveConfig,
267 admission: &crate::core::context_admission::stores::StoreAdmission,
268 authority: &crate::core::policy::runtime::PublicationAuthority,
269) -> Result<Option<PathBuf>, String> {
270 let knowledge = if knowledge_store(store) && !items.is_empty() {
271 let root = archive_project().ok_or("archive project unavailable")?;
272 let snapshot = crate::core::knowledge::protection::KnowledgeAdmission::capture(
273 &root.to_string_lossy(),
274 )?;
275 if snapshot.gateway_snapshot().digest() != admission.digest() {
276 return Err("archive admission changed; retry".into());
277 }
278 Some(snapshot)
279 } else {
280 None
281 };
282 archive_items_inner(
283 store,
284 scope,
285 items,
286 cfg,
287 Some((admission, authority)),
288 knowledge.as_ref().map(|snapshot| (snapshot, authority)),
289 Utc::now(),
290 )
291}
292
293fn knowledge_store(store: MemoryStore) -> bool {
294 matches!(
295 store,
296 MemoryStore::Facts | MemoryStore::History | MemoryStore::Patterns
297 )
298}
299
300fn admits_knowledge_archive_item(
301 store: MemoryStore,
302 admission: &crate::core::knowledge::protection::KnowledgeAdmission,
303 value: &serde_json::Value,
304) -> bool {
305 match store {
306 MemoryStore::Facts => admission.admits_archive_fact_value(value),
307 MemoryStore::History => admission.admits_archive_history_value(value),
308 MemoryStore::Patterns => admission.admits_archive_pattern_value(value),
309 MemoryStore::Procedures => admission.admits_archive_value(value),
310 }
311}
312
313fn admits_typed_knowledge_archive_item(
314 store: MemoryStore,
315 admission: &crate::core::knowledge::protection::KnowledgeAdmission,
316 value: &serde_json::Value,
317) -> bool {
318 match store {
319 MemoryStore::Facts => admission.admits_typed_archive_fact_value(value),
320 MemoryStore::History => admission.admits_typed_archive_history_value(value),
321 MemoryStore::Patterns => admission.admits_typed_archive_pattern_value(value),
322 MemoryStore::Procedures => false,
323 }
324}
325
326fn archive_store(value: &serde_json::Value) -> Option<MemoryStore> {
327 match value.get("store") {
328 Some(serde_json::Value::String(store)) => MemoryStore::parse(store),
329 None if value.get("facts").is_some() => Some(MemoryStore::Facts),
330 Some(_) | None => None,
331 }
332}
333
334fn archive_items_field(value: &serde_json::Value, store: MemoryStore) -> Option<&'static str> {
335 if value.get("items").is_some() {
336 Some("items")
337 } else if store == MemoryStore::Facts && value.get("facts").is_some() {
338 Some("facts")
339 } else {
340 None
341 }
342}
343
344fn archive_items_inner<T: Serialize>(
345 store: MemoryStore,
346 scope: Option<&str>,
347 items: &[T],
348 cfg: &ArchiveConfig,
349 authorization: Option<(
350 &crate::core::context_admission::stores::StoreAdmission,
351 &crate::core::policy::runtime::PublicationAuthority,
352 )>,
353 knowledge_authorization: Option<(
354 &crate::core::knowledge::protection::KnowledgeAdmission,
355 &crate::core::policy::runtime::PublicationAuthority,
356 )>,
357 now: DateTime<Utc>,
358) -> Result<Option<PathBuf>, String> {
359 if items.is_empty() {
360 return Ok(None);
361 }
362 if knowledge_store(store) && knowledge_authorization.is_none() {
363 return Err("knowledge archive requires an admitted publication scope".into());
364 }
365 let scope = effective_scope(store, scope)?;
366 let scope = scope.as_deref();
367 let dir = archive_dir(store, scope)?;
368 std::fs::create_dir_all(&dir).map_err(|e| format!("{e}"))?;
369 if !ordered_archive_files(&dir).1 {
370 return Err("archive chronology unavailable".into());
371 }
372
373 let suffix = now.timestamp_subsec_nanos();
376 let filename = format!("archive-{}-{suffix:09}.json", now.format("%Y%m%d-%H%M%S"));
377 let path = dir.join(filename);
378
379 let project_root =
380 crate::core::policy::diagnostics::project().map(|root| root.to_string_lossy().into_owned());
381 let envelope = ArchiveEnvelopeRef {
382 archived_at: now,
383 store: store.as_str(),
384 scope,
385 project_root: project_root.as_deref(),
386 items,
387 };
388 let original = serde_json::to_value(&envelope).map_err(|_| "archive cannot be inspected")?;
389 if let Some((admission, _)) = knowledge_authorization {
390 let records = original["items"]
391 .as_array()
392 .ok_or("archive items are not inspectable")?;
393 if !records
394 .iter()
395 .all(|record| admits_knowledge_archive_item(store, admission, record))
396 {
397 return Err("knowledge archive withheld by current policy".into());
398 }
399 }
400 let typed_items = knowledge_authorization.map(|(admission, _)| (store, admission));
401 let safe = inspect_archive(&original, typed_items)?;
402 let json = serde_json::to_string_pretty(&safe).map_err(|_| "archive serialization failed")?;
403 if inspect_archive(&safe, typed_items)? != safe {
404 return Err("archive rules changed before publication".into());
405 }
406 use std::io::Write;
407 let mut file = tempfile::NamedTempFile::new_in(&dir).map_err(|_| "archive staging failed")?;
408 file.write_all(json.as_bytes())
409 .map_err(|_| "archive write failed")?;
410 if let Some((admission, authority)) = authorization {
411 admission.authorize_publication(authority)?;
412 }
413 if let Some((admission, authority)) = knowledge_authorization {
414 admission.authorize_publication(authority)?;
415 }
416 file.persist_noclobber(&path)
418 .map_err(|_| "archive publication failed")?;
419
420 let (archives, ordered) = ordered_archive_files(&dir);
421 if !ordered {
422 return Err("archive chronology changed before retention".into());
423 }
424 if archives.len() > cfg.max_files {
425 for old in &archives[..archives.len() - cfg.max_files] {
426 let _ = std::fs::remove_file(old);
427 }
428 }
429 Ok(Some(path))
430}
431
432pub(crate) fn legacy_facts_archives() -> Vec<(PathBuf, serde_json::Value)> {
436 let Ok(base) = crate::core::data_dir::lean_ctx_data_dir().map(|d| d.join("memory/archive"))
437 else {
438 return Vec::new();
439 };
440 let Ok(entries) = std::fs::read_dir(&base) else {
441 return Vec::new();
442 };
443 let mut archives: Vec<_> = entries
444 .flatten()
445 .map(|entry| entry.path())
446 .filter(|path| path.is_file() && path.extension().is_some_and(|ext| ext == "json"))
447 .filter_map(|path| {
448 let text = crate::core::policy::diagnostics::Target::read_file(&path)?;
449 let value = serde_json::from_str::<serde_json::Value>(&text).ok()?;
450 Some((path, value))
451 })
452 .collect();
453 archives.sort_by(|a, b| a.0.cmp(&b.0));
454 archives
455}
456
457pub(crate) fn orphaned_facts_archives() -> Vec<(PathBuf, serde_json::Value)> {
461 let Ok(base) =
462 crate::core::data_dir::lean_ctx_data_dir().map(|d| d.join("memory/archive/facts"))
463 else {
464 return Vec::new();
465 };
466 let Ok(partitions) = std::fs::read_dir(&base) else {
467 return Vec::new();
468 };
469 let mut current_of: std::collections::HashMap<String, String> =
470 std::collections::HashMap::new();
471 let mut archives = Vec::new();
472 for partition in partitions.flatten() {
473 let name = partition.file_name().to_string_lossy().into_owned();
474 let Ok(files) = std::fs::read_dir(partition.path()) else {
475 continue;
476 };
477 for path in files.flatten().map(|file| file.path()) {
478 if path.extension().is_none_or(|ext| ext != "json") {
479 continue;
480 }
481 let Some(value) = crate::core::policy::diagnostics::Target::read_file(&path)
482 .and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok())
483 else {
484 continue;
485 };
486 let Some(root) = value["project_root"].as_str() else {
487 continue;
488 };
489 let current = current_of
490 .entry(root.to_string())
491 .or_insert_with(|| crate::core::project_hash::hash_project_root(root));
492 if *current != name {
493 archives.push((path, value));
494 }
495 }
496 }
497 archives.sort_by(|a, b| a.0.cmp(&b.0));
498 archives
499}
500
501pub(crate) fn drifted_facts_archives(project_root: &Path) -> Vec<(PathBuf, serde_json::Value)> {
503 let canonical = |path: &Path| crate::core::pathutil::safe_canonicalize_bounded(path, 2000);
504 let wanted = canonical(project_root);
505 orphaned_facts_archives()
506 .into_iter()
507 .filter(|(_, value)| {
508 value["project_root"]
509 .as_str()
510 .is_some_and(|root| canonical(Path::new(root)) == wanted)
511 })
512 .collect()
513}
514
515pub(crate) fn adopt_legacy_facts(
522 project_root: &Path,
523 facts: &[serde_json::Value],
524) -> Result<Vec<bool>, String> {
525 let root = project_root;
526 crate::core::policy::runtime::with_explicit_project_source_view(root, |authority| {
527 let admission = crate::core::knowledge::protection::KnowledgeAdmission::capture(
528 &root.to_string_lossy(),
529 )?;
530 let admitted: Vec<bool> = facts
531 .iter()
532 .map(|fact| admits_knowledge_archive_item(MemoryStore::Facts, &admission, fact))
533 .collect();
534 let archived = archived_fact_identities()?;
535 let kept: Vec<&serde_json::Value> = facts
536 .iter()
537 .zip(&admitted)
538 .filter_map(|(fact, ok)| {
539 (*ok && !archived.contains(&fact_identity(fact))).then_some(fact)
540 })
541 .collect();
542 archive_items_inner(
543 MemoryStore::Facts,
544 None,
545 &kept,
546 &ArchiveConfig::from_env(),
547 Some((admission.gateway_snapshot(), authority)),
548 Some((&admission, authority)),
549 Utc::now(),
550 )?;
551 Ok(admitted)
552 })?
553}
554
555fn fact_identity(fact: &serde_json::Value) -> [String; 3] {
559 ["category", "key", "value"].map(|field| fact[field].as_str().unwrap_or_default().to_owned())
560}
561
562fn archived_fact_identities() -> Result<std::collections::HashSet<[String; 3]>, String> {
564 let dir = archive_dir(MemoryStore::Facts, None)?;
565 Ok(ordered_archive_files(&dir)
566 .0
567 .iter()
568 .filter_map(|path| crate::core::policy::diagnostics::Target::read_file(path))
569 .filter_map(|text| serde_json::from_str::<serde_json::Value>(&text).ok())
570 .flat_map(|envelope| match envelope.get("items") {
571 Some(serde_json::Value::Array(items)) => items.clone(),
572 _ => Vec::new(),
573 })
574 .map(|fact| fact_identity(&fact))
575 .collect())
576}
577
578pub fn list_archives(store: MemoryStore, scope: Option<&str>) -> Vec<PathBuf> {
581 let Ok(dir) = archive_dir(store, scope) else {
582 return Vec::new();
583 };
584 ordered_archive_files(&dir).0
585}
586
587fn ordered_archive_files(dir: &Path) -> (Vec<PathBuf>, bool) {
588 #[derive(Deserialize)]
589 struct ArchiveTimestamp {
590 archived_at: DateTime<Utc>,
591 }
592
593 let Ok(entries) = std::fs::read_dir(dir) else {
594 return (Vec::new(), false);
595 };
596 let mut complete = true;
597 let mut archives = Vec::new();
598 for entry in entries {
599 let Ok(entry) = entry else {
600 complete = false;
601 continue;
602 };
603 let path = entry.path();
604 if path.extension().is_none_or(|ext| ext != "json") {
605 continue;
606 }
607 let Ok(kind) = entry.file_type() else {
608 complete = false;
609 continue;
610 };
611 if !kind.is_file() {
612 continue;
613 }
614 let timestamp = crate::core::policy::diagnostics::Target::read_file(&path)
618 .and_then(|text| serde_json::from_str::<ArchiveTimestamp>(&text).ok())
619 .map(|metadata| metadata.archived_at);
620 complete &= timestamp.is_some();
621 archives.push((timestamp, path));
622 }
623 archives.sort_unstable();
626 (
627 archives.into_iter().map(|(_, path)| path).collect(),
628 complete,
629 )
630}
631
632pub fn reachable_archives(
636 store: MemoryStore,
637 scope: Option<&str>,
638 cfg: &ArchiveConfig,
639) -> Vec<PathBuf> {
640 let mut archives = list_archives(store, scope);
641 if archives.len() > cfg.rehydrate_reach {
642 archives = archives[archives.len() - cfg.rehydrate_reach..].to_vec();
643 }
644 archives
645}
646
647pub fn restore_items<T: DeserializeOwned>(path: &Path) -> Result<Vec<T>, String> {
649 restore_items_inner(path, None)
650}
651
652pub(crate) fn restore_knowledge_items<T: DeserializeOwned>(
653 path: &Path,
654 admission: &crate::core::knowledge::protection::KnowledgeAdmission,
655) -> Result<Vec<T>, String> {
656 restore_items_inner(path, Some(admission))
657}
658
659fn restore_items_inner<T: DeserializeOwned>(
660 path: &Path,
661 supplied_admission: Option<&crate::core::knowledge::protection::KnowledgeAdmission>,
662) -> Result<Vec<T>, String> {
663 let data = crate::core::policy::diagnostics::Target::read_file(path)
664 .ok_or("archive is unavailable or uninspectable")?;
665 let original: serde_json::Value = serde_json::from_str(&data).map_err(|_| "invalid archive")?;
666 let root = archive_project().ok_or("archive project unavailable")?;
667 let canonical = |p: &Path| crate::core::pathutil::safe_canonicalize_bounded(p, 2000);
668 let protected = crate::core::knowledge::protection::current(&root.to_string_lossy())?.is_some();
669 if !protected && archive_store(&original) == Some(MemoryStore::Facts) {
670 let expected = archive_dir(MemoryStore::Facts, None)?;
673 if path.parent().map(canonical) != Some(canonical(&expected)) {
674 return Err("archive belongs to a different storage scope".into());
675 }
676 } else if protected {
677 let kind = match original["store"].as_str() {
678 Some("facts") => MemoryStore::Facts,
679 Some("history") => MemoryStore::History,
680 Some("procedures") => MemoryStore::Procedures,
681 Some("patterns") => MemoryStore::Patterns,
682 _ => return Err("archive store identity unavailable".into()),
683 };
684 let scope = original["scope"]
685 .as_str()
686 .ok_or("archive has no protected scope")?;
687 let expected = archive_dir(kind, Some(scope))?;
688 if path.parent().map(canonical) != Some(canonical(&expected)) {
689 return Err("archive belongs to a different storage scope".into());
690 }
691 }
692 let store = archive_store(&original);
693 let mut candidate = original.clone();
694 let captured_admission = if store.is_some_and(knowledge_store) && supplied_admission.is_none() {
695 Some(
696 crate::core::knowledge::protection::KnowledgeAdmission::capture(
697 &root.to_string_lossy(),
698 )?,
699 )
700 } else {
701 None
702 };
703 let mut typed_items = None;
704 if let Some(store) = store.filter(|store| knowledge_store(*store)) {
705 let admission = supplied_admission
706 .or(captured_admission.as_ref())
707 .ok_or("archive admission unavailable")?;
708 let collection =
709 archive_items_field(&candidate, store).ok_or("archive items are unavailable")?;
710 let records = candidate[collection]
711 .as_array_mut()
712 .ok_or("archive items are invalid")?;
713 records.retain(|record| admits_knowledge_archive_item(store, admission, record));
714 admission.authorize_gateway()?;
715 typed_items = Some((store, admission));
716 }
717 let safe = inspect_archive(&candidate, typed_items)?;
718 if let Some((_, admission)) = typed_items {
719 admission.authorize_gateway()?;
720 }
721 let envelope: ArchiveEnvelope<T> = serde_json::from_value(safe)
722 .map_err(|_| "archive policy result is structurally invalid")?;
723 Ok(envelope.items)
724}
725
726fn inspect_archive(
727 original: &serde_json::Value,
728 typed_items: Option<(
729 MemoryStore,
730 &crate::core::knowledge::protection::KnowledgeAdmission,
731 )>,
732) -> Result<serde_json::Value, String> {
733 let root = archive_project().ok_or("archive project unavailable")?;
734 let active = crate::core::knowledge::protection::current(&root.to_string_lossy())?;
735 let mut inspection = original.clone();
736 let mut preserved_items = Vec::new();
737 if let Some((store, admission)) = typed_items {
738 if let Some(collection) = archive_items_field(&inspection, store)
739 && let Some(items) = inspection
740 .get_mut(collection)
741 .and_then(serde_json::Value::as_array_mut)
742 {
743 for (index, item) in items.iter_mut().enumerate() {
744 if admits_typed_knowledge_archive_item(store, admission, item) {
745 preserved_items.push((index, item.clone()));
746 *item = serde_json::Value::Null;
747 }
748 }
749 }
750 }
751 let mut safe = crate::core::policy::diagnostics::inspect(&inspection, active.as_deref())
752 .ok_or("archive withheld by current policy")?;
753 if let Some((store, _)) = typed_items {
754 if let Some(collection) = archive_items_field(&safe, store)
755 && let Some(items) = safe
756 .get_mut(collection)
757 .and_then(serde_json::Value::as_array_mut)
758 {
759 for (index, item) in preserved_items {
760 let slot = items
761 .get_mut(index)
762 .ok_or("archive item projection changed shape")?;
763 *slot = item;
764 }
765 }
766 }
767 for field in ["store", "scope", "archived_at"] {
768 if safe[field] != original[field] {
769 return Err("archive identity cannot be rewritten".into());
770 }
771 }
772 let before_items = original.get("items").or_else(|| original.get("facts"));
773 let after_items = safe.get("items").or_else(|| safe.get("facts"));
774 if let (Some(before), Some(after)) = (
775 before_items.and_then(serde_json::Value::as_array),
776 after_items.and_then(serde_json::Value::as_array),
777 ) {
778 for (a, b) in before.iter().zip(after) {
779 for field in [
780 "id",
781 "key",
782 "category",
783 "source_session",
784 "supersedes",
785 "from_sessions",
786 "pattern_type",
787 ] {
788 if a.get(field) != b.get(field) {
789 return Err("archived item identity cannot be rewritten".into());
790 }
791 }
792 }
793 }
794 Ok(safe)
795}
796
797#[cfg(test)]
798pub mod tests {
799 use super::*;
800
801 fn with_temp_data_dir<T>(f: impl FnOnce() -> T) -> T {
802 let _lock = crate::core::data_dir::test_env_lock();
803 let dir = std::env::temp_dir().join(format!(
804 "lctx-archive-{}-{}",
805 std::process::id(),
806 Utc::now().timestamp_nanos_opt().unwrap_or(0)
807 ));
808 let _ = std::fs::create_dir_all(&dir);
809 crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());
810 let out = f();
811 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
812 let _ = std::fs::remove_dir_all(&dir);
813 out
814 }
815
816 #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
817 struct Item {
818 id: u32,
819 label: String,
820 }
821
822 #[test]
823 fn admitted_archive_rejects_unobserved_policy_before_publication() {
824 with_temp_data_dir(|| {
825 let project = tempfile::tempdir().expect("project root");
826 let project_path = project.path().to_str().expect("UTF-8 project path");
827 crate::core::policy::runtime::with_project_source_view(project_path, || {
828 let authority = crate::core::policy::runtime::PublicationAuthority::capture()
829 .expect("active project authority");
830 let config = crate::core::config::Config::load_arc();
831 let admission = crate::core::context_admission::stores::StoreAdmission::with_policy(
832 crate::core::context_admission::AdmissionPolicy::from_config(&config),
833 );
834 let scope = Some("publication-guard-test");
835 let result = archive_items_with_authority(
836 MemoryStore::History,
837 scope,
838 &items(1),
839 &ArchiveConfig::default(),
840 &admission,
841 &authority,
842 );
843 assert!(
844 result.is_err(),
845 "explicit unobserved snapshots cannot publish"
846 );
847 assert!(list_archives(MemoryStore::History, scope).is_empty());
848 })
849 .expect("source view");
850 });
851 }
852
853 fn items(n: u32) -> Vec<Item> {
854 (0..n)
855 .map(|i| Item {
856 id: i,
857 label: format!("item-{i}"),
858 })
859 .collect()
860 }
861
862 #[test]
863 fn round_trip_each_store() {
864 with_temp_data_dir(|| {
865 let cfg = ArchiveConfig::default();
866 for store in MemoryStore::all() {
867 let scope = if store == MemoryStore::Facts {
868 None
869 } else {
870 Some("projhash")
871 };
872 let path = archive_items(store, scope, &items(3), &cfg)
873 .unwrap()
874 .expect("wrote an archive");
875 let restored: Vec<Item> = restore_items(&path).unwrap();
876 assert_eq!(restored, items(3), "round-trip for {}", store.as_str());
877 }
878 });
879 }
880
881 #[test]
884 fn a_request_without_a_project_has_no_archive() {
885 with_temp_data_dir(|| {
886 let archived = crate::core::policy::runtime::REQUEST_PROJECT.sync_scope(
887 std::cell::RefCell::new(None),
888 || {
889 archive_items(
890 MemoryStore::Facts,
891 None,
892 &items(1),
893 &ArchiveConfig::default(),
894 )
895 },
896 );
897 assert!(archived.is_err(), "{archived:?}");
898 });
899 }
900
901 #[test]
902 fn empty_archive_is_noop() {
903 with_temp_data_dir(|| {
904 let cfg = ArchiveConfig::default();
905 let res =
906 archive_items(MemoryStore::History, Some("p"), &Vec::<Item>::new(), &cfg).unwrap();
907 assert!(res.is_none());
908 {
909 let found = &list_archives(MemoryStore::History, Some("p"));
910 assert!(found.is_empty(), "{found:?}");
911 }
912 });
913 }
914
915 fn in_project<T>(root: &Path, f: impl FnOnce() -> T) -> T {
916 crate::core::policy::runtime::REQUEST_PROJECT
917 .sync_scope(std::cell::RefCell::new(Some(root.to_path_buf())), f)
918 }
919
920 #[test]
924 fn facts_archives_are_partitioned_by_request_project() {
925 with_temp_data_dir(|| {
926 let cfg = ArchiveConfig::default();
927 let a = tempfile::tempdir().expect("project a");
928 let b = tempfile::tempdir().expect("project b");
929 let archived = in_project(a.path(), || {
930 archive_items(MemoryStore::Facts, None, &items(2), &cfg)
931 .unwrap()
932 .expect("wrote an archive")
933 });
934 let base = crate::core::data_dir::lean_ctx_data_dir()
935 .unwrap()
936 .join("memory")
937 .join("archive");
938 let legacy = base.join("archive-20260101-000000-000000.json");
939 std::fs::write(
940 &legacy,
941 r#"{"archived_at":"2026-01-01T00:00:00Z","facts":[{"id":7,"label":"old"}]}"#,
942 )
943 .unwrap();
944 in_project(b.path(), || {
945 assert!(list_archives(MemoryStore::Facts, None).is_empty());
946 assert!(restore_items::<Item>(&archived).is_err());
947 assert!(restore_items::<Item>(&legacy).is_err());
948 });
949 in_project(a.path(), || {
950 assert_eq!(
951 list_archives(MemoryStore::Facts, None),
952 vec![archived.clone()]
953 );
954 assert_eq!(restore_items::<Item>(&archived).unwrap(), items(2));
955 assert!(restore_items::<Item>(&legacy).is_err());
956 });
957 });
958 }
959
960 #[test]
961 fn legacy_facts_field_alias_still_deserializes() {
962 with_temp_data_dir(|| {
963 let dir = archive_dir(MemoryStore::Facts, None).unwrap();
964 std::fs::create_dir_all(&dir).unwrap();
965 let legacy =
967 r#"{"archived_at":"2026-01-01T00:00:00Z","facts":[{"id":7,"label":"old"}]}"#;
968 let path = dir.join("archive-20260101-000000-000000.json");
969 std::fs::write(&path, legacy).unwrap();
970 let restored: Vec<Item> = restore_items(&path).unwrap();
971 assert_eq!(
972 restored,
973 vec![Item {
974 id: 7,
975 label: "old".into()
976 }]
977 );
978 });
979 }
980
981 #[test]
982 fn prune_keeps_newest_max_files() {
983 with_temp_data_dir(|| {
984 let cfg = ArchiveConfig {
985 max_files: 3,
986 rehydrate_reach: 3,
987 };
988 for (id, nanos) in [
991 1_100_000, 1_900_000, 2_100_000, 2_900_000, 3_100_000, 3_900_000,
992 ]
993 .into_iter()
994 .enumerate()
995 {
996 let batch = [Item {
997 id: u32::try_from(id).unwrap(),
998 label: format!("batch-{id}"),
999 }];
1000 archive_items_at(
1001 MemoryStore::Patterns,
1002 Some("p"),
1003 &batch,
1004 &cfg,
1005 DateTime::from_timestamp(1_700_000_000, nanos).unwrap(),
1006 )
1007 .unwrap();
1008 }
1009 let archives = list_archives(MemoryStore::Patterns, Some("p"));
1010 let retained: Vec<u32> = archives
1011 .iter()
1012 .map(|path| restore_items::<Item>(path).unwrap()[0].id)
1013 .collect();
1014 assert_eq!(retained, [3, 4, 5]);
1015 });
1016 }
1017
1018 #[test]
1019 fn retention_orders_legacy_names_by_the_recorded_timestamp() {
1020 with_temp_data_dir(|| {
1021 let store = MemoryStore::Patterns;
1022 let dir = archive_dir(store, Some("p")).unwrap();
1023 std::fs::create_dir_all(&dir).unwrap();
1024 let old_time = DateTime::from_timestamp(1_700_000_000, 1_900_000).unwrap();
1025 let legacy = dir.join(format!(
1026 "archive-{}-900000.json",
1027 old_time.format("%Y%m%d-%H%M%S")
1028 ));
1029 std::fs::write(
1030 &legacy,
1031 serde_json::to_vec(&ArchiveEnvelopeRef {
1032 archived_at: old_time,
1033 store: store.as_str(),
1034 scope: Some("p"),
1035 project_root: None,
1036 items: &items(1),
1037 })
1038 .unwrap(),
1039 )
1040 .unwrap();
1041 let cfg = ArchiveConfig {
1042 max_files: 1,
1043 rehydrate_reach: 1,
1044 };
1045 let newest = archive_items_at(
1046 store,
1047 Some("p"),
1048 &items(2),
1049 &cfg,
1050 DateTime::from_timestamp(1_700_000_000, 2_100_000).unwrap(),
1051 )
1052 .unwrap()
1053 .unwrap();
1054 assert!(!legacy.exists());
1055 assert_eq!(
1056 list_archives(store, Some("p")).as_slice(),
1057 std::slice::from_ref(&newest)
1058 );
1059 assert_eq!(restore_items::<Item>(&newest).unwrap(), items(2));
1060 });
1061 }
1062
1063 #[test]
1064 fn unreadable_archive_chronology_blocks_writes_without_pruning() {
1065 with_temp_data_dir(|| {
1066 let store = MemoryStore::Patterns;
1067 let dir = archive_dir(store, Some("p")).unwrap();
1068 std::fs::create_dir_all(&dir).unwrap();
1069 let legacy = dir.join("archive-20231114-221320-900000.json");
1070 std::fs::write(&legacy, "not json").unwrap();
1071 let cfg = ArchiveConfig {
1072 max_files: 1,
1073 rehydrate_reach: 1,
1074 };
1075 let error = archive_items(store, Some("p"), &items(1), &cfg).unwrap_err();
1076 assert_eq!(error, "archive chronology unavailable");
1077 assert_eq!(
1078 list_archives(store, Some("p")).as_slice(),
1079 std::slice::from_ref(&legacy)
1080 );
1081 assert_eq!(std::fs::read_to_string(legacy).unwrap(), "not json");
1082 });
1083 }
1084
1085 #[test]
1086 fn reachable_is_bounded_and_aligns_with_retention_by_default() {
1087 let cfg = ArchiveConfig::default();
1088 assert_eq!(cfg.rehydrate_reach, cfg.max_files);
1089 }
1090
1091 #[test]
1092 fn from_env_reach_clamped_to_max() {
1093 let _lock = crate::core::data_dir::test_env_lock();
1094 crate::test_env::set_var("LEAN_CTX_ARCHIVE_MAX_FILES", "5");
1095 crate::test_env::set_var("LEAN_CTX_ARCHIVE_REHYDRATE_REACH", "99");
1096 let cfg = ArchiveConfig::from_env();
1097 assert_eq!(cfg.max_files, 5);
1098 assert_eq!(cfg.rehydrate_reach, 5, "reach clamped to max_files");
1099 crate::test_env::remove_var("LEAN_CTX_ARCHIVE_MAX_FILES");
1100 crate::test_env::remove_var("LEAN_CTX_ARCHIVE_REHYDRATE_REACH");
1101 }
1102
1103 #[test]
1104 fn store_parse_round_trips() {
1105 for store in MemoryStore::all() {
1106 assert_eq!(MemoryStore::parse(store.as_str()), Some(store));
1107 }
1108 assert_eq!(MemoryStore::parse("nope"), None);
1109 }
1110
1111 #[test]
1112 fn unknown_explicit_store_does_not_fall_back_to_legacy_facts() {
1113 let invalid = serde_json::json!({"store":"unknown","facts":[]});
1114 assert_eq!(archive_store(&invalid), None);
1115
1116 let legacy = serde_json::json!({"facts":[]});
1117 assert_eq!(archive_store(&legacy), Some(MemoryStore::Facts));
1118 }
1119}