Skip to main content

lean_ctx_server/tools/
server_metrics.rs

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