stakpak 0.3.68

Stakpak: Your DevOps AI Agent. Generate infrastructure code, debug Kubernetes, configure CI/CD, automate deployments, without giving an LLM the keys to production.
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
//! Configuration parsing and validation for the autopilot service.
//!
//! Handles loading and validating `autopilot.toml` configuration files.

use super::db::RELOAD_SENTINEL;
use croner::Cron;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::time::Duration;

/// Default path for autopilot configuration file.
pub const STAKPAK_AUTOPILOT_CONFIG_PATH: &str = "~/.stakpak/autopilot.toml";

/// Main autopilot configuration structure.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScheduleConfig {
    /// Autopilot-level settings (database path, log directory).
    #[serde(default)]
    pub watch: ScheduleSettings,

    /// Default values for schedules.
    #[serde(default)]
    pub defaults: ScheduleDefaults,

    /// Optional outbound notifications routed through gateway API.
    #[serde(default)]
    pub notifications: Option<NotificationConfig>,

    /// List of scheduled schedules.
    #[serde(default)]
    pub schedules: Vec<Schedule>,
}

/// Autopilot-level settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScheduleSettings {
    /// Path to SQLite database file.
    #[serde(default = "default_db_path")]
    pub db_path: String,

    /// Directory for log files.
    #[serde(default = "default_log_dir")]
    pub log_dir: String,
}

impl Default for ScheduleSettings {
    fn default() -> Self {
        Self {
            db_path: default_db_path(),
            log_dir: default_log_dir(),
        }
    }
}

fn default_db_path() -> String {
    "~/.stakpak/autopilot/autopilot.db".to_string()
}

fn default_log_dir() -> String {
    "~/.stakpak/autopilot/logs".to_string()
}

/// Determines which check script exit codes trigger the agent.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CheckTriggerOn {
    /// Trigger agent only on exit code 0 (default behavior).
    #[default]
    Success,
    /// Trigger agent on any non-zero exit code (1+).
    Failure,
    /// Trigger agent regardless of exit code (only timeout/error prevents trigger).
    Any,
}

impl CheckTriggerOn {
    /// Returns true if the given exit code should trigger the agent.
    pub fn should_trigger(&self, exit_code: i32) -> bool {
        match self {
            CheckTriggerOn::Success => exit_code == 0,
            CheckTriggerOn::Failure => exit_code != 0,
            CheckTriggerOn::Any => true,
        }
    }
}

impl std::fmt::Display for CheckTriggerOn {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CheckTriggerOn::Success => write!(f, "success"),
            CheckTriggerOn::Failure => write!(f, "failure"),
            CheckTriggerOn::Any => write!(f, "any"),
        }
    }
}

/// Default values applied to schedules when not specified.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScheduleDefaults {
    /// Default profile to use for agent invocation.
    #[serde(default = "default_profile")]
    pub profile: String,

    /// Default timeout for agent execution.
    #[serde(default = "default_timeout", with = "humantime_serde")]
    pub timeout: Duration,

    /// Default timeout for check script execution.
    #[serde(default = "default_check_timeout", with = "humantime_serde")]
    pub check_timeout: Duration,

    /// Enable Slack tools for agent (experimental).
    #[serde(default)]
    pub enable_slack_tools: bool,

    /// Enable subagents for agent.
    #[serde(default)]
    pub enable_subagents: bool,

    /// Pause when tools require approval instead of auto-approving.
    /// When true, the agent will pause and exit with code 10 when tools need approval.
    #[serde(default = "default_pause_on_approval")]
    pub pause_on_approval: bool,

    /// Run agent tool calls inside a sandboxed warden container.
    #[serde(default)]
    pub sandbox: bool,

    /// Determines which check script exit codes trigger the agent.
    /// - "success" (default): trigger on exit 0
    /// - "failure": trigger on non-zero exit codes (1+)
    /// - "any": trigger regardless of exit code
    #[serde(default)]
    pub trigger_on: CheckTriggerOn,
}

impl Default for ScheduleDefaults {
    fn default() -> Self {
        Self {
            profile: default_profile(),
            timeout: default_timeout(),
            check_timeout: default_check_timeout(),
            enable_slack_tools: false,
            enable_subagents: false,
            pause_on_approval: default_pause_on_approval(),
            sandbox: false,
            trigger_on: CheckTriggerOn::default(),
        }
    }
}

fn default_profile() -> String {
    "default".to_string()
}

fn default_timeout() -> Duration {
    Duration::from_secs(30 * 60) // 30 minutes
}

fn default_check_timeout() -> Duration {
    Duration::from_secs(30) // 30 seconds
}

fn default_pause_on_approval() -> bool {
    false // Default to auto-approve, matching async mode default
}

