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;
8pub(crate) mod bindings;
9pub(crate) mod delivered;
10pub(crate) mod presented;
11mod recovery;
12mod register;
13
14pub(crate) use recovery::{
15 RecoveryId, RecoveryRefusal, recovery_lineage, retrieve_recovery_checked,
16 store_recovery_with_lineage,
17};
18
19use super::context_admission::stored::source_authority_required;
23
24#[cfg(test)]
25#[path = "archive/source_tests.rs"]
26mod source_tests;
27
28#[derive(Debug, Clone, Serialize, Deserialize)]
29pub struct ArchiveEntry {
30 #[serde(default, skip_serializing_if = "Option::is_none")]
31 pub authority: Option<authority::ArchiveAuthority>,
32 pub id: String,
33 pub tool: String,
34 pub command: String,
35 pub size_chars: usize,
36 pub size_tokens: usize,
37 pub created_at: DateTime<Utc>,
38 pub session_id: Option<String>,
39 #[serde(default, skip_serializing_if = "Option::is_none")]
40 pub protected_until: Option<DateTime<Utc>>,
41 #[serde(default, skip_serializing_if = "Vec::is_empty")]
42 pub aliases: Vec<String>,
43 #[serde(default, skip_serializing_if = "Option::is_none")]
47 pub(crate) lineage: Option<delivered::Lineage>,
48 #[serde(default, skip_serializing_if = "Vec::is_empty")]
55 pub projects: Vec<String>,
56 #[serde(default, skip_serializing_if = "Option::is_none")]
61 pub project_root: Option<String>,
62}
63
64pub(crate) fn current_partition() -> Option<String> {
68 super::policy::diagnostics::request_project()
69 .map(|root| super::project_hash::hash_project_root(&root.to_string_lossy()))
70}
71
72fn unbound_id(partition: &str, content: &str) -> String {
75 let mut hasher = blake3::Hasher::new();
76 hasher.update(partition.as_bytes());
77 hasher.update(&[0]);
78 hasher.update(content.as_bytes());
79 hasher.finalize().to_hex()[..16].to_string()
80}
81
82fn in_current_partition(entry: &ArchiveEntry) -> bool {
84 current_partition().is_some_and(|partition| entry.projects.contains(&partition))
85}
86
87pub(crate) fn legacy_unscoped_entries() -> Vec<ArchiveEntry> {
91 list_entries_raw(None)
92 .into_iter()
93 .filter(|entry| {
94 entry.authority.is_none()
95 && entry.lineage.is_none()
96 && entry.id.len() == 16
97 && (entry.projects.is_empty() || is_drifted(entry))
98 })
99 .collect()
100}
101
102pub(crate) fn is_drifted(entry: &ArchiveEntry) -> bool {
106 match (&entry.project_root, entry.projects.first()) {
107 (Some(root), Some(partition)) => super::project_hash::hash_project_root(root) != *partition,
108 _ => false,
109 }
110}
111
112pub(crate) fn unbound_entry(id: &str) -> Option<ArchiveEntry> {
115 read_entry(id)
116 .filter(|entry| entry.authority.is_none() && entry.lineage.is_none() && id.len() == 16)
117}
118
119pub(crate) fn adopt_legacy_entry(
124 id: &str,
125 project_root: &std::path::Path,
126) -> Result<String, String> {
127 let entry = unbound_entry(id)
128 .filter(|entry| entry.projects.is_empty() || is_drifted(entry))
129 .ok_or("not a legacy archive")?;
130 let content = super::atomic_fs::read_store_file(&archive_base_dir(), &content_path(id))
131 .map_err(|_| "archive content unavailable")?;
132 super::policy::runtime::REQUEST_PROJECT
133 .sync_scope(
134 std::cell::RefCell::new(Some(project_root.to_path_buf())),
135 || {
136 store_with_result(
137 &entry.tool,
138 &entry.command,
139 &content,
140 entry.session_id.as_deref(),
141 )
142 },
143 )
144 .map(|stored| stored.id)
145 .ok_or_else(|| "withheld by the current policy, or archiving is disabled".to_string())
146}
147
148fn archive_base_dir() -> PathBuf {
149 lean_ctx_data_dir()
150 .unwrap_or_else(|_| PathBuf::from(".lean-ctx"))
151 .join("archives")
152}
153
154fn entry_dir(id: &str) -> PathBuf {
155 let prefix = if id.len() >= 2 { &id[..2] } else { id };
156 archive_base_dir().join(prefix)
157}
158
159fn content_path(id: &str) -> PathBuf {
160 entry_dir(id).join(format!("{id}.txt"))
161}
162
163fn meta_path(id: &str) -> PathBuf {
164 entry_dir(id).join(format!("{id}.meta.json"))
165}
166
167fn lock_path() -> PathBuf {
168 archive_base_dir().join(".lock")
169}
170
171fn with_archive_lock<T>(f: impl FnOnce() -> T) -> Option<T> {
172 use fs2::FileExt;
173
174 std::fs::create_dir_all(archive_base_dir()).ok()?;
175 let lock = std::fs::OpenOptions::new()
176 .read(true)
177 .write(true)
178 .create(true)
179 .truncate(false)
180 .open(lock_path())
181 .ok()?;
182 #[cfg(unix)]
183 set_private_file_perms(&lock_path());
184 lock.lock_exclusive().ok()?;
185 let result = f();
186 let _ = FileExt::unlock(&lock);
187 Some(result)
188}
189
190#[cfg(unix)]
191fn set_private_file_perms(path: &PathBuf) {
192 use std::os::unix::fs::PermissionsExt;
193 let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
194}
195
196fn compute_id(content: &str) -> String {
197 use std::collections::hash_map::DefaultHasher;
198 use std::hash::{Hash, Hasher};
199 let mut hasher = DefaultHasher::new();
200 content.hash(&mut hasher);
201 let hash = hasher.finish();
202 format!("{hash:016x}")
203}
204
205pub fn is_enabled() -> bool {
206 if let Ok(v) = std::env::var("LEAN_CTX_ARCHIVE") {
207 return !matches!(v.as_str(), "0" | "false" | "off");
208 }
209 super::config::Config::load().archive.enabled
210}
211
212fn threshold_chars() -> usize {
213 if let Ok(v) = std::env::var("LEAN_CTX_ARCHIVE_THRESHOLD")
214 && let Ok(n) = v.parse::<usize>()
215 {
216 return n;
217 }
218 super::config::Config::load().archive.threshold_chars
219}
220
221fn max_age_hours() -> u64 {
222 if let Ok(v) = std::env::var("LEAN_CTX_ARCHIVE_TTL")
223 && let Ok(n) = v.parse::<u64>()
224 {
225 return n;
226 }
227 super::config::Config::load().archive_max_age_hours_effective()
228}
229
230fn max_disk_bytes() -> u64 {
235 super::config::Config::load()
236 .archive_max_disk_mb_effective()
237 .saturating_mul(1024 * 1024)
238}
239
240pub fn should_archive(content: &str) -> bool {
241 is_enabled() && content.len() >= threshold_chars()
242}
243
244#[cfg(not(test))]
245pub(crate) const MAX_ARCHIVE_SIZE: usize = 10 * 1024 * 1024; #[cfg(test)]
250pub(crate) const MAX_ARCHIVE_SIZE: usize = 1024 * 1024;
251const BACKGROUND_RETENTION_HOURS: i64 = 1;
252
253pub fn store(tool: &str, command: &str, content: &str, session_id: Option<&str>) -> Option<String> {
254 store_with_result(tool, command, content, session_id).map(|result| result.id)
255}
256
257#[derive(Debug, Clone, PartialEq, Eq)]
258pub struct ArchiveStoreResult {
259 pub id: String,
260 pub captured_chars: usize,
261 pub archived_chars: usize,
262 pub truncated: bool,
263}
264
265pub fn store_with_result(
266 tool: &str,
267 command: &str,
268 content: &str,
269 session_id: Option<&str>,
270) -> Option<ArchiveStoreResult> {
271 store_with_authority(tool, command, content, session_id, None)
272}
273
274pub(crate) fn store_with_authority(
275 tool: &str,
276 command: &str,
277 content: &str,
278 session_id: Option<&str>,
279 authority: Option<&authority::ArchiveAuthority>,
280) -> Option<ArchiveStoreResult> {
281 super::policy::runtime::with_source_view(|| {
282 if source_authority_required() && authority.is_none() {
283 return None;
284 }
285 if authority.is_some_and(|origin| !origin.admitted()) {
286 return None;
287 }
288 let content = super::policy::content::protect_active(content).ok()?;
289 let command = super::policy::content::protect_active(command).ok()?;
290 let content = super::context_admission::recovery::admit_for_storage(&content)?;
294 let command = super::context_admission::recovery::admit_for_storage(&command)?;
295 store_admitted(tool, &command, &content, session_id, authority)
296 })
297 .ok()
298 .flatten()
299}
300
301fn store_admitted(
302 tool: &str,
303 command: &str,
304 content: &str,
305 session_id: Option<&str>,
306 authority: Option<&authority::ArchiveAuthority>,
307) -> Option<ArchiveStoreResult> {
308 if !is_enabled() || content.is_empty() {
309 return None;
310 }
311
312 let (content, mut result) = prepared_content(content);
313 result.id = match authority {
314 Some(authority) => authority.id(content)?,
315 None => unbound_id(¤t_partition()?, content),
316 };
317 let id = result.id.clone();
318 with_archive_lock(|| {
319 let c_path = content_path(&id);
320 if c_path.exists() && meta_path(&id).exists() {
321 return Some(());
322 }
323 std::fs::create_dir_all(entry_dir(&id)).ok()?;
324 if !c_path.exists() {
325 super::atomic_fs::try_atomic_write(&c_path, content.as_bytes(), None).ok()?;
326 #[cfg(unix)]
327 set_private_file_perms(&c_path);
328 }
329 let mut entry = new_entry(&id, tool, command, content, session_id, Utc::now());
330 entry.authority = authority.cloned();
331 if write_metadata(&entry).is_none() {
332 let _ = std::fs::remove_file(c_path);
333 return None;
334 }
335 Some(())
336 })
337 .flatten()?;
338 if authority.is_none() {
339 super::archive_fts::index_entry(&id, tool, command, content);
340 }
341 if authority.is_some() {
342 super::context_admission::receipt_store::references::note_recovery(&id);
343 let pointer = recovery_pointer_path(content);
347 if let Some(directory) = pointer.parent()
348 && std::fs::create_dir_all(directory).is_ok()
349 {
350 let _ = super::atomic_fs::try_atomic_write(&pointer, id.as_bytes(), None);
351 }
352 }
353 Some(result)
354}
355
356fn recovery_pointer_path(content: &str) -> PathBuf {
357 archive_base_dir()
358 .join("by-content")
359 .join(format!("{}.id", blake3::hash(content.as_bytes()).to_hex()))
360}
361
362pub fn store_recovery_copy(
372 tool: &str,
373 label: &str,
374 content: &str,
375 authority: &authority::ArchiveAuthority,
376) -> Option<String> {
377 store_with_authority(tool, label, content, None, Some(authority)).map(|stored| stored.id)
378}
379
380#[must_use]
387pub fn bound_recovery_id(content: &str) -> Option<String> {
388 let (content, _) = prepared_content(content);
389 let pointer = recovery_pointer_path(content);
390 let id = super::atomic_fs::read_store_file(&archive_base_dir(), &pointer).ok()?;
391 let id = id.trim();
392 (id.len() == 64
393 && id
394 .bytes()
395 .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
396 && read_entry(id).is_some_and(|entry| entry.authority.is_some()))
397 .then(|| id.to_owned())
398}
399
400pub fn store_background(
403 tool: &str,
404 job_id: &str,
405 content: &str,
406 session_id: Option<&str>,
407) -> Option<ArchiveStoreResult> {
408 super::policy::runtime::with_source_view(|| {
409 store_background_with_limits(
410 tool,
411 job_id,
412 content,
413 session_id,
414 Utc::now(),
415 max_disk_bytes(),
416 )
417 })
418 .ok()
419 .flatten()
420}
421
422fn store_background_with_limits(
423 tool: &str,
424 job_id: &str,
425 content: &str,
426 session_id: Option<&str>,
427 now: DateTime<Utc>,
428 budget_bytes: u64,
429) -> Option<ArchiveStoreResult> {
430 if source_authority_required() {
433 return None;
434 }
435 if !is_enabled() || content.is_empty() {
436 return None;
437 }
438 let content = super::context_admission::recovery::admit_for_storage(content)?;
440
441 let (content, mut result) = prepared_content(&content);
442 result.id = unbound_id(¤t_partition()?, content);
443 let id = result.id.clone();
444 let protected_until = now + chrono::Duration::hours(BACKGROUND_RETENTION_HOURS);
445 let (stored, evicted) = with_archive_lock(|| {
446 let mut entry = read_entry(&id)
447 .unwrap_or_else(|| new_entry(&id, tool, job_id, content, session_id, now));
448 if !entry.aliases.iter().any(|alias| alias == job_id) {
449 entry.aliases.push(job_id.to_string());
450 }
451 entry.protected_until = Some(
452 entry
453 .protected_until
454 .map_or(protected_until, |current| current.max(protected_until)),
455 );
456
457 let metadata = serde_json::to_string_pretty(&entry).ok()?;
458 let existing_bytes = scanned_entries()
459 .into_iter()
460 .find(|candidate| candidate.id == id)
461 .map_or(0, |candidate| candidate.bytes);
462 let required_bytes = content.len() as u64 + metadata.len() as u64;
463 let evicted = admit_locked(&id, existing_bytes, required_bytes, budget_bytes, now)?;
464
465 let c_path = content_path(&id);
466 let content_existed = c_path.exists();
467 if std::fs::create_dir_all(entry_dir(&id)).is_err() {
468 return Some((false, evicted));
469 }
470 if !content_existed {
471 if super::atomic_fs::try_atomic_write(&c_path, content.as_bytes(), None).is_err() {
472 return Some((false, evicted));
473 }
474 #[cfg(unix)]
475 set_private_file_perms(&c_path);
476 }
477 if super::atomic_fs::try_atomic_write(&meta_path(&id), metadata.as_bytes(), None).is_err() {
478 if !content_existed {
479 let _ = std::fs::remove_file(c_path);
480 }
481 return Some((false, evicted));
482 }
483 #[cfg(unix)]
484 set_private_file_perms(&meta_path(&id));
485 Some((true, evicted))
486 })
487 .flatten()?;
488
489 for evicted_id in evicted {
490 super::archive_fts::remove_entry(&evicted_id);
491 }
492 super::archive_fts::remove_entry(&id);
495 stored.then_some(result)
496}
497
498fn prepared_content(content: &str) -> (&str, ArchiveStoreResult) {
499 let captured_chars = content.chars().count();
500 let truncated = content.len() > MAX_ARCHIVE_SIZE;
501 let content = if truncated {
502 &content[..content.floor_char_boundary(MAX_ARCHIVE_SIZE)]
503 } else {
504 content
505 };
506 let id = compute_id(content);
507 let result = ArchiveStoreResult {
508 id,
509 captured_chars,
510 archived_chars: content.chars().count(),
511 truncated,
512 };
513 (content, result)
514}
515
516fn new_entry(
517 id: &str,
518 tool: &str,
519 command: &str,
520 content: &str,
521 session_id: Option<&str>,
522 created_at: DateTime<Utc>,
523) -> ArchiveEntry {
524 ArchiveEntry {
525 authority: None,
526 id: id.to_string(),
527 tool: tool.to_string(),
528 command: command.to_string(),
529 size_chars: content.len(),
530 size_tokens: super::tokens::count_tokens(content),
531 created_at,
532 session_id: session_id.map(std::string::ToString::to_string),
533 protected_until: None,
534 aliases: Vec::new(),
535 lineage: None,
536 projects: current_partition().into_iter().collect(),
537 project_root: super::policy::diagnostics::request_project()
538 .map(|root| root.to_string_lossy().into_owned()),
539 }
540}
541
542pub(crate) fn tool_of(id: &str) -> Option<String> {
544 read_entry(id).map(|entry| entry.tool)
545}
546
547fn read_entry(id: &str) -> Option<ArchiveEntry> {
548 serde_json::from_str(&std::fs::read_to_string(meta_path(id)).ok()?).ok()
549}
550
551fn write_metadata(entry: &ArchiveEntry) -> Option<()> {
552 let path = meta_path(&entry.id);
553 let json = serde_json::to_string_pretty(entry).ok()?;
554 super::atomic_fs::try_atomic_write(&path, json.as_bytes(), None).ok()?;
555 #[cfg(unix)]
556 set_private_file_perms(&path);
557 Some(())
558}
559
560#[derive(Debug, Clone, Copy, PartialEq, Eq)]
561pub(crate) enum ArchiveResolveError {
562 Malformed,
563 Missing,
564 Refused(&'static str),
565}
566
567pub(crate) fn retrieve_checked(id: &str) -> Result<String, ArchiveResolveError> {
571 super::policy::runtime::with_source_view(|| {
572 retrieve_admitted_budgeted(id, &mut crate::core::limits::max_read_bytes())
573 })
574 .unwrap_or(Err(ArchiveResolveError::Refused(
575 "current policy cannot be verified",
576 )))
577}
578
579pub fn retrieve(id: &str) -> Option<String> {
580 retrieve_checked(id).ok()
581}
582
583fn retrieve_admitted(id: &str) -> Option<String> {
584 retrieve_admitted_budgeted(id, &mut crate::core::limits::max_read_bytes()).ok()
585}
586
587pub(crate) fn content_matches_id(id: &str, content: &str) -> bool {
591 match read_entry(id).and_then(|entry| entry.authority) {
592 Some(origin) => origin.id(content).as_deref() == Some(id),
593 None => match read_entry(id).and_then(|entry| entry.projects.first().cloned()) {
594 Some(partition) => unbound_id(&partition, content) == id,
595 None => compute_id(content) == id,
596 },
597 }
598}
599
600fn retrieve_admitted_budgeted(
602 id: &str,
603 source_bytes: &mut usize,
604) -> Result<String, ArchiveResolveError> {
605 if !matches!(id.len(), 16 | 64)
608 || !id
609 .bytes()
610 .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
611 {
612 return Err(ArchiveResolveError::Malformed);
613 }
614 let entry = read_entry(id);
615 let authority = entry.as_ref().and_then(|entry| entry.authority.as_ref());
616 if authority.is_none() && (id.len() == 64 || source_authority_required()) {
617 return Err(ArchiveResolveError::Refused(
618 "stored output has no source authority under the active policy",
619 ));
620 }
621 if authority.is_none() && !entry.as_ref().is_some_and(in_current_partition) {
624 if let Some(adopted) = super::legacy_adoption::adopt_provable_archive(id)
627 && adopted != id
628 {
629 return retrieve_admitted_budgeted(&adopted, source_bytes);
630 }
631 return Err(ArchiveResolveError::Missing);
632 }
633 if authority.is_some_and(|origin| !origin.admitted_budgeted(source_bytes)) {
634 return Err(ArchiveResolveError::Refused(
635 "the archive's source is no longer admitted",
636 ));
637 }
638 let content = super::atomic_fs::read_store_file(&archive_base_dir(), &content_path(id))
641 .map_err(|error| match error {
642 super::atomic_fs::StoreReadError::Escapes => {
643 ArchiveResolveError::Refused("archive entry resolves outside the archive store")
644 }
645 super::atomic_fs::StoreReadError::Io(error) => match error.kind() {
646 std::io::ErrorKind::PermissionDenied => {
647 ArchiveResolveError::Refused("archive read refused by filesystem policy")
648 }
649 std::io::ErrorKind::InvalidData => ArchiveResolveError::Malformed,
650 _ => ArchiveResolveError::Missing,
651 },
652 })?;
653 if content.len() > MAX_ARCHIVE_SIZE {
654 return Err(ArchiveResolveError::Refused(
655 "archive entry exceeds the archive size bound",
656 ));
657 }
658 if authority.is_some_and(|origin| origin.id(&content).as_deref() != Some(id)) {
659 return Err(ArchiveResolveError::Refused(
660 "archive content no longer matches its source-bound address",
661 ));
662 }
663 let released = super::policy::content::protect_active(&content)
664 .map(std::borrow::Cow::into_owned)
665 .map_err(|_| {
666 ArchiveResolveError::Refused("stored output is withheld by current content rules")
667 })?;
668 if let Some(origin) = authority {
671 delivered::record_verified(&delivered::digest(&released), origin);
672 }
673 Ok(released)
674}
675
676pub(crate) fn format_range(content: &str, start: usize, end: usize) -> String {
679 let lines: Vec<&str> = content.lines().collect();
680 let start = start.saturating_sub(1).min(lines.len());
681 let end = end.min(lines.len());
682 if start >= end {
683 return String::new();
684 }
685 lines[start..end]
686 .iter()
687 .enumerate()
688 .map(|(i, line)| format!("{:>6}|{line}", start + i + 1))
689 .collect::<Vec<_>>()
690 .join("\n")
691}
692
693pub(crate) fn format_search(content: &str, pattern: &str, label: &str) -> String {
697 let pattern_lower = pattern.to_lowercase();
698 let matches: Vec<String> = content
699 .lines()
700 .enumerate()
701 .filter(|(_, line)| line.to_lowercase().contains(&pattern_lower))
702 .map(|(i, line)| format!("{:>6}|{line}", i + 1))
703 .collect();
704 if matches.is_empty() {
705 format!("No matches for \"{pattern}\" in {label}")
706 } else {
707 format!(
708 "{} match(es) for \"{}\":\n{}",
709 matches.len(),
710 pattern,
711 matches.join("\n")
712 )
713 }
714}
715
716pub(crate) fn format_json_keys(content: &str, path: Option<&str>, label: &str) -> Option<String> {
720 let root: serde_json::Value = serde_json::from_str(content.trim()).ok()?;
721 let mut cur = &root;
722 let mut walked = String::from("$");
723 if let Some(p) = path {
724 for seg in p.split(['.', '/']).filter(|s| !s.is_empty()) {
725 let next = if let Ok(idx) = seg.parse::<usize>() {
726 cur.get(idx)
727 } else {
728 cur.get(seg)
729 };
730 match next {
731 Some(v) => {
732 cur = v;
733 walked.push('.');
734 walked.push_str(seg);
735 }
736 None => {
737 return Some(format!("Path '{p}' not found at '{walked}' in {label}"));
738 }
739 }
740 }
741 }
742 Some(format!("{walked} => {}", describe_json(cur)))
743}
744
745pub fn retrieve_with_range(id: &str, start: usize, end: usize) -> Option<String> {
746 let content = retrieve(id)?;
747 Some(format_range(&content, start, end))
748}
749
750pub fn retrieve_with_search(id: &str, pattern: &str) -> Option<String> {
751 let content = retrieve(id)?;
752 Some(format_search(&content, pattern, &format!("archive {id}")))
753}
754
755pub fn retrieve_head(id: &str, n: usize) -> Option<String> {
757 retrieve_with_range(id, 1, n)
758}
759
760pub fn retrieve_tail(id: &str, n: usize) -> Option<String> {
762 let content = retrieve(id)?;
763 let total = content.lines().count();
764 let start = if total > n { total - n + 1 } else { 1 };
765 retrieve_with_range(id, start, total)
766}
767
768pub fn retrieve_json_keys(id: &str, path: Option<&str>) -> Option<String> {
770 let content = retrieve(id)?;
771 format_json_keys(&content, path, &format!("archive {id}"))
772}
773
774pub(crate) fn json_type_hint(v: &serde_json::Value) -> String {
775 use serde_json::Value;
776 match v {
777 Value::Object(m) => format!("object({})", m.len()),
778 Value::Array(a) => format!("array({})", a.len()),
779 Value::String(s) => {
780 let preview: String = s.chars().take(40).collect();
781 if s.chars().count() > 40 {
782 format!("string \"{preview}…\"")
783 } else {
784 format!("string \"{preview}\"")
785 }
786 }
787 Value::Number(n) => format!("number {n}"),
788 Value::Bool(b) => format!("bool {b}"),
789 Value::Null => "null".to_string(),
790 }
791}
792
793pub(crate) fn describe_json(v: &serde_json::Value) -> String {
794 use serde_json::Value;
795 match v {
796 Value::Object(map) => {
797 let mut keys: Vec<&String> = map.keys().collect();
798 keys.sort();
799 let rendered: Vec<String> = keys
800 .iter()
801 .map(|k| format!(" {k}: {}", json_type_hint(&map[*k])))
802 .collect();
803 format!("object ({} keys)\n{}", map.len(), rendered.join("\n"))
804 }
805 Value::Array(arr) => {
806 let elem = arr.first().map_or("empty", |e| match e {
807 Value::Object(_) => "object",
808 Value::Array(_) => "array",
809 Value::String(_) => "string",
810 Value::Number(_) => "number",
811 Value::Bool(_) => "bool",
812 Value::Null => "null",
813 });
814 let mut out = format!("array ({} items of {elem})", arr.len());
815 if let Some(Value::Object(map)) = arr.first() {
816 let mut keys: Vec<&String> = map.keys().collect();
817 keys.sort();
818 out.push_str(&format!(
819 "\n [0] keys: {}",
820 keys.iter()
821 .map(|s| s.as_str())
822 .collect::<Vec<_>>()
823 .join(", ")
824 ));
825 }
826 out
827 }
828 Value::String(s) => format!("string ({} chars)", s.len()),
829 Value::Number(n) => format!("number ({n})"),
830 Value::Bool(b) => format!("bool ({b})"),
831 Value::Null => "null".to_string(),
832 }
833}
834
835pub fn list_entries(session_id: Option<&str>) -> Vec<ArchiveEntry> {
836 super::legacy_adoption::auto_adopt_archives();
837 super::policy::runtime::with_source_view(|| {
838 let mut entries: Vec<_> = admitted_entries(session_id)
839 .into_iter()
840 .map(|(entry, _)| entry)
841 .collect();
842 if !source_authority_required() {
843 entries.extend(list_entries_raw(session_id).into_iter().filter(|entry| {
844 entry.authority.is_none() && entry.id.len() != 64 && in_current_partition(entry)
845 }));
846 entries.sort_by_key(|entry| std::cmp::Reverse(entry.created_at));
847 }
848 entries
849 })
850 .unwrap_or_default()
851}
852
853pub(crate) fn admitted_entries(session_id: Option<&str>) -> Vec<(ArchiveEntry, String)> {
856 super::policy::runtime::with_source_view(|| {
857 let mut remaining = super::policy::content::MAX_PROTECTED_CONTENT_BYTES;
860 let mut source_bytes = super::policy::content::MAX_PROTECTED_CONTENT_BYTES;
861 list_entries_raw(session_id)
862 .into_iter()
863 .filter(|entry| match &entry.authority {
864 Some(origin) => origin.matches_project(),
865 None => false,
866 })
867 .take(128)
868 .filter_map(|mut entry| {
869 if remaining == 0 {
870 return None;
871 }
872 let content = retrieve_admitted_budgeted(&entry.id, &mut source_bytes).ok()?;
873 if content.len() > remaining {
874 return None;
875 }
876 remaining -= content.len();
877 entry.command = super::policy::content::protect_active(&entry.command)
878 .ok()?
879 .into_owned();
880 entry.tool = super::policy::content::protect_active(&entry.tool)
881 .ok()?
882 .into_owned();
883 Some((entry, content))
884 })
885 .collect()
886 })
887 .unwrap_or_default()
888}
889
890fn list_entries_raw(session_id: Option<&str>) -> Vec<ArchiveEntry> {
891 let base = archive_base_dir();
892 if !base.exists() {
893 return Vec::new();
894 }
895 let mut entries = Vec::new();
896 if let Ok(dirs) = std::fs::read_dir(&base) {
897 for dir_entry in dirs.flatten() {
898 if !dir_entry.path().is_dir() {
899 continue;
900 }
901 if let Ok(files) = std::fs::read_dir(dir_entry.path()) {
902 for file in files.flatten() {
903 let path = file.path();
904 if path.extension().and_then(|e| e.to_str()) != Some("json") {
905 continue;
906 }
907 if let Ok(data) = std::fs::read_to_string(&path)
908 && let Ok(entry) = serde_json::from_str::<ArchiveEntry>(&data)
909 {
910 if let Some(sid) = session_id
911 && entry.session_id.as_deref() != Some(sid)
912 {
913 continue;
914 }
915 entries.push(entry);
916 }
917 }
918 }
919 }
920 }
921 entries.sort_by_key(|e| std::cmp::Reverse(e.created_at));
922 entries
923}
924
925pub fn resolve_alias(alias: &str) -> Option<String> {
926 super::policy::runtime::with_source_view(|| {
927 let entry = list_entries_raw(None)
928 .into_iter()
929 .find(|entry| entry.aliases.iter().any(|candidate| candidate == alias))?;
930 retrieve_admitted(&entry.id)?;
931 Some(entry.id)
932 })
933 .ok()
934 .flatten()
935}
936
937pub(crate) fn is_protected(id: &str) -> bool {
938 read_entry(id)
939 .and_then(|entry| entry.protected_until)
940 .is_some_and(|until| until > Utc::now())
941}
942
943pub fn remove_files(id: &str) {
947 let _ = with_archive_lock(|| {
948 if !is_protected(id) {
949 remove_files_locked(id);
950 }
951 });
952}
953
954fn remove_files_locked(id: &str) {
955 let _ = std::fs::remove_file(content_path(id));
956 let _ = std::fs::remove_file(meta_path(id));
957}
958
959struct ScannedArchive {
960 id: String,
961 created_at: DateTime<Utc>,
962 protected_until: Option<DateTime<Utc>>,
963 bytes: u64,
964}
965
966fn scanned_entries() -> Vec<ScannedArchive> {
967 list_entries_raw(None)
968 .into_iter()
969 .map(|entry| {
970 let content_bytes = std::fs::metadata(content_path(&entry.id)).map_or(0, |m| m.len());
971 let metadata_bytes = std::fs::metadata(meta_path(&entry.id)).map_or(0, |m| m.len());
972 ScannedArchive {
973 id: entry.id,
974 created_at: entry.created_at,
975 protected_until: entry.protected_until,
976 bytes: content_bytes + metadata_bytes,
977 }
978 })
979 .collect()
980}
981
982fn protected_at(entry: &ScannedArchive, now: DateTime<Utc>) -> bool {
983 entry.protected_until.is_some_and(|until| until > now)
984}
985
986fn admit_locked(
987 new_id: &str,
988 existing_bytes: u64,
989 required_bytes: u64,
990 budget_bytes: u64,
991 now: DateTime<Utc>,
992) -> Option<Vec<String>> {
993 if budget_bytes == 0 {
994 return Some(Vec::new());
995 }
996
997 let mut entries = scanned_entries();
998 let live_bytes: u64 = entries.iter().map(|entry| entry.bytes).sum();
999 let mut projected = live_bytes
1000 .saturating_sub(existing_bytes)
1001 .saturating_add(required_bytes);
1002 if projected <= budget_bytes {
1003 return Some(Vec::new());
1004 }
1005
1006 entries.sort_by_key(|entry| entry.created_at);
1007 let candidates: Vec<_> = entries
1008 .into_iter()
1009 .filter(|entry| entry.id != new_id && !protected_at(entry, now))
1010 .collect();
1011 let reclaimable: u64 = candidates.iter().map(|entry| entry.bytes).sum();
1012 if projected.saturating_sub(reclaimable) > budget_bytes {
1013 return None;
1014 }
1015
1016 let mut evicted = Vec::new();
1017 for entry in candidates {
1018 remove_files_locked(&entry.id);
1019 projected = projected.saturating_sub(entry.bytes);
1020 evicted.push(entry.id);
1021 if projected <= budget_bytes {
1022 break;
1023 }
1024 }
1025 Some(evicted)
1026}
1027
1028pub fn cleanup() -> u32 {
1037 let now = Utc::now();
1038 let cutoff = now - chrono::Duration::hours(max_age_hours() as i64);
1039 cleanup_with(cutoff, max_disk_bytes(), now)
1040}
1041
1042fn cleanup_with(cutoff: DateTime<Utc>, budget_bytes: u64, now: DateTime<Utc>) -> u32 {
1046 let base = archive_base_dir();
1047 if !base.exists() {
1048 return 0;
1049 }
1050
1051 let removed = with_archive_lock(|| {
1052 let mut entries = scanned_entries();
1053 entries.sort_by_key(|entry| entry.created_at);
1054 let mut live_bytes: u64 = entries.iter().map(|entry| entry.bytes).sum();
1055 let mut removed = std::collections::HashSet::new();
1056
1057 for entry in &entries {
1058 if entry.created_at < cutoff && !protected_at(entry, now) {
1059 remove_files_locked(&entry.id);
1060 live_bytes = live_bytes.saturating_sub(entry.bytes);
1061 removed.insert(entry.id.clone());
1062 }
1063 }
1064
1065 if budget_bytes > 0 {
1066 for entry in &entries {
1067 if live_bytes <= budget_bytes {
1068 break;
1069 }
1070 if !removed.contains(&entry.id) && !protected_at(entry, now) {
1071 remove_files_locked(&entry.id);
1072 live_bytes = live_bytes.saturating_sub(entry.bytes);
1073 removed.insert(entry.id.clone());
1074 }
1075 }
1076 }
1077 removed
1078 })
1079 .unwrap_or_default();
1080 for id in &removed {
1081 super::archive_fts::remove_entry(id);
1082 }
1083 removed.len() as u32
1084}
1085
1086pub fn disk_usage_bytes() -> u64 {
1087 let base = archive_base_dir();
1088 if !base.exists() {
1089 return 0;
1090 }
1091 let mut total = 0u64;
1092 if let Ok(dirs) = std::fs::read_dir(&base) {
1093 for dir_entry in dirs.flatten() {
1094 if let Ok(files) = std::fs::read_dir(dir_entry.path()) {
1095 for file in files.flatten() {
1096 total += file.metadata().map_or(0, |m| m.len());
1097 }
1098 }
1099 }
1100 }
1101 total
1102}
1103
1104pub fn content_path_str(id: &str) -> String {
1108 content_path(id).to_string_lossy().into_owned()
1109}
1110
1111pub fn format_hint(id: &str, size_chars: usize, size_tokens: usize) -> String {
1112 let clause = crate::core::recovery::handle_clause(id, Some(&content_path_str(id)));
1116 format!("[Archived: {size_chars} chars ({size_tokens} tok). {clause}]")
1117}
1118
1119#[cfg(test)]
1120mod tests {
1121 use super::*;
1122
1123 #[test]
1124 fn compute_id_deterministic() {
1125 let id1 = compute_id("test content");
1126 let id2 = compute_id("test content");
1127 assert_eq!(id1, id2);
1128 let id3 = compute_id("different content");
1129 assert_ne!(id1, id3);
1130 }
1131
1132 #[test]
1133 fn nonexistent_id_returns_none() {
1134 assert!(retrieve("nonexistent_archive_id_xyz").is_none());
1135 }
1136
1137 #[test]
1138 fn format_hint_readable() {
1139 let hint = format_hint("abc123", 5000, 1200);
1140 assert!(hint.contains("5000 chars"));
1141 assert!(hint.contains("1200 tok"));
1142 assert!(hint.contains("ctx_expand"));
1143 assert!(hint.contains("abc123"));
1144 }
1145
1146 fn write_test_entry(id: &str, created_at: DateTime<Utc>, content_bytes: usize) {
1147 std::fs::create_dir_all(entry_dir(id)).unwrap();
1148 std::fs::write(content_path(id), "x".repeat(content_bytes)).unwrap();
1149 let entry = ArchiveEntry {
1150 authority: None,
1151 id: id.to_string(),
1152 tool: "ctx_shell".to_string(),
1153 command: "test".to_string(),
1154 size_chars: content_bytes,
1155 size_tokens: content_bytes / 4,
1156 created_at,
1157 session_id: None,
1158 protected_until: None,
1159 aliases: Vec::new(),
1160 lineage: None,
1161 projects: current_partition().into_iter().collect(),
1162 project_root: None,
1163 };
1164 std::fs::write(meta_path(id), serde_json::to_string(&entry).unwrap()).unwrap();
1165 }
1166
1167 #[test]
1168 fn cleanup_removes_expired_keeps_fresh() {
1169 let _lock = crate::core::data_dir::test_env_lock();
1170 let tmp = tempfile::tempdir().unwrap();
1171 crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
1172
1173 let now = Utc::now();
1174 write_test_entry("aa_old", now - chrono::Duration::hours(100), 100);
1175 write_test_entry("bb_new", now - chrono::Duration::hours(1), 100);
1176
1177 let removed = cleanup_with(now - chrono::Duration::hours(48), u64::MAX, now);
1179 assert_eq!(removed, 1);
1180 assert!(!content_path("aa_old").exists());
1181 assert!(!meta_path("aa_old").exists());
1182 assert!(content_path("bb_new").exists());
1183
1184 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1185 }
1186
1187 #[test]
1188 fn cleanup_enforces_disk_budget_oldest_first() {
1189 let _lock = crate::core::data_dir::test_env_lock();
1190 let tmp = tempfile::tempdir().unwrap();
1191 crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
1192
1193 let now = Utc::now();
1194 write_test_entry("c1_oldest", now - chrono::Duration::minutes(30), 10_000);
1195 write_test_entry("c2_middle", now - chrono::Duration::minutes(20), 10_000);
1196 write_test_entry("c3_newest", now - chrono::Duration::minutes(10), 10_000);
1197
1198 let removed = cleanup_with(now - chrono::Duration::days(365), 25_000, now);
1201 assert_eq!(removed, 1, "only the oldest over-budget entry is evicted");
1202 assert!(!content_path("c1_oldest").exists());
1203 assert!(content_path("c2_middle").exists());
1204 assert!(content_path("c3_newest").exists());
1205
1206 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1207 }
1208
1209 #[test]
1210 fn legacy_metadata_defaults_background_retention_fields() {
1211 let entry: ArchiveEntry = serde_json::from_value(serde_json::json!({
1212 "id": "legacy",
1213 "tool": "ctx_shell",
1214 "command": "printf legacy",
1215 "size_chars": 6,
1216 "size_tokens": 2,
1217 "created_at": "2026-01-01T00:00:00Z",
1218 "session_id": null
1219 }))
1220 .unwrap();
1221
1222 assert!(entry.protected_until.is_none());
1223 assert!(entry.aliases.is_empty(), "{:?}", entry.aliases);
1224 }
1225
1226 #[test]
1227 fn protected_archive_survives_cleanup_and_direct_fts_removal_path() {
1228 let _lock = crate::core::data_dir::test_env_lock();
1229 let tmp = tempfile::tempdir().unwrap();
1230 crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
1231
1232 let now = Utc::now();
1233 write_test_entry("protected", now - chrono::Duration::hours(100), 100);
1234 let mut entry = read_entry("protected").unwrap();
1235 entry.protected_until = Some(now + chrono::Duration::hours(1));
1236 write_metadata(&entry).unwrap();
1237
1238 assert_eq!(cleanup_with(now - chrono::Duration::hours(48), 1, now), 0);
1239 remove_files("protected");
1240 assert!(content_path("protected").exists());
1241
1242 let later = now + chrono::Duration::hours(2);
1243 assert_eq!(cleanup_with(now, 1, later), 1);
1244 assert!(!content_path("protected").exists());
1245
1246 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1247 }
1248
1249 fn in_project<T>(project: &std::path::Path, f: impl FnOnce() -> T) -> T {
1251 crate::core::policy::runtime::REQUEST_PROJECT
1252 .sync_scope(std::cell::RefCell::new(Some(project.to_path_buf())), f)
1253 }
1254
1255 #[test]
1256 fn background_store_refuses_when_protected_entries_fill_budget() {
1257 let _lock = crate::core::data_dir::test_env_lock();
1258 let tmp = tempfile::tempdir().unwrap();
1259 crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
1260 crate::test_env::set_var("LEAN_CTX_ARCHIVE", "1");
1261 let project = tmp.path().join("project");
1262 std::fs::create_dir_all(&project).unwrap();
1263 in_project(&project, || {
1264 let now = Utc::now();
1265 let first = store_background_with_limits(
1266 "ctx_shell",
1267 "shell_first",
1268 "first protected output",
1269 None,
1270 now,
1271 u64::MAX,
1272 )
1273 .unwrap();
1274 let budget = scanned_entries()
1275 .into_iter()
1276 .find(|entry| entry.id == first.id)
1277 .unwrap()
1278 .bytes;
1279
1280 assert!(
1281 store_background_with_limits(
1282 "ctx_shell",
1283 "shell_second",
1284 "different protected output",
1285 None,
1286 now,
1287 budget,
1288 )
1289 .is_none()
1290 );
1291 assert_eq!(resolve_alias("shell_first"), Some(first.id));
1292 assert!(resolve_alias("shell_second").is_none());
1293 });
1294
1295 crate::test_env::remove_var("LEAN_CTX_ARCHIVE");
1296 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1297 }
1298
1299 #[test]
1300 fn concurrent_background_writers_merge_content_aliases() {
1301 let _lock = crate::core::data_dir::test_env_lock();
1302 let tmp = tempfile::tempdir().unwrap();
1303 crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
1304 crate::test_env::set_var("LEAN_CTX_ARCHIVE", "1");
1305
1306 let project = tmp.path().join("project");
1307 std::fs::create_dir_all(&project).unwrap();
1308 let barrier = std::sync::Arc::new(std::sync::Barrier::new(3));
1309 let mut writers = Vec::new();
1310 for job_id in ["shell_alpha", "shell_beta"] {
1311 let barrier = barrier.clone();
1312 let project = project.clone();
1313 writers.push(std::thread::spawn(move || {
1314 barrier.wait();
1315 in_project(&project, || {
1316 store_background_with_limits(
1317 "ctx_shell",
1318 job_id,
1319 "shared terminal output",
1320 None,
1321 Utc::now(),
1322 0,
1323 )
1324 })
1325 .unwrap()
1326 }));
1327 }
1328 barrier.wait();
1329 let first = writers.remove(0).join().unwrap();
1330 let second = writers.remove(0).join().unwrap();
1331
1332 assert_eq!(first.id, second.id);
1333 in_project(&project, || {
1334 assert_eq!(resolve_alias("shell_alpha"), Some(first.id.clone()));
1335 assert_eq!(resolve_alias("shell_beta"), Some(first.id));
1336 });
1337
1338 crate::test_env::remove_var("LEAN_CTX_ARCHIVE");
1339 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1340 }
1341}