openlatch-client 0.1.8

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
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
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
/// Configuration loading for OpenLatch daemon.
///
/// Implements the full precedence chain per CONF-03:
/// CLI flags > env vars (`OPENLATCH_*`) > `~/.openlatch/config.toml` > defaults
///
/// The default config file uses a commented-template style (D-10) with only the
/// pinned port written as an active value (D-11).
use std::path::{Path, PathBuf};

use serde::Deserialize;

use crate::error::{OlError, ERR_INVALID_CONFIG, ERR_PORT_IN_USE};

// ---------------------------------------------------------------------------
// Update check configuration
// ---------------------------------------------------------------------------

/// Configuration for the version update check performed at daemon startup.
///
/// Override via env var: `OPENLATCH_UPDATE_CHECK=false` disables the check.
#[derive(Debug, Clone)]
pub struct UpdateConfig {
    /// Whether to check for a newer version on daemon start. Default: true.
    pub check: bool,
}

impl Default for UpdateConfig {
    fn default() -> Self {
        Self { check: true }
    }
}

// ---------------------------------------------------------------------------
// Cloud forwarding configuration (D-12)
// ---------------------------------------------------------------------------

/// Runtime-resolved configuration for cloud event forwarding.
///
/// Populated from the `[cloud]` section in `config.toml` with env var overrides:
/// - `OPENLATCH_CLOUD_ENABLED` — overrides `enabled`
/// - `OPENLATCH_API_URL` — overrides `api_url`
///
/// `OPENLATCH_API_KEY` is NOT handled here — it is a credential managed by
/// `CredentialStore` in `src/core/auth/`.
#[derive(Debug, Clone)]
pub struct CloudConfig {
    /// Whether cloud forwarding is active. Default: false.
    pub enabled: bool,
    /// Cloud API base URL. Default: "https://app.openlatch.ai/api".
    pub api_url: String,
    /// TCP connect timeout in milliseconds. Default: 5000.
    pub timeout_connect_ms: u64,
    /// Total request timeout in milliseconds. Default: 10000.
    pub timeout_total_ms: u64,
    /// Number of retries on network error or 5xx (0 = no retry). Default: 1.
    pub retry_count: u32,
    /// Delay between retries in milliseconds. Default: 2000.
    pub retry_delay_ms: u64,
    /// Bounded channel size for async event forwarding. Default: 1000.
    pub channel_size: usize,
    /// How often the cloud worker re-reads the credential from the provider,
    /// in milliseconds. Default: 60_000 (60 s). E2E tests override this via
    /// `OPENLATCH_CLOUD_CREDENTIAL_POLL_MS` so the hot-reload path is
    /// observable without a real-time 60 s wait.
    pub credential_poll_interval_ms: u64,
}

impl Default for CloudConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            api_url: "https://app.openlatch.ai/api".into(),
            timeout_connect_ms: 5000,
            timeout_total_ms: 10000,
            retry_count: 1,
            retry_delay_ms: 2000,
            channel_size: 1000,
            credential_poll_interval_ms: 60_000,
        }
    }
}

// ---------------------------------------------------------------------------
// Platform-aware home directory
// ---------------------------------------------------------------------------

/// Returns the platform-appropriate openlatch data directory.
///
/// Resolution order:
/// 1. `OPENLATCH_DIR` env var — absolute path override (used by E2E tests and
///    users who need a non-default location; non-empty values only).
/// 2. Platform default:
///    - Unix/macOS: `~/.openlatch`
///    - Windows: `%APPDATA%\openlatch` (falls back to `~\openlatch` if
///      `%APPDATA%` is unavailable). On Windows this reads `FOLDERID_RoamingAppData`
///      via `SHGetKnownFolderPath` — which ignores the `APPDATA` env var —
///      so `OPENLATCH_DIR` is the supported redirection mechanism.
pub fn openlatch_dir() -> PathBuf {
    if let Ok(dir) = std::env::var("OPENLATCH_DIR") {
        if !dir.is_empty() {
            return PathBuf::from(dir);
        }
    }
    #[cfg(windows)]
    {
        dirs::data_dir()
            .unwrap_or_else(|| dirs::home_dir().expect("home directory must exist"))
            .join("openlatch")
    }
    #[cfg(not(windows))]
    {
        dirs::home_dir()
            .expect("home directory must exist")
            .join(".openlatch")
    }
}

// ---------------------------------------------------------------------------
// Config struct (public, runtime-resolved)
// ---------------------------------------------------------------------------

/// Resolved runtime configuration for the OpenLatch daemon.
///
/// This struct is constructed by [`Config::load`] from the full precedence chain:
/// CLI flags > env vars > config.toml > defaults.
#[derive(Debug, Clone)]
pub struct Config {
    /// TCP port for the local daemon (default: 7443).
    pub port: u16,
    /// Directory for audit and daemon logs.
    pub log_dir: PathBuf,
    /// Tracing log level (default: "info").
    pub log_level: String,
    /// Audit log retention in days (default: 30).
    pub retention_days: u32,
    /// Additional regex patterns for secret masking (additive to built-ins, per D-03).
    pub extra_patterns: Vec<String>,
    /// When true, daemon runs in foreground without forking.
    pub foreground: bool,
    /// Update check configuration (UPDT-01 through UPDT-04).
    pub update: UpdateConfig,
    /// Cloud forwarding configuration (CONF-01, D-12).
    pub cloud: CloudConfig,
    /// Persistent machine identifier (D-11). Generated once at init via ensure_agent_id().
    /// Format: `agt_<uuid_simple>` (e.g., "agt_550e8400e29b41d4a716446655440000").
    /// None if not yet initialized.
    pub agent_id: Option<String>,
    /// Supervision state: OS-native auto-restart for the daemon (launchd / systemd
    /// user / Task Scheduler). Populated from the `[supervision]` section in
    /// config.toml, persisted by `persist_supervision_state`.
    pub supervision: crate::supervision::SupervisionConfig,
}