fn default_schedule_enabled() -> bool {
    true
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NotificationConfig {
    pub gateway_url: String,
    #[serde(default)]
    pub gateway_token: Option<String>,
    #[serde(default)]
    pub notify_on: Option<NotifyOn>,
    #[serde(default)]
    pub channel: Option<String>,
    #[serde(default)]
    pub chat_id: Option<String>,
}

#[derive(Debug, Clone)]
pub struct DeliveryConfig {
    pub channel: String,
    pub chat_id: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum NotifyOn {
    All,
    Completions,
    Failures,
    None,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum InteractionMode {
    Silent,
    #[default]
    Interactive,
}

impl NotificationConfig {
    pub fn should_notify(&self, schedule: &Schedule, success: bool) -> bool {
        let mode = schedule
            .notify_on
            .or(self.notify_on)
            .unwrap_or(NotifyOn::All);
        match mode {
            NotifyOn::All => true,
            NotifyOn::Completions => success,
            NotifyOn::Failures => !success,
            NotifyOn::None => false,
        }
    }

    pub fn default_delivery(&self) -> Option<DeliveryConfig> {
        let channel = self.channel.as_ref()?;
        let chat_id = self.chat_id.as_ref()?;
        Some(DeliveryConfig {
            channel: channel.clone(),
            chat_id: chat_id.clone(),
        })
    }
}

/// A scheduled schedule that can wake the agent.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Schedule {
    /// Unique name for this schedule.
    pub name: String,

    /// Cron schedule expression (e.g., "*/15 * * * *").
    pub cron: String,

    /// Optional path to check script.
    /// If provided, script must exit 0 to wake agent.
    pub check: Option<String>,

    /// Timeout for check script execution.
    /// Falls back to defaults.check_timeout if not specified.
    #[serde(default, with = "option_humantime_serde")]
    pub check_timeout: Option<Duration>,

    /// Determines which check script exit codes trigger the agent.
    /// Falls back to defaults.trigger_on if not specified.
    /// - "success" (default): trigger on exit 0
    /// - "failure": trigger on non-zero exit codes (1+)
    /// - "any": trigger regardless of exit code
    pub trigger_on: Option<CheckTriggerOn>,

    /// Prompt to pass to the agent when triggered.
    pub prompt: String,

    /// Profile to use for agent invocation.
    /// Falls back to defaults.profile if not specified.
    pub profile: Option<String>,

    /// Optional board ID for task tracking.
    pub board_id: Option<String>,

    /// Timeout for agent execution.
    /// Falls back to defaults.timeout if not specified.
    #[serde(default, with = "option_humantime_serde")]
    pub timeout: Option<Duration>,

    /// Enable Slack tools for agent (experimental).
    /// Falls back to defaults.enable_slack_tools if not specified.
    pub enable_slack_tools: Option<bool>,

    /// Enable subagents for agent.
    /// Falls back to defaults.enable_subagents if not specified.
    pub enable_subagents: Option<bool>,

    /// Pause when tools require approval instead of auto-approving.
    /// Falls back to defaults.pause_on_approval if not specified.
    pub pause_on_approval: Option<bool>,

    /// Run agent tool calls inside a sandboxed warden container.
    /// Falls back to defaults.sandbox if not specified.
    pub sandbox: Option<bool>,

    /// Notification mode override for this schedule.
    pub notify_on: Option<NotifyOn>,

    /// Notification delivery channel override.
    pub notify_channel: Option<String>,

    /// Notification chat target override.
    pub notify_chat_id: Option<String>,

    /// Interactive execution mode.
    #[serde(default)]
    pub interaction: InteractionMode,

    /// Whether this schedule is active.
    #[serde(default = "default_schedule_enabled")]
    pub enabled: bool,
}

impl Schedule {
    /// Get the effective profile, falling back to defaults.
    pub fn effective_profile<'a>(&'a self, defaults: &'a ScheduleDefaults) -> &'a str {
        self.profile.as_deref().unwrap_or(&defaults.profile)
    }

    /// Get the effective timeout, falling back to defaults.
    pub fn effective_timeout(&self, defaults: &ScheduleDefaults) -> Duration {
        self.timeout.unwrap_or(defaults.timeout)
    }

    /// Get the effective check timeout, falling back to defaults.
    pub fn effective_check_timeout(&self, defaults: &ScheduleDefaults) -> Duration {
        self.check_timeout.unwrap_or(defaults.check_timeout)
    }

    /// Get the effective trigger_on, falling back to defaults.
    pub fn effective_trigger_on(&self, defaults: &ScheduleDefaults) -> CheckTriggerOn {
        self.trigger_on.unwrap_or(defaults.trigger_on)
    }

    /// Get the effective enable_slack_tools, falling back to defaults.
    pub fn effective_enable_slack_tools(&self, defaults: &ScheduleDefaults) -> bool {
        self.enable_slack_tools
            .unwrap_or(defaults.enable_slack_tools)
    }

    /// Get the effective enable_subagents, falling back to defaults.
    pub fn effective_enable_subagents(&self, defaults: &ScheduleDefaults) -> bool {
        self.enable_subagents.unwrap_or(defaults.enable_subagents)
    }

    /// Get the effective pause_on_approval, falling back to defaults.
    pub fn effective_pause_on_approval(&self, defaults: &ScheduleDefaults) -> bool {
        self.pause_on_approval.unwrap_or(defaults.pause_on_approval)
    }

    /// Get the effective sandbox, falling back to defaults.
    pub fn effective_sandbox(&self, defaults: &ScheduleDefaults) -> bool {
        self.sandbox.unwrap_or(defaults.sandbox)
    }

    /// Resolve notification delivery target using schedule overrides and global defaults.
    pub fn effective_delivery(&self, notifications: &NotificationConfig) -> Option<DeliveryConfig> {
        let channel = self
            .notify_channel
            .as_ref()
            .cloned()
            .or_else(|| notifications.channel.clone())?;

        let chat_id = self
            .notify_chat_id
            .as_ref()
            .cloned()
            .or_else(|| notifications.chat_id.clone())?;

        Some(DeliveryConfig { channel, chat_id })
    }
}

/// Custom serde module for Option<Duration> with humantime format.
mod option_humantime_serde {
    use serde::{Deserialize, Deserializer, Serialize, Serializer};
    use std::time::Duration;

    pub fn serialize<S>(value: &Option<Duration>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match value {
            Some(d) => {
                let s = humantime::format_duration(*d).to_string();
                s.serialize(serializer)
            }
            None => serializer.serialize_none(),
        }
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Duration>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let opt: Option<String> = Option::deserialize(deserializer)?;
        match opt {
            Some(s) => humantime::parse_duration(&s)
                .map(Some)
                .map_err(serde::de::Error::custom),
            None => Ok(None),
        }
    }
}

/// Errors that can occur during config loading and validation.
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
    #[error("Failed to read config file: {0}")]
    ReadError(#[from] std::io::Error),

    #[error("Failed to parse config file: {0}")]
    ParseError(#[from] toml::de::Error),

    #[error("Invalid cron expression '{expression}' for schedule '{schedule}': {message}")]
    InvalidCron {
        schedule: String,
        expression: String,
        message: String,
    },

    #[error("Duplicate schedule name: '{0}'")]
    DuplicateScheduleName(String),

    #[error("Schedule name '{0}' is reserved")]
    ReservedScheduleName(String),

    #[error("Check script not found for schedule '{schedule}': {path}")]
    CheckScriptNotFound { schedule: String, path: String },

    #[error(
        "Cannot expand '~' in check script path for schedule '{schedule}': {path}. Home directory for the running user could not be determined; use an absolute path."
    )]
    CheckScriptHomeDirUnavailable { schedule: String, path: String },

    #[error(
        "Cannot expand '~' in path: {path}. Home directory for the running user could not be determined; use an absolute path."
    )]
    PathHomeDirUnavailable { path: String },

    #[error("Schedule '{0}' is missing required field: {1}")]
    MissingRequiredField(String, String),
}

