Skip to main content

lean_ctx/core/
telemetry_v2.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Privacy-bounded, versioned telemetry event contract.
4
5use serde::{Deserialize, Serialize};
6use uuid::Uuid;
7
8pub const SCHEMA_VERSION: u16 = 2;
9pub const MAX_COUNT: u64 = 1_000_000_000;
10pub const MAX_HISTOGRAM_BUCKETS: usize = 32;
11pub const MAX_BATCH_EVENTS: usize = 64;
12/// Upper bound on distinct tools in one `tool_call_aggregate` event. The
13/// built-in registry holds fewer than 100 tools.
14pub const MAX_TOOL_ENTRIES: usize = 128;
15pub const MAX_TOOL_NAME_LEN: usize = 64;
16
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18#[serde(deny_unknown_fields)]
19pub struct TelemetryBatchV2 {
20    pub schema_version: u16,
21    pub deletion_token_hash: String,
22    pub events: Vec<TelemetryEnvelopeV2>,
23}
24
25impl TelemetryBatchV2 {
26    pub fn validate(&self) -> Result<(), TelemetryValidationError> {
27        if self.schema_version != SCHEMA_VERSION {
28            return Err(TelemetryValidationError::SchemaVersion);
29        }
30        if !valid_digest(&self.deletion_token_hash) {
31            return Err(TelemetryValidationError::DeletionTokenHash);
32        }
33        if self.events.is_empty() || self.events.len() > MAX_BATCH_EVENTS {
34            return Err(TelemetryValidationError::BatchSize);
35        }
36        self.events
37            .iter()
38            .try_for_each(TelemetryEnvelopeV2::validate)
39    }
40}
41
42fn valid_digest(value: &str) -> bool {
43    value.len() == 64
44        && value
45            .bytes()
46            .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
47}
48
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
50#[serde(deny_unknown_fields)]
51pub struct TelemetryEnvelopeV2 {
52    pub schema_version: u16,
53    pub timestamp_bucket: String,
54    pub installation_id: String,
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub account_id: Option<PseudonymousId>,
57    #[serde(skip_serializing_if = "Option::is_none")]
58    pub organization_id: Option<PseudonymousId>,
59    pub app_version: String,
60    pub event: TelemetryEventV2,
61}
62
63impl TelemetryEnvelopeV2 {
64    pub fn validate(&self) -> Result<(), TelemetryValidationError> {
65        if self.schema_version != SCHEMA_VERSION {
66            return Err(TelemetryValidationError::SchemaVersion);
67        }
68        lean_ctx_time::parse_date(&self.timestamp_bucket, "%Y-%m-%d")
69            .map_err(|_| TelemetryValidationError::TimestampBucket)?;
70        Uuid::parse_str(&self.installation_id)
71            .map_err(|_| TelemetryValidationError::InstallationId)?;
72        if self.app_version.is_empty()
73            || self.app_version.len() > 64
74            || !self
75                .app_version
76                .bytes()
77                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'+'))
78        {
79            return Err(TelemetryValidationError::AppVersion);
80        }
81        if self.account_id.as_ref().is_some_and(|id| !id.is_valid())
82            || self
83                .organization_id
84                .as_ref()
85                .is_some_and(|id| !id.is_valid())
86        {
87            return Err(TelemetryValidationError::PseudonymousId);
88        }
89        self.event.validate()
90    }
91}
92
93#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
94#[serde(transparent)]
95pub struct PseudonymousId(String);
96
97impl<'de> Deserialize<'de> for PseudonymousId {
98    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
99    where
100        D: serde::Deserializer<'de>,
101    {
102        Self::new(String::deserialize(deserializer)?)
103            .map_err(|_| serde::de::Error::custom("invalid pseudonymous ID"))
104    }
105}
106
107impl PseudonymousId {
108    pub fn new(value: impl Into<String>) -> Result<Self, TelemetryValidationError> {
109        let value = Self(value.into());
110        if value.is_valid() {
111            Ok(value)
112        } else {
113            Err(TelemetryValidationError::PseudonymousId)
114        }
115    }
116
117    fn is_valid(&self) -> bool {
118        self.0.strip_prefix("hmac-sha256:").is_some_and(|tail| {
119            tail.len() == 64
120                && tail
121                    .bytes()
122                    .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
123        })
124    }
125}
126
127#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
128#[serde(
129    tag = "name",
130    content = "metrics",
131    rename_all = "snake_case",
132    deny_unknown_fields
133)]
134/// One telemetry event. The contract is shared with the hosted service, which
135/// deserializes the same type: variants marked *hosted plane* are never built
136/// by the OSS engine and stay only so both sides read one schema
137/// (`docs/privacy/TELEMETRY-DATA-DICTIONARY.md` ยง3).
138pub enum TelemetryEventV2 {
139    Heartbeat(HeartbeatMetrics),
140    SetupProfile(SetupProfileMetrics),
141    SetupCompleted(OccurrenceMetrics),
142    IntegrationDetected(OccurrenceMetrics),
143    SessionAggregate(SessionMetrics),
144    ToolUsageAggregate(ToolUsageMetrics),
145    ToolCallAggregate(ToolCallMetrics),
146    AutopilotAggregate(DecisionMetrics),
147    AutopilotFallbackAggregate(DecisionMetrics),
148    SyncAggregate(SyncMetrics),
149    /// Hosted plane: never emitted by the OSS engine.
150    TrialStarted(OccurrenceMetrics),
151    /// Hosted plane: never emitted by the OSS engine.
152    TrialEnded(OutcomeMetrics),
153    /// Hosted plane: never emitted by the OSS engine.
154    UpgradeViewed(OccurrenceMetrics),
155    CheckoutStarted(OccurrenceMetrics),
156    /// Hosted plane: never emitted by the OSS engine.
157    SubscriptionActivated(OccurrenceMetrics),
158    /// Hosted plane: never emitted by the OSS engine.
159    SubscriptionCancelled(OccurrenceMetrics),
160    /// Hosted plane: never emitted by the OSS engine.
161    TeamCreated(OccurrenceMetrics),
162    /// Hosted plane: never emitted by the OSS engine.
163    TeamMemberInvited(OccurrenceMetrics),
164    /// Hosted plane: never emitted by the OSS engine.
165    TeamContextPromoted(OutcomeMetrics),
166    ErrorCategoryAggregate(ErrorMetrics),
167    VersionUpgrade(VersionUpgradeMetrics),
168    /// Hosted plane: never emitted by the OSS engine.
169    OrchestrationAggregate(Box<OrchestrationMetrics>),
170    UsageHistory(UsageHistoryMetrics),
171    /// Daily use of CLI commands and background features (3.11.1+).
172    FeatureAggregate(FeatureMetrics),
173}
174
175impl TelemetryEventV2 {
176    pub fn name(&self) -> &'static str {
177        match self {
178            Self::Heartbeat(_) => "heartbeat",
179            Self::SetupProfile(_) => "setup_profile",
180            Self::SetupCompleted(_) => "setup_completed",
181            Self::IntegrationDetected(_) => "integration_detected",
182            Self::SessionAggregate(_) => "session_aggregate",
183            Self::ToolUsageAggregate(_) => "tool_usage_aggregate",
184            Self::ToolCallAggregate(_) => "tool_call_aggregate",
185            Self::AutopilotAggregate(_) => "autopilot_aggregate",
186            Self::AutopilotFallbackAggregate(_) => "autopilot_fallback_aggregate",
187            Self::SyncAggregate(_) => "sync_aggregate",
188            Self::TrialStarted(_) => "trial_started",
189            Self::TrialEnded(_) => "trial_ended",
190            Self::UpgradeViewed(_) => "upgrade_viewed",
191            Self::CheckoutStarted(_) => "checkout_started",
192            Self::SubscriptionActivated(_) => "subscription_activated",
193            Self::SubscriptionCancelled(_) => "subscription_cancelled",
194            Self::TeamCreated(_) => "team_created",
195            Self::TeamMemberInvited(_) => "team_member_invited",
196            Self::TeamContextPromoted(_) => "team_context_promoted",
197            Self::ErrorCategoryAggregate(_) => "error_category_aggregate",
198            Self::VersionUpgrade(_) => "version_upgrade",
199            Self::OrchestrationAggregate(_) => "orchestration_aggregate",
200            Self::UsageHistory(_) => "usage_history",
201            Self::FeatureAggregate(_) => "feature_aggregate",
202        }
203    }
204
205    fn validate(&self) -> Result<(), TelemetryValidationError> {
206        match self {
207            Self::Heartbeat(metrics) => metrics.validate(),
208            // Both fields are closed enums: deserialization is the validation.
209            Self::SetupProfile(_) => Ok(()),
210            Self::SetupCompleted(metrics)
211            | Self::IntegrationDetected(metrics)
212            | Self::TrialStarted(metrics)
213            | Self::UpgradeViewed(metrics)
214            | Self::CheckoutStarted(metrics)
215            | Self::SubscriptionActivated(metrics)
216            | Self::SubscriptionCancelled(metrics)
217            | Self::TeamCreated(metrics)
218            | Self::TeamMemberInvited(metrics) => metrics.validate(),
219            Self::SessionAggregate(metrics) => metrics.validate(),
220            Self::ToolUsageAggregate(metrics) => metrics.validate(),
221            Self::ToolCallAggregate(metrics) => metrics.validate(),
222            Self::AutopilotAggregate(metrics) | Self::AutopilotFallbackAggregate(metrics) => {
223                metrics.validate()
224            }
225            Self::SyncAggregate(metrics) => metrics.validate(),
226            Self::TrialEnded(metrics) | Self::TeamContextPromoted(metrics) => metrics.validate(),
227            Self::ErrorCategoryAggregate(metrics) => metrics.validate(),
228            Self::VersionUpgrade(metrics) => metrics.validate(),
229            Self::OrchestrationAggregate(metrics) => metrics.validate(),
230            Self::UsageHistory(metrics) => metrics.validate(),
231            Self::FeatureAggregate(metrics) => metrics.validate(),
232        }
233    }
234}
235
236/// Upper bound for token totals: a heavy installation passes [`MAX_COUNT`]
237/// tokens within weeks, so tokens get their own, still finite, bound.
238pub const MAX_TOKENS: u64 = 1_000_000_000_000_000;
239/// Days of local history sent; matches the server's retention window.
240pub const MAX_HISTORY_DAYS: usize = 90;
241
242/// The installation's own daily usage record (`lean-ctx gain`), so history
243/// before telemetry and usage outside MCP (shell hooks, CLI) is counted.
244/// Days are `YYYY-MM-DD` in the client's calendar, strictly ascending.
245#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
246#[serde(deny_unknown_fields)]
247pub struct UsageHistoryMetrics {
248    pub days: Vec<UsageDay>,
249    pub lifetime: LifetimeUsage,
250}
251
252#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
253#[serde(deny_unknown_fields)]
254pub struct UsageDay {
255    pub date: String,
256    /// Compressed operations (tool calls, hook-wrapped commands, reads).
257    pub commands: u64,
258    /// Tokens before compression.
259    pub original_tokens: u64,
260    /// Tokens that reached the model.
261    pub delivered_tokens: u64,
262}
263
264#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
265#[serde(deny_unknown_fields)]
266pub struct LifetimeUsage {
267    pub commands: u64,
268    pub original_tokens: u64,
269    pub delivered_tokens: u64,
270    /// `YYYY-MM` of first use; month precision only.
271    #[serde(default, skip_serializing_if = "Option::is_none")]
272    pub first_use_month: Option<String>,
273}
274
275impl UsageHistoryMetrics {
276    fn validate(&self) -> Result<(), TelemetryValidationError> {
277        if self.days.len() > MAX_HISTORY_DAYS
278            || !self.days.windows(2).all(|pair| pair[0].date < pair[1].date)
279        {
280            return Err(TelemetryValidationError::History);
281        }
282        for day in &self.days {
283            if !valid_day(&day.date) {
284                return Err(TelemetryValidationError::History);
285            }
286            bounded(day.commands)?;
287            tokens_bounded(&[day.original_tokens, day.delivered_tokens])?;
288        }
289        bounded(self.lifetime.commands)?;
290        tokens_bounded(&[
291            self.lifetime.original_tokens,
292            self.lifetime.delivered_tokens,
293        ])?;
294        if self
295            .lifetime
296            .first_use_month
297            .as_deref()
298            .is_some_and(|month| !valid_day(&format!("{month}-01")))
299        {
300            return Err(TelemetryValidationError::History);
301        }
302        Ok(())
303    }
304}
305
306fn tokens_bounded(values: &[u64]) -> Result<(), TelemetryValidationError> {
307    if values.iter().all(|value| *value <= MAX_TOKENS) {
308        Ok(())
309    } else {
310        Err(TelemetryValidationError::CountBound)
311    }
312}
313
314/// A real calendar day written exactly as `YYYY-MM-DD`.
315fn valid_day(value: &str) -> bool {
316    value.len() == 10
317        && lean_ctx_time::parse_date(value, "%Y-%m-%d")
318            .is_ok_and(|date| date.strftime("%Y-%m-%d").to_string() == value)
319}
320
321#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
322#[serde(deny_unknown_fields)]
323pub struct HeartbeatMetrics {
324    pub distribution_channel: DistributionChannel,
325    pub client_family: ClientFamily,
326    pub operating_system: OperatingSystem,
327    pub architecture: Architecture,
328    /// Age of the local installation identity, bucketed. Closed enums only;
329    /// skipped when unknown so older receivers keep accepting the heartbeat.
330    #[serde(default, skip_serializing_if = "Option::is_none")]
331    pub install_age: Option<InstallAge>,
332    /// Distinct UTC days with a successful send in the trailing 30, bucketed.
333    #[serde(default, skip_serializing_if = "Option::is_none")]
334    pub active_days: Option<ActiveDays>,
335    #[serde(default, skip_serializing_if = "Option::is_none")]
336    pub runtime_environment: Option<RuntimeEnvironment>,
337}
338
339#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
340pub enum InstallAge {
341    #[serde(rename = "lt_1h")]
342    Lt1h,
343    #[serde(rename = "lt_1d")]
344    Lt1d,
345    #[serde(rename = "lt_7d")]
346    Lt7d,
347    #[serde(rename = "lt_30d")]
348    Lt30d,
349    #[serde(rename = "gte_30d")]
350    Gte30d,
351}
352
353impl InstallAge {
354    #[must_use]
355    pub fn from_seconds(seconds: u64) -> Self {
356        match seconds {
357            0..3_600 => Self::Lt1h,
358            3_600..86_400 => Self::Lt1d,
359            86_400..604_800 => Self::Lt7d,
360            604_800..2_592_000 => Self::Lt30d,
361            _ => Self::Gte30d,
362        }
363    }
364}
365
366#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
367pub enum ActiveDays {
368    #[serde(rename = "d1")]
369    D1,
370    #[serde(rename = "d2_3")]
371    D2To3,
372    #[serde(rename = "d4_7")]
373    D4To7,
374    #[serde(rename = "d8_14")]
375    D8To14,
376    #[serde(rename = "d15_plus")]
377    D15Plus,
378}
379
380impl ActiveDays {
381    #[must_use]
382    pub fn from_count(days: usize) -> Self {
383        match days {
384            0 | 1 => Self::D1,
385            2 | 3 => Self::D2To3,
386            4..=7 => Self::D4To7,
387            8..=14 => Self::D8To14,
388            _ => Self::D15Plus,
389        }
390    }
391}
392
393/// Where the process runs. Separates people from short-lived agent sandboxes
394/// without any machine, account or network identifier.
395#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
396#[serde(rename_all = "snake_case")]
397pub enum RuntimeEnvironment {
398    Local,
399    Container,
400    Codespaces,
401    Gitpod,
402    Replit,
403    CloudAgent,
404    Ci,
405    Unknown,
406}
407
408impl HeartbeatMetrics {
409    fn validate(&self) -> Result<(), TelemetryValidationError> {
410        Ok(())
411    }
412}
413
414/// How this installation is wired up, as closed enums only: no paths,
415/// project names, model names or config values leave the machine.
416#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
417#[serde(deny_unknown_fields)]
418pub struct SetupProfileMetrics {
419    pub integration_mode: IntegrationMode,
420    pub embeddings: EmbeddingsState,
421}
422
423/// Configured `hook_mode`; `Default` means the user never set one.
424#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
425#[serde(rename_all = "snake_case")]
426pub enum IntegrationMode {
427    Default,
428    Mcp,
429    Hybrid,
430    Replace,
431}
432
433#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
434#[serde(rename_all = "snake_case")]
435pub enum EmbeddingsState {
436    /// Built without the `embeddings` feature.
437    Unsupported,
438    /// Auto-download is turned off and no model is on disk.
439    Disabled,
440    /// Allowed but the model has not been downloaded yet.
441    NotInstalled,
442    Installed,
443}
444
445#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
446#[serde(deny_unknown_fields)]
447pub struct OccurrenceMetrics {
448    pub count: u64,
449}
450
451impl OccurrenceMetrics {
452    fn validate(&self) -> Result<(), TelemetryValidationError> {
453        bounded(self.count)
454    }
455}
456
457#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
458#[serde(deny_unknown_fields)]
459pub struct OutcomeMetrics {
460    pub accepted: u64,
461    pub rejected: u64,
462    pub unknown: u64,
463}
464
465impl OutcomeMetrics {
466    fn validate(&self) -> Result<(), TelemetryValidationError> {
467        bounded_many(&[self.accepted, self.rejected, self.unknown])
468    }
469}
470
471#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
472#[serde(deny_unknown_fields)]
473pub struct SessionMetrics {
474    pub sessions: u64,
475    pub duration_seconds: Histogram,
476}
477
478impl SessionMetrics {
479    fn validate(&self) -> Result<(), TelemetryValidationError> {
480        bounded(self.sessions)?;
481        self.duration_seconds.validate()
482    }
483}
484
485#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
486#[serde(deny_unknown_fields)]
487pub struct ToolUsageMetrics {
488    pub calls: u64,
489    pub failures: u64,
490    pub latency_milliseconds: Histogram,
491    /// Absent from clients before 3.11.1.
492    #[serde(default, skip_serializing_if = "Option::is_none")]
493    pub tokens: Option<TokenMetrics>,
494}
495
496/// Tokens of tool output for one day: what it would have cost uncompressed
497/// (`original`) and what reached the model (`delivered`). Counts only.
498#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
499#[serde(deny_unknown_fields)]
500pub struct TokenMetrics {
501    pub original: u64,
502    pub delivered: u64,
503}
504
505impl ToolUsageMetrics {
506    fn validate(&self) -> Result<(), TelemetryValidationError> {
507        bounded_many(&[self.calls, self.failures])?;
508        if self.failures > self.calls {
509            return Err(TelemetryValidationError::InconsistentCounts);
510        }
511        if let Some(tokens) = self.tokens {
512            bounded_many(&[tokens.original, tokens.delivered])?;
513        }
514        self.latency_milliseconds.validate()
515    }
516}
517
518/// Per-tool call counts for one day.
519///
520/// Tool names are the static keys of the built-in tool registry, never
521/// caller-supplied strings: a name is a short `[a-z0-9_]` identifier, entries
522/// are sorted and unique, and every entry has at least one call.
523#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
524#[serde(deny_unknown_fields)]
525pub struct ToolCallMetrics {
526    pub tools: Vec<ToolCallCount>,
527}
528
529#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
530#[serde(deny_unknown_fields)]
531pub struct ToolCallCount {
532    pub tool: String,
533    pub calls: u64,
534    pub failures: u64,
535    /// Summed latency of these calls; absent from clients before 3.11.1.
536    #[serde(default, skip_serializing_if = "Option::is_none")]
537    pub latency_milliseconds_total: Option<u64>,
538    /// Failures by class (never the message); absent before 3.11.1.
539    #[serde(default, skip_serializing_if = "Option::is_none")]
540    pub failure_kinds:
541        Option<std::collections::BTreeMap<crate::core::telemetry_failure::FailureKind, u64>>,
542    /// The most frequent scrubbed failure templates (see
543    /// `core::failure_template`); absent before 3.11.1.
544    #[serde(default, skip_serializing_if = "Option::is_none")]
545    pub failure_messages: Option<Vec<FailureMessage>>,
546}
547
548/// One scrubbed failure template and how often it occurred that day.
549#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
550#[serde(deny_unknown_fields)]
551pub struct FailureMessage {
552    pub template: String,
553    pub count: u64,
554}
555
556impl FailureMessage {
557    /// Shape of a template the scrubber can produce: bounded, a closed
558    /// character set and no digits.
559    fn valid(&self) -> bool {
560        let length = self.template.chars().count();
561        (1..=crate::core::failure_template::MAX_TEMPLATE_CHARS).contains(&length)
562            && self.count > 0
563            && self.template.chars().all(|c| {
564                (c.is_ascii_alphanumeric() && !c.is_ascii_digit())
565                    || " .,:;()[]{}<>!?'-_/โ€นโ€บโ€ฆ".contains(c)
566            })
567    }
568}
569
570impl ToolCallMetrics {
571    pub(crate) fn validate(&self) -> Result<(), TelemetryValidationError> {
572        if self.tools.is_empty() || self.tools.len() > MAX_TOOL_ENTRIES {
573            return Err(TelemetryValidationError::ToolEntries);
574        }
575        if !self
576            .tools
577            .windows(2)
578            .all(|pair| pair[0].tool < pair[1].tool)
579        {
580            return Err(TelemetryValidationError::ToolEntries);
581        }
582        self.tools.iter().try_for_each(ToolCallCount::validate)
583    }
584}
585
586impl ToolCallCount {
587    fn validate(&self) -> Result<(), TelemetryValidationError> {
588        if !valid_tool_name(&self.tool) {
589            return Err(TelemetryValidationError::ToolName);
590        }
591        bounded_many(&[self.calls, self.failures])?;
592        bounded(self.latency_milliseconds_total.unwrap_or_default())?;
593        let classified: u64 = self
594            .failure_kinds
595            .iter()
596            .flat_map(|kinds| kinds.values())
597            .sum();
598        if classified > self.failures
599            || self
600                .failure_kinds
601                .as_ref()
602                .is_some_and(|kinds| kinds.values().any(|count| *count == 0))
603        {
604            return Err(TelemetryValidationError::InconsistentCounts);
605        }
606        if self.calls == 0 || self.failures > self.calls {
607            return Err(TelemetryValidationError::InconsistentCounts);
608        }
609        if let Some(messages) = &self.failure_messages {
610            let sum: u64 = messages.iter().map(|message| message.count).sum();
611            if messages.is_empty()
612                || messages.len() > crate::core::telemetry_failure::MAX_FAILURE_MESSAGES
613                || sum > self.failures
614                || !messages.iter().all(FailureMessage::valid)
615            {
616                return Err(TelemetryValidationError::InconsistentCounts);
617            }
618        }
619        Ok(())
620    }
621}
622
623/// `[a-z][a-z0-9_]*`, at most [`MAX_TOOL_NAME_LEN`] bytes.
624pub fn valid_tool_name(name: &str) -> bool {
625    let bytes = name.as_bytes();
626    !bytes.is_empty()
627        && bytes.len() <= MAX_TOOL_NAME_LEN
628        && bytes[0].is_ascii_lowercase()
629        && bytes
630            .iter()
631            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'_')
632}
633
634/// Most distinct feature codes per day; extra codes are dropped on the client.
635pub const MAX_FEATURE_ENTRIES: usize = 96;
636
637/// Daily counts per feature code from the closed registry in
638/// `core::telemetry_features` (e.g. `cli.pack.export`, `index.graph`).
639/// Sorted by code; a code never carries arguments, paths or user input.
640#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
641#[serde(deny_unknown_fields)]
642pub struct FeatureMetrics {
643    pub features: Vec<FeatureCount>,
644}
645
646#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
647#[serde(deny_unknown_fields)]
648pub struct FeatureCount {
649    pub feature: String,
650    pub count: u64,
651    #[serde(default, skip_serializing_if = "is_zero")]
652    pub failures: u64,
653}
654
655fn is_zero(value: &u64) -> bool {
656    *value == 0
657}
658
659/// `segment(.segment){0,2}`, each `[a-z][a-z0-9_]{0,23}`.
660#[must_use]
661pub fn valid_feature_code(code: &str) -> bool {
662    let segments: Vec<&str> = code.split('.').collect();
663    (1..=3).contains(&segments.len())
664        && segments.iter().all(|segment| {
665            let mut bytes = segment.bytes();
666            segment.len() <= 24
667                && bytes.next().is_some_and(|byte| byte.is_ascii_lowercase())
668                && bytes
669                    .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
670        })
671}
672
673impl FeatureMetrics {
674    fn validate(&self) -> Result<(), TelemetryValidationError> {
675        if self.features.is_empty()
676            || self.features.len() > MAX_FEATURE_ENTRIES
677            || !self
678                .features
679                .windows(2)
680                .all(|pair| pair[0].feature < pair[1].feature)
681        {
682            return Err(TelemetryValidationError::FeatureEntries);
683        }
684        for entry in &self.features {
685            bounded_many(&[entry.count, entry.failures])?;
686            if !valid_feature_code(&entry.feature) {
687                return Err(TelemetryValidationError::FeatureCode);
688            }
689            if entry.count == 0 || entry.failures > entry.count {
690                return Err(TelemetryValidationError::InconsistentCounts);
691            }
692        }
693        Ok(())
694    }
695}
696
697#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
698#[serde(deny_unknown_fields)]
699pub struct DecisionMetrics {
700    pub admitted: u64,
701    pub denied: u64,
702    pub fallback: u64,
703}
704
705impl DecisionMetrics {
706    fn validate(&self) -> Result<(), TelemetryValidationError> {
707        bounded_many(&[self.admitted, self.denied, self.fallback])
708    }
709}
710
711#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
712#[serde(deny_unknown_fields)]
713pub struct SyncMetrics {
714    pub attempts: u64,
715    pub successes: u64,
716    pub failures: u64,
717}
718
719impl SyncMetrics {
720    fn validate(&self) -> Result<(), TelemetryValidationError> {
721        bounded_many(&[self.attempts, self.successes, self.failures])?;
722        if self.successes.saturating_add(self.failures) > self.attempts {
723            return Err(TelemetryValidationError::InconsistentCounts);
724        }
725        Ok(())
726    }
727}
728
729#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
730#[serde(deny_unknown_fields)]
731pub struct ErrorMetrics {
732    pub category: ErrorCategory,
733    pub count: u64,
734}
735
736impl ErrorMetrics {
737    fn validate(&self) -> Result<(), TelemetryValidationError> {
738        bounded(self.count)
739    }
740}
741
742#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
743#[serde(deny_unknown_fields)]
744pub struct VersionUpgradeMetrics {
745    pub from_major: u16,
746    pub to_major: u16,
747}
748
749impl VersionUpgradeMetrics {
750    fn validate(&self) -> Result<(), TelemetryValidationError> {
751        if self.to_major < self.from_major {
752            return Err(TelemetryValidationError::VersionDirection);
753        }
754        Ok(())
755    }
756}
757
758#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
759#[serde(deny_unknown_fields)]
760pub struct OrchestrationMetrics {
761    pub admitted_tasks: u64,
762    pub execution_plans: u64,
763    pub retries: u64,
764    pub fallbacks: u64,
765    pub cancellations: u64,
766    pub lease_conflicts: u64,
767    pub receipts: u64,
768    pub outcomes: OutcomeMetrics,
769    pub node_count: Histogram,
770    pub fan_out: Histogram,
771    pub depth: Histogram,
772    pub parallel_nodes: Histogram,
773}
774
775impl OrchestrationMetrics {
776    fn validate(&self) -> Result<(), TelemetryValidationError> {
777        bounded_many(&[
778            self.admitted_tasks,
779            self.execution_plans,
780            self.retries,
781            self.fallbacks,
782            self.cancellations,
783            self.lease_conflicts,
784            self.receipts,
785        ])?;
786        self.outcomes.validate()?;
787        self.node_count.validate()?;
788        self.fan_out.validate()?;
789        self.depth.validate()?;
790        self.parallel_nodes.validate()
791    }
792}
793
794#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
795#[serde(deny_unknown_fields)]
796pub struct Histogram {
797    pub upper_bounds: Vec<u64>,
798    pub counts: Vec<u64>,
799}
800
801impl Histogram {
802    fn validate(&self) -> Result<(), TelemetryValidationError> {
803        if self.upper_bounds.is_empty()
804            || self.upper_bounds.len() > MAX_HISTOGRAM_BUCKETS
805            || self.upper_bounds.len() != self.counts.len()
806            || !self
807                .upper_bounds
808                .windows(2)
809                .all(|window| window[0] < window[1])
810        {
811            return Err(TelemetryValidationError::Histogram);
812        }
813        bounded_many(&self.counts)
814    }
815}
816
817#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
818#[serde(rename_all = "snake_case")]
819pub enum DistributionChannel {
820    Cargo,
821    Homebrew,
822    Npm,
823    Docker,
824    Source,
825    Aur,
826    Pypi,
827    /// A release binary installed by the install script or by hand.
828    Binary,
829    Unknown,
830}
831
832#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
833#[serde(rename_all = "snake_case")]
834pub enum ClientFamily {
835    Claude,
836    Codex,
837    Cursor,
838    Gemini,
839    Windsurf,
840    Zed,
841    VscodeCopilot,
842    Kiro,
843    Antigravity,
844    Codebuddy,
845    Codewhale,
846    // 3.11.1: more MCP hosts. The server accepts these from 3.11.1 on.
847    Cline,
848    RooCode,
849    KiloCode,
850    ContinueDev,
851    Opencode,
852    Goose,
853    Amp,
854    Augment,
855    Jetbrains,
856    Warp,
857    Trae,
858    QwenCode,
859    Crush,
860    ClaudeDesktop,
861    Chatgpt,
862    LmStudio,
863    CopilotCli,
864    VisualStudio,
865    Neovim,
866    Emacs,
867    Factory,
868    Pi,
869    OhMyPi,
870    /// No MCP client was seen: LeanCTX runs only through the CLI or shell hooks.
871    None,
872    /// An MCP client LeanCTX does not recognise.
873    Other,
874}
875
876impl ClientFamily {
877    /// Maps a `client_capabilities` client id (from the MCP initialize
878    /// handshake) onto the fixed wire enum; unknown ids never leak as text.
879    #[must_use]
880    pub fn from_client_id(id: &str) -> Option<Self> {
881        Some(match id {
882            "claude-code" => Self::Claude,
883            "codex" => Self::Codex,
884            "cursor" => Self::Cursor,
885            "gemini-cli" => Self::Gemini,
886            "windsurf" => Self::Windsurf,
887            "zed" => Self::Zed,
888            "vscode-copilot" => Self::VscodeCopilot,
889            "kiro" => Self::Kiro,
890            "antigravity" => Self::Antigravity,
891            "codebuddy" => Self::Codebuddy,
892            "codewhale" => Self::Codewhale,
893            "cline" => Self::Cline,
894            "roo-code" => Self::RooCode,
895            "kilo-code" => Self::KiloCode,
896            "continue" => Self::ContinueDev,
897            "opencode" => Self::Opencode,
898            "goose" => Self::Goose,
899            "amp" => Self::Amp,
900            "augment" => Self::Augment,
901            "jetbrains" => Self::Jetbrains,
902            "warp" => Self::Warp,
903            "trae" => Self::Trae,
904            "qwen-code" => Self::QwenCode,
905            "crush" => Self::Crush,
906            "claude-desktop" => Self::ClaudeDesktop,
907            "chatgpt" => Self::Chatgpt,
908            "lm-studio" => Self::LmStudio,
909            "copilot-cli" => Self::CopilotCli,
910            "visual-studio" => Self::VisualStudio,
911            "neovim" => Self::Neovim,
912            "emacs" => Self::Emacs,
913            "factory" => Self::Factory,
914            "pi" => Self::Pi,
915            "oh-my-pi" => Self::OhMyPi,
916            _ => return None,
917        })
918    }
919}
920
921#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
922#[serde(rename_all = "snake_case")]
923pub enum OperatingSystem {
924    Macos,
925    Linux,
926    Windows,
927    Other,
928}
929
930impl OperatingSystem {
931    #[must_use]
932    pub fn current() -> Self {
933        match std::env::consts::OS {
934            "macos" => Self::Macos,
935            "linux" => Self::Linux,
936            "windows" => Self::Windows,
937            _ => Self::Other,
938        }
939    }
940}
941
942#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
943#[serde(rename_all = "snake_case")]
944pub enum Architecture {
945    X86_64,
946    Aarch64,
947    Other,
948}
949
950impl Architecture {
951    #[must_use]
952    pub fn current() -> Self {
953        match std::env::consts::ARCH {
954            "x86_64" => Self::X86_64,
955            "aarch64" => Self::Aarch64,
956            _ => Self::Other,
957        }
958    }
959}
960
961#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
962#[serde(rename_all = "snake_case")]
963pub enum ErrorCategory {
964    Authentication,
965    Authorization,
966    Configuration,
967    Network,
968    Provider,
969    Timeout,
970    Validation,
971    Internal,
972    /// A command run through a shell tool exited non-zero: the user's
973    /// command failed, not LeanCTX. Sent from 3.11.1 on.
974    Command,
975}
976
977#[derive(Debug, Clone, Copy, PartialEq, Eq)]
978pub enum TelemetryValidationError {
979    SchemaVersion,
980    DeletionTokenHash,
981    TimestampBucket,
982    InstallationId,
983    PseudonymousId,
984    AppVersion,
985    CountBound,
986    InconsistentCounts,
987    Histogram,
988    VersionDirection,
989    BatchSize,
990    ToolEntries,
991    ToolName,
992    History,
993    FeatureEntries,
994    FeatureCode,
995}
996
997fn bounded(value: u64) -> Result<(), TelemetryValidationError> {
998    if value <= MAX_COUNT {
999        Ok(())
1000    } else {
1001        Err(TelemetryValidationError::CountBound)
1002    }
1003}
1004
1005fn bounded_many(values: &[u64]) -> Result<(), TelemetryValidationError> {
1006    values.iter().try_for_each(|value| bounded(*value))
1007}
1008
1009#[cfg(test)]
1010mod tests {
1011    use super::*;
1012
1013    fn envelope(event: TelemetryEventV2) -> TelemetryEnvelopeV2 {
1014        TelemetryEnvelopeV2 {
1015            schema_version: SCHEMA_VERSION,
1016            timestamp_bucket: "2026-09-08".into(),
1017            installation_id: "550e8400-e29b-41d4-a716-446655440000".into(),
1018            account_id: None,
1019            organization_id: None,
1020            app_version: "4.0.0".into(),
1021            event,
1022        }
1023    }
1024
1025    #[test]
1026    fn valid_typed_event_roundtrips() {
1027        let event = envelope(TelemetryEventV2::ToolUsageAggregate(ToolUsageMetrics {
1028            calls: 4,
1029            failures: 1,
1030            latency_milliseconds: Histogram {
1031                upper_bounds: vec![10, 100],
1032                counts: vec![1, 3],
1033            },
1034            tokens: Some(TokenMetrics {
1035                original: 12_000,
1036                delivered: 3_000,
1037            }),
1038        }));
1039        event.validate().unwrap();
1040        let encoded = serde_json::to_vec(&event).unwrap();
1041        let decoded: TelemetryEnvelopeV2 = serde_json::from_slice(&encoded).unwrap();
1042        assert_eq!(decoded, event);
1043    }
1044
1045    #[test]
1046    fn batch_is_bounded_and_validates_every_event() {
1047        let event = envelope(TelemetryEventV2::Heartbeat(HeartbeatMetrics {
1048            distribution_channel: DistributionChannel::Cargo,
1049            client_family: ClientFamily::Codex,
1050            operating_system: OperatingSystem::Linux,
1051            architecture: Architecture::X86_64,
1052            install_age: None,
1053            active_days: None,
1054            runtime_environment: None,
1055        }));
1056        let batch = TelemetryBatchV2 {
1057            schema_version: SCHEMA_VERSION,
1058            deletion_token_hash: "a".repeat(64),
1059            events: vec![event],
1060        };
1061        assert!(batch.validate().is_ok());
1062        let mut invalid_credential = batch.clone();
1063        invalid_credential.deletion_token_hash = "raw-secret".into();
1064        assert_eq!(
1065            invalid_credential.validate(),
1066            Err(TelemetryValidationError::DeletionTokenHash)
1067        );
1068        let empty = TelemetryBatchV2 {
1069            schema_version: SCHEMA_VERSION,
1070            deletion_token_hash: "a".repeat(64),
1071            events: Vec::new(),
1072        };
1073        assert_eq!(empty.validate(), Err(TelemetryValidationError::BatchSize));
1074    }
1075
1076    #[test]
1077    fn ops_context_fields_use_closed_wire_names_and_are_omitted_when_unset() {
1078        let mut metrics = HeartbeatMetrics {
1079            distribution_channel: DistributionChannel::Aur,
1080            client_family: ClientFamily::Codex,
1081            operating_system: OperatingSystem::Linux,
1082            architecture: Architecture::X86_64,
1083            install_age: None,
1084            active_days: None,
1085            runtime_environment: None,
1086        };
1087        let bare = serde_json::to_value(&metrics).unwrap();
1088        assert_eq!(
1089            bare.as_object().unwrap().len(),
1090            4,
1091            "unset fields stay off the wire: {bare}"
1092        );
1093        metrics.install_age = Some(InstallAge::Lt1h);
1094        metrics.active_days = Some(ActiveDays::D2To3);
1095        metrics.runtime_environment = Some(RuntimeEnvironment::CloudAgent);
1096        let full = serde_json::to_value(&metrics).unwrap();
1097        assert_eq!(full["distribution_channel"], "aur");
1098        assert_eq!(full["install_age"], "lt_1h");
1099        assert_eq!(full["active_days"], "d2_3");
1100        assert_eq!(full["runtime_environment"], "cloud_agent");
1101        let decoded: HeartbeatMetrics = serde_json::from_value(full).unwrap();
1102        assert_eq!(decoded, metrics);
1103        assert!(
1104            serde_json::from_value::<HeartbeatMetrics>(serde_json::json!({
1105                "distribution_channel": "cargo", "client_family": "codex",
1106                "operating_system": "linux", "architecture": "x86_64", "install_age": "3 days"
1107            }))
1108            .is_err()
1109        );
1110    }
1111
1112    #[test]
1113    fn ops_context_buckets_have_exact_boundaries() {
1114        assert_eq!(InstallAge::from_seconds(0), InstallAge::Lt1h);
1115        assert_eq!(InstallAge::from_seconds(3_599), InstallAge::Lt1h);
1116        assert_eq!(InstallAge::from_seconds(3_600), InstallAge::Lt1d);
1117        assert_eq!(InstallAge::from_seconds(86_400), InstallAge::Lt7d);
1118        assert_eq!(InstallAge::from_seconds(604_800), InstallAge::Lt30d);
1119        assert_eq!(InstallAge::from_seconds(2_592_000), InstallAge::Gte30d);
1120        assert_eq!(ActiveDays::from_count(0), ActiveDays::D1);
1121        assert_eq!(ActiveDays::from_count(1), ActiveDays::D1);
1122        assert_eq!(ActiveDays::from_count(3), ActiveDays::D2To3);
1123        assert_eq!(ActiveDays::from_count(7), ActiveDays::D4To7);
1124        assert_eq!(ActiveDays::from_count(14), ActiveDays::D8To14);
1125        assert_eq!(ActiveDays::from_count(15), ActiveDays::D15Plus);
1126    }
1127
1128    #[test]
1129    fn unknown_fields_are_rejected() {
1130        let raw = r#"{"schema_version":2,"timestamp_bucket":"2026-09-08","installation_id":"550e8400-e29b-41d4-a716-446655440000","app_version":"4.0.0","raw_task":"secret","event":{"name":"heartbeat","metrics":{"distribution_channel":"cargo","client_family":"codex","operating_system":"linux","architecture":"x86_64"}}}"#;
1131        assert!(serde_json::from_str::<TelemetryEnvelopeV2>(raw).is_err());
1132    }
1133
1134    #[test]
1135    fn event_wrapper_preserves_valid_v2_wire_bytes() {
1136        let raw = r#"{"name":"setup_completed","metrics":{"count":1}}"#;
1137        let decoded: TelemetryEventV2 = serde_json::from_str(raw).unwrap();
1138        assert_eq!(decoded.name(), "setup_completed");
1139        decoded.validate().unwrap();
1140        assert_eq!(serde_json::to_string(&decoded).unwrap(), raw);
1141        let event = envelope(decoded);
1142        let encoded = serde_json::to_vec(&event).unwrap();
1143        let decoded: TelemetryEnvelopeV2 = serde_json::from_slice(&encoded).unwrap();
1144        assert_eq!(decoded, event);
1145        assert_eq!(serde_json::to_vec(&decoded).unwrap(), encoded);
1146    }
1147
1148    #[test]
1149    fn event_wrapper_rejects_forbidden_fields_in_every_key_position() {
1150        // Synthetic privacy fixtures only; no captured content or credentials.
1151        let forbidden = [
1152            ("source_code", "fn synthetic_fixture() {}"),
1153            ("absolute_path", "/synthetic/private/example.rs"),
1154            ("prompt", "synthetic private task instructions"),
1155            ("secret", "SYNTHETIC_NOT_A_CREDENTIAL"),
1156            (
1157                "repository_url",
1158                "https://example.invalid/private/project.git",
1159            ),
1160        ];
1161        for base in [
1162            r#"{"name":"setup_completed","metrics":{"count":1}}"#,
1163            r#"{"metrics":{"count":1},"name":"setup_completed"}"#,
1164        ] {
1165            let valid: TelemetryEventV2 = serde_json::from_str(base).unwrap();
1166            valid.validate().unwrap();
1167            for (field, value) in forbidden {
1168                let property = format!(
1169                    "{}:{}",
1170                    serde_json::to_string(field).unwrap(),
1171                    serde_json::to_string(value).unwrap()
1172                );
1173                let middle = base.find(',').unwrap();
1174                for injected in [
1175                    format!("{{{property},{}", &base[1..]),
1176                    format!("{},{property}{}", &base[..middle], &base[middle..]),
1177                    format!("{},{property}}}", &base[..base.len() - 1]),
1178                ] {
1179                    // Establish valid JSON independently: parse errors must be
1180                    // caused by the forbidden event field, not broken fixtures.
1181                    let parsed: serde_json::Value = serde_json::from_str(&injected).unwrap();
1182                    assert_eq!(parsed[field], value);
1183                    assert!(
1184                        serde_json::from_str::<TelemetryEventV2>(&injected).is_err(),
1185                        "unknown event field accepted: {field}"
1186                    );
1187                    let mut wrapped = serde_json::to_value(envelope(valid.clone())).unwrap();
1188                    wrapped["event"] = parsed;
1189                    assert!(serde_json::from_value::<TelemetryEnvelopeV2>(wrapped).is_err());
1190                }
1191            }
1192        }
1193    }
1194
1195    #[test]
1196    fn malformed_identity_date_and_version_are_rejected() {
1197        let mut event = envelope(TelemetryEventV2::Heartbeat(HeartbeatMetrics {
1198            distribution_channel: DistributionChannel::Cargo,
1199            client_family: ClientFamily::Codex,
1200            operating_system: OperatingSystem::Linux,
1201            architecture: Architecture::X86_64,
1202            install_age: None,
1203            active_days: None,
1204            runtime_environment: None,
1205        }));
1206        event.installation_id = "not-a-uuid".into();
1207        assert_eq!(
1208            event.validate(),
1209            Err(TelemetryValidationError::InstallationId)
1210        );
1211        event.installation_id = "550e8400-e29b-41d4-a716-446655440000".into();
1212        event.timestamp_bucket = "2026-02-30".into();
1213        assert_eq!(
1214            event.validate(),
1215            Err(TelemetryValidationError::TimestampBucket)
1216        );
1217        event.timestamp_bucket = "2026-09-08".into();
1218        event.schema_version = 3;
1219        assert_eq!(
1220            event.validate(),
1221            Err(TelemetryValidationError::SchemaVersion)
1222        );
1223    }
1224
1225    #[test]
1226    fn bounds_and_cross_field_counts_fail_closed() {
1227        let event = envelope(TelemetryEventV2::SyncAggregate(SyncMetrics {
1228            attempts: 1,
1229            successes: 1,
1230            failures: 1,
1231        }));
1232        assert_eq!(
1233            event.validate(),
1234            Err(TelemetryValidationError::InconsistentCounts)
1235        );
1236        let event = envelope(TelemetryEventV2::SetupCompleted(OccurrenceMetrics {
1237            count: MAX_COUNT + 1,
1238        }));
1239        assert_eq!(event.validate(), Err(TelemetryValidationError::CountBound));
1240    }
1241
1242    #[test]
1243    fn histogram_shape_and_order_are_bounded() {
1244        let histogram = Histogram {
1245            upper_bounds: vec![100, 10],
1246            counts: vec![1, 1],
1247        };
1248        assert_eq!(
1249            histogram.validate(),
1250            Err(TelemetryValidationError::Histogram)
1251        );
1252    }
1253
1254    #[test]
1255    fn pseudonymous_ids_never_accept_raw_identifiers() {
1256        assert!(PseudonymousId::new("customer@example.com").is_err());
1257        assert!(PseudonymousId::new(format!("hmac-sha256:{}", "a".repeat(64))).is_ok());
1258    }
1259
1260    #[test]
1261    fn pseudonymous_id_deserialization_preserves_constructor_invariant() {
1262        for raw in [
1263            "synthetic@example.invalid".to_owned(),
1264            "/synthetic/private/identity".to_owned(),
1265            String::new(),
1266            format!("hmac-sha256:{}", "a".repeat(63)),
1267            format!("hmac-sha256:{}", "A".repeat(64)),
1268            format!("hmac-sha256:{}", "g".repeat(64)),
1269        ] {
1270            assert!(PseudonymousId::new(raw.clone()).is_err());
1271            let encoded = serde_json::to_string(&raw).unwrap();
1272            let result = serde_json::from_str::<PseudonymousId>(&encoded);
1273            assert!(result.is_err(), "constructor invariant bypassed on wire");
1274            let message = result.unwrap_err().to_string();
1275            assert!(message.starts_with("invalid pseudonymous ID"));
1276            if !raw.is_empty() {
1277                assert!(!message.contains(&raw));
1278            }
1279        }
1280        let raw = format!("hmac-sha256:{}", "a".repeat(64));
1281        let encoded = serde_json::to_string(&raw).unwrap();
1282        let decoded: PseudonymousId = serde_json::from_str(&encoded).unwrap();
1283        assert_eq!(decoded, PseudonymousId::new(raw).unwrap());
1284        assert_eq!(serde_json::to_string(&decoded).unwrap(), encoded);
1285    }
1286
1287    #[test]
1288    fn envelope_rejects_raw_pseudonymous_ids_before_semantic_validation() {
1289        let event = envelope(TelemetryEventV2::SetupCompleted(OccurrenceMetrics {
1290            count: 1,
1291        }));
1292        for field in ["account_id", "organization_id"] {
1293            let mut wire = serde_json::to_value(&event).unwrap();
1294            wire[field] = serde_json::json!("synthetic@example.invalid");
1295            assert!(serde_json::from_value::<TelemetryEnvelopeV2>(wire).is_err());
1296        }
1297        let mut event_with_ids = event;
1298        event_with_ids.account_id =
1299            Some(PseudonymousId::new(format!("hmac-sha256:{}", "a".repeat(64))).unwrap());
1300        event_with_ids.organization_id =
1301            Some(PseudonymousId::new(format!("hmac-sha256:{}", "b".repeat(64))).unwrap());
1302        let encoded = serde_json::to_vec(&event_with_ids).unwrap();
1303        let decoded: TelemetryEnvelopeV2 = serde_json::from_slice(&encoded).unwrap();
1304        decoded.validate().unwrap();
1305        assert_eq!(decoded, event_with_ids);
1306        assert_eq!(serde_json::to_vec(&decoded).unwrap(), encoded);
1307    }
1308
1309    fn tool_call(tool: &str, calls: u64, failures: u64) -> ToolCallCount {
1310        ToolCallCount {
1311            tool: tool.into(),
1312            calls,
1313            failures,
1314            latency_milliseconds_total: None,
1315            failure_kinds: None,
1316            failure_messages: None,
1317        }
1318    }
1319
1320    fn tool_call_event(tools: Vec<ToolCallCount>) -> TelemetryEnvelopeV2 {
1321        envelope(TelemetryEventV2::ToolCallAggregate(ToolCallMetrics {
1322            tools,
1323        }))
1324    }
1325
1326    #[test]
1327    fn setup_profile_is_closed_enums_on_the_wire() {
1328        let event = TelemetryEventV2::SetupProfile(SetupProfileMetrics {
1329            integration_mode: IntegrationMode::Replace,
1330            embeddings: EmbeddingsState::NotInstalled,
1331        });
1332        let json = serde_json::to_value(&event).unwrap();
1333        assert_eq!(
1334            json,
1335            serde_json::json!({
1336                "name": "setup_profile",
1337                "metrics": {"integration_mode": "replace", "embeddings": "not_installed"}
1338            })
1339        );
1340        assert_eq!(
1341            serde_json::from_value::<TelemetryEventV2>(json).unwrap(),
1342            event
1343        );
1344        for bad in [
1345            serde_json::json!({"name": "setup_profile", "metrics": {"integration_mode": "/home/me", "embeddings": "installed"}}),
1346            serde_json::json!({"name": "setup_profile", "metrics": {"integration_mode": "mcp", "embeddings": "installed", "model": "x"}}),
1347        ] {
1348            assert!(serde_json::from_value::<TelemetryEventV2>(bad).is_err());
1349        }
1350    }
1351
1352    #[test]
1353    fn every_detected_client_id_maps_to_a_stable_wire_family() {
1354        let cases = [
1355            ("claude-code", "claude"),
1356            ("codex", "codex"),
1357            ("cursor", "cursor"),
1358            ("gemini-cli", "gemini"),
1359            ("windsurf", "windsurf"),
1360            ("zed", "zed"),
1361            ("vscode-copilot", "vscode_copilot"),
1362            ("kiro", "kiro"),
1363            ("antigravity", "antigravity"),
1364            ("codebuddy", "codebuddy"),
1365            ("codewhale", "codewhale"),
1366            ("pi", "pi"),
1367            ("oh-my-pi", "oh_my_pi"),
1368        ];
1369        for (id, wire) in cases {
1370            let family = ClientFamily::from_client_id(id).expect(id);
1371            assert_eq!(serde_json::to_value(family).unwrap(), wire);
1372        }
1373        assert_eq!(ClientFamily::from_client_id("unknown"), None);
1374        assert_eq!(ClientFamily::from_client_id("my-private-fork"), None);
1375    }
1376
1377    #[test]
1378    fn tool_call_aggregate_roundtrips_on_the_wire() {
1379        let event = tool_call_event(vec![tool_call("ctx_read", 5, 1), tool_call("shell", 2, 0)]);
1380        event.validate().unwrap();
1381        let encoded = serde_json::to_string(&event.event).unwrap();
1382        assert_eq!(
1383            encoded,
1384            r#"{"name":"tool_call_aggregate","metrics":{"tools":[{"tool":"ctx_read","calls":5,"failures":1},{"tool":"shell","calls":2,"failures":0}]}}"#
1385        );
1386        let decoded: TelemetryEnvelopeV2 =
1387            serde_json::from_slice(&serde_json::to_vec(&event).unwrap()).unwrap();
1388        assert_eq!(decoded, event);
1389    }
1390
1391    #[test]
1392    fn tool_call_aggregate_rejects_free_text_and_inconsistent_entries() {
1393        let reject = |tools: Vec<ToolCallCount>, expected| {
1394            assert_eq!(tool_call_event(tools).validate(), Err(expected));
1395        };
1396        use TelemetryValidationError::{InconsistentCounts, ToolEntries, ToolName};
1397        reject(Vec::new(), ToolEntries);
1398        reject(
1399            vec![tool_call("ctx_shell", 1, 0), tool_call("ctx_read", 1, 0)],
1400            ToolEntries,
1401        );
1402        reject(
1403            vec![tool_call("ctx_read", 1, 0), tool_call("ctx_read", 1, 0)],
1404            ToolEntries,
1405        );
1406        for name in [
1407            "",
1408            "Ctx_read",
1409            "ctx-read",
1410            "/etc/passwd",
1411            "ctx read",
1412            "_ctx",
1413        ] {
1414            reject(vec![tool_call(name, 1, 0)], ToolName);
1415        }
1416        reject(
1417            vec![tool_call(&"a".repeat(MAX_TOOL_NAME_LEN + 1), 1, 0)],
1418            ToolName,
1419        );
1420        reject(vec![tool_call("ctx_read", 0, 0)], InconsistentCounts);
1421        reject(vec![tool_call("ctx_read", 1, 2)], InconsistentCounts);
1422        let too_many = (0..=MAX_TOOL_ENTRIES)
1423            .map(|index| tool_call(&format!("tool_{index:04}"), 1, 0))
1424            .collect();
1425        reject(too_many, ToolEntries);
1426        let unknown_field = r#"{"name":"tool_call_aggregate","metrics":{"tools":[{"tool":"ctx_read","calls":1,"failures":0,"path":"/secret"}]}}"#;
1427        assert!(serde_json::from_str::<TelemetryEventV2>(unknown_field).is_err());
1428    }
1429}