collet 0.1.0

Relentless agentic coding orchestrator with zero-drop agent loops
Documentation
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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
//! Lightweight telemetry: anonymous usage analytics + crash/error reporting.
//!
//! - **Analytics**: fire-and-forget anonymous events (session start, feature usage)
//! - **Error reporting**: Sentry-compatible error envelopes + crash file for panics
//!
//! All telemetry is:
//! - Opt-out via `[telemetry] enabled = false` or `COLLET_TELEMETRY=0`
//! - Non-blocking (tokio::spawn, 5s timeout)
//! - Anonymous (machine_id is a random UUID, no PII)
//! - Remote kill-switch enabled (check on init + session start)
//!
//! No data is sent until real endpoint URLs are configured.

use serde_json::json;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, OnceLock};

// ---------------------------------------------------------------------------
// Endpoints — defaults are the official project keys (write-only, safe to
// embed in open-source). Contributors can override via env vars at build time
// so their local test events don't pollute the production dashboard.
// ---------------------------------------------------------------------------

/// PostHog capture endpoint.
const POSTHOG_HOST: &str = "https://us.i.posthog.com";

/// PostHog project API key (write-only — can send events, cannot read data).
/// Override at build time: `POSTHOG_API_KEY=phc_xxx cargo build --release`
const POSTHOG_API_KEY: &str = match option_env!("POSTHOG_API_KEY") {
    Some(v) => v,
    None => "phc_Xpd1b1yslA6CCT4lTgYc14Chnj03jPDpfqglXerbHWt",
};

/// Sentry DSN for error/crash reporting (write-only).
/// Override at build time: `SENTRY_DSN=https://...@....ingest.sentry.io/... cargo build --release`
const SENTRY_DSN: &str = match option_env!("SENTRY_DSN") {
    Some(v) => v,
    None => "https://498029f4e2283ddb0522df1835527d82@o238879.ingest.us.sentry.io/4511091812663296",
};

/// Kill switch endpoint — returns JSON `{"disabled": true/false}`.
const KILL_SWITCH_URL: &str = "https://telemetry.collet.dev/v1/kill-switch";

/// Kill switch cache file name (stored in collet_home).
const KILL_SWITCH_CACHE_FILE: &str = "telemetry_kill_switch.json";

/// How long to cache kill switch status before re-checking (24 hours).
const KILL_SWITCH_CACHE_TTL_SECS: u64 = 24 * 60 * 60;

// ---------------------------------------------------------------------------
// Global client (for panic hook access)
// ---------------------------------------------------------------------------

static GLOBAL_CLIENT: OnceLock<TelemetryClient> = OnceLock::new();

/// Global kill switch flag — set by remote check, respected by all events.
static KILL_SWITCH_ACTIVE: AtomicBool = AtomicBool::new(false);

// ---------------------------------------------------------------------------
// Client
// ---------------------------------------------------------------------------

/// Lightweight telemetry client. Cheaply cloneable (Arc-wrapped).
#[derive(Clone)]
pub struct TelemetryClient {
    inner: Arc<Inner>,
}

struct Inner {
    enabled: bool,
    error_reporting: bool,
    analytics: bool,
    http: reqwest::Client,
    machine_id: String,
    version: String,
    collet_home: PathBuf,
}

// ---------------------------------------------------------------------------
// Initialization
// ---------------------------------------------------------------------------

/// Initialize telemetry from resolved config.
///
/// - Loads or creates a persistent `machine_id` (random UUID).
/// - Installs a panic hook that writes crash reports to disk.
/// - Uploads any pending crash report from a previous run.
/// - Checks remote kill switch (async, non-blocking).
pub fn init(config: &crate::config::Config) -> TelemetryClient {
    let machine_id = load_or_create_machine_id(&config.collet_home);

    let http = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(5))
        .build()
        .unwrap_or_default();

    // Check kill switch (cached or fresh)
    let kill_switch_active = check_kill_switch_cached(&config.collet_home, &http);
    KILL_SWITCH_ACTIVE.store(kill_switch_active, Ordering::Relaxed);

    let client = TelemetryClient {
        inner: Arc::new(Inner {
            enabled: config.telemetry_enabled,
            error_reporting: config.telemetry_error_reporting,
            analytics: config.telemetry_analytics,
            http,
            machine_id,
            version: env!("CARGO_PKG_VERSION").to_string(),
            collet_home: config.collet_home.clone(),
        }),
    };

    let _ = GLOBAL_CLIENT.set(client.clone());

    // Install panic hook (wraps any previously installed hook).
    let prev = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        capture_panic_global(info);
        prev(info);
    }));

    // Upload crash report left by a previous panic (if any).
    upload_pending_crash(&client);

    client
}

