openlatch-client 0.1.18

OpenLatch runtime enforcement node — the capture-and-enforce client for the AI Operations Platform
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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
/// `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, ERR_PORT_IN_USE};
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 the token file to its owner on every platform.
    crate::fs_secure::restrict_to_owner(&token_path).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);
        }
        // An explicit OPENLATCH_PORT outranks probing. Probing picks a
        // default when the operator has expressed no preference; it is not an
        // override. Passing the probe result down as `cli_port` gave it
        // CLI-flag precedence, so `OPENLATCH_PORT=7599 openlatch init` pinned
        // 7443 and silently discarded the request — while probe_free_port's
        // own failure text tells the operator to "set OPENLATCH_PORT to a
        // specific port". init has no --port flag, so this env var is the only
        // way to express the intent at all.
        //
        // --reconfig still applies: it discards the previous pin above, then
        // lands on whatever the operator asked for here.
        let requested = std::env::var("OPENLATCH_PORT")
            .ok()
            .filter(|v| !v.trim().is_empty())
            .map(|v| config::parse_port_env(&v))
            .transpose()?;

        let selected = match requested {
            Some(p) => {
                // Fail loudly rather than probing past it. Silently binding a
                // different port is what produces a daemon and a settings.json
                // that disagree, and the hook fails open when they do.
                if std::net::TcpListener::bind(("127.0.0.1", p)).is_err() {
                    return Err(OlError::new(
                        ERR_PORT_IN_USE,
                        format!("OPENLATCH_PORT={p} is already in use"),
                    )
                    .with_suggestion(format!(
                        "Free port {p}, choose another via OPENLATCH_PORT, or unset it to probe {}-{} automatically.",
                        config::PORT_RANGE_START,
                        config::PORT_RANGE_END
                    ))
                    .with_docs("https://docs.openlatch.ai/errors/OL-1500"));
                }
                output.print_substep(&format!("Selected port {p} (from OPENLATCH_PORT)"));
                p
            }
            None => {
                let probed =
                    config::probe_free_port(config::PORT_RANGE_START, config::PORT_RANGE_END)?;
                output.print_substep(&format!("Selected port {probed} (first available)"));
                probed
            }
        };
        // Write config.toml with the selected port
        config::ensure_config(selected)?;
        // Write daemon.port file for hook binary discovery
        config::write_port_file(selected)?;
        selected
    } 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)?;

    // Must land before the auth flow below: `auth login` opens the browser at
    // `cloud.api_url`, so a --api-url applied afterwards would authenticate
    // against the wrong platform on the very run that set it.
    if let Some(api_url) = &args.api_url {
        config::persist_api_url(&config_path, api_url)?;
        output.print_substep(&format!("Cloud API URL set to {api_url}"));
    }

    // `--no-boundary` must hold on every path, so it lands in config BEFORE the
    // config is loaded below.
    //
    // It used to be read in exactly one place — inside the `--foreground`
    // branch of the daemon start. The background paths, which are the default,
    // passed no boundary intent at all: the spawned daemon read `[boundary]
    // enabled` from config, bound the port, and wrote `ANTHROPIC_BASE_URL` into
    // settings.json. So the documented opt-out did nothing unless you also
    // passed `--foreground`, and with live agent sessions on the machine the
    // flag read as a safety measure while being none.
    //
    // Persisted rather than passed down: `init` installs OS supervision by
    // default, so a one-shot flag would be undone by the supervisor's next
    // start. Config is the only place the intent survives.
    if args.no_boundary {
        config::persist_boundary_enabled(&config_path, false)?;
        output.print_substep(
            "Model boundary disabled in config — agents connect to the provider directly",
        );
    }

    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.55: Stage the hook binary into `<ol_dir>/bin/` BEFORE writing any
    // hook command.
    //
    // `resolve_hook_binary_path()` has always documented this directory as "the
    // canonical install location populated by `openlatch init` on the first
    // run", and nothing populated it — the only staging in the tree lived in
    // `doctor --fix`. On a machine whose `openlatch` had no `openlatch-hook`
    // sibling, the resolver fell through to a bare name, `init` wrote it into
    // all 12 entries, and every tool call in every session died with
    // `openlatch-hook: command not found` — invisibly, because the hook fails
    // open. Failing here is the point: an install that cannot resolve its own
    // hook binary is not a successful install, and settings.json is still
    // untouched at this line.
    match hooks::staging::stage_hook_binary(&ol_dir) {
        Ok(outcome) => {
            output.print_step(&format!("Hook binary at {}", outcome.target().display()));
        }
        Err(e) => {
            output.print_error(&e);
            return Err(e);
        }
    }

    // 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));
    }

    // NOTE: `init` deliberately does NOT write the model-boundary wiring.
    //
    // It used to, right here, before anything had bound the pinned port — and
    // `init --foreground` then started a daemon that never bound it, so
    // `ANTHROPIC_BASE_URL` pointed every Claude Code session on the machine at a
    // port nobody held. The write now belongs to the daemon, which does it after
    // its bind succeeds and undoes it when it stops (`daemon::serve_with_listener`).
    // `init` starts the daemon a few lines below; that is what wires the agent.

    // 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 start_plan = plan_daemon_start(
        args.no_start,
        args.foreground,
        supervision_mode_label == "active",
    );
    let (port, pid) = if start_plan == DaemonStartPlan::Skip {
        output.print_step("Skipped daemon start (--no-start)");
        (cfg.port, 0u32)
    } else if start_plan == DaemonStartPlan::SupervisorOwned {
        // The supervisor already started a daemon, a few lines above:
        // `systemctl enable --now` and launchd's `RunAtLoad` both start the
        // unit at INSTALL time. Spawning one here as well is what produced the
        // 130-restart loop — two daemons racing for port 7443, and whichever
        // lost exited 0 straight into `Restart=always`. There is one owner, and
        // from here `init` only waits for it.
        if wait_for_health(cfg.port, 10) {
            let pid = lifecycle::read_pid_file().unwrap_or(0);
            output.print_step(&format!(
                "Daemon started on port {} (PID {pid}, supervised)",
                cfg.port
            ));
            (cfg.port, pid)
        } else if let Some(pid) =
            lifecycle::read_pid_file().filter(|p| lifecycle::is_process_alive(*p))
        {
            // A supervised daemon exists and is simply not serving yet.
            // Spawning a second one here would be the same double-owner bug in
            // a different costume, and it would not help: whatever is keeping
            // that process from answering would stop a fresh one too.
            output.print_step(&format!(
                "Daemon starting under supervision (PID {pid}) — not yet answering /health"
            ));
            if output.format == OutputFormat::Human && !output.quiet {
                eprintln!("  Check `openlatch status` shortly, or the newest ~/.openlatch/logs/daemon.log.<date>.");
            }
            (cfg.port, pid)
        } else {
            // Nothing is running and nothing is starting: the supervisor
            // accepted the install but demonstrably started nothing. THIS is
            // the case the direct spawn exists for.
            tracing::warn!(
                "supervision reported active but no daemon came up; starting one directly"
            );
            match lifecycle::spawn_daemon_background(cfg.port, &new_token) {
                Ok(pid) => {
                    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);
                }
            }
        }
    } 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
        ));
        // The foreground daemon IS the daemon — there is no background one
        // behind it — so it must bind the boundary and own the agent wiring,
        // exactly like `openlatch start`. Passing `false` here is what made
        // `init --foreground` deterministically break every Claude Code session
        // on the machine.
        //
        // `args.no_boundary` is deliberately NOT consulted here any more: it was
        // persisted into config above, so `cfg.boundary.enabled` already carries
        // it. One source of truth is the point — this branch reading the flag
        // while the background branches did not is exactly how the opt-out came
        // to hold on one path out of three.
        #[cfg(feature = "boundary")]
        let spawn_boundary = cfg.boundary.enabled;
        #[cfg(not(feature = "boundary"))]
        let spawn_boundary = false;
        run_daemon_foreground(cfg.port, &new_token, spawn_boundary)?;
        (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 5.5: The model boundary must be proven, not assumed.
    //
    // Everything above can succeed against a boundary that binds its port and
    // cannot forward a single byte, and that install is worse than no install:
    // `ANTHROPIC_BASE_URL` would point every Claude Code session on the machine
    // at a listener that answers 502. The daemon gates the write on a real round
    // trip; this reads its verdict and refuses to report success without one.
    #[cfg(feature = "boundary")]
    verify_boundary_preflight(args, &cfg, start_plan, output)?;

    // 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"));
    let fully_live = !args.no_start && auth_success;
    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());
        }
        if fully_live {
            print_init_success_banner(output.color);
        }
    }

    // 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".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).
