返回 CodeWhale
event.rs
根目录 / crates / telemetry / src / event.rs
1 //! The wire schema. This module is the whole of what may leave the machine.
2 //!
3 //! Every field below is an integer, a boolean, or a **closed enum string**,
4 //! except exactly four bounded strings: `app_version`, `git_sha`,
5 //! `panic_site`, and `model_usage.model`, which is closed against the bundled
6 //! model catalog. Each of those four has a written rule. There is no free-form string type here and no open-keyed map, which is
7 //! what makes "aggregates and events, never content" a property the compiler
8 //! and the test suite can enforce rather than a promise.
9 //!
10 //! Bounded is not the same as *built bounded*. These types are also a
11 //! **deserialization target**: `flush` reads `buffer.jsonl` back off disk and
12 //! hands the lines to `serde`, which will fill `site`, `previous_version`, and
13 //! `providers` with any string the file contains. Anything running as the user
14 //! can append to that file, `$CODEWHALE_HOME` is a predictable path, and this
15 //! product executes model-authored shell commands. [`Event::is_bounded`] is
16 //! therefore checked on the drain path, and it is the reason the guarantee
17 //! above survives contact with the filesystem.
18 //!
19 //! Three standing rules for anyone extending this file:
20 //!
21 //! 1. **Never `#[derive(Serialize)]` over an existing state type.**
22 //! `codewhale_state::Thread` carries `git_sha`, `git_branch`,
23 //! `git_origin_url`, `cwd`, and `path`. A payload builder that accepts one
24 //! and derives breaches the red lines in a single line. Every struct here is
25 //! built from scratch with explicit fields.
26 //! 2. **Bump [`SCHEMA_VERSION`] on any field add, remove, or retype**, and
27 //! never reuse a number. The golden snapshot test fails until you do.
28 //! 3. **A new string field needs a clause in [`Event::is_bounded`]**, not just
29 //! a doc comment naming its rule. A rule only the constructor honours is a
30 //! rule the drain path does not have.
31
32 use serde::{Deserialize, Serialize};
33
34 /// Wire schema version. Bumped on any field add, remove, or retype; never
35 /// reused. `crates/telemetry/tests/golden/v1.json` pins what v1 was.
36 pub const SCHEMA_VERSION: u32 = 4;
37
38 /// Default-on policy disclosure version. This is not human consent.
39 pub const NOTICE_VERSION: u32 = 6;
40
41 /// Which product surface produced a batch.
42 ///
43 /// Deliberately **not** derived from the executable: `codewhale-tui` serves at
44 /// least five surfaces, and app-server runs in-process inside `codewhale`, so
45 /// `current_exe()` would report every app-server session as CLI. Each
46 /// subcommand dispatch names its own surface.
47 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
48 #[serde(rename_all = "kebab-case")]
49 pub enum Surface {
50 /// The interactive terminal UI.
51 Tui,
52 /// `codewhale exec` — one non-interactive run.
53 Exec,
54 /// Terminal `config` / `auth` / `update` subcommands.
55 Cli,
56 /// The app-server protocol surface (in-process inside `codewhale`).
57 AppServer,
58 /// The MCP server surface.
59 McpServer,
60 /// `codewhale serve`.
61 Serve,
62 /// Public website product interactions.
63 Website,
64 /// Browser application interactions.
65 WebApp,
66 /// Native desktop application interactions.
67 Desktop,
68 /// Control-plane application interactions.
69 ControlPlane,
70 /// A VS Code-family extension client of this schema.
71 ///
72 /// Deliberately **generic**, the way `web-app` and `desktop` are: the
73 /// client is not one publisher's extension, and a surface naming a vendor
74 /// would narrow the whitelist for every later extension built on the same
75 /// client. The editor's own name and version are **not** collected — this
76 /// value names the kind of client that emitted the batch, never the host
77 /// application it happened to run inside.
78 VscodeExtension,
79 }
80
81 impl Surface {
82 /// Every surface, for exhaustive iteration in tests and schema checks.
83 pub const ALL: &'static [Self] = &[
84 Self::Tui,
85 Self::Exec,
86 Self::Cli,
87 Self::AppServer,
88 Self::McpServer,
89 Self::Serve,
90 Self::Website,
91 Self::WebApp,
92 Self::Desktop,
93 Self::ControlPlane,
94 Self::VscodeExtension,
95 ];
96
97 /// The wire spelling.
98 #[must_use]
99 pub fn as_str(self) -> &'static str {
100 match self {
101 Self::Tui => "tui",
102 Self::Exec => "exec",
103 Self::Cli => "cli",
104 Self::AppServer => "app-server",
105 Self::McpServer => "mcp-server",
106 Self::Serve => "serve",
107 Self::Website => "website",
108 Self::WebApp => "web-app",
109 Self::Desktop => "desktop",
110 Self::ControlPlane => "control-plane",
111 Self::VscodeExtension => "vscode-extension",
112 }
113 }
114
115 /// The inverse of [`Self::as_str`], or `None` for anything else.
116 ///
117 /// The round trip is pinned by a test, so a value that can be spelled can
118 /// also be parsed and vice versa. This is the only place a surface name is
119 /// turned back into a variant, which is what lets an *embedder* declare one
120 /// without a second copy of the closed list.
121 #[must_use]
122 pub fn parse(value: &str) -> Option<Self> {
123 Self::ALL
124 .iter()
125 .copied()
126 .find(|surface| surface.as_str() == value)
127 }
128 }
129
130 /// Operating system family. A closed whitelist, so an unrecognised
131 /// `std::env::consts::OS` reports `other` rather than shipping a novel string.
132 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
133 #[serde(rename_all = "snake_case")]
134 pub enum Os {
135 /// Linux.
136 Linux,
137 /// macOS.
138 Macos,
139 /// Windows.
140 Windows,
141 /// FreeBSD.
142 Freebsd,
143 /// Android.
144 Android,
145 /// Anything else.
146 Other,
147 }
148
149 impl Os {
150 /// Every value, for exhaustive iteration.
151 pub const ALL: &'static [Self] = &[
152 Self::Linux,
153 Self::Macos,
154 Self::Windows,
155 Self::Freebsd,
156 Self::Android,
157 Self::Other,
158 ];
159
160 /// The wire spelling.
161 #[must_use]
162 pub fn as_str(self) -> &'static str {
163 match self {
164 Self::Linux => "linux",
165 Self::Macos => "macos",
166 Self::Windows => "windows",
167 Self::Freebsd => "freebsd",
168 Self::Android => "android",
169 Self::Other => "other",
170 }
171 }
172 }
173
174 /// CPU family.
175 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
176 #[serde(rename_all = "snake_case")]
177 pub enum Arch {
178 /// 64-bit x86.
179 X86_64,
180 /// 64-bit ARM.
181 Aarch64,
182 /// Anything else.
183 Other,
184 }
185
186 impl Arch {
187 /// Every value, for exhaustive iteration.
188 pub const ALL: &'static [Self] = &[Self::X86_64, Self::Aarch64, Self::Other];
189
190 /// The wire spelling.
191 #[must_use]
192 pub fn as_str(self) -> &'static str {
193 match self {
194 Self::X86_64 => "x86_64",
195 Self::Aarch64 => "aarch64",
196 Self::Other => "other",
197 }
198 }
199 }
200
201 /// C runtime the binary was **compiled** against.
202 ///
203 /// Compile-time (`cfg!(target_env)`), never runtime-detected: the only way to
204 /// read this at runtime is `/etc/os-release` or shelling to `ldd`, both of which
205 /// surface corporate golden-image vendor strings.
206 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
207 #[serde(rename_all = "snake_case")]
208 pub enum Libc {
209 /// glibc.
210 Gnu,
211 /// musl.
212 Musl,
213 /// Not a libc target (macOS, Windows, and anything else).
214 None,
215 }
216
217 impl Libc {
218 /// Every value, for exhaustive iteration.
219 pub const ALL: &'static [Self] = &[Self::Gnu, Self::Musl, Self::None];
220
221 /// The wire spelling.
222 #[must_use]
223 pub fn as_str(self) -> &'static str {
224 match self {
225 Self::Gnu => "gnu",
226 Self::Musl => "musl",
227 Self::None => "none",
228 }
229 }
230 }
231
232 /// Whether this binary is newly installed, upgraded, or downgraded.
233 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
234 #[serde(rename_all = "snake_case")]
235 pub enum InstallKind {
236 /// No prior version record on this machine.
237 Install,
238 /// The recorded version is older than this one.
239 Upgrade,
240 /// The recorded version is newer than this one.
241 Downgrade,
242 }
243
244 impl InstallKind {
245 /// Every value, for exhaustive iteration.
246 pub const ALL: &'static [Self] = &[Self::Install, Self::Upgrade, Self::Downgrade];
247
248 /// The wire spelling.
249 #[must_use]
250 pub fn as_str(self) -> &'static str {
251 match self {
252 Self::Install => "install",
253 Self::Upgrade => "upgrade",
254 Self::Downgrade => "downgrade",
255 }
256 }
257 }
258
259 /// How a session was started.
260 ///
261 /// Mirrors `codewhale_state::SessionSource` by value, deliberately re-declared
262 /// here rather than imported: this crate must not depend on the thread store,
263 /// which is the one crate whose types carry paths and git identity.
264 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
265 #[serde(rename_all = "snake_case")]
266 pub enum SessionSource {
267 /// A user opened a session directly.
268 Interactive,
269 /// Resumed from a persisted session.
270 Resume,
271 /// Forked from an existing conversation.
272 Fork,
273 /// Started programmatically.
274 Api,
275 /// Not stated.
276 Unknown,
277 /// Started under CI (`CI` or `GITHUB_ACTIONS` set), including the GitHub
278 /// Action, so automation is never counted as a person.
279 Ci,
280 }
281
282 impl SessionSource {
283 /// Every value, for exhaustive iteration.
284 pub const ALL: &'static [Self] = &[
285 Self::Interactive,
286 Self::Resume,
287 Self::Fork,
288 Self::Api,
289 Self::Unknown,
290 Self::Ci,
291 ];
292
293 /// The wire spelling.
294 #[must_use]
295 pub fn as_str(self) -> &'static str {
296 match self {
297 Self::Interactive => "interactive",
298 Self::Resume => "resume",
299 Self::Fork => "fork",
300 Self::Api => "api",
301 Self::Unknown => "unknown",
302 Self::Ci => "ci",
303 }
304 }
305 }
306
307 /// How long a session lasted, bucketed. Half-open intervals, in seconds.
308 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
309 #[serde(rename_all = "snake_case")]
310 pub enum DurationBucket {
311 /// `d < 60`
312 #[serde(rename = "lt_1m")]
313 Lt1m,
314 /// `60 <= d < 600`
315 #[serde(rename = "1m_10m")]
316 OneToTen,
317 /// `600 <= d < 3600`
318 #[serde(rename = "10m_60m")]
319 TenToSixty,
320 /// `d >= 3600`
321 #[serde(rename = "gt_60m")]
322 Gt60m,
323 }
324
325 impl DurationBucket {
326 /// Every value, for exhaustive iteration.
327 pub const ALL: &'static [Self] = &[Self::Lt1m, Self::OneToTen, Self::TenToSixty, Self::Gt60m];
328
329 /// Bucket a session duration in whole seconds.
330 #[must_use]
331 pub fn from_secs(secs: u64) -> Self {
332 match secs {
333 0..60 => Self::Lt1m,
334 60..600 => Self::OneToTen,
335 600..3600 => Self::TenToSixty,
336 _ => Self::Gt60m,
337 }
338 }
339
340 /// The wire spelling.
341 #[must_use]
342 pub fn as_str(self) -> &'static str {
343 match self {
344 Self::Lt1m => "lt_1m",
345 Self::OneToTen => "1m_10m",
346 Self::TenToSixty => "10m_60m",
347 Self::Gt60m => "gt_60m",
348 }
349 }
350 }
351
352 /// How the process ended.
353 ///
354 /// Derived from an explicit atomic set by the panic hook, the signal task, and
355 /// the clean path — **never from an exit code**.
356 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
357 #[serde(rename_all = "snake_case")]
358 pub enum ExitClass {
359 /// Ordinary successful exit.
360 Clean,
361 /// Terminated by a signal.
362 Signal,
363 /// Terminated by a panic.
364 Panic,
365 /// Exited non-successfully without a signal or a panic.
366 Error,
367 }
368
369 impl ExitClass {
370 /// Every value, for exhaustive iteration.
371 pub const ALL: &'static [Self] = &[Self::Clean, Self::Signal, Self::Panic, Self::Error];
372
373 /// The wire spelling.
374 #[must_use]
375 pub fn as_str(self) -> &'static str {
376 match self {
377 Self::Clean => "clean",
378 Self::Signal => "signal",
379 Self::Panic => "panic",
380 Self::Error => "error",
381 }
382 }
383
384 /// Stable numeric encoding for the process-wide `AtomicU8`.
385 #[must_use]
386 pub fn as_u8(self) -> u8 {
387 match self {
388 Self::Clean => 0,
389 Self::Signal => 1,
390 Self::Panic => 2,
391 Self::Error => 3,
392 }
393 }
394
395 /// Inverse of [`Self::as_u8`]; anything unrecognised reads as `Clean`.
396 #[must_use]
397 pub fn from_u8(value: u8) -> Self {
398 match value {
399 1 => Self::Signal,
400 2 => Self::Panic,
401 3 => Self::Error,
402 _ => Self::Clean,
403 }
404 }
405 }
406
407 /// Cold-start time, bucketed, in milliseconds.
408 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
409 #[serde(rename_all = "snake_case")]
410 pub enum ColdStartBucket {
411 /// `ms < 250`
412 #[serde(rename = "lt_250")]
413 Lt250,
414 /// `250 <= ms < 1000`
415 #[serde(rename = "250_1000")]
416 Mid,
417 /// `1000 <= ms < 3000`
418 #[serde(rename = "1000_3000")]
419 Slow,
420 /// `ms >= 3000`
421 #[serde(rename = "gte_3000")]
422 Gte3000,
423 }
424
425 impl ColdStartBucket {
426 /// Every value, for exhaustive iteration.
427 pub const ALL: &'static [Self] = &[Self::Lt250, Self::Mid, Self::Slow, Self::Gte3000];
428
429 /// Bucket a cold-start measurement in milliseconds.
430 #[must_use]
431 pub fn from_millis(ms: u64) -> Self {
432 match ms {
433 0..250 => Self::Lt250,
434 250..1000 => Self::Mid,
435 1000..3000 => Self::Slow,
436 _ => Self::Gte3000,
437 }
438 }
439
440 /// The wire spelling.
441 #[must_use]
442 pub fn as_str(self) -> &'static str {
443 match self {
444 Self::Lt250 => "lt_250",
445 Self::Mid => "250_1000",
446 Self::Slow => "1000_3000",
447 Self::Gte3000 => "gte_3000",
448 }
449 }
450 }
451
452 /// Feature-use counts for one session.
453 ///
454 /// A struct of named `u32`s rather than a map, deliberately: a
455 /// `BTreeMap<&'static str, u32>` is an open key set the compiler cannot police,
456 /// so the doc-match test would be asserting that the doc matches a fixture
457 /// rather than the binary. Adding a counter now requires editing this file,
458 /// which is where that test lives. Every field serializes, including zeros.
459 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
460 pub struct Counters {
461 /// Model turns completed.
462 pub turns: u32,
463 /// Tool calls executed, across every surface.
464 pub tool_calls: u32,
465 /// Fleet dispatches started.
466 pub fleet_dispatch: u32,
467 /// `workflow_run` invocations, keyed off the parsed action discriminant.
468 pub workflow_run: u32,
469 /// Sub-agents spawned.
470 pub subagent_spawn: u32,
471 /// MCP servers that reached `connected`.
472 pub mcp_server_connected: u32,
473 /// Native-memory searches.
474 pub memory_search: u32,
475 /// Approval modals shown.
476 pub approval_modal_shown: u32,
477 /// Approvals granted by an auto-allow rule.
478 pub approval_auto_allowed: u32,
479 /// Command-palette opens.
480 pub command_palette_open: u32,
481 }
482
483 impl Counters {
484 /// Field names in declaration order, for the doc-match test.
485 pub const FIELDS: &'static [&'static str] = &[
486 "turns",
487 "tool_calls",
488 "fleet_dispatch",
489 "workflow_run",
490 "subagent_spawn",
491 "mcp_server_connected",
492 "memory_search",
493 "approval_modal_shown",
494 "approval_auto_allowed",
495 "command_palette_open",
496 ];
497 }
498
499 /// Closed aggregate product counters shared with browser and app clients.
500 /// Runtime sessions keep their existing counters and add no second collector.
501 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
502 #[serde(deny_unknown_fields)]
503 pub struct ProductCounters {
504 /// Aggregate page view count.
505 pub page_view: u32,
506 /// Aggregate docs view count.
507 pub docs_view: u32,
508 /// Aggregate install copy count.
509 pub install_copy: u32,
510 /// Aggregate download count.
511 pub download: u32,
512 /// Aggregate signup count.
513 pub signup: u32,
514 /// Aggregate login count.
515 pub login: u32,
516 /// Aggregate session create count.
517 pub session_create: u32,
518 /// Aggregate session resume count.
519 pub session_resume: u32,
520 /// Aggregate turn submit count.
521 pub turn_submit: u32,
522 /// Aggregate turn complete count.
523 pub turn_complete: u32,
524 /// Aggregate settings open count.
525 pub settings_open: u32,
526 /// Aggregate integration connect count.
527 pub integration_connect: u32,
528 /// Aggregate error shown count.
529 pub error_shown: u32,
530 }
531
532 impl ProductCounters {
533 /// Closed wire field names.
534 pub const FIELDS: &'static [&'static str] = &[
535 "page_view",
536 "docs_view",
537 "install_copy",
538 "download",
539 "signup",
540 "login",
541 "session_create",
542 "session_resume",
543 "turn_submit",
544 "turn_complete",
545 "settings_open",
546 "integration_connect",
547 "error_shown",
548 ];
549 }
550
551 /// Error counts for one session.
552 ///
553 /// Every value is a count of a **variant discriminant**, never of an
554 /// `err.to_string()`. `ToolError::PathEscape`'s `Display` *is* an absolute path;
555 /// the secret store's *is* the store's absolute path; every `LlmError` variant
556 /// carries the raw provider HTTP body verbatim, and a 400 from a content filter
557 /// routinely echoes the prompt.
558 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
559 pub struct Errors {
560 /// Credential preflight rejected the route.
561 pub auth_preflight_failed: u32,
562 /// Provider responded 4xx.
563 pub provider_http_4xx: u32,
564 /// Provider responded 5xx.
565 pub provider_http_5xx: u32,
566 /// A tool call was denied by policy.
567 pub tool_denied_by_policy: u32,
568 /// A tool call timed out.
569 pub tool_timeout: u32,
570 /// A request failed below HTTP — DNS, connect, TLS, or timeout.
571 pub network_error: u32,
572 }
573
574 impl Errors {
575 /// Field names in declaration order, for the doc-match test.
576 pub const FIELDS: &'static [&'static str] = &[
577 "auth_preflight_failed",
578 "provider_http_4xx",
579 "provider_http_5xx",
580 "tool_denied_by_policy",
581 "tool_timeout",
582 "network_error",
583 ];
584 }
585
586 /// Per-session histogram of turn wall-clock time.
587 ///
588 /// A histogram, never a per-turn series: a timestamped stream of turn durations
589 /// reconstructs a session's working rhythm, which is the same objection that
590 /// rules out per-tool-call phone-home.
591 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
592 pub struct TurnWall {
593 /// Turns under 5 seconds.
594 pub lt_5s: u32,
595 /// Turns in `[5s, 30s)`.
596 #[serde(rename = "5_30s")]
597 pub five_to_thirty: u32,
598 /// Turns in `[30s, 120s)`.
599 #[serde(rename = "30_120s")]
600 pub thirty_to_onetwenty: u32,
601 /// Turns at or over 120 seconds.
602 pub gte_120s: u32,
603 }
604
605 impl TurnWall {
606 /// Field names in wire spelling, in declaration order.
607 pub const FIELDS: &'static [&'static str] = &["lt_5s", "5_30s", "30_120s", "gte_120s"];
608
609 /// Record one turn of `secs` wall-clock seconds.
610 pub fn observe_secs(&mut self, secs: u64) {
611 match secs {
612 0..5 => self.lt_5s = self.lt_5s.saturating_add(1),
613 5..30 => self.five_to_thirty = self.five_to_thirty.saturating_add(1),
614 30..120 => self.thirty_to_onetwenty = self.thirty_to_onetwenty.saturating_add(1),
615 _ => self.gte_120s = self.gte_120s.saturating_add(1),
616 }
617 }
618 }
619
620 /// One telemetry event.
621 ///
622 /// The tag is the `event` key, so the wire form is flat and the variant set is
623 /// closed.
624 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
625 #[serde(tag = "event", rename_all = "snake_case")]
626 pub enum Event {
627 /// This binary's version differs from the one last recorded on this machine.
628 InstallOrUpgrade {
629 /// Install, upgrade, or downgrade.
630 kind: InstallKind,
631 /// The previously recorded version, read from the telemetry state file
632 /// **only** — never from session history or config mtimes, which have a
633 /// different privacy contract.
634 previous_version: Option<String>,
635 },
636 /// A session began.
637 SessionStart {
638 /// How it was started.
639 source: SessionSource,
640 },
641 /// A session ended. Everything the session accumulated ships here, once.
642 SessionEnd {
643 /// Bucketed wall-clock session length.
644 duration_bucket: DurationBucket,
645 /// How the process ended.
646 exit_class: ExitClass,
647 /// Bucketed cold start. `null` on surfaces that do not measure it.
648 cold_start_bucket: Option<ColdStartBucket>,
649 /// Sorted, deduplicated `ProviderKind` names. A custom provider yields
650 /// the literal `"custom"`, never the customer's `[providers.<name>]`
651 /// table key; bundled public-catalog model ids are reported separately
652 /// in `ModelUsage` (all other models map to `"other"`).
653 providers: Vec<String>,
654 /// Feature-use counts.
655 counters: Counters,
656 /// Error counts.
657 errors: Errors,
658 /// Turn wall-clock histogram.
659 turn_wall: TurnWall,
660 },
661 /// The process panicked.
662 Panic {
663 /// Source location, reduced by the `crates/` allowlist. Never the panic
664 /// *message*: a slicing panic embeds the entire string being sliced, and
665 /// this tree slices user and model text in dozens of places.
666 site: String,
667 },
668 /// Anonymous service health aggregates under explicit operator consent.
669 OperationsSummary {
670 /// Aggregate requests.
671 requests: u32,
672 /// Aggregate errors.
673 errors: u32,
674 /// Aggregate duration ms total.
675 duration_ms_total: u32,
676 /// Aggregate duration ms max.
677 duration_ms_max: u32,
678 /// Aggregate probes.
679 probes: u32,
680 /// Aggregate probes failed.
681 probes_failed: u32,
682 },
683 /// Aggregate browser or application interactions without a timeline.
684 ProductUsage {
685 /// Closed counts; never a URL, user identity, or work content.
686 counters: ProductCounters,
687 },
688 /// One session's model turns and token counts for one provider and model.
689 ModelUsage {
690 /// A known provider id ([`is_known_provider_id`]).
691 provider: String,
692 /// A bundled-catalog model id, or `other` ([`is_reported_model_id`]).
693 model: String,
694 /// Turn outcomes and token totals.
695 counters: ModelCounters,
696 /// Turn wall-clock buckets for these turns.
697 turn_wall: TurnWall,
698 },
699 /// One session's calls of one tool.
700 ToolUsage {
701 /// A first-party tool name, `mcp` or `other` ([`is_reported_tool_name`]).
702 tool: String,
703 /// Calls made.
704 calls: u32,
705 /// Calls that returned an error.
706 errors: u32,
707 },
708 }
709
710 /// Turn outcomes and token totals for one provider and model in a session.
711 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
712 pub struct ModelCounters {
713 /// Turns that completed.
714 pub turns_ok: u32,
715 /// Turns that failed.
716 pub turns_failed: u32,
717 /// Turns the user or the runtime interrupted.
718 pub turns_interrupted: u32,
719 /// Input tokens, including cache reads.
720 pub input_tokens: u64,
721 /// Output tokens, including reasoning.
722 pub output_tokens: u64,
723 /// Input tokens served from the provider's prompt cache.
724 pub cache_read_tokens: u64,
725 /// Input tokens written to the provider's prompt cache.
726 pub cache_write_tokens: u64,
727 }
728
729 impl ModelCounters {
730 /// Wire keys, in order.
731 pub const FIELDS: &'static [&'static str] = &[
732 "turns_ok",
733 "turns_failed",
734 "turns_interrupted",
735 "input_tokens",
736 "output_tokens",
737 "cache_read_tokens",
738 "cache_write_tokens",
739 ];
740 }
741
742 /// First-party tool names reported by `tool_usage`. Any other name is
743 /// reported as `mcp` or `other`, so a plugin's or server's tool name never
744 /// leaves the machine.
745 pub const TOOL_NAMES: &[&str] = &[
746 "agent",
747 "apply_patch",
748 "authenticate",
749 "automation_adopt",
750 "automation_create",
751 "automation_delete",
752 "automation_list",
753 "automation_pause",
754 "automation_read",
755 "automation_resume",
756 "automation_run",
757 "automation_update",
758 "bash",
759 "code_execution",
760 "context_archive_search",
761 "create_goal",
762 "edit",
763 "edit_file",
764 "exec_shell",
765 "execute_tools",
766 "fetch_url",
767 "file_search",
768 "fim_edit",
769 "get_goal",
770 "git_blame",
771 "git_commit_plan",
772 "git_diff",
773 "git_fetch",
774 "git_log",
775 "git_merge_tree",
776 "git_review_scope",
777 "git_show",
778 "git_status",
779 "github_close_issue",
780 "github_close_pr",
781 "github_comment",
782 "github_issue_context",
783 "github_pr_context",
784 "github_report_draft",
785 "github_report_read",
786 "grep_files",
787 "handle_read",
788 "image_ocr",
789 "list_dir",
790 "load_skill",
791 "lsp",
792 "memory_search",
793 "notify",
794 "pandoc_convert",
795 "pr_attempt_list",
796 "pr_attempt_preflight",
797 "pr_attempt_read",
798 "pr_attempt_record",
799 "present",
800 "read",
801 "read_file",
802 "read_media",
803 "remember",
804 "request_plugin_install",
805 "request_user_input",
806 "retrieve_tool_result",
807 "revert_turn",
808 "review",
809 "rlm",
810 "run_tests",
811 "run_verifiers",
812 "send_later",
813 "session_search",
814 "show_data",
815 "speech",
816 "start_mcp_server",
817 "task_cancel",
818 "task_create",
819 "task_gate_run",
820 "task_list",
821 "task_read",
822 "task_shell_wait",
823 "terminal_cancel",
824 "terminal_reset",
825 "terminal_run",
826 "terminal_send",
827 "terminal_wait",
828 "todo_write",
829 "tool_search",
830 "tui_help",
831 "update_goal",
832 "validate_data",
833 "wait_for_dev_server",
834 "web.run",
835 "web_search",
836 "workflow",
837 "write",
838 "write_file",
839 ];
840
841 /// The `tool` value for a tool name: itself when first-party, `mcp` for an
842 /// MCP pool tool, otherwise `other`.
843 #[must_use]
844 pub fn reported_tool_name(name: &str, is_mcp: bool) -> &'static str {
845 match TOOL_NAMES.iter().find(|known| **known == name) {
846 Some(known) => known,
847 None if is_mcp => "mcp",
848 None => "other",
849 }
850 }
851
852 /// Whether `value` may appear as `tool_usage.tool`.
853 #[must_use]
854 pub fn is_reported_tool_name(value: &str) -> bool {
855 value == "mcp" || value == "other" || TOOL_NAMES.contains(&value)
856 }
857
858 /// The `model` value for a model id: the lowercased id when the bundled model
859 /// catalog lists it, otherwise `other`. Custom, local and fine-tuned model
860 /// names therefore never leave the machine.
861 #[must_use]
862 pub fn reported_model_id(model: &str) -> String {
863 let id = model.trim().to_ascii_lowercase();
864 if is_catalogued_model(&id) {
865 id
866 } else {
867 "other".to_string()
868 }
869 }
870
871 /// Whether `value` may appear as `model_usage.model`.
872 #[must_use]
873 pub fn is_reported_model_id(value: &str) -> bool {
874 value == "other" || (value == value.to_ascii_lowercase() && is_catalogued_model(value))
875 }
876
877 fn is_catalogued_model(id: &str) -> bool {
878 if id.is_empty() || id.len() > 128 {
879 return false;
880 }
881 let catalog = codewhale_config::catalog::bundled_models_dev_catalog();
882 catalog.reviewed.intrinsic.contains_key(id)
883 || catalog
884 .models
885 .keys()
886 .any(|key| key.eq_ignore_ascii_case(id))
887 || catalog.providers.values().any(|provider| {
888 provider
889 .models
890 .keys()
891 .any(|key| key.eq_ignore_ascii_case(id))
892 })
893 }
894
895 impl Event {
896 /// The `event` discriminant, for the doc-match test.
897 #[must_use]
898 pub fn name(&self) -> &'static str {
899 match self {
900 Self::InstallOrUpgrade { .. } => "install_or_upgrade",
901 Self::SessionStart { .. } => "session_start",
902 Self::SessionEnd { .. } => "session_end",
903 Self::Panic { .. } => "panic",
904 Self::ProductUsage { .. } => "product_usage",
905 Self::ModelUsage { .. } => "model_usage",
906 Self::ToolUsage { .. } => "tool_usage",
907 Self::OperationsSummary { .. } => "operations_summary",
908 }
909 }
910
911 /// One representative instance per event variant for schema and manifest tests.
912 #[must_use]
913 pub fn sample_all() -> Vec<Self> {
914 vec![
915 Self::InstallOrUpgrade {
916 kind: InstallKind::Upgrade,
917 previous_version: Some("0.9.3-rc.1".to_string()),
918 },
919 Self::SessionStart {
920 source: SessionSource::Resume,
921 },
922 Self::SessionEnd {
923 duration_bucket: DurationBucket::OneToTen,
924 exit_class: ExitClass::Panic,
925 cold_start_bucket: Some(ColdStartBucket::Mid),
926 providers: vec!["custom".to_string(), "deepseek".to_string()],
927 counters: Counters {
928 turns: 14,
929 tool_calls: 61,
930 fleet_dispatch: 0,
931 workflow_run: 0,
932 subagent_spawn: 2,
933 mcp_server_connected: 0,
934 memory_search: 0,
935 approval_modal_shown: 0,
936 approval_auto_allowed: 0,
937 command_palette_open: 3,
938 },
939 errors: Errors {
940 auth_preflight_failed: 0,
941 provider_http_4xx: 0,
942 provider_http_5xx: 1,
943 tool_denied_by_policy: 0,
944 tool_timeout: 0,
945 network_error: 0,
946 },
947 turn_wall: TurnWall {
948 lt_5s: 9,
949 five_to_thirty: 4,
950 thirty_to_onetwenty: 1,
951 gte_120s: 0,
952 },
953 },
954 Self::Panic {
955 site: "crates/tui/src/tui/ui.rs:8801:17".to_string(),
956 },
957 Self::ProductUsage {
958 counters: ProductCounters {
959 page_view: 1,
960 ..ProductCounters::default()
961 },
962 },
963 Self::OperationsSummary {
964 requests: 10,
965 errors: 1,
966 duration_ms_total: 1500,
967 duration_ms_max: 300,
968 probes: 2,
969 probes_failed: 0,
970 },
971 Self::ModelUsage {
972 provider: "deepseek".to_string(),
973 model: "other".to_string(),
974 counters: ModelCounters {
975 turns_ok: 12,
976 turns_failed: 1,
977 turns_interrupted: 0,
978 input_tokens: 418_230,
979 output_tokens: 9_120,
980 cache_read_tokens: 380_001,
981 cache_write_tokens: 0,
982 },
983 turn_wall: TurnWall {
984 lt_5s: 3,
985 five_to_thirty: 8,
986 thirty_to_onetwenty: 2,
987 gte_120s: 0,
988 },
989 },
990 Self::ToolUsage {
991 tool: "read_file".to_string(),
992 calls: 41,
993 errors: 2,
994 },
995 ]
996 }
997
998 /// Whether every string this event carries is inside its declared bound.
999 ///
1000 /// The bounds above are enforced by the *constructors* — `Counters` is a
1001 /// struct of `u32`s, `providers` comes from `ProviderKind::as_str()`, and
1002 /// `site` comes from [`crate::reduce_panic_site`]. That holds only for an
1003 /// event this process built. Events are also **read back from
1004 /// `buffer.jsonl` and deserialized** before a batch is assembled, and
1005 /// `serde` will happily fill `site`, `previous_version`, and `providers`
1006 /// with any string the file contains. Anything running as this user can
1007 /// append a line to that file — including a `Bash` tool call this session
1008 /// made on the model's behalf — so the drain path must re-establish the
1009 /// bound rather than inherit it.
1010 ///
1011 /// Failing this check drops the event. It is never *sanitized*: a payload
1012 /// that the schema cannot account for is not made safe by editing it.
1013 #[must_use]
1014 pub fn is_bounded(&self) -> bool {
1015 match self {
1016 Self::SessionStart { .. }
1017 | Self::ProductUsage { .. }
1018 | Self::OperationsSummary { .. } => true,
1019 Self::InstallOrUpgrade {
1020 previous_version, ..
1021 } => previous_version
1022 .as_deref()
1023 .is_none_or(is_release_version_string),
1024 Self::SessionEnd { providers, .. } => {
1025 providers.iter().all(|name| is_known_provider_id(name))
1026 }
1027 Self::Panic { site } => is_reduced_panic_site(site),
1028 Self::ModelUsage {
1029 provider, model, ..
1030 } => is_known_provider_id(provider) && is_reported_model_id(model),
1031 Self::ToolUsage { tool, .. } => is_reported_tool_name(tool),
1032 }
1033 }
1034 }
1035
1036 /// Whether `value` is a release version this schema may carry.
1037 ///
1038 /// `^\d+\.\d+\.\d+(-[0-9A-Za-z.]+)?$` — the rule already written on
1039 /// [`Batch::app_version`], applied to `previous_version` as well because that
1040 /// field is read back from `state.json` rather than built in this process.
1041 #[must_use]
1042 pub fn is_release_version_string(value: &str) -> bool {
1043 let (core, pre) = match value.split_once('-') {
1044 Some((core, pre)) => (core, Some(pre)),
1045 None => (value, None),
1046 };
1047 let parts: Vec<&str> = core.split('.').collect();
1048 if parts.len() != 3
1049 || !parts
1050 .iter()
1051 .all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()))
1052 {
1053 return false;
1054 }
1055 match pre {
1056 None => true,
1057 Some(pre) => !pre.is_empty() && pre.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'.'),
1058 }
1059 }
1060
1061 /// Whether `value` is in the output space of [`crate::reduce_panic_site`]:
1062 /// the literal `<dep>`, or `crates/…​.rs:<line>:<column>` over the allowlist
1063 /// charset.
1064 #[must_use]
1065 pub fn is_reduced_panic_site(value: &str) -> bool {
1066 if value == "<dep>" {
1067 return true;
1068 }
1069 let Some((file, rest)) = value.split_once(".rs:") else {
1070 return false;
1071 };
1072 let Some((line, column)) = rest.split_once(':') else {
1073 return false;
1074 };
1075 file.starts_with("crates/")
1076 && file
1077 .bytes()
1078 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'/' | b'.' | b'-'))
1079 && !line.is_empty()
1080 && line.bytes().all(|b| b.is_ascii_digit())
1081 && !column.is_empty()
1082 && column.bytes().all(|b| b.is_ascii_digit())
1083 }
1084
1085 /// Whether `value` is a provider id this build knows.
1086 ///
1087 /// Checked against the **full** provider registry, not
1088 /// `ProviderKind::all()`: that list is the selectable catalog subset, while
1089 /// captured intrinsic kinds legitimately include dialect kinds
1090 /// (`deepseek-anthropic`, the Model Studio plan variants) that are absent from
1091 /// it. Narrowing to the catalog would silently drop a real user's route.
1092 #[must_use]
1093 pub fn is_known_provider_id(value: &str) -> bool {
1094 codewhale_config::provider::all_providers()
1095 .iter()
1096 .any(|provider| provider.id() == value)
1097 }
1098
1099 /// The POST body. One per flush.
1100 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1101 pub struct Batch {
1102 /// [`SCHEMA_VERSION`].
1103 pub schema_version: u32,
1104 /// [`NOTICE_VERSION`], policy metadata rather than proof of acceptance.
1105 pub notice_version: u32,
1106 /// RFC3339 UTC, second precision. Per-**batch** only — events carry no
1107 /// timestamps at all.
1108 pub sent_at: String,
1109 /// Random v4 UUID stored on this machine, rotated every 90 days.
1110 pub install_id: String,
1111 /// `CARGO_PKG_VERSION`. Must match `^\d+\.\d+\.\d+(-[0-9A-Za-z.]+)?$`.
1112 pub app_version: String,
1113 /// First 12 hex chars of the release-CI build sha, or `null` for every
1114 /// locally built binary.
1115 pub git_sha: Option<String>,
1116 /// Which surface produced this batch.
1117 pub surface: Surface,
1118 /// OS family.
1119 pub os: Os,
1120 /// CPU family.
1121 pub arch: Arch,
1122 /// Compile-time libc.
1123 pub libc: Libc,
1124 /// Whether both stdin and stdout were terminals.
1125 pub tty: bool,
1126 /// The events.
1127 pub events: Vec<Event>,
1128 }
1129
1130 impl Batch {
1131 /// Envelope field names in declaration order, for the doc-match test.
1132 pub const FIELDS: &'static [&'static str] = &[
1133 "schema_version",
1134 "notice_version",
1135 "sent_at",
1136 "install_id",
1137 "app_version",
1138 "git_sha",
1139 "surface",
1140 "os",
1141 "arch",
1142 "libc",
1143 "tty",
1144 "events",
1145 ];
1146 }
1147
1147 lines RUST