openlatch-client 0.1.6

The open-source security layer for AI agents — client forwarder
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
/// `openlatch init` command handler.
///
/// Runs the full initialization flow:
/// 1. Detect AI agent (D-01)
/// 2. Regenerate auth token (D-02)
/// 3. Write hooks to settings.json (D-03, D-04)
///    3.5. Auth flow — browser or env var validation (D-06, D-07, D-09)
/// 4. Start the daemon (D-05)
///    4.5. Show cloud sync status (D-08)
///
/// In JSON mode, emits a single JSON object at the end instead of step-by-step output.
use crate::auth::{retrieve_credential, FileCredentialStore, KeyringCredentialStore};
use crate::cli::commands::lifecycle;
use crate::cli::output::{OutputConfig, OutputFormat};
use crate::cli::AuthLoginArgs;
use crate::cli::InitArgs;
use crate::config;
use crate::error::{OlError, ERR_INVALID_CONFIG};
use crate::hooks;
use crate::hooks::DetectedAgent;
use crate::telemetry::{self, config as telemetry_config, consent_file_path, Event};
use secrecy::ExposeSecret;
use std::io::{BufRead, IsTerminal, Write};

/// Run the `openlatch init` command.
///
/// Detects the AI agent, regenerates the auth token, writes hooks, and starts the daemon.
/// Prints step-by-step checkmark output in human mode (D-01 through D-05).
/// In JSON mode, emits a single JSON object.
///
/// # Errors
///
/// Returns an error at the first failing step. No rollback is performed (D-03).
pub fn run_init(args: &InitArgs, output: &OutputConfig) -> Result<(), OlError> {
    crate::cli::header::print(output, &["init"]);

    // Ensure the openlatch directory exists
    let ol_dir = config::openlatch_dir();
    std::fs::create_dir_all(&ol_dir).map_err(|e| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!(
                "Cannot create openlatch directory '{}': {e}",
                ol_dir.display()
            ),
        )
        .with_suggestion("Check that you have write permission to your home directory.")
    })?;
    std::fs::create_dir_all(ol_dir.join("logs")).map_err(|e| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!("Cannot create logs directory: {e}"),
        )
    })?;

    // Step 1: Detect agent (D-01)
    let agent = match hooks::detect_agent() {
        Ok(a) => {
            let label = agent_label(&a);
            output.print_step(&format!("Detected agent: {label}"));
            a
        }
        Err(e) => {
            output.print_error(&e);
            return Err(e);
        }
    };

    // Step 2: Regenerate token (D-02 — always regenerate)
    // Check if token file already existed to display the right message
    let token_path = ol_dir.join("daemon.token");
    let token_existed = token_path.exists();

    // Always regenerate: write a fresh token
    let new_token = config::generate_token();
    std::fs::write(&token_path, &new_token).map_err(|e| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!("Cannot write token file '{}': {e}", token_path.display()),
        )
        .with_suggestion("Check that you have write permission to the openlatch directory.")
    })?;

    // SECURITY: Restrict token file to owner only (mode 0600) on Unix.
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let perms = std::fs::Permissions::from_mode(0o600);
        std::fs::set_permissions(&token_path, perms).map_err(|e| {
            OlError::new(
                ERR_INVALID_CONFIG,
                format!("Cannot set permissions on token file: {e}"),
            )
        })?;
    }

    let token_action = if token_existed {
        "(regenerated existing)"
    } else {
        "(new)"
    };
    output.print_step(&format!("Generated auth token {token_action}"));

    // Step 3: Resolve port + write config (no hooks yet — see Step 7).
    let settings_path = match &agent {
        DetectedAgent::ClaudeCode { settings_path, .. } => settings_path.clone(),
    };

    // Port probing: on first init (no config.toml) or --reconfig, probe 7443-7543
    // for a free port. On normal re-init, use the pinned port from existing config.
    let config_path = config::openlatch_dir().join("config.toml");
    let needs_port_probe = !config_path.exists() || args.reconfig;

    let port = if needs_port_probe {
        if args.reconfig {
            // Stop running daemon before rebinding (if any)
            let _ = lifecycle::run_stop(output);
            // Remove stale port file
            let _ = std::fs::remove_file(config::openlatch_dir().join("daemon.port"));
            // Remove old config so ensure_config writes fresh
            let _ = std::fs::remove_file(&config_path);
        }
        let probed = config::probe_free_port(config::PORT_RANGE_START, config::PORT_RANGE_END)?;
        output.print_substep(&format!("Selected port {probed} (first available)"));
        // Write config.toml with the probed port
        config::ensure_config(probed)?;
        // Write daemon.port file for hook binary discovery
        config::write_port_file(probed)?;
        probed
    } else {
        config::Config::load(None, None, false)?.port
    };

    // D-11: ensure [daemon].agent_id is present before anything reads the
    // config. Without this, re-running `openlatch init` on an install that
    // predates the agent_id field leaves it blank and the daemon silently
    // forwards `agent_id = ""` to cloud on every event.
    config::ensure_agent_id(&config_path)?;

    let cfg = config::Config::load(Some(port), None, false)?;

    // Step 4: Auth flow (D-06, D-07, D-09).
    // Runs BEFORE hook installation so a canceled / failed auth leaves no
    // broken hooks pointing at a half-configured daemon.
    let (auth_success, org_name) = run_auth_for_init(output)?;

    // Step 4.5: Telemetry consent (moved before hooks for foreground mode).
    handle_telemetry_consent(args, output, &ol_dir)?;

    // Step 4.6: Install hooks BEFORE daemon start. This is critical for
    // --foreground mode where run_daemon_foreground blocks forever — hooks
    // must be installed before the daemon starts so the reconciler finds them.
    let hook_result = match hooks::install_hooks(&agent, cfg.port, &new_token) {
        Ok(r) => r,
        Err(e) => {
            output.print_error(&e);
            return Err(e);
        }
    };

    output.print_step(&format!("Hooks written to {}", settings_path.display()));
    for entry in &hook_result.entries {
        let action_label = match entry.action {
            hooks::HookAction::Added => "added",
            hooks::HookAction::Replaced => "replaced",
        };
        output.print_substep(&format!("{} ({})", entry.event_type, action_label));
    }

    // Step 4.7: Install OS-native supervision (launchd / systemd-user / Task Scheduler).
    // Default-on: absence of --no-persistence means install. Skipped when the user
    // explicitly asked for a foreground session, --no-start, or --no-persistence.
    let (supervision_backend_label, supervision_mode_label, supervision_deferred_reason) =
        run_supervision_install_for_init(args, &config_path, output);

    // Step 5: Start daemon (D-05) — skip if --no-start
    let (port, pid) = if args.no_start {
        output.print_step("Skipped daemon start (--no-start)");
        (cfg.port, 0u32)
    } else if args.foreground {
        // Foreground mode: start inline (blocking). We print the step first, then call.
        output.print_step(&format!(
            "Starting daemon on port {} (foreground)",
            cfg.port
        ));
        run_daemon_foreground(cfg.port, &new_token)?;
        (cfg.port, std::process::id())
    } else {
        match lifecycle::spawn_daemon_background(cfg.port, &new_token) {
            Ok(pid) => {
                // Wait up to 5 seconds for /health to return 200
                let _ = wait_for_health(cfg.port, 5);
                output.print_step(&format!("Daemon started on port {} (PID {pid})", cfg.port));
                (cfg.port, pid)
            }
            Err(e) => {
                output.print_error(&e);
                return Err(e);
            }
        }
    };

    // Step 4.5: Show cloud sync status (D-08)
    if auth_success {
        let cloud_msg = if org_name.is_empty() {
            "Cloud sync: enabled".to_string()
        } else {
            format!("Cloud sync: connected (org: {org_name})")
        };
        output.print_step(&cloud_msg);
        if output.format == OutputFormat::Human && !output.quiet {
            eprintln!("  Events will be forwarded automatically");
        }
    }

    // Final line: show where events will appear (D-05, PLAT-02)
    let today = chrono::Local::now().format("%Y-%m-%d");
    let log_path = config::openlatch_dir()
        .join("logs")
        .join(format!("events-{today}.jsonl"));
    if output.format == OutputFormat::Human && !output.quiet {
        eprintln!();
        if args.no_start {
            eprintln!("Setup complete. Run `openlatch start` to launch the daemon.");
        } else {
            eprintln!("Ready. Events will appear in: {}", log_path.display());
        }
    }

    // Telemetry: emit cli_initialized after the install completes successfully.
    let agent_label_str = match &agent {
        DetectedAgent::ClaudeCode { .. } => "claude-code",
    };
    telemetry::capture_global(Event::cli_initialized(
        agent_label_str,
        hook_result.entries.len(),
        !token_existed,
    ));
    telemetry::capture_global(Event::supervision_installed(
        supervision_backend_label,
        supervision_mode_label,
        supervision_deferred_reason.as_deref(),
    ));

    // JSON output mode: emit single JSON object
    if output.format == OutputFormat::Json {
        let hooks_list: Vec<&str> = hook_result
            .entries
            .iter()
            .map(|e| e.event_type.as_str())
            .collect();

        let agent_str = match &agent {
            DetectedAgent::ClaudeCode { .. } => "claude-code",
        };

        let cloud_status = if auth_success {
            "connected"
        } else {
            "not_configured"
        };
        let json = serde_json::json!({
            "status": "ok",
            "agent": agent_str,
            "port": port,
            "pid": pid,
            "hooks": hooks_list,
            "log_path": log_path.to_string_lossy(),
            "token_action": token_action,
            "daemon_started": !args.no_start,
            "cloud_status": cloud_status,
            "org_name": org_name,
            "supervision": {
                "mode": supervision_mode_label,
                "backend": supervision_backend_label,
                "disabled_reason": supervision_deferred_reason,
            },
        });
        output.print_json(&json);
    }

    Ok(())
}

