返回 CodeWhale
telemetry_contract.rs
根目录 / crates / tui / tests / integration / telemetry_contract.rs
1 //! Process-level telemetry contract.
2 //!
3 //! Everything here drives the real `codewhale` binary inside a sealed
4 //! `HOME`/`CODEWHALE_HOME`, with a loopback recorder standing in for the
5 //! telemetry endpoint. The unit tests in `codewhale-telemetry` prove the
6 //! predicate; these prove that the *emitting process* consults it — which is
7 //! the thing v1 of this design got wrong, because `resolve_runtime_options`
8 //! had no non-test caller and so neither `telemetry = false` in the config file
9 //! nor `CODEWHALE_TELEMETRY=0` was ever read by a process that would have sent.
10 //!
11 //! Two disciplines make the zero-request assertions non-vacuous:
12 //!
13 //! 1. Short CLI tests require complete local sessions after an acknowledged
14 //! flush, or an explicit bounded-writer timeout. Disabled runs create no
15 //! telemetry state. Short commands do not wait for network delivery.
16 //! 2. Full `exec` tests prove the buffered events reach a live recorder while
17 //! respecting the same persistent and run-scoped opt-outs.
18 //!
19 //! The recorder is `http://127.0.0.1:<port>` — loopback, which is the one place
20 //! `validate_endpoint` permits plaintext, and a packet that never leaves the
21 //! machine.
22
23 #![cfg(unix)]
24
25 use std::io::Read;
26 use std::path::{Path, PathBuf};
27 use std::process::{Command, Output, Stdio};
28 use std::sync::{Mutex, MutexGuard, OnceLock};
29 use std::time::{Duration, Instant};
30
31 use codewhale_config::{SetupState, TELEMETRY_NOTICE_VERSION};
32 use futures_util::FutureExt;
33 use serde_json::{Value, json};
34 use tempfile::TempDir;
35 use wait_timeout::ChildExt;
36 use wiremock::matchers::{method, path as path_matcher};
37 use wiremock::{Mock, MockServer, ResponseTemplate};
38
39 /// Where the recorder listens for batches.
40 const TELEMETRY_PATH: &str = "/v1/telemetry";
41 /// Where the mock model listens.
42 const MODEL_PATH: &str = "/v1/chat/completions";
43 const TEST_MODEL: &str = "telemetry-contract-model";
44
45 /// Sentinels planted through real inputs. None of these may appear in a batch.
46 ///
47 /// Deliberately low-entropy: `crates/engine/src/fleet/ledger.rs` notes that
48 /// realistic-looking tokens trip secret scanning at push time.
49 const SENTINEL_PROMPT: &str = "tc-prompt-sentinel-do-not-collect";
50 const SENTINEL_FILENAME: &str = "tc-workspace-sentinel-file.txt";
51 const SENTINEL_PROVIDER_TABLE: &str = "tc_custom_provider_sentinel";
52 const SENTINEL_MCP_SERVER: &str = "tc-mcp-server-sentinel";
53 const SENTINEL_API_KEY: &str = "tc-api-key-sentinel-not-a-real-key";
54 /// Planted by writing to a spool file directly, which is what any other
55 /// process running as this user can do.
56 const SENTINEL_INJECTED: &str = "tc-injected-sentinel-/Users/victim/secret-repo";
57 /// The key lives only in the child's environment, never in a file, so the
58 /// "absent from every written file" assertion means something.
59 const SENTINEL_API_KEY_ENV: &str = "TC_SENTINEL_API_KEY";
60
61 const EXEC_TIMEOUT: Duration = Duration::from_secs(90);
62
63 // ── Fixture ──────────────────────────────────────────────────────────────
64
65 struct Fixture {
66 // The consolidated integration target runs tests in parallel. Each test in
67 // this module launches the full Codewhale binary, and low-resource CI
68 // runners can fail those children before they reach either loopback server.
69 // These tests exercise telemetry contracts, not launch concurrency, so one
70 // process fixture at a time keeps their non-vacuity assertions meaningful.
71 _process_test_guard: MutexGuard<'static, ()>,
72 _root: TempDir,
73 home: PathBuf,
74 codewhale_home: PathBuf,
75 workspace: PathBuf,
76 config_path: PathBuf,
77 endpoint: Option<String>,
78 }
79
80 impl Fixture {
81 fn new() -> Self {
82 let process_test_guard = telemetry_process_test_lock()
83 .lock()
84 .unwrap_or_else(|poisoned| poisoned.into_inner());
85 let root = TempDir::new().expect("fixture root");
86 let home = root.path().join("home");
87 let codewhale_home = root.path().join("codewhale-home");
88 let workspace = root.path().join("workspace");
89 for dir in [&home, &codewhale_home, &workspace] {
90 std::fs::create_dir_all(dir).expect("create fixture dir");
91 }
92 let config_path = root.path().join("config.toml");
93 std::fs::write(&config_path, "").expect("write config");
94 Self {
95 _process_test_guard: process_test_guard,
96 _root: root,
97 home,
98 codewhale_home,
99 workspace,
100 config_path,
101 endpoint: None,
102 }
103 }
104
105 /// Point this fixture at a loopback recorder.
106 fn with_endpoint(mut self, base_url: &str) -> Self {
107 self.endpoint = Some(format!("{base_url}{TELEMETRY_PATH}"));
108 self
109 }
110
111 fn write_config(&self, body: &str) {
112 std::fs::write(&self.config_path, body).expect("write config");
113 }
114
115 /// Record the answer a user would have given on a TTY.
116 ///
117 /// Explicit preferences are machine-scoped and preserve historical no
118 /// across TTY and headless launches. Presentation records no preference.
119 fn record_notice(&self, opt_in: bool) {
120 let mut state = SetupState::default();
121 state.record_telemetry_notice(TELEMETRY_NOTICE_VERSION, opt_in);
122 state
123 .save_to(&self.codewhale_home.join("setup_state.json"))
124 .expect("write setup state");
125 }
126
127 fn setup_state_path(&self) -> PathBuf {
128 self.codewhale_home.join("setup_state.json")
129 }
130
131 fn telemetry_root(&self) -> PathBuf {
132 self.codewhale_home.join("telemetry")
133 }
134
135 fn command(&self) -> Command {
136 let mut command = Command::new(crate::binary::codewhale());
137 command
138 .current_dir(&self.workspace)
139 .env_clear()
140 .env("PATH", std::env::var_os("PATH").expect("PATH"))
141 .env("HOME", &self.home)
142 .env("USERPROFILE", &self.home)
143 .env("XDG_CONFIG_HOME", self.home.join(".config"))
144 .env("XDG_DATA_HOME", self.home.join(".local").join("share"))
145 .env("XDG_CACHE_HOME", self.home.join(".cache"))
146 .env("CODEWHALE_HOME", &self.codewhale_home)
147 .env("CODEWHALE_SECRET_BACKEND", "file")
148 .env("CODEWHALE_MEMORY", "false")
149 // A pinned mirror version keeps the release crate from issuing a
150 // metadata request, so the only egress a test can observe is the
151 // one this file is about.
152 .env(
153 "CODEWHALE_RELEASE_BASE_URL",
154 "https://example.invalid/releases",
155 )
156 .env("DEEPSEEK_TUI_VERSION", env!("CARGO_PKG_VERSION"))
157 .env("RUST_LOG", "warn")
158 .stdin(Stdio::null());
159 if let Some(endpoint) = &self.endpoint {
160 command.env("CODEWHALE_TELEMETRY_ENDPOINT", endpoint);
161 }
162 command
163 }
164
165 /// The cheapest subcommand that still traverses the whole telemetry
166 /// lifecycle: arm, `session_start`, dispatch, `session_end`, bounded local
167 /// persistence. Verbose logging exposes the actual persistence outcome.
168 /// The read-only `config telemetry` query traverses the shared command
169 /// lifecycle without provider, MCP, or model execution. Structural Doctor
170 /// deliberately has no telemetry lifecycle or persistence side effects.
171 fn run_short_command(&self) -> Output {
172 let mut command = self.command();
173 command.args([
174 "--verbose",
175 "--config",
176 self.config_path.to_str().expect("config path"),
177 "config",
178 "telemetry",
179 ]);
180 let output = command.output().expect("run codewhale config telemetry");
181 assert!(
182 output.status.success(),
183 "config telemetry failed\nstdout:\n{}\nstderr:\n{}",
184 String::from_utf8_lossy(&output.stdout),
185 String::from_utf8_lossy(&output.stderr)
186 );
187 output
188 }
189
190 /// Every regular file under the sealed roots, for leak scanning.
191 fn written_files(&self) -> Vec<PathBuf> {
192 let mut out = Vec::new();
193 for base in [&self.home, &self.codewhale_home, &self.workspace] {
194 collect_files(base, &mut out);
195 }
196 out.push(self.config_path.clone());
197 out
198 }
199 }
200
201 fn telemetry_process_test_lock() -> &'static Mutex<()> {
202 static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
203 LOCK.get_or_init(Mutex::default)
204 }
205
206 fn collect_files(dir: &Path, out: &mut Vec<PathBuf>) {
207 let Ok(entries) = std::fs::read_dir(dir) else {
208 return;
209 };
210 for entry in entries.flatten() {
211 let path = entry.path();
212 match entry.file_type() {
213 Ok(kind) if kind.is_dir() => collect_files(&path, out),
214 Ok(kind) if kind.is_file() => out.push(path),
215 _ => {}
216 }
217 }
218 }
219
220 // ── Recorder ─────────────────────────────────────────────────────────────
221
222 /// A loopback endpoint that accepts every batch and keeps the body.
223 ///
224 /// The body is the point. The recorder `crates/tui/tests/diagnostic_read_only.rs`
225 /// copies deliberately drops it; a telemetry contract that cannot read what was
226 /// sent can only assert "something happened".
227 async fn start_recorder() -> MockServer {
228 let server = MockServer::start().await;
229 Mock::given(method("POST"))
230 .and(path_matcher(TELEMETRY_PATH))
231 .respond_with(ResponseTemplate::new(200))
232 .mount(&server)
233 .await;
234 server
235 }
236
237 /// Every request the recorder saw, batch bodies included.
238 async fn recorded_batches(server: &MockServer) -> Vec<Value> {
239 let requests = server
240 .received_requests()
241 .await
242 .expect("the recorder must retain its request log");
243 requests
244 .iter()
245 .filter(|request| request.url.path() == TELEMETRY_PATH)
246 .map(|request| {
247 serde_json::from_slice::<Value>(&request.body).unwrap_or_else(|error| {
248 panic!(
249 "a telemetry batch must be JSON: {error}\nbody: {}",
250 String::from_utf8_lossy(&request.body)
251 )
252 })
253 })
254 .collect()
255 }
256
257 /// How many chat completions the mock model served.
258 ///
259 /// The sentinel test's whole claim is that a prompt which *did* reach a model
260 /// did not reach a batch, so a run where the turn never happened would be
261 /// vacuous.
262 async fn model_request_count(server: &MockServer) -> usize {
263 server
264 .received_requests()
265 .await
266 .expect("the recorder must retain its request log")
267 .iter()
268 .filter(|request| request.url.path() == MODEL_PATH)
269 .count()
270 }
271
272 async fn assert_no_batches(server: &MockServer, why: &str) {
273 let batches = recorded_batches(server).await;
274 assert!(
275 batches.is_empty(),
276 "{why}: expected zero telemetry requests, recorded {}:\n{}",
277 batches.len(),
278 serde_json::to_string_pretty(&batches).unwrap_or_default()
279 );
280 }
281
282 fn spool_files(fixture: &Fixture) -> Vec<PathBuf> {
283 let Ok(entries) = std::fs::read_dir(fixture.telemetry_root().join("spool")) else {
284 return Vec::new();
285 };
286 let mut files: Vec<PathBuf> = entries
287 .filter_map(Result::ok)
288 .map(|entry| entry.path())
289 .filter(|path| path.extension().is_some_and(|ext| ext == "jsonl"))
290 .collect();
291 files.sort();
292 files
293 }
294
295 fn only_spool_file(fixture: &Fixture) -> Option<PathBuf> {
296 let mut files = spool_files(fixture);
297 (files.len() == 1).then(|| files.remove(0))
298 }
299
300 fn buffered_events(fixture: &Fixture) -> Vec<Value> {
301 let mut events = Vec::new();
302 for path in spool_files(fixture) {
303 let body = std::fs::read_to_string(&path).unwrap_or_else(|error| {
304 panic!(
305 "read locally buffered telemetry at {}: {error}",
306 path.display()
307 )
308 });
309 for line in body.lines().filter(|line| !line.trim().is_empty()) {
310 let value = serde_json::from_str::<Value>(line).unwrap_or_else(|error| {
311 panic!("buffered telemetry must be JSON: {error}\nline: {line}")
312 });
313 if value.get("event").is_some() {
314 events.push(value);
315 }
316 }
317 }
318 events
319 }
320
321 async fn assert_short_cli_persistence_without_network(
322 fixture: &Fixture,
323 server: &MockServer,
324 output: &Output,
325 why: &str,
326 ) {
327 assert_no_batches(server, why).await;
328 let stderr = String::from_utf8_lossy(&output.stderr);
329 let outcomes: Vec<_> = stderr
330 .lines()
331 .filter_map(|line| {
332 line.split_once("telemetry local persistence outcome=")
333 .map(|(_, outcome)| outcome)
334 })
335 .collect();
336 assert_eq!(
337 outcomes.len(),
338 1,
339 "{why}: require exactly one persistence outcome, not an inference from exit time: {stderr}"
340 );
341 match outcomes[0] {
342 // The detached writer may still be queued when the bounded CLI exits.
343 // Only the real timeout receipt excuses an incomplete local session.
344 "TimedOut" => return,
345 "Buffered" => {}
346 outcome => panic!("{why}: unexpected local persistence outcome: {outcome}"),
347 }
348 let events = buffered_events(fixture);
349 assert!(
350 events.iter().any(|event| event["event"] == "session_start"),
351 "{why}: the local buffer must carry the session it describes: {events:?}"
352 );
353 assert!(
354 events.iter().any(|event| event["event"] == "session_end"),
355 "{why}: local persistence must carry session_end: {events:?}"
356 );
357 }
358
359 // ── Short CLI persistence is bounded and observable ──────────────────────
360
361 /// An acknowledged short CLI flush must preserve a complete session. A slow
362 /// local writer must report its deadline without waiting for the endpoint.
363 #[tokio::test(flavor = "current_thread")]
364 async fn current_explicit_consent_buffers_one_complete_session_without_network() {
365 let server = start_recorder().await;
366 let fixture = Fixture::new().with_endpoint(&server.uri());
367
368 fixture.write_config("telemetry = true\n");
369 fixture.record_notice(true);
370 let output = fixture.run_short_command();
371
372 assert_short_cli_persistence_without_network(
373 &fixture,
374 &server,
375 &output,
376 "current explicit consent",
377 )
378 .await;
379 }
380
381 #[tokio::test(flavor = "current_thread")]
382 async fn default_on_reports_local_persistence_without_network() {
383 let server = start_recorder().await;
384 let fixture = Fixture::new().with_endpoint(&server.uri());
385
386 let output = fixture.run_short_command();
387
388 assert_short_cli_persistence_without_network(
389 &fixture,
390 &server,
391 &output,
392 "the documented default",
393 )
394 .await;
395 }
396
397 #[tokio::test(flavor = "current_thread")]
398 async fn incomplete_short_cli_sessions_require_an_explicit_timeout() {
399 use std::os::unix::process::ExitStatusExt;
400
401 let server = start_recorder().await;
402 let fixture = Fixture::new().with_endpoint(&server.uri());
403 std::fs::create_dir_all(fixture.telemetry_root()).expect("create local buffer root");
404 std::fs::create_dir_all(fixture.telemetry_root().join("spool")).expect("create spool dir");
405 std::fs::write(
406 fixture
407 .telemetry_root()
408 .join("spool")
409 .join(format!("{}.jsonl", "a".repeat(32))),
410 "{\"event\":\"session_start\",\"source\":\"unknown\"}\n",
411 )
412 .expect("write incomplete session");
413
414 // A successful process exit, an acknowledged but incomplete append, or an
415 // unrecognized outcome must not be relabelled as an allowed deadline.
416 for diagnostic in [
417 "",
418 "info telemetry local persistence outcome=Buffered\n",
419 "info telemetry local persistence outcome=Dropped\n",
420 "info telemetry local persistence outcome=TimedOutLater\n",
421 "info telemetry local persistence outcome=TimedOut\ninfo telemetry local persistence outcome=Buffered\n",
422 ] {
423 let output = Output {
424 status: std::process::ExitStatus::from_raw(0),
425 stdout: Vec::new(),
426 stderr: diagnostic.as_bytes().to_vec(),
427 };
428 let rejected = std::panic::AssertUnwindSafe(assert_short_cli_persistence_without_network(
429 &fixture,
430 &server,
431 &output,
432 "unexplained missing session_end",
433 ))
434 .catch_unwind()
435 .await;
436 assert!(
437 rejected.is_err(),
438 "accepted invalid receipt: {diagnostic:?}"
439 );
440 }
441
442 let timed_out = Output {
443 status: std::process::ExitStatus::from_raw(0),
444 stdout: Vec::new(),
445 stderr: b"info telemetry local persistence outcome=TimedOut\n".to_vec(),
446 };
447 assert_short_cli_persistence_without_network(
448 &fixture,
449 &server,
450 &timed_out,
451 "explicit bounded writer timeout",
452 )
453 .await;
454 }
455
456 // ── Off is real ──────────────────────────────────────────────────────────
457
458 /// The only test that proves the emitting process reads the config *file*.
459 ///
460 /// No environment variable is set here on purpose. `CODEWHALE_TELEMETRY=0` and
461 /// the config key travel different paths, and v1 of this design shipped a
462 /// kill switch that only the env half ever reached.
463 #[tokio::test(flavor = "current_thread")]
464 async fn config_file_only_opt_out_sends_zero_requests() {
465 let server = start_recorder().await;
466 let fixture = Fixture::new().with_endpoint(&server.uri());
467 fixture.write_config("telemetry = false\n");
468 fixture.record_notice(true);
469
470 let output = fixture.run_short_command();
471 assert!(output.status.success());
472
473 assert_no_batches(&server, "`telemetry = false` in the config file").await;
474 assert!(
475 !fixture.telemetry_root().exists(),
476 "a fresh config-file opt-out must create no telemetry state"
477 );
478 }
479
480 #[tokio::test(flavor = "current_thread")]
481 async fn telemetry_disabled_by_env_sends_zero_requests() {
482 let server = start_recorder().await;
483 let fixture = Fixture::new().with_endpoint(&server.uri());
484 fixture.write_config("telemetry = true\n");
485 fixture.record_notice(true);
486
487 let mut command = fixture.command();
488 command
489 .env("CODEWHALE_TELEMETRY", "0")
490 .args([
491 "--config",
492 fixture.config_path.to_str().expect("config path"),
493 "doctor",
494 ])
495 .output()
496 .expect("run codewhale doctor");
497
498 assert_no_batches(&server, "`CODEWHALE_TELEMETRY=0`").await;
499 assert!(
500 !fixture.telemetry_root().exists(),
501 "a fresh run-scoped opt-out must create no telemetry state"
502 );
503 }
504
505 /// An unparseable env value fails **closed**, rather than falling through to
506 /// the config file's `true`.
507 #[tokio::test(flavor = "current_thread")]
508 async fn an_unparseable_telemetry_env_value_sends_zero_requests() {
509 let server = start_recorder().await;
510 let fixture = Fixture::new().with_endpoint(&server.uri());
511 fixture.write_config("telemetry = true\n");
512 fixture.record_notice(true);
513
514 fixture
515 .command()
516 .env("CODEWHALE_TELEMETRY", "maybe")
517 .args([
518 "--config",
519 fixture.config_path.to_str().expect("config path"),
520 "doctor",
521 ])
522 .output()
523 .expect("run codewhale doctor");
524
525 assert_no_batches(&server, "`CODEWHALE_TELEMETRY=maybe`").await;
526 assert!(
527 !fixture.telemetry_root().exists(),
528 "a fresh forced-off run must create no telemetry state"
529 );
530 }
531
532 /// A fresh headless run defaults on and records presentation, not acceptance.
533 #[tokio::test(flavor = "current_thread")]
534 async fn telemetry_defaults_on_without_notice_buffers_a_complete_session() {
535 let server = start_recorder().await;
536 let fixture = Fixture::new().with_endpoint(&server.uri());
537 // Deliberately no `record_notice`.
538
539 let output = fixture.run_short_command();
540
541 assert_short_cli_persistence_without_network(&fixture, &server, &output, "default-on usage")
542 .await;
543 let state = SetupState::load_from(&fixture.setup_state_path()).expect("shown state");
544 assert_eq!(
545 state.telemetry_notice_shown_for.as_deref(),
546 Some(TELEMETRY_NOTICE_VERSION)
547 );
548 assert!(!state.telemetry_accepted(TELEMETRY_NOTICE_VERSION));
549 }
550
551 /// A previous acceptance remains enabled under the default-on policy.
552 #[tokio::test(flavor = "current_thread")]
553 async fn a_stale_accepted_notice_remains_on_without_synthesizing_current_acceptance() {
554 let server = start_recorder().await;
555 let fixture = Fixture::new().with_endpoint(&server.uri());
556 fixture.write_config("telemetry = true\n");
557 let mut state = SetupState::default();
558 state.record_telemetry_notice("0", true);
559 state
560 .save_to(&fixture.setup_state_path())
561 .expect("write setup state");
562
563 let output = fixture.run_short_command();
564
565 assert_short_cli_persistence_without_network(&fixture, &server, &output, "default-on usage")
566 .await;
567 let state = SetupState::load_from(&fixture.setup_state_path()).expect("shown state");
568 assert_eq!(
569 state.telemetry_notice_shown_for.as_deref(),
570 Some(TELEMETRY_NOTICE_VERSION)
571 );
572 assert!(!state.telemetry_accepted(TELEMETRY_NOTICE_VERSION));
573 }
574
575 // ── Nothing survives a disable ───────────────────────────────────────────
576
577 /// A human's "off" wipes: tombstone first, data truncated, lock file left in
578 /// place, identity removed.
579 #[tokio::test(flavor = "current_thread")]
580 async fn disabling_after_buffering_wipes_and_sends_nothing() {
581 let server = start_recorder().await;
582 let fixture = Fixture::new().with_endpoint(&server.uri());
583 let root = fixture.telemetry_root();
584 seed_consenting_home(&root);
585 fixture.write_config("telemetry = false\n");
586 fixture.record_notice(true);
587
588 fixture.run_short_command();
589
590 assert_no_batches(&server, "an explicit opt-out with a populated buffer").await;
591 assert!(
592 root.join("disabled").exists(),
593 "the tombstone is written first and never removed"
594 );
595 assert_eq!(
596 std::fs::read(root.join("buffer.jsonl")).expect("buffer survives as an empty file"),
597 Vec::<u8>::new(),
598 "buffered events must be truncated, not sent"
599 );
600 assert!(
601 root.join("buffer.jsonl.lock").exists(),
602 "the lock file is never unlinked: replacing it would leave appenders \
603 and compactors holding different inodes"
604 );
605 assert!(
606 !root.join("install_id.json").exists(),
607 "the install identity must not survive an opt-out"
608 );
609 }
610
611 /// A non-persistent forced-off result must preserve an existing identity and
612 /// unflushed buffer.
613 #[tokio::test(flavor = "current_thread")]
614 async fn forced_off_run_preserves_a_consenting_users_state() {
615 let server = start_recorder().await;
616 let fixture = Fixture::new().with_endpoint(&server.uri());
617 let root = fixture.telemetry_root();
618 seed_consenting_home(&root);
619 let before = snapshot(&root);
620 let mut command = fixture.command();
621 command
622 .env("CODEWHALE_TELEMETRY", "not-a-bool")
623 .args([
624 "--config",
625 fixture.config_path.to_str().expect("config path"),
626 "doctor",
627 ])
628 .output()
629 .expect("run codewhale doctor");
630
631 assert_no_batches(&server, "a forced-off run").await;
632 assert_eq!(
633 snapshot(&root),
634 before,
635 "a forced-off run must leave a consenting user's telemetry state byte-identical"
636 );
637 }
638
639 /// The documented one-command kill switch stops collection and destroys
640 /// nothing.
641 ///
642 /// `CODEWHALE_TELEMETRY=0` used to resolve as an *answer*, so it took the
643 /// destructive opt-out branch: an agent harness that set it for one command
644 /// deleted the install id and truncated the dry-run records of the person who
645 /// owns the machine, and the "permanent" tombstone it left was cleared by the
646 /// user's very next ordinary run. Off for the run, and only for the run.
647 #[tokio::test(flavor = "current_thread")]
648 async fn a_run_scoped_kill_switch_preserves_a_consenting_users_state() {
649 let server = start_recorder().await;
650 let fixture = Fixture::new().with_endpoint(&server.uri());
651 let root = fixture.telemetry_root();
652 seed_consenting_home(&root);
653 let before = snapshot(&root);
654 fixture.write_config("telemetry = true\n");
655 fixture.record_notice(true);
656
657 for value in ["0", "off", "false"] {
658 fixture
659 .command()
660 .env("CODEWHALE_TELEMETRY", value)
661 .args([
662 "--config",
663 fixture.config_path.to_str().expect("config path"),
664 "doctor",
665 ])
666 .output()
667 .expect("run codewhale doctor");
668
669 assert_no_batches(&server, "a run-scoped kill switch").await;
670 assert!(
671 !root.join("disabled").exists(),
672 "`CODEWHALE_TELEMETRY={value}` tombstoned a machine nobody opted out"
673 );
674 assert_eq!(
675 snapshot(&root),
676 before,
677 "`CODEWHALE_TELEMETRY={value}` touched a consenting user's telemetry state"
678 );
679 }
680
681 // And the persistent switch still is the destructive one, on the same
682 // home, so the two are not merely both no-ops here.
683 fixture.write_config("telemetry = false\n");
684 fixture.run_short_command();
685 assert!(
686 root.join("disabled").exists(),
687 "the config-file opt-out must still wipe and tombstone"
688 );
689 assert!(!root.join("install_id.json").exists());
690 }
691
692 /// A run that was never permitted to collect creates no directory at all —
693 /// which is also what makes the process panic hook, installed before the
694 /// command line is even parsed, write nothing for a disabled user.
695 #[tokio::test(flavor = "current_thread")]
696 async fn a_disabled_run_creates_no_telemetry_directory() {
697 let server = start_recorder().await;
698 let fixture = Fixture::new().with_endpoint(&server.uri());
699 fixture.write_config("telemetry = false\n");
700 fixture.record_notice(false);
701
702 fixture.run_short_command();
703
704 assert_no_batches(&server, "a declined run").await;
705 assert!(
706 !fixture.telemetry_root().exists(),
707 "nothing may be created for a user who declined on a fresh home"
708 );
709 }
710
711 // ── The notice is never answered by silence ──────────────────────────────
712
713 /// Deferral is not a decision. `--skip-onboarding` records and prints no notice
714 /// decision, while the non-interactive run still follows the documented
715 /// default — unlike the constitution checkpoint, which persists a `Deferred`
716 /// completion.
717 #[tokio::test(flavor = "current_thread")]
718 async fn skip_onboarding_writes_no_telemetry_decision() {
719 let server = start_recorder().await;
720 let fixture = Fixture::new().with_endpoint(&server.uri());
721 fixture.write_config("telemetry = true\n");
722
723 let mut command = fixture.command();
724 let output = command
725 .args([
726 "--verbose",
727 "--config",
728 fixture.config_path.to_str().expect("config path"),
729 "--skip-onboarding",
730 "config",
731 "telemetry",
732 ])
733 .output()
734 .expect("run short telemetry config command");
735 assert!(output.status.success());
736
737 let stdout = String::from_utf8_lossy(&output.stdout);
738 let stderr = String::from_utf8_lossy(&output.stderr);
739 for stream in [&stdout, &stderr] {
740 assert!(
741 !stream.contains("keep telemetry off"),
742 "the notice must not be rendered on a path that cannot answer it"
743 );
744 }
745
746 if let Some(state) = SetupState::load_from(&fixture.setup_state_path()) {
747 assert_eq!(
748 state.telemetry_notice_decided_for, None,
749 "skip-onboarding must leave the telemetry decision unset"
750 );
751 }
752 assert_short_cli_persistence_without_network(
753 &fixture,
754 &server,
755 &output,
756 "`--skip-onboarding` follows the default",
757 )
758 .await;
759 let state = SetupState::load_from(&fixture.setup_state_path()).expect("shown state");
760 assert_eq!(
761 state.telemetry_notice_shown_for.as_deref(),
762 Some(TELEMETRY_NOTICE_VERSION)
763 );
764 assert!(!state.telemetry_accepted(TELEMETRY_NOTICE_VERSION));
765 }
766
767 // ── Payload red lines, through a real turn ───────────────────────────────
768
769 /// Five sentinel classes planted through real inputs — the prompt, a workspace
770 /// filename, a custom `[providers.<name>]` table key, an MCP server name, and
771 /// the API key — asserted absent from every recorded batch.
772 ///
773 /// The API key is held to the stricter standard the harness at
774 /// `crates/tui/tests/verifiers_harness_contract.rs` applies: absent from stdout,
775 /// stderr, and every file under the sealed roots as well. The other four
776 /// legitimately appear in files the product owns — a prompt is in the session
777 /// transcript, a provider table key is in the config the user wrote — so the
778 /// claim about them is precisely that they never reach a *batch*.
779 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
780 async fn batch_contains_no_planted_sentinel() {
781 let server = start_recorder().await;
782 mount_model(&server, Duration::ZERO).await;
783 let fixture = Fixture::new().with_endpoint(&server.uri());
784 plant_sentinels(&fixture, &server.uri());
785
786 let output = run_exec(&fixture, SENTINEL_PROMPT);
787 assert_exec_succeeded(&output, "sentinel payload run");
788
789 assert!(
790 model_request_count(&server).await > 0,
791 "the sentinel prompt must actually have reached a model, or this test \
792 proves nothing\nstdout:\n{}\nstderr:\n{}",
793 String::from_utf8_lossy(&output.stdout),
794 String::from_utf8_lossy(&output.stderr)
795 );
796 let batches = recorded_batches(&server).await;
797 assert!(
798 !batches.is_empty(),
799 "this test is only meaningful against a batch that was actually sent"
800 );
801 for batch in &batches {
802 assert_eq!(batch["schema_version"], 4);
803 assert_eq!(batch["notice_version"], 6);
804 assert!(batch.get("consent_version").is_none());
805 }
806 let shown = SetupState::load_from(&fixture.setup_state_path()).expect("disclosure marker");
807 assert_eq!(shown.telemetry_notice_decided_for, None);
808 assert!(!shown.telemetry_opt_in);
809 let serialized = serde_json::to_string(&batches).expect("serialize batches");
810 for sentinel in [
811 SENTINEL_PROMPT,
812 SENTINEL_FILENAME,
813 SENTINEL_PROVIDER_TABLE,
814 SENTINEL_MCP_SERVER,
815 SENTINEL_API_KEY,
816 ] {
817 assert!(
818 !serialized.contains(sentinel),
819 "sentinel `{sentinel}` reached a telemetry batch:\n{serialized}"
820 );
821 }
822
823 let stdout = String::from_utf8_lossy(&output.stdout);
824 let stderr = String::from_utf8_lossy(&output.stderr);
825 assert!(
826 !stdout.contains(SENTINEL_API_KEY),
827 "the API key leaked into stdout"
828 );
829 assert!(
830 !stderr.contains(SENTINEL_API_KEY),
831 "the API key leaked into stderr"
832 );
833 for file in fixture.written_files() {
834 let Ok(bytes) = std::fs::read(&file) else {
835 continue;
836 };
837 assert!(
838 !String::from_utf8_lossy(&bytes).contains(SENTINEL_API_KEY),
839 "the API key leaked into {}",
840 file.display()
841 );
842 }
843 }
844
845 /// The buffer file is an **untrusted input**, and this is the test that says so.
846 ///
847 /// Every bound in `codewhale-telemetry`'s schema is a property of how a payload
848 /// is *built*: closed enums, `u32`s, `ProviderKind::as_str()`,
849 /// `reduce_panic_site`. None of that survives the round trip, because `flush`
850 /// re-reads `buffer.jsonl` and deserializes it — and `$CODEWHALE_HOME` is a
851 /// predictable path that anything running as the user can append to. The
852 /// realistic writer is not an intruder: it is a `Bash` tool call this very
853 /// session made on the model's behalf, or an MCP server, or a hook. Without a
854 /// drain-path re-check, telemetry is a confused deputy that POSTs whatever that
855 /// writer chooses to the configured endpoint, under the user's install id, past
856 /// every egress control the user has on the provider route.
857 ///
858 /// The injection happens **after** the session has armed, on purpose: `init`
859 /// truncates the buffer, so a pre-arming plant proves nothing.
860 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
861 async fn a_hostile_buffer_line_never_reaches_a_batch() {
862 let server = start_recorder().await;
863 // A slow first token holds the session open long enough to append.
864 mount_model(&server, Duration::from_secs(5)).await;
865 let fixture = Fixture::new().with_endpoint(&server.uri());
866 plant_sentinels(&fixture, &server.uri());
867
868 let mut command = exec_command(&fixture, "hello");
869 let mut child = command.spawn().expect("spawn codewhale exec");
870 let stdout = read_in_background(child.stdout.take().expect("stdout pipe"));
871 let stderr = read_in_background(child.stderr.take().expect("stderr pipe"));
872
873 wait_until(Duration::from_secs(30), || {
874 only_spool_file(&fixture).is_some()
875 });
876 let buffer = only_spool_file(&fixture).expect("this session's spool");
877 append_lines(
878 &buffer,
879 &[
880 // The path-bearing field, carrying a path it was never meant to.
881 json!({"event": "panic", "site": SENTINEL_INJECTED}).to_string(),
882 // The one event field read back from `state.json`.
883 json!({"event": "install_or_upgrade", "kind": "upgrade",
884 "previous_version": SENTINEL_INJECTED})
885 .to_string(),
886 // The provider set, whose whole design is that it cannot carry a
887 // customer's `[providers.<name>]` table key.
888 json!({"event": "session_end", "duration_bucket": "lt_1m",
889 "exit_class": "clean", "cold_start_bucket": null,
890 "providers": [SENTINEL_INJECTED],
891 "counters": {"turns": 0, "tool_calls": 0, "fleet_dispatch": 0,
892 "workflow_run": 0, "subagent_spawn": 0,
893 "mcp_server_connected": 0, "memory_search": 0,
894 "approval_modal_shown": 0, "approval_auto_allowed": 0,
895 "command_palette_open": 0},
896 "errors": {"auth_preflight_failed": 0, "provider_http_4xx": 0,
897 "provider_http_5xx": 0, "tool_denied_by_policy": 0,
898 "tool_timeout": 0, "network_error": 0},
899 "turn_wall": {"lt_5s": 0, "5_30s": 0, "30_120s": 0, "gte_120s": 0}})
900 .to_string(),
901 ],
902 );
903
904 let status = child
905 .wait_timeout(EXEC_TIMEOUT)
906 .expect("wait for codewhale exec")
907 .expect("codewhale exec must exit");
908 let output = Output {
909 status,
910 stdout: stdout.join().expect("stdout reader"),
911 stderr: stderr.join().expect("stderr reader"),
912 };
913 assert_exec_succeeded(&output, "hostile-buffer payload run");
914
915 let batches = recorded_batches(&server).await;
916 assert!(
917 !batches.is_empty(),
918 "this test is only meaningful against a batch that was actually sent"
919 );
920 let serialized = serde_json::to_string(&batches).expect("serialize batches");
921 assert!(
922 !serialized.contains(SENTINEL_INJECTED),
923 "a line appended to buffer.jsonl was POSTed verbatim:\n{serialized}"
924 );
925 }
926
927 /// Append raw lines to a sink, the way any other process on the machine would.
928 fn append_lines(path: &Path, lines: &[String]) {
929 use std::io::Write as _;
930 let mut file = std::fs::OpenOptions::new()
931 .append(true)
932 .open(path)
933 .expect("open the telemetry buffer");
934 for line in lines {
935 writeln!(file, "{line}").expect("append to the telemetry buffer");
936 }
937 }
938
939 /// The documented mid-session opt-out — `codewhale config set telemetry false`,
940 /// written by another process — must be observed by a session that is already
941 /// running. The flush re-resolves from disk before it sends anything.
942 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
943 async fn mid_session_opt_out_stops_the_shutdown_flush() {
944 let server = start_recorder().await;
945 // A slow first token gives the second writer a window while the session is
946 // armed and buffering.
947 mount_model(&server, Duration::from_secs(4)).await;
948 let fixture = Fixture::new().with_endpoint(&server.uri());
949 plant_sentinels(&fixture, &server.uri());
950
951 let mut command = exec_command(&fixture, "hello");
952 let mut child = command.spawn().expect("spawn codewhale exec");
953 let stdout = read_in_background(child.stdout.take().expect("stdout pipe"));
954 let stderr = read_in_background(child.stderr.take().expect("stderr pipe"));
955
956 // Wait until this session's event is actually buffered, then leave enough
957 // time for any accidental background flush to reach the recorder. Nothing
958 // may be sent before shutdown.
959 wait_until(Duration::from_secs(30), || {
960 only_spool_file(&fixture)
961 .and_then(|buffer| std::fs::read_to_string(buffer).ok())
962 .is_some_and(|body| body.contains("\"event\":\"session_start\""))
963 });
964 tokio::time::sleep(Duration::from_millis(250)).await;
965 assert_no_batches(&server, "before the shutdown flush").await;
966
967 // Now take the documented way out from outside the process. The only
968 // flush, at shutdown, must re-resolve this write and suppress the batch.
969 fixture.write_config(&sentinel_config(&server.uri(), false));
970
971 let status = child
972 .wait_timeout(EXEC_TIMEOUT)
973 .expect("wait for codewhale exec")
974 .expect("codewhale exec must exit");
975 let output = Output {
976 status,
977 stdout: stdout.join().expect("stdout reader"),
978 stderr: stderr.join().expect("stderr reader"),
979 };
980 assert_exec_succeeded(&output, "mid-session opt-out run");
981
982 assert_no_batches(&server, "an opt-out written mid-session").await;
983 let root = fixture.telemetry_root();
984 assert!(
985 root.join("disabled").exists(),
986 "the opt-out wipe must leave a tombstone the next run also honours"
987 );
988 }
989
990 /// Ctrl-C must not wait on a lock a second Codewhale process is holding.
991 ///
992 /// This is why appends never take the compaction lock: `flock` is per-fd within
993 /// a process, so a blocking acquisition on the signal path would hang exit for
994 /// as long as any other holder lives.
995 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
996 async fn ctrl_c_exits_while_a_second_process_holds_the_lock() {
997 let server = start_recorder().await;
998 mount_model(&server, Duration::from_secs(30)).await;
999 let fixture = Fixture::new().with_endpoint(&server.uri());
1000 plant_sentinels(&fixture, &server.uri());
1001
1002 let mut command = exec_command(&fixture, "hello");
1003 let mut child = command.spawn().expect("spawn codewhale exec");
1004
1005 let root = fixture.telemetry_root();
1006 let lock_path = root.join("buffer.jsonl.lock");
1007 // Arming itself takes the lock, so the holder below must wait until the
1008 // session is armed — otherwise this test would pin a deadlock it created.
1009 wait_until(Duration::from_secs(30), || {
1010 only_spool_file(&fixture).is_some()
1011 });
1012 let _holder = LockHolder::take(&lock_path);
1013
1014 // SIGINT to the child alone; the process group belongs to the test runner.
1015 let pid = child.id() as libc::pid_t;
1016 // SAFETY: `kill` with a pid this process spawned and has not reaped.
1017 unsafe {
1018 libc::kill(pid, libc::SIGINT);
1019 }
1020
1021 let started = Instant::now();
1022 let status = child
1023 .wait_timeout(Duration::from_secs(10))
1024 .expect("wait for codewhale exec");
1025 let status = status.unwrap_or_else(|| {
1026 let _ = child.kill();
1027 panic!(
1028 "Ctrl-C blocked for {:?} while another process held the telemetry lock — \
1029 the signal path must append without taking it",
1030 started.elapsed()
1031 )
1032 });
1033 assert_eq!(
1034 status.code(),
1035 Some(130),
1036 "SIGINT must still exit 130 with the telemetry lock held elsewhere"
1037 );
1038 assert!(
1039 started.elapsed() < Duration::from_secs(1),
1040 "Ctrl-C took {:?} while the telemetry lock was held elsewhere",
1041 started.elapsed()
1042 );
1043 }
1044
1045 /// Holds the telemetry compaction lock for the lifetime of the value.
1046 struct LockHolder {
1047 file: std::fs::File,
1048 }
1049
1050 impl LockHolder {
1051 fn take(path: &Path) -> Self {
1052 let file = std::fs::OpenOptions::new()
1053 .create(true)
1054 .read(true)
1055 .write(true)
1056 .truncate(false)
1057 .open(path)
1058 .expect("open the telemetry lock");
1059 let fd = std::os::unix::io::AsRawFd::as_raw_fd(&file);
1060 let started = Instant::now();
1061 loop {
1062 // SAFETY: `fd` is owned by `file` and outlives the call.
1063 let taken = unsafe { libc::flock(fd, libc::LOCK_EX | libc::LOCK_NB) };
1064 if taken == 0 {
1065 break;
1066 }
1067
1068 let err = std::io::Error::last_os_error();
1069 let retryable = err
1070 .raw_os_error()
1071 .is_some_and(|code| code == libc::EWOULDBLOCK || code == libc::EAGAIN);
1072 assert!(retryable, "failed to take the telemetry lock: {err}");
1073 assert!(
1074 started.elapsed() < Duration::from_secs(5),
1075 "the telemetry arming lock remained held for {:?}",
1076 started.elapsed()
1077 );
1078 std::thread::sleep(Duration::from_millis(10));
1079 }
1080 Self { file }
1081 }
1082 }
1083
1084 impl Drop for LockHolder {
1085 fn drop(&mut self) {
1086 let fd = std::os::unix::io::AsRawFd::as_raw_fd(&self.file);
1087 // SAFETY: same fd, still owned by `self`.
1088 unsafe {
1089 libc::flock(fd, libc::LOCK_UN);
1090 }
1091 }
1092 }
1093
1094 // ── exec harness ─────────────────────────────────────────────────────────
1095
1096 fn sse_chunk(value: Value) -> String {
1097 format!(
1098 "data: {}\n\n",
1099 serde_json::to_string(&value).expect("SSE JSON")
1100 )
1101 }
1102
1103 fn text_sse(text: &str) -> String {
1104 [
1105 sse_chunk(json!({
1106 "id": "chatcmpl-tc",
1107 "object": "chat.completion.chunk",
1108 "model": TEST_MODEL,
1109 "choices": [{"index": 0, "delta": {"content": text}, "finish_reason": null}]
1110 })),
1111 sse_chunk(json!({
1112 "id": "chatcmpl-tc",
1113 "object": "chat.completion.chunk",
1114 "model": TEST_MODEL,
1115 "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],
1116 "usage": {"prompt_tokens": 7, "completion_tokens": 2, "total_tokens": 9}
1117 })),
1118 "data: [DONE]\n\n".to_string(),
1119 ]
1120 .join("")
1121 }
1122
1123 async fn mount_model(server: &MockServer, delay: Duration) {
1124 Mock::given(method("GET"))
1125 .and(path_matcher("/v1/models"))
1126 .respond_with(
1127 ResponseTemplate::new(200)
1128 .insert_header("content-type", "application/json")
1129 .set_body_json(json!({
1130 "object": "list",
1131 "data": [{"id": TEST_MODEL, "object": "model"}]
1132 })),
1133 )
1134 .mount(server)
1135 .await;
1136 Mock::given(method("POST"))
1137 .and(path_matcher(MODEL_PATH))
1138 .respond_with(
1139 ResponseTemplate::new(200)
1140 .insert_header("content-type", "text/event-stream")
1141 .insert_header("cache-control", "no-cache")
1142 .set_body_string(text_sse("acknowledged"))
1143 .set_delay(delay),
1144 )
1145 .mount(server)
1146 .await;
1147 }
1148
1149 /// A config whose provider table key, MCP server name, and workspace file are
1150 /// all sentinels, so a leak has somewhere to come from.
1151 fn sentinel_config(base_url: &str, telemetry: bool) -> String {
1152 format!(
1153 "telemetry = {telemetry}\nprovider = \"{SENTINEL_PROVIDER_TABLE}\"\n\n\
1154 [providers.{SENTINEL_PROVIDER_TABLE}]\n\
1155 kind = \"openai-compatible\"\n\
1156 base_url = \"{base_url}/v1\"\n\
1157 model = \"{TEST_MODEL}\"\n\
1158 api_key_env = \"{SENTINEL_API_KEY_ENV}\"\n"
1159 )
1160 }
1161
1162 fn plant_sentinels(fixture: &Fixture, base_url: &str) {
1163 let config = sentinel_config(base_url, true);
1164 fixture.write_config(
1165 config
1166 .strip_prefix("telemetry = true\n")
1167 .expect("fixture preference"),
1168 );
1169 // No saved preference or acceptance: the real exec path must use default-on.
1170 std::fs::write(
1171 fixture.workspace.join(SENTINEL_FILENAME),
1172 "sentinel workspace file\n",
1173 )
1174 .expect("plant workspace file");
1175 std::fs::write(
1176 fixture.codewhale_home.join("mcp.json"),
1177 // Keep the MCP name in a real parsed config without starting a process
1178 // that exits before CodeWhale can write its initialize request. The
1179 // telemetry contract is about name redaction, not broken-pipe handling.
1180 json!({"mcpServers": {SENTINEL_MCP_SERVER: {
1181 "command": "/bin/true",
1182 "args": [],
1183 "disabled": true
1184 }}})
1185 .to_string(),
1186 )
1187 .expect("plant MCP config");
1188 }
1189
1190 fn exec_command(fixture: &Fixture, prompt: &str) -> Command {
1191 let mut command = fixture.command();
1192 command
1193 .env(
1194 "CODEWHALE_MCP_CONFIG",
1195 fixture.codewhale_home.join("mcp.json"),
1196 )
1197 .env(SENTINEL_API_KEY_ENV, SENTINEL_API_KEY)
1198 .args([
1199 "--config",
1200 fixture.config_path.to_str().expect("config path"),
1201 "--workspace",
1202 fixture.workspace.to_str().expect("workspace path"),
1203 "--no-project-config",
1204 "--skip-onboarding",
1205 "exec",
1206 "--auto",
1207 "--output-format",
1208 "stream-json",
1209 "--",
1210 prompt,
1211 ])
1212 .stdout(Stdio::piped())
1213 .stderr(Stdio::piped());
1214 command
1215 }
1216
1217 fn run_exec(fixture: &Fixture, prompt: &str) -> Output {
1218 let mut command = exec_command(fixture, prompt);
1219 let mut child = command.spawn().expect("spawn codewhale exec");
1220 let stdout = read_in_background(child.stdout.take().expect("stdout pipe"));
1221 let stderr = read_in_background(child.stderr.take().expect("stderr pipe"));
1222 let status = match child.wait_timeout(EXEC_TIMEOUT).expect("wait for exec") {
1223 Some(status) => status,
1224 None => {
1225 let _ = child.kill();
1226 panic!("codewhale exec did not exit within {EXEC_TIMEOUT:?}");
1227 }
1228 };
1229 Output {
1230 status,
1231 stdout: stdout.join().expect("stdout reader"),
1232 stderr: stderr.join().expect("stderr reader"),
1233 }
1234 }
1235
1236 fn assert_exec_succeeded(output: &Output, context: &str) {
1237 assert!(
1238 output.status.success(),
1239 "{context} exited with {}\nstdout:\n{}\nstderr:\n{}",
1240 output.status,
1241 String::from_utf8_lossy(&output.stdout),
1242 String::from_utf8_lossy(&output.stderr)
1243 );
1244 }
1245
1246 fn read_in_background(mut pipe: impl Read + Send + 'static) -> std::thread::JoinHandle<Vec<u8>> {
1247 std::thread::spawn(move || {
1248 let mut buffer = Vec::new();
1249 let _ = pipe.read_to_end(&mut buffer);
1250 buffer
1251 })
1252 }
1253
1254 fn wait_until(limit: Duration, mut ready: impl FnMut() -> bool) {
1255 let started = Instant::now();
1256 while started.elapsed() < limit {
1257 if ready() {
1258 return;
1259 }
1260 std::thread::sleep(Duration::from_millis(25));
1261 }
1262 panic!("condition was not reached within {limit:?}");
1263 }
1264
1265 // ── Seeded state ─────────────────────────────────────────────────────────
1266
1267 /// A home that already belongs to a consenting user: an identity, a populated
1268 /// buffer, a flush record, and the lock file.
1269 fn seed_consenting_home(root: &Path) {
1270 std::fs::create_dir_all(root).expect("create telemetry root");
1271 std::fs::write(
1272 root.join("install_id.json"),
1273 json!({
1274 "schema_version": 1,
1275 "install_id": "11111111-2222-3333-4444-555555555555",
1276 "rotated_at": "2026-01-01T00:00:00Z"
1277 })
1278 .to_string(),
1279 )
1280 .expect("seed install id");
1281 std::fs::write(
1282 root.join("state.json"),
1283 json!({"schema_version": 1, "last_version": "0.0.1"}).to_string(),
1284 )
1285 .expect("seed state");
1286 std::fs::write(
1287 root.join("buffer.jsonl"),
1288 format!(
1289 "{}\n",
1290 json!({"event": "session_start", "source": "unknown"})
1291 ),
1292 )
1293 .expect("seed buffer");
1294 std::fs::write(root.join("buffer.jsonl.lock"), b"").expect("seed lock file");
1295 }
1296
1297 fn snapshot(root: &Path) -> Vec<(String, Vec<u8>)> {
1298 let mut files = Vec::new();
1299 collect_files(root, &mut files);
1300 let mut out: Vec<(String, Vec<u8>)> = files
1301 .into_iter()
1302 .map(|path| {
1303 let name = path
1304 .strip_prefix(root)
1305 .unwrap_or(&path)
1306 .to_string_lossy()
1307 .into_owned();
1308 let bytes = std::fs::read(&path).unwrap_or_default();
1309 (name, bytes)
1310 })
1311 .collect();
1312 out.sort();
1313 out
1314 }
1315
1315 lines RUST