impl Config {
    /// Return sensible defaults for all config fields.
    pub fn defaults() -> Self {
        Self {
            port: 7443,
            log_dir: openlatch_dir().join("logs"),
            log_level: "info".into(),
            retention_days: 30,
            extra_patterns: vec![],
            foreground: false,
            update: UpdateConfig::default(),
            cloud: CloudConfig::default(),
            agent_id: None,
            supervision: crate::supervision::SupervisionConfig::default(),
        }
    }

    /// Load configuration from the full precedence chain.
    ///
    /// Precedence order (highest to lowest):
    /// 1. CLI flags (`cli_*` parameters — `Some(value)` overrides)
    /// 2. Environment variables (`OPENLATCH_PORT`, `OPENLATCH_HOST`, `OPENLATCH_LOG_DIR`,
    ///    `OPENLATCH_LOG`, `OPENLATCH_RETENTION_DAYS`)
    /// 3. `~/.openlatch/config.toml` (parsed, partial overrides)
    /// 4. Compile-time defaults
    ///
    /// # Errors
    ///
    /// Returns [`OlError`] if the config file exists but cannot be parsed as valid TOML.
    pub fn load(
        cli_port: Option<u16>,
        cli_log_level: Option<String>,
        cli_foreground: bool,
    ) -> Result<Self, OlError> {
        let mut cfg = Self::defaults();

        // Layer 3: config.toml
        let config_path = openlatch_dir().join("config.toml");
        if config_path.exists() {
            let raw = std::fs::read_to_string(&config_path).map_err(|e| {
                OlError::new(ERR_INVALID_CONFIG, format!("Cannot read config file: {e}"))
                    .with_suggestion("Check that the file is readable and not corrupted.")
            })?;
            let toml_cfg: TomlConfig = toml::from_str(&raw).map_err(|e| {
                OlError::new(
                    ERR_INVALID_CONFIG,
                    format!("Invalid TOML in config file: {e}"),
                )
                .with_suggestion("Check your config.toml for syntax errors.")
                .with_docs("https://docs.openlatch.ai/configuration")
            })?;
            if let Some(daemon) = toml_cfg.daemon {
                if let Some(port) = daemon.port {
                    cfg.port = port;
                }
                if let Some(ref mid) = daemon.agent_id {
                    cfg.agent_id = Some(mid.clone());
                }
            }
            if let Some(logging) = toml_cfg.logging {
                if let Some(level) = logging.level {
                    cfg.log_level = level;
                }
                if let Some(dir) = logging.dir {
                    cfg.log_dir = PathBuf::from(dir);
                }
                if let Some(days) = logging.retention_days {
                    cfg.retention_days = days;
                }
            }
            if let Some(privacy) = toml_cfg.privacy {
                if let Some(patterns) = privacy.extra_patterns {
                    cfg.extra_patterns = patterns;
                }
            }
            if let Some(update) = toml_cfg.update {
                if let Some(check) = update.check {
                    cfg.update.check = check;
                }
            }
            if let Some(sup) = toml_cfg.supervision {
                use crate::supervision::{SupervisionMode, SupervisorKind};
                if let Some(mode) = sup.mode.as_deref() {
                    cfg.supervision.mode = match mode {
                        "active" => SupervisionMode::Active,
                        "deferred" => SupervisionMode::Deferred,
                        _ => SupervisionMode::Disabled,
                    };
                }
                if let Some(backend) = sup.backend.as_deref() {
                    cfg.supervision.backend = match backend {
                        "launchd" => SupervisorKind::Launchd,
                        "systemd" => SupervisorKind::Systemd,
                        "task_scheduler" => SupervisorKind::TaskScheduler,
                        _ => SupervisorKind::None,
                    };
                }
                cfg.supervision.disabled_reason = sup.disabled_reason;
            }
            if let Some(cloud) = toml_cfg.cloud {
                if let Some(v) = cloud.enabled {
                    cfg.cloud.enabled = v;
                }
                if let Some(v) = cloud.api_url {
                    cfg.cloud.api_url = v;
                }
                if let Some(v) = cloud.timeout_connect_ms {
                    cfg.cloud.timeout_connect_ms = v;
                }
                if let Some(v) = cloud.timeout_total_ms {
                    cfg.cloud.timeout_total_ms = v;
                }
                if let Some(v) = cloud.retry_count {
                    cfg.cloud.retry_count = v;
                }
                if let Some(v) = cloud.retry_delay_ms {
                    cfg.cloud.retry_delay_ms = v;
                }
                if let Some(v) = cloud.channel_size {
                    cfg.cloud.channel_size = v;
                }
                if let Some(v) = cloud.credential_poll_interval_ms {
                    cfg.cloud.credential_poll_interval_ms = v;
                }
            }
        }

        // Layer 2: env vars
        if let Ok(val) = std::env::var("OPENLATCH_PORT") {
            cfg.port = val.parse::<u16>().map_err(|_| {
                OlError::new(
                    ERR_INVALID_CONFIG,
                    format!("OPENLATCH_PORT is not a valid port number: '{val}'"),
                )
                .with_suggestion("Set OPENLATCH_PORT to an integer between 1024 and 65535.")
            })?;
        }
        if let Ok(val) = std::env::var("OPENLATCH_LOG_DIR") {
            cfg.log_dir = PathBuf::from(val);
        }
        if let Ok(val) = std::env::var("OPENLATCH_LOG") {
            cfg.log_level = val;
        }
        if let Ok(val) = std::env::var("OPENLATCH_RETENTION_DAYS") {
            cfg.retention_days = val.parse::<u32>().map_err(|_| {
                OlError::new(
                    ERR_INVALID_CONFIG,
                    format!("OPENLATCH_RETENTION_DAYS is not a valid integer: '{val}'"),
                )
                .with_suggestion("Set OPENLATCH_RETENTION_DAYS to a positive integer.")
            })?;
        }
        // UPDT-04: env var override for update check
        if let Ok(val) = std::env::var("OPENLATCH_UPDATE_CHECK") {
            if val == "false" || val == "0" {
                cfg.update.check = false;
            }
        }
        // CONF-02: cloud env var overrides
        if let Ok(val) = std::env::var("OPENLATCH_CLOUD_ENABLED") {
            cfg.cloud.enabled = val == "true" || val == "1";
        }
        if let Ok(val) = std::env::var("OPENLATCH_API_URL") {
            cfg.cloud.api_url = val;
        }
        if let Ok(val) = std::env::var("OPENLATCH_CLOUD_CREDENTIAL_POLL_MS") {
            cfg.cloud.credential_poll_interval_ms = val.parse::<u64>().map_err(|_| {
                OlError::new(
                    ERR_INVALID_CONFIG,
                    format!("OPENLATCH_CLOUD_CREDENTIAL_POLL_MS is not a valid integer: '{val}'"),
                )
                .with_suggestion(
                    "Set OPENLATCH_CLOUD_CREDENTIAL_POLL_MS to a positive integer (ms).",
                )
            })?;
        }

        // Layer 1: CLI flags (highest priority)
        if let Some(port) = cli_port {
            cfg.port = port;
        }
        if let Some(level) = cli_log_level {
            cfg.log_level = level;
        }
        if cli_foreground {
            cfg.foreground = true;
        }

        Ok(cfg)
    }
}

