lean_ctx/core/
introspect.rs1use std::collections::HashMap;
16use std::sync::{LazyLock, Mutex};
17use std::time::Instant;
18
19use serde::{Deserialize, Serialize};
20
21pub struct Subsystem {
25 pub key: &'static str,
26 pub label: &'static str,
27 pub science: &'static str,
28}
29
30pub const SUBSYSTEMS: &[Subsystem] = &[
33 Subsystem {
34 key: "phi_recompute",
35 label: "Sticky-Phi fix",
36 science: "time-variant salience (attention)",
37 },
38 Subsystem {
39 key: "power_law_decay",
40 label: "Power-law decay",
41 science: "Ebbinghaus forgetting + spacing effect",
42 },
43 Subsystem {
44 key: "memory_consolidation",
45 label: "Memory consolidation",
46 science: "complementary learning systems",
47 },
48 Subsystem {
49 key: "integration_phi",
50 label: "Integration-aware Phi",
51 science: "IIT non-redundancy (MMR)",
52 },
53 Subsystem {
54 key: "gwt_ignition",
55 label: "Global-workspace ignition",
56 science: "global workspace theory",
57 },
58 Subsystem {
59 key: "field_weights_bandit",
60 label: "Learned field weights",
61 science: "reinforcement learning (bandit)",
62 },
63 Subsystem {
64 key: "replay_consolidation",
65 label: "Idle replay",
66 science: "sharp-wave-ripple replay",
67 },
68 Subsystem {
69 key: "immune_detector",
70 label: "Context-poisoning screen (Control)",
71 science: "self/non-self screening of provider data",
72 },
73 Subsystem {
74 key: "observation_synthesis",
75 label: "Observation synthesis",
76 science: "entity-summary memory (Hindsight)",
77 },
78];
79
80#[derive(Debug, Clone, Default, Serialize, Deserialize)]
82pub struct Activity {
83 pub count: u64,
84 pub last_unix: i64,
85}
86
87#[derive(Default)]
88struct Entry {
89 count: u64,
90 flushed: u64,
93 last_unix: i64,
94}
95
96#[derive(Default)]
97struct Registry {
98 entries: HashMap<&'static str, Entry>,
99 last_flush: Option<Instant>,
100}
101
102static REGISTRY: LazyLock<Mutex<Registry>> = LazyLock::new(|| Mutex::new(Registry::default()));
103
104const FLUSH_DEBOUNCE: std::time::Duration = std::time::Duration::from_secs(2);
106
107fn now_unix() -> i64 {
108 std::time::SystemTime::now()
109 .duration_since(std::time::UNIX_EPOCH)
110 .map_or(0, |d| d.as_secs() as i64)
111}
112
113pub fn tick(key: &'static str) {
116 if let Ok(mut reg) = REGISTRY.lock() {
117 let e = reg.entries.entry(key).or_default();
118 e.count += 1;
119 e.last_unix = now_unix();
120 }
121}
122
123fn activity_path() -> Option<std::path::PathBuf> {
124 crate::core::data_dir::lean_ctx_data_dir()
125 .ok()
126 .map(|d| d.join("cognition_activity.json"))
127}
128
129fn read_disk() -> HashMap<String, Activity> {
130 activity_path()
131 .filter(|p| p.exists())
132 .and_then(|p| std::fs::read_to_string(p).ok())
133 .and_then(|s| serde_json::from_str(&s).ok())
134 .unwrap_or_default()
135}
136
137pub fn flush() {
141 let Ok(mut reg) = REGISTRY.lock() else {
142 return;
143 };
144 if reg.entries.values().all(|e| e.count == e.flushed) {
145 reg.last_flush = Some(Instant::now());
146 return;
147 }
148 let mut disk = read_disk();
149 for (key, e) in &mut reg.entries {
150 let delta = e.count - e.flushed;
151 if delta == 0 {
152 continue;
153 }
154 let rec = disk.entry((*key).to_string()).or_default();
155 rec.count += delta;
156 rec.last_unix = rec.last_unix.max(e.last_unix);
157 e.flushed = e.count;
158 }
159 if let Some(path) = activity_path() {
160 if let Some(parent) = path.parent() {
161 let _ = std::fs::create_dir_all(parent);
162 }
163 if let Ok(json) = serde_json::to_string_pretty(&disk) {
164 let _ = crate::config_io::write_atomic(&path, &json);
165 }
166 }
167 reg.last_flush = Some(Instant::now());
168}
169
170pub fn flush_if_due() {
173 let due = {
174 match REGISTRY.lock() {
175 Ok(reg) => reg.last_flush.is_none_or(|t| t.elapsed() >= FLUSH_DEBOUNCE),
176 Err(_) => false,
177 }
178 };
179 if due {
180 flush();
181 }
182}
183
184pub fn snapshot() -> Vec<(&'static Subsystem, Activity)> {
188 let mut disk = read_disk();
189 if let Ok(reg) = REGISTRY.lock() {
190 for (key, e) in ®.entries {
191 let rec = disk.entry((*key).to_string()).or_default();
192 rec.count += e.count - e.flushed;
193 rec.last_unix = rec.last_unix.max(e.last_unix);
194 }
195 }
196 SUBSYSTEMS
197 .iter()
198 .map(|s| {
199 let act = disk.get(s.key).cloned().unwrap_or_default();
200 (s, act)
201 })
202 .collect()
203}
204
205pub fn format_report() -> String {
207 let snap = snapshot();
208 let active = snap.iter().filter(|(_, a)| a.count > 0).count();
209 let total = snap.len();
210 let mut out = String::new();
211 out.push_str(&format!(
212 "Cognition subsystems: {active}/{total} active ({total} wired)\n\n"
213 ));
214 for (sys, act) in snap {
215 let status = if act.count > 0 { "active" } else { "idle " };
216 let last = if act.last_unix > 0 {
217 format_age(now_unix() - act.last_unix)
218 } else {
219 "never".to_string()
220 };
221 out.push_str(&format!(
222 " [{status}] {label:<26} count={count:<7} last={last:<10} {science}\n",
223 label = sys.label,
224 count = act.count,
225 science = sys.science,
226 ));
227 }
228 out
229}
230
231pub fn snapshot_json() -> String {
233 let map: HashMap<&str, Activity> = snapshot().into_iter().map(|(s, a)| (s.key, a)).collect();
234 serde_json::to_string_pretty(&map).unwrap_or_else(|_| "{}".to_string())
235}
236
237fn format_age(secs: i64) -> String {
238 if secs < 0 {
239 return "just now".to_string();
240 }
241 if secs < 60 {
242 format!("{secs}s ago")
243 } else if secs < 3600 {
244 format!("{}m ago", secs / 60)
245 } else if secs < 86400 {
246 format!("{}h ago", secs / 3600)
247 } else {
248 format!("{}d ago", secs / 86400)
249 }
250}
251
252#[cfg(test)]
253pub mod tests {
254 use super::*;
255
256 #[test]
257 fn tick_increments_in_memory_snapshot() {
258 let _env = crate::core::data_dir::test_env_lock();
260 let dir = tempfile::tempdir().unwrap();
261 crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.path());
262
263 tick("phi_recompute");
264 tick("phi_recompute");
265 let snap = snapshot();
266 let phi = snap
267 .iter()
268 .find(|(s, _)| s.key == "phi_recompute")
269 .map(|(_, a)| a.count)
270 .unwrap();
271 assert!(phi >= 2, "tick should be reflected in snapshot, got {phi}");
272 }
273
274 #[test]
275 fn flush_persists_and_accumulates() {
276 let _env = crate::core::data_dir::test_env_lock();
277 let dir = tempfile::tempdir().unwrap();
278 crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.path());
279
280 tick("replay_consolidation");
281 flush();
282 let disk = read_disk();
283 assert!(
284 disk.get("replay_consolidation")
285 .is_some_and(|a| a.count >= 1)
286 );
287
288 tick("replay_consolidation");
290 flush();
291 let disk2 = read_disk();
292 assert!(
293 disk2.get("replay_consolidation").unwrap().count >= 2,
294 "deltas should accumulate across flushes"
295 );
296 }
297
298 #[test]
299 fn report_lists_all_subsystems() {
300 let _env = crate::core::data_dir::test_env_lock();
301 let dir = tempfile::tempdir().unwrap();
302 crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.path());
303 let report = format_report();
304 for sys in SUBSYSTEMS {
305 assert!(
306 report.contains(sys.label),
307 "report must mention {}",
308 sys.label
309 );
310 }
311 }
312}