/// Who starts the daemon at the end of `init`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DaemonStartPlan {
    /// `--no-start` — nothing starts.
    Skip,
    /// `--foreground` — this process becomes the daemon.
    Foreground,
    /// Supervision installed successfully, which means a daemon is ALREADY
    /// starting: both `systemctl enable --now` and launchd's `RunAtLoad` start
    /// the unit at install time. `init` waits for it instead of spawning.
    SupervisorOwned,
    /// Nobody else owns the daemon — `init` spawns it itself.
    SpawnBackground,
}

/// Decide who starts the daemon. Pure, so the ordering is testable without a
/// systemd on the machine.
///
/// The order is the whole content of the function. `--no-start` and
/// `--foreground` are explicit user requests and win over everything;
/// `supervision_active` is a fact about the machine and only decides the
/// remaining case. (`run_supervision_install_for_init` already declines to
/// install under either flag, so the last two arguments cannot both be
/// meaningful — the ordering here makes that independent of that function.)
pub(crate) fn plan_daemon_start(
    no_start: bool,
    foreground: bool,
    supervision_active: bool,
) -> DaemonStartPlan {
    if no_start {
        DaemonStartPlan::Skip
    } else if foreground {
        DaemonStartPlan::Foreground
    } else if supervision_active {
        DaemonStartPlan::SupervisorOwned
    } else {
        DaemonStartPlan::SpawnBackground
    }
}

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, spawn_boundary: bool) -> 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();
        // `--foreground` makes this process the long-lived daemon, not a setup
        // helper: it binds the pinned boundary port and owns the agent's
        // `ANTHROPIC_BASE_URL` for as long as it runs. An occupied port fails
        // the start rather than degrading it (OL-BND-PORT).
        match crate::daemon::start_server(
            cfg.clone(),
            token_owned,
            Some(credential_store),
            spawn_boundary,
        )
        .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(())
}

