1use std::collections::BTreeMap;
15use std::fs::OpenOptions;
16use std::io::Read;
17use std::path::{Path, PathBuf};
18use std::time::Duration;
19
20use serde::{Deserialize, Serialize};
21
22pub const CLIENT_SESSIONS_FILE: &str = "client_sessions.json";
24pub const SESSIONS_PER_CLIENT: usize = 5;
26pub const MIN_SESSION_SECS: u64 = 60;
30const MAX_CLIENTS: usize = 32;
32const MAX_FILE_BYTES: u64 = 64 * 1024;
34const LOCK_TIMEOUT: Duration = Duration::from_millis(200);
36
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
41pub struct ClientSession {
42 pub pid: u32,
43 pub started: u64,
44 pub calls: u64,
45 #[serde(default)]
46 pub ended: Option<u64>,
47}
48
49impl ClientSession {
50 fn is_empty(&self) -> bool {
54 self.calls == 0
55 && self
56 .ended
57 .is_some_and(|end| end.saturating_sub(self.started) >= MIN_SESSION_SECS)
58 }
59}
60
61#[derive(Debug, Default, Serialize, Deserialize)]
62struct Ledger {
63 clients: BTreeMap<String, Vec<ClientSession>>,
64}
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub struct SetupTarget {
69 pub name: &'static str,
71 pub agent: &'static str,
73 pub writes_setup: bool,
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub struct Steering {
84 pub declined: bool,
88 pub shell_hooks: bool,
91}
92
93#[derive(Debug, Clone, PartialEq, Eq)]
95pub struct EmptyStreak {
96 pub client: String,
98 pub sessions: usize,
99}
100
101impl EmptyStreak {
102 pub fn target(&self) -> Option<SetupTarget> {
104 setup_target(&self.client)
105 }
106
107 pub fn line(&self, steering: Steering) -> Option<String> {
111 let target = self.target()?;
112 if steering.declined {
113 return None;
114 }
115 let name = target.name;
116 let seen = format!(
117 "{name}: connected {} times without a ctx call",
118 self.sessions
119 );
120 Some(if !target.writes_setup {
121 format!(
122 "{seen}; if your agent should use LeanCTX, ask it to use the ctx tools (lean-ctx writes no rules for {name})"
123 )
124 } else if steering.shell_hooks {
125 format!(
126 "{seen} (shell commands through LeanCTX are not counted); if your agent should use the ctx tools, run lean-ctx init --agent {}",
127 target.agent
128 )
129 } else {
130 format!(
131 "{seen}; if your agent should use LeanCTX, run lean-ctx init --agent {}",
132 target.agent
133 )
134 })
135 }
136}
137
138pub fn setup_target(client: &str) -> Option<SetupTarget> {
142 let (name, agent, writes_setup) = match client {
143 "claude-code" => ("Claude Code", "claude", true),
144 "codex" => ("Codex", "codex", true),
145 "cursor" => ("Cursor", "cursor", true),
146 "gemini-cli" => ("Gemini CLI", "gemini", true),
147 "antigravity" => ("Antigravity", "antigravity", true),
148 "windsurf" => ("Windsurf", "windsurf", true),
149 "zed" => ("Zed", "zed", true),
150 "vscode-copilot" => ("VS Code Copilot", "copilot", true),
151 "vscode" => ("VS Code", "vscode", true),
152 "kiro" => ("Kiro", "kiro", true),
153 "codebuddy" => ("CodeBuddy", "codebuddy", true),
154 "codewhale" => ("CodeWhale", "codewhale", false),
155 "muse" => ("Muse Code", "muse", false),
156 "cline" => ("Cline", "cline", true),
157 "roo-code" => ("Roo Code", "roo", true),
158 "continue" => ("Continue", "continue", true),
159 "opencode" => ("OpenCode", "opencode", true),
160 "goose" => ("Goose", "goose", false),
161 "amp" => ("Amp", "amp", true),
162 "augment" => ("Augment", "augment", true),
163 "jetbrains" => ("JetBrains", "jetbrains", true),
164 "trae" => ("Trae", "trae", true),
165 "qwen-code" => ("Qwen Code", "qwen", true),
166 "crush" => ("Crush", "crush", true),
167 "neovim" => ("Neovim", "neovim", true),
168 "emacs" => ("Emacs", "emacs", true),
169 "pi" => ("Pi", "pi", true),
170 "oh-my-pi" => ("Oh My Pi", "omp", true),
171 _ => return None,
172 };
173 Some(SetupTarget {
174 name,
175 agent,
176 writes_setup,
177 })
178}
179
180#[derive(Debug, Clone, Copy)]
182pub enum Mark {
183 Started,
185 Called,
187 Ended { calls: u64, at: u64 },
189}
190
191#[derive(Debug, Clone)]
193pub struct ClientSessions {
194 path: PathBuf,
195}
196
197impl ClientSessions {
198 pub fn in_data_dir(dir: &Path) -> Self {
199 Self {
200 path: dir.join(CLIENT_SESSIONS_FILE),
201 }
202 }
203
204 pub fn record(&self, client: &str, pid: u32, started: u64, mark: Mark) -> Result<(), String> {
210 if setup_target(client).is_none() {
211 return Ok(());
212 }
213 let lock_path = self.path.with_extension("json.lock");
214 let mut options = OpenOptions::new();
215 options.create(true).truncate(false).write(true);
216 #[cfg(unix)]
217 std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
218 let lock = options.open(&lock_path).map_err(|e| e.to_string())?;
219 lean_ctx_fs::file_lock::acquire_exclusive_timeout(&lock, LOCK_TIMEOUT)?;
220
221 let mut ledger = self.load();
222 let sessions = ledger.clients.entry(client.to_string()).or_default();
223 let index = if let Some(i) = sessions
224 .iter()
225 .position(|s| s.pid == pid && s.started == started)
226 {
227 i
228 } else {
229 sessions.push(ClientSession {
230 pid,
231 started,
232 calls: 0,
233 ended: None,
234 });
235 sessions.len() - 1
236 };
237 let session = &mut sessions[index];
238 match mark {
239 Mark::Started => {}
240 Mark::Called => session.calls = session.calls.max(1),
241 Mark::Ended { calls, at } => {
242 session.calls = session.calls.max(calls);
243 session.ended = Some(at);
244 if session.calls == 0 && at.saturating_sub(started) < MIN_SESSION_SECS {
245 sessions.remove(index);
246 }
247 }
248 }
249 sessions.sort_by_key(|s| s.started);
250 let excess = sessions.len().saturating_sub(SESSIONS_PER_CLIENT);
251 sessions.drain(..excess);
252 ledger.clients.retain(|_, sessions| !sessions.is_empty());
253 while ledger.clients.len() > MAX_CLIENTS {
254 let oldest = ledger
255 .clients
256 .iter()
257 .min_by_key(|(_, s)| s.last().map_or(0, |s| s.started))
258 .map(|(name, _)| name.clone());
259 match oldest {
260 Some(name) => ledger.clients.remove(&name),
261 None => break,
262 };
263 }
264
265 #[cfg(unix)]
267 let permissions =
268 Some(<std::fs::Permissions as std::os::unix::fs::PermissionsExt>::from_mode(0o600));
269 #[cfg(not(unix))]
270 let permissions: Option<std::fs::Permissions> = None;
271 let bytes = serde_json::to_vec(&ledger).map_err(|e| e.to_string())?;
272 lean_ctx_fs::atomic_fs::try_atomic_write(&self.path, &bytes, permissions.as_ref())
273 .map_err(|e| e.to_string())
274 }
275
276 pub fn empty_streaks(&self) -> Vec<EmptyStreak> {
279 self.load()
280 .clients
281 .into_iter()
282 .filter(|(client, sessions)| {
283 setup_target(client).is_some()
284 && sessions.len() >= SESSIONS_PER_CLIENT
285 && sessions.iter().all(ClientSession::is_empty)
286 })
287 .map(|(client, sessions)| EmptyStreak {
288 client,
289 sessions: sessions.len(),
290 })
291 .collect()
292 }
293
294 fn load(&self) -> Ledger {
295 let Ok(file) = std::fs::File::open(&self.path) else {
296 return Ledger::default();
297 };
298 let mut text = String::new();
299 if file
300 .take(MAX_FILE_BYTES + 1)
301 .read_to_string(&mut text)
302 .is_err()
303 || text.len() as u64 > MAX_FILE_BYTES
304 {
305 return Ledger::default();
306 }
307 serde_json::from_str(&text).unwrap_or_default()
308 }
309}
310
311#[cfg(test)]
312mod tests {
313 use super::*;
314
315 const PLAIN: Steering = Steering {
316 declined: false,
317 shell_hooks: false,
318 };
319
320 fn ledger() -> (tempfile::TempDir, ClientSessions) {
321 let dir = tempfile::tempdir().unwrap();
322 let store = ClientSessions::in_data_dir(dir.path());
323 (dir, store)
324 }
325
326 fn session(store: &ClientSessions, client: &str, started: u64, secs: u64) {
328 store
329 .record(client, 100, started, Mark::Started)
330 .and_then(|()| {
331 store.record(
332 client,
333 100,
334 started,
335 Mark::Ended {
336 calls: 0,
337 at: started + secs,
338 },
339 )
340 })
341 .unwrap();
342 }
343
344 fn empty_session(store: &ClientSessions, client: &str, started: u64) {
345 session(store, client, started * 1000, MIN_SESSION_SECS);
346 }
347
348 #[cfg(unix)]
349 fn mode(dir: &Path) -> u32 {
350 use std::os::unix::fs::PermissionsExt as _;
351 std::fs::metadata(dir.join(CLIENT_SESSIONS_FILE))
352 .unwrap()
353 .permissions()
354 .mode()
355 & 0o777
356 }
357
358 fn pi_streak(store: &ClientSessions) -> EmptyStreak {
359 for started in 1..=SESSIONS_PER_CLIENT as u64 {
360 empty_session(store, "pi", started);
361 }
362 let mut streaks = store.empty_streaks();
363 assert_eq!(streaks.len(), 1);
364 streaks.remove(0)
365 }
366
367 #[test]
368 fn five_empty_sessions_give_one_observation_with_a_conditional_fix() {
369 let (_dir, store) = ledger();
370 assert_eq!(
371 pi_streak(&store).line(PLAIN).as_deref(),
372 Some(
373 "Pi: connected 5 times without a ctx call; if your agent should use LeanCTX, run lean-ctx init --agent pi"
374 )
375 );
376 }
377
378 #[test]
379 fn short_sessions_never_count_and_never_push_real_sessions_out() {
380 let (_dir, store) = ledger();
381 for started in 1..SESSIONS_PER_CLIENT as u64 {
382 empty_session(&store, "codex", started);
383 }
384 for probe in 0..20 {
386 session(&store, "codex", 50_000 + probe, 2);
387 }
388 assert!(store.empty_streaks().is_empty(), "probes are no sessions");
389 empty_session(&store, "codex", 99);
390 assert_eq!(store.empty_streaks().len(), 1, "the four real ones stayed");
391 }
392
393 #[test]
394 fn no_line_while_a_session_is_used_running_or_without_an_end() {
395 let (_dir, store) = ledger();
396 for started in 1..SESSIONS_PER_CLIENT as u64 {
397 empty_session(&store, "cursor", started);
398 }
399 store.record("cursor", 9, 60_000, Mark::Started).unwrap();
401 assert!(store.empty_streaks().is_empty());
402 store.record("cursor", 9, 60_000, Mark::Called).unwrap();
404 store
405 .record(
406 "cursor",
407 9,
408 60_000,
409 Mark::Ended {
410 calls: 3,
411 at: 60_001,
412 },
413 )
414 .unwrap();
415 assert!(store.empty_streaks().is_empty());
416 }
417
418 #[test]
419 fn no_line_when_the_user_declined_rule_steering() {
420 let (_dir, store) = ledger();
421 let declined = Steering {
422 declined: true,
423 shell_hooks: false,
424 };
425 assert_eq!(pi_streak(&store).line(declined), None);
426 }
427
428 #[test]
429 fn shell_hook_clients_get_a_line_that_says_shell_use_is_not_counted() {
430 let (_dir, store) = ledger();
431 let hooks = Steering {
432 declined: false,
433 shell_hooks: true,
434 };
435 assert_eq!(
436 pi_streak(&store).line(hooks).as_deref(),
437 Some(
438 "Pi: connected 5 times without a ctx call (shell commands through LeanCTX are not counted); if your agent should use the ctx tools, run lean-ctx init --agent pi"
439 )
440 );
441 }
442
443 #[test]
444 fn hosts_without_a_setup_surface_get_no_init_command() {
445 let (_dir, store) = ledger();
446 for started in 1..=SESSIONS_PER_CLIENT as u64 {
447 empty_session(&store, "goose", started);
448 }
449 let line = store.empty_streaks()[0].line(PLAIN).unwrap();
450 assert_eq!(
451 line,
452 "Goose: connected 5 times without a ctx call; if your agent should use LeanCTX, ask it to use the ctx tools (lean-ctx writes no rules for Goose)"
453 );
454 }
455
456 #[test]
457 fn oh_my_pi_gets_its_init_command_since_init_writes_its_rules() {
458 assert!(setup_target("oh-my-pi").is_some_and(|t| t.writes_setup && t.agent == "omp"));
459 }
460
461 #[test]
462 fn the_file_is_bounded_private_and_skips_clients_without_a_fix() {
463 let (dir, store) = ledger();
464 for started in 1..=12 {
465 empty_session(&store, "claude-code", started);
466 }
467 empty_session(&store, "unknown", 1);
468 let ledger = store.load();
469 assert_eq!(ledger.clients.len(), 1);
470 let kept = &ledger.clients["claude-code"];
471 assert_eq!(kept.len(), SESSIONS_PER_CLIENT);
472 assert_eq!(kept[0].started, 8000, "the newest sessions are kept");
473 #[cfg(unix)]
474 assert_eq!(mode(dir.path()), 0o600);
475 #[cfg(not(unix))]
476 let _ = dir;
477 }
478
479 #[test]
480 fn a_corrupt_or_oversized_file_reads_empty_and_is_replaced() {
481 let (dir, store) = ledger();
482 let path = dir.path().join(CLIENT_SESSIONS_FILE);
483 for started in 1..=SESSIONS_PER_CLIENT as u64 {
485 empty_session(&store, "pi", started);
486 }
487 let mut padded = std::fs::read(&path).unwrap();
488 padded.resize(MAX_FILE_BYTES as usize + 1, b' ');
489 std::fs::write(&path, &padded).unwrap();
490 assert!(store.empty_streaks().is_empty());
491 std::fs::write(&path, b"{\"clients\": [tru").unwrap();
493 assert!(store.empty_streaks().is_empty());
494 store.record("pi", 1, 1, Mark::Started).unwrap();
495 assert_eq!(store.load().clients["pi"].len(), 1);
496 #[cfg(unix)]
497 assert_eq!(mode(dir.path()), 0o600);
498 }
499
500 #[test]
501 fn concurrent_servers_keep_both_sessions() {
502 let (_dir, store) = ledger();
503 let barrier = std::sync::Barrier::new(2);
504 std::thread::scope(|scope| {
505 for pid in [1, 2] {
506 let (store, barrier) = (&store, &barrier);
507 scope.spawn(move || {
508 barrier.wait();
509 let mut attempts = 0;
514 while let Err(error) = store.record("codex", pid, 7, Mark::Started) {
515 attempts += 1;
516 assert!(attempts < 50, "lock never free: {error}");
517 }
518 });
519 }
520 });
521 let pids: Vec<u32> = store.load().clients["codex"]
522 .iter()
523 .map(|s| s.pid)
524 .collect();
525 assert_eq!(pids.len(), 2, "{pids:?}");
526 }
527}