// ---------------------------------------------------------------------------
// Analytics events
// ---------------------------------------------------------------------------

impl TelemetryClient {
    /// Fire-and-forget anonymous analytics event.
    ///
    /// `properties` is an arbitrary JSON value attached to the event.
    pub fn track_event(&self, name: &str, properties: serde_json::Value) {
        // In debug builds, log the event payload for development-time verification
        // instead of silently dropping or sending to production analytics.
        if cfg!(debug_assertions) {
            tracing::debug!(
                target: "telemetry",
                event = %name,
                properties = %properties,
                "Telemetry event (debug build, not sent)"
            );
            return;
        }
        if !self.inner.enabled || !self.inner.analytics {
            return;
        }
        if KILL_SWITCH_ACTIVE.load(Ordering::Relaxed) {
            return;
        }
        let client = self.clone();
        let name = name.to_string();
        tokio::spawn(async move {
            let url = format!("{}/capture/", POSTHOG_HOST);
            let payload = json!({
                "api_key": POSTHOG_API_KEY,
                "event": name,
                "distinct_id": client.inner.machine_id,
                "properties": {
                    "$lib": "collet",
                    "$lib_version": client.inner.version,
                },
                "timestamp": chrono::Utc::now().to_rfc3339(),
            });
            // Merge caller properties into the payload
            let mut payload = payload;
            if let (Some(base), Some(extra)) = (
                payload["properties"].as_object().cloned(),
                properties.as_object(),
            ) {
                let mut merged = base;
                for (k, v) in extra {
                    merged.insert(k.clone(), v.clone());
                }
                payload["properties"] = json!(merged);
            }
            let _ = client.inner.http.post(&url).json(&payload).send().await;
        });
    }

    /// Capture a non-fatal error with context.
    pub fn capture_error(&self, error: &str, context: serde_json::Value) {
        if cfg!(debug_assertions) {
            tracing::debug!(
                target: "telemetry",
                error = %error,
                "Telemetry error (debug build, not sent)"
            );
            return;
        }
        if !self.inner.enabled || !self.inner.error_reporting {
            return;
        }
        if KILL_SWITCH_ACTIVE.load(Ordering::Relaxed) {
            return;
        }
        let Some(url) = sentry_store_url() else {
            return;
        };
        let client = self.clone();
        let error = error.to_string();
        tokio::spawn(async move {
            let payload = build_error_payload(
                &client.inner.machine_id,
                &client.inner.version,
                "error",
                "Error",
                &error,
                None,
                context,
            );
            let _ = client.inner.http.post(&url).json(&payload).send().await;
        });
    }

    /// Write a crash report to disk (called from panic hook — no async).
    fn capture_panic(&self, info: &std::panic::PanicHookInfo<'_>) {
        if !self.inner.enabled || !self.inner.error_reporting {
            return;
        }

        let message = match info.payload().downcast_ref::<&str>() {
            Some(s) => s.to_string(),
            None => match info.payload().downcast_ref::<String>() {
                Some(s) => s.clone(),
                None => "unknown panic".to_string(),
            },
        };

        let location = info
            .location()
            .map(|l| format!("{}:{}:{}", l.file(), l.line(), l.column()));

        let payload = build_error_payload(
            &self.inner.machine_id,
            &self.inner.version,
            "fatal",
            "Panic",
            &message,
            location,
            json!({}),
        );

        // Write to disk — uploading happens on next startup.
        let logs_dir = self.inner.collet_home.join("logs");
        let _ = std::fs::create_dir_all(&logs_dir);
        let date = chrono::Utc::now().format("%Y-%m-%d");
        let crash_path = logs_dir.join(format!("crash_{date}.jsonl"));
        if let Ok(mut file) = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&crash_path)
        {
            let line = serde_json::to_string(&payload).unwrap_or_default();
            let _ = writeln!(file, "{line}");
        }
    }

    /// Whether telemetry is enabled at all.
    pub fn is_enabled(&self) -> bool {
        self.inner.enabled
    }
}