// ---------------------------------------------------------------------------
// TOML intermediate structs (all fields optional — partial overrides)
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize)]
struct TomlConfig {
    #[serde(default)]
    daemon: Option<DaemonToml>,
    #[serde(default)]
    logging: Option<LoggingToml>,
    #[serde(default)]
    privacy: Option<PrivacyToml>,
    #[serde(default)]
    update: Option<UpdateToml>,
    #[serde(default)]
    cloud: Option<CloudToml>,
    #[serde(default)]
    supervision: Option<SupervisionToml>,
}

#[derive(Debug, Deserialize)]
struct DaemonToml {
    port: Option<u16>,
    agent_id: Option<String>,
}

#[derive(Debug, Deserialize)]
struct CloudToml {
    enabled: Option<bool>,
    api_url: Option<String>,
    timeout_connect_ms: Option<u64>,
    timeout_total_ms: Option<u64>,
    retry_count: Option<u32>,
    retry_delay_ms: Option<u64>,
    channel_size: Option<usize>,
    credential_poll_interval_ms: Option<u64>,
}

#[derive(Debug, Deserialize)]
struct LoggingToml {
    level: Option<String>,
    dir: Option<String>,
    retention_days: Option<u32>,
}

#[derive(Debug, Deserialize)]
struct PrivacyToml {
    extra_patterns: Option<Vec<String>>,
}

#[derive(Debug, Deserialize)]
struct UpdateToml {
    check: Option<bool>,
}

#[derive(Debug, Deserialize)]
struct SupervisionToml {
    mode: Option<String>,
    backend: Option<String>,
    disabled_reason: Option<String>,
}

// ---------------------------------------------------------------------------
// Default config template (D-10 / D-11)
// ---------------------------------------------------------------------------

/// Generate the default config.toml content.
///
/// Per D-10: commented template style — all sections present, every field commented.
/// Per D-11: only the pinned `port` value is written as an active (uncommented) line.
pub fn generate_default_config_toml(port: u16) -> String {
    format!(
        r#"# OpenLatch Configuration
# Uncomment and modify values to customize behavior.

[daemon]
port = {port}
# SECURITY: bind address is always 127.0.0.1 — not configurable
# agent_id is generated by 'openlatch init'

[logging]
# level = "info"
# dir = "~/.openlatch/logs"
# retention_days = 30

[privacy]
# Extra regex patterns for secret masking (additive to built-ins).
# Each entry is a regex string applied to JSON string values.
# extra_patterns = ["CUSTOM_SECRET_[A-Z0-9]{{32}}"]

# [update]
# check = true  # Set to false to disable update checks on daemon start

# [cloud]
# enabled = true
# api_url = "https://app.openlatch.ai/api"
# timeout_connect_ms = 5000
# timeout_total_ms = 10000
# retry_count = 1
# retry_delay_ms = 2000
# channel_size = 1000

# [supervision]
# OS-native auto-restart (launchd / systemd-user / Task Scheduler).
# Managed by `openlatch init` and `openlatch supervision {{install|uninstall|enable|disable}}`.
# mode = "disabled"           # "active" | "deferred" | "disabled"
# backend = "none"            # "launchd" | "systemd" | "task_scheduler" | "none"
# disabled_reason = "user_opt_out"
"#
    )
}

/// Ensure the openlatch config directory and config.toml exist.
///
/// Creates `~/.openlatch/` if missing, writes `config.toml` with the default
/// template if missing, then returns the path to `config.toml`.
///
/// # Errors
///
/// Returns [`OlError`] if the directory or file cannot be created.
pub fn ensure_config(port: u16) -> Result<PathBuf, OlError> {
    let dir = openlatch_dir();
    std::fs::create_dir_all(&dir).map_err(|e| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!("Cannot create config directory '{}': {e}", dir.display()),
        )
        .with_suggestion("Check that you have write permission to your home directory.")
    })?;

    let config_path = dir.join("config.toml");
    if !config_path.exists() {
        let content = generate_default_config_toml(port);
        std::fs::write(&config_path, content).map_err(|e| {
            OlError::new(
                ERR_INVALID_CONFIG,
                format!("Cannot write config file '{}': {e}", config_path.display()),
            )
            .with_suggestion("Check that you have write permission to ~/.openlatch/.")
        })?;
    }

    Ok(config_path)
}

// ---------------------------------------------------------------------------
// Token generation and management (SEC-01)
// ---------------------------------------------------------------------------

/// Generate a cryptographically random 64-character hex token.
///
/// Uses two UUIDv4 values (each 16 bytes of OS CSPRNG entropy via `getrandom`)
/// concatenated to produce 32 bytes = 64 hex characters. No additional
/// dependencies are needed since `uuid` with the `v4` feature already pulls
/// in `getrandom` which maps to the OS CSPRNG on all platforms.
///
/// # Security
///
/// The resulting string is suitable as a bearer token for daemon authentication.
/// The `uuid` crate uses `getrandom` internally, which calls `BCryptGenRandom`
/// on Windows and `getrandom(2)` / `/dev/urandom` on Unix.
pub fn generate_token() -> String {
    let a = uuid::Uuid::new_v4();
    let b = uuid::Uuid::new_v4();
    format!("{}{}", a.simple(), b.simple())
}