impl ScheduleConfig {
    /// Load configuration from the default path (~/.stakpak/autopilot.toml).
    pub fn load_default() -> Result<Self, ConfigError> {
        let path = expand_tilde_for_path(Path::new(STAKPAK_AUTOPILOT_CONFIG_PATH))?;
        Self::load(&path)
    }

    /// Load configuration from a specific path.
    pub fn load<P: AsRef<Path>>(path: P) -> Result<Self, ConfigError> {
        let content = std::fs::read_to_string(path.as_ref())?;
        let config: ScheduleConfig = toml::from_str(&content)?;
        config.validate()?;
        Ok(config)
    }

    /// Parse configuration from a string (useful for testing).
    pub fn parse(content: &str) -> Result<Self, ConfigError> {
        let config: ScheduleConfig = toml::from_str(content)?;
        config.validate()?;
        Ok(config)
    }

    /// Validate the configuration.
    pub fn validate(&self) -> Result<(), ConfigError> {
        self.validate_unique_schedule_names()?;
        self.validate_reserved_schedule_names()?;
        self.validate_cron_expressions()?;
        self.validate_runtime_paths()?;
        self.validate_check_scripts()?;
        Ok(())
    }

    /// Ensure all schedule names are unique.
    fn validate_unique_schedule_names(&self) -> Result<(), ConfigError> {
        let mut seen = HashSet::new();
        for schedule in &self.schedules {
            if !seen.insert(&schedule.name) {
                return Err(ConfigError::DuplicateScheduleName(schedule.name.clone()));
            }
        }
        Ok(())
    }

    /// Ensure no reserved schedule names are used.
    fn validate_reserved_schedule_names(&self) -> Result<(), ConfigError> {
        for schedule in &self.schedules {
            if schedule.name.trim() == RELOAD_SENTINEL {
                return Err(ConfigError::ReservedScheduleName(schedule.name.clone()));
            }
        }
        Ok(())
    }

    /// Validate all cron expressions are parseable.
    fn validate_cron_expressions(&self) -> Result<(), ConfigError> {
        for schedule in &self.schedules {
            if let Err(e) = Cron::from_str(&schedule.cron) {
                return Err(ConfigError::InvalidCron {
                    schedule: schedule.name.clone(),
                    expression: schedule.cron.clone(),
                    message: e.to_string(),
                });
            }
        }
        Ok(())
    }

    /// Validate top-level runtime paths expand cleanly.
    fn validate_runtime_paths(&self) -> Result<(), ConfigError> {
        expand_tilde_for_path(Path::new(&self.watch.db_path))?;
        expand_tilde_for_path(Path::new(&self.watch.log_dir))?;
        Ok(())
    }

    /// Validate check script paths exist (if specified).
    fn validate_check_scripts(&self) -> Result<(), ConfigError> {
        for schedule in &self.schedules {
            if let Some(check_path) = &schedule.check {
                let expanded =
                    expand_tilde_for_check_path(Path::new(check_path), schedule.name.as_str())?;
                if !expanded.exists() {
                    return Err(ConfigError::CheckScriptNotFound {
                        schedule: schedule.name.clone(),
                        path: check_path.clone(),
                    });
                }
            }
        }
        Ok(())
    }

