lean_ctx/core/
compact_directive.rs1use std::time::{SystemTime, UNIX_EPOCH};
10
11use serde::{Deserialize, Serialize};
12
13const TTL_SECS: u64 = 1800;
15
16const MIN_INTERVAL_SECS: u64 = 300;
19
20#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct CompactDirective {
22 pub created_unix: u64,
23 pub keep_recent_turns: usize,
25 pub summary: String,
27 pub boundary_fingerprint: Option<String>,
31 pub original_handle: Option<String>,
34}
35
36fn now_unix() -> u64 {
37 SystemTime::now()
38 .duration_since(UNIX_EPOCH)
39 .map(|d| d.as_secs())
40 .unwrap_or(0)
41}
42
43fn store_path() -> Option<std::path::PathBuf> {
44 crate::core::data_dir::lean_ctx_data_dir()
45 .ok()
46 .map(|d| d.join("compact_directive.json"))
47}
48
49pub fn create(keep_recent_turns: usize, summary: String) -> Result<(), String> {
53 if let Some(existing) = load_active()
54 && now_unix().saturating_sub(existing.created_unix) < MIN_INTERVAL_SECS
55 {
56 return Err(format!(
57 "a compaction from {}s ago is still active — one compact per {}s \
58 (anti-obsession guard); use ctx_session action=\"restore\" first if needed",
59 now_unix().saturating_sub(existing.created_unix),
60 MIN_INTERVAL_SECS
61 ));
62 }
63 let directive = CompactDirective {
64 created_unix: now_unix(),
65 keep_recent_turns,
66 summary,
67 boundary_fingerprint: None,
68 original_handle: None,
69 };
70 save(&directive)
71}
72
73pub fn save(directive: &CompactDirective) -> Result<(), String> {
74 let path = store_path().ok_or_else(|| "no data dir".to_string())?;
75 let json = serde_json::to_string(directive).map_err(|e| e.to_string())?;
76 std::fs::write(path, json).map_err(|e| e.to_string())
77}
78
79pub fn load_active() -> Option<CompactDirective> {
81 let path = store_path()?;
82 let raw = std::fs::read_to_string(&path).ok()?;
83 let directive: CompactDirective = serde_json::from_str(&raw).ok()?;
84 if now_unix().saturating_sub(directive.created_unix) > TTL_SECS {
85 let _ = std::fs::remove_file(&path);
86 return None;
87 }
88 Some(directive)
89}
90
91pub fn clear() -> bool {
94 store_path().is_some_and(|path| std::fs::remove_file(path).is_ok())
95}
96
97#[cfg(test)]
98mod tests {
99 use super::*;
100
101 #[test]
102 fn directive_roundtrip_rate_limit_and_clear() {
103 let _lock = crate::core::data_dir::test_env_lock();
104 let _dir = crate::core::data_dir::isolated_data_dir();
105 assert!(load_active().is_none());
106
107 create(6, "summary one".into()).expect("first create succeeds");
108 let d = load_active().expect("directive active");
109 assert_eq!(d.keep_recent_turns, 6);
110 assert!(d.boundary_fingerprint.is_none());
111
112 let err = create(4, "summary two".into()).expect_err("rate-limited");
114 assert!(err.contains("anti-obsession"), "{err}");
115
116 assert!(clear());
117 assert!(load_active().is_none());
118 create(4, "summary three".into()).expect("create after clear");
120 clear();
121 }
122
123 #[test]
124 fn expired_directive_is_ignored_and_removed() {
125 let _lock = crate::core::data_dir::test_env_lock();
126 let _dir = crate::core::data_dir::isolated_data_dir();
127 let stale = CompactDirective {
128 created_unix: now_unix() - TTL_SECS - 10,
129 keep_recent_turns: 6,
130 summary: "old".into(),
131 boundary_fingerprint: None,
132 original_handle: None,
133 };
134 save(&stale).unwrap();
135 assert!(load_active().is_none(), "expired directive must not apply");
136 assert!(load_active().is_none());
137 }
138}