/// Run the auth flow for `openlatch init` (Step 3.5).
///
/// Priority order:
/// 1. `OPENLATCH_API_KEY` env var (D-09) — validate online, fail-open on network error
/// 2. Existing credential in keychain/file — re-validate, re-trigger if invalid (D-07)
/// 3. No credential — run browser auth flow (D-06)
///
/// Returns `(auth_success, org_name)`. On auth failure (401/403), propagates error.
fn run_auth_for_init(output: &OutputConfig) -> Result<(bool, String), OlError> {
    let keyring = KeyringCredentialStore::new();
    let cfg = config::Config::load(None, None, false).ok();
    let agent_id = cfg
        .as_ref()
        .and_then(|c| c.agent_id.clone())
        .unwrap_or_default();
    let file_store =
        FileCredentialStore::new(config::openlatch_dir().join("credentials.enc"), agent_id);

    // WR-03: read api_url from config so staging/custom environments are respected
    let api_url = cfg
        .map(|c| c.cloud.api_url)
        .unwrap_or_else(|| "https://app.openlatch.ai/api".to_string());

    // WR-05: Create a single Tokio runtime here and reuse it for all async validation
    // calls in this function. Previously each code path created its own Runtime::new(),
    // which is harmless today (sync call site) but would panic if run_init is ever called
    // from an async context (e.g. tests or a future TUI).
    //
    // NOTE: run_login (Path 3) creates its own runtime internally. That is safe here
    // because it is called from sync code after this runtime's block_on() has returned —
    // there is no nesting at runtime.
    let rt = tokio::runtime::Runtime::new().map_err(|e| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!("Failed to create async runtime: {e}"),
        )
    })?;

    // Path 1: OPENLATCH_API_KEY env var (D-09)
    if let Ok(val) = std::env::var("OPENLATCH_API_KEY") {
        if !val.is_empty() {
            let (online, org_name, _org_id) =
                rt.block_on(crate::cli::commands::auth::validate_online(&val, &api_url));
            if online {
                let msg = if org_name.is_empty() {
                    "Authenticated via env var".to_string()
                } else {
                    format!("Authenticated via env var (org: {org_name})")
                };
                output.print_step(&msg);
                return Ok((true, org_name));
            }
            // Network error → fail-open (Pitfall 4): proceed with key stored
            output.print_step("Authenticated via env var (cloud offline - validation skipped)");
            return Ok((true, String::new()));
        }
    }

    // Path 2: Check existing credential (D-07)
    if let Ok(existing_key) = retrieve_credential(&keyring, &file_store) {
        let key_str = existing_key.expose_secret().to_string();
        let v = rt.block_on(crate::cli::commands::auth::validate_online_full(
            &key_str, &api_url,
        ));
        if v.online {
            let msg = if v.org_name.is_empty() {
                "Authenticated".to_string()
            } else {
                format!("Authenticated (org: {})", v.org_name)
            };
            output.print_step(&msg);
            return Ok((true, v.org_name));
        }
        if !v.rejected {
            // Cloud unreachable — fail-open, keep existing credential
            output.print_step("Authenticated (cloud offline - using stored credentials)");
            return Ok((true, String::new()));
        }
        // Server rejected the credential (401/403) — re-trigger auth
        output.print_substep("Existing credentials invalid, re-authenticating...");
    }

    // Path 3: Run browser auth flow (D-06)
    // run_login creates its own runtime internally — safe here because it is called
    // from sync code (the rt.block_on() above has already returned).
    let login_args = AuthLoginArgs { no_browser: false };
    crate::cli::commands::auth::run_login(&login_args, output)?;

    // After successful login, retrieve the newly stored credential to get org info
    if let Ok(key) = retrieve_credential(&keyring, &file_store) {
        let key_str = key.expose_secret().to_string();
        let (_, org_name, _) = rt.block_on(crate::cli::commands::auth::validate_online(
            &key_str, &api_url,
        ));
        return Ok((true, org_name));
    }

    Ok((true, String::new()))
}