/// Ensure a daemon bearer token exists at `{dir}/daemon.token`.
///
/// If the token file already exists, reads and returns the existing token.
/// If it does not exist, generates a new token, writes it to the file with
/// restricted permissions (mode 0600 on Unix), and returns the new token.
///
/// # Errors
///
/// Returns [`OlError`] if the token file cannot be read or written.
///
/// # Security (SEC-01)
///
/// The token file is set to mode 0600 on Unix (user read/write only).
/// On Windows, the file is written to the user's AppData directory which is
/// already restricted to the current user by default ACLs.
pub fn ensure_token(dir: &Path) -> Result<String, OlError> {
    let token_path = dir.join("daemon.token");

    if token_path.exists() {
        // Read existing token
        let token = std::fs::read_to_string(&token_path).map_err(|e| {
            OlError::new(
                crate::error::ERR_INVALID_CONFIG,
                format!("Cannot read token file '{}': {e}", token_path.display()),
            )
            .with_suggestion("Check that the file exists and is readable.")
        })?;
        return Ok(token.trim().to_string());
    }

    // Generate and write new token — ensure parent directory exists first
    let token = generate_token();
    if let Some(parent) = token_path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| {
            OlError::new(
                crate::error::ERR_INVALID_CONFIG,
                format!("Cannot create directory '{}': {e}", parent.display()),
            )
            .with_suggestion("Check that you have write permission to the parent directory.")
        })?;
    }
    std::fs::write(&token_path, &token).map_err(|e| {
        OlError::new(
            crate::error::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.
    // Windows does not need this because AppData is already restricted by ACLs.
    #[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(
                crate::error::ERR_INVALID_CONFIG,
                format!("Cannot set permissions on token file: {e}"),
            )
            .with_suggestion("Check that you have permission to modify file attributes.")
        })?;
    }

    Ok(token)
}

// ---------------------------------------------------------------------------
// Agent ID generation and management (D-11, CONF-03)
// ---------------------------------------------------------------------------

/// Ensure a machine identifier exists in `[daemon].agent_id` within `config_path`.
///
/// On first call: generates `agt_<uuid_simple>`, inserts it into the config file
/// (preserving all other content), and returns the new ID.
///
/// On subsequent calls: reads the existing ID and returns it unchanged (idempotent).
///
/// # Format
///
/// `agt_` prefix + 32 lowercase hex digits (UUID v4 simple format, no hyphens).
/// Example: `agt_550e8400e29b41d4a716446655440000`
///
/// # Errors
///
/// Returns [`OlError`] if the config file cannot be read or written.
pub fn ensure_agent_id(config_path: &Path) -> Result<String, OlError> {
    // Read and parse the existing file
    let raw = std::fs::read_to_string(config_path).map_err(|e| {
        OlError::new(
            crate::error::ERR_INVALID_CONFIG,
            format!("Cannot read config file '{}': {e}", config_path.display()),
        )
        .with_suggestion("Check that the file exists and is readable.")
    })?;

    let toml_cfg: TomlConfig = toml::from_str(&raw).map_err(|e| {
        OlError::new(
            crate::error::ERR_INVALID_CONFIG,
            format!("Invalid TOML in config file: {e}"),
        )
        .with_suggestion("Check your config.toml for syntax errors.")
    })?;

    // If agent_id already exists, return it (idempotent)
    if let Some(ref daemon) = toml_cfg.daemon {
        if let Some(ref existing_id) = daemon.agent_id {
            return Ok(existing_id.clone());
        }
    }

    // Generate new agent_id
    let new_id = format!("agt_{}", uuid::Uuid::new_v4().simple());

    // Insert agent_id into the raw config string, preserving all other content.
    // Strategy: find [daemon] section, insert agent_id line after port line (or
    // after [daemon] header if no port line is present). If no [daemon] section,
    // append one.
    let updated_raw = insert_agent_id_into_toml(&raw, &new_id);

    std::fs::write(config_path, &updated_raw).map_err(|e| {
        OlError::new(
            crate::error::ERR_INVALID_CONFIG,
            format!("Cannot write config file '{}': {e}", config_path.display()),
        )
        .with_suggestion("Check that you have write permission to ~/.openlatch/.")
    })?;

    Ok(new_id)
}

/// Insert `agent_id = "..."` into TOML raw string, preserving all other content.
///
/// Finds the `[daemon]` section and inserts the agent_id line after the `port =`
/// line (or directly after `[daemon]` if no port line exists). If no `[daemon]`
/// section exists, appends one to the end.
fn insert_agent_id_into_toml(raw: &str, agent_id: &str) -> String {
    let agent_id_line = format!("agent_id = \"{agent_id}\"");

    // Find [daemon] section — look for a line that is exactly "[daemon]"
    let daemon_header_pos = raw
        .lines()
        .enumerate()
        .find(|(_, line)| line.trim() == "[daemon]")
        .map(|(idx, _)| idx);

    match daemon_header_pos {
        Some(daemon_idx) => {
            // [daemon] section found — find the best insertion point
            // Look for the last non-empty, non-comment line within the [daemon] section
            // (before the next section header or end of file)
            let lines: Vec<&str> = raw.lines().collect();
            let insert_after = find_insert_position(&lines, daemon_idx);

            // Rebuild the string with the new line inserted
            let mut result = String::with_capacity(raw.len() + agent_id_line.len() + 1);
            for (i, line) in lines.iter().enumerate() {
                result.push_str(line);
                result.push('\n');
                if i == insert_after {
                    result.push_str(&agent_id_line);
                    result.push('\n');
                }
            }
            result
        }
        None => {
            // No [daemon] section — append one
            let mut result = raw.to_string();
            if !result.ends_with('\n') {
                result.push('\n');
            }
            result.push_str("\n[daemon]\n");
            result.push_str(&agent_id_line);
            result.push('\n');
            result
        }
    }
}

