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    Pi,
857    OhMyPi,
858    /// No MCP client was seen: LeanCTX runs only through the CLI or shell hooks.
859    None,
860    /// An MCP client LeanCTX does not recognise.
861    Other,
862}
863
864impl ClientFamily {
865    /// Maps a `client_capabilities` client id (from the MCP initialize
866    /// handshake) onto the fixed wire enum; unknown ids never leak as text.
867    #[must_use]
868    pub fn from_client_id(id: &str) -> Option<Self> {
869        Some(match id {
870            "claude-code" => Self::Claude,
871            "codex" => Self::Codex,
872            "cursor" => Self::Cursor,
873            "gemini-cli" => Self::Gemini,
874            "windsurf" => Self::Windsurf,
875            "zed" => Self::Zed,
876            "vscode-copilot" => Self::VscodeCopilot,
877            "kiro" => Self::Kiro,
878            "antigravity" => Self::Antigravity,
879            "codebuddy" => Self::Codebuddy,
880            "codewhale" => Self::Codewhale,
881            "cline" => Self::Cline,
882            "roo-code" => Self::RooCode,
883            "kilo-code" => Self::KiloCode,
884            "continue" => Self::ContinueDev,
885            "opencode" => Self::Opencode,
886            "goose" => Self::Goose,
887            "amp" => Self::Amp,
888            "augment" => Self::Augment,
889            "jetbrains" => Self::Jetbrains,
890            "warp" => Self::Warp,
891            "trae" => Self::Trae,
892            "qwen-code" => Self::QwenCode,
893            "crush" => Self::Crush,
894            "claude-desktop" => Self::ClaudeDesktop,
895            "chatgpt" => Self::Chatgpt,
896            "lm-studio" => Self::LmStudio,
897            "copilot-cli" => Self::CopilotCli,
898            "visual-studio" => Self::VisualStudio,
899            "neovim" => Self::Neovim,
900            "emacs" => Self::Emacs,
901            "factory" => Self::Factory,
902            "pi" => Self::Pi,
903            "oh-my-pi" => Self::OhMyPi,
904            _ => return None,
905        })
906    }
907}
908
909#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
910#[serde(rename_all = "snake_case")]
911pub enum OperatingSystem {
912    Macos,
913    Linux,
914    Windows,
915    Other,
916}
917
918impl OperatingSystem {
919    #[must_use]
920    pub fn current() -> Self {
921        match std::env::consts::OS {
922            "macos" => Self::Macos,
923            "linux" => Self::Linux,
924            "windows" => Self::Windows,
925            _ => Self::Other,
926        }
927    }
928}
929
930#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
931#[serde(rename_all = "snake_case")]
932pub enum Architecture {
933    X86_64,
934    Aarch64,
935    Other,
936}
937
938impl Architecture {
939    #[must_use]
940    pub fn current() -> Self {
941        match std::env::consts::ARCH {
942            "x86_64" => Self::X86_64,
943            "aarch64" => Self::Aarch64,
944            _ => Self::Other,
945        }
946    }
947}
948
949#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
950#[serde(rename_all = "snake_case")]
951pub enum ErrorCategory {
952    Authentication,
953    Authorization,
954    Configuration,
955    Network,
956    Provider,
957    Timeout,
958    Validation,
959    Internal,
960    /// A command run through a shell tool exited non-zero: the user's
961    /// command failed, not LeanCTX. Sent from 3.11.1 on.
962    Command,
963}
964
965#[derive(Debug, Clone, Copy, PartialEq, Eq)]
966pub enum TelemetryValidationError {
967    SchemaVersion,
968    DeletionTokenHash,
969    TimestampBucket,
970    InstallationId,
971    PseudonymousId,
972    AppVersion,
973    CountBound,
974    InconsistentCounts,
975    Histogram,
976    VersionDirection,
977    BatchSize,
978    ToolEntries,
979    ToolName,
980    History,
981    FeatureEntries,
982    FeatureCode,
983}
984
985fn bounded(value: u64) -> Result<(), TelemetryValidationError> {
986    if value <= MAX_COUNT {
987        Ok(())
988    } else {
989        Err(TelemetryValidationError::CountBound)
990    }
991}
992
993fn bounded_many(values: &[u64]) -> Result<(), TelemetryValidationError> {
994    values.iter().try_for_each(|value| bounded(*value))
995}
996
997#[cfg(test)]
998mod tests {
999    use super::*;
1000
1001    fn envelope(event: TelemetryEventV2) -> TelemetryEnvelopeV2 {
1002        TelemetryEnvelopeV2 {
1003            schema_version: SCHEMA_VERSION,
1004            timestamp_bucket: "2026-09-08".into(),
1005            installation_id: "550e8400-e29b-41d4-a716-446655440000".into(),
1006            account_id: None,
1007            organization_id: None,
1008            app_version: "4.0.0".into(),
1009            event,
1010        }
1011    }
1012
1013    #[test]
1014    fn valid_typed_event_roundtrips() {
1015        let event = envelope(TelemetryEventV2::ToolUsageAggregate(ToolUsageMetrics {
1016            calls: 4,
1017            failures: 1,
1018            latency_milliseconds: Histogram {
1019                upper_bounds: vec![10, 100],
1020                counts: vec![1, 3],
1021            },
1022            tokens: Some(TokenMetrics {
1023                original: 12_000,
1024                delivered: 3_000,
1025            }),
1026        }));
1027        event.validate().unwrap();
1028        let encoded = serde_json::to_vec(&event).unwrap();
1029        let decoded: TelemetryEnvelopeV2 = serde_json::from_slice(&encoded).unwrap();
1030        assert_eq!(decoded, event);
1031    }
1032
1033    #[test]
1034    fn batch_is_bounded_and_validates_every_event() {
1035        let event = envelope(TelemetryEventV2::Heartbeat(HeartbeatMetrics {
1036            distribution_channel: DistributionChannel::Cargo,
1037            client_family: ClientFamily::Codex,
1038            operating_system: OperatingSystem::Linux,
1039            architecture: Architecture::X86_64,
1040            install_age: None,
1041            active_days: None,
1042            runtime_environment: None,
1043        }));
1044        let batch = TelemetryBatchV2 {
1045            schema_version: SCHEMA_VERSION,
1046            deletion_token_hash: "a".repeat(64),
1047            events: vec![event],
1048        };
1049        assert!(batch.validate().is_ok());
1050        let mut invalid_credential = batch.clone();
1051        invalid_credential.deletion_token_hash = "raw-secret".into();
1052        assert_eq!(
1053            invalid_credential.validate(),
1054            Err(TelemetryValidationError::DeletionTokenHash)
1055        );
1056        let empty = TelemetryBatchV2 {
1057            schema_version: SCHEMA_VERSION,
1058            deletion_token_hash: "a".repeat(64),
1059            events: Vec::new(),
1060        };
1061        assert_eq!(empty.validate(), Err(TelemetryValidationError::BatchSize));
1062    }
1063
1064    #[test]
1065    fn ops_context_fields_use_closed_wire_names_and_are_omitted_when_unset() {
1066        let mut metrics = HeartbeatMetrics {
1067            distribution_channel: DistributionChannel::Aur,
1068            client_family: ClientFamily::Codex,
1069            operating_system: OperatingSystem::Linux,
1070            architecture: Architecture::X86_64,
1071            install_age: None,
1072            active_days: None,
1073            runtime_environment: None,
1074        };
1075        let bare = serde_json::to_value(&metrics).unwrap();
1076        assert_eq!(
1077            bare.as_object().unwrap().len(),
1078            4,
1079            "unset fields stay off the wire: {bare}"
1080        );
1081        metrics.install_age = Some(InstallAge::Lt1h);
1082        metrics.active_days = Some(ActiveDays::D2To3);
1083        metrics.runtime_environment = Some(RuntimeEnvironment::CloudAgent);
1084        let full = serde_json::to_value(&metrics).unwrap();
1085        assert_eq!(full["distribution_channel"], "aur");
1086        assert_eq!(full["install_age"], "lt_1h");
1087        assert_eq!(full["active_days"], "d2_3");
1088        assert_eq!(full["runtime_environment"], "cloud_agent");
1089        let decoded: HeartbeatMetrics = serde_json::from_value(full).unwrap();
1090        assert_eq!(decoded, metrics);
1091        assert!(
1092            serde_json::from_value::<HeartbeatMetrics>(serde_json::json!({
1093                "distribution_channel": "cargo", "client_family": "codex",
1094                "operating_system": "linux", "architecture": "x86_64", "install_age": "3 days"
1095            }))
1096            .is_err()
1097        );
1098    }
1099
1100    #[test]
1101    fn ops_context_buckets_have_exact_boundaries() {
1102        assert_eq!(InstallAge::from_seconds(0), InstallAge::Lt1h);
1103        assert_eq!(InstallAge::from_seconds(3_599), InstallAge::Lt1h);
1104        assert_eq!(InstallAge::from_seconds(3_600), InstallAge::Lt1d);
1105        assert_eq!(InstallAge::from_seconds(86_400), InstallAge::Lt7d);
1106        assert_eq!(InstallAge::from_seconds(604_800), InstallAge::Lt30d);
1107        assert_eq!(InstallAge::from_seconds(2_592_000), InstallAge::Gte30d);
1108        assert_eq!(ActiveDays::from_count(0), ActiveDays::D1);
1109        assert_eq!(ActiveDays::from_count(1), ActiveDays::D1);
1110        assert_eq!(ActiveDays::from_count(3), ActiveDays::D2To3);
1111        assert_eq!(ActiveDays::from_count(7), ActiveDays::D4To7);
1112        assert_eq!(ActiveDays::from_count(14), ActiveDays::D8To14);
1113        assert_eq!(ActiveDays::from_count(15), ActiveDays::D15Plus);
1114    }
1115
1116    #[test]
1117    fn unknown_fields_are_rejected() {
1118        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"}}}"#;
1119        assert!(serde_json::from_str::<TelemetryEnvelopeV2>(raw).is_err());
1120    }
1121
1122    #[test]
1123    fn event_wrapper_preserves_valid_v2_wire_bytes() {
1124        let raw = r#"{"name":"setup_completed","metrics":{"count":1}}"#;
1125        let decoded: TelemetryEventV2 = serde_json::from_str(raw).unwrap();
1126        assert_eq!(decoded.name(), "setup_completed");
1127        decoded.validate().unwrap();
1128        assert_eq!(serde_json::to_string(&decoded).unwrap(), raw);
1129        let event = envelope(decoded);
1130        let encoded = serde_json::to_vec(&event).unwrap();
1131        let decoded: TelemetryEnvelopeV2 = serde_json::from_slice(&encoded).unwrap();
1132        assert_eq!(decoded, event);
1133        assert_eq!(serde_json::to_vec(&decoded).unwrap(), encoded);
1134    }
1135
1136    #[test]
1137    fn event_wrapper_rejects_forbidden_fields_in_every_key_position() {
1138        // Synthetic privacy fixtures only; no captured content or credentials.
1139        let forbidden = [
1140            ("source_code", "fn synthetic_fixture() {}"),
1141            ("absolute_path", "/synthetic/private/example.rs"),
1142            ("prompt", "synthetic private task instructions"),
1143            ("secret", "SYNTHETIC_NOT_A_CREDENTIAL"),
1144            (
1145                "repository_url",
1146                "https://example.invalid/private/project.git",
1147            ),
1148        ];
1149        for base in [
1150            r#"{"name":"setup_completed","metrics":{"count":1}}"#,
1151            r#"{"metrics":{"count":1},"name":"setup_completed"}"#,
1152        ] {
1153            let valid: TelemetryEventV2 = serde_json::from_str(base).unwrap();
1154            valid.validate().unwrap();
1155            for (field, value) in forbidden {
1156                let property = format!(
1157                    "{}:{}",
1158                    serde_json::to_string(field).unwrap(),
1159                    serde_json::to_string(value).unwrap()
1160                );
1161                let middle = base.find(',').unwrap();
1162                for injected in [
1163                    format!("{{{property},{}", &base[1..]),
1164                    format!("{},{property}{}", &base[..middle], &base[middle..]),
1165                    format!("{},{property}}}", &base[..base.len() - 1]),
1166                ] {
1167                    // Establish valid JSON independently: parse errors must be
1168                    // caused by the forbidden event field, not broken fixtures.
1169                    let parsed: serde_json::Value = serde_json::from_str(&injected).unwrap();
1170                    assert_eq!(parsed[field], value);
1171                    assert!(
1172                        serde_json::from_str::<TelemetryEventV2>(&injected).is_err(),
1173                        "unknown event field accepted: {field}"
1174                    );
1175                    let mut wrapped = serde_json::to_value(envelope(valid.clone())).unwrap();
1176                    wrapped["event"] = parsed;
1177                    assert!(serde_json::from_value::<TelemetryEnvelopeV2>(wrapped).is_err());
1178                }
1179            }
1180        }
1181    }
1182
1183    #[test]
1184    fn malformed_identity_date_and_version_are_rejected() {
1185        let mut event = envelope(TelemetryEventV2::Heartbeat(HeartbeatMetrics {
1186            distribution_channel: DistributionChannel::Cargo,
1187            client_family: ClientFamily::Codex,
1188            operating_system: OperatingSystem::Linux,
1189            architecture: Architecture::X86_64,
1190            install_age: None,
1191            active_days: None,
1192            runtime_environment: None,
1193        }));
1194        event.installation_id = "not-a-uuid".into();
1195        assert_eq!(
1196            event.validate(),
1197            Err(TelemetryValidationError::InstallationId)
1198        );
1199        event.installation_id = "550e8400-e29b-41d4-a716-446655440000".into();
1200        event.timestamp_bucket = "2026-02-30".into();
1201        assert_eq!(
1202            event.validate(),
1203            Err(TelemetryValidationError::TimestampBucket)
1204        );
1205        event.timestamp_bucket = "2026-09-08".into();
1206        event.schema_version = 3;
1207        assert_eq!(
1208            event.validate(),
1209            Err(TelemetryValidationError::SchemaVersion)
1210        );
1211    }
1212
1213    #[test]
1214    fn bounds_and_cross_field_counts_fail_closed() {
1215        let event = envelope(TelemetryEventV2::SyncAggregate(SyncMetrics {
1216            attempts: 1,
1217            successes: 1,
1218            failures: 1,
1219        }));
1220        assert_eq!(
1221            event.validate(),
1222            Err(TelemetryValidationError::InconsistentCounts)
1223        );
1224        let event = envelope(TelemetryEventV2::SetupCompleted(OccurrenceMetrics {
1225            count: MAX_COUNT + 1,
1226        }));
1227        assert_eq!(event.validate(), Err(TelemetryValidationError::CountBound));
1228    }
1229
1230    #[test]
1231    fn histogram_shape_and_order_are_bounded() {
1232        let histogram = Histogram {
1233            upper_bounds: vec![100, 10],
1234            counts: vec![1, 1],
1235        };
1236        assert_eq!(
1237            histogram.validate(),
1238            Err(TelemetryValidationError::Histogram)
1239        );
1240    }
1241
1242    #[test]
1243    fn pseudonymous_ids_never_accept_raw_identifiers() {
1244        assert!(PseudonymousId::new("customer@example.com").is_err());
1245        assert!(PseudonymousId::new(format!("hmac-sha256:{}", "a".repeat(64))).is_ok());
1246    }
1247
1248    #[test]
1249    fn pseudonymous_id_deserialization_preserves_constructor_invariant() {
1250        for raw in [
1251            "synthetic@example.invalid".to_owned(),
1252            "/synthetic/private/identity".to_owned(),
1253            String::new(),
1254            format!("hmac-sha256:{}", "a".repeat(63)),
1255            format!("hmac-sha256:{}", "A".repeat(64)),
1256            format!("hmac-sha256:{}", "g".repeat(64)),
1257        ] {
1258            assert!(PseudonymousId::new(raw.clone()).is_err());
1259            let encoded = serde_json::to_string(&raw).unwrap();
1260            let result = serde_json::from_str::<PseudonymousId>(&encoded);
1261            assert!(result.is_err(), "constructor invariant bypassed on wire");
1262            let message = result.unwrap_err().to_string();
1263            assert!(message.starts_with("invalid pseudonymous ID"));
1264            if !raw.is_empty() {
1265                assert!(!message.contains(&raw));
1266            }
1267        }
1268        let raw = format!("hmac-sha256:{}", "a".repeat(64));
1269        let encoded = serde_json::to_string(&raw).unwrap();
1270        let decoded: PseudonymousId = serde_json::from_str(&encoded).unwrap();
1271        assert_eq!(decoded, PseudonymousId::new(raw).unwrap());
1272        assert_eq!(serde_json::to_string(&decoded).unwrap(), encoded);
1273    }
1274
1275    #[test]
1276    fn envelope_rejects_raw_pseudonymous_ids_before_semantic_validation() {
1277        let event = envelope(TelemetryEventV2::SetupCompleted(OccurrenceMetrics {
1278            count: 1,
1279        }));
1280        for field in ["account_id", "organization_id"] {
1281            let mut wire = serde_json::to_value(&event).unwrap();
1282            wire[field] = serde_json::json!("synthetic@example.invalid");
1283            assert!(serde_json::from_value::<TelemetryEnvelopeV2>(wire).is_err());
1284        }
1285        let mut event_with_ids = event;
1286        event_with_ids.account_id =
1287            Some(PseudonymousId::new(format!("hmac-sha256:{}", "a".repeat(64))).unwrap());
1288        event_with_ids.organization_id =
1289            Some(PseudonymousId::new(format!("hmac-sha256:{}", "b".repeat(64))).unwrap());
1290        let encoded = serde_json::to_vec(&event_with_ids).unwrap();
1291        let decoded: TelemetryEnvelopeV2 = serde_json::from_slice(&encoded).unwrap();
1292        decoded.validate().unwrap();
1293        assert_eq!(decoded, event_with_ids);
1294        assert_eq!(serde_json::to_vec(&decoded).unwrap(), encoded);
1295    }
1296
1297    fn tool_call(tool: &str, calls: u64, failures: u64) -> ToolCallCount {
1298        ToolCallCount {
1299            tool: tool.into(),
1300            calls,
1301            failures,
1302            latency_milliseconds_total: None,
1303            failure_kinds: None,
1304            failure_messages: None,
1305        }
1306    }
1307
1308    fn tool_call_event(tools: Vec<ToolCallCount>) -> TelemetryEnvelopeV2 {
1309        envelope(TelemetryEventV2::ToolCallAggregate(ToolCallMetrics {
1310            tools,
1311        }))
1312    }
1313
1314    #[test]
1315    fn setup_profile_is_closed_enums_on_the_wire() {
1316        let event = TelemetryEventV2::SetupProfile(SetupProfileMetrics {
1317            integration_mode: IntegrationMode::Replace,
1318            embeddings: EmbeddingsState::NotInstalled,
1319        });
1320        let json = serde_json::to_value(&event).unwrap();
1321        assert_eq!(
1322            json,
1323            serde_json::json!({
1324                "name": "setup_profile",
1325                "metrics": {"integration_mode": "replace", "embeddings": "not_installed"}
1326            })
1327        );
1328        assert_eq!(
1329            serde_json::from_value::<TelemetryEventV2>(json).unwrap(),
1330            event
1331        );
1332        for bad in [
1333            serde_json::json!({"name": "setup_profile", "metrics": {"integration_mode": "/home/me", "embeddings": "installed"}}),
1334            serde_json::json!({"name": "setup_profile", "metrics": {"integration_mode": "mcp", "embeddings": "installed", "model": "x"}}),
1335        ] {
1336            assert!(serde_json::from_value::<TelemetryEventV2>(bad).is_err());
1337        }
1338    }
1339
1340    #[test]
1341    fn every_detected_client_id_maps_to_a_stable_wire_family() {
1342        let cases = [
1343            ("claude-code", "claude"),
1344            ("codex", "codex"),
1345            ("cursor", "cursor"),
1346            ("gemini-cli", "gemini"),
1347            ("windsurf", "windsurf"),
1348            ("zed", "zed"),
1349            ("vscode-copilot", "vscode_copilot"),
1350            ("kiro", "kiro"),
1351            ("antigravity", "antigravity"),
1352            ("codebuddy", "codebuddy"),
1353            ("codewhale", "codewhale"),
1354            ("pi", "pi"),
1355            ("oh-my-pi", "oh_my_pi"),
1356        ];
1357        for (id, wire) in cases {
1358            let family = ClientFamily::from_client_id(id).expect(id);
1359            assert_eq!(serde_json::to_value(family).unwrap(), wire);
1360        }
1361        assert_eq!(ClientFamily::from_client_id("unknown"), None);
1362        assert_eq!(ClientFamily::from_client_id("my-private-fork"), None);
1363    }
1364
1365    #[test]
1366    fn tool_call_aggregate_roundtrips_on_the_wire() {
1367        let event = tool_call_event(vec![tool_call("ctx_read", 5, 1), tool_call("shell", 2, 0)]);
1368        event.validate().unwrap();
1369        let encoded = serde_json::to_string(&event.event).unwrap();
1370        assert_eq!(
1371            encoded,
1372            r#"{"name":"tool_call_aggregate","metrics":{"tools":[{"tool":"ctx_read","calls":5,"failures":1},{"tool":"shell","calls":2,"failures":0}]}}"#
1373        );
1374        let decoded: TelemetryEnvelopeV2 =
1375            serde_json::from_slice(&serde_json::to_vec(&event).unwrap()).unwrap();
1376        assert_eq!(decoded, event);
1377    }
1378
1379    #[test]
1380    fn tool_call_aggregate_rejects_free_text_and_inconsistent_entries() {
1381        let reject = |tools: Vec<ToolCallCount>, expected| {
1382            assert_eq!(tool_call_event(tools).validate(), Err(expected));
1383        };
1384        use TelemetryValidationError::{InconsistentCounts, ToolEntries, ToolName};
1385        reject(Vec::new(), ToolEntries);
1386        reject(
1387            vec![tool_call("ctx_shell", 1, 0), tool_call("ctx_read", 1, 0)],
1388            ToolEntries,
1389        );
1390        reject(
1391            vec![tool_call("ctx_read", 1, 0), tool_call("ctx_read", 1, 0)],
1392            ToolEntries,
1393        );
1394        for name in [
1395            "",
1396            "Ctx_read",
1397            "ctx-read",
1398            "/etc/passwd",
1399            "ctx read",
1400            "_ctx",
1401        ] {
1402            reject(vec![tool_call(name, 1, 0)], ToolName);
1403        }
1404        reject(
1405            vec![tool_call(&"a".repeat(MAX_TOOL_NAME_LEN + 1), 1, 0)],
1406            ToolName,
1407        );
1408        reject(vec![tool_call("ctx_read", 0, 0)], InconsistentCounts);
1409        reject(vec![tool_call("ctx_read", 1, 2)], InconsistentCounts);
1410        let too_many = (0..=MAX_TOOL_ENTRIES)
1411            .map(|index| tool_call(&format!("tool_{index:04}"), 1, 0))
1412            .collect();
1413        reject(too_many, ToolEntries);
1414        let unknown_field = r#"{"name":"tool_call_aggregate","metrics":{"tools":[{"tool":"ctx_read","calls":1,"failures":0,"path":"/secret"}]}}"#;
1415        assert!(serde_json::from_str::<TelemetryEventV2>(unknown_field).is_err());
1416    }
1417}