/// Final banner shown when `openlatch init` completes fully and the daemon
/// is actively forwarding events to the cloud.
fn print_init_success_banner(color: bool) {
    use crate::cli::color as c;
    let check = c::checkmark(color);
    let headline = c::bold(
        "OpenLatch is now capturing activity from your AI agents",
        color,
    );
    let url = c::bold("https://app.openlatch.ai", color);
    let rule = c::dim(
        "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
        color,
    );
    let lines = [
        String::new(),
        rule.clone(),
        format!("  {check} {headline}"),
        String::new(),
        "  Nothing else to do — OpenLatch runs in the background,".to_string(),
        "  capturing what your agents do so you can see and".to_string(),
        "  control it from the console.".to_string(),
        String::new(),
        "  Explore agent activity, inventory, and the audit trail:".to_string(),
        format!("  {url}"),
        rule,
    ];
    for line in lines {
        eprintln!("{line}");
    }
    let _ = std::io::stderr().flush();
}

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",
        "  most to the people we protect.",
        "",
        "  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.
/// How long `init` waits for the daemon's wiring supervisor to reach a verdict.
///
/// Its first probe has a 5 s budget of its own and runs the moment the listener
/// is bound, so this is that plus room for a cold start on a slow machine.
#[cfg(feature = "boundary")]
const PREFLIGHT_VERDICT_WAIT: std::time::Duration = std::time::Duration::from_secs(15);

