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#[cfg(test)]
315mod tests {
316    use super::*;
317
318    fn args(words: &[&str]) -> Vec<String> {
319        std::iter::once("lean-ctx")
320            .chain(words.iter().copied())
321            .map(str::to_string)
322            .collect()
323    }
324
325    #[test]
326    fn commands_and_registry_verbs_become_codes() {
327        assert_eq!(
328            cli_code(&args(&["pack", "export", "my-secret-pack"])).as_deref(),
329            Some("cli.pack.export")
330        );
331        assert_eq!(
332            cli_code(&args(&["pack", "import", "/home/a/x.ctxpkg"])).as_deref(),
333            Some("cli.pack.import")
334        );
335        assert_eq!(
336            cli_code(&args(&["graph", "build"])).as_deref(),
337            Some("cli.graph.build")
338        );
339        assert_eq!(
340            cli_code(&args(&["index", "build-full"])).as_deref(),
341            Some("cli.index.build_full")
342        );
343        assert_eq!(
344            cli_code(&args(&["quality-lab"])).as_deref(),
345            Some("cli.quality_lab")
346        );
347        assert_eq!(
348            cli_code(&args(&["report-tokens"])).as_deref(),
349            Some("cli.token_report")
350        );
351        assert_eq!(
352            cli_code(&args(&["--self-update"])).as_deref(),
353            Some("cli.update")
354        );
355        assert_eq!(
356            cli_code(&args(&["telemetry", "off"])).as_deref(),
357            Some("cli.telemetry.off")
358        );
359    }
360
361    #[test]
362    fn user_input_never_becomes_part_of_a_code() {
363        assert_eq!(
364            cli_code(&args(&["knowledge", "remember", "the db password"])).as_deref(),
365            Some("cli.knowledge")
366        );
367        assert_eq!(
368            cli_code(&args(&["graph", "/Users/a/private-repo"])).as_deref(),
369            Some("cli.graph")
370        );
371        assert_eq!(
372            cli_code(&args(&["semantic-search", "export"])).as_deref(),
373            Some("cli.semantic_search.export")
374        );
375        assert!(cli_code(&args(&["my-custom-thing"])).is_none());
376        assert!(cli_code(&args(&[])).is_none());
377    }
378
379    #[test]
380    fn hot_path_commands_are_not_counted() {
381        for command in [
382            "-c",
383            "exec",
384            "hook",
385            "read",
386            "grep",
387            "statusline",
388            "mcp",
389            "__complete",
390        ] {
391            assert!(cli_code(&args(&[command, "build"])).is_none(), "{command}");
392        }
393    }
394
395    #[test]
396    fn every_registry_code_is_a_valid_wire_code() {
397        for (command, aliases) in COMMANDS {
398            for spelling in std::iter::once(*command).chain(aliases.iter().copied()) {
399                let code = cli_code(&args(&[spelling])).unwrap_or_else(|| panic!("{spelling}"));
400                assert_eq!(code, format!("cli.{command}"));
401                for verb in VERBS {
402                    assert!(
403                        cli_code(&args(&[spelling, verb])).is_some(),
404                        "{spelling} {verb}"
405                    );
406                }
407            }
408        }
409        for feature in [
410            Feature::GraphIndex,
411            Feature::Bm25Index,
412            Feature::SemanticIndex,
413        ] {
414            assert!(crate::core::telemetry_v2::valid_feature_code(
415                feature.code()
416            ));
417        }
418    }
419}