1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use std::path::PathBuf;
4
5use super::data_dir::lean_ctx_data_dir;
6
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct ArchiveEntry {
9 pub id: String,
10 pub tool: String,
11 pub command: String,
12 pub size_chars: usize,
13 pub size_tokens: usize,
14 pub created_at: DateTime<Utc>,
15 pub session_id: Option<String>,
16}
17
18fn archive_base_dir() -> PathBuf {
19 lean_ctx_data_dir()
20 .unwrap_or_else(|_| PathBuf::from(".lean-ctx"))
21 .join("archives")
22}
23
24fn entry_dir(id: &str) -> PathBuf {
25 let prefix = if id.len() >= 2 { &id[..2] } else { id };
26 archive_base_dir().join(prefix)
27}
28
29fn content_path(id: &str) -> PathBuf {
30 entry_dir(id).join(format!("{id}.txt"))
31}
32
33fn meta_path(id: &str) -> PathBuf {
34 entry_dir(id).join(format!("{id}.meta.json"))
35}
36
37#[cfg(unix)]
38fn set_private_file_perms(path: &PathBuf) {
39 use std::os::unix::fs::PermissionsExt;
40 let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
41}
42
43fn compute_id(content: &str) -> String {
44 use std::collections::hash_map::DefaultHasher;
45 use std::hash::{Hash, Hasher};
46 let mut hasher = DefaultHasher::new();
47 content.hash(&mut hasher);
48 let hash = hasher.finish();
49 format!("{hash:016x}")
50}
51
52pub fn is_enabled() -> bool {
53 if let Ok(v) = std::env::var("LEAN_CTX_ARCHIVE") {
54 return !matches!(v.as_str(), "0" | "false" | "off");
55 }
56 super::config::Config::load().archive.enabled
57}
58
59fn threshold_chars() -> usize {
60 if let Ok(v) = std::env::var("LEAN_CTX_ARCHIVE_THRESHOLD")
61 && let Ok(n) = v.parse::<usize>()
62 {
63 return n;
64 }
65 super::config::Config::load().archive.threshold_chars
66}
67
68fn max_age_hours() -> u64 {
69 if let Ok(v) = std::env::var("LEAN_CTX_ARCHIVE_TTL")
70 && let Ok(n) = v.parse::<u64>()
71 {
72 return n;
73 }
74 super::config::Config::load().archive_max_age_hours_effective()
75}
76
77fn max_disk_bytes() -> u64 {
82 super::config::Config::load()
83 .archive_max_disk_mb_effective()
84 .saturating_mul(1024 * 1024)
85}
86
87pub fn should_archive(content: &str) -> bool {
88 is_enabled() && content.len() >= threshold_chars()
89}
90
91const MAX_ARCHIVE_SIZE: usize = 10 * 1024 * 1024; pub fn store(tool: &str, command: &str, content: &str, session_id: Option<&str>) -> Option<String> {
94 store_with_result(tool, command, content, session_id).map(|result| result.id)
95}
96
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub struct ArchiveStoreResult {
99 pub id: String,
100 pub captured_chars: usize,
101 pub archived_chars: usize,
102 pub truncated: bool,
103}
104
105pub fn store_with_result(
106 tool: &str,
107 command: &str,
108 content: &str,
109 session_id: Option<&str>,
110) -> Option<ArchiveStoreResult> {
111 if !is_enabled() || content.is_empty() {
112 return None;
113 }
114
115 let captured_chars = content.chars().count();
116 let truncated = content.len() > MAX_ARCHIVE_SIZE;
117 let content = if content.len() > MAX_ARCHIVE_SIZE {
118 &content[..content.floor_char_boundary(MAX_ARCHIVE_SIZE)]
119 } else {
120 content
121 };
122
123 let id = compute_id(content);
124 let result = ArchiveStoreResult {
125 id: id.clone(),
126 captured_chars,
127 archived_chars: content.chars().count(),
128 truncated,
129 };
130 let c_path = content_path(&id);
131
132 if c_path.exists() {
134 return Some(result);
135 }
136
137 let dir = entry_dir(&id);
138 if std::fs::create_dir_all(&dir).is_err() {
139 return None;
140 }
141
142 let pid = std::process::id();
148 let tmp_path = c_path.with_extension(format!("tmp.{pid}"));
149 if std::fs::write(&tmp_path, content).is_err() {
150 return None;
151 }
152 if std::fs::rename(&tmp_path, &c_path).is_err() {
153 let _ = std::fs::remove_file(&tmp_path);
154 if c_path.exists() {
156 return Some(result);
157 }
158 return None;
159 }
160 #[cfg(unix)]
161 set_private_file_perms(&c_path);
162
163 let tokens = super::tokens::count_tokens(content);
164 let entry = ArchiveEntry {
165 id: id.clone(),
166 tool: tool.to_string(),
167 command: command.to_string(),
168 size_chars: content.len(),
169 size_tokens: tokens,
170 created_at: Utc::now(),
171 session_id: session_id.map(std::string::ToString::to_string),
172 };
173
174 if let Ok(json) = serde_json::to_string_pretty(&entry) {
175 let meta_tmp = meta_path(&id).with_extension(format!("tmp.{pid}"));
176 if std::fs::write(&meta_tmp, &json).is_ok() {
177 let meta_final = meta_path(&id);
178 let _ = std::fs::rename(&meta_tmp, &meta_final);
179 #[cfg(unix)]
180 set_private_file_perms(&meta_final);
181 }
182 }
183
184 super::archive_fts::index_entry(&id, tool, command, content);
185
186 Some(result)
187}
188
189pub fn retrieve(id: &str) -> Option<String> {
190 let path = content_path(id);
191 std::fs::read_to_string(path).ok()
192}
193
194pub(crate) fn format_range(content: &str, start: usize, end: usize) -> String {
197 let lines: Vec<&str> = content.lines().collect();
198 let start = start.saturating_sub(1).min(lines.len());
199 let end = end.min(lines.len());
200 if start >= end {
201 return String::new();
202 }
203 lines[start..end]
204 .iter()
205 .enumerate()
206 .map(|(i, line)| format!("{:>6}|{line}", start + i + 1))
207 .collect::<Vec<_>>()
208 .join("\n")
209}
210
211pub(crate) fn format_search(content: &str, pattern: &str, label: &str) -> String {
215 let pattern_lower = pattern.to_lowercase();
216 let matches: Vec<String> = content
217 .lines()
218 .enumerate()
219 .filter(|(_, line)| line.to_lowercase().contains(&pattern_lower))
220 .map(|(i, line)| format!("{:>6}|{line}", i + 1))
221 .collect();
222 if matches.is_empty() {
223 format!("No matches for \"{pattern}\" in {label}")
224 } else {
225 format!(
226 "{} match(es) for \"{}\":\n{}",
227 matches.len(),
228 pattern,
229 matches.join("\n")
230 )
231 }
232}
233
234pub(crate) fn format_json_keys(content: &str, path: Option<&str>, label: &str) -> Option<String> {
238 let root: serde_json::Value = serde_json::from_str(content.trim()).ok()?;
239 let mut cur = &root;
240 let mut walked = String::from("$");
241 if let Some(p) = path {
242 for seg in p.split(['.', '/']).filter(|s| !s.is_empty()) {
243 let next = if let Ok(idx) = seg.parse::<usize>() {
244 cur.get(idx)
245 } else {
246 cur.get(seg)
247 };
248 match next {
249 Some(v) => {
250 cur = v;
251 walked.push('.');
252 walked.push_str(seg);
253 }
254 None => {
255 return Some(format!("Path '{p}' not found at '{walked}' in {label}"));
256 }
257 }
258 }
259 }
260 Some(format!("{walked} => {}", describe_json(cur)))
261}
262
263pub fn retrieve_with_range(id: &str, start: usize, end: usize) -> Option<String> {
264 let content = retrieve(id)?;
265 Some(format_range(&content, start, end))
266}
267
268pub fn retrieve_with_search(id: &str, pattern: &str) -> Option<String> {
269 let content = retrieve(id)?;
270 Some(format_search(&content, pattern, &format!("archive {id}")))
271}
272
273pub fn retrieve_head(id: &str, n: usize) -> Option<String> {
275 retrieve_with_range(id, 1, n)
276}
277
278pub fn retrieve_tail(id: &str, n: usize) -> Option<String> {
280 let content = retrieve(id)?;
281 let total = content.lines().count();
282 let start = if total > n { total - n + 1 } else { 1 };
283 retrieve_with_range(id, start, total)
284}
285
286pub fn retrieve_json_keys(id: &str, path: Option<&str>) -> Option<String> {
288 let content = retrieve(id)?;
289 format_json_keys(&content, path, &format!("archive {id}"))
290}
291
292pub(crate) fn json_type_hint(v: &serde_json::Value) -> String {
293 use serde_json::Value;
294 match v {
295 Value::Object(m) => format!("object({})", m.len()),
296 Value::Array(a) => format!("array({})", a.len()),
297 Value::String(s) => {
298 let preview: String = s.chars().take(40).collect();
299 if s.chars().count() > 40 {
300 format!("string \"{preview}…\"")
301 } else {
302 format!("string \"{preview}\"")
303 }
304 }
305 Value::Number(n) => format!("number {n}"),
306 Value::Bool(b) => format!("bool {b}"),
307 Value::Null => "null".to_string(),
308 }
309}
310
311pub(crate) fn describe_json(v: &serde_json::Value) -> String {
312 use serde_json::Value;
313 match v {
314 Value::Object(map) => {
315 let mut keys: Vec<&String> = map.keys().collect();
316 keys.sort();
317 let rendered: Vec<String> = keys
318 .iter()
319 .map(|k| format!(" {k}: {}", json_type_hint(&map[*k])))
320 .collect();
321 format!("object ({} keys)\n{}", map.len(), rendered.join("\n"))
322 }
323 Value::Array(arr) => {
324 let elem = arr.first().map_or("empty", |e| match e {
325 Value::Object(_) => "object",
326 Value::Array(_) => "array",
327 Value::String(_) => "string",
328 Value::Number(_) => "number",
329 Value::Bool(_) => "bool",
330 Value::Null => "null",
331 });
332 let mut out = format!("array ({} items of {elem})", arr.len());
333 if let Some(Value::Object(map)) = arr.first() {
334 let mut keys: Vec<&String> = map.keys().collect();
335 keys.sort();
336 out.push_str(&format!(
337 "\n [0] keys: {}",
338 keys.iter()
339 .map(|s| s.as_str())
340 .collect::<Vec<_>>()
341 .join(", ")
342 ));
343 }
344 out
345 }
346 Value::String(s) => format!("string ({} chars)", s.len()),
347 Value::Number(n) => format!("number ({n})"),
348 Value::Bool(b) => format!("bool ({b})"),
349 Value::Null => "null".to_string(),
350 }
351}
352
353pub fn list_entries(session_id: Option<&str>) -> Vec<ArchiveEntry> {
354 let base = archive_base_dir();
355 if !base.exists() {
356 return Vec::new();
357 }
358 let mut entries = Vec::new();
359 if let Ok(dirs) = std::fs::read_dir(&base) {
360 for dir_entry in dirs.flatten() {
361 if !dir_entry.path().is_dir() {
362 continue;
363 }
364 if let Ok(files) = std::fs::read_dir(dir_entry.path()) {
365 for file in files.flatten() {
366 let path = file.path();
367 if path.extension().and_then(|e| e.to_str()) != Some("json") {
368 continue;
369 }
370 if let Ok(data) = std::fs::read_to_string(&path)
371 && let Ok(entry) = serde_json::from_str::<ArchiveEntry>(&data)
372 {
373 if let Some(sid) = session_id
374 && entry.session_id.as_deref() != Some(sid)
375 {
376 continue;
377 }
378 entries.push(entry);
379 }
380 }
381 }
382 }
383 }
384 entries.sort_by_key(|e| std::cmp::Reverse(e.created_at));
385 entries
386}
387
388pub fn remove_files(id: &str) {
392 let _ = std::fs::remove_file(content_path(id));
393 let _ = std::fs::remove_file(meta_path(id));
394}
395
396pub fn cleanup() -> u32 {
405 let cutoff = Utc::now() - chrono::Duration::hours(max_age_hours() as i64);
406 cleanup_with(cutoff, max_disk_bytes())
407}
408
409fn cleanup_with(cutoff: DateTime<Utc>, budget_bytes: u64) -> u32 {
413 let base = archive_base_dir();
414 if !base.exists() {
415 return 0;
416 }
417
418 struct Scanned {
419 id: String,
420 created_at: DateTime<Utc>,
421 bytes: u64,
422 }
423
424 let mut entries: Vec<Scanned> = Vec::new();
425 if let Ok(dirs) = std::fs::read_dir(&base) {
426 for dir_entry in dirs.flatten() {
427 if !dir_entry.path().is_dir() {
428 continue;
429 }
430 if let Ok(files) = std::fs::read_dir(dir_entry.path()) {
431 for file in files.flatten() {
432 let path = file.path();
433 if path.extension().and_then(|e| e.to_str()) != Some("json") {
434 continue;
435 }
436 let Ok(data) = std::fs::read_to_string(&path) else {
437 continue;
438 };
439 let Ok(entry) = serde_json::from_str::<ArchiveEntry>(&data) else {
440 continue;
441 };
442 let content_bytes =
443 std::fs::metadata(content_path(&entry.id)).map_or(0, |m| m.len());
444 let meta_bytes = file.metadata().map_or(0, |m| m.len());
445 entries.push(Scanned {
446 id: entry.id,
447 created_at: entry.created_at,
448 bytes: content_bytes + meta_bytes,
449 });
450 }
451 }
452 }
453 }
454
455 entries.sort_by_key(|e| e.created_at);
458 let mut live_bytes: u64 = entries.iter().map(|e| e.bytes).sum();
459
460 let mut removed = 0u32;
461 for e in &entries {
462 let expired = e.created_at < cutoff;
463 let over_budget = budget_bytes > 0 && live_bytes > budget_bytes;
464 if !expired && !over_budget {
465 break;
466 }
467 remove_files(&e.id);
468 super::archive_fts::remove_entry(&e.id);
469 live_bytes = live_bytes.saturating_sub(e.bytes);
470 removed += 1;
471 }
472 removed
473}
474
475pub fn disk_usage_bytes() -> u64 {
476 let base = archive_base_dir();
477 if !base.exists() {
478 return 0;
479 }
480 let mut total = 0u64;
481 if let Ok(dirs) = std::fs::read_dir(&base) {
482 for dir_entry in dirs.flatten() {
483 if let Ok(files) = std::fs::read_dir(dir_entry.path()) {
484 for file in files.flatten() {
485 total += file.metadata().map_or(0, |m| m.len());
486 }
487 }
488 }
489 }
490 total
491}
492
493pub fn content_path_str(id: &str) -> String {
497 content_path(id).to_string_lossy().into_owned()
498}
499
500pub fn format_hint(id: &str, size_chars: usize, size_tokens: usize) -> String {
501 let clause = crate::core::recovery::handle_clause(id, Some(&content_path_str(id)));
505 format!("[Archived: {size_chars} chars ({size_tokens} tok). {clause}]")
506}
507
508#[cfg(test)]
509mod tests {
510 use super::*;
511
512 #[test]
513 fn compute_id_deterministic() {
514 let id1 = compute_id("test content");
515 let id2 = compute_id("test content");
516 assert_eq!(id1, id2);
517 let id3 = compute_id("different content");
518 assert_ne!(id1, id3);
519 }
520
521 #[test]
522 fn nonexistent_id_returns_none() {
523 assert!(retrieve("nonexistent_archive_id_xyz").is_none());
524 }
525
526 #[test]
527 fn format_hint_readable() {
528 let hint = format_hint("abc123", 5000, 1200);
529 assert!(hint.contains("5000 chars"));
530 assert!(hint.contains("1200 tok"));
531 assert!(hint.contains("ctx_expand"));
532 assert!(hint.contains("abc123"));
533 }
534
535 fn write_test_entry(id: &str, created_at: DateTime<Utc>, content_bytes: usize) {
536 std::fs::create_dir_all(entry_dir(id)).unwrap();
537 std::fs::write(content_path(id), "x".repeat(content_bytes)).unwrap();
538 let entry = ArchiveEntry {
539 id: id.to_string(),
540 tool: "ctx_shell".to_string(),
541 command: "test".to_string(),
542 size_chars: content_bytes,
543 size_tokens: content_bytes / 4,
544 created_at,
545 session_id: None,
546 };
547 std::fs::write(meta_path(id), serde_json::to_string(&entry).unwrap()).unwrap();
548 }
549
550 #[test]
551 fn cleanup_removes_expired_keeps_fresh() {
552 let _lock = crate::core::data_dir::test_env_lock();
553 let tmp = tempfile::tempdir().unwrap();
554 crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
555
556 let now = Utc::now();
557 write_test_entry("aa_old", now - chrono::Duration::hours(100), 100);
558 write_test_entry("bb_new", now - chrono::Duration::hours(1), 100);
559
560 let removed = cleanup_with(now - chrono::Duration::hours(48), u64::MAX);
562 assert_eq!(removed, 1);
563 assert!(!content_path("aa_old").exists());
564 assert!(!meta_path("aa_old").exists());
565 assert!(content_path("bb_new").exists());
566
567 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
568 }
569
570 #[test]
571 fn cleanup_enforces_disk_budget_oldest_first() {
572 let _lock = crate::core::data_dir::test_env_lock();
573 let tmp = tempfile::tempdir().unwrap();
574 crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
575
576 let now = Utc::now();
577 write_test_entry("c1_oldest", now - chrono::Duration::minutes(30), 10_000);
578 write_test_entry("c2_middle", now - chrono::Duration::minutes(20), 10_000);
579 write_test_entry("c3_newest", now - chrono::Duration::minutes(10), 10_000);
580
581 let removed = cleanup_with(now - chrono::Duration::days(365), 25_000);
584 assert_eq!(removed, 1, "only the oldest over-budget entry is evicted");
585 assert!(!content_path("c1_oldest").exists());
586 assert!(content_path("c2_middle").exists());
587 assert!(content_path("c3_newest").exists());
588
589 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
590 }
591}