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