Skip to main content

lean_ctx/core/
tool_health.rs

1//! `lean-ctx tools health` — does every advertised MCP tool and injected rule
2//! earn its always-on token cost? (#848)
3//!
4//! lean-ctx ships ~80 MCP tools plus injected rules files; the thesis is "every
5//! token earns its place". This report cross-references the *fixed cost* of each
6//! advertised tool schema and rules file with *recorded usage* (the
7//! [`CostStore`] post-dispatch ledger) and flags "rot":
8//!
9//! * tools that cost schema tokens every session but are never called,
10//! * rules files that bill the same guidance to a client more than once,
11//! * stale knowledge facts (old and never retrieved).
12//!
13//! Deterministic and local-only: it reads existing on-disk telemetry, sorts
14//! everything stably, and adds **no** new hot-path cost (`last_used` rides the
15//! existing cost-attribution write). It never auto-applies anything — every
16//! finding is a suggestion the operator acts on explicitly.
17
18use std::path::Path;
19
20use serde::Serialize;
21
22use crate::core::a2a::cost_attribution::CostStore;
23use crate::core::context_overhead::tool_tokens;
24use crate::core::rules_overhead::{RulesFileCost, collect_rules_files, duplicate_clients};
25
26/// A tool whose schema costs >= this many tokens *and* is used for <1% of all
27/// calls is flagged `LowUse` — expensive surface that barely pays its way.
28const LOW_USE_TOKEN_FLOOR: usize = 150;
29/// Share of total recorded calls below which a heavy tool counts as `LowUse`.
30const LOW_USE_CALL_SHARE: f64 = 0.01;
31/// A fact older than this (days) that was never retrieved is a prune candidate.
32const STALE_FACT_DAYS: i64 = 30;
33
34#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
35#[serde(rename_all = "snake_case")]
36pub enum ToolStatus {
37    /// Called regularly — earns its schema cost.
38    Active,
39    /// Used, but rarely, while carrying a heavy schema.
40    LowUse,
41    /// Never called in the recorded history — pure rot.
42    Unused,
43    /// No usage telemetry yet — cannot judge.
44    Unknown,
45}
46
47impl ToolStatus {
48    #[must_use]
49    pub fn label(self) -> &'static str {
50        match self {
51            ToolStatus::Active => "active",
52            ToolStatus::LowUse => "low-use",
53            ToolStatus::Unused => "unused",
54            ToolStatus::Unknown => "unknown",
55        }
56    }
57}
58
59#[derive(Debug, Clone, Serialize)]
60pub struct ToolEntry {
61    pub name: String,
62    pub schema_tokens: usize,
63    pub calls: u64,
64    pub last_used: Option<String>,
65    pub status: ToolStatus,
66    pub action: String,
67    /// Value-per-token signal: recorded calls per 1 000 always-on schema tokens.
68    /// The telemetry fallback for #961 when no per-tool outcome eval exists.
69    pub value_per_1k_tokens: f64,
70}
71
72#[derive(Debug, Clone, Serialize)]
73pub struct RuleEntry {
74    pub path: String,
75    pub file_tokens: usize,
76    pub lean_ctx_tokens: usize,
77    pub carries_full: bool,
78    pub clients: Vec<String>,
79    pub action: String,
80}
81
82#[derive(Debug, Clone, Serialize, Default)]
83pub struct KnowledgeHealth {
84    pub total_facts: usize,
85    pub active_facts: usize,
86    pub stale_facts: usize,
87    pub action: String,
88}
89
90#[derive(Debug, Clone, Serialize)]
91pub struct ToolHealthReport {
92    pub tool_profile: String,
93    pub advertised_tools: usize,
94    pub tool_schema_tokens: usize,
95    pub instruction_tokens: usize,
96    pub rules_tokens: usize,
97    /// Tool schemas + MCP instructions + every auto-loaded rules file.
98    pub fixed_total_tokens: usize,
99    pub has_usage_data: bool,
100    pub total_recorded_calls: u64,
101    pub unused_tools: usize,
102    /// Schema tokens spent every session on tools that are never called.
103    pub unused_tool_tokens: usize,
104    /// Low-value tools (unused or low-use) the operator should consider disabling.
105    pub disable_candidates: Vec<String>,
106    /// Schema tokens reclaimable by disabling every [`Self::disable_candidates`].
107    pub reclaimable_tokens: usize,
108    /// Aggregated, copy-pasteable "consider disabling X" recommendation.
109    pub disable_action: String,
110    /// Outcome signal from the latest `eval footprint` artifact (#959), if any:
111    /// whether the tool-schema element as a whole earns its tokens.
112    pub footprint_note: Option<String>,
113    pub tools: Vec<ToolEntry>,
114    pub rules: Vec<RuleEntry>,
115    pub duplicate_clients: Vec<(String, usize)>,
116    pub knowledge: KnowledgeHealth,
117}
118
119fn classify(has_usage: bool, calls: u64, schema_tokens: usize, total_calls: u64) -> ToolStatus {
120    if !has_usage {
121        return ToolStatus::Unknown;
122    }
123    if calls == 0 {
124        return ToolStatus::Unused;
125    }
126    if schema_tokens >= LOW_USE_TOKEN_FLOOR
127        && (calls as f64) < (total_calls as f64) * LOW_USE_CALL_SHARE
128    {
129        return ToolStatus::LowUse;
130    }
131    ToolStatus::Active
132}
133
134/// Recorded calls per 1 000 always-on schema tokens — higher = better value.
135fn value_per_1k(calls: u64, schema_tokens: usize) -> f64 {
136    if schema_tokens == 0 {
137        0.0
138    } else {
139        calls as f64 / schema_tokens as f64 * 1000.0
140    }
141}
142
143fn action_for(status: ToolStatus, calls: u64, schema_tokens: usize) -> String {
144    match status {
145        ToolStatus::Unused => format!(
146            "never called — trim via a leaner tool profile to reclaim {schema_tokens} tok/session"
147        ),
148        ToolStatus::LowUse => {
149            format!("rarely used ({calls}×) yet costs {schema_tokens} tok/session — review")
150        }
151        ToolStatus::Active | ToolStatus::Unknown => String::new(),
152    }
153}
154
155/// Pure report builder — every input is supplied, so it is fully deterministic
156/// and unit-testable without touching disk or the clock.
157#[must_use]
158pub fn build_report(
159    advertised: &[rmcp::model::Tool],
160    usage: &CostStore,
161    rules: &[RulesFileCost],
162    duplicates: Vec<(String, usize)>,
163    instruction_tokens: usize,
164    tool_profile: String,
165    knowledge: KnowledgeHealth,
166) -> ToolHealthReport {
167    let total_recorded_calls: u64 = usage.tools.values().map(|t| t.total_calls).sum();
168    let has_usage_data = total_recorded_calls > 0;
169
170    let mut tools: Vec<ToolEntry> = advertised
171        .iter()
172        .map(|t| {
173            let name = t.name.as_ref().to_string();
174            let schema_tokens = tool_tokens(t);
175            let (calls, last_used) = usage
176                .tools
177                .get(&name)
178                .map_or((0, None), |c| (c.total_calls, c.last_used.clone()));
179            let status = classify(has_usage_data, calls, schema_tokens, total_recorded_calls);
180            let action = action_for(status, calls, schema_tokens);
181            ToolEntry {
182                name,
183                schema_tokens,
184                calls,
185                last_used,
186                status,
187                action,
188                value_per_1k_tokens: value_per_1k(calls, schema_tokens),
189            }
190        })
191        .collect();
192    tools.sort_by(|a, b| a.name.cmp(&b.name));
193
194    let tool_schema_tokens: usize = tools.iter().map(|t| t.schema_tokens).sum();
195    let unused_tools = tools
196        .iter()
197        .filter(|t| t.status == ToolStatus::Unused)
198        .count();
199    let unused_tool_tokens = tools
200        .iter()
201        .filter(|t| t.status == ToolStatus::Unused)
202        .map(|t| t.schema_tokens)
203        .sum();
204
205    // Low-value tools the operator should consider disabling: never-called or
206    // heavy-but-rarely-called. `tools` is already name-sorted → deterministic.
207    let low_value = |t: &&ToolEntry| matches!(t.status, ToolStatus::Unused | ToolStatus::LowUse);
208    let disable_candidates: Vec<String> = tools
209        .iter()
210        .filter(low_value)
211        .map(|t| t.name.clone())
212        .collect();
213    let reclaimable_tokens: usize = tools
214        .iter()
215        .filter(low_value)
216        .map(|t| t.schema_tokens)
217        .sum();
218    let disable_action = if disable_candidates.is_empty() {
219        String::new()
220    } else {
221        format!(
222            "consider disabling {} low-value tool(s) to reclaim {reclaimable_tokens} tok/session: {} — apply via `tools_disabled` in config or a leaner `tool_profile`",
223            disable_candidates.len(),
224            disable_candidates.join(", ")
225        )
226    };
227
228    let dup_clients: std::collections::HashSet<&str> =
229        duplicates.iter().map(|(c, _)| c.as_str()).collect();
230    let rules_out: Vec<RuleEntry> = rules
231        .iter()
232        .map(|r| {
233            let is_dup = r.carries_full && r.clients.iter().any(|c| dup_clients.contains(c));
234            let action = if is_dup {
235                "duplicate full lean-ctx source — run `lean-ctx rules dedup --apply`".to_string()
236            } else {
237                String::new()
238            };
239            RuleEntry {
240                path: r.path.clone(),
241                file_tokens: r.file_tokens,
242                lean_ctx_tokens: r.lean_ctx_tokens,
243                carries_full: r.carries_full,
244                clients: r.clients.iter().map(|c| (*c).to_string()).collect(),
245                action,
246            }
247        })
248        .collect();
249
250    let rules_tokens: usize = rules_out.iter().map(|r| r.file_tokens).sum();
251    let fixed_total_tokens = tool_schema_tokens + instruction_tokens + rules_tokens;
252
253    ToolHealthReport {
254        tool_profile,
255        advertised_tools: tools.len(),
256        tool_schema_tokens,
257        instruction_tokens,
258        rules_tokens,
259        fixed_total_tokens,
260        has_usage_data,
261        total_recorded_calls,
262        unused_tools,
263        unused_tool_tokens,
264        disable_candidates,
265        reclaimable_tokens,
266        disable_action,
267        footprint_note: None,
268        tools,
269        rules: rules_out,
270        duplicate_clients: duplicates,
271        knowledge,
272    }
273}
274
275/// Reads the latest `eval footprint` artifact (#959) and summarises whether the
276/// tool-schema element earns its tokens — the per-outcome signal that complements
277/// the telemetry-based [`value_per_1k`]. Returns `None` when no run is on disk.
278fn latest_footprint_note() -> Option<String> {
279    use crate::core::eval_ab::footprint::{FootprintReport, InjectedElement};
280
281    let dir = crate::core::data_dir::lean_ctx_data_dir()
282        .ok()?
283        .join("eval");
284    let mut artifacts: Vec<(std::time::SystemTime, std::path::PathBuf)> = std::fs::read_dir(&dir)
285        .ok()?
286        .flatten()
287        .filter_map(|e| {
288            let path = e.path();
289            let name = path.file_name()?.to_str()?.to_string();
290            let is_json = path
291                .extension()
292                .and_then(|x| x.to_str())
293                .is_some_and(|x| x.eq_ignore_ascii_case("json"));
294            if name.starts_with("footprint-report-v1_") && is_json {
295                Some((e.metadata().ok()?.modified().ok()?, path))
296            } else {
297                None
298            }
299        })
300        .collect();
301    artifacts.sort_by_key(|a| a.0);
302    let (_, path) = artifacts.last()?;
303
304    let raw = std::fs::read_to_string(path).ok()?;
305    let report: FootprintReport = serde_json::from_str(&raw).ok()?;
306    let schemas = report
307        .elements
308        .iter()
309        .find(|e| e.element == InjectedElement::ToolSchemas)?;
310    let verdict = if schemas.prune_recommended {
311        "PRUNE-recommended"
312    } else {
313        "earns its cost"
314    };
315    Some(format!(
316        "footprint eval ({}): tool schemas {verdict} (Δpass {:+.0}%, cost {} tok)",
317        report.suite,
318        schemas.pass_rate_delta * 100.0,
319        schemas.token_cost
320    ))
321}
322
323fn resolve_tool_profile() -> String {
324    let cfg = crate::core::config::Config::load();
325    if crate::server::tool_visibility::explicit_profile(&cfg) {
326        cfg.tool_profile_effective().as_str().to_string()
327    } else {
328        "lean (default)".to_string()
329    }
330}
331
332fn knowledge_health(project: &Path) -> KnowledgeHealth {
333    let Some(knowledge) =
334        crate::core::knowledge::ProjectKnowledge::load(&project.to_string_lossy())
335    else {
336        return KnowledgeHealth::default();
337    };
338    let total = knowledge.facts.len();
339    let current: Vec<_> = knowledge.facts.iter().filter(|f| f.is_current()).collect();
340    let now = chrono::Utc::now();
341    let stale = current
342        .iter()
343        .filter(|f| (now - f.created_at).num_days() > STALE_FACT_DAYS && f.retrieval_count == 0)
344        .count();
345    let action = if stale > 0 {
346        format!(
347            "{stale} stale fact(s) (>{STALE_FACT_DAYS}d, never retrieved) — review with `lean-ctx knowledge`"
348        )
349    } else {
350        String::new()
351    };
352    KnowledgeHealth {
353        total_facts: total,
354        active_facts: current.len(),
355        stale_facts: stale,
356        action,
357    }
358}
359
360/// Gathers real on-disk telemetry for `home`/`project` and builds the report.
361#[must_use]
362pub fn compute(home: &Path, project: &Path) -> ToolHealthReport {
363    let advertised = crate::server::tool_visibility::advertised_tool_defs_default();
364    let usage = CostStore::load();
365    let rules = collect_rules_files(home, project);
366    let duplicates = duplicate_clients(&rules);
367    let instructions = crate::instructions::build_instructions(crate::tools::CrpMode::effective());
368    let instruction_tokens = crate::core::tokens::count_tokens(&instructions);
369    let knowledge = knowledge_health(project);
370    let mut report = build_report(
371        &advertised,
372        &usage,
373        &rules,
374        duplicates,
375        instruction_tokens,
376        resolve_tool_profile(),
377        knowledge,
378    );
379    report.footprint_note = latest_footprint_note();
380    report
381}
382
383#[cfg(test)]
384mod tests {
385    use super::*;
386    use crate::core::a2a::cost_attribution::ToolCost;
387
388    fn tool(name: &'static str) -> rmcp::model::Tool {
389        crate::tool_defs::tool_def(
390            name,
391            "a representative description used to give the schema some token weight",
392            serde_json::json!({
393                "type": "object",
394                "properties": { "path": { "type": "string", "description": "file path" } }
395            }),
396        )
397    }
398
399    fn usage_with(calls: &[(&str, u64)]) -> CostStore {
400        let mut store = CostStore::default();
401        for (name, n) in calls {
402            store.tools.insert(
403                (*name).to_string(),
404                ToolCost {
405                    tool_name: (*name).to_string(),
406                    total_calls: *n,
407                    last_used: Some("2026-06-01T00:00:00+00:00".to_string()),
408                    ..Default::default()
409                },
410            );
411        }
412        store
413    }
414
415    #[test]
416    fn classify_unknown_without_usage_history() {
417        assert_eq!(classify(false, 0, 500, 0), ToolStatus::Unknown);
418        assert_eq!(classify(false, 9, 500, 0), ToolStatus::Unknown);
419    }
420
421    #[test]
422    fn classify_unused_when_history_exists_but_tool_never_called() {
423        assert_eq!(classify(true, 0, 500, 1000), ToolStatus::Unused);
424    }
425
426    #[test]
427    fn classify_low_use_for_expensive_rarely_called_tool() {
428        // 1 call out of 10_000, heavy schema → low-use.
429        assert_eq!(classify(true, 1, 400, 10_000), ToolStatus::LowUse);
430        // Same rarity but a cheap schema → still active (not worth flagging).
431        assert_eq!(classify(true, 1, 50, 10_000), ToolStatus::Active);
432    }
433
434    #[test]
435    fn classify_active_for_well_used_tool() {
436        assert_eq!(classify(true, 500, 400, 1000), ToolStatus::Active);
437    }
438
439    #[test]
440    fn build_report_flags_unused_and_sorts_tools() {
441        let advertised = vec![tool("ctx_search"), tool("ctx_read"), tool("ctx_shell")];
442        // History exists (ctx_read used), ctx_search/ctx_shell never called.
443        let usage = usage_with(&[("ctx_read", 40)]);
444        let report = build_report(
445            &advertised,
446            &usage,
447            &[],
448            Vec::new(),
449            100,
450            "lean (default)".to_string(),
451            KnowledgeHealth::default(),
452        );
453
454        assert!(report.has_usage_data);
455        assert_eq!(report.total_recorded_calls, 40);
456        // Sorted alphabetically.
457        let names: Vec<&str> = report.tools.iter().map(|t| t.name.as_str()).collect();
458        assert_eq!(names, vec!["ctx_read", "ctx_search", "ctx_shell"]);
459        // Two unused tools, each contributing its schema tokens.
460        assert_eq!(report.unused_tools, 2);
461        assert!(report.unused_tool_tokens > 0);
462        let read = report.tools.iter().find(|t| t.name == "ctx_read").unwrap();
463        assert_eq!(read.status, ToolStatus::Active);
464        assert!(read.last_used.is_some());
465        // Fixed total = tool schemas + instructions(100) + rules(0).
466        assert_eq!(
467            report.fixed_total_tokens,
468            report.tool_schema_tokens + 100 + report.rules_tokens
469        );
470    }
471
472    #[test]
473    fn value_per_1k_rewards_cheap_well_used_tools() {
474        assert!(value_per_1k(100, 50) > value_per_1k(100, 500));
475        assert_eq!(value_per_1k(0, 100), 0.0);
476        assert_eq!(value_per_1k(10, 0), 0.0, "no schema cost → no division");
477    }
478
479    #[test]
480    fn build_report_recommends_disabling_low_value_tools() {
481        let advertised = vec![tool("ctx_read"), tool("ctx_search"), tool("ctx_shell")];
482        // History exists; ctx_search + ctx_shell never called → disable candidates.
483        let usage = usage_with(&[("ctx_read", 40)]);
484        let report = build_report(
485            &advertised,
486            &usage,
487            &[],
488            Vec::new(),
489            0,
490            "lean (default)".to_string(),
491            KnowledgeHealth::default(),
492        );
493        assert!(
494            report
495                .disable_candidates
496                .contains(&"ctx_search".to_string())
497        );
498        assert!(report.disable_candidates.contains(&"ctx_shell".to_string()));
499        assert!(
500            !report.disable_candidates.contains(&"ctx_read".to_string()),
501            "an active tool is never a disable candidate"
502        );
503        assert!(report.reclaimable_tokens > 0);
504        assert!(report.disable_action.contains("consider disabling"));
505        assert!(
506            report.footprint_note.is_none(),
507            "the pure builder never reads disk artifacts"
508        );
509        let read = report.tools.iter().find(|t| t.name == "ctx_read").unwrap();
510        assert!(read.value_per_1k_tokens > 0.0);
511    }
512
513    #[test]
514    fn build_report_unknown_status_without_history() {
515        let advertised = vec![tool("ctx_read")];
516        let report = build_report(
517            &advertised,
518            &CostStore::default(),
519            &[],
520            Vec::new(),
521            0,
522            "lean (default)".to_string(),
523            KnowledgeHealth::default(),
524        );
525        assert!(!report.has_usage_data);
526        assert_eq!(report.unused_tools, 0, "never flag rot without history");
527        assert_eq!(report.tools[0].status, ToolStatus::Unknown);
528    }
529
530    #[test]
531    fn build_report_marks_duplicate_rules() {
532        let rules = vec![
533            RulesFileCost {
534                path: "a/.cursor/rules/lean-ctx.mdc".into(),
535                file_tokens: 200,
536                lean_ctx_tokens: 200,
537                carries_full: true,
538                clients: vec!["cursor"],
539            },
540            RulesFileCost {
541                path: "a/.cursorrules".into(),
542                file_tokens: 150,
543                lean_ctx_tokens: 150,
544                carries_full: true,
545                clients: vec!["cursor"],
546            },
547        ];
548        let dups = duplicate_clients(&rules);
549        let report = build_report(
550            &[],
551            &CostStore::default(),
552            &rules,
553            dups,
554            0,
555            "lean (default)".to_string(),
556            KnowledgeHealth::default(),
557        );
558        assert_eq!(report.rules.len(), 2);
559        assert!(
560            report.rules.iter().all(|r| r.action.contains("dedup")),
561            "both cursor full sources flagged as duplicates"
562        );
563        assert_eq!(report.rules_tokens, 350);
564    }
565
566    #[test]
567    fn compute_smoke_runs_and_counts_advertised_tools() {
568        // `advertised_tool_defs_default()` reads process-global env (tool
569        // profile, unified/full mode) and config, so it is not pure. Isolate the
570        // data dir and serialize on the shared test-env lock — otherwise a
571        // concurrent env-mutating test (e.g. the minimal-arm overhead test that
572        // sets LEAN_CTX_TOOL_PROFILE=minimal) can flip the profile between the two
573        // calls below, making the counts disagree. Latent race; surfaced once a
574        // slower sibling test shifted parallel scheduling (#945).
575        let _iso = crate::core::data_dir::isolated_data_dir();
576        let tmp = tempfile::tempdir().unwrap();
577        let report = compute(tmp.path(), tmp.path());
578        let expected = crate::server::tool_visibility::advertised_tool_defs_default().len();
579        assert_eq!(report.advertised_tools, expected);
580        assert!(report.tool_schema_tokens > 0);
581        assert!(report.fixed_total_tokens >= report.tool_schema_tokens);
582    }
583}