/// Install the OS supervisor and persist the resulting state into config.toml.
///
/// Returns `(backend_label, mode_label, deferred_reason)` for downstream
/// telemetry and JSON output. All errors are non-fatal — init always
/// continues so users are never locked out of setup by a platform quirk
/// (headless macOS CI, Alpine without systemd, Windows schtasks permissions).
fn run_supervision_install_for_init(
    args: &InitArgs,
    config_path: &std::path::Path,
    output: &OutputConfig,
) -> (&'static str, &'static str, Option<String>) {
    use crate::supervision::{select_supervisor, SupervisionMode, SupervisorKind};

    // Skip cases: foreground is explicitly ephemeral; no_start means the user
    // doesn't want the daemon running right now (so don't register auto-start);
    // no_persistence is the explicit opt-out.
    let skip_reason: Option<&'static str> = if args.foreground {
        Some("foreground_session")
    } else if args.no_start {
        Some("no_start")
    } else if args.no_persistence {
        Some("user_opt_out")
    } else {
        None
    };

    if let Some(reason) = skip_reason {
        let _ = config::persist_supervision_state(
            config_path,
            &SupervisionMode::Disabled,
            &SupervisorKind::None,
            Some(reason),
        );
        let msg = match reason {
            "user_opt_out" => "Supervision: skipped (--no-persistence)",
            "foreground_session" => "Supervision: skipped (foreground session)",
            "no_start" => "Supervision: skipped (--no-start)",
            _ => "Supervision: skipped",
        };
        output.print_step(msg);
        return ("none", "disabled", Some(reason.to_string()));
    }

    let Some(supervisor) = select_supervisor() else {
        let reason = "unsupported_os";
        let _ = config::persist_supervision_state(
            config_path,
            &SupervisionMode::Deferred,
            &SupervisorKind::None,
            Some(reason),
        );
        output
            .print_step("Supervision: deferred (no supported supervisor detected on this system)");
        return ("none", "deferred", Some(reason.to_string()));
    };

    let exe_path =
        std::env::current_exe().unwrap_or_else(|_| std::path::PathBuf::from("openlatch"));
    let backend = supervisor.kind();
    let backend_label: &'static str = match backend {
        SupervisorKind::Launchd => "launchd",
        SupervisorKind::Systemd => "systemd",
        SupervisorKind::TaskScheduler => "task_scheduler",
        SupervisorKind::None => "none",
    };

    match supervisor.install(&exe_path) {
        Ok(()) => {
            let _ = config::persist_supervision_state(
                config_path,
                &SupervisionMode::Active,
                &backend,
                None,
            );
            output.print_step(&format!(
                "Supervision installed ({backend_label}) — daemon will auto-start on login"
            ));
            if output.format == OutputFormat::Human && !output.quiet {
                eprintln!(
                    "  Disable with `openlatch supervision disable` or run `openlatch init --no-persistence`."
                );
            }
            (backend_label, "active", None)
        }
        Err(e) => {
            let reason_text = format!("{} ({})", e.message, e.code);
            let _ = config::persist_supervision_state(
                config_path,
                &SupervisionMode::Deferred,
                &backend,
                Some(&reason_text),
            );
            output.print_step(&format!(
                "Supervision: deferred — {backend_label} install failed ({})",
                e.code
            ));
            if output.format == OutputFormat::Human && !output.quiet {
                eprintln!("  {}", e.message);
                eprintln!(
                    "  Init will continue; run `openlatch supervision install` to retry after the issue is resolved."
                );
            }
            (backend_label, "deferred", Some(reason_text))
        }
    }
}

