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