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    ("dashboard", &[]),
66    ("team", &[]),
67    ("provider", &[]),
68    ("serve", &[]),
69    ("watch", &[]),
70    ("proxy", &[]),
71    ("daemon", &[]),
72    ("init", &[]),
73    ("setup", &[]),
74    ("onboard", &[]),
75    ("install", &[]),
76    ("bootstrap", &[]),
77    ("wrap", &[]),
78    ("unwrap", &[]),
79    ("status", &[]),
80    ("cognitive", &[]),
81    ("deps", &[]),
82    ("discover", &[]),
83    ("engine", &[]),
84    ("ghost", &[]),
85    ("filter", &[]),
86    ("heatmap", &[]),
87    ("graph", &[]),
88    ("smells", &[]),
89    ("session", &[]),
90    ("ledger", &[]),
91    ("ocla", &[]),
92    ("control", &["context-control"]),
93    ("plan", &["context-plan"]),
94    ("compile", &["context-compile"]),
95    ("import", &[]),
96    ("checkpoints", &[]),
97    ("knowledge", &[]),
98    ("kit", &["kits"]),
99    ("skillify", &[]),
100    ("summary", &[]),
101    ("overview", &[]),
102    ("compress", &[]),
103    ("wrapped", &[]),
104    ("sessions", &["session-store"]),
105    ("benchmark", &[]),
106    ("benchmark_run", &["benchmark-run", "bench-run"]),
107    ("calibrate", &[]),
108    ("pair", &[]),
109    ("compact", &[]),
110    ("profile", &[]),
111    ("tools", &[]),
112    ("config", &[]),
113    ("allow", &[]),
114    ("allow_path", &["allow-path"]),
115    ("security", &[]),
116    ("yolo", &[]),
117    ("secure", &["lockdown"]),
118    ("trust", &[]),
119    ("untrust", &[]),
120    ("stats", &[]),
121    ("introspect", &[]),
122    ("cache", &[]),
123    ("theme", &[]),
124    ("enterprise", &[]),
125    ("tee", &[]),
126    ("terse", &["compression"]),
127    ("slow_log", &["slow-log"]),
128    ("debug_log", &["debug-log"]),
129    ("editor_bridge", &["editor-bridge"]),
130    ("update", &["--self-update"]),
131    ("restart", &[]),
132    ("stop", &[]),
133    ("doctor", &[]),
134    ("harden", &[]),
135    ("export_rules", &["export-rules"]),
136    ("gotchas", &["bugs"]),
137    ("learn", &[]),
138    ("buddy", &["pet"]),
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#[must_use]
263pub fn cli_code(args: &[String]) -> Option<String> {
264    let first = args.get(1)?.as_str();
265    if NOT_COUNTED.contains(&first) {
266        return None;
267    }
268    let (command, _) = COMMANDS.iter().find(|(name, aliases)| {
269        *name == first || segment(first) == *name || aliases.contains(&first)
270    })?;
271    let verb = args
272        .get(2)
273        .map(String::as_str)
274        .filter(|word| VERBS.contains(word))
275        .map(segment);
276    let code = match verb {
277        Some(verb) => format!("cli.{command}.{verb}"),
278        None => format!("cli.{command}"),
279    };
280    crate::core::telemetry_v2::valid_feature_code(&code).then_some(code)
281}
282
283/// Counts a CLI invocation. Never fails the command.
284pub fn record_cli(args: &[String]) {
285    if let Some(code) = cli_code(args) {
286        let _ = crate::core::telemetry_aggregate::record_feature(&code, true);
287    }
288}
289
290/// Background features with a fixed code.
291#[derive(Debug, Clone, Copy, PartialEq, Eq)]
292pub enum Feature {
293    GraphIndex,
294    Bm25Index,
295    SemanticIndex,
296}
297
298impl Feature {
299    #[must_use]
300    pub fn code(self) -> &'static str {
301        match self {
302            Self::GraphIndex => "index.graph",
303            Self::Bm25Index => "index.bm25",
304            Self::SemanticIndex => "index.semantic",
305        }
306    }
307}
308
309/// Counts one run of a background feature and whether it succeeded.
310pub fn record(feature: Feature, ok: bool) {
311    let _ = crate::core::telemetry_aggregate::record_feature(feature.code(), ok);
312}
313
314/// An MCP server that completed the client handshake.
315const MCP_SESSION: &str = "mcp.session";
316/// One that then ended without answering a single tool call: a client that
317/// starts every configured server (often in a throwaway container) and whose
318/// agent never uses LeanCTX. Counted, not hidden, so Ops can tell such starts
319/// from real sessions.
320const MCP_SESSION_EMPTY: &str = "mcp.session.empty";
321
322/// Counts an MCP server start after the handshake.
323pub fn record_mcp_session_start() {
324    let _ = crate::core::telemetry_aggregate::record_feature(MCP_SESSION, true);
325}
326
327/// The code an ending MCP server adds, given its tool calls.
328fn mcp_session_end_code(tool_calls: u64) -> Option<&'static str> {
329    (tool_calls == 0).then_some(MCP_SESSION_EMPTY)
330}
331
332/// Counts the end of an MCP server that answered no tool call. Every exit path
333/// (transport closed, parent gone, idle exit) calls this before its final
334/// send; only the first call of a process counts.
335pub fn record_mcp_session_end() {
336    static ENDED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
337    if ENDED.swap(true, std::sync::atomic::Ordering::SeqCst) {
338        return;
339    }
340    let tool_calls = crate::core::telemetry::global_metrics()
341        .tool_calls_total
342        .load(std::sync::atomic::Ordering::Relaxed);
343    if let Some(code) = mcp_session_end_code(tool_calls) {
344        let _ = crate::core::telemetry_aggregate::record_feature(code, true);
345    }
346}
347
348#[cfg(test)]
349mod tests {
350    use super::*;
351
352    fn args(words: &[&str]) -> Vec<String> {
353        std::iter::once("lean-ctx")
354            .chain(words.iter().copied())
355            .map(str::to_string)
356            .collect()
357    }
358
359    #[test]
360    fn commands_and_registry_verbs_become_codes() {
361        assert_eq!(
362            cli_code(&args(&["pack", "export", "my-secret-pack"])).as_deref(),
363            Some("cli.pack.export")
364        );
365        assert_eq!(
366            cli_code(&args(&["pack", "import", "/home/a/x.ctxpkg"])).as_deref(),
367            Some("cli.pack.import")
368        );
369        assert_eq!(
370            cli_code(&args(&["graph", "build"])).as_deref(),
371            Some("cli.graph.build")
372        );
373        assert_eq!(
374            cli_code(&args(&["index", "build-full"])).as_deref(),
375            Some("cli.index.build_full")
376        );
377        assert_eq!(
378            cli_code(&args(&["quality-lab"])).as_deref(),
379            Some("cli.quality_lab")
380        );
381        assert_eq!(
382            cli_code(&args(&["report-tokens"])).as_deref(),
383            Some("cli.token_report")
384        );
385        assert_eq!(
386            cli_code(&args(&["--self-update"])).as_deref(),
387            Some("cli.update")
388        );
389        assert_eq!(
390            cli_code(&args(&["telemetry", "off"])).as_deref(),
391            Some("cli.telemetry.off")
392        );
393    }
394
395    #[test]
396    fn user_input_never_becomes_part_of_a_code() {
397        assert_eq!(
398            cli_code(&args(&["knowledge", "remember", "the db password"])).as_deref(),
399            Some("cli.knowledge")
400        );
401        assert_eq!(
402            cli_code(&args(&["graph", "/Users/a/private-repo"])).as_deref(),
403            Some("cli.graph")
404        );
405        assert_eq!(
406            cli_code(&args(&["semantic-search", "export"])).as_deref(),
407            Some("cli.semantic_search.export")
408        );
409        assert!(cli_code(&args(&["my-custom-thing"])).is_none());
410        assert!(cli_code(&args(&[])).is_none());
411    }
412
413    #[test]
414    fn hot_path_commands_are_not_counted() {
415        for command in [
416            "-c",
417            "exec",
418            "hook",
419            "read",
420            "grep",
421            "statusline",
422            "mcp",
423            "__complete",
424        ] {
425            assert!(cli_code(&args(&[command, "build"])).is_none(), "{command}");
426        }
427    }
428
429    #[test]
430    fn every_registry_code_is_a_valid_wire_code() {
431        for (command, aliases) in COMMANDS {
432            for spelling in std::iter::once(*command).chain(aliases.iter().copied()) {
433                let code = cli_code(&args(&[spelling])).unwrap_or_else(|| panic!("{spelling}"));
434                assert_eq!(code, format!("cli.{command}"));
435                for verb in VERBS {
436                    assert!(
437                        cli_code(&args(&[spelling, verb])).is_some(),
438                        "{spelling} {verb}"
439                    );
440                }
441            }
442        }
443        for feature in [
444            Feature::GraphIndex,
445            Feature::Bm25Index,
446            Feature::SemanticIndex,
447        ] {
448            assert!(crate::core::telemetry_v2::valid_feature_code(
449                feature.code()
450            ));
451        }
452        for code in [MCP_SESSION, MCP_SESSION_EMPTY] {
453            assert!(
454                crate::core::telemetry_v2::valid_feature_code(code),
455                "{code}"
456            );
457        }
458    }
459
460    #[test]
461    fn only_a_session_without_tool_calls_is_marked_empty() {
462        assert_eq!(mcp_session_end_code(0), Some("mcp.session.empty"));
463        assert_eq!(mcp_session_end_code(1), None);
464        assert_eq!(mcp_session_end_code(u64::MAX), None);
465    }
466}