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
7fn fold_value_snapshot(
10 session: &mut crate::core::session::SessionState,
11) -> crate::core::value::snapshot::ValueSnapshot {
12 let security = crate::core::security_events::drain_pending();
13 session.stats.security.merge(&security);
14 crate::core::value::snapshot::ValueSnapshot::from_session(session)
15}
16
17fn publish_value_snapshot(snapshot: crate::core::value::snapshot::ValueSnapshot) {
19 if !crate::core::value::display_enabled() {
20 return;
21 }
22 drop(tokio::task::spawn_blocking(move || {
23 crate::core::value::snapshot::write_throttled(&snapshot);
24 crate::core::value::milestones::maybe_notify();
25 }));
26}
27
28fn ocla_metric_points(
34 context: &crate::core::ocla::OclaRequestContext,
35 tool: &str,
36 original: usize,
37 saved: usize,
38 duration_ms: u64,
39) -> Vec<crate::core::ocla::MetricPoint> {
40 let mut dimensions = std::collections::BTreeMap::new();
41 dimensions.insert("tool".to_string(), tool.to_string());
42 let original = metric_milli(original as u64);
43 let saved = metric_milli(saved as u64);
44 let duration = metric_milli(duration_ms);
45 vec![
46 crate::core::ocla::MetricPoint {
47 context: context.clone(),
48 name: "mcp.tool.original_tokens".to_string(),
49 value_milli: original,
50 dimensions: dimensions.clone(),
51 },
52 crate::core::ocla::MetricPoint {
53 context: context.clone(),
54 name: "mcp.tool.saved_tokens".to_string(),
55 value_milli: saved,
56 dimensions: dimensions.clone(),
57 },
58 crate::core::ocla::MetricPoint {
59 context: context.clone(),
60 name: "mcp.tool.duration_ms".to_string(),
61 value_milli: duration,
62 dimensions,
63 },
64 ]
65}
66
67fn metric_milli(value: u64) -> i64 {
68 i64::try_from(value.saturating_mul(1_000)).unwrap_or(i64::MAX)
69}
70
71impl LeanCtxServer {
72 pub async fn record_call(
74 &self,
75 tool: &str,
76 original: usize,
77 saved: usize,
78 mode: Option<String>,
79 ) {
80 self.record_call_with_timing(tool, original, saved, mode, 0)
81 .await;
82 }
83
84 pub async fn record_call_with_path(
88 &self,
89 tool: &str,
90 original: usize,
91 saved: usize,
92 mode: Option<String>,
93 path: Option<&str>,
94 duration_ms: u64,
95 ) {
96 self.record_call_with_timing_inner(tool, original, saved, mode, duration_ms, path)
97 .await;
98 }
99
100 pub async fn record_call_with_timing(
102 &self,
103 tool: &str,
104 original: usize,
105 saved: usize,
106 mode: Option<String>,
107 duration_ms: u64,
108 ) {
109 self.record_call_with_timing_inner(tool, original, saved, mode, duration_ms, None)
110 .await;
111 }
112
113 async fn record_call_with_timing_inner(
114 &self,
115 tool: &str,
116 original: usize,
117 saved: usize,
118 mode: Option<String>,
119 duration_ms: u64,
120 path: Option<&str>,
121 ) {
122 if let Some(agent_id) = self.presence_agent_id.read().await.clone()
123 && let Err(error) = crate::core::agents::AgentRegistry::heartbeat_persistent(&agent_id)
124 {
125 tracing::warn!("lean-ctx: failed to update MCP agent heartbeat: {error}");
126 }
127 crate::core::nudge::record_recovery_action(tool);
130 let ts = chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
131 let mut calls = self.tool_calls.write().await;
132 calls.push(ToolCallRecord {
133 tool: tool.to_string(),
134 original_tokens: original,
135 saved_tokens: saved,
136 mode: mode.clone(),
137 duration_ms,
138 timestamp: ts.clone(),
139 });
140
141 const MAX_TOOL_CALL_RECORDS: usize = 500;
142 if calls.len() > MAX_TOOL_CALL_RECORDS {
143 let excess = calls.len() - MAX_TOOL_CALL_RECORDS;
144 calls.drain(..excess);
145 }
146
147 if duration_ms > 0 || original > 0 {
152 Self::append_tool_call_log(tool, duration_ms, original, saved, mode.as_deref(), &ts);
153 }
154
155 crate::core::events::emit_tool_call(
156 tool,
157 original as u64,
158 saved as u64,
159 mode.clone(),
160 duration_ms,
161 path.map(ToString::to_string),
162 );
163
164 let output_tokens = original.saturating_sub(saved);
165 let session_id = self.session.read().await.id.clone();
166 let model = std::env::var("LEAN_CTX_MODEL").unwrap_or_else(|_| "unknown".to_string());
167 if let Err(error) = crate::core::measurement::MeasurementFramework::from_data_dir()
168 .record_tool_call(&session_id, tool, 0, original as u64, saved as u64, &model)
169 {
170 tracing::debug!("lean-ctx: measurement write failed: {error}");
171 }
172 crate::core::metering::MeterStore::append_best_effort(
173 crate::core::metering::MeterEntry::new(
174 tool,
175 original as u64,
176 output_tokens as u64,
177 saved as u64,
178 ),
179 );
180 crate::core::stats::record_at_turn(
181 tool,
182 original,
183 output_tokens,
184 crate::core::context_overhead::observed_turns(),
185 );
186 if tool == "ctx_shell" {
193 crate::core::savings_ledger::record_tool_event(
194 tool,
195 original,
196 output_tokens,
197 None,
198 None,
199 );
200 }
201
202 {
205 let session_r = self.session.read().await;
206 let agent_id = self
207 .presence_agent_id
208 .read()
209 .await
210 .clone()
211 .unwrap_or_default();
212 let ctx = crate::core::ocla::OclaRequestContext {
213 request_id: format!("mcp-{}", self.call_count.load(Ordering::Relaxed)),
214 session_id: session_r.id.clone(),
215 agent_id,
216 content_ref: path.map_or_else(|| format!("tool:{tool}"), |p| format!("file:{p}")),
217 tenant_id: None,
218 trace_id: "tr-unit".into(),
219 task_id: None,
220 parent_task_id: None,
221 };
222 drop(session_r);
223 let observation = crate::core::ocla::Observation {
224 context: ctx.clone(),
225 name: format!("tool_call:{tool}"),
226 attributes: std::collections::BTreeMap::from([
227 ("original_tokens".into(), original.to_string()),
228 ("saved_tokens".into(), saved.to_string()),
229 ("duration_ms".into(), duration_ms.to_string()),
230 ]),
231 };
232 let hook = crate::core::ocla::OclaRegistry::global()
233 .observation_hook
234 .as_ref();
235 let _ = hook.observe(observation).await;
236
237 let outcome = crate::core::ocla::Outcome {
238 context: ctx.clone(),
239 accepted: Some(saved > 0),
240 quality_score_milli: if original > 0 {
241 Some(((saved as u64 * 1000) / original as u64).min(1000) as u16)
242 } else {
243 None
244 },
245 outcome_ref: None,
246 };
247 let _ = crate::core::ocla::OclaRegistry::global()
248 .outcome_tracker
249 .record_outcome(outcome);
250
251 let metrics = ocla_metric_points(&ctx, tool, original, saved, duration_ms);
255 let _ = crate::core::ocla::OclaRegistry::global()
256 .metrics_exporter
257 .export_metrics(metrics)
258 .await;
259 }
260 let mut session = self.session.write().await;
261 session.record_tool_call(saved as u64, original as u64);
262 if tool == "ctx_shell" {
263 session.record_command();
264 }
265 let pending_save = if session.should_save() {
266 session.prepare_save().ok()
267 } else {
268 None
269 };
270 let value_snapshot = fold_value_snapshot(&mut session);
271 drop(calls);
272 drop(session);
273 publish_value_snapshot(value_snapshot);
274
275 let pro_count = self.pro_trigger_check_count.fetch_add(1, Ordering::Relaxed) + 1;
276 if pro_count.is_multiple_of(10) {
277 let signals = {
278 let session = self.session.read().await;
279 crate::core::pro_triggers::local_usage_signals(&session)
280 };
281 tokio::task::spawn_blocking(move || {
282 for nudge in crate::core::pro_triggers::evaluate_triggers(&signals) {
283 tracing::info!(kind = ?nudge.kind, message = %nudge.message, "lean-ctx Pro trigger fired");
284 }
285 });
286 }
287
288 if let Some(prepared) = pending_save {
289 drop(tokio::task::spawn_blocking(move || {
290 let _ = prepared.write_to_disk();
291 }));
292 }
293
294 self.write_mcp_live_stats().await;
295 write_science_live_stats();
296 }
297
298 pub async fn publish_value_snapshot(&self) {
302 let snapshot = {
303 let mut session = self.session.write().await;
304 fold_value_snapshot(&mut session)
305 };
306 publish_value_snapshot(snapshot);
307 }
308
309 pub fn increment_and_check(&self) -> bool {
311 let count = self.call_count.fetch_add(1, Ordering::Relaxed) + 1;
312 let interval = Self::checkpoint_interval_effective();
313 interval > 0 && count.is_multiple_of(interval)
314 }
315
316 pub async fn auto_checkpoint(&self) -> Option<String> {
318 let cache = self.cache.read().await;
319 if cache.get_all_entries().is_empty() {
320 return None;
321 }
322 let complexity = crate::core::adaptive::classify_from_context(&cache);
323 let checkpoint = ctx_compress::handle(&cache, false, CrpMode::effective());
324 drop(cache);
325
326 let mut session = self.session.write().await;
327 let pending_save = session.prepare_save().ok();
328 let session_summary = session.format_compact();
329 let has_insights = !session.findings.is_empty() || !session.decisions.is_empty();
330 let project_root = session.project_root.clone();
331 let summary_candidate = crate::core::session_summary::build_candidate(&session);
333 drop(session);
334
335 if let Some(prepared) = pending_save {
336 tokio::task::spawn_blocking(move || {
337 let _ = prepared.write_to_disk();
338 });
339 }
340
341 if has_insights && let Some(ref root) = project_root {
342 let root = root.clone();
343 std::thread::spawn(move || {
344 auto_consolidate_knowledge(&root);
345 });
346 }
347
348 if let Some(ref root) = project_root {
350 let root = root.clone();
351 std::thread::spawn(move || {
352 let _ =
353 crate::core::session_summary::maybe_record_periodic(&root, summary_candidate);
354 });
355 }
356
357 let multi_agent_block = self
358 .auto_multi_agent_checkpoint(project_root.as_ref())
359 .await;
360
361 self.record_call("ctx_compress", 0, 0, Some("auto".to_string()))
362 .await;
363
364 self.record_cep_snapshot().await;
365
366 if !crate::core::protocol::meta_visible() {
367 return None;
368 }
369
370 let doc_reminder = {
371 let session = self.session.read().await;
372 let calls = self.tool_calls.read().await;
373 Self::activity_nudge(&session, &calls)
374 };
375
376 Some(format!(
377 "{checkpoint}\n\n--- SESSION STATE ---\n{session_summary}\n\n{}{multi_agent_block}{doc_reminder}",
378 complexity.instruction_suffix()
379 ))
380 }
381
382 async fn auto_multi_agent_checkpoint(&self, project_root: Option<&String>) -> String {
383 let Some(root) = project_root else {
384 return String::new();
385 };
386
387 let registry = crate::core::agents::AgentRegistry::load_or_create();
388 let active = registry.list_active(Some(root));
389 if active.len() <= 1 {
390 return String::new();
391 }
392
393 let agent_id = self.agent_id.read().await;
394 let my_id = match agent_id.as_deref() {
395 Some(id) => id.to_string(),
396 None => return String::new(),
397 };
398 drop(agent_id);
399
400 let cache = self.cache.read().await;
401 let entries = cache.get_all_entries();
402 if !entries.is_empty() {
403 let mut by_access: Vec<_> = entries.iter().collect();
404 by_access.sort_by_key(|x| std::cmp::Reverse(x.1.read_count()));
405 let top_paths: Vec<&str> = by_access
406 .iter()
407 .take(5)
408 .map(|(key, _)| key.as_str())
409 .collect();
410 let paths_csv = top_paths.join(",");
411
412 let _ = ctx_share::handle(
413 "push",
414 Some(&my_id),
415 None,
416 Some(&paths_csv),
417 None,
418 &cache,
419 root,
420 );
421 }
422 drop(cache);
423
424 let pending_count = registry
425 .scratchpad
426 .iter()
427 .filter(|e| !e.read_by.contains(&my_id) && e.from_agent != my_id)
428 .count();
429
430 let shared_dir = crate::core::data_dir::lean_ctx_data_dir()
431 .unwrap_or_default()
432 .join("agents")
433 .join("shared");
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 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 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 adoption: Self::compute_adoption(calls),
537 }
538 }
539
540 fn compute_adoption(calls: &[ToolCallRecord]) -> super::server::AdoptionMetrics {
543 let ctx_tool_calls = calls.iter().filter(|c| c.tool.starts_with("ctx_")).count() as u64;
544 let total = calls.len() as u64;
545 let native_passthrough = total.saturating_sub(ctx_tool_calls);
546 let adoption_pct = if total > 0 {
547 ((ctx_tool_calls as f64 / total as f64) * 100.0).round() as u32
548 } else {
549 0
550 };
551 super::server::AdoptionMetrics {
552 ctx_tool_calls,
553 native_passthrough,
554 adoption_pct,
555 }
556 }
557
558 async fn write_mcp_live_stats(&self) {
559 let count = self.call_count.load(Ordering::Relaxed);
560 if count > 1 && !count.is_multiple_of(5) {
561 return;
562 }
563
564 let cache = self.cache.read().await;
565 let calls = self.tool_calls.read().await;
566 let stats = cache.get_stats();
567 let complexity = crate::core::adaptive::classify_from_context(&cache);
568 let dedup = crate::tools::ctx_read::dedup_hook::summary();
569
570 let cs = Self::compute_cep_stats(&calls, stats, &complexity);
571 let started_at = calls
572 .first()
573 .map(|c| c.timestamp.clone())
574 .unwrap_or_default();
575
576 drop(cache);
577 drop(calls);
578
579 crate::core::stats::record_cep_session(
585 cs.cep_score,
586 cs.cache_hits,
587 cs.total_reads,
588 cs.total_original,
589 cs.total_compressed,
590 &cs.mode_counts,
591 cs.tool_call_count,
592 &cs.complexity,
593 );
594
595 let reuse = crate::core::cache::reuse_snapshot();
600 let provider_reuse = crate::proxy::cache_attribution::snapshot();
601
602 let source_snapshot = crate::core::auto_mode_resolver::source_counts();
603 let compressed_cache_hits = source_snapshot
604 .iter()
605 .find(|(k, _)| *k == "compressed_cache_hit")
606 .map_or(0, |(_, v)| *v);
607 let full_delivery_degraded = source_snapshot
608 .iter()
609 .find(|(k, _)| *k == "full_delivery_degraded")
610 .map_or(0, |(_, v)| *v);
611
612 let live = serde_json::json!({
613 "cep_score": cs.cep_score,
614 "cache_utilization": cs.cache_util,
615 "mode_diversity": cs.mode_diversity,
616 "compression_rate": cs.compression_rate,
617 "task_complexity": cs.complexity,
618 "files_cached": cs.total_reads,
619 "total_reads": cs.total_reads,
620 "cache_hits": cs.cache_hits,
621 "dedup_reads": dedup.total_reads,
622 "dedup_hits": dedup.dedup_hits,
623 "dedup_tokens_saved": dedup.tokens_saved,
624 "read_reuse_rate": reuse.read_reuse_rate(),
625 "disk_reuse_rate": reuse.disk_reuse_rate(),
626 "provider_reuse_rate": provider_reuse.provider_reuse_rate(),
627 "read_reuse": {
628 "reused_renderings": reuse.reused_renderings,
629 "eligible_ctx_reads": reuse.eligible_ctx_reads,
630 },
631 "disk_reuse": {
632 "content_cache_hits": reuse.disk_content_hits,
633 "eligible_search_reads": reuse.eligible_search_reads,
634 },
635 "provider_reuse": {
636 "warm_reuses": provider_reuse.warm_reuses,
637 "ttl_lapses": provider_reuse.ttl_lapses,
638 "prefix_changes": provider_reuse.prefix_changes,
639 "eligible_requests": provider_reuse.eligible_provider_requests(),
640 },
641 "reuse_outcomes": {
642 "cold": reuse.cold,
643 "disk_content_hit": reuse.disk_content_hits,
644 "render_cache_hit": reuse.render_cache_hits,
645 "unchanged_stub": reuse.unchanged_stubs,
646 "cross_file_ref": reuse.cross_file_refs,
647 "fresh_bypass": reuse.fresh_bypasses,
648 "stale": reuse.stale,
649 "variant_evicted": reuse.variant_evicted,
650 "policy_bypass": reuse.policy_bypasses,
651 },
652 "compressed_cache_hits": compressed_cache_hits,
653 "full_delivery_degraded": full_delivery_degraded,
654 "tokens_saved": cs.total_saved,
655 "tokens_original": cs.total_original,
656 "tool_calls": cs.tool_call_count,
657 "adoption_pct": cs.adoption.adoption_pct,
658 "ctx_tool_calls": cs.adoption.ctx_tool_calls,
659 "native_passthrough": cs.adoption.native_passthrough,
660 "started_at": started_at,
661 "updated_at": chrono::Local::now().to_rfc3339(),
662 });
663
664 if let Ok(dir) = crate::core::paths::state_dir() {
665 let _ = std::fs::write(dir.join("mcp-live.json"), live.to_string());
666 }
667 }
668
669 pub async fn record_cep_snapshot(&self) {
671 let cache = self.cache.read().await;
672 let calls = self.tool_calls.read().await;
673 let stats = cache.get_stats();
674 let complexity = crate::core::adaptive::classify_from_context(&cache);
675
676 let cs = Self::compute_cep_stats(&calls, stats, &complexity);
677
678 drop(cache);
679 drop(calls);
680
681 crate::core::stats::record_cep_session(
682 cs.cep_score,
683 cs.cache_hits,
684 cs.total_reads,
685 cs.total_original,
686 cs.total_compressed,
687 &cs.mode_counts,
688 cs.tool_call_count,
689 &cs.complexity,
690 );
691 }
692
693 fn activity_nudge(
694 session: &crate::core::session::SessionState,
695 calls: &[ToolCallRecord],
696 ) -> &'static str {
697 let last_doc_ts = session
698 .progress
699 .last()
700 .map(|p| p.timestamp)
701 .or_else(|| session.decisions.last().map(|d| d.timestamp))
702 .or_else(|| session.findings.last().map(|f| f.timestamp));
703
704 if let Some(ts) = last_doc_ts {
705 let age = chrono::Utc::now() - ts;
706 if age.num_minutes() < 8 {
707 return "";
708 }
709 }
710
711 let (weighted_score, significant_tools, shell_heavy, edit_heavy) =
712 Self::compute_activity_score(calls, last_doc_ts);
713
714 if weighted_score < 20 || significant_tools < 5 {
715 if session.stats.total_tool_calls >= 30
716 && session.decisions.is_empty()
717 && session.progress.is_empty()
718 {
719 return "\n[CHECKPOINT: please document current progress via ctx_session(action=\"task\") or ctx_knowledge(action=\"remember\")]";
720 }
721 return "";
722 }
723
724 if shell_heavy {
725 "\n[CHECKPOINT: multiple shell commands executed — any test results or findings worth persisting via ctx_knowledge(action=\"remember\")?]"
726 } else if edit_heavy {
727 "\n[CHECKPOINT: several files modified — document the architecture decision or pattern via ctx_knowledge(action=\"remember\")?]"
728 } else {
729 "\n[CHECKPOINT: significant work detected — consider persisting decisions via ctx_knowledge(action=\"remember\")]"
730 }
731 }
732
733 fn compute_activity_score(
734 calls: &[ToolCallRecord],
735 last_doc_ts: Option<chrono::DateTime<chrono::Utc>>,
736 ) -> (u32, u32, bool, bool) {
737 let mut weighted_score: u32 = 0;
738 let mut significant_tools: u32 = 0;
739 let mut shell_count: u32 = 0;
740 let mut edit_count: u32 = 0;
741
742 let since_doc: Vec<&ToolCallRecord> = if let Some(ts) = last_doc_ts {
743 let ts_str = ts.format("%Y-%m-%d %H:%M:%S").to_string();
744 calls.iter().filter(|c| c.timestamp > ts_str).collect()
745 } else {
746 calls.iter().collect()
747 };
748
749 for call in &since_doc {
750 let tool = call.tool.as_str();
751 let is_knowledge = tool == "ctx_knowledge" || tool == "ctx_session";
752 if is_knowledge {
753 weighted_score = 0;
754 significant_tools = 0;
755 shell_count = 0;
756 edit_count = 0;
757 continue;
758 }
759
760 let (weight, significant) = match tool {
761 "edit" | "write" | "str_replace" => {
762 edit_count += 1;
763 (4u32, true)
764 }
765 "ctx_shell" => {
766 shell_count += 1;
767 let is_test_or_build = call
768 .mode
769 .as_deref()
770 .is_some_and(|m| m.contains("test") || m.contains("build"));
771 if is_test_or_build {
772 (3, true)
773 } else {
774 (2, true)
775 }
776 }
777 "ctx_read" => {
778 let is_cache_hit = call.saved_tokens > 0
779 && call.original_tokens > 0
780 && call.saved_tokens == call.original_tokens;
781 if is_cache_hit { (0, false) } else { (1, false) }
782 }
783 _ => (1, false),
784 };
785
786 weighted_score = weighted_score.saturating_add(weight);
787 if significant {
788 significant_tools += 1;
789 }
790 }
791
792 let shell_heavy = shell_count >= 3 && shell_count > edit_count;
793 let edit_heavy = edit_count >= 3 && edit_count >= shell_count;
794
795 (weighted_score, significant_tools, shell_heavy, edit_heavy)
796 }
797}
798
799pub(crate) fn write_science_live_stats() {
801 use crate::core::anti_interrupt::{InterruptionEvent, session_interruptions};
802 use crate::core::cognitive_gate;
803
804 let events = session_interruptions();
805 let mut redundant_reads = 0usize;
806 let mut bounce_waste = 0usize;
807 let mut prevented = 0usize;
808 for (event, was_prevented) in &events {
809 if *was_prevented {
810 prevented += 1;
811 }
812 match event {
813 InterruptionEvent::RedundantRead { .. } => redundant_reads += 1,
814 InterruptionEvent::BounceWaste { .. } => bounce_waste += 1,
815 _ => {}
816 }
817 }
818
819 let echo = crate::core::output_echo::load_stats();
820 let impact = crate::core::anti_interrupt::compute_impact();
821
822 let stats = serde_json::json!({
823 "cognitive_mode": if cognitive_gate::full_science_enabled() {
824 "full"
825 } else if cognitive_gate::basic_science_enabled() {
826 "basic"
827 } else {
828 "off"
829 },
830 "anti_interrupt": {
831 "events": events.len(),
832 "redundant_reads": redundant_reads,
833 "bounce_waste": bounce_waste,
834 "prevented": prevented,
835 "score": impact.score,
836 "focus_time_saved_minutes": impact.focus_time_saved_minutes,
837 },
838 "verbosity": {
839 "recommended_level": crate::core::verbosity::recommended_compression()
840 .map(|l| format!("{l:?}")),
841 "auto_applied": crate::core::verbosity::auto_apply_happened(),
842 },
843 "prefetch": {
844 "warmed": crate::core::context_prefetch::warmed_count(),
845 "skipped": crate::core::context_prefetch::skipped_count(),
846 },
847 "echo": {
848 "avg_ratio": echo.avg_ratio(50),
849 "window": echo.reports.len(),
850 "total_analyzed": echo.total_analyzed,
851 },
852 "updated_at": chrono::Local::now().to_rfc3339(),
853 });
854
855 if let Ok(dir) = crate::core::paths::state_dir() {
856 if let Ok(json) = serde_json::to_string_pretty(&stats) {
857 let _ = std::fs::write(dir.join("science-live.json"), json);
858 }
859 }
860}
861
862#[cfg(test)]
863mod activity_score_tests {
864 use super::*;
865
866 fn make_call(tool: &str, mode: Option<&str>) -> ToolCallRecord {
867 ToolCallRecord {
868 tool: tool.to_string(),
869 original_tokens: 100,
870 saved_tokens: 50,
871 mode: mode.map(String::from),
872 duration_ms: 10,
873 timestamp: "2026-01-01 12:00:00".to_string(),
874 }
875 }
876
877 fn make_cache_hit() -> ToolCallRecord {
878 ToolCallRecord {
879 tool: "ctx_read".to_string(),
880 original_tokens: 100,
881 saved_tokens: 100,
882 mode: Some("full".to_string()),
883 duration_ms: 1,
884 timestamp: "2026-01-01 12:00:00".to_string(),
885 }
886 }
887
888 #[test]
889 fn empty_calls_zero_score() {
890 let (score, sig, _, _) = LeanCtxServer::compute_activity_score(&[], None);
891 assert_eq!(score, 0);
892 assert_eq!(sig, 0);
893 }
894
895 #[test]
896 fn edits_have_highest_weight() {
897 let calls = vec![
898 make_call("edit", None),
899 make_call("edit", None),
900 make_call("edit", None),
901 ];
902 let (score, sig, _, edit_heavy) = LeanCtxServer::compute_activity_score(&calls, None);
903 assert_eq!(score, 12);
904 assert_eq!(sig, 3);
905 assert!(edit_heavy);
906 }
907
908 #[test]
909 fn shell_test_build_weight_three() {
910 let calls = vec![
911 make_call("ctx_shell", Some("test")),
912 make_call("ctx_shell", Some("build")),
913 make_call("ctx_shell", Some("test")),
914 ];
915 let (score, sig, shell_heavy, _) = LeanCtxServer::compute_activity_score(&calls, None);
916 assert_eq!(score, 9);
917 assert_eq!(sig, 3);
918 assert!(shell_heavy);
919 }
920
921 #[test]
922 fn cache_hits_zero_weight() {
923 let calls = vec![make_cache_hit(), make_cache_hit(), make_cache_hit()];
924 let (score, sig, _, _) = LeanCtxServer::compute_activity_score(&calls, None);
925 assert_eq!(score, 0);
926 assert_eq!(sig, 0);
927 }
928
929 #[test]
930 fn knowledge_call_resets_score() {
931 let calls = vec![
932 make_call("edit", None),
933 make_call("edit", None),
934 make_call("ctx_knowledge", None),
935 make_call("ctx_read", None),
936 ];
937 let (score, sig, _, _) = LeanCtxServer::compute_activity_score(&calls, None);
938 assert_eq!(score, 1);
939 assert_eq!(sig, 0);
940 }
941
942 #[test]
943 fn mixed_workflow_scoring() {
944 let calls = vec![
945 make_call("ctx_read", None),
946 make_call("ctx_read", None),
947 make_call("edit", None),
948 make_call("edit", None),
949 make_call("ctx_shell", Some("test output")),
950 make_call("ctx_shell", None),
951 ];
952 let (score, sig, _, _) = LeanCtxServer::compute_activity_score(&calls, None);
953 assert_eq!(score, 2 + 4 + 4 + 3 + 2);
954 assert_eq!(sig, 4);
955 }
956
957 #[test]
958 fn ocla_metrics_are_payload_free_and_saturating() {
959 let context = crate::core::ocla::OclaRequestContext {
960 request_id: "mcp-1".into(),
961 session_id: "session-1".into(),
962 agent_id: "agent-1".into(),
963 content_ref: "tool:ctx_read".into(),
964 tenant_id: None,
965 trace_id: "tr-unit".into(),
966 task_id: None,
967 parent_task_id: None,
968 };
969 let points = super::ocla_metric_points(&context, "ctx_read", 750, 125, 42);
970 assert_eq!(points.len(), 3);
971 assert_eq!(points[0].name, "mcp.tool.original_tokens");
972 assert_eq!(points[0].value_milli, 750_000);
973 assert_eq!(points[1].name, "mcp.tool.saved_tokens");
974 assert_eq!(points[1].value_milli, 125_000);
975 assert_eq!(points[2].name, "mcp.tool.duration_ms");
976 assert_eq!(points[2].value_milli, 42_000);
977 assert_eq!(points[0].dimensions["tool"], "ctx_read");
978 assert_eq!(points[0].context, context);
979 assert!(!points[0].dimensions.contains_key("path"));
980
981 let saturated = super::ocla_metric_points(
982 &points[0].context,
983 "ctx_shell",
984 usize::MAX,
985 usize::MAX,
986 u64::MAX,
987 );
988 assert!(saturated.iter().all(|point| point.value_milli == i64::MAX));
989 }
990}