// ---------------------------------------------------------------------------
// Global accessor — call from anywhere without threading the client
// ---------------------------------------------------------------------------

/// Get a reference to the global telemetry client (set by [`init`]).
pub fn global() -> Option<&'static TelemetryClient> {
    GLOBAL_CLIENT.get()
}

/// Convenience: fire-and-forget analytics event via global client.
///
/// No-op if telemetry is not initialized, disabled, or kill-switched.
pub fn track(name: &str, properties: serde_json::Value) {
    if is_kill_switch_active() {
        return;
    }
    if let Some(client) = global()
        && client.is_enabled()
    {
        client.track_event(name, properties);
    }
}

/// Convenience: capture a non-fatal error via global client.
pub fn error(message: &str, context: serde_json::Value) {
    if let Some(client) = global() {
        client.capture_error(message, context);
    }
}

// ---------------------------------------------------------------------------
// Panic hook (global access)
// ---------------------------------------------------------------------------

/// Called from the panic hook installed in [`init`].
fn capture_panic_global(info: &std::panic::PanicHookInfo<'_>) {
    if let Some(client) = GLOBAL_CLIENT.get() {
        client.capture_panic(info);
    }
}

// ---------------------------------------------------------------------------
// Crash report upload
// ---------------------------------------------------------------------------

/// Upload crash reports left by previous panics, then delete the files.
fn upload_pending_crash(client: &TelemetryClient) {
    let logs_dir = client.inner.collet_home.join("logs");
    let Ok(entries) = std::fs::read_dir(&logs_dir) else {
        return;
    };

    let Some(url) = sentry_store_url() else {
        return;
    };

    for entry in entries.flatten() {
        let path = entry.path();
        let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
        if !name.starts_with("crash_") || !name.ends_with(".jsonl") {
            continue;
        }

        let Ok(data) = std::fs::read_to_string(&path) else {
            let _ = std::fs::remove_file(&path);
            continue;
        };

        let payloads: Vec<serde_json::Value> = data
            .lines()
            .filter_map(|l| serde_json::from_str(l).ok())
            .collect();

        if payloads.is_empty() {
            let _ = std::fs::remove_file(&path);
            continue;
        }

        let c = client.clone();
        let url = url.clone();
        tokio::spawn(async move {
            for payload in payloads {
                let _ = c.inner.http.post(&url).json(&payload).send().await;
            }
        });

        let _ = std::fs::remove_file(&path);
    }
}

// ---------------------------------------------------------------------------
// Kill Switch
// ---------------------------------------------------------------------------

/// Check kill switch status (cached or fresh from remote).
///
/// Returns `true` if telemetry should be disabled.
fn check_kill_switch_cached(collet_home: &Path, _http: &reqwest::Client) -> bool {
    // Try to read cached status first
    let cache_path = collet_home.join(KILL_SWITCH_CACHE_FILE);
    if let Ok(data) = std::fs::read_to_string(&cache_path)
        && let Ok(cached) = serde_json::from_str::<KillSwitchCache>(&data)
    {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        // Use cached value if not expired
        if now.saturating_sub(cached.checked_at) < KILL_SWITCH_CACHE_TTL_SECS {
            return cached.disabled;
        }
    }

    // If kill switch URL is the default placeholder, skip remote check
    if KILL_SWITCH_URL.contains("telemetry.collet.dev") {
        return false;
    }

    // For sync init, we can't make async requests.
    // Return false (enabled) and let refresh_kill_switch() handle fresh check.
    // The cache will be populated on first async refresh.
    false
}

/// Kill switch cache structure.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct KillSwitchCache {
    /// Whether telemetry is disabled.
    disabled: bool,
    /// Unix timestamp when this was checked.
    checked_at: u64,
}

