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