Skip to main content

lean_ctx/tools/
server_metrics.rs

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