openlatch-client 0.5.2

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
//! Consent resolver for the telemetry subsystem.
//!
//! Resolves the current consent state by applying the precedence rules from
//! `.brainstorms/2026-04-13-posthog-client-telemetry.md §4.3`:
//!
//! 1. `DO_NOT_TRACK=1` → disabled (cross-tool standard)
//! 2. `OPENLATCH_TELEMETRY_DISABLED=1` → disabled
//! 3. CI environment detected → disabled
//! 4. `~/.openlatch/telemetry.json { enabled: false }` → disabled
//! 5. `~/.openlatch/telemetry.json { enabled: true }` → enabled
//! 6. File missing → disabled (until `openlatch init` writes consent)
//!
//! The resolver also reports which rule fired, so `openlatch system telemetry status`
//! can explain the deciding factor to the user (invariant I7).

use std::path::Path;

use super::config::{read_consent, ConsentFile};

/// Final consent state — the question `capture()` asks before doing anything.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConsentState {
    /// Telemetry is active — events may be captured and sent.
    Enabled,
    /// Telemetry is off — `capture()` is a no-op, no network.
    Disabled,
}

/// Which precedence rule decided the final state.
///
/// Exposed via `openlatch system telemetry status` so users can verify opt-out
/// actually took effect (invariant I7 — "trust but verify").
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DecidedBy {
    /// `DO_NOT_TRACK` environment variable is set to a truthy value.
    DoNotTrackEnv,
    /// `OPENLATCH_TELEMETRY_DISABLED` environment variable is set.
    OpenlatchDisabledEnv,
    /// A CI environment was detected (`CI=true`, `GITHUB_ACTIONS`, etc.).
    CiEnvironment,
    /// Value came from the `~/.openlatch/telemetry.json` file.
    ConfigFile,
    /// No consent file existed — default is disabled until the first-run notice fires.
    DefaultUnconsented,
    /// The baked PostHog key is empty, so the subsystem cannot emit anyway.
    NoBakedKey,
}

/// Resolved consent state plus the rule that decided it.
#[derive(Debug, Clone, Copy)]
pub struct Resolved {
    pub state: ConsentState,
    pub decided_by: DecidedBy,
}

impl Resolved {
    pub fn enabled(&self) -> bool {
        self.state == ConsentState::Enabled
    }
}

/// Resolve the current consent state by reading env vars and `telemetry.json`.
///
/// Pure function — takes the config path as a parameter so tests can point it
/// at a tempdir. Never fails: parse errors on the config file are treated as
/// "disabled" (invariant — corrupt file never silently re-enables).
pub fn resolve(config_path: &Path) -> Resolved {
    if is_truthy_env("DO_NOT_TRACK") {
        return Resolved {
            state: ConsentState::Disabled,
            decided_by: DecidedBy::DoNotTrackEnv,
        };
    }
    if is_truthy_env("OPENLATCH_TELEMETRY_DISABLED") {
        return Resolved {
            state: ConsentState::Disabled,
            decided_by: DecidedBy::OpenlatchDisabledEnv,
        };
    }
    if in_ci() {
        return Resolved {
            state: ConsentState::Disabled,
            decided_by: DecidedBy::CiEnvironment,
        };
    }

    match read_consent(config_path) {
        Ok(Some(ConsentFile { enabled, .. })) => Resolved {
            state: if enabled {
                ConsentState::Enabled
            } else {
                ConsentState::Disabled
            },
            decided_by: DecidedBy::ConfigFile,
        },
        Ok(None) => Resolved {
            state: ConsentState::Disabled,
            decided_by: DecidedBy::DefaultUnconsented,
        },
        // Corrupt file → treat as disabled. This is a non-observable failure
        // by design (invariant I10 — no telemetry about telemetry).
        Err(_) => Resolved {
            state: ConsentState::Disabled,
            decided_by: DecidedBy::ConfigFile,
        },
    }
}

fn is_truthy_env(name: &str) -> bool {
    std::env::var(name).is_ok_and(|v| {
        let v = v.trim().to_ascii_lowercase();
        !matches!(v.as_str(), "" | "0" | "false" | "no" | "off")
    })
}