/// Get a human-readable agent label with path for display.
fn agent_label(agent: &DetectedAgent) -> String {
    match agent {
        DetectedAgent::ClaudeCode { claude_dir, .. } => {
            format!("Claude Code ({})", claude_dir.display())
        }
    }
}

/// Start the daemon in foreground mode (blocking).
///
/// This creates a tokio runtime and starts the daemon server directly.
fn run_daemon_foreground(port: u16, token: &str) -> Result<(), OlError> {
    let mut cfg = config::Config::load(Some(port), None, true)?;
    cfg.foreground = true;

    let rt = tokio::runtime::Runtime::new().map_err(|e| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!("Failed to create async runtime: {e}"),
        )
    })?;

    let token_owned = token.to_string();
    let pid = std::process::id();

    // Tag this process as the daemon in Sentry. See sibling copy in
    // lifecycle.rs::run_daemon_foreground for rationale.
    #[cfg(feature = "crash-report")]
    crate::crash_report::enrich_daemon_scope(cfg.port, pid);

    rt.block_on(async move {
        use crate::envelope;
        use crate::logging;
        use crate::privacy;

        let _guard = logging::daemon_log::init_daemon_logging(&cfg.log_dir, true);

        if let Ok(deleted) = logging::cleanup_old_logs(&cfg.log_dir, cfg.retention_days) {
            if deleted > 0 {
                tracing::info!(deleted = deleted, "cleaned up old log files");
            }
        }

        privacy::init_filter(&cfg.extra_patterns);

        // Write PID file so status/stop can find us
        let pid_path = config::openlatch_dir().join("daemon.pid");
        if let Err(e) = std::fs::write(&pid_path, pid.to_string()) {
            tracing::warn!(error = %e, "failed to write PID file");
        }

        logging::daemon_log::log_startup(
            env!("CARGO_PKG_VERSION"),
            cfg.port,
            pid,
            envelope::os_string(),
            envelope::arch_string(),
        );
        crate::cli::commands::lifecycle::log_observability_status_from_env();

        let credential_store = crate::cli::commands::lifecycle::build_credential_store();
        match crate::daemon::start_server(cfg.clone(), token_owned, Some(credential_store)).await {
            Ok((uptime_secs, events)) => {
                eprintln!(
                    "openlatch daemon stopped \u{2022} uptime {} \u{2022} {} events processed",
                    crate::daemon::format_uptime(uptime_secs),
                    events
                );
            }
            Err(e) => {
                tracing::error!(error = %e, "daemon exited with error");
                eprintln!("Error: daemon exited unexpectedly: {e}");
            }
        }

        // Clean up PID file on exit
        let _ = std::fs::remove_file(&pid_path);
    });

    #[cfg(feature = "crash-report")]
    crate::crash_report::flush(std::time::Duration::from_secs(2));

    Ok(())
}

