Skip to main content

lean_ctx/tools/
server_metrics.rs

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