1const COMMANDS: &[(&str, &[&str])] = &[
15 ("badge", &[]),
16 ("shell", &["--shell"]),
17 ("gain", &[]),
18 ("spend", &[]),
19 ("savings", &[]),
20 ("learning", &[]),
21 ("autopilot", &[]),
22 ("conformance", &["selftest"]),
23 ("health", &[]),
24 ("billing", &[]),
25 ("finops", &[]),
26 ("roi", &[]),
27 ("output_savings", &["output-savings"]),
28 ("value_report", &["value-report"]),
29 ("evidence_export", &["evidence-export"]),
30 ("evidence", &[]),
31 ("shadow", &[]),
32 ("triage", &[]),
33 ("scenario", &[]),
34 ("token_report", &["token-report", "report-tokens"]),
35 ("pack", &[]),
36 ("migrate", &[]),
37 ("policy", &[]),
38 ("addon", &["addons"]),
39 ("plugin", &["plugins"]),
40 ("embeddings", &[]),
41 ("model", &[]),
42 ("gpu", &["enable-gpu"]),
43 ("rules", &[]),
44 ("proof", &[]),
45 ("value", &[]),
46 ("claude_mod", &["claude-mod"]),
47 ("inspect", &[]),
48 ("snapshot", &[]),
49 ("verify", &[]),
50 ("verify_cache", &["verify-cache", "cache-selftest"]),
51 ("visualize", &[]),
52 ("audit", &[]),
53 ("compliance", &[]),
54 ("agent", &[]),
55 ("instructions", &[]),
56 ("index", &[]),
57 ("semantic_search", &["semantic-search", "search-code"]),
58 ("explore", &[]),
59 ("repomap", &["repo-map"]),
60 ("cep", &[]),
61 ("demo", &[]),
62 ("dashboard", &["cockpit"]),
65 ("team", &[]),
66 ("provider", &[]),
67 ("serve", &[]),
68 ("watch", &[]),
69 ("proxy", &[]),
70 ("daemon", &[]),
71 ("init", &[]),
72 ("setup", &[]),
73 ("onboard", &[]),
74 ("install", &[]),
75 ("bootstrap", &[]),
76 ("wrap", &[]),
77 ("unwrap", &[]),
78 ("status", &[]),
79 ("cognitive", &[]),
80 ("deps", &[]),
81 ("discover", &[]),
82 ("engine", &[]),
83 ("ghost", &[]),
84 ("filter", &[]),
85 ("heatmap", &[]),
86 ("graph", &[]),
87 ("smells", &[]),
88 ("session", &[]),
89 ("ledger", &[]),
90 ("ocla", &[]),
91 ("control", &["context-control"]),
92 ("plan", &["context-plan"]),
93 ("compile", &["context-compile"]),
94 ("import", &[]),
95 ("checkpoints", &[]),
96 ("knowledge", &[]),
97 ("kit", &["kits"]),
98 ("skillify", &[]),
99 ("summary", &[]),
100 ("overview", &[]),
101 ("compress", &[]),
102 ("wrapped", &[]),
103 ("sessions", &["session-store"]),
104 ("benchmark", &[]),
105 ("benchmark_run", &["benchmark-run", "bench-run"]),
106 ("calibrate", &[]),
107 ("compact", &[]),
108 ("profile", &[]),
109 ("tools", &[]),
110 ("config", &[]),
111 ("allow", &[]),
112 ("allow_path", &["allow-path"]),
113 ("security", &[]),
114 ("yolo", &[]),
115 ("secure", &["lockdown"]),
116 ("trust", &[]),
117 ("untrust", &[]),
118 ("stats", &[]),
119 ("introspect", &[]),
120 ("cache", &[]),
121 ("theme", &[]),
122 ("enterprise", &[]),
123 ("tee", &[]),
124 ("terse", &["compression"]),
125 ("slow_log", &["slow-log"]),
126 ("debug_log", &["debug-log"]),
127 ("editor_bridge", &["editor-bridge"]),
128 ("update", &["--self-update"]),
129 ("restart", &[]),
130 ("stop", &[]),
131 ("doctor", &[]),
132 ("harden", &[]),
133 ("export_rules", &["export-rules"]),
134 ("gotchas", &["bugs"]),
135 ("learn", &[]),
136 ("report_issue", &["report-issue", "report"]),
137 ("uninstall", &[]),
138 ("safety_levels", &["safety-levels", "safety"]),
139 ("cheat", &["cheatsheet", "cheat-sheet"]),
140 ("login", &[]),
141 ("register", &[]),
142 ("sync", &[]),
143 ("contribute", &[]),
144 ("telemetry", &[]),
145 ("cloud", &[]),
146 ("upgrade", &[]),
147];
148
149const VERBS: &[&str] = &[
152 "add",
153 "apply",
154 "auto-load",
155 "build",
156 "build-full",
157 "build-semantic",
158 "check",
159 "checkpoint-inspect",
160 "checkpoint-seal",
161 "clean",
162 "clear",
163 "create",
164 "delete",
165 "delete-remote",
166 "diff",
167 "disable",
168 "doctor",
169 "enable",
170 "explain",
171 "export",
172 "export-html",
173 "gc",
174 "get",
175 "impact",
176 "import",
177 "info",
178 "init",
179 "inspect",
180 "install",
181 "list",
182 "login",
183 "logout",
184 "ls",
185 "migrate",
186 "neighbors",
187 "off",
188 "on",
189 "parity",
190 "path",
191 "prune",
192 "publish",
193 "pull",
194 "push",
195 "rebuild",
196 "receive",
197 "related",
198 "remove",
199 "reset",
200 "restart",
201 "rm",
202 "rollback",
203 "run",
204 "search",
205 "send",
206 "set",
207 "show",
208 "snapshot",
209 "start",
210 "status",
211 "stop",
212 "symbol",
213 "uninstall",
214 "update",
215 "verify",
216 "warm",
217 "watch",
218];
219
220const NOT_COUNTED: &[&str] = &[
223 "-c",
224 "exec",
225 "-t",
226 "--track",
227 "hook",
228 "__complete",
229 "completions",
230 "mcp",
231 "read",
232 "call",
233 "diff",
234 "grep",
235 "glob",
236 "find",
237 "ls",
238 "raw",
239 "bypass",
240 "statusline",
241 "editor-signal",
242 "editor-session",
243 "prompt-segment",
244 "git-trailer",
245 "help",
246 "--help",
247 "-h",
248 "codex-protected",
249 "dev-install",
250 "codesign-setup",
251 "forgot-password",
252];
253
254fn segment(word: &str) -> String {
255 word.trim_start_matches('-').replace('-', "_")
256}
257
258#[must_use]
261pub fn cli_code(args: &[String]) -> Option<String> {
262 let first = args.get(1)?.as_str();
263 if NOT_COUNTED.contains(&first) || args.iter().skip(2).any(|a| a == "--dry-run") {
264 return None;
265 }
266 let (command, _) = COMMANDS.iter().find(|(name, aliases)| {
267 *name == first || segment(first) == *name || aliases.contains(&first)
268 })?;
269 let verb = args
270 .get(2)
271 .map(String::as_str)
272 .filter(|word| VERBS.contains(word))
273 .map(segment);
274 let code = match verb {
275 Some(verb) => format!("cli.{command}.{verb}"),
276 None => format!("cli.{command}"),
277 };
278 crate::core::telemetry_v2::valid_feature_code(&code).then_some(code)
279}
280
281pub fn record_cli(args: &[String]) {
283 if let Some(code) = cli_code(args) {
284 let _ = crate::core::telemetry_aggregate::record_feature(&code, true);
285 }
286}
287
288#[derive(Debug, Clone, Copy, PartialEq, Eq)]
290pub enum Feature {
291 GraphIndex,
292 Bm25Index,
293 SemanticIndex,
294}
295
296impl Feature {
297 #[must_use]
298 pub fn code(self) -> &'static str {
299 match self {
300 Self::GraphIndex => "index.graph",
301 Self::Bm25Index => "index.bm25",
302 Self::SemanticIndex => "index.semantic",
303 }
304 }
305}
306
307pub fn record(feature: Feature, ok: bool) {
309 let _ = crate::core::telemetry_aggregate::record_feature(feature.code(), ok);
310}
311
312const MCP_SESSION: &str = "mcp.session";
314const MCP_SESSION_EMPTY: &str = "mcp.session.empty";
319const MCP_SESSION_CLEAN: &str = "mcp.session.clean";
322const MCP_SESSION_RECOVERED: &str = "mcp.session.recovered";
324const MCP_SESSION_UNRESOLVED: &str = "mcp.session.unresolved";
327const MCP_SESSION_RETRY: &str = "mcp.session.retry";
330
331const MCP_SESSION_HOOKED: &str = "mcp.session.hooked";
335const MCP_SESSION_HOOK_CALLS: &str = "mcp.session.hook_calls";
339
340const HOST_SESSION_ENV: &[&str] = &[
344 "CLAUDE_CODE_SESSION_ID",
345 "CLAUDE_SESSION_ID",
346 "CODEX_THREAD_ID",
347 "GEMINI_SESSION_ID",
348 "CODEBUDDY_SESSION_ID",
349];
350
351fn host_session_id_from_env() -> Option<String> {
353 HOST_SESSION_ENV.iter().find_map(|key| {
354 std::env::var(key)
355 .ok()
356 .map(|value| value.trim().to_owned())
357 .filter(|value| !value.is_empty())
358 })
359}
360
361fn hook_calls_path_in(dir: &std::path::Path, session_id: &str) -> Option<std::path::PathBuf> {
365 let session_id = session_id.trim();
366 if session_id.is_empty() {
367 return None;
368 }
369 let key = blake3::hash(session_id.as_bytes()).to_hex();
370 Some(dir.join(&key.as_str()[..16]))
371}
372
373fn hook_calls_path(session_id: &str) -> Option<std::path::PathBuf> {
375 let dir = crate::core::data_dir::lean_ctx_data_dir().ok()?;
376 hook_calls_path_in(&dir.join("hook_calls"), session_id)
377}
378
379fn read_hook_counter(path: &std::path::Path) -> u64 {
380 std::fs::read_to_string(path)
381 .ok()
382 .and_then(|raw| raw.trim().parse().ok())
383 .unwrap_or(0)
384}
385
386fn bump_hook_counter(path: &std::path::Path, eligible: bool) {
391 if !eligible {
392 return;
393 }
394 let Some(dir) = path.parent() else {
395 return;
396 };
397 if std::fs::create_dir_all(dir).is_err() {
398 return;
399 }
400 let next = read_hook_counter(path).saturating_add(1);
401 let tmp = path.with_extension(format!("{}.tmp", std::process::id()));
402 if write_private(&tmp, next.to_string().as_bytes()).is_ok()
403 && std::fs::rename(&tmp, path).is_err()
404 {
405 let _ = std::fs::remove_file(&tmp);
406 }
407}
408
409fn write_private(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
411 use std::io::Write;
412 let mut options = std::fs::OpenOptions::new();
413 options.write(true).create(true).truncate(true);
414 #[cfg(unix)]
415 {
416 use std::os::unix::fs::OpenOptionsExt;
417 options.mode(0o600);
418 }
419 let mut file = options.open(path)?;
420 #[cfg(unix)]
421 {
422 use std::os::unix::fs::PermissionsExt;
423 file.set_permissions(std::fs::Permissions::from_mode(0o600))?;
424 }
425 file.write_all(bytes)
426}
427
428const HOOK_COUNTER_MAX_AGE: std::time::Duration = std::time::Duration::from_hours(168);
432const HOOK_COUNTER_SWEEP_LIMIT: usize = 4096;
434
435fn sweep_hook_counters(
438 dir: &std::path::Path,
439 now: std::time::SystemTime,
440 max_age: std::time::Duration,
441) {
442 let Some(cutoff) = now.checked_sub(max_age) else {
443 return;
444 };
445 let Ok(entries) = std::fs::read_dir(dir) else {
446 return;
447 };
448 for entry in entries.flatten().take(HOOK_COUNTER_SWEEP_LIMIT) {
449 let Ok(meta) = entry.metadata() else {
450 continue;
451 };
452 if meta.is_file() && meta.modified().is_ok_and(|modified| modified < cutoff) {
453 let _ = std::fs::remove_file(entry.path());
454 }
455 }
456}
457
458pub fn record_hook_call(session_id: &str) {
463 if let Some(path) = hook_calls_path(session_id) {
464 bump_hook_counter(
465 &path,
466 crate::core::telemetry_aggregate::telemetry_collection_eligible(),
467 );
468 }
469}
470
471static HOOK_BASELINE: std::sync::OnceLock<(std::path::PathBuf, u64)> = std::sync::OnceLock::new();
475
476pub fn record_mcp_session_start() {
478 let _ = crate::core::telemetry_aggregate::record_feature(MCP_SESSION, true);
479 if let Ok(dir) = crate::core::data_dir::lean_ctx_data_dir() {
480 sweep_hook_counters(
481 &dir.join("hook_calls"),
482 std::time::SystemTime::now(),
483 HOOK_COUNTER_MAX_AGE,
484 );
485 }
486 if let Some(path) = host_session_id_from_env().and_then(|id| hook_calls_path(&id)) {
487 let start = read_hook_counter(&path);
488 let _ = HOOK_BASELINE.set((path, start));
489 }
490}
491
492fn hook_calls_since_start() -> Option<u64> {
498 HOOK_BASELINE.get().map(|(path, start)| {
499 let calls = read_hook_counter(path).saturating_sub(*start);
500 let _ = std::fs::remove_file(path);
501 calls
502 })
503}
504
505fn leanctx_side(kind: crate::core::telemetry_failure::FailureKind) -> bool {
510 use crate::core::telemetry_failure::FailureKind;
511 matches!(
512 kind,
513 FailureKind::Timeout
514 | FailureKind::Unavailable
515 | FailureKind::TooLarge
516 | FailureKind::Other
517 )
518}
519
520fn mcp_session_end_tallies(
525 outcome: &crate::core::telemetry::SessionOutcome,
526 hook_calls: Option<u64>,
527) -> Vec<(&'static str, u64, u64)> {
528 let hooks = hook_calls
529 .filter(|calls| *calls > 0)
530 .map(|calls| (MCP_SESSION_HOOK_CALLS, calls, 0));
531 if outcome.calls == 0 {
532 return match (hook_calls, hooks) {
533 (None, _) => Vec::new(),
534 (Some(_), Some(hooks)) => vec![(MCP_SESSION_HOOKED, 1, 0), hooks],
535 (Some(_), None) => vec![(MCP_SESSION_EMPTY, 1, 0)],
536 };
537 }
538 let ending = if outcome.failures == 0 {
539 (MCP_SESSION_CLEAN, 1, 0)
540 } else if outcome.unresolved.is_empty() {
541 (MCP_SESSION_RECOVERED, 1, 0)
542 } else {
543 let ours = outcome.unresolved.iter().any(|kind| leanctx_side(*kind));
544 (MCP_SESSION_UNRESOLVED, 1, u64::from(ours))
545 };
546 let mut tallies = vec![
547 ending,
548 (MCP_SESSION_RETRY, outcome.retries, outcome.retry_failures),
549 ];
550 tallies.extend(hooks);
551 tallies
552}
553
554pub fn record_mcp_session_end() {
558 static ENDED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
559 if ENDED.swap(true, std::sync::atomic::Ordering::SeqCst) {
560 return;
561 }
562 let outcome = crate::core::telemetry::global_metrics().session_outcome();
563 let tallies = mcp_session_end_tallies(&outcome, hook_calls_since_start());
564 let _ = crate::core::telemetry_aggregate::record_feature_counts(&tallies);
565}
566
567pub const APP_CODE_DETECTED: &str = "app.code.detected";
571pub const APP_CODE_HINT_SHOWN: &str = "app.code_hint.shown";
573
574pub fn record_app_detected() {
576 let _ = crate::core::telemetry_aggregate::record_feature(APP_CODE_DETECTED, true);
577}
578
579pub fn record_app_hint_shown() {
581 let _ = crate::core::telemetry_aggregate::record_feature(APP_CODE_HINT_SHOWN, true);
582}
583
584#[cfg(test)]
585mod tests {
586 use super::*;
587
588 fn args(words: &[&str]) -> Vec<String> {
589 std::iter::once("lean-ctx")
590 .chain(words.iter().copied())
591 .map(str::to_string)
592 .collect()
593 }
594
595 #[test]
596 fn dry_runs_are_not_counted() {
597 for words in [
598 &["setup", "--dry-run"][..],
599 &["onboard", "--agents", "cursor", "--dry-run"][..],
600 &["update", "--dry-run"][..],
601 &["uninstall", "--dry-run"][..],
602 ] {
603 assert_eq!(cli_code(&args(words)), None, "{words:?}");
604 }
605 assert_eq!(cli_code(&args(&["setup"])).as_deref(), Some("cli.setup"));
606 }
607
608 #[test]
609 fn commands_and_registry_verbs_become_codes() {
610 assert_eq!(
611 cli_code(&args(&["pack", "export", "my-secret-pack"])).as_deref(),
612 Some("cli.pack.export")
613 );
614 assert_eq!(
615 cli_code(&args(&["pack", "import", "/home/a/x.ctxpkg"])).as_deref(),
616 Some("cli.pack.import")
617 );
618 assert_eq!(
619 cli_code(&args(&["graph", "build"])).as_deref(),
620 Some("cli.graph.build")
621 );
622 assert_eq!(
623 cli_code(&args(&["index", "build-full"])).as_deref(),
624 Some("cli.index.build_full")
625 );
626 assert_eq!(
627 cli_code(&args(&["report-tokens"])).as_deref(),
628 Some("cli.token_report")
629 );
630 assert_eq!(
631 cli_code(&args(&["--self-update"])).as_deref(),
632 Some("cli.update")
633 );
634 assert_eq!(
635 cli_code(&args(&["cockpit"])).as_deref(),
636 Some("cli.dashboard")
637 );
638 assert_eq!(
639 cli_code(&args(&["telemetry", "off"])).as_deref(),
640 Some("cli.telemetry.off")
641 );
642 }
643
644 #[test]
645 fn user_input_never_becomes_part_of_a_code() {
646 assert_eq!(
647 cli_code(&args(&["knowledge", "remember", "the db password"])).as_deref(),
648 Some("cli.knowledge")
649 );
650 assert_eq!(
651 cli_code(&args(&["graph", "/Users/a/private-repo"])).as_deref(),
652 Some("cli.graph")
653 );
654 assert_eq!(
655 cli_code(&args(&["semantic-search", "export"])).as_deref(),
656 Some("cli.semantic_search.export")
657 );
658 assert!(cli_code(&args(&["my-custom-thing"])).is_none());
659 assert!(cli_code(&args(&[])).is_none());
660 }
661
662 #[test]
663 fn hot_path_commands_are_not_counted() {
664 for command in [
665 "-c",
666 "exec",
667 "hook",
668 "read",
669 "grep",
670 "statusline",
671 "mcp",
672 "__complete",
673 ] {
674 assert!(cli_code(&args(&[command, "build"])).is_none(), "{command}");
675 }
676 }
677
678 #[test]
679 fn every_registry_code_is_a_valid_wire_code() {
680 for (command, aliases) in COMMANDS {
681 for spelling in std::iter::once(*command).chain(aliases.iter().copied()) {
682 let code = cli_code(&args(&[spelling])).unwrap_or_else(|| panic!("{spelling}"));
683 assert_eq!(code, format!("cli.{command}"));
684 for verb in VERBS {
685 assert!(
686 cli_code(&args(&[spelling, verb])).is_some(),
687 "{spelling} {verb}"
688 );
689 }
690 }
691 }
692 for feature in [
693 Feature::GraphIndex,
694 Feature::Bm25Index,
695 Feature::SemanticIndex,
696 ] {
697 assert!(crate::core::telemetry_v2::valid_feature_code(
698 feature.code()
699 ));
700 }
701 for code in [
702 MCP_SESSION,
703 MCP_SESSION_EMPTY,
704 MCP_SESSION_CLEAN,
705 MCP_SESSION_RECOVERED,
706 MCP_SESSION_UNRESOLVED,
707 MCP_SESSION_RETRY,
708 MCP_SESSION_HOOKED,
709 MCP_SESSION_HOOK_CALLS,
710 APP_CODE_DETECTED,
711 APP_CODE_HINT_SHOWN,
712 ] {
713 assert!(
714 crate::core::telemetry_v2::valid_feature_code(code),
715 "{code}"
716 );
717 }
718 }
719
720 #[test]
721 fn every_ended_session_gets_exactly_one_outcome() {
722 use crate::core::telemetry::SessionOutcome;
723 use crate::core::telemetry_failure::FailureKind;
724 let outcome = |calls, failures, unresolved: Vec<FailureKind>| SessionOutcome {
725 calls,
726 failures,
727 unresolved,
728 retries: 0,
729 retry_failures: 0,
730 };
731 assert_eq!(
732 mcp_session_end_tallies(&outcome(0, 0, vec![]), Some(0)),
733 [("mcp.session.empty", 1, 0)]
734 );
735 assert_eq!(
736 mcp_session_end_tallies(&outcome(4, 0, vec![]), Some(0))[0],
737 ("mcp.session.clean", 1, 0)
738 );
739 assert_eq!(
740 mcp_session_end_tallies(&outcome(4, 2, vec![]), Some(0))[0],
741 ("mcp.session.recovered", 1, 0)
742 );
743 assert_eq!(
744 mcp_session_end_tallies(&outcome(4, 2, vec![FailureKind::NotFound]), Some(0))[0],
745 ("mcp.session.unresolved", 1, 0),
746 "a missing file is the caller's to resolve"
747 );
748 assert_eq!(
749 mcp_session_end_tallies(
750 &outcome(4, 2, vec![FailureKind::NotFound, FailureKind::Timeout]),
751 Some(0)
752 )[0],
753 ("mcp.session.unresolved", 1, 1),
754 "a timeout is LeanCTX's"
755 );
756 }
757
758 #[test]
759 fn retries_ride_along_with_the_outcome() {
760 let outcome = crate::core::telemetry::SessionOutcome {
761 calls: 9,
762 failures: 3,
763 unresolved: vec![],
764 retries: 3,
765 retry_failures: 1,
766 };
767 assert_eq!(
768 mcp_session_end_tallies(&outcome, Some(0)),
769 [("mcp.session.recovered", 1, 0), ("mcp.session.retry", 3, 1)]
770 );
771 }
772
773 #[test]
774 fn hook_handled_sessions_are_not_empty() {
775 let dir = tempfile::tempdir().unwrap();
776 let counter = hook_calls_path_in(dir.path(), "session-a").unwrap();
777 let start = read_hook_counter(&counter);
778 for _ in 0..3 {
779 bump_hook_counter(&counter, true);
780 }
781 let hook_calls = read_hook_counter(&counter).saturating_sub(start);
782 assert_eq!(hook_calls, 3);
783 #[cfg(unix)]
784 {
785 use std::os::unix::fs::PermissionsExt;
786 let mode = std::fs::metadata(&counter).unwrap().permissions().mode();
787 assert_eq!(mode & 0o777, 0o600, "the counter is private to its owner");
788 }
789 let idle = crate::core::telemetry::SessionOutcome {
790 calls: 0,
791 failures: 0,
792 unresolved: vec![],
793 retries: 0,
794 retry_failures: 0,
795 };
796 assert_eq!(
797 mcp_session_end_tallies(&idle, Some(hook_calls)),
798 [
799 ("mcp.session.hooked", 1, 0),
800 ("mcp.session.hook_calls", 3, 0)
801 ],
802 "a governor session whose hooks did the work is not empty"
803 );
804 assert!(
805 mcp_session_end_tallies(&idle, None).is_empty(),
806 "without a host session id an idle session is unknown, never empty"
807 );
808 }
809
810 #[test]
811 fn hook_calls_are_kept_per_session() {
812 let dir = tempfile::tempdir().unwrap();
813 let busy = hook_calls_path_in(dir.path(), "session-busy").unwrap();
814 let idle = hook_calls_path_in(dir.path(), "session-idle").unwrap();
815 for _ in 0..2 {
816 bump_hook_counter(&busy, true);
817 }
818 assert_eq!(read_hook_counter(&busy), 2);
819 assert_eq!(
820 read_hook_counter(&idle),
821 0,
822 "a parallel session in the same checkout sees none of another session's hook calls"
823 );
824 assert!(hook_calls_path_in(dir.path(), " ").is_none());
825 }
826
827 #[test]
828 fn stale_hook_counters_are_swept_and_fresh_ones_kept() {
829 let dir = tempfile::tempdir().unwrap();
830 let now = std::time::SystemTime::now();
831 let stale = hook_calls_path_in(dir.path(), "session-cleared").unwrap();
832 let fresh = hook_calls_path_in(dir.path(), "session-running").unwrap();
833 bump_hook_counter(&stale, true);
834 bump_hook_counter(&fresh, true);
835 let stale_tmp = dir.path().join("orphan.123.tmp");
836 write_private(&stale_tmp, b"1").unwrap();
837 let eight_days_ago = now - std::time::Duration::from_hours(192);
838 for old in [&stale, &stale_tmp] {
839 std::fs::File::options()
840 .write(true)
841 .open(old)
842 .unwrap()
843 .set_modified(eight_days_ago)
844 .unwrap();
845 }
846 sweep_hook_counters(dir.path(), now, HOOK_COUNTER_MAX_AGE);
847 assert!(!stale.exists(), "an orphaned counter is swept after 7 days");
848 assert!(!stale_tmp.exists(), "an orphaned temp file is swept too");
849 assert_eq!(
850 read_hook_counter(&fresh),
851 1,
852 "a live session's counter stays"
853 );
854 }
855
856 #[test]
857 fn telemetry_off_writes_no_hook_counter() {
858 let dir = tempfile::tempdir().unwrap();
859 let counter = hook_calls_path_in(dir.path(), "session-a").unwrap();
860 bump_hook_counter(&counter, false);
861 assert!(
862 !counter.exists(),
863 "telemetry off must not write the counter"
864 );
865 assert!(std::fs::read_dir(dir.path()).unwrap().next().is_none());
866 }
867}