/// Detect common CI environments. A best-effort match against the most
/// prevalent CI indicators — any unexpected CI is still caught by the
/// generic `CI` variable that most providers set.
pub fn in_ci() -> bool {
    const CI_VARS: &[&str] = &[
        "CI",
        "GITHUB_ACTIONS",
        "GITLAB_CI",
        "CIRCLECI",
        "JENKINS_URL",
        "BUILDKITE",
        "TF_BUILD",
        "TEAMCITY_VERSION",
        "BITBUCKET_BUILD_NUMBER",
    ];
    CI_VARS
        .iter()
        .any(|v| std::env::var(v).is_ok_and(|x| !x.is_empty()))
}

// ---------------------------------------------------------------------------
// Crash reporting — the SECOND, INDEPENDENT gate.
//
// Two gates live in this file and share nothing: no early return, no cached
// state, no environment variable. A user who opted out of product analytics has
// not asked to stop sending crash reports, and a user who silenced crash
// reports has not opted out of analytics. Folding them would be a one-line
// change and a privacy regression.
// ---------------------------------------------------------------------------

/// Which precedence rule decided crash reporting's state.
///
/// DELIBERATELY NARROWER than the product-telemetry chain above. `DO_NOT_TRACK` and
/// CI-environment detection are NOT consulted: crash reports are diagnostic rather than
/// behavioural, and CI panics are exactly the bugs we want to catch. That reasoning is
/// carried over from the module this replaces — it was a decision, not an oversight, and
/// a future reader will otherwise "fix" it.
///
/// **These variant names are a log contract.** The daemon writes
/// `format!("{:?}", decided_by)` into daemon.log's `crash_report_decided_by`, which
/// operators grep. Renaming one changes what they see.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CrashDecidedBy {
    /// `OPENLATCH_CRASH_REPORTING` is set to a falsy value.
    CrashReportingEnv,
    /// No PostHog project key baked at build time and none at runtime.
    NoProjectKey,
    /// The `[crashreport]` section decided it — EITHER WAY. `enabled = false` disables;
    /// `enabled = true` enables and still reports `ConfigFile`, which is what lets
    /// `openlatch doctor` print `on (config.toml)` rather than `on (default)`. Defining
    /// this as the disabled case only would silently collapse those two labels.
    ConfigFile,
    /// Section absent, or the file could not be parsed.
    DefaultEnabled,
}

/// Resolved crash-reporting state plus the rule that decided it.
#[derive(Debug, Clone, Copy)]
pub struct CrashResolved {
    pub state: ConsentState,
    pub decided_by: CrashDecidedBy,
}

impl CrashResolved {
    pub fn enabled(&self) -> bool {
        self.state == ConsentState::Enabled
    }
}

/// Resolve crash-reporting consent.
///
/// Precedence, top wins:
///
/// 1. `OPENLATCH_CRASH_REPORTING` falsy -> disabled (hard lock)
/// 2. no project key anywhere           -> disabled (nothing to send to)
/// 3. `[crashreport] enabled = false`   -> disabled
/// 4. section missing, or `= true`      -> **enabled** (default-on)
///
/// Rung 4 is the single default-on consent decision in the product, and it is
/// intentional: an operator needs to see panics to fix them.
///
/// A PARSE ERROR on `config.toml` resolves to ENABLED, unlike the product-telemetry
/// chain which treats it as disabled. A corrupt file must not silently stop crash
/// diagnostics.
///
/// `key_present` is the runtime view of "is there a PostHog key to send to" — callers
/// pass `telemetry::network::key_is_present()`.
pub fn resolve_crash(config_path: &Path, key_present: bool) -> CrashResolved {
    if is_falsy_env("OPENLATCH_CRASH_REPORTING") {
        return CrashResolved {
            state: ConsentState::Disabled,
            decided_by: CrashDecidedBy::CrashReportingEnv,
        };
    }
    if !key_present {
        return CrashResolved {
            state: ConsentState::Disabled,
            decided_by: CrashDecidedBy::NoProjectKey,
        };
    }
    match super::config::read_crashreport_section(config_path) {
        Ok(Some(section)) => CrashResolved {
            state: if section.enabled {
                ConsentState::Enabled
            } else {
                ConsentState::Disabled
            },
            decided_by: CrashDecidedBy::ConfigFile,
        },
        Ok(None) | Err(_) => CrashResolved {
            state: ConsentState::Enabled,
            decided_by: CrashDecidedBy::DefaultEnabled,
        },
    }
}