    /// Get the expanded database path.
    pub fn db_path(&self) -> PathBuf {
        expand_tilde(&self.watch.db_path)
    }

    /// Get the expanded log directory path.
    pub fn log_dir(&self) -> PathBuf {
        expand_tilde(&self.watch.log_dir)
    }

    /// Inject runtime-generated gateway credentials into the notification config.
    ///
    /// The gateway auth token is generated fresh each `stakpak up` and never
    /// persisted to disk.  Without this patch the scheduler would read a stale
    /// (or absent) `gateway_token` from `autopilot.toml` and get 401s on every
    /// `POST /v1/gateway/send` call.
    ///
    /// This must be called after every config load (initial *and* hot-reload)
    /// so that the in-memory config always carries the current runtime token.
    pub fn apply_runtime_gateway_credentials(&mut self, url: &str, token: &str) {
        if let Some(ref mut notifications) = self.notifications {
            // Always override the token — disk value is never authoritative.
            // Trim to avoid storing whitespace-only tokens that would cause
            // auth failures downstream (symmetric with the URL path below).
            let trimmed = token.trim();
            if !trimmed.is_empty() {
                notifications.gateway_token = Some(trimmed.to_string());
            }
            // Fill the URL only when missing/empty; the user may have set a
            // custom external gateway URL that should be preserved.
            if notifications.gateway_url.trim().is_empty() {
                notifications.gateway_url = url.to_string();
            }
        }
    }

    /// True when notifications are configured to local loopback gateway URL.
    pub fn notifications_points_to_local_loopback(&self) -> bool {
        let Some(notifications) = &self.notifications else {
            return false;
        };

        let url = notifications.gateway_url.to_ascii_lowercase();
        url.contains("127.0.0.1") || url.contains("localhost")
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TildeExpansionError {
    HomeDirUnavailable,
}

fn current_user_home_dir() -> Option<PathBuf> {
    dirs::home_dir().or_else(resolve_home_dir_from_system)
}

#[cfg(unix)]
fn resolve_home_dir_from_system() -> Option<PathBuf> {
    use std::ffi::{CStr, OsStr};
    use std::os::unix::ffi::OsStrExt;
    use std::ptr;

    // Fallback for environments where HOME is missing: ask the OS for the
    // effective user's passwd entry directly.
    unsafe {
        let uid = libc::geteuid();
        let mut pwd: libc::passwd = std::mem::zeroed();
        let mut result: *mut libc::passwd = ptr::null_mut();

        let mut buf_len = libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX);
        if buf_len <= 0 {
            buf_len = 4096;
        }
        let mut buf_len = usize::try_from(buf_len).unwrap_or(4096).max(1024);
        let mut buf = vec![0u8; buf_len];

        let rc = loop {
            let rc = libc::getpwuid_r(
                uid,
                &mut pwd,
                buf.as_mut_ptr().cast(),
                buf.len(),
                &mut result,
            );

            if rc == libc::ERANGE && buf_len < 65536 {
                buf_len *= 2;
                buf.resize(buf_len, 0);
                continue;
            }
            break rc;
        };

        if rc != 0 || result.is_null() || pwd.pw_dir.is_null() {
            return None;
        }

        let home_cstr = CStr::from_ptr(pwd.pw_dir);
        let home_os = OsStr::from_bytes(home_cstr.to_bytes());
        Some(PathBuf::from(home_os))
    }
}

#[cfg(not(unix))]
fn resolve_home_dir_from_system() -> Option<PathBuf> {
    None
}

fn expand_tilde_with_home(
    path: &Path,
    home: Option<&Path>,
) -> Result<PathBuf, TildeExpansionError> {
    let path_str = path.to_string_lossy();

    if path_str == "~" {
        return home
            .map(Path::to_path_buf)
            .ok_or(TildeExpansionError::HomeDirUnavailable);
    }

    if let Some(stripped) = path_str
        .strip_prefix("~/")
        .or_else(|| path_str.strip_prefix("~\\"))
    {
        return home
            .map(|home_dir| home_dir.join(stripped))
            .ok_or(TildeExpansionError::HomeDirUnavailable);
    }

    Ok(path.to_path_buf())
}

fn expand_tilde_for_path(path: &Path) -> Result<PathBuf, ConfigError> {
    let home = current_user_home_dir();
    expand_tilde_with_home(path, home.as_deref()).map_err(|_| ConfigError::PathHomeDirUnavailable {
        path: path.to_string_lossy().into_owned(),
    })
}

fn expand_tilde_for_check_path(path: &Path, schedule_name: &str) -> Result<PathBuf, ConfigError> {
    let home = current_user_home_dir();
    expand_tilde_with_home(path, home.as_deref()).map_err(|_| {
        ConfigError::CheckScriptHomeDirUnavailable {
            schedule: schedule_name.to_string(),
            path: path.to_string_lossy().into_owned(),
        }
    })
}

/// Expand ~ to home directory in paths.
pub fn expand_tilde<P: AsRef<Path>>(path: P) -> PathBuf {
    let path_ref = path.as_ref();
    let home = current_user_home_dir();
    expand_tilde_with_home(path_ref, home.as_deref()).unwrap_or_else(|_| path_ref.to_path_buf())
}

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

