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