/// Force a fresh kill switch check (called at app startup).
pub fn refresh_kill_switch() {
    let Some(client) = GLOBAL_CLIENT.get() else {
        return;
    };
    if !client.inner.enabled {
        return;
    }

    let collet_home = client.inner.collet_home.clone();
    let http = client.inner.http.clone();

    // Spawn async check
    tokio::spawn(async move {
        let cache_path = collet_home.join(KILL_SWITCH_CACHE_FILE);

        // Fetch fresh status
        let disabled = match http
            .get(KILL_SWITCH_URL)
            .timeout(std::time::Duration::from_secs(2))
            .send()
            .await
        {
            Ok(response) => {
                if let Ok(json) = response.json::<serde_json::Value>().await {
                    json.get("disabled")
                        .and_then(|v| v.as_bool())
                        .unwrap_or(false)
                } else {
                    // If response parsing fails, keep current state
                    return;
                }
            }
            Err(_) => {
                // On error, keep current state (fail open)
                return;
            }
        };

        // Update global flag
        KILL_SWITCH_ACTIVE.store(disabled, Ordering::Relaxed);

        // Update cache
        let cache = KillSwitchCache {
            disabled,
            checked_at: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
        };
        let _ = std::fs::create_dir_all(&collet_home);
        let _ = std::fs::write(
            &cache_path,
            serde_json::to_string(&cache).unwrap_or_default(),
        );
    });
}

/// Check if kill switch is currently active (checked by `track` before every event).
pub fn is_kill_switch_active() -> bool {
    KILL_SWITCH_ACTIVE.load(Ordering::Relaxed)
}