/// Find the line index after which to insert agent_id within a [daemon] section.
///
/// Prefers inserting after `port = ...` if present; otherwise inserts after the
/// `[daemon]` header line itself.
fn find_insert_position(lines: &[&str], daemon_header_idx: usize) -> usize {
    // Walk forward from [daemon] header to find port line or next section
    let mut best = daemon_header_idx;
    for (i, line) in lines.iter().enumerate().skip(daemon_header_idx + 1) {
        let trimmed = line.trim();
        // Stop at next section header
        if trimmed.starts_with('[') {
            break;
        }
        // Track port line as best insertion point
        if trimmed.starts_with("port") {
            best = i;
            break;
        }
    }
    best
}

// ---------------------------------------------------------------------------
// Supervision state persistence
// ---------------------------------------------------------------------------

/// Persist supervision state into the `[supervision]` section of `config.toml`.
///
/// Updates (or creates) the section atomically via write-tmp + rename. Existing
/// content outside `[supervision]` is preserved.
///
/// # Arguments
///
/// - `config_path`: absolute path to `~/.openlatch/config.toml`.
/// - `mode`: `active`, `deferred`, or `disabled`.
/// - `backend`: `launchd`, `systemd`, `task_scheduler`, or `none`.
/// - `disabled_reason`: free-form reason (e.g., `user_opt_out`,
///   `foreground_session`, `headless_install_no_gui`).
pub fn persist_supervision_state(
    config_path: &Path,
    mode: &crate::supervision::SupervisionMode,
    backend: &crate::supervision::SupervisorKind,
    disabled_reason: Option<&str>,
) -> Result<(), OlError> {
    let mode_str = match mode {
        crate::supervision::SupervisionMode::Active => "active",
        crate::supervision::SupervisionMode::Deferred => "deferred",
        crate::supervision::SupervisionMode::Disabled => "disabled",
    };
    let backend_str = match backend {
        crate::supervision::SupervisorKind::Launchd => "launchd",
        crate::supervision::SupervisorKind::Systemd => "systemd",
        crate::supervision::SupervisorKind::TaskScheduler => "task_scheduler",
        crate::supervision::SupervisorKind::None => "none",
    };

    // Ensure config.toml exists so we have something to edit.
    if !config_path.exists() {
        if let Some(parent) = config_path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| {
                OlError::new(
                    ERR_INVALID_CONFIG,
                    format!("Cannot create config directory: {e}"),
                )
            })?;
        }
        std::fs::write(config_path, "").map_err(|e| {
            OlError::new(
                ERR_INVALID_CONFIG,
                format!("Cannot create config file: {e}"),
            )
        })?;
    }

    let raw = std::fs::read_to_string(config_path).map_err(|e| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!("Cannot read config file '{}': {e}", config_path.display()),
        )
    })?;

    let new_raw = rewrite_supervision_section(&raw, mode_str, backend_str, disabled_reason);

    // Atomic write: tmp + rename.
    let tmp_path = config_path.with_extension("toml.tmp");
    std::fs::write(&tmp_path, &new_raw)
        .map_err(|e| OlError::new(ERR_INVALID_CONFIG, format!("Cannot write config tmp: {e}")))?;
    std::fs::rename(&tmp_path, config_path)
        .map_err(|e| OlError::new(ERR_INVALID_CONFIG, format!("Cannot rename config tmp: {e}")))?;

    Ok(())
}

/// Rewrite (or insert) the `[supervision]` section of a TOML string.
///
/// Finds an existing `[supervision]` header (preserving both commented and
/// uncommented forms) and replaces the block up to the next section header.
/// If absent, appends a fresh section.
fn rewrite_supervision_section(
    raw: &str,
    mode: &str,
    backend: &str,
    disabled_reason: Option<&str>,
) -> String {
    let mut block = String::new();
    block.push_str("[supervision]\n");
    block.push_str(&format!("mode = \"{mode}\"\n"));
    block.push_str(&format!("backend = \"{backend}\"\n"));
    if let Some(reason) = disabled_reason {
        block.push_str(&format!("disabled_reason = \"{reason}\"\n"));
    }

    let lines: Vec<&str> = raw.lines().collect();
    let mut header_idx: Option<usize> = None;
    for (i, line) in lines.iter().enumerate() {
        let trimmed = line.trim();
        if trimmed == "[supervision]" || trimmed == "# [supervision]" {
            header_idx = Some(i);
            break;
        }
    }

    match header_idx {
        Some(start) => {
            // Find the next section header (uncommented) to know where to stop.
            let mut end = lines.len();
            for (i, line) in lines.iter().enumerate().skip(start + 1) {
                let trimmed = line.trim();
                if trimmed.starts_with('[') && !trimmed.starts_with("[supervision]") {
                    end = i;
                    break;
                }
            }
            let mut result = String::new();
            for line in lines.iter().take(start) {
                result.push_str(line);
                result.push('\n');
            }
            result.push_str(&block);
            for line in lines.iter().skip(end) {
                result.push_str(line);
                result.push('\n');
            }
            result
        }
        None => {
            let mut result = raw.to_string();
            if !result.is_empty() && !result.ends_with('\n') {
                result.push('\n');
            }
            if !result.is_empty() {
                result.push('\n');
            }
            result.push_str(&block);
            result
        }
    }
}

// ---------------------------------------------------------------------------
// Port probing and port file (PRD: probe 7443-7543 on first init)
// ---------------------------------------------------------------------------

/// Default port range start for probing.
pub const PORT_RANGE_START: u16 = 7443;
/// Default port range end for probing (inclusive).
pub const PORT_RANGE_END: u16 = 7543;

/// Probe ports in the given range, returning the first available port.
///
/// Uses a sync `std::net::TcpListener` bind-and-drop to test availability.
/// Safe to call before any async runtime is started.
///
/// # Errors
///
/// Returns `OL-1500` if no port in the range is free.
pub fn probe_free_port(start: u16, end: u16) -> Result<u16, OlError> {
    for port in start..=end {
        if std::net::TcpListener::bind(("127.0.0.1", port)).is_ok() {
            return Ok(port);
        }
    }
    Err(OlError::new(
        ERR_PORT_IN_USE,
        format!("No free port found in range {start}-{end}"),
    )
    .with_suggestion(format!(
        "Free a port in the {start}-{end} range, or set OPENLATCH_PORT to a specific port."
    ))
    .with_docs("https://docs.openlatch.ai/errors/OL-1500"))
}