    #[test]
    fn test_parse_valid_config() {
        let config_str = r#"
[watch]
db_path = "~/.stakpak/autopilot/autopilot.db"
log_dir = "~/.stakpak/autopilot/logs"

[defaults]
profile = "production"
timeout = "1h"
check_timeout = "1m"

[[schedules]]
name = "disk-cleanup"
cron = "*/15 * * * *"
prompt = "Check disk usage and clean up if needed"
profile = "maintenance"
timeout = "45m"

[[schedules]]
name = "health-check"
cron = "0 * * * *"
prompt = "Run health checks"
board_id = "board_123"
"#;

        let config = ScheduleConfig::parse(config_str).expect("Should parse valid config");

        assert_eq!(config.watch.db_path, "~/.stakpak/autopilot/autopilot.db");
        assert_eq!(config.defaults.profile, "production");
        assert_eq!(config.defaults.timeout, Duration::from_secs(3600));
        assert_eq!(config.defaults.check_timeout, Duration::from_secs(60));
        assert_eq!(config.schedules.len(), 2);

        let schedule1 = &config.schedules[0];
        assert_eq!(schedule1.name, "disk-cleanup");
        assert_eq!(schedule1.cron, "*/15 * * * *");
        assert_eq!(schedule1.profile, Some("maintenance".to_string()));
        assert_eq!(schedule1.timeout, Some(Duration::from_secs(45 * 60)));

        let schedule2 = &config.schedules[1];
        assert_eq!(schedule2.name, "health-check");
        assert_eq!(schedule2.board_id, Some("board_123".to_string()));
        // Should use defaults
        assert_eq!(schedule2.effective_profile(&config.defaults), "production");
    }

    #[test]
    fn test_parse_minimal_config() {
        let config_str = r#"
[[schedules]]
name = "simple"
cron = "0 0 * * *"
prompt = "Do something"
"#;

        let config = ScheduleConfig::parse(config_str).expect("Should parse minimal config");

        // Check defaults are applied
        assert_eq!(config.watch.db_path, "~/.stakpak/autopilot/autopilot.db");
        assert_eq!(config.defaults.profile, "default");
        assert_eq!(config.defaults.timeout, Duration::from_secs(30 * 60));
        assert_eq!(config.schedules.len(), 1);
    }

    #[test]
    fn test_invalid_cron() {
        let config_str = r#"
[[schedules]]
name = "bad-cron"
cron = "invalid cron expression"
prompt = "This should fail"
"#;

        let result = ScheduleConfig::parse(config_str);
        assert!(result.is_err());

        let err = result.unwrap_err();
        assert!(matches!(err, ConfigError::InvalidCron { .. }));
        if let ConfigError::InvalidCron { schedule, .. } = err {
            assert_eq!(schedule, "bad-cron");
        }
    }

    #[test]
    fn test_duplicate_schedule_names() {
        let config_str = r#"
[[schedules]]
name = "duplicate"
cron = "0 * * * *"
prompt = "First"

[[schedules]]
name = "duplicate"
cron = "0 0 * * *"
prompt = "Second"
"#;

        let result = ScheduleConfig::parse(config_str);
        assert!(result.is_err());

        let err = result.unwrap_err();
        assert!(matches!(err, ConfigError::DuplicateScheduleName(_)));
        if let ConfigError::DuplicateScheduleName(name) = err {
            assert_eq!(name, "duplicate");
        }
    }

    #[test]
    fn test_reserved_schedule_name_rejected() {
        let config_str = r#"
[[schedules]]
name = "__config_reload__"
cron = "0 * * * *"
prompt = "Reserved"
"#;

        let result = ScheduleConfig::parse(config_str);
        assert!(result.is_err());

        let err = result.unwrap_err();
        assert!(matches!(err, ConfigError::ReservedScheduleName(_)));
        if let ConfigError::ReservedScheduleName(name) = err {
            assert_eq!(name, "__config_reload__");
        }
    }

    #[test]
    fn test_path_expansion() {
        let expanded = expand_tilde("~/test/path");
        assert!(!expanded.to_string_lossy().starts_with("~"));

        let home = dirs::home_dir().expect("Should have home dir");
        assert!(expanded.starts_with(&home));
        assert!(expanded.ends_with("test/path"));
    }

    #[test]
    fn test_expand_tilde_with_home_requires_home_for_tilde_paths() {
        let result = expand_tilde_with_home(Path::new("~/test/path"), None);
        assert_eq!(result, Err(TildeExpansionError::HomeDirUnavailable));
    }

    #[test]
    fn test_expand_tilde_with_home_passthrough_for_non_tilde_paths() {
        let input = Path::new("/tmp/check.sh");
        let result = expand_tilde_with_home(input, None);
        assert_eq!(result, Ok(input.to_path_buf()));
    }

    #[test]
    fn test_default_values() {
        let config_str = r#"
[[schedules]]
name = "test"
cron = "0 0 * * *"
prompt = "Test prompt"
"#;

        let config = ScheduleConfig::parse(config_str).expect("Should parse");
        let schedule = &config.schedules[0];

        // Verify defaults are used
        assert_eq!(schedule.effective_profile(&config.defaults), "default");
        assert_eq!(
            schedule.effective_timeout(&config.defaults),
            Duration::from_secs(30 * 60)
        );
        assert_eq!(
            schedule.effective_check_timeout(&config.defaults),
            Duration::from_secs(30)
        );
    }

