1use std::collections::BTreeSet;
14use std::path::{Path, PathBuf};
15use std::sync::atomic::{AtomicU64, Ordering};
16
17use lean_ctx_time::Date;
18
19use serde::{Deserialize, Serialize};
20
21use super::proof::Proof;
22use crate::core::config::{ValueDisplayConfig, ValueDisplayMode};
23
24const TOKEN_LADDER: [(u64, &str); 4] = [
25 (1_000_000, "1M"),
26 (10_000_000, "10M"),
27 (100_000_000, "100M"),
28 (1_000_000_000, "1B"),
29];
30const STREAK_LADDER: [u32; 3] = [7, 30, 100];
31const MIN_GAP_SECS: i64 = 24 * 60 * 60;
32const CHECK_EVERY_SECS: u64 = 30 * 60;
34
35static LAST_CHECK: AtomicU64 = AtomicU64::new(0);
36
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct Milestone {
39 pub id: String,
40 pub body: String,
41}
42
43#[derive(Debug, Default, Serialize, Deserialize)]
44#[serde(default)]
45struct State {
46 shown: BTreeSet<String>,
47 last_notified: i64,
49 claim: String,
52}
53
54struct Rung {
56 notify: Milestone,
57 lower: Vec<String>,
58}
59
60fn token_rung(net_saved: u64) -> Option<Rung> {
61 let reached: Vec<_> = TOKEN_LADDER
62 .iter()
63 .filter(|(n, _)| net_saved >= *n)
64 .collect();
65 let (_, top) = reached.last()?;
66 Some(Rung {
67 notify: Milestone {
68 id: format!("tokens_{top}"),
69 body: format!("{top} tokens kept out of your model's context so far."),
70 },
71 lower: reached[..reached.len() - 1]
72 .iter()
73 .map(|(_, label)| format!("tokens_{label}"))
74 .collect(),
75 })
76}
77
78fn streak_rung(longest: u32) -> Option<Rung> {
79 let reached: Vec<_> = STREAK_LADDER.iter().filter(|n| longest >= **n).collect();
80 let top = **reached.last()?;
81 Some(Rung {
82 notify: Milestone {
83 id: format!("streak_{top}"),
84 body: format!("{top} days in a row with lean-ctx."),
85 },
86 lower: reached[..reached.len() - 1]
87 .iter()
88 .map(|n| format!("streak_{n}"))
89 .collect(),
90 })
91}
92
93pub fn longest_streak(days: &BTreeSet<String>) -> u32 {
95 let mut longest = 0;
96 let mut run = 0;
97 let mut prev: Option<Date> = None;
98 for day in days {
99 let Ok(date) = lean_ctx_time::parse_date(day, "%Y-%m-%d") else {
100 continue;
101 };
102 run = match prev {
103 Some(p) if p.tomorrow().ok() == Some(date) => run + 1,
104 _ => 1,
105 };
106 longest = longest.max(run);
107 prev = Some(date);
108 }
109 longest
110}
111
112fn reached(proof: &Proof) -> Vec<Rung> {
114 let mut out = Vec::new();
115 out.extend(token_rung(proof.net_saved()));
116 if proof.security.secrets_redacted > 0 {
117 out.push(Rung {
118 notify: Milestone {
119 id: "first_secret".into(),
120 body: "A secret was kept out of your model's context for the first time.".into(),
121 },
122 lower: Vec::new(),
123 });
124 }
125 if proof.security.shell_blocked > 0 {
126 out.push(Rung {
127 notify: Milestone {
128 id: "first_block".into(),
129 body: "lean-ctx blocked a risky command for the first time.".into(),
130 },
131 lower: Vec::new(),
132 });
133 }
134 out.extend(streak_rung(longest_streak(&proof.active_days)));
135 out
136}
137
138fn decide(proof: &Proof, state: &mut State, now: i64) -> Option<Milestone> {
141 if proof.tampered() {
142 return None;
143 }
144 let rungs = reached(proof);
145 let pending: Vec<&Rung> = rungs
146 .iter()
147 .filter(|r| !state.shown.contains(&r.notify.id))
148 .collect();
149 if pending.is_empty() || now - state.last_notified < MIN_GAP_SECS {
150 return None;
151 }
152 let rung = pending[0];
153 state.shown.insert(rung.notify.id.clone());
154 state.shown.extend(rung.lower.iter().cloned());
155 state.last_notified = now;
156 Some(rung.notify.clone())
157}
158
159fn state_path(dir: &Path) -> PathBuf {
160 dir.join("milestones.json")
161}
162
163fn load_state(path: &Path) -> State {
164 std::fs::read(path)
165 .ok()
166 .and_then(|b| serde_json::from_slice(&b).ok())
167 .unwrap_or_default()
168}
169
170fn check_in(dir: &Path, proof: &Proof, now: i64) -> Option<Milestone> {
173 let path = state_path(dir);
174 let mut state = load_state(&path);
175 let milestone = decide(proof, &mut state, now)?;
176 state.claim = format!("{}-{now}-{}", std::process::id(), milestone.id);
177 let json = serde_json::to_vec(&state).ok()?;
178 let _ = std::fs::create_dir_all(dir);
179 crate::core::atomic_fs::try_atomic_write(&path, &json, None).ok()?;
180 (load_state(&path).claim == state.claim).then_some(milestone)
182}
183
184fn notifications_enabled(cfg: &ValueDisplayConfig) -> bool {
187 cfg.notifications
188 && matches!(
189 cfg.effective_mode(),
190 ValueDisplayMode::Milestones | ValueDisplayMode::Verbose
191 )
192}
193
194pub fn maybe_notify() {
197 let now = lean_ctx_time::UtcDateTime::now().timestamp();
198 let now_u = u64::try_from(now).unwrap_or(0);
199 let last = LAST_CHECK.load(Ordering::Relaxed);
200 if now_u.saturating_sub(last) < CHECK_EVERY_SECS
201 || LAST_CHECK
202 .compare_exchange(last, now_u, Ordering::Relaxed, Ordering::Relaxed)
203 .is_err()
204 {
205 return;
206 }
207 if !notifications_enabled(&crate::core::config::Config::load_arc().value_display) {
208 return;
209 }
210 let Some(dir) = super::snapshot::value_dir() else {
211 return;
212 };
213 let proof = super::proof::build(None, true);
214 if let Some(m) = check_in(&dir, &proof, now) {
215 super::notify::send(
216 "lean-ctx",
217 &format!("{}\nProof: lean-ctx value --all", m.body),
218 );
219 }
220}
221
222#[cfg(test)]
223mod tests {
224 use super::*;
225
226 fn proof(net: u64, secrets: u64, days: &[&str]) -> Proof {
227 let mut p = super::super::proof::build_from(None, None, None, None);
228 p.tokens_saved = net;
229 p.security.secrets_redacted = secrets;
230 p.active_days = days.iter().map(ToString::to_string).collect();
231 p
232 }
233
234 const DAY: i64 = 24 * 60 * 60;
235
236 #[test]
237 fn only_the_highest_new_rung_is_shown_and_lower_ones_are_marked() {
238 let mut state = State::default();
239 let m = decide(&proof(42_000_000, 0, &[]), &mut state, DAY).unwrap();
240 assert_eq!(m.id, "tokens_10M");
241 assert!(m.body.starts_with("10M tokens"));
242 assert!(state.shown.contains("tokens_1M"));
243 assert_eq!(
245 decide(&proof(42_000_000, 0, &[]), &mut state, 3 * DAY),
246 None
247 );
248 }
249
250 #[test]
251 fn at_most_one_notification_per_day() {
252 let mut state = State::default();
253 let p = proof(2_000_000, 1, &[]);
254 assert_eq!(decide(&p, &mut state, DAY).unwrap().id, "tokens_1M");
255 assert_eq!(decide(&p, &mut state, DAY + 60), None);
256 assert_eq!(decide(&p, &mut state, 2 * DAY).unwrap().id, "first_secret");
257 }
258
259 #[test]
260 fn a_tampered_chain_celebrates_nothing() {
261 let mut p = proof(5_000_000, 0, &[]);
262 p.ledger.intact = false;
263 assert_eq!(decide(&p, &mut State::default(), DAY), None);
264 }
265
266 #[test]
267 fn streaks_count_consecutive_utc_days() {
268 let days: BTreeSet<String> = [
269 "2026-09-01",
270 "2026-09-02",
271 "2026-09-03",
272 "2026-09-05",
273 "2026-09-06",
274 ]
275 .iter()
276 .map(ToString::to_string)
277 .collect();
278 assert_eq!(longest_streak(&days), 3);
279 let week: Vec<String> = (1..=8).map(|d| format!("2026-08-{d:02}")).collect();
280 let refs: Vec<&str> = week.iter().map(String::as_str).collect();
281 let m = decide(&proof(0, 0, &refs), &mut State::default(), DAY).unwrap();
282 assert_eq!(m.id, "streak_7");
283 }
284
285 #[test]
286 fn notifications_are_opt_in_via_the_milestones_mode() {
287 let mut cfg = ValueDisplayConfig::default();
288 assert!(!notifications_enabled(&cfg), "default minimal stays silent");
289 cfg.mode = ValueDisplayMode::Milestones;
290 assert!(notifications_enabled(&cfg));
291 cfg.mode = ValueDisplayMode::Verbose;
292 assert!(notifications_enabled(&cfg));
293 cfg.notifications = false;
294 assert!(!notifications_enabled(&cfg));
295 }
296
297 #[test]
298 fn nothing_reached_means_nothing_written() {
299 let dir = tempfile::tempdir().unwrap();
300 assert_eq!(check_in(dir.path(), &proof(10, 0, &[]), DAY), None);
301 assert!(!state_path(dir.path()).exists());
302 }
303
304 #[test]
305 fn a_milestone_is_claimed_once_across_processes() {
306 let dir = tempfile::tempdir().unwrap();
307 let p = proof(1_500_000, 0, &[]);
308 assert!(check_in(dir.path(), &p, DAY).is_some());
309 assert_eq!(check_in(dir.path(), &p, 3 * DAY), None);
311 }
312}