返回 CodeWhale
tests.rs
根目录 / crates / telemetry / src / tests.rs
1 //! The tests are the contract.
2 //!
3 //! Two of them are load-bearing beyond ordinary coverage:
4 //! `every_payload_field_is_bounded` walks a fully-populated batch and asserts
5 //! that every string leaf is a member of a declared enum set or one of exactly
6 //! three regexed strings, and `every_string_leaf_survives_redaction_unchanged`
7 //! runs the workflow crate's disclosure redactor over each leaf **individually**
8 //! — never over the serialized document, which would be one whitespace-free
9 //! token and would report clean no matter what it contained.
10
11 use std::path::{Path, PathBuf};
12 use std::time::{Duration, Instant};
13
14 use codewhale_config::{
15 CliRuntimeOverrides, ConfigToml, ResolvedRuntimeOptions, SetupState, TELEMETRY_NOTICE_VERSION,
16 };
17 use serde_json::Value;
18
19 use crate::buffer;
20 use crate::decision::{
21 EndpointError, TelemetryDecision, decide_in_home, load_setup_state_for_decision_at,
22 permission_still_enabled_in_home, re_decide_with_setup_path, validate_endpoint,
23 };
24 use crate::envelope;
25 use crate::event::*;
26
27 // ---------------------------------------------------------------- fixtures --
28
29 fn temp_home() -> tempfile::TempDir {
30 tempfile::tempdir().expect("temp home")
31 }
32
33 fn root_of(home: &tempfile::TempDir) -> PathBuf {
34 home.path().join(crate::TELEMETRY_DIR)
35 }
36
37 /// A resolved-options value with everything but telemetry left at its default.
38 fn resolved(telemetry: bool, explicit_off: bool, endpoint: Option<&str>) -> ResolvedRuntimeOptions {
39 let mut options =
40 ConfigToml::default().resolve_runtime_options(&CliRuntimeOverrides::default());
41 options.telemetry = telemetry;
42 options.telemetry_explicit_off = explicit_off;
43 options.telemetry_endpoint = endpoint.map(str::to_string);
44 options
45 }
46
47 fn accepted_setup() -> SetupState {
48 let mut setup = SetupState::default();
49 setup.record_telemetry_notice(TELEMETRY_NOTICE_VERSION, true);
50 setup
51 }
52
53 fn declined_setup() -> SetupState {
54 let mut setup = SetupState::default();
55 setup.record_telemetry_notice(TELEMETRY_NOTICE_VERSION, false);
56 setup
57 }
58
59 fn stale_setup() -> SetupState {
60 let mut setup = SetupState::default();
61 setup.record_telemetry_notice("0", true);
62 setup
63 }
64
65 #[test]
66 fn setup_state_loader_defaults_only_when_the_privacy_record_is_absent() {
67 let home = temp_home();
68 let path = home.path().join("setup_state.json");
69
70 assert!(
71 load_setup_state_for_decision_at(&path).is_some(),
72 "a genuinely fresh install uses the documented default"
73 );
74
75 std::fs::write(&path, b"{not-json").expect("write corrupt setup state");
76 assert!(
77 load_setup_state_for_decision_at(&path).is_none(),
78 "an existing unreadable privacy record must fail closed"
79 );
80
81 accepted_setup()
82 .save_to(&path)
83 .expect("write valid setup state");
84 assert!(
85 load_setup_state_for_decision_at(&path)
86 .is_some_and(|setup| setup.telemetry_accepted(TELEMETRY_NOTICE_VERSION)),
87 "a valid setup state remains usable"
88 );
89 }
90
91 #[test]
92 fn flush_redecision_fails_closed_on_a_corrupt_setup_state() {
93 let home = temp_home();
94 let config_path = home.path().join("config.toml");
95 let setup_path = home.path().join("setup_state.json");
96 std::fs::write(&config_path, "telemetry = true\n").expect("write config");
97 std::fs::write(&setup_path, b"{not-json").expect("write corrupt setup state");
98
99 assert!(matches!(
100 re_decide_with_setup_path(Some(&config_path), &setup_path, Surface::Exec),
101 TelemetryDecision::ForcedOff
102 ));
103 }
104
105 /// One instance of every event variant, populated with the most adversarial
106 /// values the schema permits.
107 ///
108 /// **This list is hand-written, and the compiler cannot make you extend it.**
109 /// A new `Event` variant carrying a free-form `String` would be walked by none
110 /// of the red-line tests below — they all start here — and `golden_payload_v1`
111 /// would still pass, because it serializes this same fixture. Nothing closes
112 /// that hole from inside this file; enumerating an enum's variants needs
113 /// reflection this workspace deliberately does not depend on. What does bite is
114 /// [`Event::is_bounded`], whose `match self` is exhaustive: adding a variant
115 /// fails the build until its author states a bound. If you are that author,
116 /// add the variant here too.
117 fn every_event() -> Vec<Event> {
118 Event::sample_all()
119 }
120
121 /// A fully-populated batch. This is the artifact the red-line tests walk.
122 pub(crate) fn every_field_batch() -> Batch {
123 Batch {
124 schema_version: SCHEMA_VERSION,
125 notice_version: NOTICE_VERSION,
126 sent_at: "2026-08-03T18:04:11Z".to_string(),
127 install_id: "3f2a9c1e-0000-4000-8000-000000000001".to_string(),
128 app_version: "0.9.4".to_string(),
129 git_sha: Some("abcdef012345".to_string()),
130 surface: Surface::ControlPlane,
131 os: Os::Macos,
132 arch: Arch::Aarch64,
133 libc: Libc::None,
134 tty: true,
135 events: every_event(),
136 }
137 }
138
139 // --------------------------------------------------------- schema red lines --
140
141 fn walk_strings(value: &Value, path: &str, out: &mut Vec<(String, String)>) {
142 match value {
143 Value::String(text) => out.push((path.to_string(), text.clone())),
144 Value::Array(items) => {
145 for (index, item) in items.iter().enumerate() {
146 walk_strings(item, &format!("{path}[{index}]"), out);
147 }
148 }
149 Value::Object(map) => {
150 for (key, item) in map {
151 let child = if path.is_empty() {
152 key.clone()
153 } else {
154 format!("{path}.{key}")
155 };
156 walk_strings(item, &child, out);
157 }
158 }
159 _ => {}
160 }
161 }
162
163 pub(crate) fn string_leaves(value: &Value) -> Vec<(String, String)> {
164 let mut out = Vec::new();
165 walk_strings(value, "", &mut out);
166 out
167 }
168
169 // The version and panic-site rules are the shipped predicates, not local
170 // copies. A test that re-implements the rule it is checking passes against a
171 // binary that enforces nothing — which is exactly what
172 // `a_hostile_buffer_line_never_reaches_a_batch` found the first time.
173 use crate::event::{is_reduced_panic_site, is_release_version_string as is_app_version};
174
175 fn is_short_sha(value: &str) -> bool {
176 value.len() == 12
177 && value
178 .bytes()
179 .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
180 }
181
182 /// Every closed-enum string this schema may ever emit.
183 fn closed_enum_values() -> Vec<String> {
184 let mut values: Vec<String> = Vec::new();
185 values.extend(Surface::ALL.iter().map(|v| v.as_str().to_string()));
186 values.extend(Os::ALL.iter().map(|v| v.as_str().to_string()));
187 values.extend(Arch::ALL.iter().map(|v| v.as_str().to_string()));
188 values.extend(Libc::ALL.iter().map(|v| v.as_str().to_string()));
189 values.extend(InstallKind::ALL.iter().map(|v| v.as_str().to_string()));
190 values.extend(SessionSource::ALL.iter().map(|v| v.as_str().to_string()));
191 values.extend(DurationBucket::ALL.iter().map(|v| v.as_str().to_string()));
192 values.extend(ExitClass::ALL.iter().map(|v| v.as_str().to_string()));
193 values.extend(ColdStartBucket::ALL.iter().map(|v| v.as_str().to_string()));
194 // The `event` tag values.
195 values.extend(every_event().iter().map(|e| e.name().to_string()));
196 // `providers` entries: `ProviderKind::as_str()` is a `&'static str` from a
197 // closed enum, and `Custom` yields the literal "custom".
198 values.extend(
199 codewhale_config::ProviderKind::all()
200 .iter()
201 .map(|kind| kind.as_str().to_string()),
202 );
203 values
204 }
205
206 #[test]
207 fn every_payload_field_is_bounded() {
208 let batch = every_field_batch();
209 let json = serde_json::to_value(&batch).expect("serialize batch");
210 let enums = closed_enum_values();
211 let leaves = string_leaves(&json);
212 assert!(
213 leaves.len() >= 10,
214 "the walk found suspiciously few string leaves: {leaves:?}"
215 );
216
217 for (path, value) in leaves {
218 let ok = match path.as_str() {
219 "app_version" => is_app_version(&value),
220 "git_sha" => is_short_sha(&value),
221 "sent_at" => value.ends_with('Z') && value.len() == 20,
222 "install_id" => uuid::Uuid::parse_str(&value).is_ok(),
223 p if p.ends_with(".site") => is_reduced_panic_site(&value),
224 p if p.ends_with(".previous_version") => is_app_version(&value),
225 p if p.ends_with(".tool") => is_reported_tool_name(&value),
226 p if p.ends_with(".model") => is_reported_model_id(&value),
227 _ => enums.contains(&value),
228 };
229 assert!(ok, "unbounded string leaf at {path}: {value:?}");
230 }
231 }
232
233 #[test]
234 fn counters_and_errors_serialize_every_field_including_zeros() {
235 let json = serde_json::to_value(Counters::default()).expect("serialize counters");
236 let object = json.as_object().expect("counters is an object");
237 assert_eq!(object.len(), Counters::FIELDS.len());
238 for field in Counters::FIELDS {
239 assert_eq!(object.get(*field), Some(&Value::from(0u32)), "{field}");
240 }
241
242 let json = serde_json::to_value(Errors::default()).expect("serialize errors");
243 let object = json.as_object().expect("errors is an object");
244 assert_eq!(object.len(), Errors::FIELDS.len());
245 for field in Errors::FIELDS {
246 assert_eq!(object.get(*field), Some(&Value::from(0u32)), "{field}");
247 }
248
249 let json = serde_json::to_value(TurnWall::default()).expect("serialize turn_wall");
250 let object = json.as_object().expect("turn_wall is an object");
251 assert_eq!(object.len(), TurnWall::FIELDS.len());
252 for field in TurnWall::FIELDS {
253 assert_eq!(object.get(*field), Some(&Value::from(0u32)), "{field}");
254 }
255 }
256
257 #[test]
258 fn no_event_field_is_ever_omitted() {
259 // Options serialize as `null` rather than being skipped, so the key set on
260 // the wire is closed and the golden-match test can be exact.
261 let event = Event::SessionEnd {
262 duration_bucket: DurationBucket::Lt1m,
263 exit_class: ExitClass::Clean,
264 cold_start_bucket: None,
265 providers: Vec::new(),
266 counters: Counters::default(),
267 errors: Errors::default(),
268 turn_wall: TurnWall::default(),
269 };
270 let json = serde_json::to_value(&event).expect("serialize");
271 assert_eq!(json.get("cold_start_bucket"), Some(&Value::Null));
272
273 let event = Event::InstallOrUpgrade {
274 kind: InstallKind::Install,
275 previous_version: None,
276 };
277 let json = serde_json::to_value(&event).expect("serialize");
278 assert_eq!(json.get("previous_version"), Some(&Value::Null));
279 }
280
281 // ------------------------------------------------------ scrubber assertions --
282
283 /// Run the workflow crate's disclosure redactor over **each string leaf**.
284 ///
285 /// Never over the serialized document: `redact_for_disclosure` tokenizes with
286 /// `input.split(' ')`, and a compact `serde_json` batch has no spaces, so the
287 /// whole document would be one token and every classifier would fail on it. A
288 /// batch containing an absolute path, a live-looking key, and a whole prompt
289 /// would report clean. The gate would detect nothing while appearing to pass.
290 fn redaction_kinds_over_leaves(json: &Value) -> Vec<String> {
291 let mut kinds = Vec::new();
292 for (_, value) in string_leaves(json) {
293 let redaction = codewhale_workflow::redaction::redact_for_disclosure(&value);
294 if redaction.redacted() {
295 kinds.extend(redaction.kinds());
296 }
297 }
298 kinds
299 }
300
301 #[test]
302 fn every_string_leaf_survives_redaction_unchanged() {
303 let json = serde_json::to_value(every_field_batch()).expect("serialize batch");
304 let kinds = redaction_kinds_over_leaves(&json);
305 assert!(
306 kinds.is_empty(),
307 "a real payload tripped the disclosure redactor: {kinds:?}"
308 );
309 }
310
311 #[test]
312 fn redaction_catches_a_planted_absolute_path() {
313 let mut json = serde_json::to_value(every_field_batch()).expect("serialize batch");
314 json["app_version"] = Value::from("/Users/hunter/src/app/main.rs");
315 let kinds = redaction_kinds_over_leaves(&json);
316 assert!(
317 kinds.iter().any(|k| k == "absolute_path"),
318 "the negative control did not fire: {kinds:?}"
319 );
320 }
321
322 #[test]
323 fn redaction_catches_a_planted_secret() {
324 let mut json = serde_json::to_value(every_field_batch()).expect("serialize batch");
325 // Deliberately low-entropy: a realistic token in a fixture trips secret
326 // scanners at push time.
327 json["app_version"] = Value::from("api_key=sk-live-abcdef0123456789abcdef");
328 let kinds = redaction_kinds_over_leaves(&json);
329 assert!(
330 kinds.iter().any(|k| k == "secret"),
331 "the negative control did not fire: {kinds:?}"
332 );
333 }
334
335 #[test]
336 fn panic_site_is_the_only_field_that_may_carry_a_path() {
337 // `panic_site` is a repo-relative path by design, so it is the one
338 // documented exemption. Prove the redactor would flag such a value, and
339 // that no other leaf in a real payload carries one.
340 let planted = codewhale_workflow::redaction::redact_for_disclosure("crates/tui/src/main.rs");
341 assert!(
342 planted.kinds().iter().any(|k| k == "relative_path"),
343 "the redactor no longer classifies a repo-relative path: {:?}",
344 planted.kinds()
345 );
346
347 let json = serde_json::to_value(every_field_batch()).expect("serialize batch");
348 for (path, value) in string_leaves(&json) {
349 if path.ends_with(".site") {
350 continue;
351 }
352 let redaction = codewhale_workflow::redaction::redact_for_disclosure(&value);
353 assert!(
354 !redaction.kinds().iter().any(|k| k.ends_with("path")),
355 "a non-exempt leaf carries a path: {path} = {value:?}"
356 );
357 }
358 }
359
360 // ------------------------------------------- the drain path is a boundary --
361
362 /// The buffer is a **deserializer input**, not an internal channel.
363 ///
364 /// Every bound above is a property of how this process *builds* an event.
365 /// `flush` re-reads `buffer.jsonl` and hands the lines to `serde`, and any
366 /// process running as the user can append to that file — including a `Bash`
367 /// tool call the session made on the model's behalf, since `$CODEWHALE_HOME`
368 /// is a predictable path. Before `Event::is_bounded` existed, an appended
369 /// `{"event":"panic","site":"…/Users/victim/secret-repo"}` was POSTed verbatim
370 /// to the configured endpoint under the user's install id; the process-level
371 /// proof of that is `a_hostile_buffer_line_never_reaches_a_batch` in
372 /// `crates/tui/tests/telemetry_contract.rs`.
373 #[test]
374 fn hostile_buffer_lines_are_dropped_before_they_reach_a_batch() {
375 let hostile = [
376 // A path, which is the class `panic_site` is the sole exemption for.
377 r#"{"event":"panic","site":"/Users/victim/src/secret-repo/main.rs"}"#,
378 // A whole prompt in the one field that is allowed to look like text.
379 r#"{"event":"panic","site":"rewrite the auth module for acme-corp"}"#,
380 // A frame outside the `crates/` allowlist, spelled to look inside it.
381 r#"{"event":"panic","site":"../vendor/crates/foo/src/lib.rs:1:1"}"#,
382 // `previous_version` is read back from `state.json`, never validated
383 // at the point it is written.
384 r#"{"event":"install_or_upgrade","kind":"upgrade","previous_version":"/Users/victim/.ssh/id_ed25519"}"#,
385 // A customer's `[providers.<name>]` table key — the exact string
386 // `record_provider` takes a `ProviderKind` by value to avoid.
387 r#"{"event":"session_end","duration_bucket":"lt_1m","exit_class":"clean","cold_start_bucket":null,"providers":["acme_internal_gateway"],"counters":{"turns":0,"tool_calls":0,"fleet_dispatch":0,"workflow_run":0,"subagent_spawn":0,"mcp_server_connected":0,"memory_search":0,"approval_modal_shown":0,"approval_auto_allowed":0,"command_palette_open":0},"errors":{"auth_preflight_failed":0,"provider_http_4xx":0,"provider_http_5xx":0,"tool_denied_by_policy":0,"tool_timeout":0,"network_error":0},"turn_wall":{"lt_5s":0,"5_30s":0,"30_120s":0,"gte_120s":0}}"#,
388 ];
389 for line in hostile {
390 let event = serde_json::from_str::<Event>(line)
391 .unwrap_or_else(|error| panic!("the fixture must be parseable: {error}\n{line}"));
392 assert!(
393 !event.is_bounded(),
394 "an out-of-bounds event passed the drain check: {line}"
395 );
396 let parsed = crate::actor::parse_events(&[line.to_string()]);
397 assert!(
398 parsed.is_empty(),
399 "a hostile buffer line survived the drain: {line}"
400 );
401 }
402 }
403
404 /// The drain check must not delete real telemetry. Everything this process
405 /// legitimately records has to survive a round trip through the buffer.
406 #[test]
407 fn every_legitimately_recorded_event_survives_the_drain() {
408 let lines: Vec<String> = every_event()
409 .iter()
410 .map(|event| serde_json::to_string(event).expect("serialize"))
411 .collect();
412 assert_eq!(
413 crate::actor::parse_events(&lines).len(),
414 lines.len(),
415 "the drain check dropped an event this process builds itself"
416 );
417
418 // Dialect kinds (`deepseek-anthropic`, the Model Studio plan variants) are
419 // absent from the selectable `ProviderKind::ALL` catalog subset,
420 // but captured intrinsic kinds include them for real routes. Narrowing the
421 // provider bound to the catalog would drop those users' `session_end`.
422 for kind in [
423 codewhale_config::ProviderKind::DeepseekAnthropic,
424 codewhale_config::ProviderKind::MinimaxAnthropic,
425 codewhale_config::ProviderKind::Custom,
426 ] {
427 assert!(
428 crate::event::is_known_provider_id(kind.as_str()),
429 "a real routed provider is not a legal `providers` entry: {}",
430 kind.as_str()
431 );
432 }
433 }
434
435 /// `install_id` is the one envelope field read verbatim off disk into a batch.
436 #[test]
437 fn a_non_uuid_install_id_on_disk_is_replaced_rather_than_sent() {
438 let home = temp_home();
439 let root = root_of(&home);
440 buffer::ensure_dir(&root).expect("create telemetry root");
441 std::fs::write(
442 buffer::install_id_path(&root),
443 serde_json::json!({
444 "schema_version": 1,
445 "install_id": "/Users/victim/src/secret-repo",
446 "rotated_at": envelope::now_rfc3339(),
447 })
448 .to_string(),
449 )
450 .expect("plant a hostile install id");
451
452 let record = envelope::read_or_create_install_id(&root).expect("read install id");
453 assert!(
454 uuid::Uuid::parse_str(&record.install_id).is_ok(),
455 "a non-UUID install id was carried onto the wire: {:?}",
456 record.install_id
457 );
458 }
459
460 /// Audit R05-09: only a canonical v4 id with a past `rotated_at` survives a
461 /// read. A v1 (MAC + clock), nil, braced, uppercase, or padded id is replaced,
462 /// and so is a future timestamp that would otherwise never rotate.
463 #[test]
464 fn a_non_canonical_or_future_dated_install_id_is_rotated() {
465 let now = envelope::now_rfc3339();
466 let future = (chrono::Utc::now() + chrono::Duration::days(3650))
467 .to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
468 let canonical = "3f2a9c1e-0000-4000-8000-000000000001";
469 for (install_id, rotated_at) in [
470 ("6ba7b810-9dad-11d1-80b4-00c04fd430c8", now.as_str()),
471 ("00000000-0000-0000-0000-000000000000", now.as_str()),
472 ("{3f2a9c1e-0000-4000-8000-000000000001}", now.as_str()),
473 ("3F2A9C1E-0000-4000-8000-000000000001", now.as_str()),
474 (" 3f2a9c1e-0000-4000-8000-000000000001 ", now.as_str()),
475 (canonical, future.as_str()),
476 ] {
477 let home = temp_home();
478 let root = root_of(&home);
479 buffer::ensure_dir(&root).expect("create telemetry root");
480 std::fs::write(
481 buffer::install_id_path(&root),
482 serde_json::json!({
483 "schema_version": 1,
484 "install_id": install_id,
485 "rotated_at": rotated_at,
486 })
487 .to_string(),
488 )
489 .expect("plant install id");
490
491 let record = envelope::read_or_create_install_id(&root).expect("read install id");
492 assert_ne!(record.install_id, install_id, "kept {install_id:?}");
493 let minted = uuid::Uuid::parse_str(&record.install_id).expect("minted uuid");
494 assert_eq!(minted.get_version(), Some(uuid::Version::Random));
495 }
496
497 // The canonical, past-dated form is kept.
498 let home = temp_home();
499 let root = root_of(&home);
500 buffer::ensure_dir(&root).expect("create telemetry root");
501 let kept = envelope::InstallId {
502 schema_version: 1,
503 install_id: canonical.to_string(),
504 rotated_at: now.clone(),
505 };
506 std::fs::write(
507 buffer::install_id_path(&root),
508 serde_json::to_string(&kept).unwrap(),
509 )
510 .expect("plant canonical id");
511 let record = envelope::read_or_create_install_id(&root).expect("read install id");
512 assert_eq!(record.install_id, canonical);
513 }
514
515 // ------------------------------------------------------------- panic sites --
516
517 #[test]
518 fn panic_site_reduces_dependency_frames() {
519 assert_eq!(
520 envelope::reduce_panic_site("crates/tui/src/x.rs", 9, 1),
521 "crates/tui/src/x.rs:9:1"
522 );
523 assert_eq!(
524 envelope::reduce_panic_site(
525 "/Users/builder/.cargo/registry/src/index.crates.io-1949cf8c/ratatui-0.29.0/src/y.rs",
526 1,
527 1
528 ),
529 "<dep>"
530 );
531 assert_eq!(
532 envelope::reduce_panic_site("/rustc/deadbeef/library/core/src/panicking.rs", 1, 1),
533 "<dep>"
534 );
535 // A path that merely mentions `crates/` somewhere is not a `crates/` frame.
536 assert_eq!(
537 envelope::reduce_panic_site("../vendor/crates/foo/src/lib.rs", 1, 1),
538 "<dep>"
539 );
540 }
541
542 #[test]
543 fn git_sha_is_null_without_release_env() {
544 // The build script emits `CODEWHALE_RELEASE_BUILD_SHA` only when
545 // `CODEWHALE_BUILD_SHA` (or a build-only compatibility alias) was in the
546 // build environment, so on a developer machine this is `None` and on
547 // release CI it is twelve hex characters. Both are asserted, because the
548 // test has to pass in both places and neither shape may ever be a path, a
549 // version, or a full sha.
550 // The rule that produces it lives in `codewhale-build-support` and is
551 // tested there against an injected environment; what is asserted here is
552 // that whatever reaches the payload is `null` or twelve lowercase hex
553 // characters, and never a path, a version, or a full sha.
554 if let Some(sha) = envelope::release_build_sha() {
555 assert!(
556 is_short_sha(&sha),
557 "release sha has the wrong shape: {sha:?}"
558 );
559 }
560 assert_eq!(
561 envelope::short_hex_sha("ABCDEF0123456789abcdef0123456789abcdef01"),
562 Some("abcdef012345".to_string())
563 );
564 assert_eq!(envelope::short_hex_sha("not-a-sha"), None);
565 assert_eq!(envelope::short_hex_sha("abc123"), None);
566 }
567
568 // --------------------------------------------------------------- decisions --
569
570 #[test]
571 fn decision_matrix_is_exhaustive() {
572 let home = temp_home();
573 let path = home.path();
574
575 // Row: nobody has said anything. No acceptance is inferred.
576 assert!(matches!(
577 decide_in_home(
578 Some(path),
579 &resolved(true, false, None),
580 &SetupState::default(),
581 Surface::Tui
582 ),
583 TelemetryDecision::Enabled(_)
584 ));
585
586 // Row: a human said off. That is an answer.
587 assert!(matches!(
588 decide_in_home(
589 Some(path),
590 &resolved(false, true, None),
591 &accepted_setup(),
592 Surface::Tui
593 ),
594 TelemetryDecision::OptedOut
595 ));
596
597 // Row: config on with no notice record also uses the default-on policy.
598 assert!(matches!(
599 decide_in_home(
600 Some(path),
601 &resolved(true, false, None),
602 &SetupState::default(),
603 Surface::Tui
604 ),
605 TelemetryDecision::Enabled(_)
606 ));
607
608 // Row: on, asked, declined.
609 assert!(matches!(
610 decide_in_home(
611 Some(path),
612 &resolved(true, false, None),
613 &declined_setup(),
614 Surface::Tui
615 ),
616 TelemetryDecision::OptedOut
617 ));
618
619 // Row: old explicit yes remains on under the current default-on policy.
620 assert!(matches!(
621 decide_in_home(
622 Some(path),
623 &resolved(true, false, None),
624 &stale_setup(),
625 Surface::Tui
626 ),
627 TelemetryDecision::Enabled(_)
628 ));
629
630 // Row: on and accepted, no home to keep state in.
631 assert!(matches!(
632 decide_in_home(
633 None,
634 &resolved(true, false, None),
635 &accepted_setup(),
636 Surface::Tui
637 ),
638 TelemetryDecision::ForcedOff
639 ));
640
641 // Row: on and accepted, plaintext endpoint to a public host.
642 assert!(matches!(
643 decide_in_home(
644 Some(path),
645 &resolved(true, false, Some("http://example.com/t")),
646 &accepted_setup(),
647 Surface::Tui
648 ),
649 TelemetryDecision::ForcedOff
650 ));
651
652 // Row: on and accepted, no endpoint — the dry-run sink, which resolution
653 // reaches from an explicitly empty `telemetry_endpoint`. (The *shipped*
654 // default is `DEFAULT_TELEMETRY_ENDPOINT`; this predicate never sees it,
655 // because it reads an already-resolved value.)
656 let decision = decide_in_home(
657 Some(path),
658 &resolved(true, false, None),
659 &accepted_setup(),
660 Surface::Exec,
661 );
662 let TelemetryDecision::Enabled(consent) = decision else {
663 panic!("an accepted, endpoint-less machine must be Enabled");
664 };
665 assert_eq!(consent.endpoint(), None);
666 assert_eq!(consent.surface(), Surface::Exec);
667 assert_eq!(consent.root(), root_of(&home));
668
669 // Row: on and accepted, https endpoint.
670 assert!(
671 decide_in_home(
672 Some(path),
673 &resolved(true, false, Some("https://example.com/t")),
674 &accepted_setup(),
675 Surface::Tui
676 )
677 .is_enabled()
678 );
679
680 // Row: every headless surface uses the same documented default and kill
681 // switches.
682 for surface in Surface::ALL {
683 assert!(
684 decide_in_home(
685 Some(path),
686 &resolved(true, false, None),
687 &SetupState::default(),
688 *surface
689 )
690 .is_enabled(),
691 "{surface:?} uses default-on without inferring acceptance"
692 );
693 }
694 }
695
696 #[test]
697 fn every_surface_spelling_parses_back_to_its_variant() {
698 // `Surface::parse` is the only place a name becomes a variant, and an
699 // embedder declares itself by name, so the round trip has to be exact in
700 // both directions. A value that can be spelled must parse; a variant must
701 // not be reachable under a second spelling.
702 for surface in Surface::ALL {
703 assert_eq!(
704 Surface::parse(surface.as_str()),
705 Some(*surface),
706 "{surface:?} does not parse back from its own wire spelling"
707 );
708 }
709 assert_eq!(
710 Surface::parse("TUI"),
711 None,
712 "parsing is exact, not case-folded"
713 );
714 assert_eq!(Surface::parse(" vscode-extension "), None, "no trimming");
715 assert_eq!(Surface::parse("vscode"), None);
716 assert_eq!(Surface::parse("ide"), None);
717 assert_eq!(Surface::parse(""), None);
718 assert_eq!(Surface::parse("desktop"), Some(Surface::Desktop));
719 }
720
721 #[test]
722 fn an_unparseable_env_value_forces_off_and_does_not_wipe() {
723 // The floor in `codewhale-config` turns an unreadable `CODEWHALE_TELEMETRY`
724 // into `telemetry == false` *without* setting `telemetry_explicit_off`. A
725 // typo is not a user answer and must never destroy state.
726 let home = temp_home();
727 let root = root_of(&home);
728 buffer::ensure_dir(&root).expect("create root");
729 let buffer_path = buffer::buffer_path(&root);
730 buffer::append(
731 &root,
732 &buffer_path,
733 "{\"event\":\"session_start\",\"source\":\"api\"}",
734 )
735 .expect("seed");
736
737 let decision = decide_in_home(
738 Some(home.path()),
739 &resolved(false, false, None),
740 &accepted_setup(),
741 Surface::Tui,
742 );
743 assert!(matches!(decision, TelemetryDecision::ForcedOff));
744 assert!(!buffer::tombstone_present(&root));
745 assert_eq!(buffer::read_lines(&buffer_path).len(), 1);
746 }
747
748 #[test]
749 fn only_opt_out_touches_disk() {
750 // Every ForcedOff row against a seeded, consenting home must leave it
751 // byte-identical. This is the finding that a "wipe on resolved false" would
752 // have broken: `false` is the *default*, so it fired on every ordinary run.
753 let forced_off_rows: Vec<(ResolvedRuntimeOptions, SetupState)> = vec![
754 (resolved(false, false, None), accepted_setup()),
755 (
756 resolved(true, false, Some("http://example.com/t")),
757 accepted_setup(),
758 ),
759 ];
760
761 for (options, setup) in forced_off_rows {
762 let home = temp_home();
763 let root = root_of(&home);
764 buffer::ensure_dir(&root).expect("create root");
765 let before = seed_consenting_home(&root);
766
767 let decision = decide_in_home(Some(home.path()), &options, &setup, Surface::Tui);
768 assert!(
769 matches!(decision, TelemetryDecision::ForcedOff),
770 "expected ForcedOff, got {}",
771 decision.label()
772 );
773 assert_eq!(snapshot(&root), before, "a ForcedOff run touched disk");
774 }
775
776 // Every OptedOut row wipes: tombstone present, data truncated, lock file
777 // still present, identity gone.
778 let home = temp_home();
779 let root = root_of(&home);
780 buffer::ensure_dir(&root).expect("create root");
781 seed_consenting_home(&root);
782
783 let decision = decide_in_home(
784 Some(home.path()),
785 &resolved(false, true, None),
786 &accepted_setup(),
787 Surface::Tui,
788 );
789 assert!(matches!(decision, TelemetryDecision::OptedOut));
790 assert!(buffer::tombstone_present(&root));
791 assert!(buffer::buffer_path(&root).exists());
792 assert!(buffer::read_lines(&buffer::buffer_path(&root)).is_empty());
793 assert!(buffer::read_lines(&buffer::dryrun_path(&root)).is_empty());
794 assert!(
795 buffer::lock_path(&root).exists(),
796 "the lock file must survive a wipe: unlinking it leaves appenders on a dead inode"
797 );
798 assert!(!buffer::install_id_path(&root).exists());
799 assert!(!buffer::state_path(&root).exists());
800 }
801
802 #[test]
803 fn default_on_does_not_hide_a_durable_sidecar_decline() {
804 let home = temp_home();
805 let root = root_of(&home);
806 buffer::ensure_dir(&root).expect("create root");
807 let before = seed_consenting_home(&root);
808 let mut options = resolved(false, false, None);
809
810 // A run-scoped kill switch still preserves the preexisting ordering.
811 options.telemetry_source = codewhale_config::TelemetrySource::Env;
812 assert!(matches!(
813 decide_in_home(Some(home.path()), &options, &declined_setup(), Surface::Tui),
814 TelemetryDecision::ForcedOff
815 ));
816 assert_eq!(snapshot(&root), before);
817
818 // Once that temporary switch is gone, the durable decline must wipe even
819 // though the new shipped configuration preference is on.
820 options.telemetry = true;
821 options.telemetry_source = codewhale_config::TelemetrySource::Default;
822 assert!(matches!(
823 decide_in_home(Some(home.path()), &options, &declined_setup(), Surface::Tui),
824 TelemetryDecision::OptedOut
825 ));
826 assert!(buffer::tombstone_present(&root));
827 assert!(!buffer::install_id_path(&root).exists());
828 assert!(buffer::read_lines(&buffer::buffer_path(&root)).is_empty());
829 }
830
831 #[test]
832 fn the_tombstone_outlives_every_run_the_opt_out_covers() {
833 // `docs/TELEMETRY.md` says the opt-out's tombstone survives, and an
834 // adversary showed it did not: one ordinary run afterwards called
835 // `buffer::arm`, which removes the tombstone, and minted a fresh install
836 // id. Both halves of that are now impossible, and for the same reason —
837 // the opt-out is a *persisted* statement, so every later run re-reads it,
838 // takes the OptedOut branch again, and never reaches arming at all.
839 let home = temp_home();
840 let root = root_of(&home);
841 buffer::ensure_dir(&root).expect("create root");
842 seed_consenting_home(&root);
843
844 // The user writes `telemetry = false`.
845 let opted_out = resolved(false, true, None);
846 assert!(matches!(
847 decide_in_home(
848 Some(home.path()),
849 &opted_out,
850 &accepted_setup(),
851 Surface::Tui
852 ),
853 TelemetryDecision::OptedOut
854 ));
855 assert!(buffer::tombstone_present(&root));
856 let after_wipe = snapshot(&root);
857
858 // Three more launches of any surface, with the setting still in place.
859 for surface in [Surface::Tui, Surface::Exec, Surface::AppServer] {
860 let decision = decide_in_home(Some(home.path()), &opted_out, &accepted_setup(), surface);
861 assert!(
862 matches!(decision, TelemetryDecision::OptedOut),
863 "{surface:?} re-read the opt-out as {}",
864 decision.label()
865 );
866 assert!(
867 buffer::tombstone_present(&root),
868 "{surface:?} cleared the tombstone"
869 );
870 assert!(
871 !buffer::install_id_path(&root).exists(),
872 "{surface:?} minted a new identity for an opted-out machine"
873 );
874 assert!(!buffer::state_path(&root).exists());
875 assert!(buffer::read_lines(&buffer::buffer_path(&root)).is_empty());
876 assert!(buffer::read_lines(&buffer::dryrun_path(&root)).is_empty());
877 assert_eq!(snapshot(&root), after_wipe, "{surface:?} touched disk");
878 }
879
880 // Only writing the setting back turns collection on again, and that is the
881 // one path allowed to clear the tombstone.
882 let TelemetryDecision::Enabled(consent) = decide_in_home(
883 Some(home.path()),
884 &resolved(true, false, None),
885 &accepted_setup(),
886 Surface::Tui,
887 ) else {
888 panic!("an explicit re-enable must produce consent");
889 };
890 buffer::arm(&root, consent.tombstone_generation(), || true).expect("re-consent arms");
891 assert!(!buffer::tombstone_present(&root));
892 }
893
894 #[test]
895 fn a_run_scoped_kill_switch_costs_a_consenting_user_nothing() {
896 // The documented one-command recipe — `CODEWHALE_TELEMETRY=0 codewhale` —
897 // used to take the destructive opt-out branch, so it deleted the install
898 // id and truncated the user's own dry-run records every time it was used.
899 // The resolver now reports that as "off, but nobody revoked anything", and
900 // this is the half of that contract the telemetry crate owns.
901 let home = temp_home();
902 let root = root_of(&home);
903 buffer::ensure_dir(&root).expect("create root");
904 let before = seed_consenting_home(&root);
905 let identity = std::fs::read(buffer::install_id_path(&root)).expect("seeded install id");
906
907 for _ in 0..3 {
908 let decision = decide_in_home(
909 Some(home.path()),
910 // `telemetry == false`, `telemetry_explicit_off == false`: the
911 // shape a run-scoped kill switch resolves to.
912 &resolved(false, false, None),
913 &accepted_setup(),
914 Surface::Exec,
915 );
916 assert!(matches!(decision, TelemetryDecision::ForcedOff));
917 }
918
919 assert_eq!(snapshot(&root), before, "a kill-switch run touched disk");
920 assert!(!buffer::tombstone_present(&root));
921 assert_eq!(
922 std::fs::read(buffer::install_id_path(&root)).expect("install id"),
923 identity,
924 "the install id churned across a kill-switch run"
925 );
926 }
927
928 #[test]
929 fn an_opt_out_on_a_fresh_home_creates_nothing() {
930 let home = temp_home();
931 let root = root_of(&home);
932 let decision = decide_in_home(
933 Some(home.path()),
934 &resolved(false, true, None),
935 &SetupState::default(),
936 Surface::Tui,
937 );
938 assert!(matches!(decision, TelemetryDecision::OptedOut));
939 assert!(
940 !root.exists(),
941 "a fresh user who opts out must not get a telemetry directory"
942 );
943 }
944
945 fn seed_consenting_home(root: &Path) -> Vec<(String, Vec<u8>)> {
946 buffer::append(
947 root,
948 &buffer::buffer_path(root),
949 "{\"event\":\"session_start\",\"source\":\"interactive\"}",
950 )
951 .expect("seed buffer");
952 buffer::append_locked(root, &buffer::dryrun_path(root), "{\"schema_version\":1}")
953 .expect("seed dryrun");
954 envelope::read_or_create_install_id(root).expect("seed install id");
955 envelope::write_state(root, &envelope::TelemetryState::default()).expect("seed state");
956 snapshot(root)
957 }
958
959 fn snapshot(root: &Path) -> Vec<(String, Vec<u8>)> {
960 let Ok(entries) = std::fs::read_dir(root) else {
961 return Vec::new();
962 };
963 let mut out: Vec<(String, Vec<u8>)> = entries
964 .filter_map(Result::ok)
965 .map(|entry| {
966 let name = entry.file_name().to_string_lossy().to_string();
967 let body = std::fs::read(entry.path()).unwrap_or_default();
968 (name, body)
969 })
970 .collect();
971 out.sort();
972 out
973 }
974
975 #[test]
976 fn failed_wipe_fails_closed() {
977 let home = temp_home();
978 let root = root_of(&home);
979 buffer::ensure_dir(&root).expect("create root");
980 seed_consenting_home(&root);
981
982 // Make the buffer un-truncatable. The tombstone is written first, so even
983 // when the rest of the wipe fails the buffer is permanently undrainable.
984 let buffer_path = buffer::buffer_path(&root);
985 let readonly_worked = make_read_only(&buffer_path);
986
987 let result = buffer::wipe(&root);
988 assert!(
989 buffer::tombstone_present(&root),
990 "the tombstone must survive"
991 );
992 if readonly_worked {
993 assert!(result.is_err(), "a failed truncate must be reported");
994 }
995 assert!(
996 crate::spool::take_own(&root, &buffer_path).is_empty(),
997 "a tombstoned buffer must never drain, wipe failure or not"
998 );
999 assert!(
1000 buffer::append(
1001 &root,
1002 &buffer_path,
1003 "{\"event\":\"session_start\",\"source\":\"api\"}"
1004 )
1005 .is_none(),
1006 "a tombstoned buffer must never accept an append"
1007 );
1008 }
1009
1010 #[cfg(unix)]
1011 fn make_read_only(path: &Path) -> bool {
1012 use std::os::unix::fs::PermissionsExt as _;
1013 // Root ignores the mode bits, so this fixture cannot be relied on there.
1014 if geteuid_is_root() {
1015 return false;
1016 }
1017 std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o400)).is_ok()
1018 }
1019
1020 #[cfg(unix)]
1021 fn geteuid_is_root() -> bool {
1022 unsafe extern "C" {
1023 fn geteuid() -> u32;
1024 }
1025 unsafe { geteuid() == 0 }
1026 }
1027
1028 #[cfg(not(unix))]
1029 fn make_read_only(_path: &Path) -> bool {
1030 false
1031 }
1032
1033 // --------------------------------------------------------------- endpoints --
1034
1035 #[test]
1036 fn plain_http_is_rejected_except_on_loopback() {
1037 assert!(validate_endpoint("https://example.com/t").is_ok());
1038 assert_eq!(
1039 validate_endpoint("http://example.com/t"),
1040 Err(EndpointError::InsecureScheme)
1041 );
1042 assert!(validate_endpoint("http://127.0.0.1:9/x").is_ok());
1043 assert!(validate_endpoint("http://localhost:9/x").is_ok());
1044 assert!(validate_endpoint("http://[::1]:9/x").is_ok());
1045 assert_eq!(
1046 validate_endpoint("ftp://example.com/t"),
1047 Err(EndpointError::UnsupportedScheme)
1048 );
1049 assert_eq!(
1050 validate_endpoint("example.com"),
1051 Err(EndpointError::Unparseable)
1052 );
1053 }
1054
1055 #[test]
1056 fn no_environment_variable_can_authorize_plaintext() {
1057 // `CODEWHALE_ALLOW_INSECURE_HTTP` is a *provider* trust decision — it
1058 // permits an insecure model base URL for harnesses that intercept model
1059 // traffic. Honouring it here would let that decision also authorize
1060 // telemetry POSTs to an arbitrary host. No override of any kind exists.
1061 unsafe { std::env::set_var("CODEWHALE_ALLOW_INSECURE_HTTP", "1") };
1062 let with_env = validate_endpoint("http://example.com/t");
1063 unsafe { std::env::remove_var("CODEWHALE_ALLOW_INSECURE_HTTP") };
1064 assert_eq!(with_env, Err(EndpointError::InsecureScheme));
1065 }
1066
1067 // -------------------------------------------------------- install identity --
1068
1069 #[test]
1070 fn install_id_is_random_and_rotates() {
1071 let first_home = temp_home();
1072 let second_home = temp_home();
1073 let first_root = root_of(&first_home);
1074 let second_root = root_of(&second_home);
1075
1076 let first = envelope::read_or_create_install_id(&first_root).expect("mint");
1077 let second = envelope::read_or_create_install_id(&second_root).expect("mint");
1078 assert_ne!(
1079 first.install_id, second.install_id,
1080 "two fresh homes must not share an id"
1081 );
1082 assert!(uuid::Uuid::parse_str(&first.install_id).is_ok());
1083
1084 // Stable across reads on the same home.
1085 let again = envelope::read_or_create_install_id(&first_root).expect("re-read");
1086 assert_eq!(first.install_id, again.install_id);
1087
1088 // Not a function of hostname, user, or path: nothing derivable appears in
1089 // the value, and two homes under the same user differ.
1090 for derived in [
1091 std::env::var("USER").unwrap_or_default(),
1092 std::env::var("HOME").unwrap_or_default(),
1093 first_root.display().to_string(),
1094 ] {
1095 if derived.trim().is_empty() {
1096 continue;
1097 }
1098 assert!(!first.install_id.contains(derived.trim()));
1099 }
1100
1101 // 91 days old rotates.
1102 let stale = envelope::InstallId {
1103 schema_version: 1,
1104 install_id: first.install_id.clone(),
1105 rotated_at: (chrono::Utc::now() - chrono::Duration::days(91))
1106 .to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
1107 };
1108 codewhale_config::persistence::atomic_write_json(&buffer::install_id_path(&first_root), &stale)
1109 .expect("write stale id");
1110 let rotated = envelope::read_or_create_install_id(&first_root).expect("rotate");
1111 assert_ne!(rotated.install_id, first.install_id);
1112 assert_ne!(rotated.rotated_at, stale.rotated_at);
1113 }
1114
1115 // ------------------------------------------------------------------ buffer --
1116
1117 fn line(n: usize) -> String {
1118 serde_json::to_string(&Event::Panic {
1119 site: format!("crates/tui/src/x.rs:{n}:1"),
1120 })
1121 .expect("serialize")
1122 }
1123
1124 #[test]
1125 fn ring_buffer_drops_oldest_at_cap_for_both_sinks() {
1126 let home = temp_home();
1127 let root = root_of(&home);
1128 for path in [buffer::buffer_path(&root), buffer::dryrun_path(&root)] {
1129 for n in 0..600 {
1130 buffer::append(&root, &path, &line(n)).expect("append");
1131 }
1132 let kept = buffer::read_lines(&path);
1133 assert_eq!(kept.len(), buffer::MAX_EVENTS, "{}", path.display());
1134 assert_eq!(
1135 kept.first().expect("first"),
1136 &line(600 - buffer::MAX_EVENTS)
1137 );
1138 assert_eq!(kept.last().expect("last"), &line(599));
1139 }
1140 }
1141
1142 #[test]
1143 fn probe_threshold_cannot_hide_an_over_cap_buffer() {
1144 // The append path skips the count probe below a byte threshold. That is
1145 // only safe if `MAX_EVENTS` lines cannot fit under it.
1146 let shortest = serde_json::to_string(&Event::SessionStart {
1147 source: SessionSource::Api,
1148 })
1149 .expect("serialize");
1150 let floor = (shortest.len() as u64 + 1) * buffer::MAX_EVENTS as u64;
1151 assert!(
1152 floor > 4096,
1153 "the shortest event is now small enough that {} of them fit under the probe threshold",
1154 buffer::MAX_EVENTS
1155 );
1156 }
1157
1158 #[test]
1159 fn a_line_over_pipe_buf_is_dropped_not_split() {
1160 let home = temp_home();
1161 let root = root_of(&home);
1162 let path = buffer::buffer_path(&root);
1163 let huge = format!("{{\"pad\":\"{}\"}}", "x".repeat(buffer::MAX_LINE_BYTES));
1164 assert!(buffer::append(&root, &path, &huge).is_none());
1165 assert!(buffer::read_lines(&path).is_empty());
1166 }
1167
1168 #[test]
1169 fn drain_skips_a_torn_trailing_line() {
1170 let home = temp_home();
1171 let root = root_of(&home);
1172 let path = buffer::buffer_path(&root);
1173 buffer::append(&root, &path, &line(1)).expect("append");
1174 buffer::append(&root, &path, &line(2)).expect("append");
1175 // `std::process::exit` on the signal path can cut a concurrent write.
1176 {
1177 use std::io::Write as _;
1178 let mut file = std::fs::OpenOptions::new()
1179 .append(true)
1180 .open(&path)
1181 .expect("open");
1182 file.write_all(b"{\"event\":\"pan").expect("tear");
1183 }
1184 let drained = crate::spool::take_own(&root, &path);
1185 assert_eq!(drained.len(), 3, "the drain returns raw lines");
1186 let parsed: Vec<Event> = drained
1187 .iter()
1188 .filter_map(|l| serde_json::from_str(l).ok())
1189 .collect();
1190 assert_eq!(parsed.len(), 2, "the torn line must not reach a batch");
1191 assert!(!path.exists(), "taking a spool deletes it");
1192 }
1193
1194 #[test]
1195 fn append_drops_without_blocking_on_a_held_privacy_lock() {
1196 let home = temp_home();
1197 let root = root_of(&home);
1198 buffer::ensure_dir(&root).expect("create root");
1199 let path = buffer::buffer_path(&root);
1200
1201 let held = std::sync::Arc::new(std::sync::Barrier::new(2));
1202 let release = std::sync::Arc::new(std::sync::Barrier::new(2));
1203 let holder_root = root.clone();
1204 let holder_held = held.clone();
1205 let holder_release = release.clone();
1206 let holder = std::thread::spawn(move || {
1207 buffer::with_lock(&holder_root, || {
1208 holder_held.wait();
1209 holder_release.wait();
1210 Ok(())
1211 })
1212 });
1213
1214 held.wait();
1215 let started = Instant::now();
1216 let outcome = buffer::append(&root, &path, &line(7));
1217 let elapsed = started.elapsed();
1218 release.wait();
1219 holder.join().expect("holder thread").expect("holder lock");
1220
1221 assert!(outcome.is_none(), "a contended append must be dropped");
1222 assert!(
1223 elapsed < Duration::from_millis(250),
1224 "an append waited {elapsed:?} on the privacy lock"
1225 );
1226 assert!(
1227 buffer::read_lines(&path).is_empty(),
1228 "the panic-safe path bypassed the privacy lock"
1229 );
1230 }
1231
1232 #[test]
1233 fn a_tombstoned_buffer_never_appends_or_drains() {
1234 let home = temp_home();
1235 let root = root_of(&home);
1236 buffer::ensure_dir(&root).expect("create root");
1237 buffer::append(&root, &buffer::buffer_path(&root), &line(1)).expect("append");
1238 buffer::wipe(&root).expect("wipe");
1239
1240 assert!(buffer::append(&root, &buffer::buffer_path(&root), &line(2)).is_none());
1241 assert!(buffer::append_locked(&root, &buffer::dryrun_path(&root), "{}").is_none());
1242 assert!(crate::spool::take_own(&root, &buffer::buffer_path(&root)).is_empty());
1243 }
1244
1245 #[test]
1246 fn arming_after_a_tombstone_deletes_spools_and_truncates_the_legacy_buffer() {
1247 let home = temp_home();
1248 let root = root_of(&home);
1249 buffer::ensure_dir(&root).expect("create root");
1250 buffer::append(&root, &buffer::buffer_path(&root), &line(1)).expect("append");
1251 buffer::wipe(&root).expect("wipe");
1252 std::fs::create_dir_all(crate::spool::dir(&root)).expect("spool dir");
1253 let planted = crate::spool::dir(&root).join(format!("{}.jsonl", "a".repeat(32)));
1254 std::fs::write(&planted, "{}\n").expect("plant");
1255
1256 let generation = buffer::tombstone_generation(&root).expect("read wipe generation");
1257 buffer::arm(&root, generation.as_ref(), || true).expect("arm");
1258 assert!(!buffer::tombstone_present(&root));
1259 assert!(buffer::read_lines(&buffer::buffer_path(&root)).is_empty());
1260 assert!(!planted.exists(), "re-enabling must not inherit old spools");
1261 }
1262
1263 #[test]
1264 fn stale_consent_cannot_clear_a_newer_opt_out_but_fresh_reenable_can() {
1265 let home = temp_home();
1266 let root = root_of(&home);
1267 let config_path = home.path().join("config.toml");
1268 let setup_path = home.path().join("setup_state.json");
1269 accepted_setup()
1270 .save_to(&setup_path)
1271 .expect("write accepted setup state");
1272
1273 // This process resolved the old enabled config before another process
1274 // persisted an opt-out and completed its wipe.
1275 let stale_resolved = resolved(true, false, None);
1276 let TelemetryDecision::Enabled(pre_wipe_consent) = decide_in_home(
1277 Some(home.path()),
1278 &stale_resolved,
1279 &accepted_setup(),
1280 Surface::Tui,
1281 ) else {
1282 panic!("pre-wipe enabled facts must produce consent");
1283 };
1284 std::fs::write(&config_path, "telemetry = false\n").expect("persist opt-out");
1285 buffer::ensure_dir(&root).expect("create telemetry root");
1286 buffer::wipe(&root).expect("complete newer wipe");
1287 assert!(
1288 buffer::arm(&root, pre_wipe_consent.tombstone_generation(), || true).is_err(),
1289 "an old consent token cleared a newer tombstone generation"
1290 );
1291 assert!(buffer::tombstone_present(&root));
1292
1293 // Even the difficult ordering — stale config facts combined with the new
1294 // tombstone generation — cannot arm, because arm re-reads the durable
1295 // predicate while holding the wipe lock.
1296 let TelemetryDecision::Enabled(stale_consent) = decide_in_home(
1297 Some(home.path()),
1298 &stale_resolved,
1299 &accepted_setup(),
1300 Surface::Tui,
1301 ) else {
1302 panic!("fixture must carry stale enabled facts");
1303 };
1304 assert!(
1305 buffer::arm(&root, stale_consent.tombstone_generation(), || {
1306 permission_still_enabled_in_home(
1307 Some(&config_path),
1308 &setup_path,
1309 Some(home.path()),
1310 &root,
1311 )
1312 })
1313 .is_err(),
1314 "stale consent cleared a completed opt-out"
1315 );
1316 assert!(buffer::tombstone_present(&root));
1317
1318 // The documented explicit re-enable updates the durable register first. A
1319 // fresh consent observes both that value and the current generation, so it
1320 // may clear exactly that tombstone.
1321 std::fs::write(&config_path, "telemetry = true\n").expect("persist re-enable");
1322 let TelemetryDecision::Enabled(fresh_consent) = decide_in_home(
1323 Some(home.path()),
1324 &resolved(true, false, None),
1325 &accepted_setup(),
1326 Surface::Tui,
1327 ) else {
1328 panic!("fresh re-enable must produce consent");
1329 };
1330 buffer::arm(&root, fresh_consent.tombstone_generation(), || {
1331 permission_still_enabled_in_home(Some(&config_path), &setup_path, Some(home.path()), &root)
1332 })
1333 .expect("fresh re-enable arms");
1334 assert!(!buffer::tombstone_present(&root));
1335 }
1336
1337 #[test]
1338 fn completed_wipe_blocks_identity_and_state_recreation() {
1339 let home = temp_home();
1340 let root = root_of(&home);
1341 buffer::ensure_dir(&root).expect("create telemetry root");
1342 envelope::read_or_create_install_id(&root).expect("seed install id");
1343 envelope::write_state(&root, &envelope::TelemetryState::default()).expect("seed state");
1344 buffer::wipe(&root).expect("wipe telemetry home");
1345
1346 assert!(
1347 envelope::read_or_create_install_id(&root).is_err(),
1348 "an in-flight flush recreated the deleted install id"
1349 );
1350 assert!(
1351 envelope::write_state(&root, &envelope::TelemetryState::default()).is_err(),
1352 "an in-flight flush recreated state after opt-out"
1353 );
1354 assert!(!buffer::install_id_path(&root).exists());
1355 assert!(!buffer::state_path(&root).exists());
1356 }
1357
1358 // ------------------------------------------------------------ unarmed gate --
1359
1360 #[test]
1361 fn termination_reporting_is_a_noop_when_unarmed() {
1362 assert!(!crate::is_armed());
1363 crate::record_session_end();
1364 crate::record_session_end_blocking(ExitClass::Signal);
1365 assert_eq!(
1366 crate::report_termination(ExitClass::Signal, Duration::from_millis(10)),
1367 crate::FlushOutcome::Empty
1368 );
1369 assert_eq!(
1370 crate::flush_for_termination(Duration::from_millis(10)),
1371 crate::FlushOutcome::Empty
1372 );
1373 }
1374
1375 #[test]
1376 fn record_blocking_is_a_noop_when_unarmed() {
1377 // The process panic hook is installed before the command line is parsed, so
1378 // this is the state the hook runs in for every user who never opted in.
1379 let home = temp_home();
1380 let root = root_of(&home);
1381 assert!(!crate::is_armed());
1382 crate::record_blocking(Event::Panic {
1383 site: "crates/tui/src/x.rs:1:1".to_string(),
1384 });
1385 crate::record(Event::SessionStart {
1386 source: SessionSource::Interactive,
1387 });
1388 crate::set_exit_class(ExitClass::Panic);
1389 assert_eq!(crate::exit_class(), ExitClass::Clean);
1390 assert!(
1391 !root.exists(),
1392 "an unarmed process must create no directory"
1393 );
1394 }
1395
1396 // ------------------------------------------------------------------ client --
1397
1398 #[test]
1399 fn endpoint_unset_writes_the_dry_run_sink() {
1400 let home = temp_home();
1401 let root = root_of(&home);
1402 let batch = every_field_batch();
1403 assert_eq!(
1404 crate::client::send(&root, None, &batch),
1405 crate::client::SendOutcome::DryRun
1406 );
1407 let written = buffer::read_lines(&buffer::dryrun_path(&root));
1408 assert_eq!(written.len(), 1);
1409 let round_tripped: Batch = serde_json::from_str(&written[0]).expect("parse dry-run batch");
1410 assert_eq!(round_tripped, batch);
1411 assert!(
1412 !buffer::buffer_path(&root).exists(),
1413 "the dry-run sink is a separate file from the pending buffer"
1414 );
1415 }
1416
1417 #[test]
1418 fn a_tombstoned_home_sends_nothing_even_with_an_endpoint() {
1419 let home = temp_home();
1420 let root = root_of(&home);
1421 buffer::ensure_dir(&root).expect("create root");
1422 buffer::wipe(&root).expect("wipe");
1423 // The tombstone check fires before any client is constructed, so this
1424 // asserts on the sink rather than on network timing.
1425 assert_eq!(
1426 crate::client::send(&root, Some("http://127.0.0.1:1/t"), &every_field_batch()),
1427 crate::client::SendOutcome::Dropped
1428 );
1429 assert!(buffer::read_lines(&buffer::dryrun_path(&root)).is_empty());
1430 }
1431
1432 #[test]
1433 fn wipe_and_delivery_share_one_ordering_boundary() {
1434 let home = temp_home();
1435 let root = root_of(&home);
1436 let entered = std::sync::Arc::new(std::sync::Barrier::new(2));
1437 let release = std::sync::Arc::new(std::sync::Barrier::new(2));
1438
1439 let send_root = root.clone();
1440 let send_entered = entered.clone();
1441 let send_release = release.clone();
1442 let send = std::thread::spawn(move || {
1443 crate::client::send_with_transport(
1444 &send_root,
1445 Some("https://telemetry.codewhale.ai/v1/batch"),
1446 &every_field_batch(),
1447 move |_, _, _| {
1448 send_entered.wait();
1449 send_release.wait();
1450 crate::client::SendOutcome::Accepted
1451 },
1452 )
1453 });
1454 entered.wait();
1455
1456 // The real send path is paused inside its transport callback. A
1457 // non-blocking probe must observe the same lock that wipe takes; this
1458 // deterministically pins the entire delivery inside the boundary without
1459 // depending on loopback networking in a restricted test sandbox.
1460 assert!(
1461 buffer::try_with_lock(&root, || Ok(()))
1462 .expect("probe privacy lock")
1463 .is_none(),
1464 "network delivery did not hold the wipe lock"
1465 );
1466
1467 // Start the real blocking wipe while the POST is still in flight. It can
1468 // only complete after the response releases the sender's privacy guard.
1469 let wipe_root = root.clone();
1470 let wipe = std::thread::spawn(move || buffer::wipe(&wipe_root));
1471 release.wait();
1472 assert_eq!(
1473 send.join().expect("send thread"),
1474 crate::client::SendOutcome::Accepted
1475 );
1476
1477 wipe.join()
1478 .expect("wipe thread")
1479 .expect("wipe after delivery");
1480 assert!(buffer::tombstone_present(&root));
1481 assert_eq!(
1482 crate::client::send(&root, Some("http://127.0.0.1:1/t"), &every_field_batch()),
1483 crate::client::SendOutcome::Dropped,
1484 "a send crossed the completed wipe boundary"
1485 );
1486 }
1487
1488 // ----------------------------------------------------------------- buckets --
1489
1490 #[test]
1491 fn buckets_are_half_open_at_every_boundary() {
1492 assert_eq!(DurationBucket::from_secs(0), DurationBucket::Lt1m);
1493 assert_eq!(DurationBucket::from_secs(59), DurationBucket::Lt1m);
1494 assert_eq!(DurationBucket::from_secs(60), DurationBucket::OneToTen);
1495 assert_eq!(DurationBucket::from_secs(599), DurationBucket::OneToTen);
1496 assert_eq!(DurationBucket::from_secs(600), DurationBucket::TenToSixty);
1497 assert_eq!(DurationBucket::from_secs(3599), DurationBucket::TenToSixty);
1498 assert_eq!(DurationBucket::from_secs(3600), DurationBucket::Gt60m);
1499
1500 assert_eq!(ColdStartBucket::from_millis(249), ColdStartBucket::Lt250);
1501 assert_eq!(ColdStartBucket::from_millis(250), ColdStartBucket::Mid);
1502 assert_eq!(ColdStartBucket::from_millis(999), ColdStartBucket::Mid);
1503 assert_eq!(ColdStartBucket::from_millis(1000), ColdStartBucket::Slow);
1504 assert_eq!(ColdStartBucket::from_millis(2999), ColdStartBucket::Slow);
1505 assert_eq!(ColdStartBucket::from_millis(3000), ColdStartBucket::Gte3000);
1506
1507 let mut wall = TurnWall::default();
1508 for secs in [0, 4, 5, 29, 30, 119, 120, 10_000] {
1509 wall.observe_secs(secs);
1510 }
1511 assert_eq!(wall.lt_5s, 2);
1512 assert_eq!(wall.five_to_thirty, 2);
1513 assert_eq!(wall.thirty_to_onetwenty, 2);
1514 assert_eq!(wall.gte_120s, 2);
1515 }
1516
1517 #[test]
1518 fn exit_class_round_trips_through_the_atomic_encoding() {
1519 for class in ExitClass::ALL {
1520 assert_eq!(ExitClass::from_u8(class.as_u8()), *class);
1521 }
1522 assert_eq!(ExitClass::from_u8(130), ExitClass::Clean);
1523 }
1524
1525 // ---------------------------------------------------------------- counters --
1526
1527 #[test]
1528 fn custom_provider_emits_literal_custom() {
1529 let counters = crate::SessionCounters::default();
1530 counters.record_provider(codewhale_config::ProviderKind::Custom);
1531 counters.record_provider(codewhale_config::ProviderKind::Deepseek);
1532 counters.record_provider(codewhale_config::ProviderKind::Custom);
1533 let providers = counters.providers();
1534 assert_eq!(
1535 providers,
1536 vec!["custom".to_string(), "deepseek".to_string()]
1537 );
1538 }
1539
1540 #[test]
1541 fn counter_bumps_land_in_the_named_field() {
1542 let counters = crate::SessionCounters::default();
1543 counters.bump(crate::Counter::Turns);
1544 counters.bump(crate::Counter::Turns);
1545 counters.bump(crate::Counter::CommandPaletteOpen);
1546 counters.bump_error(crate::ErrorCounter::ProviderHttp5xx);
1547 counters.observe_turn_secs(3);
1548
1549 let snapshot = counters.counters();
1550 assert_eq!(snapshot.turns, 2);
1551 assert_eq!(snapshot.command_palette_open, 1);
1552 assert_eq!(snapshot.tool_calls, 0);
1553 assert_eq!(counters.errors().provider_http_5xx, 1);
1554 assert_eq!(counters.turn_wall().lt_5s, 1);
1555 }
1556
1557 #[test]
1558 fn http_status_maps_to_the_class_counter_and_nothing_else() {
1559 assert_eq!(
1560 crate::counters::http_status_counter(404),
1561 Some(crate::ErrorCounter::ProviderHttp4xx)
1562 );
1563 assert_eq!(
1564 crate::counters::http_status_counter(503),
1565 Some(crate::ErrorCounter::ProviderHttp5xx)
1566 );
1567 assert_eq!(crate::counters::http_status_counter(200), None);
1568 assert_eq!(crate::counters::http_status_counter(302), None);
1569 }
1570
1571 // --------------------------------------------------------------- API shape --
1572
1573 #[test]
1574 fn no_public_api_accepts_a_bare_bool() {
1575 // `init` takes a `TelemetryConsent` **by value**, and `TelemetryConsent` has
1576 // no public constructor other than `decide`. This is a shape assertion: it
1577 // stops compiling if the signature is ever widened.
1578 let init: fn(crate::TelemetryConsent) = crate::init;
1579 let _ = init;
1580
1581 // The only source of one is `decide`, which still applies every persistent
1582 // and run-scoped opt-out before constructing the capability.
1583 let home = temp_home();
1584 assert!(
1585 decide_in_home(
1586 Some(home.path()),
1587 &resolved(true, false, None),
1588 &accepted_setup(),
1589 Surface::Cli
1590 )
1591 .is_enabled()
1592 );
1593 }
1594
1595 // ----------------------------------------------- golden and code are welded --
1596
1597 const GOLDEN_V4: &str = include_str!("../tests/golden/v4.json");
1598
1599 /// Every key of a serialized value, including nested objects.
1600 fn serialized_keys(value: &Value) -> std::collections::BTreeSet<String> {
1601 let mut keys = std::collections::BTreeSet::new();
1602 fn walk(value: &Value, out: &mut std::collections::BTreeSet<String>) {
1603 match value {
1604 Value::Object(map) => {
1605 for (key, item) in map {
1606 out.insert(key.clone());
1607 walk(item, out);
1608 }
1609 }
1610 Value::Array(items) => {
1611 for item in items {
1612 walk(item, out);
1613 }
1614 }
1615 _ => {}
1616 }
1617 }
1618 walk(value, &mut keys);
1619 keys
1620 }
1621
1622 #[test]
1623 fn batch_envelope_and_events_serialize_exactly_their_declared_fields() {
1624 let batch = serde_json::to_value(every_field_batch()).expect("serialize");
1625 let envelope: std::collections::BTreeSet<String> = batch
1626 .as_object()
1627 .expect("batch is an object")
1628 .keys()
1629 .cloned()
1630 .collect();
1631 let declared: std::collections::BTreeSet<String> =
1632 Batch::FIELDS.iter().map(|f| (*f).to_string()).collect();
1633 assert_eq!(envelope.len(), Batch::FIELDS.len());
1634 assert_eq!(
1635 envelope, declared,
1636 "the batch envelope drifted from `Batch::FIELDS`"
1637 );
1638
1639 let golden: Value = serde_json::from_str(GOLDEN_V4).expect("golden parses");
1640 let golden_events = golden["events"].as_array().expect("golden events");
1641 let events = every_event();
1642 assert_eq!(golden_events.len(), events.len());
1643 for (event, golden_event) in events.iter().zip(golden_events) {
1644 let serialized = serialized_keys(&serde_json::to_value(event).expect("serialize"));
1645 assert!(
1646 !serialized.is_empty(),
1647 "no keys serialized for {}",
1648 event.name()
1649 );
1650 assert_eq!(
1651 serialized,
1652 serialized_keys(golden_event),
1653 "the `{}` event drifted from the v4 golden",
1654 event.name()
1655 );
1656 }
1657 }
1658
1659 #[test]
1660 fn golden_payload_v4() {
1661 assert_eq!(NOTICE_VERSION.to_string(), TELEMETRY_NOTICE_VERSION);
1662 // `crates/telemetry/tests/golden/v4.json` is one fully-populated instance of
1663 // the envelope and every event. Any field add, remove, or retype fails here
1664 // until the developer re-blesses it under a bumped `SCHEMA_VERSION` — and it
1665 // is also the artifact a future receiver author reads to know exactly what
1666 // v1 was.
1667 //
1668 // Re-bless with: `CODEWHALE_BLESS_TELEMETRY_GOLDEN=1 cargo test -p codewhale-telemetry`
1669 let batch = every_field_batch();
1670 assert_eq!(
1671 batch.schema_version, SCHEMA_VERSION,
1672 "the fixture must be built at the current schema version"
1673 );
1674 let mut rendered = serde_json::to_string_pretty(&batch).expect("serialize");
1675 rendered.push('\n');
1676
1677 if std::env::var("CODEWHALE_BLESS_TELEMETRY_GOLDEN").is_ok() {
1678 let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/golden/v4.json");
1679 std::fs::create_dir_all(path.parent().expect("parent")).expect("create golden dir");
1680 std::fs::write(&path, &rendered).expect("write golden");
1681 return;
1682 }
1683
1684 assert_eq!(
1685 rendered, GOLDEN_V4,
1686 "the v4 payload changed; bump SCHEMA_VERSION and re-bless the golden file"
1687 );
1688 }
1689
1690 #[test]
1691 fn version_comparison_names_install_upgrade_and_downgrade() {
1692 assert!(crate::version_is_older("0.9.3", "0.9.4"));
1693 assert!(crate::version_is_older("0.9", "0.9.4"));
1694 assert!(crate::version_is_older("0.10.0", "1.0.0"));
1695 assert!(!crate::version_is_older("0.9.4", "0.9.4"));
1696 assert!(!crate::version_is_older("0.9.5", "0.9.4"));
1697 // A pre-release suffix is not part of the ordering question being asked.
1698 assert!(!crate::version_is_older("0.9.4-rc.1", "0.9.4"));
1699 // Unparseable segments read as zero, so an unknown version never invents an
1700 // upgrade that did not happen.
1701 assert!(!crate::version_is_older("nightly", "0.0.0"));
1702 }
1703
1704 #[test]
1705 fn an_install_or_upgrade_is_reported_once_per_version() {
1706 let home = temp_home();
1707 let root = root_of(&home);
1708 buffer::ensure_dir(&root).expect("create telemetry dir");
1709
1710 // No prior record on this machine.
1711 let mut state = envelope::read_state(&root);
1712 assert_eq!(state.last_version, None);
1713
1714 // The state file is written before the event is queued, so the second
1715 // launch at the same version has nothing left to report.
1716 state.last_version = Some(env!("CARGO_PKG_VERSION").to_string());
1717 envelope::write_state(&root, &state).expect("write state");
1718 assert_eq!(
1719 envelope::read_state(&root).last_version.as_deref(),
1720 Some(env!("CARGO_PKG_VERSION"))
1721 );
1722
1723 // The previous version is read from this file and from nowhere else —
1724 // never from session history or config mtimes, which answer the same
1725 // question under a different privacy contract.
1726 let entries: Vec<String> = std::fs::read_dir(&root)
1727 .expect("read dir")
1728 .filter_map(|entry| Some(entry.ok()?.file_name().to_string_lossy().into_owned()))
1729 .collect();
1730 assert!(
1731 entries.iter().any(|name| name == "state.json"),
1732 "expected state.json in {entries:?}"
1733 );
1734 }
1735
1736 #[test]
1737 fn the_notice_summarizes_what_the_schema_collects_and_states_every_red_line() {
1738 use crate::notice;
1739
1740 let body = notice::NOTICE_BODY;
1741
1742 // The modal names the useful product categories and links the exact
1743 // field-by-field schema. `install_id` is "a random ID stored on this
1744 // machine"; transport metadata remains in the linked document. The body
1745 // wraps at 72 columns, so multi-word claims are matched across the
1746 // reflowed whitespace.
1747 let flat: String = body.split_whitespace().collect();
1748 for claim in [
1749 "version",
1750 "OS and CPU family",
1751 "session duration and outcome",
1752 "aggregate feature and error counters",
1753 "random ID stored on this machine",
1754 "every 90 days",
1755 "on by default",
1756 "Codewhale",
1757 ] {
1758 assert!(
1759 flat.contains(&claim.split_whitespace().collect::<String>()),
1760 "the notice does not describe: {claim}"
1761 );
1762 }
1763
1764 // And every red line has to be stated as *not collected*, not as
1765 // anonymized or sampled — two promises this client does not make.
1766 for red_line in [
1767 "conversations",
1768 "code",
1769 "prompts",
1770 "files",
1771 "repo or branch names",
1772 "model content",
1773 "credentials",
1774 "per-turn or per-tool timeline",
1775 ] {
1776 assert!(
1777 flat.contains(&red_line.split_whitespace().collect::<String>()),
1778 "the notice does not disclaim: {red_line}"
1779 );
1780 }
1781 assert!(!body.to_ascii_lowercase().contains("anonymized"));
1782
1783 // The modal names the persistent opt-out because that is the switch that
1784 // also fulfils its deletion promise. Run-only kill switches stay in the
1785 // linked schema document, which explains that they erase nothing.
1786 assert!(body.contains("codewhale config set telemetry false"));
1787 assert!(!body.contains("CODEWHALE_TELEMETRY=0"));
1788 assert!(body.contains("docs/TELEMETRY.md"));
1789 }
1790
1791 // ------------------------------------------------------------- the spools --
1792
1793 mod spools {
1794 use super::*;
1795 use crate::actor::{Context, send_dead};
1796 use crate::spool::{self, SpoolContext};
1797
1798 fn header(surface: Surface, version: &str) -> SpoolContext {
1799 SpoolContext::new(
1800 surface,
1801 version.to_string(),
1802 Some("abcdef123456".to_string()),
1803 true,
1804 )
1805 }
1806
1807 fn event_line(source: SessionSource) -> String {
1808 serde_json::to_string(&Event::SessionStart { source }).expect("serialize")
1809 }
1810
1811 fn plant(root: &Path, nonce: char, header_line: &str, events: &[String]) -> PathBuf {
1812 std::fs::create_dir_all(spool::dir(root)).expect("spool dir");
1813 let path = spool::dir(root).join(format!("{}.jsonl", nonce.to_string().repeat(32)));
1814 let mut body = format!("{header_line}\n");
1815 for event in events {
1816 body.push_str(event);
1817 body.push('\n');
1818 }
1819 std::fs::write(&path, body).expect("plant spool");
1820 path
1821 }
1822
1823 fn header_line(surface: Surface, version: &str) -> String {
1824 serde_json::to_string(&header(surface, version)).expect("serialize header")
1825 }
1826
1827 fn current(root: &Path) -> Context {
1828 let header = header(Surface::Tui, "0.10.3");
1829 let (spool, nonce) = spool::open(root, &header);
1830 Context {
1831 root: root.to_path_buf(),
1832 endpoint: None,
1833 surface: Surface::Tui,
1834 config_path: None,
1835 app_version: "0.10.3".to_string(),
1836 git_sha: None,
1837 tty: false,
1838 spool,
1839 nonce,
1840 }
1841 }
1842
1843 fn dryrun_batches(root: &Path) -> Vec<Batch> {
1844 buffer::read_lines(&buffer::dryrun_path(root))
1845 .iter()
1846 .map(|line| serde_json::from_str(line).expect("a dry-run batch"))
1847 .collect()
1848 }
1849
1850 #[test]
1851 fn a_dead_spool_is_recovered_with_its_own_surface_and_version() {
1852 let home = temp_home();
1853 let root = root_of(&home);
1854 let context = current(&root);
1855 let path = plant(
1856 &root,
1857 'b',
1858 &header_line(Surface::Serve, "0.9.9"),
1859 &[event_line(SessionSource::Interactive)],
1860 );
1861
1862 let outcomes = send_dead(&context);
1863
1864 assert_eq!(outcomes, vec![crate::FlushOutcome::DryRun]);
1865 let batches = dryrun_batches(&root);
1866 assert_eq!(batches.len(), 1);
1867 assert_eq!(batches[0].surface, Surface::Serve);
1868 assert_eq!(batches[0].app_version, "0.9.9");
1869 assert_eq!(batches[0].git_sha.as_deref(), Some("abcdef123456"));
1870 assert_eq!(batches[0].events.len(), 1);
1871 assert!(!path.exists());
1872 }
1873
1874 #[test]
1875 fn a_dead_spool_is_never_sent_twice() {
1876 let home = temp_home();
1877 let root = root_of(&home);
1878 let context = current(&root);
1879 plant(
1880 &root,
1881 'b',
1882 &header_line(Surface::Exec, "0.10.3"),
1883 &[event_line(SessionSource::Interactive)],
1884 );
1885 assert_eq!(send_dead(&context).len(), 1);
1886 assert!(send_dead(&context).is_empty());
1887 assert_eq!(dryrun_batches(&root).len(), 1);
1888 }
1889
1890 #[test]
1891 fn a_live_locked_spool_is_untouched() {
1892 let home = temp_home();
1893 let root = root_of(&home);
1894 let live = header(Surface::Serve, "0.10.3");
1895 let (live_path, live_nonce) = spool::open(&root, &live);
1896 buffer::append(&root, &live_path, &event_line(SessionSource::Interactive)).expect("append");
1897
1898 let taken = spool::take_dead(&root, &"c".repeat(32), std::time::SystemTime::now());
1899
1900 assert!(taken.is_empty());
1901 assert_eq!(buffer::read_lines(&live_path).len(), 2);
1902 assert!(
1903 spool::dir(&root)
1904 .join(format!("{live_nonce}.lock"))
1905 .exists()
1906 );
1907 }
1908
1909 #[test]
1910 fn the_running_process_never_recovers_its_own_spool() {
1911 let home = temp_home();
1912 let root = root_of(&home);
1913 let context = current(&root);
1914 buffer::append(
1915 &root,
1916 &context.spool,
1917 &event_line(SessionSource::Interactive),
1918 )
1919 .expect("append");
1920 assert!(send_dead(&context).is_empty());
1921 assert_eq!(buffer::read_lines(&context.spool).len(), 2);
1922 }
1923
1924 #[test]
1925 fn a_tombstone_blocks_recovery_and_append() {
1926 let home = temp_home();
1927 let root = root_of(&home);
1928 let context = current(&root);
1929 buffer::wipe(&root).expect("wipe");
1930 let planted = plant(
1931 &root,
1932 'b',
1933 &header_line(Surface::Serve, "0.10.3"),
1934 &[event_line(SessionSource::Interactive)],
1935 );
1936
1937 assert!(send_dead(&context).is_empty());
1938 assert!(dryrun_batches(&root).is_empty());
1939 assert!(
1940 planted.exists(),
1941 "nothing is read or sent under a tombstone"
1942 );
1943 assert!(buffer::append(&root, &context.spool, "{}").is_none());
1944 }
1945
1946 #[test]
1947 fn wipe_removes_every_spool() {
1948 let home = temp_home();
1949 let root = root_of(&home);
1950 let context = current(&root);
1951 plant(
1952 &root,
1953 'b',
1954 &header_line(Surface::Serve, "0.10.3"),
1955 &[event_line(SessionSource::Interactive)],
1956 );
1957 buffer::wipe(&root).expect("wipe");
1958 assert!(!spool::dir(&root).exists());
1959 assert!(!context.spool.exists());
1960 }
1961
1962 #[test]
1963 fn a_hostile_context_drops_the_whole_spool_unsent() {
1964 let home = temp_home();
1965 let root = root_of(&home);
1966 let context = current(&root);
1967 let good = event_line(SessionSource::Interactive);
1968 let hostile_headers = [
1969 header_line(Surface::Serve, "/Users/victim/secret"),
1970 header_line(Surface::Serve, "0.10.3").replace("abcdef123456", "ZZZZZZZZZZZZ"),
1971 header_line(Surface::Serve, "0.10.3").replace("\"spool\":1", "\"spool\":2"),
1972 header_line(Surface::Serve, "0.10.3")
1973 .replace("\"schema_version\":", "\"x\":9,\"schema_version\":"),
1974 header_line(Surface::Serve, "0.10.3").replace("\"serve\"", "\"not-a-surface\""),
1975 format!(
1976 "{{\"schema_version\":{},\"notice_version\":{},\"app_version\":\"0.10.3\"}}",
1977 SCHEMA_VERSION + 1,
1978 NOTICE_VERSION
1979 ),
1980 good.clone(),
1981 ];
1982 for (index, hostile) in hostile_headers.iter().enumerate() {
1983 let nonce = char::from(b'1' + index as u8);
1984 let path = plant(&root, nonce, hostile, std::slice::from_ref(&good));
1985 assert!(send_dead(&context).is_empty(), "{hostile}");
1986 assert!(!path.exists(), "{hostile}");
1987 }
1988 let mut stale = header(Surface::Serve, "0.10.3");
1989 stale.schema_version = SCHEMA_VERSION + 1;
1990 plant(
1991 &root,
1992 'f',
1993 &serde_json::to_string(&stale).expect("serialize"),
1994 std::slice::from_ref(&good),
1995 );
1996 assert!(send_dead(&context).is_empty());
1997 assert!(dryrun_batches(&root).is_empty());
1998 }
1999
2000 #[test]
2001 fn a_hostile_event_in_a_dead_spool_is_dropped_and_the_rest_sent() {
2002 let home = temp_home();
2003 let root = root_of(&home);
2004 let context = current(&root);
2005 plant(
2006 &root,
2007 'b',
2008 &header_line(Surface::Serve, "0.10.3"),
2009 &[
2010 r#"{"event":"panic","site":"/Users/victim/src/secret-repo/main.rs"}"#.to_string(),
2011 event_line(SessionSource::Interactive),
2012 ],
2013 );
2014 assert_eq!(send_dead(&context).len(), 1);
2015 let batches = dryrun_batches(&root);
2016 assert_eq!(batches[0].events.len(), 1);
2017 assert!(!serde_json::to_string(&batches).unwrap().contains("victim"));
2018 }
2019
2020 #[test]
2021 fn the_count_and_age_caps_hold() {
2022 let home = temp_home();
2023 let root = root_of(&home);
2024 let context = current(&root);
2025 let now = std::time::SystemTime::now();
2026 let mut paths = Vec::new();
2027 for (index, nonce) in ['1', '2', '3', '4', '5', '6'].into_iter().enumerate() {
2028 let path = plant(
2029 &root,
2030 nonce,
2031 &header_line(Surface::Serve, "0.10.3"),
2032 &[event_line(SessionSource::Interactive)],
2033 );
2034 let age = Duration::from_secs(60 * (index as u64 + 1));
2035 std::fs::File::options()
2036 .write(true)
2037 .open(&path)
2038 .expect("open")
2039 .set_modified(now - age)
2040 .expect("set mtime");
2041 paths.push(path);
2042 }
2043 let stale = plant(
2044 &root,
2045 '7',
2046 &header_line(Surface::Serve, "0.10.3"),
2047 &[event_line(SessionSource::Interactive)],
2048 );
2049 std::fs::File::options()
2050 .write(true)
2051 .open(&stale)
2052 .expect("open")
2053 .set_modified(now - Duration::from_secs(8 * 24 * 60 * 60))
2054 .expect("set mtime");
2055
2056 assert_eq!(send_dead(&context).len(), spool::MAX_RECOVERED);
2057 assert_eq!(dryrun_batches(&root).len(), spool::MAX_RECOVERED);
2058 for path in paths.iter().chain([&stale]) {
2059 assert!(!path.exists(), "{} must be gone", path.display());
2060 }
2061 }
2062
2063 #[test]
2064 fn two_processes_never_mix_lines() {
2065 let home = temp_home();
2066 let root = root_of(&home);
2067 let (tui_path, _) = spool::open(&root, &header(Surface::Tui, "0.10.3"));
2068 let (exec_path, _) = spool::open(&root, &header(Surface::Exec, "0.10.3"));
2069 assert_ne!(tui_path, exec_path);
2070 buffer::append(&root, &tui_path, &event_line(SessionSource::Interactive)).expect("append");
2071 buffer::append(&root, &exec_path, &event_line(SessionSource::Ci)).expect("append");
2072
2073 let tui = spool::take_own(&root, &tui_path);
2074 assert!(tui.iter().any(|l| l.contains("interactive")));
2075 assert!(
2076 tui.iter()
2077 .all(|l| !l.contains("\"ci\"") && !l.contains("exec"))
2078 );
2079 assert!(exec_path.exists(), "taking one spool leaves the other");
2080 }
2081
2082 const LOCK_CHILD_ROOT: &str = "CODEWHALE_TEST_SPOOL_LOCK_CHILD_ROOT";
2083
2084 #[test]
2085 fn lock_holder_child() {
2086 let Some(root) = std::env::var_os(LOCK_CHILD_ROOT) else {
2087 return;
2088 };
2089 let root = PathBuf::from(root);
2090 let (path, _) = spool::open(&root, &header(Surface::Exec, "0.10.3"));
2091 buffer::append(&root, &path, &event_line(SessionSource::Ci)).expect("append");
2092 std::fs::write(
2093 root.join("child-ready.tmp"),
2094 path.to_string_lossy().as_bytes(),
2095 )
2096 .expect("ready marker");
2097 std::fs::rename(root.join("child-ready.tmp"), root.join("child-ready"))
2098 .expect("publish ready marker");
2099 let mut line = String::new();
2100 let _ = std::io::stdin().read_line(&mut line);
2101 }
2102
2103 #[test]
2104 fn the_spool_lock_holds_across_processes_stale_locks_and_crashes() {
2105 let home = temp_home();
2106 let root = root_of(&home);
2107 std::fs::create_dir_all(&root).expect("root");
2108 let mut child = std::process::Command::new(std::env::current_exe().expect("test binary"))
2109 .args(["--exact", "tests::spools::lock_holder_child", "--nocapture"])
2110 .env(LOCK_CHILD_ROOT, &root)
2111 .stdin(std::process::Stdio::piped())
2112 .stdout(std::process::Stdio::null())
2113 .spawn()
2114 .expect("spawn lock holder");
2115 let ready = root.join("child-ready");
2116 let deadline = std::time::Instant::now() + Duration::from_secs(60);
2117 while !ready.exists() {
2118 assert!(
2119 std::time::Instant::now() < deadline,
2120 "lock holder never became ready"
2121 );
2122 std::thread::sleep(Duration::from_millis(20));
2123 }
2124 let child_spool = PathBuf::from(std::fs::read_to_string(&ready).expect("ready path"));
2125 let child_lines = buffer::read_lines(&child_spool);
2126 assert_eq!(child_lines.len(), 2);
2127 assert!(spool::is_header_line(&child_lines[0]));
2128
2129 let own = "c".repeat(32);
2130 assert!(
2131 spool::take_dead(&root, &own, std::time::SystemTime::now()).is_empty(),
2132 "a spool locked by a live process is not dead"
2133 );
2134 assert_eq!(buffer::read_lines(&child_spool), child_lines);
2135
2136 let stale = plant(
2137 &root,
2138 'b',
2139 &header_line(Surface::Serve, "0.10.3"),
2140 &[event_line(SessionSource::Interactive)],
2141 );
2142 let stale_lock = stale.with_extension("lock");
2143 std::fs::write(&stale_lock, b"").expect("stale lock");
2144 let orphan_lock = spool::dir(&root).join(format!("{}.lock", "d".repeat(32)));
2145 std::fs::write(&orphan_lock, b"").expect("orphan lock");
2146 let headerless = plant(
2147 &root,
2148 'e',
2149 &event_line(SessionSource::Interactive),
2150 &[event_line(SessionSource::Interactive)],
2151 );
2152
2153 let taken = spool::take_dead(&root, &own, std::time::SystemTime::now());
2154 assert_eq!(taken.len(), 1, "only the stale spool is recovered");
2155 assert_eq!(taken[0].context.surface, Surface::Serve);
2156 for gone in [&stale, &stale_lock, &orphan_lock, &headerless] {
2157 assert!(!gone.exists(), "{} must be gone", gone.display());
2158 }
2159 assert_eq!(buffer::read_lines(&child_spool), child_lines);
2160
2161 child.kill().expect("kill lock holder");
2162 let _ = child.wait();
2163
2164 let crashed_before_send = spool::take_dead(&root, &own, std::time::SystemTime::now());
2165 assert_eq!(crashed_before_send.len(), 1);
2166 assert_eq!(crashed_before_send[0].context.surface, Surface::Exec);
2167 assert_eq!(crashed_before_send[0].lines.len(), 1);
2168 assert!(!child_spool.exists());
2169 drop(crashed_before_send);
2170
2171 assert!(
2172 spool::take_dead(&root, &own, std::time::SystemTime::now()).is_empty(),
2173 "a spool deleted before a send that never happened is not sent again"
2174 );
2175 assert!(
2176 spool::data_files(&root).is_empty(),
2177 "{:?}",
2178 spool::data_files(&root)
2179 );
2180 }
2181
2182 #[test]
2183 fn the_ring_keeps_the_header() {
2184 let home = temp_home();
2185 let root = root_of(&home);
2186 let (path, _) = spool::open(&root, &header(Surface::Serve, "0.10.3"));
2187 for n in 0..700 {
2188 buffer::append(&root, &path, &line(n)).expect("append");
2189 }
2190 let lines = buffer::read_lines(&path);
2191 assert!(lines.len() <= buffer::MAX_EVENTS);
2192 assert!(spool::is_header_line(&lines[0]));
2193 assert!(lines.last().unwrap().contains(&line(699)));
2194 }
2195 }
2196
2197 #[test]
2198 fn arming_skips_a_busy_privacy_lock_instead_of_wedging_the_launch() {
2199 let home = temp_home();
2200 let root = root_of(&home);
2201 buffer::ensure_dir(&root).expect("telemetry root");
2202 let file = std::fs::OpenOptions::new()
2203 .create(true)
2204 .truncate(true)
2205 .write(true)
2206 .open(buffer::lock_path(&root))
2207 .expect("open lock");
2208 let mut lock = fd_lock::RwLock::new(file);
2209 let _guard = lock.try_write().expect("hold the privacy lock");
2210
2211 let started = Instant::now();
2212 let error = buffer::arm(&root, None, || true).expect_err("busy lock must not arm");
2213 assert!(started.elapsed() < Duration::from_secs(5));
2214 assert!(error.to_string().contains("lock stayed busy"));
2215 }
2216
2217 #[test]
2218 fn arm_reinstalls_tombstone_if_permission_flips_false_after_removal() {
2219 let home = temp_home();
2220 let root = root_of(&home);
2221 buffer::ensure_dir(&root).expect("telemetry root");
2222 buffer::wipe(&root).expect("wipe");
2223 let generation = buffer::tombstone_generation(&root).expect("read wipe generation");
2224 let checks = std::sync::atomic::AtomicUsize::new(0);
2225 let err = buffer::arm(&root, generation.as_ref(), || {
2226 checks.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0
2227 })
2228 .expect_err("revoked permission after tombstone removal must fail closed");
2229 assert!(err.to_string().contains("no longer enabled"));
2230 assert!(buffer::tombstone_present(&root));
2231 }
2232
2233 #[test]
2234 fn persistent_preference_waits_for_delivery_even_after_startup_budget() {
2235 let home = temp_home();
2236 let root = root_of(&home);
2237 buffer::ensure_dir(&root).expect("telemetry root");
2238 let file = std::fs::File::create(buffer::lock_path(&root)).expect("privacy lock");
2239 let mut lock = fd_lock::RwLock::new(file);
2240 let guard = lock.try_write().expect("hold delivery lock");
2241 let (finished, completion) = std::sync::mpsc::channel();
2242 std::thread::scope(|scope| {
2243 scope.spawn(|| {
2244 finished.send(buffer::wipe(&root)).expect("report wipe");
2245 });
2246 assert!(matches!(
2247 completion.recv_timeout(std::time::Duration::from_millis(3200)),
2248 Err(std::sync::mpsc::RecvTimeoutError::Timeout)
2249 ));
2250 drop(guard);
2251 completion
2252 .recv_timeout(std::time::Duration::from_secs(10))
2253 .expect("wipe completed")
2254 .expect("wipe succeeded");
2255 });
2256 assert!(buffer::tombstone_present(&root));
2257 }
2258
2259 #[test]
2260 fn lockless_wipe_fallback_installs_non_empty_tombstone() {
2261 let home = temp_home();
2262 let root = root_of(&home);
2263 buffer::ensure_dir(&root).expect("telemetry root");
2264 let file = std::fs::OpenOptions::new()
2265 .create(true)
2266 .truncate(true)
2267 .write(true)
2268 .open(buffer::lock_path(&root))
2269 .expect("open lock");
2270 let mut lock = fd_lock::RwLock::new(file);
2271 let _guard = lock.try_write().expect("hold the privacy lock");
2272
2273 let err = buffer::wipe_on_startup(&root).expect_err("busy lock returns error");
2274 assert!(err.to_string().contains("lock stayed busy"));
2275 assert!(buffer::tombstone_present(&root));
2276 assert!(
2277 buffer::tombstone_generation(&root)
2278 .expect("read fallback tombstone")
2279 .is_some()
2280 );
2281 }
2282
2282 lines RUST