Skip to main content

lean_ctx/core/
telemetry_features.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! The closed registry of feature codes for telemetry (3.11.1+).
4//!
5//! A code names *what* LeanCTX did, never with what: `cli.pack.export`,
6//! `index.graph`. CLI arguments are matched against the fixed lists below and
7//! only the matching literal is counted, so a path, file name, query or any
8//! other user input can never become a code. Commands on the hot path of
9//! every shell command or editor event are not counted at all; the daily
10//! usage record already covers that work.
11
12/// Top-level commands counted as `cli.<command>`. Aliases map to the first
13/// spelling the dispatcher accepts.
14const COMMANDS: &[(&str, &[&str])] = &[
15    ("badge", &[]),
16    ("shell", &["--shell"]),
17    ("gain", &[]),
18    ("spend", &[]),
19    ("savings", &[]),
20    ("learning", &[]),
21    ("autopilot", &[]),
22    ("conformance", &["selftest"]),
23    ("health", &[]),
24    ("quality_lab", &["quality-lab"]),
25    ("billing", &[]),
26    ("finops", &[]),
27    ("roi", &[]),
28    ("output_savings", &["output-savings"]),
29    ("value_report", &["value-report"]),
30    ("evidence_export", &["evidence-export"]),
31    ("evidence", &[]),
32    ("shadow", &[]),
33    ("triage", &[]),
34    ("scenario", &[]),
35    ("measure", &[]),
36    ("token_report", &["token-report", "report-tokens"]),
37    ("pack", &[]),
38    ("migrate", &[]),
39    ("policy", &[]),
40    ("addon", &["addons"]),
41    ("plugin", &["plugins"]),
42    ("embeddings", &[]),
43    ("model", &[]),
44    ("gpu", &["enable-gpu"]),
45    ("rules", &[]),
46    ("proof", &["prove"]),
47    ("value", &[]),
48    ("claude_mod", &["claude-mod"]),
49    ("inspect", &[]),
50    ("snapshot", &[]),
51    ("verify", &[]),
52    ("eval", &[]),
53    ("verify_cache", &["verify-cache", "cache-selftest"]),
54    ("visualize", &[]),
55    ("audit", &[]),
56    ("compliance", &[]),
57    ("agent", &[]),
58    ("instructions", &[]),
59    ("index", &[]),
60    ("semantic_search", &["semantic-search", "search-code"]),
61    ("explore", &[]),
62    ("repomap", &["repo-map"]),
63    ("cep", &[]),
64    ("demo", &[]),
65    // `cockpit` is the Cockpit's name since 3.12; it stays one feature with
66    // its `dashboard` alias under the existing `cli.dashboard` code.
67    ("dashboard", &["cockpit"]),
68    ("team", &[]),
69    ("provider", &[]),
70    ("serve", &[]),
71    ("watch", &[]),
72    ("proxy", &[]),
73    ("daemon", &[]),
74    ("init", &[]),
75    ("setup", &[]),
76    ("onboard", &[]),
77    ("install", &[]),
78    ("bootstrap", &[]),
79    ("wrap", &[]),
80    ("unwrap", &[]),
81    ("status", &[]),
82    ("cognitive", &[]),
83    ("deps", &[]),
84    ("discover", &[]),
85    ("engine", &[]),
86    ("ghost", &[]),
87    ("filter", &[]),
88    ("heatmap", &[]),
89    ("graph", &[]),
90    ("smells", &[]),
91    ("session", &[]),
92    ("ledger", &[]),
93    ("ocla", &[]),
94    ("control", &["context-control"]),
95    ("plan", &["context-plan"]),
96    ("compile", &["context-compile"]),
97    ("import", &[]),
98    ("checkpoints", &[]),
99    ("knowledge", &[]),
100    ("kit", &["kits"]),
101    ("skillify", &[]),
102    ("summary", &[]),
103    ("overview", &[]),
104    ("compress", &[]),
105    ("wrapped", &[]),
106    ("sessions", &["session-store"]),
107    ("benchmark", &[]),
108    ("benchmark_run", &["benchmark-run", "bench-run"]),
109    ("calibrate", &[]),
110    ("compact", &[]),
111    ("profile", &[]),
112    ("tools", &[]),
113    ("config", &[]),
114    ("allow", &[]),
115    ("allow_path", &["allow-path"]),
116    ("security", &[]),
117    ("yolo", &[]),
118    ("secure", &["lockdown"]),
119    ("trust", &[]),
120    ("untrust", &[]),
121    ("stats", &[]),
122    ("introspect", &[]),
123    ("cache", &[]),
124    ("theme", &[]),
125    ("enterprise", &[]),
126    ("tee", &[]),
127    ("terse", &["compression"]),
128    ("slow_log", &["slow-log"]),
129    ("debug_log", &["debug-log"]),
130    ("editor_bridge", &["editor-bridge"]),
131    ("update", &["--self-update"]),
132    ("restart", &[]),
133    ("stop", &[]),
134    ("doctor", &[]),
135    ("harden", &[]),
136    ("export_rules", &["export-rules"]),
137    ("gotchas", &["bugs"]),
138    ("learn", &[]),
139    ("report_issue", &["report-issue", "report"]),
140    ("uninstall", &[]),
141    ("safety_levels", &["safety-levels", "safety"]),
142    ("cheat", &["cheatsheet", "cheat-sheet"]),
143    ("login", &[]),
144    ("register", &[]),
145    ("sync", &[]),
146    ("contribute", &[]),
147    ("telemetry", &[]),
148    ("cloud", &[]),
149    ("upgrade", &[]),
150];
151
152/// Second words counted as `cli.<command>.<verb>` when they follow a counted
153/// command. Product verbs only; anything else is counted as the bare command.
154const VERBS: &[&str] = &[
155    "add",
156    "apply",
157    "auto-load",
158    "build",
159    "build-full",
160    "build-semantic",
161    "check",
162    "checkpoint-inspect",
163    "checkpoint-seal",
164    "clean",
165    "clear",
166    "create",
167    "delete",
168    "delete-remote",
169    "diff",
170    "disable",
171    "doctor",
172    "enable",
173    "explain",
174    "export",
175    "export-html",
176    "gc",
177    "get",
178    "impact",
179    "import",
180    "info",
181    "init",
182    "inspect",
183    "install",
184    "list",
185    "login",
186    "logout",
187    "ls",
188    "migrate",
189    "neighbors",
190    "off",
191    "on",
192    "parity",
193    "path",
194    "prune",
195    "publish",
196    "pull",
197    "push",
198    "rebuild",
199    "receive",
200    "related",
201    "remove",
202    "reset",
203    "restart",
204    "rm",
205    "rollback",
206    "run",
207    "search",
208    "send",
209    "set",
210    "show",
211    "snapshot",
212    "start",
213    "status",
214    "stop",
215    "symbol",
216    "uninstall",
217    "update",
218    "verify",
219    "warm",
220    "watch",
221];
222
223/// Commands that run on every shell command, editor event or prompt render.
224/// Counting them would add a locked file write to the hot path.
225const NOT_COUNTED: &[&str] = &[
226    "-c",
227    "exec",
228    "-t",
229    "--track",
230    "hook",
231    "__complete",
232    "completions",
233    "mcp",
234    "read",
235    "call",
236    "diff",
237    "grep",
238    "glob",
239    "find",
240    "ls",
241    "raw",
242    "bypass",
243    "statusline",
244    "editor-signal",
245    "editor-session",
246    "prompt-segment",
247    "git-trailer",
248    "help",
249    "--help",
250    "-h",
251    "codex-protected",
252    "dev-install",
253    "codesign-setup",
254    "forgot-password",
255];
256
257fn segment(word: &str) -> String {
258    word.trim_start_matches('-').replace('-', "_")
259}
260
261/// The feature code for a CLI invocation, or `None` when it is not counted.
262/// A `--dry-run` promises to write nothing, the usage counter included.
263#[must_use]
264pub fn cli_code(args: &[String]) -> Option<String> {
265    let first = args.get(1)?.as_str();
266    if NOT_COUNTED.contains(&first) || args.iter().skip(2).any(|a| a == "--dry-run") {
267        return None;
268    }
269    let (command, _) = COMMANDS.iter().find(|(name, aliases)| {
270        *name == first || segment(first) == *name || aliases.contains(&first)
271    })?;
272    let verb = args
273        .get(2)
274        .map(String::as_str)
275        .filter(|word| VERBS.contains(word))
276        .map(segment);
277    let code = match verb {
278        Some(verb) => format!("cli.{command}.{verb}"),
279        None => format!("cli.{command}"),
280    };
281    crate::core::telemetry_v2::valid_feature_code(&code).then_some(code)
282}
283
284/// Counts a CLI invocation. Never fails the command.
285pub fn record_cli(args: &[String]) {
286    if let Some(code) = cli_code(args) {
287        let _ = crate::core::telemetry_aggregate::record_feature(&code, true);
288    }
289}
290
291/// Background features with a fixed code.
292#[derive(Debug, Clone, Copy, PartialEq, Eq)]
293pub enum Feature {
294    GraphIndex,
295    Bm25Index,
296    SemanticIndex,
297}
298
299impl Feature {
300    #[must_use]
301    pub fn code(self) -> &'static str {
302        match self {
303            Self::GraphIndex => "index.graph",
304            Self::Bm25Index => "index.bm25",
305            Self::SemanticIndex => "index.semantic",
306        }
307    }
308}
309
310/// Counts one run of a background feature and whether it succeeded.
311pub fn record(feature: Feature, ok: bool) {
312    let _ = crate::core::telemetry_aggregate::record_feature(feature.code(), ok);
313}
314
315/// An MCP server that completed the client handshake.
316const MCP_SESSION: &str = "mcp.session";
317/// One that then ended without answering a single tool call: a client that
318/// starts every configured server (often in a throwaway container) and whose
319/// agent never uses LeanCTX. Counted, not hidden, so Ops can tell such starts
320/// from real sessions.
321const MCP_SESSION_EMPTY: &str = "mcp.session.empty";
322/// Every other ended session gets exactly one of three outcomes (3.11.5+):
323/// no tool call failed;
324const MCP_SESSION_CLEAN: &str = "mcp.session.clean";
325/// calls failed, but the last call of every tool succeeded;
326const MCP_SESSION_RECOVERED: &str = "mcp.session.recovered";
327/// the last call of some tool failed. Also counted as a failure when one of
328/// those last failures lies on LeanCTX's side rather than the caller's.
329const MCP_SESSION_UNRESOLVED: &str = "mcp.session.unresolved";
330/// Calls made right after a failed call of the same tool; a failure when the
331/// retry failed again.
332const MCP_SESSION_RETRY: &str = "mcp.session.retry";
333
334/// Counts an MCP server start after the handshake.
335pub fn record_mcp_session_start() {
336    let _ = crate::core::telemetry_aggregate::record_feature(MCP_SESSION, true);
337}
338
339/// A failure LeanCTX itself has to fix: a timeout, an unavailable
340/// dependency, a size limit or an unclassified error. Bad input, a missing
341/// file, a stale edit, a permission or a deliberate policy block are the
342/// caller's to resolve.
343fn leanctx_side(kind: crate::core::telemetry_failure::FailureKind) -> bool {
344    use crate::core::telemetry_failure::FailureKind;
345    matches!(
346        kind,
347        FailureKind::Timeout
348            | FailureKind::Unavailable
349            | FailureKind::TooLarge
350            | FailureKind::Other
351    )
352}
353
354/// The `(code, count, failures)` tallies an ending MCP server adds.
355fn mcp_session_end_tallies(
356    outcome: &crate::core::telemetry::SessionOutcome,
357) -> Vec<(&'static str, u64, u64)> {
358    if outcome.calls == 0 {
359        return vec![(MCP_SESSION_EMPTY, 1, 0)];
360    }
361    let ending = if outcome.failures == 0 {
362        (MCP_SESSION_CLEAN, 1, 0)
363    } else if outcome.unresolved.is_empty() {
364        (MCP_SESSION_RECOVERED, 1, 0)
365    } else {
366        let ours = outcome.unresolved.iter().any(|kind| leanctx_side(*kind));
367        (MCP_SESSION_UNRESOLVED, 1, u64::from(ours))
368    };
369    vec![
370        ending,
371        (MCP_SESSION_RETRY, outcome.retries, outcome.retry_failures),
372    ]
373}
374
375/// Counts how an MCP session ended. Every exit path (transport closed, parent
376/// gone, idle exit) calls this before its final send; only the first call of
377/// a process counts.
378pub fn record_mcp_session_end() {
379    static ENDED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
380    if ENDED.swap(true, std::sync::atomic::Ordering::SeqCst) {
381        return;
382    }
383    let outcome = crate::core::telemetry::global_metrics().session_outcome();
384    let _ =
385        crate::core::telemetry_aggregate::record_feature_counts(&mcp_session_end_tallies(&outcome));
386}
387
388#[cfg(test)]
389mod tests {
390    use super::*;
391
392    fn args(words: &[&str]) -> Vec<String> {
393        std::iter::once("lean-ctx")
394            .chain(words.iter().copied())
395            .map(str::to_string)
396            .collect()
397    }
398
399    #[test]
400    fn dry_runs_are_not_counted() {
401        for words in [
402            &["setup", "--dry-run"][..],
403            &["onboard", "--agents", "cursor", "--dry-run"][..],
404            &["update", "--dry-run"][..],
405            &["uninstall", "--dry-run"][..],
406        ] {
407            assert_eq!(cli_code(&args(words)), None, "{words:?}");
408        }
409        assert_eq!(cli_code(&args(&["setup"])).as_deref(), Some("cli.setup"));
410    }
411
412    #[test]
413    fn commands_and_registry_verbs_become_codes() {
414        assert_eq!(
415            cli_code(&args(&["pack", "export", "my-secret-pack"])).as_deref(),
416            Some("cli.pack.export")
417        );
418        assert_eq!(
419            cli_code(&args(&["pack", "import", "/home/a/x.ctxpkg"])).as_deref(),
420            Some("cli.pack.import")
421        );
422        assert_eq!(
423            cli_code(&args(&["graph", "build"])).as_deref(),
424            Some("cli.graph.build")
425        );
426        assert_eq!(
427            cli_code(&args(&["index", "build-full"])).as_deref(),
428            Some("cli.index.build_full")
429        );
430        assert_eq!(
431            cli_code(&args(&["quality-lab"])).as_deref(),
432            Some("cli.quality_lab")
433        );
434        assert_eq!(
435            cli_code(&args(&["report-tokens"])).as_deref(),
436            Some("cli.token_report")
437        );
438        assert_eq!(
439            cli_code(&args(&["--self-update"])).as_deref(),
440            Some("cli.update")
441        );
442        assert_eq!(
443            cli_code(&args(&["cockpit"])).as_deref(),
444            Some("cli.dashboard")
445        );
446        assert_eq!(
447            cli_code(&args(&["telemetry", "off"])).as_deref(),
448            Some("cli.telemetry.off")
449        );
450    }
451
452    #[test]
453    fn user_input_never_becomes_part_of_a_code() {
454        assert_eq!(
455            cli_code(&args(&["knowledge", "remember", "the db password"])).as_deref(),
456            Some("cli.knowledge")
457        );
458        assert_eq!(
459            cli_code(&args(&["graph", "/Users/a/private-repo"])).as_deref(),
460            Some("cli.graph")
461        );
462        assert_eq!(
463            cli_code(&args(&["semantic-search", "export"])).as_deref(),
464            Some("cli.semantic_search.export")
465        );
466        assert!(cli_code(&args(&["my-custom-thing"])).is_none());
467        assert!(cli_code(&args(&[])).is_none());
468    }
469
470    #[test]
471    fn hot_path_commands_are_not_counted() {
472        for command in [
473            "-c",
474            "exec",
475            "hook",
476            "read",
477            "grep",
478            "statusline",
479            "mcp",
480            "__complete",
481        ] {
482            assert!(cli_code(&args(&[command, "build"])).is_none(), "{command}");
483        }
484    }
485
486    #[test]
487    fn every_registry_code_is_a_valid_wire_code() {
488        for (command, aliases) in COMMANDS {
489            for spelling in std::iter::once(*command).chain(aliases.iter().copied()) {
490                let code = cli_code(&args(&[spelling])).unwrap_or_else(|| panic!("{spelling}"));
491                assert_eq!(code, format!("cli.{command}"));
492                for verb in VERBS {
493                    assert!(
494                        cli_code(&args(&[spelling, verb])).is_some(),
495                        "{spelling} {verb}"
496                    );
497                }
498            }
499        }
500        for feature in [
501            Feature::GraphIndex,
502            Feature::Bm25Index,
503            Feature::SemanticIndex,
504        ] {
505            assert!(crate::core::telemetry_v2::valid_feature_code(
506                feature.code()
507            ));
508        }
509        for code in [
510            MCP_SESSION,
511            MCP_SESSION_EMPTY,
512            MCP_SESSION_CLEAN,
513            MCP_SESSION_RECOVERED,
514            MCP_SESSION_UNRESOLVED,
515            MCP_SESSION_RETRY,
516        ] {
517            assert!(
518                crate::core::telemetry_v2::valid_feature_code(code),
519                "{code}"
520            );
521        }
522    }
523
524    #[test]
525    fn every_ended_session_gets_exactly_one_outcome() {
526        use crate::core::telemetry::SessionOutcome;
527        use crate::core::telemetry_failure::FailureKind;
528        let outcome = |calls, failures, unresolved: Vec<FailureKind>| SessionOutcome {
529            calls,
530            failures,
531            unresolved,
532            retries: 0,
533            retry_failures: 0,
534        };
535        assert_eq!(
536            mcp_session_end_tallies(&outcome(0, 0, vec![])),
537            [("mcp.session.empty", 1, 0)]
538        );
539        assert_eq!(
540            mcp_session_end_tallies(&outcome(4, 0, vec![]))[0],
541            ("mcp.session.clean", 1, 0)
542        );
543        assert_eq!(
544            mcp_session_end_tallies(&outcome(4, 2, vec![]))[0],
545            ("mcp.session.recovered", 1, 0)
546        );
547        assert_eq!(
548            mcp_session_end_tallies(&outcome(4, 2, vec![FailureKind::NotFound]))[0],
549            ("mcp.session.unresolved", 1, 0),
550            "a missing file is the caller's to resolve"
551        );
552        assert_eq!(
553            mcp_session_end_tallies(&outcome(
554                4,
555                2,
556                vec![FailureKind::NotFound, FailureKind::Timeout]
557            ))[0],
558            ("mcp.session.unresolved", 1, 1),
559            "a timeout is LeanCTX's"
560        );
561    }
562
563    #[test]
564    fn retries_ride_along_with_the_outcome() {
565        let outcome = crate::core::telemetry::SessionOutcome {
566            calls: 9,
567            failures: 3,
568            unresolved: vec![],
569            retries: 3,
570            retry_failures: 1,
571        };
572        assert_eq!(
573            mcp_session_end_tallies(&outcome),
574            [("mcp.session.recovered", 1, 0), ("mcp.session.retry", 3, 1)]
575        );
576    }
577}