    #[test]
    fn test_various_cron_expressions() {
        // Test various valid cron expressions (standard 5-part: min hour day month weekday)
        let expressions = [
            "* * * * *",     // Every minute
            "*/5 * * * *",   // Every 5 minutes
            "0 0 * * *",     // Daily at midnight
            "0 0 * * 0",     // Weekly on Sunday
            "0 0 1 * *",     // Monthly on 1st
            "0 0 1 1 *",     // Yearly on Jan 1st
            "30 4 1,15 * *", // 4:30 AM on 1st and 15th
            "0 0-5 * * *",   // Midnight to 5 AM hourly
            "0 0 * * 1-5",   // Weekdays at midnight
            "0 9 * * 1-5",   // Weekdays at 9 AM
        ];

        for expr in expressions {
            let config_str = format!(
                r#"
[[schedules]]
name = "test"
cron = "{}"
prompt = "Test"
"#,
                expr
            );

            let result = ScheduleConfig::parse(&config_str);
            assert!(
                result.is_ok(),
                "Should parse valid cron expression: {}",
                expr
            );
        }
    }

    #[test]
    fn test_humantime_durations() {
        let config_str = r#"
[defaults]
timeout = "2h 30m"
check_timeout = "45s"

[[schedules]]
name = "test"
cron = "0 0 * * *"
prompt = "Test"
timeout = "1h 15m 30s"
check_timeout = "2m"
"#;

        let config = ScheduleConfig::parse(config_str).expect("Should parse humantime durations");

        assert_eq!(
            config.defaults.timeout,
            Duration::from_secs(2 * 3600 + 30 * 60)
        );
        assert_eq!(config.defaults.check_timeout, Duration::from_secs(45));

        let schedule = &config.schedules[0];
        assert_eq!(
            schedule.timeout,
            Some(Duration::from_secs(3600 + 15 * 60 + 30))
        );
        assert_eq!(schedule.check_timeout, Some(Duration::from_secs(120)));
    }

    #[test]
    fn test_empty_schedules() {
        let config_str = r#"
[watch]
db_path = "/custom/path/watch.db"
"#;

        let config =
            ScheduleConfig::parse(config_str).expect("Should parse config with no schedules");
        assert!(config.schedules.is_empty());
    }

    #[test]
    fn test_check_script_not_found() {
        let config_str = r#"
[[schedules]]
name = "with-check"
cron = "0 * * * *"
prompt = "Test"
check = "/nonexistent/path/to/script.sh"
"#;

        let result = ScheduleConfig::parse(config_str);
        assert!(result.is_err());

        let err = result.unwrap_err();
        assert!(matches!(err, ConfigError::CheckScriptNotFound { .. }));
        if let ConfigError::CheckScriptNotFound { schedule, path } = err {
            assert_eq!(schedule, "with-check");
            assert_eq!(path, "/nonexistent/path/to/script.sh");
        }
    }

    #[test]
    fn test_missing_required_field_name() {
        let config_str = r#"
[[schedules]]
cron = "0 * * * *"
prompt = "Test"
"#;

        let result = ScheduleConfig::parse(config_str);
        assert!(result.is_err());
        // Should fail at TOML parsing level due to missing required field
        assert!(matches!(result.unwrap_err(), ConfigError::ParseError(_)));
    }

