Skip to main content

lean_ctx/tools/
server_metrics.rs

1use std::sync::atomic::Ordering;
2
3use super::server::{CepComputedStats, CrpMode, LeanCtxServer, ToolCallRecord};
4use super::startup::auto_consolidate_knowledge;
5use super::{ctx_compress, ctx_share};
6
7/// Build payload-free OCLA metrics for one completed MCP tool call.
8///
9/// Values use milli-units and saturate at the signed metric contract's upper
10/// bound. Tool dimensions are bounded metadata; request payloads and paths
11/// never enter the exporter.
12fn ocla_metric_points(
13    context: &crate::core::ocla::OclaRequestContext,
14    tool: &str,
15    original: usize,
16    saved: usize,
17    duration_ms: u64,
18) -> Vec<crate::core::ocla::MetricPoint> {
19    let mut dimensions = std::collections::BTreeMap::new();
20    dimensions.insert("tool".to_string(), tool.to_string());
21    let original = metric_milli(original as u64);
22    let saved = metric_milli(saved as u64);
23    let duration = metric_milli(duration_ms);
24    vec![
25        crate::core::ocla::MetricPoint {
26            context: context.clone(),
27            name: "mcp.tool.original_tokens".to_string(),
28            value_milli: original,
29            dimensions: dimensions.clone(),
30        },
31        crate::core::ocla::MetricPoint {
32            context: context.clone(),
33            name: "mcp.tool.saved_tokens".to_string(),
34            value_milli: saved,
35            dimensions: dimensions.clone(),
36        },
37        crate::core::ocla::MetricPoint {
38            context: context.clone(),
39            name: "mcp.tool.duration_ms".to_string(),
40            value_milli: duration,
41            dimensions,
42        },
43    ]
44}
45
46fn metric_milli(value: u64) -> i64 {
47    i64::try_from(value.saturating_mul(1_000)).unwrap_or(i64::MAX)
48}
49
50impl LeanCtxServer {
51    /// Records a tool call's token savings without timing information.
52    pub async fn record_call(
53        &self,
54        tool: &str,
55        original: usize,
56        saved: usize,
57        mode: Option<String>,
58    ) {
59        self.record_call_with_timing(tool, original, saved, mode, 0)
60            .await;
61    }
62
63    /// Records a tool call like `record_call`, but includes an optional file
64    /// path for observability and the measured handler duration (#1020 — the
65    /// duration is what makes the row land in `tool-calls.log`).
66    pub async fn record_call_with_path(
67        &self,
68        tool: &str,
69        original: usize,
70        saved: usize,
71        mode: Option<String>,
72        path: Option<&str>,
73        duration_ms: u64,
74    ) {
75        self.record_call_with_timing_inner(tool, original, saved, mode, duration_ms, path)
76            .await;
77    }
78
79    /// Records a tool call's token savings, duration, and emits events and stats.
80    pub async fn record_call_with_timing(
81        &self,
82        tool: &str,
83        original: usize,
84        saved: usize,
85        mode: Option<String>,
86        duration_ms: u64,
87    ) {
88        self.record_call_with_timing_inner(tool, original, saved, mode, duration_ms, None)
89            .await;
90    }
91
92    async fn record_call_with_timing_inner(
93        &self,
94        tool: &str,
95        original: usize,
96        saved: usize,
97        mode: Option<String>,
98        duration_ms: u64,
99        path: Option<&str>,
100    ) {
101        if let Some(agent_id) = self.presence_agent_id.read().await.clone()
102            && let Err(error) = crate::core::agents::AgentRegistry::heartbeat_persistent(&agent_id)
103        {
104            tracing::warn!("lean-ctx: failed to update MCP agent heartbeat: {error}");
105        }
106        // #1570 P2/P6: a successful recovery tool clears budget-nudge anchors
107        // and starts the anti-obsession cooldown.
108        crate::core::nudge::record_recovery_action(tool);
109        let ts = chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
110        let mut calls = self.tool_calls.write().await;
111        calls.push(ToolCallRecord {
112            tool: tool.to_string(),
113            original_tokens: original,
114            saved_tokens: saved,
115            mode: mode.clone(),
116            duration_ms,
117            timestamp: ts.clone(),
118        });
119
120        const MAX_TOOL_CALL_RECORDS: usize = 500;
121        if calls.len() > MAX_TOOL_CALL_RECORDS {
122            let excess = calls.len() - MAX_TOOL_CALL_RECORDS;
123            calls.drain(..excess);
124        }
125
126        // #1020: persist whenever we have a duration OR real metrics. The old
127        // `duration_ms > 0` gate dropped every read/search row (they record with
128        // measured metrics but were previously logged via a separate zero-filled
129        // path), so `tool-calls.log` only ever showed `orig=0 saved=0 mode=-`.
130        if duration_ms > 0 || original > 0 {
131            Self::append_tool_call_log(tool, duration_ms, original, saved, mode.as_deref(), &ts);
132        }
133
134        crate::core::events::emit_tool_call(
135            tool,
136            original as u64,
137            saved as u64,
138            mode.clone(),
139            duration_ms,
140            path.map(ToString::to_string),
141        );
142
143        let output_tokens = original.saturating_sub(saved);
144        let session_id = self.session.read().await.id.clone();
145        let model = std::env::var("LEAN_CTX_MODEL").unwrap_or_else(|_| "unknown".to_string());
146        if let Err(error) = crate::core::measurement::MeasurementFramework::from_data_dir()
147            .record_tool_call(&session_id, tool, 0, original as u64, saved as u64, &model)
148        {
149            tracing::debug!("lean-ctx: measurement write failed: {error}");
150        }
151        crate::core::metering::MeterStore::append_best_effort(
152            crate::core::metering::MeterEntry::new(
153                tool,
154                original as u64,
155                output_tokens as u64,
156                saved as u64,
157            ),
158        );
159        crate::core::stats::record_at_turn(
160            tool,
161            original,
162            output_tokens,
163            crate::core::context_overhead::observed_turns(),
164        );
165        // MCP shell savings are measured (raw vs compressed output), so they are
166        // ledger-grade (GL #479 D2). Reads are ledgered by the ctx_read /
167        // ctx_multi_read callers (#685, decoupled from the heatmap) and ctx_search
168        // records itself — only shell is recorded here, exactly once. `actual_tokens`
169        // is the *sent* output; a prior duplicate block passed `saved` and so both
170        // double-counted shell events and stored the wrong saving (#685).
171        if tool == "ctx_shell" {
172            crate::core::savings_ledger::record_tool_event(
173                tool,
174                original,
175                output_tokens,
176                None,
177                None,
178            );
179        }
180
181        // OCLA ObservationHook: project every MCP tool call as a structured
182        // observation for the canonical observation capability.
183        {
184            let session_r = self.session.read().await;
185            let agent_id = self
186                .presence_agent_id
187                .read()
188                .await
189                .clone()
190                .unwrap_or_default();
191            let ctx = crate::core::ocla::OclaRequestContext {
192                request_id: format!("mcp-{}", self.call_count.load(Ordering::Relaxed)),
193                session_id: session_r.id.clone(),
194                agent_id,
195                content_ref: path.map_or_else(|| format!("tool:{tool}"), |p| format!("file:{p}")),
196                tenant_id: None,
197                trace_id: "tr-unit".into(),
198                task_id: None,
199                parent_task_id: None,
200            };
201            drop(session_r);
202            let observation = crate::core::ocla::Observation {
203                context: ctx.clone(),
204                name: format!("tool_call:{tool}"),
205                attributes: std::collections::BTreeMap::from([
206                    ("original_tokens".into(), original.to_string()),
207                    ("saved_tokens".into(), saved.to_string()),
208                    ("duration_ms".into(), duration_ms.to_string()),
209                ]),
210            };
211            let hook = crate::core::ocla::OclaRegistry::global()
212                .observation_hook
213                .as_ref();
214            let _ = hook.observe(observation).await;
215
216            let outcome = crate::core::ocla::Outcome {
217                context: ctx.clone(),
218                accepted: Some(saved > 0),
219                quality_score_milli: if original > 0 {
220                    Some(((saved as u64 * 1000) / original as u64).min(1000) as u16)
221                } else {
222                    None
223                },
224                outcome_ref: None,
225            };
226            let _ = crate::core::ocla::OclaRegistry::global()
227                .outcome_tracker
228                .record_outcome(outcome);
229
230            // OCLA MetricsExporter projection: one bounded, local batch per
231            // tool call. This is observational only and cannot affect stats,
232            // billing, or external export destinations.
233            let metrics = ocla_metric_points(&ctx, tool, original, saved, duration_ms);
234            let _ = crate::core::ocla::OclaRegistry::global()
235                .metrics_exporter
236                .export_metrics(metrics)
237                .await;
238        }
239        let mut session = self.session.write().await;
240        session.record_tool_call(saved as u64, original as u64);
241        if tool == "ctx_shell" {
242            session.record_command();
243        }
244        let pending_save = if session.should_save() {
245            session.prepare_save().ok()
246        } else {
247            None
248        };
249        drop(calls);
250        drop(session);
251
252        let pro_count = self.pro_trigger_check_count.fetch_add(1, Ordering::Relaxed) + 1;
253        if pro_count.is_multiple_of(10) {
254            let signals = {
255                let session = self.session.read().await;
256                crate::core::pro_triggers::local_usage_signals(&session)
257            };
258            tokio::task::spawn_blocking(move || {
259                for nudge in crate::core::pro_triggers::evaluate_triggers(&signals) {
260                    tracing::info!(kind = ?nudge.kind, message = %nudge.message, "lean-ctx Pro trigger fired");
261                }
262            });
263        }
264
265        if let Some(prepared) = pending_save {
266            drop(tokio::task::spawn_blocking(move || {
267                let _ = prepared.write_to_disk();
268            }));
269        }
270
271        self.write_mcp_live_stats().await;
272        write_science_live_stats();
273    }
274
275    /// Increments the call counter and returns true if a checkpoint is due.
276    pub fn increment_and_check(&self) -> bool {
277        let count = self.call_count.fetch_add(1, Ordering::Relaxed) + 1;
278        let interval = Self::checkpoint_interval_effective();
279        interval > 0 && count.is_multiple_of(interval)
280    }
281
282    /// Generates a compressed context checkpoint with session state and multi-agent sync.
283    pub async fn auto_checkpoint(&self) -> Option<String> {
284        let cache = self.cache.read().await;
285        if cache.get_all_entries().is_empty() {
286            return None;
287        }
288        let complexity = crate::core::adaptive::classify_from_context(&cache);
289        let checkpoint = ctx_compress::handle(&cache, false, CrpMode::effective());
290        drop(cache);
291
292        let mut session = self.session.write().await;
293        let pending_save = session.prepare_save().ok();
294        let session_summary = session.format_compact();
295        let has_insights = !session.findings.is_empty() || !session.decisions.is_empty();
296        let project_root = session.project_root.clone();
297        // Snapshot the session under the lock; persist the summary off the hot path.
298        let summary_candidate = crate::core::session_summary::build_candidate(&session);
299        drop(session);
300
301        if let Some(prepared) = pending_save {
302            tokio::task::spawn_blocking(move || {
303                let _ = prepared.write_to_disk();
304            });
305        }
306
307        if has_insights && let Some(ref root) = project_root {
308            let root = root.clone();
309            std::thread::spawn(move || {
310                auto_consolidate_knowledge(&root);
311            });
312        }
313
314        // Periodically record a recallable AI session summary (#292), off-thread.
315        if let Some(ref root) = project_root {
316            let root = root.clone();
317            std::thread::spawn(move || {
318                let _ =
319                    crate::core::session_summary::maybe_record_periodic(&root, summary_candidate);
320            });
321        }
322
323        let multi_agent_block = self
324            .auto_multi_agent_checkpoint(project_root.as_ref())
325            .await;
326
327        self.record_call("ctx_compress", 0, 0, Some("auto".to_string()))
328            .await;
329
330        self.record_cep_snapshot().await;
331
332        if !crate::core::protocol::meta_visible() {
333            return None;
334        }
335
336        let doc_reminder = {
337            let session = self.session.read().await;
338            let calls = self.tool_calls.read().await;
339            Self::activity_nudge(&session, &calls)
340        };
341
342        Some(format!(
343            "{checkpoint}\n\n--- SESSION STATE ---\n{session_summary}\n\n{}{multi_agent_block}{doc_reminder}",
344            complexity.instruction_suffix()
345        ))
346    }
347
348    async fn auto_multi_agent_checkpoint(&self, project_root: Option<&String>) -> String {
349        let Some(root) = project_root else {
350            return String::new();
351        };
352
353        let registry = crate::core::agents::AgentRegistry::load_or_create();
354        let active = registry.list_active(Some(root));
355        if active.len() <= 1 {
356            return String::new();
357        }
358
359        let agent_id = self.agent_id.read().await;
360        let my_id = match agent_id.as_deref() {
361            Some(id) => id.to_string(),
362            None => return String::new(),
363        };
364        drop(agent_id);
365
366        let cache = self.cache.read().await;
367        let entries = cache.get_all_entries();
368        if !entries.is_empty() {
369            let mut by_access: Vec<_> = entries.iter().collect();
370            by_access.sort_by_key(|x| std::cmp::Reverse(x.1.read_count()));
371            let top_paths: Vec<&str> = by_access
372                .iter()
373                .take(5)
374                .map(|(key, _)| key.as_str())
375                .collect();
376            let paths_csv = top_paths.join(",");
377
378            let _ = ctx_share::handle(
379                "push",
380                Some(&my_id),
381                None,
382                Some(&paths_csv),
383                None,
384                &cache,
385                root,
386            );
387        }
388        drop(cache);
389
390        let pending_count = registry
391            .scratchpad
392            .iter()
393            .filter(|e| !e.read_by.contains(&my_id) && e.from_agent != my_id)
394            .count();
395
396        let shared_dir = crate::core::data_dir::lean_ctx_data_dir()
397            .unwrap_or_default()
398            .join("agents")
399            .join("shared");
400        let shared_count = if shared_dir.exists() {
401            std::fs::read_dir(&shared_dir).map_or(0, std::iter::Iterator::count)
402        } else {
403            0
404        };
405
406        let agent_names: Vec<String> = active
407            .iter()
408            .map(|a| {
409                let role = a.role.as_deref().unwrap_or(&a.agent_type);
410                format!("{role}({})", &a.agent_id[..8.min(a.agent_id.len())])
411            })
412            .collect();
413
414        format!(
415            "\n\n--- MULTI-AGENT SYNC ---\nAgents: {} | Pending msgs: {} | Shared contexts: {}\nAuto-shared top-5 cached files.\n--- END SYNC ---",
416            agent_names.join(", "),
417            pending_count,
418            shared_count,
419        )
420    }
421
422    /// Appends a tool call entry to the rotating `tool-calls.log` file.
423    pub fn append_tool_call_log(
424        tool: &str,
425        duration_ms: u64,
426        original: usize,
427        saved: usize,
428        mode: Option<&str>,
429        timestamp: &str,
430    ) {
431        const MAX_LOG_LINES: usize = 50;
432        if let Ok(dir) = crate::core::paths::state_dir() {
433            let log_path = dir.join("tool-calls.log");
434            let mode_str = mode.unwrap_or("-");
435            let slow = if duration_ms > 5000 { " **SLOW**" } else { "" };
436            let line = format!(
437                "{timestamp}\t{tool}\t{duration_ms}ms\torig={original}\tsaved={saved}\tmode={mode_str}{slow}\n"
438            );
439
440            let mut lines: Vec<String> = std::fs::read_to_string(&log_path)
441                .unwrap_or_default()
442                .lines()
443                .map(std::string::ToString::to_string)
444                .collect();
445
446            lines.push(line.trim_end().to_string());
447            if lines.len() > MAX_LOG_LINES {
448                lines.drain(0..lines.len() - MAX_LOG_LINES);
449            }
450
451            let _ = std::fs::write(&log_path, lines.join("\n") + "\n");
452        }
453    }
454
455    fn compute_cep_stats(
456        calls: &[ToolCallRecord],
457        stats: &crate::core::cache::CacheStats,
458        complexity: &crate::core::adaptive::TaskComplexity,
459    ) -> CepComputedStats {
460        let total_original: u64 = calls.iter().map(|c| c.original_tokens as u64).sum();
461        let total_saved: u64 = calls.iter().map(|c| c.saved_tokens as u64).sum();
462        let total_compressed = total_original.saturating_sub(total_saved);
463        let compression_rate = if total_original > 0 {
464            total_saved as f64 / total_original as f64
465        } else {
466            0.0
467        };
468
469        let modes_used: std::collections::HashSet<&str> =
470            calls.iter().filter_map(|c| c.mode.as_deref()).collect();
471        let mode_diversity = (modes_used.len() as f64 / 10.0).min(1.0);
472        let cache_util = stats.hit_rate() / 100.0;
473        // Output efficiency (#501): 1 - avg echo ratio. An agent that keeps
474        // re-quoting delivered content burns the input savings on output.
475        let output_efficiency = 1.0 - crate::core::output_echo::current_avg_ratio();
476        let cep_score = cache_util * 0.25
477            + mode_diversity * 0.15
478            + compression_rate * 0.45
479            + output_efficiency * 0.15;
480
481        let mut mode_counts: std::collections::HashMap<String, u64> =
482            std::collections::HashMap::new();
483        for call in calls {
484            if let Some(ref mode) = call.mode {
485                *mode_counts.entry(mode.clone()).or_insert(0) += 1;
486            }
487        }
488
489        CepComputedStats {
490            cep_score: (cep_score * 100.0).round() as u32,
491            cache_util: (cache_util * 100.0).round() as u32,
492            mode_diversity: (mode_diversity * 100.0).round() as u32,
493            compression_rate: (compression_rate * 100.0).round() as u32,
494            total_original,
495            total_compressed,
496            total_saved,
497            mode_counts,
498            complexity: format!("{complexity:?}"),
499            cache_hits: stats.cache_hits(),
500            total_reads: stats.total_reads(),
501            tool_call_count: calls.len() as u64,
502            adoption: Self::compute_adoption(calls),
503        }
504    }
505
506    /// Compute adoption metrics from tool call history.
507    /// ctx_* calls = lean-ctx MCP adoption; other tools = native passthrough.
508    fn compute_adoption(calls: &[ToolCallRecord]) -> super::server::AdoptionMetrics {
509        let ctx_tool_calls = calls.iter().filter(|c| c.tool.starts_with("ctx_")).count() as u64;
510        let total = calls.len() as u64;
511        let native_passthrough = total.saturating_sub(ctx_tool_calls);
512        let adoption_pct = if total > 0 {
513            ((ctx_tool_calls as f64 / total as f64) * 100.0).round() as u32
514        } else {
515            0
516        };
517        super::server::AdoptionMetrics {
518            ctx_tool_calls,
519            native_passthrough,
520            adoption_pct,
521        }
522    }
523
524    async fn write_mcp_live_stats(&self) {
525        let count = self.call_count.load(Ordering::Relaxed);
526        if count > 1 && !count.is_multiple_of(5) {
527            return;
528        }
529
530        let cache = self.cache.read().await;
531        let calls = self.tool_calls.read().await;
532        let stats = cache.get_stats();
533        let complexity = crate::core::adaptive::classify_from_context(&cache);
534        let dedup = crate::tools::ctx_read::dedup_hook::summary();
535
536        let cs = Self::compute_cep_stats(&calls, stats, &complexity);
537        let started_at = calls
538            .first()
539            .map(|c| c.timestamp.clone())
540            .unwrap_or_default();
541
542        drop(cache);
543        drop(calls);
544
545        // Persist CEP on the live-stats cadence (first call + every 5th) so even
546        // short sessions register `sessions`/`total_cache_hits` instead of only
547        // recording on an `auto_checkpoint` that a brief workload may never reach.
548        // `record_cep_session` is delta-based and PID-guarded, so the extra call
549        // that coincides with a checkpoint is a no-op for the totals (#361).
550        crate::core::stats::record_cep_session(
551            cs.cep_score,
552            cs.cache_hits,
553            cs.total_reads,
554            cs.total_original,
555            cs.total_compressed,
556            &cs.mode_counts,
557            cs.tool_call_count,
558            &cs.complexity,
559        );
560
561        // Cache layers can both participate in one read (for example a
562        // session-cache rendering later collapsed by content dedup).  Never
563        // aggregate their independent counters into a synthetic hit rate.
564        // `reuse_snapshot` records one terminal outcome per read instead.
565        let reuse = crate::core::cache::reuse_snapshot();
566        let provider_reuse = crate::proxy::cache_attribution::snapshot();
567
568        let source_snapshot = crate::core::auto_mode_resolver::source_counts();
569        let compressed_cache_hits = source_snapshot
570            .iter()
571            .find(|(k, _)| *k == "compressed_cache_hit")
572            .map_or(0, |(_, v)| *v);
573        let full_delivery_degraded = source_snapshot
574            .iter()
575            .find(|(k, _)| *k == "full_delivery_degraded")
576            .map_or(0, |(_, v)| *v);
577
578        let live = serde_json::json!({
579            "cep_score": cs.cep_score,
580            "cache_utilization": cs.cache_util,
581            "mode_diversity": cs.mode_diversity,
582            "compression_rate": cs.compression_rate,
583            "task_complexity": cs.complexity,
584            "files_cached": cs.total_reads,
585            "total_reads": cs.total_reads,
586            "cache_hits": cs.cache_hits,
587            "dedup_reads": dedup.total_reads,
588            "dedup_hits": dedup.dedup_hits,
589            "dedup_tokens_saved": dedup.tokens_saved,
590            "read_reuse_rate": reuse.read_reuse_rate(),
591            "disk_reuse_rate": reuse.disk_reuse_rate(),
592            "provider_reuse_rate": provider_reuse.provider_reuse_rate(),
593            "read_reuse": {
594                "reused_renderings": reuse.reused_renderings,
595                "eligible_ctx_reads": reuse.eligible_ctx_reads,
596            },
597            "disk_reuse": {
598                "content_cache_hits": reuse.disk_content_hits,
599                "eligible_search_reads": reuse.eligible_search_reads,
600            },
601            "provider_reuse": {
602                "warm_reuses": provider_reuse.warm_reuses,
603                "ttl_lapses": provider_reuse.ttl_lapses,
604                "prefix_changes": provider_reuse.prefix_changes,
605                "eligible_requests": provider_reuse.eligible_provider_requests(),
606            },
607            "reuse_outcomes": {
608                "cold": reuse.cold,
609                "disk_content_hit": reuse.disk_content_hits,
610                "render_cache_hit": reuse.render_cache_hits,
611                "unchanged_stub": reuse.unchanged_stubs,
612                "cross_file_ref": reuse.cross_file_refs,
613                "fresh_bypass": reuse.fresh_bypasses,
614                "stale": reuse.stale,
615                "variant_evicted": reuse.variant_evicted,
616                "policy_bypass": reuse.policy_bypasses,
617            },
618            "compressed_cache_hits": compressed_cache_hits,
619            "full_delivery_degraded": full_delivery_degraded,
620            "tokens_saved": cs.total_saved,
621            "tokens_original": cs.total_original,
622            "tool_calls": cs.tool_call_count,
623            "adoption_pct": cs.adoption.adoption_pct,
624            "ctx_tool_calls": cs.adoption.ctx_tool_calls,
625            "native_passthrough": cs.adoption.native_passthrough,
626            "started_at": started_at,
627            "updated_at": chrono::Local::now().to_rfc3339(),
628        });
629
630        if let Ok(dir) = crate::core::paths::state_dir() {
631            let _ = std::fs::write(dir.join("mcp-live.json"), live.to_string());
632        }
633    }
634
635    /// Persists a CEP (Cognitive Efficiency Protocol) score snapshot for analytics.
636    pub async fn record_cep_snapshot(&self) {
637        let cache = self.cache.read().await;
638        let calls = self.tool_calls.read().await;
639        let stats = cache.get_stats();
640        let complexity = crate::core::adaptive::classify_from_context(&cache);
641
642        let cs = Self::compute_cep_stats(&calls, stats, &complexity);
643
644        drop(cache);
645        drop(calls);
646
647        crate::core::stats::record_cep_session(
648            cs.cep_score,
649            cs.cache_hits,
650            cs.total_reads,
651            cs.total_original,
652            cs.total_compressed,
653            &cs.mode_counts,
654            cs.tool_call_count,
655            &cs.complexity,
656        );
657    }
658
659    fn activity_nudge(
660        session: &crate::core::session::SessionState,
661        calls: &[ToolCallRecord],
662    ) -> &'static str {
663        let last_doc_ts = session
664            .progress
665            .last()
666            .map(|p| p.timestamp)
667            .or_else(|| session.decisions.last().map(|d| d.timestamp))
668            .or_else(|| session.findings.last().map(|f| f.timestamp));
669
670        if let Some(ts) = last_doc_ts {
671            let age = chrono::Utc::now() - ts;
672            if age.num_minutes() < 8 {
673                return "";
674            }
675        }
676
677        let (weighted_score, significant_tools, shell_heavy, edit_heavy) =
678            Self::compute_activity_score(calls, last_doc_ts);
679
680        if weighted_score < 20 || significant_tools < 5 {
681            if session.stats.total_tool_calls >= 30
682                && session.decisions.is_empty()
683                && session.progress.is_empty()
684            {
685                return "\n[CHECKPOINT: please document current progress via ctx_session(action=\"task\") or ctx_knowledge(action=\"remember\")]";
686            }
687            return "";
688        }
689
690        if shell_heavy {
691            "\n[CHECKPOINT: multiple shell commands executed — any test results or findings worth persisting via ctx_knowledge(action=\"remember\")?]"
692        } else if edit_heavy {
693            "\n[CHECKPOINT: several files modified — document the architecture decision or pattern via ctx_knowledge(action=\"remember\")?]"
694        } else {
695            "\n[CHECKPOINT: significant work detected — consider persisting decisions via ctx_knowledge(action=\"remember\")]"
696        }
697    }
698
699    fn compute_activity_score(
700        calls: &[ToolCallRecord],
701        last_doc_ts: Option<chrono::DateTime<chrono::Utc>>,
702    ) -> (u32, u32, bool, bool) {
703        let mut weighted_score: u32 = 0;
704        let mut significant_tools: u32 = 0;
705        let mut shell_count: u32 = 0;
706        let mut edit_count: u32 = 0;
707
708        let since_doc: Vec<&ToolCallRecord> = if let Some(ts) = last_doc_ts {
709            let ts_str = ts.format("%Y-%m-%d %H:%M:%S").to_string();
710            calls.iter().filter(|c| c.timestamp > ts_str).collect()
711        } else {
712            calls.iter().collect()
713        };
714
715        for call in &since_doc {
716            let tool = call.tool.as_str();
717            let is_knowledge = tool == "ctx_knowledge" || tool == "ctx_session";
718            if is_knowledge {
719                weighted_score = 0;
720                significant_tools = 0;
721                shell_count = 0;
722                edit_count = 0;
723                continue;
724            }
725
726            let (weight, significant) = match tool {
727                "edit" | "write" | "str_replace" => {
728                    edit_count += 1;
729                    (4u32, true)
730                }
731                "ctx_shell" => {
732                    shell_count += 1;
733                    let is_test_or_build = call
734                        .mode
735                        .as_deref()
736                        .is_some_and(|m| m.contains("test") || m.contains("build"));
737                    if is_test_or_build {
738                        (3, true)
739                    } else {
740                        (2, true)
741                    }
742                }
743                "ctx_read" => {
744                    let is_cache_hit = call.saved_tokens > 0
745                        && call.original_tokens > 0
746                        && call.saved_tokens == call.original_tokens;
747                    if is_cache_hit { (0, false) } else { (1, false) }
748                }
749                _ => (1, false),
750            };
751
752            weighted_score = weighted_score.saturating_add(weight);
753            if significant {
754                significant_tools += 1;
755            }
756        }
757
758        let shell_heavy = shell_count >= 3 && shell_count > edit_count;
759        let edit_heavy = edit_count >= 3 && edit_count >= shell_count;
760
761        (weighted_score, significant_tools, shell_heavy, edit_heavy)
762    }
763}
764
765/// Persist science-module telemetry for the dashboard (separate process).
766pub(crate) fn write_science_live_stats() {
767    use crate::core::anti_interrupt::{InterruptionEvent, session_interruptions};
768    use crate::core::cognitive_gate;
769
770    let events = session_interruptions();
771    let mut redundant_reads = 0usize;
772    let mut bounce_waste = 0usize;
773    let mut prevented = 0usize;
774    for (event, was_prevented) in &events {
775        if *was_prevented {
776            prevented += 1;
777        }
778        match event {
779            InterruptionEvent::RedundantRead { .. } => redundant_reads += 1,
780            InterruptionEvent::BounceWaste { .. } => bounce_waste += 1,
781            _ => {}
782        }
783    }
784
785    let echo = crate::core::output_echo::load_stats();
786    let impact = crate::core::anti_interrupt::compute_impact();
787
788    let stats = serde_json::json!({
789        "cognitive_mode": if cognitive_gate::full_science_enabled() {
790            "full"
791        } else if cognitive_gate::basic_science_enabled() {
792            "basic"
793        } else {
794            "off"
795        },
796        "anti_interrupt": {
797            "events": events.len(),
798            "redundant_reads": redundant_reads,
799            "bounce_waste": bounce_waste,
800            "prevented": prevented,
801            "score": impact.score,
802            "focus_time_saved_minutes": impact.focus_time_saved_minutes,
803        },
804        "verbosity": {
805            "recommended_level": crate::core::verbosity::recommended_compression()
806                .map(|l| format!("{l:?}")),
807            "auto_applied": crate::core::verbosity::auto_apply_happened(),
808        },
809        "prefetch": {
810            "warmed": crate::core::context_prefetch::warmed_count(),
811            "skipped": crate::core::context_prefetch::skipped_count(),
812        },
813        "echo": {
814            "avg_ratio": echo.avg_ratio(50),
815            "window": echo.reports.len(),
816            "total_analyzed": echo.total_analyzed,
817        },
818        "updated_at": chrono::Local::now().to_rfc3339(),
819    });
820
821    if let Ok(dir) = crate::core::paths::state_dir() {
822        if let Ok(json) = serde_json::to_string_pretty(&stats) {
823            let _ = std::fs::write(dir.join("science-live.json"), json);
824        }
825    }
826}
827
828#[cfg(test)]
829mod activity_score_tests {
830    use super::*;
831
832    fn make_call(tool: &str, mode: Option<&str>) -> ToolCallRecord {
833        ToolCallRecord {
834            tool: tool.to_string(),
835            original_tokens: 100,
836            saved_tokens: 50,
837            mode: mode.map(String::from),
838            duration_ms: 10,
839            timestamp: "2026-01-01 12:00:00".to_string(),
840        }
841    }
842
843    fn make_cache_hit() -> ToolCallRecord {
844        ToolCallRecord {
845            tool: "ctx_read".to_string(),
846            original_tokens: 100,
847            saved_tokens: 100,
848            mode: Some("full".to_string()),
849            duration_ms: 1,
850            timestamp: "2026-01-01 12:00:00".to_string(),
851        }
852    }
853
854    #[test]
855    fn empty_calls_zero_score() {
856        let (score, sig, _, _) = LeanCtxServer::compute_activity_score(&[], None);
857        assert_eq!(score, 0);
858        assert_eq!(sig, 0);
859    }
860
861    #[test]
862    fn edits_have_highest_weight() {
863        let calls = vec![
864            make_call("edit", None),
865            make_call("edit", None),
866            make_call("edit", None),
867        ];
868        let (score, sig, _, edit_heavy) = LeanCtxServer::compute_activity_score(&calls, None);
869        assert_eq!(score, 12);
870        assert_eq!(sig, 3);
871        assert!(edit_heavy);
872    }
873
874    #[test]
875    fn shell_test_build_weight_three() {
876        let calls = vec![
877            make_call("ctx_shell", Some("test")),
878            make_call("ctx_shell", Some("build")),
879            make_call("ctx_shell", Some("test")),
880        ];
881        let (score, sig, shell_heavy, _) = LeanCtxServer::compute_activity_score(&calls, None);
882        assert_eq!(score, 9);
883        assert_eq!(sig, 3);
884        assert!(shell_heavy);
885    }
886
887    #[test]
888    fn cache_hits_zero_weight() {
889        let calls = vec![make_cache_hit(), make_cache_hit(), make_cache_hit()];
890        let (score, sig, _, _) = LeanCtxServer::compute_activity_score(&calls, None);
891        assert_eq!(score, 0);
892        assert_eq!(sig, 0);
893    }
894
895    #[test]
896    fn knowledge_call_resets_score() {
897        let calls = vec![
898            make_call("edit", None),
899            make_call("edit", None),
900            make_call("ctx_knowledge", None),
901            make_call("ctx_read", None),
902        ];
903        let (score, sig, _, _) = LeanCtxServer::compute_activity_score(&calls, None);
904        assert_eq!(score, 1);
905        assert_eq!(sig, 0);
906    }
907
908    #[test]
909    fn mixed_workflow_scoring() {
910        let calls = vec![
911            make_call("ctx_read", None),
912            make_call("ctx_read", None),
913            make_call("edit", None),
914            make_call("edit", None),
915            make_call("ctx_shell", Some("test output")),
916            make_call("ctx_shell", None),
917        ];
918        let (score, sig, _, _) = LeanCtxServer::compute_activity_score(&calls, None);
919        assert_eq!(score, 2 + 4 + 4 + 3 + 2);
920        assert_eq!(sig, 4);
921    }
922
923    #[test]
924    fn ocla_metrics_are_payload_free_and_saturating() {
925        let context = crate::core::ocla::OclaRequestContext {
926            request_id: "mcp-1".into(),
927            session_id: "session-1".into(),
928            agent_id: "agent-1".into(),
929            content_ref: "tool:ctx_read".into(),
930            tenant_id: None,
931            trace_id: "tr-unit".into(),
932            task_id: None,
933            parent_task_id: None,
934        };
935        let points = super::ocla_metric_points(&context, "ctx_read", 750, 125, 42);
936        assert_eq!(points.len(), 3);
937        assert_eq!(points[0].name, "mcp.tool.original_tokens");
938        assert_eq!(points[0].value_milli, 750_000);
939        assert_eq!(points[1].name, "mcp.tool.saved_tokens");
940        assert_eq!(points[1].value_milli, 125_000);
941        assert_eq!(points[2].name, "mcp.tool.duration_ms");
942        assert_eq!(points[2].value_milli, 42_000);
943        assert_eq!(points[0].dimensions["tool"], "ctx_read");
944        assert_eq!(points[0].context, context);
945        assert!(!points[0].dimensions.contains_key("path"));
946
947        let saturated = super::ocla_metric_points(
948            &points[0].context,
949            "ctx_shell",
950            usize::MAX,
951            usize::MAX,
952            u64::MAX,
953        );
954        assert!(saturated.iter().all(|point| point.value_milli == i64::MAX));
955    }
956}