/// Read the daemon's boundary preflight verdict and fail the install on a proven
/// failure.
///
/// Three outcomes, deliberately not two:
///
/// - **`ok`** — the agent is wired to a listener that demonstrably reaches the
///   provider. Say so and move on.
/// - **`failed`** — the boundary bound its port and could NOT complete a round
///   trip. The daemon has already left the agent unwired, so sessions work; but
///   nothing is captured and the operator must know, so `init` exits non-zero.
///   Hooks, daemon and supervision all stay installed — none of them depend on
///   the proxy, and tearing them down would turn one degraded subsystem into no
///   install at all.
/// - **no verdict inside the budget** — a warning, never a failure. "We could
///   not tell in 15 s" is not evidence of breakage, the supervisor keeps
///   probing, and it will not wire anything until it is green. Failing here
///   would cost slow machines their install for nothing.
#[cfg(feature = "boundary")]
fn verify_boundary_preflight(
    args: &InitArgs,
    cfg: &config::Config,
    start_plan: DaemonStartPlan,
    output: &OutputConfig,
) -> Result<(), OlError> {
    // Nothing to verify: no daemon was started, the boundary is off, this is an
    // isolated instance that never wires the machine-global agent config, or
    // the foreground path — where the daemon IS this process and we only reach
    // here after it has already shut down.
    if start_plan == DaemonStartPlan::Skip
        || args.foreground
        || !cfg.boundary.enabled
        || args.no_boundary
        || !cfg.boundary.owns_agent_wiring()
    {
        return Ok(());
    }

    let port = cfg.boundary.port;
    let deadline = std::time::Instant::now() + PREFLIGHT_VERDICT_WAIT;
    let url = format!("http://127.0.0.1:{port}/admin/boundary/status");

    loop {
        let status = reqwest::blocking::Client::builder()
            .timeout(std::time::Duration::from_secs(2))
            .build()
            .ok()
            .and_then(|c| c.get(&url).send().ok())
            .and_then(|r| r.json::<serde_json::Value>().ok());

        if let Some(body) = status {
            match body.get("preflight").and_then(|v| v.as_str()) {
                Some("ok") => {
                    output.print_step(&format!(
                        "Model boundary verified — agent routed via http://127.0.0.1:{port}"
                    ));
                    return Ok(());
                }
                Some("failed") => {
                    let reason = body
                        .get("preflight_error")
                        .and_then(|v| v.as_str())
                        .unwrap_or("the boundary could not complete a request to the provider");
                    let err = OlError::new(
                        crate::error::ERR_BOUNDARY_PREFLIGHT_FAILED,
                        format!("Model boundary check failed: {reason}"),
                    )
                    .with_suggestion(
                        "Your agent settings were left untouched, so sessions connect straight to \
                         the provider and keep working — but nothing is captured. Check network \
                         reachability to https://api.anthropic.com (proxy, VPN, TLS interception), \
                         then run `openlatch restart`. Run `openlatch doctor` for the full picture."
                            .to_string(),
                    )
                    .with_docs("https://docs.openlatch.ai/errors/OL-BND-PREFLIGHT");
                    output.print_error(&err);
                    return Err(err);
                }
                // "pending" — the supervisor has not finished its first probe.
                _ => {}
            }
        }

        if std::time::Instant::now() >= deadline {
            output.print_substep(
                "Model boundary: no verdict yet — the daemon is still checking it. \
                 Run `openlatch doctor` in a moment to confirm.",
            );
            return Ok(());
        }
        std::thread::sleep(std::time::Duration::from_millis(250));
    }
}

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
}

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

    /// The bug: `init` installed supervision (which starts a daemon via
    /// `enable --now` / `RunAtLoad`) and then spawned a second daemon
    /// unconditionally. Both raced for the port; the loser exited 0 into
    /// `Restart=always`. With a supervisor active there must be exactly one
    /// owner, and it is not `init`.
    #[test]
    fn active_supervision_means_init_does_not_spawn() {
        assert_eq!(
            plan_daemon_start(false, false, true),
            DaemonStartPlan::SupervisorOwned
        );
    }

    #[test]
    fn without_supervision_init_still_spawns() {
        assert_eq!(
            plan_daemon_start(false, false, false),
            DaemonStartPlan::SpawnBackground
        );
    }

    /// Explicit user requests outrank the machine's supervision state — and
    /// stay outranking it even if a future change lets supervision install
    /// under these flags.
    #[test]
    fn explicit_flags_win_over_supervision() {
        assert_eq!(plan_daemon_start(true, false, true), DaemonStartPlan::Skip);
        assert_eq!(
            plan_daemon_start(false, true, true),
            DaemonStartPlan::Foreground
        );
        // --no-start beats --foreground: nothing starts at all.
        assert_eq!(plan_daemon_start(true, true, true), DaemonStartPlan::Skip);
    }
}