/// Write the daemon's port number to `~/.openlatch/daemon.port`.
///
/// Plain text file containing just the port number. Readable by the hook binary
/// without TOML parsing.
pub fn write_port_file(port: u16) -> Result<(), OlError> {
    let path = openlatch_dir().join("daemon.port");
    std::fs::write(&path, port.to_string()).map_err(|e| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!("Cannot write port file '{}': {e}", path.display()),
        )
    })?;
    Ok(())
}

/// Read the daemon's port from `~/.openlatch/daemon.port`.
///
/// Returns `None` if the file doesn't exist or can't be parsed.
pub fn read_port_file() -> Option<u16> {
    let path = openlatch_dir().join("daemon.port");
    std::fs::read_to_string(path)
        .ok()?
        .trim()
        .parse::<u16>()
        .ok()
}

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

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

    #[test]
    fn test_config_defaults_values() {
        // Test 1: Config::defaults() returns expected values
        let cfg = Config::defaults();
        assert_eq!(cfg.port, 7443, "Default port must be 7443");
        assert_eq!(cfg.log_level, "info", "Default log level must be info");
        assert_eq!(cfg.retention_days, 30, "Default retention must be 30 days");
    }

    #[test]
    fn test_config_loads_from_toml_file() {
        // Test 2: Config loads from a TOML file in a temp directory
        let tmp = TempDir::new().unwrap();
        let config_path = tmp.path().join("config.toml");
        std::fs::write(
            &config_path,
            r#"
[daemon]
port = 8080
"#,
        )
        .unwrap();

        // Write a minimal config to the openlatch dir location by overriding
        // via env var (since Config::load reads from openlatch_dir())
        // We'll test the TOML parsing logic directly via env override
        // and by placing the file at the expected path.

        // Directly test the TOML parse path:
        let raw = std::fs::read_to_string(&config_path).unwrap();
        let toml_cfg: TomlConfig = toml::from_str(&raw).unwrap();
        let daemon = toml_cfg.daemon.unwrap();
        assert_eq!(daemon.port, Some(8080));
    }

    #[test]
    fn test_config_cli_port_overrides_default() {
        // Test 3: CLI port flag overrides default (avoids thread-unsafe env::set_var)
        let cfg = Config::load(Some(9000), None, false)
            .expect("Config::load should succeed with valid CLI port");
        assert_eq!(cfg.port, 9000, "CLI port should override default");
    }

    #[test]
    fn test_generate_token_produces_64_char_hex() {
        // Test 4: generate_token() produces a 32-byte hex string (64 chars)
        let token = generate_token();
        assert_eq!(
            token.len(),
            64,
            "Token must be 64 characters (32 bytes hex-encoded), got: {token}"
        );
        assert!(
            token.chars().all(|c| c.is_ascii_hexdigit()),
            "Token must be hex-encoded, got: {token}"
        );
    }

    #[test]
    fn test_ensure_token_creates_and_returns_token() {
        // Test 5: ensure_token() creates token file and returns token; second call reads existing
        let tmp = TempDir::new().unwrap();

        // First call: creates the file
        let token1 = ensure_token(tmp.path()).expect("First ensure_token call should succeed");
        assert_eq!(token1.len(), 64, "Generated token must be 64 chars");
        assert!(
            tmp.path().join("daemon.token").exists(),
            "Token file must be created"
        );

        // Second call: reads the existing file
        let token2 = ensure_token(tmp.path()).expect("Second ensure_token call should succeed");
        assert_eq!(token1, token2, "Second call must return the same token");
    }

    #[cfg(unix)]
    #[test]
    fn test_ensure_token_file_has_mode_0600() {
        // Test 6: On Unix, token file has mode 0o600
        use std::os::unix::fs::PermissionsExt;

        let tmp = TempDir::new().unwrap();
        ensure_token(tmp.path()).expect("ensure_token should succeed");

        let token_path = tmp.path().join("daemon.token");
        let metadata = std::fs::metadata(&token_path).unwrap();
        let mode = metadata.permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "Token file must have mode 0600, got: {mode:o}");
    }

    #[test]
    fn test_generate_default_config_toml_format() {
        // Test 7: generate_default_config_toml() contains "# [daemon]" (commented sections)
        // and "port = 7443" as the only uncommented value
        let content = generate_default_config_toml(7443);

        assert!(
            content.contains("port = 7443"),
            "Must contain active port line: {content}"
        );
        // The [daemon] section header is present (active)
        assert!(
            content.contains("[daemon]"),
            "Must contain [daemon] section: {content}"
        );
        // All other fields are commented
        assert!(
            content.contains("# level ="),
            "level must be commented out: {content}"
        );
        assert!(
            content.contains("# retention_days ="),
            "retention_days must be commented: {content}"
        );
    }

    #[test]
    fn test_config_extra_patterns_defaults_empty() {
        // Test 8: Config::extra_patterns field exists and defaults to empty vec
        let cfg = Config::defaults();
        assert!(
            cfg.extra_patterns.is_empty(),
            "Default extra_patterns must be empty"
        );
    }

    #[test]
    fn test_probe_free_port_finds_available_port() {
        // Probe a range — at least one port should be free on any test machine
        let port = probe_free_port(PORT_RANGE_START, PORT_RANGE_END)
            .expect("should find at least one free port");
        assert!((PORT_RANGE_START..=PORT_RANGE_END).contains(&port));
    }

    #[test]
    fn test_probe_free_port_skips_occupied_port() {
        // Bind a port, then probe a range starting at that port — should skip it
        let listener =
            std::net::TcpListener::bind(("127.0.0.1", 0)).expect("should bind to random port");
        let occupied = listener.local_addr().unwrap().port();

        // Probe a 1-port range with the occupied port — must fail
        let result = probe_free_port(occupied, occupied);
        assert!(
            result.is_err(),
            "must fail when only port in range is occupied"
        );

        // Probe a 2-port range — should find the next one
        if occupied < 65535 {
            let result = probe_free_port(occupied, occupied + 1);
            assert!(result.is_ok(), "should find next port after occupied one");
            assert_eq!(result.unwrap(), occupied + 1);
        }
    }

    #[test]
    fn test_write_and_read_port_file_round_trip() {
        let tmp = TempDir::new().unwrap();
        let port_path = tmp.path().join("daemon.port");

        // Write port file to temp location (test the format, not the path logic)
        std::fs::write(&port_path, "8080").unwrap();
        let content = std::fs::read_to_string(&port_path).unwrap();
        assert_eq!(content.trim().parse::<u16>().unwrap(), 8080);
    }

    // ---------------------------------------------------------------------------
    // Task 2: agent_id tests (TDD RED → GREEN)
    // ---------------------------------------------------------------------------

    #[test]
    fn test_ensure_agent_id_creates_agt_prefixed_id() {
        // ensure_agent_id() creates agent_id starting with "agt_" followed by 32 hex chars
        let tmp = TempDir::new().unwrap();
        let config_path = tmp.path().join("config.toml");
        std::fs::write(&config_path, "[daemon]\nport = 7443\n").unwrap();

        let mid = ensure_agent_id(&config_path).expect("ensure_agent_id should succeed");
        assert!(
            mid.starts_with("agt_"),
            "agent_id must start with 'agt_': {mid}"
        );
        let hex_part = &mid[4..]; // "agt_" is 4 chars
        assert_eq!(
            hex_part.len(),
            32,
            "hex part must be 32 chars (UUID simple): {mid}"
        );
        assert!(
            hex_part.chars().all(|c| c.is_ascii_hexdigit()),
            "hex part must be hex digits: {mid}"
        );
    }

    #[test]
    fn test_ensure_agent_id_is_idempotent() {
        // Second call to ensure_agent_id() returns the same value
        let tmp = TempDir::new().unwrap();
        let config_path = tmp.path().join("config.toml");
        std::fs::write(&config_path, "[daemon]\nport = 7443\n").unwrap();

        let mid1 = ensure_agent_id(&config_path).expect("first call should succeed");
        let mid2 = ensure_agent_id(&config_path).expect("second call should succeed");
        assert_eq!(mid1, mid2, "ensure_agent_id must be idempotent");
    }

    #[test]
    fn test_ensure_agent_id_preserves_port_value() {
        // ensure_agent_id() does not overwrite existing port in [daemon]
        let tmp = TempDir::new().unwrap();
        let config_path = tmp.path().join("config.toml");
        std::fs::write(&config_path, "[daemon]\nport = 8888\n").unwrap();

        ensure_agent_id(&config_path).expect("ensure_agent_id should succeed");

        let raw = std::fs::read_to_string(&config_path).unwrap();
        assert!(
            raw.contains("port = 8888"),
            "port must be preserved after ensure_agent_id: {raw}"
        );
    }

    #[test]
    fn test_config_reads_agent_id_from_daemon_section() {
        // Config struct has agent_id field; TOML [daemon].agent_id is parsed
        let toml_str = r#"
[daemon]
port = 7443
agent_id = "agt_abcdef1234567890abcdef1234567890"
"#;
        let toml_cfg: TomlConfig = toml::from_str(toml_str).unwrap();
        let daemon = toml_cfg.daemon.unwrap();
        assert_eq!(
            daemon.agent_id.as_deref(),
            Some("agt_abcdef1234567890abcdef1234567890")
        );
    }

    // ---------------------------------------------------------------------------
    // Task 1: CloudConfig tests (TDD RED → GREEN)
    // ---------------------------------------------------------------------------

    #[test]
    fn test_cloud_config_default_values() {
        // CloudConfig::default() must return all specified defaults
        let cfg = CloudConfig::default();
        assert!(cfg.enabled, "cloud.enabled default must be true");
        assert_eq!(
            cfg.api_url, "https://app.openlatch.ai/api",
            "cloud.api_url default must be https://app.openlatch.ai/api"
        );
        assert_eq!(
            cfg.timeout_connect_ms, 5000,
            "cloud.timeout_connect_ms default must be 5000"
        );
        assert_eq!(
            cfg.timeout_total_ms, 10000,
            "cloud.timeout_total_ms default must be 10000"
        );
        assert_eq!(cfg.retry_count, 1, "cloud.retry_count default must be 1");
        assert_eq!(
            cfg.retry_delay_ms, 2000,
            "cloud.retry_delay_ms default must be 2000"
        );
        assert_eq!(
            cfg.channel_size, 1000,
            "cloud.channel_size default must be 1000"
        );
    }

    #[test]
    fn test_config_defaults_includes_cloud_config() {
        // Config::defaults() must include a cloud field with CloudConfig defaults
        let cfg = Config::defaults();
        assert!(cfg.cloud.enabled);
        assert_eq!(cfg.cloud.api_url, "https://app.openlatch.ai/api");
        assert_eq!(cfg.cloud.timeout_connect_ms, 5000);
        assert_eq!(cfg.cloud.timeout_total_ms, 10000);
        assert_eq!(cfg.cloud.retry_count, 1);
        assert_eq!(cfg.cloud.retry_delay_ms, 2000);
        assert_eq!(cfg.cloud.channel_size, 1000);
    }

    #[test]
    fn test_config_load_no_cloud_section_returns_defaults() {
        // Config::load() with no [cloud] section must return CloudConfig default values
        // Parse TOML with only daemon section — no cloud section
        let toml_str = r#"
[daemon]
port = 7443
"#;
        let toml_cfg: TomlConfig = toml::from_str(toml_str).unwrap();
        assert!(
            toml_cfg.cloud.is_none(),
            "TomlConfig.cloud must be None when [cloud] is absent"
        );
    }

    #[test]
    fn test_config_load_parses_all_cloud_fields() {
        // Config::load() must parse all 7 cloud fields from [cloud] TOML section
        let toml_str = r#"
[cloud]
enabled = true
api_url = "https://custom.openlatch.ai"
timeout_connect_ms = 3000
timeout_total_ms = 8000
retry_count = 3
retry_delay_ms = 1000
channel_size = 500
"#;
        let toml_cfg: TomlConfig = toml::from_str(toml_str).unwrap();
        let cloud = toml_cfg.cloud.unwrap();
        assert_eq!(cloud.enabled, Some(true));
        assert_eq!(
            cloud.api_url.as_deref(),
            Some("https://custom.openlatch.ai")
        );
        assert_eq!(cloud.timeout_connect_ms, Some(3000));
        assert_eq!(cloud.timeout_total_ms, Some(8000));
        assert_eq!(cloud.retry_count, Some(3));
        assert_eq!(cloud.retry_delay_ms, Some(1000));
        assert_eq!(cloud.channel_size, Some(500));
    }

    #[test]
    fn test_config_load_partial_cloud_section_merges_with_defaults() {
        // Partial [cloud] section: only provided fields overridden, rest stay at defaults
        let toml_str = r#"
[cloud]
enabled = true
api_url = "https://staging.openlatch.ai"
"#;
        let toml_cfg: TomlConfig = toml::from_str(toml_str).unwrap();
        let cloud = toml_cfg.cloud.unwrap();
        // Provided fields must be Some
        assert_eq!(cloud.enabled, Some(true));
        assert_eq!(
            cloud.api_url.as_deref(),
            Some("https://staging.openlatch.ai")
        );
        // Unprovided fields must be None (merging with defaults happens in Config::load)
        assert!(cloud.timeout_connect_ms.is_none());
        assert!(cloud.retry_count.is_none());
    }

    #[test]
    fn test_supervision_toml_round_trip() {
        let toml_str = r#"
[supervision]
mode = "active"
backend = "launchd"
disabled_reason = "user_opt_out"
"#;
        let toml_cfg: TomlConfig = toml::from_str(toml_str).unwrap();
        let sup = toml_cfg.supervision.unwrap();
        assert_eq!(sup.mode.as_deref(), Some("active"));
        assert_eq!(sup.backend.as_deref(), Some("launchd"));
        assert_eq!(sup.disabled_reason.as_deref(), Some("user_opt_out"));
    }

    #[test]
    fn test_rewrite_supervision_section_appends_when_absent() {
        let raw = "[daemon]\nport = 7443\n";
        let out = rewrite_supervision_section(raw, "active", "launchd", None);
        assert!(out.contains("[supervision]"));
        assert!(out.contains("mode = \"active\""));
        assert!(out.contains("backend = \"launchd\""));
        assert!(!out.contains("disabled_reason"));
        assert!(out.contains("[daemon]"));
        assert!(out.contains("port = 7443"));
    }

    #[test]
    fn test_rewrite_supervision_section_replaces_existing() {
        let raw = "[daemon]\nport = 7443\n\n[supervision]\nmode = \"disabled\"\nbackend = \"none\"\ndisabled_reason = \"user_opt_out\"\n\n[cloud]\nenabled = false\n";
        let out = rewrite_supervision_section(raw, "active", "task_scheduler", None);
        assert!(out.contains("mode = \"active\""));
        assert!(out.contains("backend = \"task_scheduler\""));
        // Old reason removed since we passed None.
        assert!(!out.contains("user_opt_out"));
        // Other sections preserved.
        assert!(out.contains("[cloud]"));
        assert!(out.contains("enabled = false"));
    }

    #[test]
    fn test_rewrite_supervision_section_replaces_commented_header() {
        let raw = "[daemon]\nport = 7443\n\n# [supervision]\n# mode = \"disabled\"\n";
        let out = rewrite_supervision_section(raw, "active", "launchd", Some("ok"));
        assert!(out.contains("[supervision]"));
        assert!(out.contains("mode = \"active\""));
        // Commented template replaced, not duplicated.
        assert_eq!(out.matches("[supervision]").count(), 1);
    }

    #[test]
    fn test_persist_supervision_state_writes_to_disk() {
        use crate::supervision::{SupervisionMode, SupervisorKind};
        let tmp = TempDir::new().unwrap();
        let config_path = tmp.path().join("config.toml");
        std::fs::write(&config_path, "[daemon]\nport = 7443\n").unwrap();

        persist_supervision_state(
            &config_path,
            &SupervisionMode::Active,
            &SupervisorKind::Launchd,
            None,
        )
        .expect("persist should succeed");

        let raw = std::fs::read_to_string(&config_path).unwrap();
        assert!(raw.contains("[supervision]"));
        assert!(raw.contains("mode = \"active\""));
        assert!(raw.contains("backend = \"launchd\""));
    }

    #[test]
    fn test_generate_default_config_toml_contains_supervision_template() {
        let content = generate_default_config_toml(7443);
        assert!(
            content.contains("# [supervision]"),
            "Must contain commented [supervision] header: {content}"
        );
        assert!(
            content.contains("# mode = \"disabled\""),
            "Must contain commented mode line: {content}"
        );
    }

    #[test]
    fn test_generate_default_config_toml_contains_cloud_section() {
        // generate_default_config_toml() must contain commented [cloud] section
        let content = generate_default_config_toml(7443);
        assert!(
            content.contains("# [cloud]"),
            "Must contain commented [cloud] header: {content}"
        );
        assert!(
            content.contains("# enabled = true"),
            "Must contain commented enabled line: {content}"
        );
        assert!(
            content.contains("# api_url = \"https://app.openlatch.ai/api\""),
            "Must contain commented api_url line: {content}"
        );
        assert!(
            content.contains("# timeout_connect_ms = 5000"),
            "Must contain commented timeout_connect_ms line: {content}"
        );
        assert!(
            content.contains("# timeout_total_ms = 10000"),
            "Must contain commented timeout_total_ms line: {content}"
        );
        assert!(
            content.contains("# retry_count = 1"),
            "Must contain commented retry_count line: {content}"
        );
        assert!(
            content.contains("# retry_delay_ms = 2000"),
            "Must contain commented retry_delay_ms line: {content}"
        );
        assert!(
            content.contains("# channel_size = 1000"),
            "Must contain commented channel_size line: {content}"
        );
    }
}