/// True when the variable is present AND set to a falsy value.
///
/// NOTE THE POLARITY, which is the opposite of the variable this replaces:
/// `SENTRY_DISABLED` was truthy-to-disable, `OPENLATCH_CRASH_REPORTING` is
/// falsy-to-disable. Anything else — including an empty string, and including a
/// `=1` copied across from the old variable — leaves crash reporting ON. That is the
/// hard break, and it is why the release notes have to describe it as a behaviour
/// change rather than a rename.
fn is_falsy_env(name: &str) -> bool {
    std::env::var(name).is_ok_and(|v| {
        matches!(
            v.trim().to_ascii_lowercase().as_str(),
            "0" | "false" | "no" | "off"
        )
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Mutex;
    use tempfile::TempDir;

    // Env vars are process-global; serialize tests that mutate them.
    static ENV_LOCK: Mutex<()> = Mutex::new(());

    fn clear_env() {
        for v in [
            "DO_NOT_TRACK",
            "OPENLATCH_TELEMETRY_DISABLED",
            "CI",
            "GITHUB_ACTIONS",
            "GITLAB_CI",
            "CIRCLECI",
            "JENKINS_URL",
            "BUILDKITE",
            "TF_BUILD",
            "TEAMCITY_VERSION",
            "BITBUCKET_BUILD_NUMBER",
        ] {
            std::env::remove_var(v);
        }
    }

    #[test]
    fn test_do_not_track_hard_overrides_enabled_config() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();
        std::env::set_var("DO_NOT_TRACK", "1");
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("telemetry.json");
        // Even with consent=true written, DO_NOT_TRACK wins (I3).
        super::super::config::write_consent(&path, true).unwrap();

        let r = resolve(&path);

        assert_eq!(r.state, ConsentState::Disabled);
        assert_eq!(r.decided_by, DecidedBy::DoNotTrackEnv);
        clear_env();
    }

    #[test]
    fn test_openlatch_disabled_env_wins_over_config() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();
        std::env::set_var("OPENLATCH_TELEMETRY_DISABLED", "1");
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("telemetry.json");
        super::super::config::write_consent(&path, true).unwrap();

        let r = resolve(&path);

        assert_eq!(r.state, ConsentState::Disabled);
        assert_eq!(r.decided_by, DecidedBy::OpenlatchDisabledEnv);
        clear_env();
    }

    #[test]
    fn test_ci_environment_disables_even_when_enabled() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();
        std::env::set_var("GITHUB_ACTIONS", "true");
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("telemetry.json");
        super::super::config::write_consent(&path, true).unwrap();

        let r = resolve(&path);

        assert_eq!(r.state, ConsentState::Disabled);
        assert_eq!(r.decided_by, DecidedBy::CiEnvironment);
        clear_env();
    }

    #[test]
    fn test_missing_file_defaults_to_disabled_unconsented() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("telemetry.json");

        let r = resolve(&path);

        assert_eq!(r.state, ConsentState::Disabled);
        assert_eq!(r.decided_by, DecidedBy::DefaultUnconsented);
    }

    #[test]
    fn test_enabled_config_with_no_env_overrides_is_enabled() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("telemetry.json");
        super::super::config::write_consent(&path, true).unwrap();

        let r = resolve(&path);

        assert_eq!(r.state, ConsentState::Enabled);
        assert_eq!(r.decided_by, DecidedBy::ConfigFile);
    }

    #[test]
    fn test_falsy_env_values_do_not_disable() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();
        std::env::set_var("DO_NOT_TRACK", "0");
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("telemetry.json");
        super::super::config::write_consent(&path, true).unwrap();

        let r = resolve(&path);

        // "0" is falsy — DO_NOT_TRACK does not fire.
        assert_eq!(r.state, ConsentState::Enabled);
        assert_eq!(r.decided_by, DecidedBy::ConfigFile);
        clear_env();
    }

    // -----------------------------------------------------------------------
    // Crash reporting. Every case from the module this replaced has a
    // counterpart here, renamed rungs included, plus the two the rename added:
    // the hard break and the independence of the two gates.
    // -----------------------------------------------------------------------

    fn clear_crash_env() {
        std::env::remove_var("OPENLATCH_CRASH_REPORTING");
        std::env::remove_var("SENTRY_DISABLED");
    }

    #[test]
    fn crash_env_falsy_disables() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_crash_env();
        let tmp = TempDir::new().unwrap();
        for value in ["0", "false", "no", "off", "FALSE", "Off", " 0 "] {
            std::env::set_var("OPENLATCH_CRASH_REPORTING", value);
            let r = resolve_crash(&tmp.path().join("config.toml"), true);
            assert_eq!(r.state, ConsentState::Disabled, "value: {value:?}");
            assert_eq!(r.decided_by, CrashDecidedBy::CrashReportingEnv);
        }
        clear_crash_env();
    }

    /// The polarity is the opposite of the variable this replaced. `=1` is not a
    /// spelling of "disabled" any more — it leaves reporting on.
    #[test]
    fn crash_env_truthy_leaves_reporting_on() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_crash_env();
        let tmp = TempDir::new().unwrap();
        for value in ["1", "true", "yes", ""] {
            std::env::set_var("OPENLATCH_CRASH_REPORTING", value);
            let r = resolve_crash(&tmp.path().join("config.toml"), true);
            assert_eq!(r.state, ConsentState::Enabled, "value: {value:?}");
        }
        clear_crash_env();
    }

    /// THE HARD BREAK, pinned so nobody reinstates an alias by accident. A user who
    /// had opted out with the old variable starts sending again — that is the
    /// accepted cost, and it is why the release notes call it a behaviour change.
    ///
    /// THIS TEST IS THE ONE PLACE THE OLD VARIABLE NAME DELIBERATELY SURVIVES.
    /// The removal is otherwise complete, and the repo-wide absence grep excludes
    /// this file for exactly this reason: a test that the old name does nothing
    /// cannot be written without the old name. Do not "finish the cleanup" by
    /// deleting it — deleting it is how an alias gets reinstated unnoticed.
    #[test]
    fn sentry_disabled_has_no_effect() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_crash_env();
        std::env::set_var("SENTRY_DISABLED", "1");
        let tmp = TempDir::new().unwrap();
        let r = resolve_crash(&tmp.path().join("config.toml"), true);
        assert_eq!(r.state, ConsentState::Enabled);
        assert_eq!(r.decided_by, CrashDecidedBy::DefaultEnabled);
        clear_crash_env();
    }

    #[test]
    fn crash_disabled_without_a_project_key() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_crash_env();
        let tmp = TempDir::new().unwrap();
        let r = resolve_crash(&tmp.path().join("config.toml"), false);
        assert_eq!(r.state, ConsentState::Disabled);
        assert_eq!(r.decided_by, CrashDecidedBy::NoProjectKey);
    }

    #[test]
    fn crash_config_false_disables() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_crash_env();
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("config.toml");
        std::fs::write(
            &path,
            "[crashreport]
enabled = false
",
        )
        .unwrap();
        let r = resolve_crash(&path, true);
        assert_eq!(r.state, ConsentState::Disabled);
        assert_eq!(r.decided_by, CrashDecidedBy::ConfigFile);
    }

    /// `ConfigFile` is reported EITHER WAY, which is what lets `doctor` print
    /// "on (config.toml)" rather than collapsing it into "on (default)".
    #[test]
    fn crash_config_true_reports_config_file() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_crash_env();
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("config.toml");
        std::fs::write(
            &path,
            "[crashreport]
enabled = true
",
        )
        .unwrap();
        let r = resolve_crash(&path, true);
        assert_eq!(r.state, ConsentState::Enabled);
        assert_eq!(r.decided_by, CrashDecidedBy::ConfigFile);
    }

    #[test]
    fn crash_enabled_by_default_when_the_section_is_absent() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_crash_env();
        let tmp = TempDir::new().unwrap();
        let r = resolve_crash(&tmp.path().join("config.toml"), true);
        assert_eq!(r.state, ConsentState::Enabled);
        assert_eq!(r.decided_by, CrashDecidedBy::DefaultEnabled);
    }

    /// The deliberate asymmetry with product telemetry: a corrupt file must not
    /// silently stop crash diagnostics.
    #[test]
    fn crash_enabled_when_the_config_is_corrupt() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_crash_env();
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("config.toml");
        std::fs::write(
            &path,
            b"[crashreport
enabled = ",
        )
        .unwrap();
        let r = resolve_crash(&path, true);
        assert_eq!(r.state, ConsentState::Enabled);
        assert_eq!(r.decided_by, CrashDecidedBy::DefaultEnabled);
    }

    /// THE INDEPENDENCE CRITERION. Four combinations, each asserting BOTH resolvers:
    /// neither gate may move the other. This is an acceptance criterion, not a review
    /// comment — folding the two chains would be a one-line change and a privacy
    /// regression.
    #[test]
    fn the_two_gates_are_independent() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();
        clear_crash_env();
        let tmp = TempDir::new().unwrap();
        let telemetry_path = tmp.path().join("telemetry.json");
        let config_path = tmp.path().join("config.toml");

        for (telemetry_on, crash_on) in [(true, true), (true, false), (false, true), (false, false)]
        {
            super::super::config::write_consent(&telemetry_path, telemetry_on).unwrap();
            std::fs::write(
                &config_path,
                format!(
                    "[crashreport]
enabled = {crash_on}
"
                ),
            )
            .unwrap();

            let telemetry = resolve(&telemetry_path);
            let crash = resolve_crash(&config_path, true);

            assert_eq!(
                telemetry.enabled(),
                telemetry_on,
                "product telemetry moved with crash={crash_on}"
            );
            assert_eq!(
                crash.enabled(),
                crash_on,
                "crash reporting moved with telemetry={telemetry_on}"
            );
        }
        clear_env();
        clear_crash_env();
    }

    /// The DESIGNED ASYMMETRY, which the four-combination test above cannot see because
    /// it only varies the two config files. These are the rungs that would cross over if
    /// someone folded `is_truthy_env` and `is_falsy_env` together, or reused one chain's
    /// early returns in the other.
    #[test]
    fn neither_gate_env_rung_reaches_the_other() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();
        clear_crash_env();
        let tmp = TempDir::new().unwrap();
        let telemetry_path = tmp.path().join("telemetry.json");
        let config_path = tmp.path().join("config.toml");
        super::super::config::write_consent(&telemetry_path, true).unwrap();

        // DO_NOT_TRACK is a product-analytics opt-out. Crash reports are diagnostic and
        // are deliberately NOT covered by it.
        std::env::set_var("DO_NOT_TRACK", "1");
        assert!(!resolve(&telemetry_path).enabled());
        assert!(
            resolve_crash(&config_path, true).enabled(),
            "DO_NOT_TRACK must not silence crash reports"
        );
        clear_env();

        // CI disables analytics; CI panics are exactly the bugs worth catching.
        std::env::set_var("CI", "true");
        assert!(!resolve(&telemetry_path).enabled());
        assert!(
            resolve_crash(&config_path, true).enabled(),
            "a CI run must still report panics"
        );
        clear_env();

        // And the reverse: silencing crash reports leaves analytics alone.
        std::env::set_var("OPENLATCH_CRASH_REPORTING", "0");
        assert!(!resolve_crash(&config_path, true).enabled());
        assert!(
            resolve(&telemetry_path).enabled(),
            "the crash opt-out must not disable product telemetry"
        );
        clear_crash_env();
        clear_env();
    }

    #[test]
    fn test_corrupt_config_file_resolves_disabled() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("telemetry.json");
        std::fs::write(&path, b"{ not json").unwrap();

        let r = resolve(&path);

        assert_eq!(r.state, ConsentState::Disabled);
        assert_eq!(r.decided_by, DecidedBy::ConfigFile);
    }
}