/// First-run telemetry consent prompt.
///
/// Order of precedence (per `.brainstorms/...telemetry.md §4.5`):
/// 1. `--telemetry` / `--no-telemetry` flag → write decision, no prompt
/// 2. Existing `telemetry.json` → respect it, no prompt (idempotent)
/// 3. Non-interactive (no TTY, CI, `--quiet`, JSON mode) → write disabled + one-liner
/// 4. Interactive TTY → show notice, read line, default Y
///
/// I11: writes `telemetry.json` BEFORE any event capture happens elsewhere.
fn handle_telemetry_consent(
    args: &InitArgs,
    output: &OutputConfig,
    ol_dir: &std::path::Path,
) -> Result<(), OlError> {
    let consent_path = consent_file_path(ol_dir);

    // 1. Explicit flags win.
    if args.no_telemetry {
        telemetry_config::write_consent(&consent_path, false)?;
        output.print_step("Telemetry: disabled (--no-telemetry)");
        return Ok(());
    }
    if args.telemetry {
        telemetry_config::write_consent(&consent_path, true)?;
        output.print_step("Telemetry: enabled (--telemetry)");
        return Ok(());
    }

    // 2. Existing decision — leave it alone.
    if consent_path.exists() {
        return Ok(());
    }

    // 3. Non-interactive: default disabled, print one-liner.
    let stdin_is_tty = std::io::stdin().is_terminal();
    let stdout_is_tty = std::io::stdout().is_terminal();
    let interactive =
        stdin_is_tty && stdout_is_tty && output.format == OutputFormat::Human && !output.quiet;
    if !interactive {
        telemetry_config::write_consent(&consent_path, false)?;
        if output.format == OutputFormat::Human && !output.quiet {
            eprintln!(
                "ℹ Telemetry is off in non-interactive mode. Enable with `openlatch telemetry enable`."
            );
        }
        return Ok(());
    }

    // 4. Interactive prompt.
    print_telemetry_notice();
    let enabled = read_consent_answer();
    telemetry_config::write_consent(&consent_path, enabled)?;
    if enabled {
        output.print_step("Telemetry: enabled — thanks for helping shape OpenLatch.");
    } else {
        output.print_step("Telemetry: disabled — enable later with `openlatch telemetry enable`.");
    }
    Ok(())
}