/// Return a human-readable telemetry status summary (for `/telemetry` command).
pub fn status_text() -> String {
    let Some(client) = GLOBAL_CLIENT.get() else {
        return "Telemetry: not initialized".to_string();
    };
    let i = &client.inner;
    let kill = KILL_SWITCH_ACTIVE.load(Ordering::Relaxed);
    let debug_build = cfg!(debug_assertions);
    let placeholder = POSTHOG_API_KEY.is_empty();

    let mut lines = Vec::with_capacity(16);
    lines.push("── Telemetry Status ──".to_string());
    lines.push(String::new());

    // Master switch
    let master = if !i.enabled {
        "❌ Disabled"
    } else if kill {
        "⛔ Disabled (remote kill switch)"
    } else {
        "✅ Enabled"
    };
    lines.push(format!("Master:          {master}"));
    lines.push(format!(
        "Analytics:       {}",
        if i.analytics { "✅ On" } else { "❌ Off" }
    ));
    lines.push(format!(
        "Error Reporting: {}",
        if i.error_reporting {
            "✅ On"
        } else {
            "❌ Off"
        }
    ));
    lines.push(String::new());

    // Data sending
    if debug_build {
        lines.push("Data Sending:    🔇 Inactive (debug build)".to_string());
        lines.push("                 No data leaves your machine.".to_string());
    } else if placeholder {
        lines.push("Data Sending:    🔇 Inactive (no API key configured)".to_string());
        lines.push("                 No data leaves your machine.".to_string());
    } else {
        lines.push("Data Sending:    📡 Active".to_string());
    }
    lines.push(String::new());

    // Machine ID
    lines.push(format!("Machine ID:      {}", i.machine_id));
    lines.push(format!("Version:         {}", i.version));
    lines.push(String::new());

    // Crash report
    let crash_path = i.collet_home.join("logs").join("crash_report.json");
    if crash_path.exists() {
        lines.push("Pending Crash:   ⚠️  crash_report.json found".to_string());
    } else {
        lines.push("Pending Crash:   None".to_string());
    }
    lines.push(String::new());

    // Collected events
    lines.push("── Collected Events ──".to_string());
    lines.push("session_start    model, mode, version, os, arch".to_string());
    lines.push("session_end      model, mode, outcome, iterations, duration".to_string());
    lines.push("feature_used     feature name (MCP server name, skill, subagent)".to_string());
    lines.push("command_used     slash command name".to_string());
    lines.push("model_switch     from/to model names".to_string());
    lines.push("compaction       pass, tokens before/after".to_string());
    lines.push("tool_error       tool name, model (no code content)".to_string());
    lines.push(String::new());

    // Not collected
    lines.push("── NOT Collected ──".to_string());
    lines.push("• Source code, file paths, prompts, API keys".to_string());
    lines.push("• Personal information (username, IP, email)".to_string());
    lines.push(String::new());

    // How to disable
    lines.push("── Disable ──".to_string());
    lines.push("export COLLET_TELEMETRY=0".to_string());
    lines.push("# or in config.toml:".to_string());
    lines.push("[telemetry]".to_string());
    lines.push("enabled = false".to_string());

    lines.join("\n")
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Build a Sentry-compatible error/crash payload.
fn build_error_payload(
    machine_id: &str,
    version: &str,
    level: &str,
    error_type: &str,
    message: &str,
    location: Option<String>,
    contexts: serde_json::Value,
) -> serde_json::Value {
    let event_id = uuid::Uuid::new_v4().to_string().replace('-', "");
    let mut exception = json!({
        "type": error_type,
        "value": message,
    });
    if let Some(loc) = location {
        exception["stacktrace"] = json!({"frames": [{"function": loc}]});
    }
    json!({
        "event_id": event_id,
        "timestamp": chrono::Utc::now().to_rfc3339(),
        "platform": "rust",
        "release": format!("collet@{version}"),
        "server_name": machine_id,
        "level": level,
        "exception": { "values": [exception] },
        "contexts": contexts,
    })
}

/// Load machine_id from `~/.collet/machine_id`, or create one.
fn load_or_create_machine_id(collet_home: &Path) -> String {
    let path = collet_home.join("machine_id");
    if let Ok(id) = std::fs::read_to_string(&path) {
        let id = id.trim().to_string();
        if !id.is_empty() {
            return id;
        }
    }
    let id = uuid::Uuid::new_v4().to_string();
    let _ = std::fs::create_dir_all(collet_home);
    let _ = std::fs::write(&path, &id);
    id
}

/// Parse `SENTRY_DSN` into a store API URL.
///
/// DSN format: `https://<key>@<host>/<project_id>`
/// Store URL:  `https://<host>/api/<project_id>/store/?sentry_key=<key>`
///
/// Returns `None` if the DSN is empty or malformed.
fn sentry_store_url() -> Option<String> {
    if SENTRY_DSN.is_empty() {
        return None;
    }
    // Strip scheme
    let without_scheme = SENTRY_DSN.strip_prefix("https://")?;
    // Split key@host/project_id
    let (key, rest) = without_scheme.split_once('@')?;
    let (host, project_id) = rest.rsplit_once('/')?;
    if key.is_empty() || host.is_empty() || project_id.is_empty() {
        return None;
    }
    Some(format!(
        "https://{host}/api/{project_id}/store/?sentry_key={key}"
    ))
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_load_or_create_machine_id() {
        let dir = tempfile::tempdir().unwrap();
        let id1 = load_or_create_machine_id(dir.path());
        assert!(!id1.is_empty());
        // Second call returns same ID.
        let id2 = load_or_create_machine_id(dir.path());
        assert_eq!(id1, id2);
    }

    #[test]
    fn test_build_error_payload() {
        let payload =
            build_error_payload("mid", "1.0.0", "error", "TestErr", "boom", None, json!({}));
        assert_eq!(payload["level"], "error");
        assert_eq!(payload["exception"]["values"][0]["value"], "boom");
    }

    #[test]
    fn test_sentry_store_url_parsing() {
        let url = sentry_store_url();
        // Default DSN should parse successfully
        assert!(url.is_some(), "default SENTRY_DSN should parse");
        let url = url.unwrap();
        assert!(url.contains("/api/"));
        assert!(url.contains("/store/"));
        assert!(url.contains("sentry_key="));
    }

    #[test]
    fn test_posthog_api_key_present() {
        assert!(
            !POSTHOG_API_KEY.is_empty(),
            "POSTHOG_API_KEY should have a default"
        );
        assert!(POSTHOG_API_KEY.starts_with("phc_"));
    }

    #[test]
    fn test_build_error_payload_with_location() {
        let payload = build_error_payload(
            "machine123",
            "0.1.0",
            "fatal",
            "Panic",
            "index out of bounds",
            Some("src/main.rs:42:10".to_string()),
            json!({"thread": "main"}),
        );
        assert_eq!(payload["level"], "fatal");
        assert_eq!(payload["exception"]["values"][0]["type"], "Panic");
        assert_eq!(
            payload["exception"]["values"][0]["value"],
            "index out of bounds"
        );
        assert!(payload["exception"]["values"][0]["stacktrace"].is_object());
        assert_eq!(payload["contexts"]["thread"], "main");
        assert_eq!(payload["server_name"], "machine123");
        assert_eq!(payload["platform"], "rust");
    }

    #[test]
    fn test_machine_id_is_valid_uuid() {
        let dir = tempfile::tempdir().unwrap();
        let id = load_or_create_machine_id(dir.path());
        // Should be a valid UUID format
        assert!(
            uuid::Uuid::parse_str(&id).is_ok(),
            "machine_id should be valid UUID"
        );
    }

    #[test]
    fn test_disabled_client_skips_events() {
        let dir = tempfile::tempdir().unwrap();
        let client = TelemetryClient {
            inner: Arc::new(Inner {
                enabled: false,
                error_reporting: true,
                analytics: true,
                http: reqwest::Client::new(),
                machine_id: "test-id".to_string(),
                version: "0.1.0".to_string(),
                collet_home: dir.path().to_path_buf(),
            }),
        };

        // These should be no-ops (not panic, not send)
        client.track_event("test_event", json!({"foo": "bar"}));
        client.capture_error("test error", json!({}));

        // Verify client state
        assert!(!client.is_enabled());
    }

    #[test]
    fn test_analytics_disabled_skips_events() {
        let dir = tempfile::tempdir().unwrap();
        let client = TelemetryClient {
            inner: Arc::new(Inner {
                enabled: true,
                error_reporting: true,
                analytics: false, // analytics off
                http: reqwest::Client::new(),
                machine_id: "test-id".to_string(),
                version: "0.1.0".to_string(),
                collet_home: dir.path().to_path_buf(),
            }),
        };

        // track_event should be no-op when analytics=false
        client.track_event("test_event", json!({}));
        assert!(client.inner.enabled);
        assert!(!client.inner.analytics);
    }

    #[test]
    fn test_error_reporting_disabled_skips_errors() {
        let dir = tempfile::tempdir().unwrap();
        let client = TelemetryClient {
            inner: Arc::new(Inner {
                enabled: true,
                error_reporting: false, // error reporting off
                analytics: true,
                http: reqwest::Client::new(),
                machine_id: "test-id".to_string(),
                version: "0.1.0".to_string(),
                collet_home: dir.path().to_path_buf(),
            }),
        };

        // capture_error should be no-op when error_reporting=false
        client.capture_error("test error", json!({}));
        assert!(client.inner.enabled);
        assert!(!client.inner.error_reporting);
    }

    #[test]
    fn test_event_payload_structure() {
        // Verify the expected structure of analytics events
        let expected_keys = [
            "event",
            "distinct_id",
            "properties",
            "timestamp",
            "app_version",
        ];
        let sample = json!({
            "event": "session_start",
            "distinct_id": "test-uuid",
            "properties": {"mode": "agent", "model": "gpt-4"},
            "timestamp": "2024-01-01T00:00:00Z",
            "app_version": "0.1.0",
        });
        for key in expected_keys {
            assert!(sample.get(key).is_some(), "Missing key: {}", key);
        }
    }

    #[test]
    fn test_status_text_contains_sections() {
        // status_text() without init should return "not initialized"
        // (unless a previous test set the global — tests run in same process)
        let text = status_text();
        // At minimum it should contain some recognizable section header
        assert!(
            text.contains("Telemetry") || text.contains("not initialized"),
            "status_text should contain Telemetry or not-initialized msg"
        );
    }

    #[test]
    fn test_session_end_payload_outcomes() {
        // Test all outcome types for session_end event
        let outcomes = ["success", "error", "guard_stop", "cancelled"];
        for outcome in outcomes {
            let payload = json!({
                "event": "session_end",
                "distinct_id": "test-id",
                "properties": {
                    "outcome": outcome,
                    "model": "test-model",
                    "mode": "agent",
                    "iter": 5,
                    "secs": 60,
                },
            });
            assert_eq!(payload["properties"]["outcome"], outcome);
        }
    }
}