    #[test]
    fn test_missing_required_field_cron() {
        let config_str = r#"
[[schedules]]
name = "test"
prompt = "Test"
"#;

        let result = ScheduleConfig::parse(config_str);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), ConfigError::ParseError(_)));
    }

    #[test]
    fn test_missing_required_field_prompt() {
        let config_str = r#"
[[schedules]]
name = "test"
cron = "0 * * * *"
"#;

        let result = ScheduleConfig::parse(config_str);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), ConfigError::ParseError(_)));
    }

    #[test]
    fn test_check_trigger_on_should_trigger() {
        // Success mode: only exit 0 triggers
        assert!(CheckTriggerOn::Success.should_trigger(0));
        assert!(!CheckTriggerOn::Success.should_trigger(1));
        assert!(!CheckTriggerOn::Success.should_trigger(2));
        assert!(!CheckTriggerOn::Success.should_trigger(-1));

        // Failure mode: any non-zero triggers
        assert!(!CheckTriggerOn::Failure.should_trigger(0));
        assert!(CheckTriggerOn::Failure.should_trigger(1));
        assert!(CheckTriggerOn::Failure.should_trigger(2));
        assert!(CheckTriggerOn::Failure.should_trigger(-1));

        // Any mode: all exit codes trigger
        assert!(CheckTriggerOn::Any.should_trigger(0));
        assert!(CheckTriggerOn::Any.should_trigger(1));
        assert!(CheckTriggerOn::Any.should_trigger(2));
        assert!(CheckTriggerOn::Any.should_trigger(-1));
    }

    #[test]
    fn test_check_trigger_on_default() {
        assert_eq!(CheckTriggerOn::default(), CheckTriggerOn::Success);
    }

    #[test]
    fn test_check_trigger_on_display() {
        assert_eq!(CheckTriggerOn::Success.to_string(), "success");
        assert_eq!(CheckTriggerOn::Failure.to_string(), "failure");
        assert_eq!(CheckTriggerOn::Any.to_string(), "any");
    }

    #[test]
    fn test_check_trigger_on_parsing() {
        // Test parsing from TOML
        let config_str = r#"
[[schedules]]
name = "success-trigger"
cron = "0 * * * *"
prompt = "Test"
trigger_on = "success"

[[schedules]]
name = "failure-trigger"
cron = "0 * * * *"
prompt = "Test"
trigger_on = "failure"

[[schedules]]
name = "any-trigger"
cron = "0 * * * *"
prompt = "Test"
trigger_on = "any"

[[schedules]]
name = "default-trigger"
cron = "0 * * * *"
prompt = "Test"
"#;

        let config = ScheduleConfig::parse(config_str).expect("Should parse trigger_on values");
        assert_eq!(config.schedules.len(), 4);

        assert_eq!(
            config.schedules[0].trigger_on,
            Some(CheckTriggerOn::Success)
        );
        assert_eq!(
            config.schedules[1].trigger_on,
            Some(CheckTriggerOn::Failure)
        );
        assert_eq!(config.schedules[2].trigger_on, Some(CheckTriggerOn::Any));
        assert_eq!(config.schedules[3].trigger_on, None);
    }

    #[test]
    fn test_check_trigger_on_defaults_fallback() {
        let config_str = r#"
[defaults]
trigger_on = "failure"

[[schedules]]
name = "uses-default"
cron = "0 * * * *"
prompt = "Test"

[[schedules]]
name = "overrides-default"
cron = "0 * * * *"
prompt = "Test"
trigger_on = "success"
"#;

        let config =
            ScheduleConfig::parse(config_str).expect("Should parse trigger_on with defaults");

        // First schedule should use default (failure)
        assert_eq!(
            config.schedules[0].effective_trigger_on(&config.defaults),
            CheckTriggerOn::Failure
        );

        // Second schedule should override to success
        assert_eq!(
            config.schedules[1].effective_trigger_on(&config.defaults),
            CheckTriggerOn::Success
        );
    }

    #[test]
    fn test_trigger_on_invalid_value() {
        let config_str = r#"
[[schedules]]
name = "invalid"
cron = "0 * * * *"
prompt = "Test"
trigger_on = "invalid"
"#;

        let result = ScheduleConfig::parse(config_str);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), ConfigError::ParseError(_)));
    }

    #[test]
    fn test_interaction_defaults_to_interactive() {
        let config_str = r#"
[[schedules]]
name = "default-interaction"
cron = "0 * * * *"
prompt = "Test"
"#;

        let config = ScheduleConfig::parse(config_str).expect("config should parse");
        assert_eq!(
            config.schedules[0].interaction,
            InteractionMode::Interactive
        );
    }

    #[test]
    fn test_interaction_can_be_silent() {
        let config_str = r#"
[[schedules]]
name = "silent"
cron = "0 * * * *"
prompt = "Test"
interaction = "silent"
"#;

        let config = ScheduleConfig::parse(config_str).expect("config should parse");
        assert_eq!(config.schedules[0].interaction, InteractionMode::Silent);
    }

    // ========================================================================
    // apply_runtime_gateway_credentials tests
    // ========================================================================

    fn config_with_notifications(gateway_url: &str, gateway_token: Option<&str>) -> ScheduleConfig {
        let config_str = format!(
            r##"
[notifications]
gateway_url = "{gateway_url}"
channel = "slack"
chat_id = "#ops"

[[schedules]]
name = "test"
cron = "0 * * * *"
prompt = "test"
"##,
        );
        let mut config = ScheduleConfig::parse(&config_str).expect("config should parse");
        if let Some(ref mut n) = config.notifications {
            n.gateway_token = gateway_token.map(String::from);
        }
        config
    }

    fn config_without_notifications() -> ScheduleConfig {
        let config_str = r##"
[[schedules]]
name = "test"
cron = "0 * * * *"
prompt = "test"
"##;
        ScheduleConfig::parse(config_str).expect("config should parse")
    }

    #[test]
    fn test_apply_credentials_injects_token_when_missing() {
        let mut config = config_with_notifications("http://127.0.0.1:4096", None);
        assert!(
            config
                .notifications
                .as_ref()
                .expect("notifications should exist")
                .gateway_token
                .is_none()
        );

        config
            .apply_runtime_gateway_credentials("http://127.0.0.1:4096", "runtime-secret-token-abc");

        let notifications = config.notifications.expect("notifications should exist");
        assert_eq!(
            notifications.gateway_token.as_deref(),
            Some("runtime-secret-token-abc"),
            "runtime token should be injected"
        );
    }

    #[test]
    fn test_apply_credentials_overwrites_stale_disk_token() {
        let mut config = config_with_notifications(
            "http://127.0.0.1:4096",
            Some("stale-token-from-previous-run"),
        );

        config.apply_runtime_gateway_credentials("http://127.0.0.1:4096", "fresh-runtime-token");

        let notifications = config.notifications.expect("notifications should exist");
        assert_eq!(
            notifications.gateway_token.as_deref(),
            Some("fresh-runtime-token"),
            "stale disk token should be overwritten by runtime token"
        );
    }

    #[test]
    fn test_apply_credentials_preserves_custom_gateway_url() {
        let custom_url = "https://gateway.example.com";
        let mut config = config_with_notifications(custom_url, None);

        config.apply_runtime_gateway_credentials("http://127.0.0.1:4096", "runtime-token");

        let notifications = config.notifications.expect("notifications should exist");
        assert_eq!(
            notifications.gateway_url, custom_url,
            "user-configured external gateway URL should not be overwritten"
        );
        assert_eq!(
            notifications.gateway_token.as_deref(),
            Some("runtime-token"),
        );
    }

    #[test]
    fn test_apply_credentials_fills_empty_gateway_url() {
        let mut config = config_with_notifications("", None);

        config.apply_runtime_gateway_credentials("http://127.0.0.1:5555", "runtime-token");

        let notifications = config.notifications.expect("notifications should exist");
        assert_eq!(
            notifications.gateway_url, "http://127.0.0.1:5555",
            "empty gateway_url should be filled from runtime"
        );
    }

    #[test]
    fn test_apply_credentials_fills_whitespace_only_gateway_url() {
        let config_str = r##"
[notifications]
gateway_url = "   "
channel = "slack"
chat_id = "#ops"

[[schedules]]
name = "test"
cron = "0 * * * *"
prompt = "test"
"##;
        let mut config = ScheduleConfig::parse(config_str).expect("config should parse");

        config.apply_runtime_gateway_credentials("http://127.0.0.1:4096", "runtime-token");

        let notifications = config.notifications.expect("notifications should exist");
        assert_eq!(
            notifications.gateway_url, "http://127.0.0.1:4096",
            "whitespace-only gateway_url should be replaced"
        );
    }

    #[test]
    fn test_apply_credentials_noop_without_notifications_section() {
        let mut config = config_without_notifications();
        assert!(config.notifications.is_none());

        // Should not panic or create a notifications section.
        config.apply_runtime_gateway_credentials("http://127.0.0.1:4096", "runtime-token");

        assert!(
            config.notifications.is_none(),
            "should not fabricate a notifications section"
        );
    }

    #[test]
    fn test_apply_credentials_skips_empty_runtime_token() {
        let mut config = config_with_notifications("http://127.0.0.1:4096", Some("existing-token"));

        config.apply_runtime_gateway_credentials("http://127.0.0.1:4096", "");

        let notifications = config.notifications.expect("notifications should exist");
        assert_eq!(
            notifications.gateway_token.as_deref(),
            Some("existing-token"),
            "empty runtime token should not overwrite an existing token"
        );
    }

    #[test]
    fn test_apply_credentials_skips_whitespace_only_runtime_token() {
        let mut config = config_with_notifications("http://127.0.0.1:4096", Some("existing-token"));

        config.apply_runtime_gateway_credentials("http://127.0.0.1:4096", "   ");

        let notifications = config.notifications.expect("notifications should exist");
        assert_eq!(
            notifications.gateway_token.as_deref(),
            Some("existing-token"),
            "whitespace-only runtime token should not overwrite an existing token"
        );
    }

    #[test]
    fn test_apply_credentials_trims_runtime_token() {
        let mut config = config_with_notifications("http://127.0.0.1:4096", None);

        config.apply_runtime_gateway_credentials("http://127.0.0.1:4096", "  runtime-token  ");

        let notifications = config.notifications.expect("notifications should exist");
        assert_eq!(
            notifications.gateway_token.as_deref(),
            Some("runtime-token"),
            "stored token should be trimmed"
        );
    }

    #[test]
    fn test_apply_credentials_skips_empty_runtime_token_when_disk_token_absent() {
        let mut config = config_with_notifications("http://127.0.0.1:4096", None);

        config.apply_runtime_gateway_credentials("http://127.0.0.1:4096", "");

        let notifications = config.notifications.expect("notifications should exist");
        assert!(
            notifications.gateway_token.is_none(),
            "empty runtime token should not inject a Some(\"\")"
        );
    }

    #[test]
    fn test_apply_credentials_idempotent() {
        let mut config = config_with_notifications("http://127.0.0.1:4096", None);

        config.apply_runtime_gateway_credentials("http://127.0.0.1:4096", "runtime-token");
        config.apply_runtime_gateway_credentials("http://127.0.0.1:4096", "runtime-token");

        let notifications = config.notifications.expect("notifications should exist");
        assert_eq!(
            notifications.gateway_token.as_deref(),
            Some("runtime-token"),
        );
        assert_eq!(notifications.gateway_url, "http://127.0.0.1:4096",);
    }

    #[test]
    fn test_apply_credentials_preserves_notification_fields() {
        let mut config = config_with_notifications("http://127.0.0.1:4096", None);

        config.apply_runtime_gateway_credentials("http://127.0.0.1:4096", "runtime-token");

        let notifications = config.notifications.expect("notifications should exist");
        assert_eq!(notifications.channel.as_deref(), Some("slack"));
        assert_eq!(notifications.chat_id.as_deref(), Some("#ops"));
        assert!(
            notifications.notify_on.is_none(),
            "unrelated fields should not be mutated"
        );
    }
}