fn print_telemetry_notice() {
    let lines = [
        "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
        "  Help shape OpenLatch",
        "",
        "  OpenLatch is early, and anonymous usage data is how we",
        "  learn which agents, detections, and workflows matter to",
        "  developers like you.",
        "",
        "  What we collect:",
        "    ✓ Command names (e.g. `init`, `status`) and durations",
        "    ✓ Which AI agents you use",
        "    ✓ Error codes and daemon health signals",
        "    ✓ Aggregated hook volume (counts only, every 5 min)",
        "",
        "  What we NEVER collect:",
        "    ✗ File contents, source code, or prompts",
        "    ✗ Environment variables, tokens, or secrets",
        "    ✗ Command arguments or flag values",
        "    ✗ IP addresses, hostnames, usernames",
        "",
        "  Turn it off anytime: openlatch telemetry disable",
        "",
        "  Share anonymous usage data to help improve OpenLatch? [Y/n]",
        "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
    ];
    for line in lines {
        eprintln!("{line}");
    }
    let _ = std::io::stderr().flush();
}

fn read_consent_answer() -> bool {
    let mut buf = String::new();
    let stdin = std::io::stdin();
    let _ = stdin.lock().read_line(&mut buf);
    let answer = buf.trim().to_ascii_lowercase();
    // Default Y on empty input. Only explicit "n"/"no" declines.
    !matches!(answer.as_str(), "n" | "no")
}

/// Wait for the daemon's /health endpoint to return 200, up to `timeout_secs`.
///
/// Returns `true` if health check passed within the timeout, `false` otherwise.
fn wait_for_health(port: u16, timeout_secs: u64) -> bool {
    let url = format!("http://127.0.0.1:{port}/health");
    let start = std::time::Instant::now();
    let timeout = std::time::Duration::from_secs(timeout_secs);

    while start.elapsed() < timeout {
        if let Ok(resp) = reqwest::blocking::get(&url) {
            if resp.status().is_success() {
                return true;
            }
        }
        std::thread::sleep(std::time::Duration::from_millis(200));
    }
    false
}