vent-mcp 0.2.0

STDIO MCP server that lets agents vent to configured channels
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
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
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
//! Configuration loading, defaults, and validation for vent-mcp.
//!
//! Configuration is the main policy boundary for the server. It decides which
//! channels are valid, where events may be delivered, how JSONL output is placed,
//! and how webhook payloads can be shaped. This module deliberately validates
//! those choices before the server starts or the CLI sends a message, so callers
//! cannot route feedback to undeclared channels, malformed webhook destinations,
//! or ambiguous provider mappings.

use std::collections::{BTreeMap, BTreeSet};
use std::env;
use std::ffi::OsString;
use std::fs;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::provider::ProviderTemplate;

const DEFAULT_CONFIG_FILE_NAME: &str = "config.toml";
const DEFAULT_CONFIG_DIR_NAME: &str = "vent-mcp";
pub(crate) const DEFAULT_LOG_SINK_NAME: &str = "log";
const ENV_CONFIG: &str = "VENT_MCP_CONFIG";
#[cfg(feature = "webhook")]
const DEFAULT_WEBHOOK_TIMEOUT_MS: u64 = 10_000;

/// Validated configuration loaded from disk with its resolved file path.
#[derive(Debug, Clone, PartialEq)]
pub struct LoadedConfig {
    path: PathBuf,
    config: RuntimeConfig,
}

impl LoadedConfig {
    /// Resolves, creates when appropriate, reads, and validates the active config.
    ///
    /// Environment-specified configs must already exist, while default user
    /// locations can be bootstrapped with the built-in safe defaults.
    pub fn load() -> Result<Self, ConfigError> {
        let resolved = resolve_config_path()?;
        Self::load_from_resolved_path(resolved)
    }

    /// Loads and validates a config from an explicit path.
    ///
    /// This bypasses automatic default creation and is used by tests and callers
    /// that already know which config file should be authoritative.
    pub fn load_from_path(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
        let path = path.as_ref().to_path_buf();
        let config = AppConfig::load_from_path(&path)?;
        Self::from_app_config(path, config)
    }

    /// Loads a config from a previously resolved path, creating defaults when safe.
    ///
    /// Default creation happens only for implicit XDG or home-directory paths.
    /// An explicit environment override is treated as intentional and therefore
    /// fails when the file is missing.
    fn load_from_resolved_path(resolved: ResolvedConfigPath) -> Result<Self, ConfigError> {
        if !resolved.path.exists() {
            if resolved.source == ConfigPathSource::Env {
                return Err(ConfigError::NotFound {
                    path: resolved.path,
                });
            }
            write_default_config(&resolved.path)?;
        }

        Self::load_from_path(resolved.path)
    }

    fn from_app_config(path: PathBuf, config: AppConfig) -> Result<Self, ConfigError> {
        let config_dir = config_dir_for_path(&path);
        let config = RuntimeConfig::from_app_config(config, config_dir)?;
        Ok(Self { path, config })
    }

    /// Returns the normalized runtime configuration.
    #[must_use]
    pub fn config(&self) -> &RuntimeConfig {
        &self.config
    }

    /// Consumes the loaded config and returns its normalized runtime form.
    #[must_use]
    pub fn into_config(self) -> RuntimeConfig {
        self.config
    }

    /// Returns the directory that contains the active configuration file.
    ///
    /// Sinks use this as the base for default relative storage decisions.
    #[must_use]
    pub fn config_dir(&self) -> PathBuf {
        config_dir_for_path(&self.path)
    }
}

/// Normalized runtime policy derived from validated TOML configuration.
#[derive(Debug, Clone, PartialEq)]
pub struct RuntimeConfig {
    default_channel: String,
    logging: LoggingConfig,
    channels: Vec<ChannelConfig>,
    #[cfg(feature = "webhook")]
    providers: BTreeMap<String, ProviderTemplate>,
    sinks: Vec<SinkConfig>,
    sinks_by_name: BTreeMap<String, usize>,
    config_dir: PathBuf,
    jsonl_dir: PathBuf,
}

impl RuntimeConfig {
    pub(crate) fn from_app_config(
        config: AppConfig,
        config_dir: PathBuf,
    ) -> Result<Self, ConfigValidationError> {
        config.validate()?;
        let AppConfig {
            default_channel,
            logging,
            channels,
            providers: raw_providers,
            sinks,
        } = config;

        #[cfg(feature = "webhook")]
        let providers = compile_webhook_providers(&raw_providers)?;
        #[cfg(not(feature = "webhook"))]
        let _ = raw_providers;

        let sinks_by_name = sinks
            .iter()
            .enumerate()
            .map(|(index, sink)| (sink.name().to_string(), index))
            .collect();
        let jsonl_dir = resolve_jsonl_dir(&logging, &config_dir)?;

        Ok(Self {
            default_channel,
            logging,
            channels,
            #[cfg(feature = "webhook")]
            providers,
            sinks,
            sinks_by_name,
            config_dir,
            jsonl_dir,
        })
    }

    /// Returns the channel used when callers omit an explicit channel.
    #[must_use]
    pub fn default_channel(&self) -> &str {
        &self.default_channel
    }

    /// Reports whether a channel name is configured.
    #[must_use]
    pub fn has_channel(&self, name: &str) -> bool {
        self.channels.iter().any(|channel| channel.name == name)
    }

    /// True when only the default channel exists and channel choice can be hidden.
    #[must_use]
    pub fn has_only_default_channel(&self) -> bool {
        self.channels.len() == 1 && self.channels[0].name == self.default_channel
    }

    /// Builds the channel catalog exposed by the `list_channels` MCP tool.
    #[must_use]
    pub fn channel_list(&self) -> crate::types::ListChannelsOutput {
        crate::types::ListChannelsOutput {
            default_channel: self.default_channel.clone(),
            channels: self
                .channels
                .iter()
                .map(|channel| crate::types::ChannelInfo {
                    name: channel.name.clone(),
                    description: channel.description.clone(),
                })
                .collect(),
        }
    }

    pub(crate) fn sinks_for_channel(&self, channel_name: &str) -> Option<Vec<&SinkConfig>> {
        let channel = self
            .channels
            .iter()
            .find(|channel| channel.name == channel_name)?;
        Some(
            channel
                .sinks
                .iter()
                .map(|sink| {
                    let index = self
                        .sinks_by_name
                        .get(sink)
                        .expect("validated channel sink reference");
                    &self.sinks[*index]
                })
                .collect(),
        )
    }

    pub(crate) fn jsonl_dir(&self) -> &Path {
        &self.jsonl_dir
    }

    #[cfg(feature = "webhook")]
    pub(crate) fn webhook_provider(&self, name: &str) -> Option<&ProviderTemplate> {
        self.providers.get(name)
    }

    #[allow(dead_code)]
    pub(crate) fn config_dir(&self) -> &Path {
        &self.config_dir
    }

    #[allow(dead_code)]
    pub(crate) fn logging(&self) -> &LoggingConfig {
        &self.logging
    }
}

/// Top-level TOML configuration shape for channels, sinks, providers, and logging.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default, deny_unknown_fields)]
pub struct AppConfig {
    pub default_channel: String,
    pub logging: LoggingConfig,
    pub channels: Vec<ChannelConfig>,
    pub providers: BTreeMap<String, WebhookProviderConfig>,
    pub sinks: Vec<SinkConfig>,
}

impl Default for AppConfig {
    /// Builds the conservative default config with one channel and JSONL logging.
    ///
    /// The default creates a local, non-network sink so a first run has somewhere
    /// to record vents without requiring webhook credentials or provider setup.
    fn default() -> Self {
        Self {
            default_channel: "feedback".to_string(),
            logging: LoggingConfig::default(),
            channels: vec![ChannelConfig {
                name: "feedback".to_string(),
                description: "Blocked work, repeated failures, or confusing workflows. Avoid routine progress updates.".to_string(),
                sinks: vec![DEFAULT_LOG_SINK_NAME.to_string()],
            }],
            providers: default_webhook_providers(),
            sinks: vec![default_log_sink()],
        }
    }
}

impl AppConfig {
    /// Reads, parses, and validates TOML configuration from disk.
    ///
    /// The parsed value is never returned before validation succeeds, keeping
    /// downstream server and sink code free from partial-config assumptions.
    pub fn load_from_path(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
        let path = path.as_ref();
        if !path.exists() {
            return Err(ConfigError::NotFound {
                path: path.to_path_buf(),
            });
        }

        let raw = fs::read_to_string(path).map_err(|source| ConfigError::Read {
            path: path.to_path_buf(),
            source,
        })?;

        let config: Self = toml::from_str(&raw).map_err(|source| ConfigError::ParseTomlAtPath {
            path: path.to_path_buf(),
            source,
        })?;
        config.validate()?;
        Ok(config)
    }

    /// Parses and validates TOML configuration from a string.
    ///
    /// This is used by config tests without exposing raw parsing as binary API.
    #[cfg(test)]
    pub fn from_toml_str(raw: &str) -> Result<Self, ConfigError> {
        let config: Self =
            toml::from_str(raw).map_err(|source| ConfigError::ParseToml { source })?;
        config.validate()?;
        Ok(config)
    }

    /// Validates channel, provider, and sink settings as one coherent policy.
    ///
    /// The checks reject empty lists, duplicate or malformed channel names,
    /// default channels that do not exist, invalid provider maps, and sink
    /// settings that would fail later in less predictable ways.
    pub fn validate(&self) -> Result<(), ConfigValidationError> {
        validate_channel_name(&self.default_channel, "default_channel")?;

        if self.channels.is_empty() {
            return Err(ConfigValidationError::ChannelsMustNotBeEmpty);
        }
        if self.sinks.is_empty() {
            return Err(ConfigValidationError::SinksMustNotBeEmpty);
        }

        let mut channel_names = BTreeSet::new();
        for channel in &self.channels {
            validate_channel_name(&channel.name, "channels.name")?;
            if channel.description.trim().is_empty() {
                return Err(ConfigValidationError::ChannelDescriptionMustNotBeEmpty {
                    channel: channel.name.clone(),
                });
            }
            if channel.sinks.is_empty() {
                return Err(ConfigValidationError::ChannelSinksMustNotBeEmpty {
                    channel: channel.name.clone(),
                });
            }
            let mut channel_sinks = BTreeSet::new();
            for sink in &channel.sinks {
                validate_provider_name(sink, "channels.sinks")?;
                if !channel_sinks.insert(sink.as_str()) {
                    return Err(ConfigValidationError::DuplicateChannelSink {
                        channel: channel.name.clone(),
                        sink: sink.clone(),
                    });
                }
            }
            if !channel_names.insert(channel.name.as_str()) {
                return Err(ConfigValidationError::DuplicateChannel {
                    channel: channel.name.clone(),
                });
            }
        }

        if !channel_names.contains(self.default_channel.as_str()) {
            return Err(ConfigValidationError::DefaultChannelMustExist {
                channel: self.default_channel.clone(),
            });
        }

        for (provider_name, provider) in &self.providers {
            validate_provider_name(provider_name, "providers")?;
            provider.validate(provider_name)?;
        }

        let mut sink_names = BTreeSet::new();
        for sink in &self.sinks {
            sink.validate(&self.providers)?;
            let name = sink.name();
            validate_provider_name(name, "sinks.name")?;
            if !sink_names.insert(name) {
                return Err(ConfigValidationError::DuplicateSinkName {
                    sink: name.to_string(),
                });
            }
        }

        // All jsonl sinks share one vents.jsonl file, so a channel may reference at most one.
        let jsonl_sink_names: BTreeSet<&str> = self
            .sinks
            .iter()
            .filter(|sink| matches!(sink, SinkConfig::Jsonl(_)))
            .map(SinkConfig::name)
            .collect();

        for channel in &self.channels {
            let mut jsonl_in_channel = 0;
            for sink in &channel.sinks {
                if !sink_names.contains(sink.as_str()) {
                    return Err(ConfigValidationError::UnknownChannelSink {
                        channel: channel.name.clone(),
                        sink: sink.clone(),
                    });
                }
                if jsonl_sink_names.contains(sink.as_str()) {
                    jsonl_in_channel += 1;
                }
            }
            if jsonl_in_channel > 1 {
                return Err(ConfigValidationError::MultipleJsonlSinksInChannel {
                    channel: channel.name.clone(),
                });
            }
        }

        Ok(())
    }
}

/// JSONL storage location overrides for persisted vent records.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(default, deny_unknown_fields)]
pub struct LoggingConfig {
    pub jsonl_dir: Option<String>,
}

/// One named vent channel and the sinks that receive its events.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ChannelConfig {
    pub name: String,
    pub description: String,
    #[serde(default)]
    pub sinks: Vec<String>,
}

/// Concrete delivery destination referenced by channel routes.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "type", rename_all = "lowercase", deny_unknown_fields)]
pub enum SinkConfig {
    Jsonl(JsonlSinkConfig),
    #[cfg(feature = "webhook")]
    Webhook(WebhookSinkConfig),
}

impl SinkConfig {
    /// Validates the concrete sink variant against the provider registry.
    ///
    /// JSONL has no extra settings, while webhook sinks must reference only
    /// defined providers and pass URL, timeout, and header checks.
    fn validate(
        &self,
        _providers: &BTreeMap<String, WebhookProviderConfig>,
    ) -> Result<(), ConfigValidationError> {
        match self {
            SinkConfig::Jsonl(_) => Ok(()),
            #[cfg(feature = "webhook")]
            SinkConfig::Webhook(config) => config.validate(_providers),
        }
    }

    #[must_use]
    pub fn name(&self) -> &str {
        match self {
            SinkConfig::Jsonl(config) => &config.name,
            #[cfg(feature = "webhook")]
            SinkConfig::Webhook(config) => &config.name,
        }
    }
}

/// JSONL sink definition that appends vent records to the shared log file.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(default, deny_unknown_fields)]
pub struct JsonlSinkConfig {
    pub name: String,
}

/// HTTP webhook sink with optional provider shaping and env-backed headers.
#[cfg(feature = "webhook")]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct WebhookSinkConfig {
    pub name: String,
    pub url: String,
    pub provider: Option<String>,
    pub headers: Vec<WebhookHeaderConfig>,
    pub timeout_ms: u64,
}

#[cfg(feature = "webhook")]
impl Default for WebhookSinkConfig {
    /// Builds a webhook sink with empty destination and default timeout.
    ///
    /// The URL remains intentionally empty so deserialization can fill it and
    /// validation can reject configs that omit a real endpoint.
    fn default() -> Self {
        Self {
            name: String::new(),
            url: String::new(),
            provider: None,
            headers: Vec::new(),
            timeout_ms: DEFAULT_WEBHOOK_TIMEOUT_MS,
        }
    }
}

#[cfg(feature = "webhook")]
impl WebhookSinkConfig {
    /// Validates one webhook sink and any provider reference it contains.
    ///
    /// Webhooks must target HTTP(S), have a positive timeout, use non-empty
    /// environment-backed headers, and either request raw event JSON or a known
    /// provider mapping.
    fn validate(
        &self,
        providers: &BTreeMap<String, WebhookProviderConfig>,
    ) -> Result<(), ConfigValidationError> {
        if self.url.trim().is_empty() {
            return Err(ConfigValidationError::WebhookUrlMustNotBeEmpty);
        }

        let parsed = url::Url::parse(&self.url).map_err(|_| {
            ConfigValidationError::WebhookUrlMustBeHttp {
                url: self.url.clone(),
            }
        })?;
        if !matches!(parsed.scheme(), "http" | "https") {
            return Err(ConfigValidationError::WebhookUrlMustBeHttp {
                url: self.url.clone(),
            });
        }
        if self.timeout_ms == 0 {
            return Err(ConfigValidationError::WebhookTimeoutMsMustBePositive);
        }
        if let Some(provider) = self.provider.as_deref().map(str::trim) {
            if provider.is_empty() {
                return Err(ConfigValidationError::WebhookProviderNameMustNotBeEmpty);
            }
            validate_provider_name(provider, "sinks.provider")?;
            if provider != "raw" && !providers.contains_key(provider) {
                return Err(ConfigValidationError::UnknownWebhookProvider {
                    provider: provider.to_string(),
                });
            }
        }

        let mut header_names = BTreeSet::new();
        for header in &self.headers {
            if header.name.trim().is_empty() {
                return Err(ConfigValidationError::WebhookHeaderNameMustNotBeEmpty);
            }
            if header.env.trim().is_empty() {
                return Err(ConfigValidationError::WebhookHeaderEnvMustNotBeEmpty {
                    header: header.name.clone(),
                });
            }
            let normalized = header.name.trim().to_ascii_lowercase();
            if !header_names.insert(normalized) {
                return Err(ConfigValidationError::DuplicateWebhookHeader {
                    header: header.name.clone(),
                });
            }
        }

        Ok(())
    }
}

/// Maps vent event fields onto dotted webhook JSON output paths.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(default)]
pub struct WebhookProviderConfig {
    pub field_label_key: Option<String>,
    #[serde(flatten)]
    pub fields: BTreeMap<String, String>,
}

impl WebhookProviderConfig {
    /// Validates a provider's event-field-to-output-path mapping.
    ///
    /// Providers are constrained to known event fields and unique dotted output
    /// paths so rendered webhook payloads cannot collide or silently drop fields.
    fn validate(&self, provider_name: &str) -> Result<(), ConfigValidationError> {
        ProviderTemplate::compile(provider_name, self).map(|_| ())
    }
}

/// Webhook header populated from a named environment variable at send time.
#[cfg(feature = "webhook")]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct WebhookHeaderConfig {
    pub name: String,
    pub env: String,
}

/// Resolved config file path and the lookup rule that selected it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedConfigPath {
    pub path: PathBuf,
    pub source: ConfigPathSource,
}

/// Why a config path was chosen during environment-based resolution.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfigPathSource {
    Env,
    Xdg,
    Home,
}

/// Errors while resolving, reading, parsing, or bootstrapping configuration files.
#[derive(Debug, Error)]
pub enum ConfigError {
    #[error("home directory is not set")]
    HomeDirectoryNotSet,
    #[error("config file not found at {path}")]
    NotFound { path: PathBuf },
    #[error("failed to read config file at {path}: {source}")]
    Read {
        path: PathBuf,
        source: std::io::Error,
    },
    #[error("failed to parse config file at {path}: {source}")]
    ParseTomlAtPath {
        path: PathBuf,
        source: toml::de::Error,
    },
    #[error("failed to parse config: {source}")]
    ParseToml { source: toml::de::Error },
    #[error("{0}")]
    Validation(#[from] ConfigValidationError),
    #[error("failed to create config directory at {path}: {source}")]
    CreateConfigDir {
        path: PathBuf,
        source: std::io::Error,
    },
    #[error("failed to serialize default config: {source}")]
    SerializeDefaultConfig { source: toml::ser::Error },
    #[error("failed to write default config at {path}: {source}")]
    WriteDefaultConfig {
        path: PathBuf,
        source: std::io::Error,
    },
}

/// Policy violations detected while validating TOML configuration.
#[derive(Debug, Error, PartialEq, Eq)]
pub enum ConfigValidationError {
    #[error("channels must contain at least one channel")]
    ChannelsMustNotBeEmpty,
    #[error("sinks must contain at least one sink")]
    SinksMustNotBeEmpty,
    #[error("invalid channel name in {field}: {name}")]
    InvalidChannelName { field: String, name: String },
    #[error("duplicate sink name: {sink}")]
    DuplicateSinkName { sink: String },
    #[error("duplicate channel: {channel}")]
    DuplicateChannel { channel: String },
    #[error("channel must reference at least one sink: {channel}")]
    ChannelSinksMustNotBeEmpty { channel: String },
    #[error("duplicate sink reference in channel {channel}: {sink}")]
    DuplicateChannelSink { channel: String, sink: String },
    #[error("unknown sink reference in channel {channel}: {sink}")]
    UnknownChannelSink { channel: String, sink: String },
    #[error("default channel does not exist: {channel}")]
    DefaultChannelMustExist { channel: String },
    #[error("channel description must not be empty: {channel}")]
    ChannelDescriptionMustNotBeEmpty { channel: String },
    #[error("webhook url must not be empty")]
    WebhookUrlMustNotBeEmpty,
    #[error("webhook url must be an http or https URL: {url}")]
    WebhookUrlMustBeHttp { url: String },
    #[cfg(feature = "webhook")]
    #[error("webhook timeout_ms must be positive")]
    WebhookTimeoutMsMustBePositive,
    #[cfg(feature = "webhook")]
    #[error("webhook header name must not be empty")]
    WebhookHeaderNameMustNotBeEmpty,
    #[cfg(feature = "webhook")]
    #[error("webhook header env must not be empty for header {header}")]
    WebhookHeaderEnvMustNotBeEmpty { header: String },
    #[cfg(feature = "webhook")]
    #[error("duplicate webhook header: {header}")]
    DuplicateWebhookHeader { header: String },
    #[error("webhook provider name must not be empty")]
    WebhookProviderNameMustNotBeEmpty,
    #[error("unknown webhook provider: {provider}")]
    UnknownWebhookProvider { provider: String },
    #[error("webhook provider map must not be empty: {provider}")]
    WebhookProviderMapMustNotBeEmpty { provider: String },
    #[error("invalid webhook provider label key in {provider}: {label_key}")]
    InvalidWebhookProviderLabelKey { provider: String, label_key: String },
    #[error("unknown webhook provider field in {provider}: {field}")]
    UnknownWebhookProviderField { provider: String, field: String },
    #[error("invalid webhook provider path in {provider} for {field}: {path}")]
    InvalidWebhookProviderPath {
        provider: String,
        field: String,
        path: String,
    },
    #[error("duplicate webhook provider output path in {provider}: {path}")]
    DuplicateWebhookProviderPath { provider: String, path: String },
    #[error(
        "webhook provider output path in {provider} collides with another mapped path: {path}"
    )]
    CollidingWebhookProviderPath { provider: String, path: String },
    #[error("cannot expand home-relative jsonl_dir because HOME is not set: {path}")]
    JsonlDirHomeNotSet { path: String },
    #[error(
        "channel {channel} references multiple jsonl sinks, which would write duplicate records to the shared log file"
    )]
    MultipleJsonlSinksInChannel { channel: String },
}

/// Resolves the active configuration path from process environment.
///
/// The lookup order is explicit config path, XDG config home, then the user's
/// home directory. Empty environment values are ignored rather than treated as
/// real paths.
pub fn resolve_config_path() -> Result<ResolvedConfigPath, ConfigError> {
    resolve_config_path_with(
        |key| env::var_os(key),
        env::var_os("HOME").map(PathBuf::from),
    )
}

/// Resolves a config path using injectable environment and home-directory inputs.
///
/// This helper keeps path precedence testable without mutating global process
/// environment. The returned source records why the path was selected so loading
/// can decide whether default creation is allowed.
pub fn resolve_config_path_with<F>(
    lookup_var: F,
    home_dir: Option<PathBuf>,
) -> Result<ResolvedConfigPath, ConfigError>
where
    F: Fn(&str) -> Option<OsString>,
{
    if let Some(path) = lookup_var(ENV_CONFIG).and_then(non_empty_os_string) {
        return Ok(ResolvedConfigPath {
            path: PathBuf::from(path),
            source: ConfigPathSource::Env,
        });
    }

    if let Some(xdg_config_home) = lookup_var("XDG_CONFIG_HOME").and_then(non_empty_os_string) {
        return Ok(ResolvedConfigPath {
            path: PathBuf::from(xdg_config_home)
                .join(DEFAULT_CONFIG_DIR_NAME)
                .join(DEFAULT_CONFIG_FILE_NAME),
            source: ConfigPathSource::Xdg,
        });
    }

    let home = home_dir.ok_or(ConfigError::HomeDirectoryNotSet)?;
    Ok(ResolvedConfigPath {
        path: home
            .join(".config")
            .join(DEFAULT_CONFIG_DIR_NAME)
            .join(DEFAULT_CONFIG_FILE_NAME),
        source: ConfigPathSource::Home,
    })
}

/// Treats empty OS strings as unset environment values.
fn non_empty_os_string(value: OsString) -> Option<OsString> {
    if value.is_empty() {
        None
    } else {
        Some(value)
    }
}

fn config_dir_for_path(path: &Path) -> PathBuf {
    path.parent()
        .map(Path::to_path_buf)
        .unwrap_or_else(|| PathBuf::from("."))
}

fn resolve_jsonl_dir(
    logging: &LoggingConfig,
    config_dir: &Path,
) -> Result<PathBuf, ConfigValidationError> {
    // Empty or whitespace jsonl_dir falls back to the config directory, not CWD.
    let Some(value) = logging
        .jsonl_dir
        .as_deref()
        .map(str::trim)
        .filter(|value| !value.is_empty())
    else {
        return Ok(config_dir.to_path_buf());
    };

    expand_tilde(value).map_err(|()| ConfigValidationError::JsonlDirHomeNotSet {
        path: value.to_string(),
    })
}

fn expand_tilde(value: &str) -> Result<PathBuf, ()> {
    expand_tilde_with(value, home_dir())
}

fn expand_tilde_with(value: &str, home: Option<PathBuf>) -> Result<PathBuf, ()> {
    // Home-relative paths error when HOME is unset instead of writing under literal ~/… .
    if value == "~" {
        return home.ok_or(());
    }

    if let Some(rest) = value.strip_prefix("~/") {
        return home.map(|home| home.join(rest)).ok_or(());
    }

    Ok(Path::new(value).to_path_buf())
}

fn home_dir() -> Option<PathBuf> {
    env::var_os("HOME")
        .filter(|home| !home.is_empty())
        .map(PathBuf::from)
}

#[cfg(feature = "webhook")]
fn compile_webhook_providers(
    providers: &BTreeMap<String, WebhookProviderConfig>,
) -> Result<BTreeMap<String, ProviderTemplate>, ConfigValidationError> {
    providers
        .iter()
        .map(|(name, provider)| {
            ProviderTemplate::compile(name, provider).map(|template| (name.clone(), template))
        })
        .collect()
}

/// Validates channel-like names used by configuration and sink selection.
///
/// Names are limited to lowercase ASCII letters, digits, underscores, and dashes
/// so they remain stable in CLI input, MCP schemas, status labels, and webhook
/// provider references.
fn validate_channel_name(name: &str, field: &str) -> Result<(), ConfigValidationError> {
    let valid = !name.is_empty()
        && name.len() <= 64
        && name
            .bytes()
            .all(|byte| matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'_' | b'-'));

    if valid {
        Ok(())
    } else {
        Err(ConfigValidationError::InvalidChannelName {
            field: field.to_string(),
            name: name.to_string(),
        })
    }
}

/// Validates provider names with the same rules used for channels.
fn validate_provider_name(name: &str, field: &str) -> Result<(), ConfigValidationError> {
    validate_channel_name(name, field)
}

#[must_use]
pub(crate) fn default_log_sink() -> SinkConfig {
    SinkConfig::Jsonl(JsonlSinkConfig {
        name: DEFAULT_LOG_SINK_NAME.to_string(),
    })
}

/// Supplies built-in webhook provider mappings for common receivers.
///
/// These defaults let users send useful payloads to raw automation endpoints,
/// text-only chat endpoints, and rich chat endpoints without writing the mapping
/// from scratch.
fn default_webhook_providers() -> BTreeMap<String, WebhookProviderConfig> {
    [
        ("zapier", raw_event_provider()),
        ("make", raw_event_provider()),
        ("n8n", raw_event_provider()),
        ("pipedream", raw_event_provider()),
        ("workato", raw_event_provider()),
        ("ifttt", ifttt_provider()),
        ("slack", slack_like_provider()),
        ("mattermost", slack_like_provider()),
        (
            "discord",
            labeled_context_provider("name", "content", "embeds.0.fields.0.value"),
        ),
        ("microsoft_teams", text_provider("text")),
        ("google_chat", text_provider("text")),
        ("webex", text_provider("markdown")),
    ]
    .into_iter()
    .map(|(name, provider)| (name.to_string(), provider))
    .collect()
}

/// Maps the canonical vent event shape unchanged into a receiver-specific body.
fn raw_event_provider() -> WebhookProviderConfig {
    WebhookProviderConfig {
        field_label_key: None,
        fields: BTreeMap::from([
            ("id".to_string(), "id".to_string()),
            ("timestamp".to_string(), "timestamp".to_string()),
            ("channel".to_string(), "channel".to_string()),
            ("message".to_string(), "message".to_string()),
            ("project".to_string(), "project".to_string()),
        ]),
    }
}

/// Maps only the vent message into a provider's plain text field.
fn text_provider(message_path: &str) -> WebhookProviderConfig {
    WebhookProviderConfig {
        field_label_key: None,
        fields: BTreeMap::from([("message".to_string(), message_path.to_string())]),
    }
}

/// Maps message and project into rich fields with generated labels.
fn labeled_context_provider(
    label_key: &str,
    message_path: &str,
    project_path: &str,
) -> WebhookProviderConfig {
    WebhookProviderConfig {
        field_label_key: Some(label_key.to_string()),
        fields: BTreeMap::from([
            ("message".to_string(), message_path.to_string()),
            ("project".to_string(), project_path.to_string()),
        ]),
    }
}

/// Maps into Slack-compatible attachment fields.
fn slack_like_provider() -> WebhookProviderConfig {
    labeled_context_provider("title", "text", "attachments.0.fields.0.value")
}

/// Maps the three Maker Webhooks values IFTTT exposes to applets.
fn ifttt_provider() -> WebhookProviderConfig {
    WebhookProviderConfig {
        field_label_key: None,
        fields: BTreeMap::from([
            ("message".to_string(), "value1".to_string()),
            ("channel".to_string(), "value2".to_string()),
            ("project".to_string(), "value3".to_string()),
        ]),
    }
}

/// Writes a default config file at an implicit config path.
///
/// Parent directories are created as needed, and serialization errors remain
/// explicit so startup failures explain whether creation or rendering failed.
fn write_default_config(path: &Path) -> Result<(), ConfigError> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).map_err(|source| ConfigError::CreateConfigDir {
            path: parent.to_path_buf(),
            source,
        })?;
    }

    let rendered = toml::to_string_pretty(&AppConfig::default())
        .map_err(|source| ConfigError::SerializeDefaultConfig { source })?;
    fs::write(path, rendered).map_err(|source| ConfigError::WriteDefaultConfig {
        path: path.to_path_buf(),
        source,
    })?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use std::ffi::OsString;
    use std::path::PathBuf;

    use tempfile::tempdir;

    #[cfg(feature = "webhook")]
    use super::SinkConfig;
    use super::{
        resolve_config_path_with, AppConfig, ConfigPathSource, ConfigValidationError, LoadedConfig,
    };

    /// Verifies config path lookup precedence without touching real environment variables.
    #[test]
    fn resolve_config_path_uses_expected_precedence() {
        let from_env = resolve_config_path_with(
            |name| match name {
                "VENT_MCP_CONFIG" => Some(OsString::from("/tmp/override.toml")),
                "XDG_CONFIG_HOME" => Some(OsString::from("/xdg")),
                _ => None,
            },
            Some(PathBuf::from("/Users/alice")),
        )
        .expect("env override should resolve");
        assert_eq!(from_env.path, PathBuf::from("/tmp/override.toml"));
        assert_eq!(from_env.source, ConfigPathSource::Env);

        let from_xdg = resolve_config_path_with(
            |name| match name {
                "XDG_CONFIG_HOME" => Some(OsString::from("/xdg")),
                _ => None,
            },
            Some(PathBuf::from("/Users/alice")),
        )
        .expect("xdg should resolve");
        assert_eq!(from_xdg.path, PathBuf::from("/xdg/vent-mcp/config.toml"));
        assert_eq!(from_xdg.source, ConfigPathSource::Xdg);

        let from_home = resolve_config_path_with(|_| None, Some(PathBuf::from("/Users/alice")))
            .expect("home should resolve");
        assert_eq!(
            from_home.path,
            PathBuf::from("/Users/alice/.config/vent-mcp/config.toml")
        );
        assert_eq!(from_home.source, ConfigPathSource::Home);
    }

    /// Verifies validation requires the default channel to be declared.
    #[test]
    fn config_validation_rejects_missing_default_channel() {
        let raw = r#"
default_channel = "missing"

[[channels]]
name = "general"
description = "General feedback."
sinks = ["log"]

[[sinks]]
type = "jsonl"
name = "log"
"#;

        let error = AppConfig::from_toml_str(raw).expect_err("config should fail");
        assert!(matches!(
            error.into_validation(),
            Some(ConfigValidationError::DefaultChannelMustExist { .. })
        ));
    }

    /// Verifies duplicate channel names are rejected.
    #[test]
    fn config_validation_rejects_duplicate_channels() {
        let raw = r#"
default_channel = "general"

[[channels]]
name = "general"
description = "General feedback."
sinks = ["log"]

[[channels]]
name = "general"
description = "Duplicate feedback."
sinks = ["log"]

[[sinks]]
type = "jsonl"
name = "log"
"#;

        let error = AppConfig::from_toml_str(raw).expect_err("config should fail");
        assert!(matches!(
            error.into_validation(),
            Some(ConfigValidationError::DuplicateChannel { .. })
        ));
    }

    /// Verifies configs must define at least one sink.
    #[test]
    fn config_validation_rejects_empty_sinks() {
        let raw = r#"
default_channel = "general"
sinks = []

[[channels]]
name = "general"
description = "General feedback."
sinks = ["log"]
"#;

        let error = AppConfig::from_toml_str(raw).expect_err("config should fail");
        assert!(matches!(
            error.into_validation(),
            Some(ConfigValidationError::SinksMustNotBeEmpty)
        ));
    }

    /// Verifies every channel must explicitly route to at least one sink.
    #[test]
    fn config_validation_rejects_channel_without_sinks() {
        let raw = r#"
default_channel = "general"

[[channels]]
name = "general"
description = "General feedback."

[[sinks]]
type = "jsonl"
name = "log"
"#;

        let error = AppConfig::from_toml_str(raw).expect_err("config should fail");
        assert!(matches!(
            error.into_validation(),
            Some(ConfigValidationError::ChannelSinksMustNotBeEmpty { .. })
        ));
    }

    /// Verifies channel routes must reference known sink definitions.
    #[test]
    fn config_validation_rejects_unknown_channel_sink() {
        let raw = r#"
default_channel = "general"

[[channels]]
name = "general"
description = "General feedback."
sinks = ["missing"]

[[sinks]]
type = "jsonl"
name = "log"
"#;

        let error = AppConfig::from_toml_str(raw).expect_err("config should fail");
        assert!(matches!(
            error.into_validation(),
            Some(ConfigValidationError::UnknownChannelSink { .. })
        ));
    }

    /// Verifies named sinks are validated and cannot collide.
    #[test]
    fn config_validation_rejects_duplicate_sink_names() {
        let raw = r#"
default_channel = "general"

[[channels]]
name = "general"
description = "General feedback."
sinks = ["log"]

[[sinks]]
type = "jsonl"
name = "log"

[[sinks]]
type = "jsonl"
name = "log"
"#;

        let error = AppConfig::from_toml_str(raw).expect_err("config should fail");
        assert!(matches!(
            error.into_validation(),
            Some(ConfigValidationError::DuplicateSinkName { .. })
        ));
    }

    /// Verifies sink definitions must have explicit names for channel routing.
    #[test]
    fn config_validation_rejects_unnamed_sinks() {
        let raw = r#"
default_channel = "general"

[[channels]]
name = "general"
description = "General feedback."
sinks = ["log"]

[[sinks]]
type = "jsonl"
"#;

        let error = AppConfig::from_toml_str(raw).expect_err("config should fail");
        assert!(matches!(
            error.into_validation(),
            Some(ConfigValidationError::InvalidChannelName { field, .. })
                if field == "sinks.name"
        ));
    }

    /// Verifies webhook TOML parses headers, provider references, and timeout values.
    #[test]
    #[cfg(feature = "webhook")]
    fn config_parses_webhook_with_env_headers() {
        let raw = r#"
default_channel = "general"

[[channels]]
name = "general"
description = "General feedback."
sinks = ["slack"]

[[sinks]]
type = "webhook"
name = "slack"
url = "https://example.com/vent"
provider = "slack"
timeout_ms = 2500
headers = [
  { name = "Authorization", env = "VENT_MCP_WEBHOOK_AUTHORIZATION" },
]
"#;

        let config = AppConfig::from_toml_str(raw).expect("webhook config");
        assert_eq!(config.sinks.len(), 1);
        let SinkConfig::Webhook(webhook) = &config.sinks[0] else {
            panic!("expected webhook sink");
        };
        assert_eq!(webhook.provider.as_deref(), Some("slack"));
        assert_eq!(webhook.timeout_ms, 2500);
    }

    /// Verifies webhook timeouts default to a positive value and reject zero.
    #[test]
    #[cfg(feature = "webhook")]
    fn webhook_timeout_defaults_and_must_be_positive() {
        let raw = r#"
default_channel = "general"

[[channels]]
name = "general"
description = "General feedback."
sinks = ["webhook"]

[[sinks]]
type = "webhook"
name = "webhook"
url = "https://example.com/vent"
"#;

        let config = AppConfig::from_toml_str(raw).expect("webhook config");
        let SinkConfig::Webhook(webhook) = &config.sinks[0] else {
            panic!("expected webhook sink");
        };
        assert_eq!(webhook.timeout_ms, super::DEFAULT_WEBHOOK_TIMEOUT_MS);

        let invalid = r#"
default_channel = "general"

[[channels]]
name = "general"
description = "General feedback."
sinks = ["webhook"]

[[sinks]]
type = "webhook"
name = "webhook"
url = "https://example.com/vent"
timeout_ms = 0
"#;
        let error = AppConfig::from_toml_str(invalid).expect_err("timeout should fail");
        assert!(matches!(
            error.into_validation(),
            Some(ConfigValidationError::WebhookTimeoutMsMustBePositive)
        ));
    }

    /// Verifies provider mappings must reference known fields, paths, and providers.
    #[test]
    #[cfg(feature = "webhook")]
    fn webhook_provider_config_validates_sink_references_and_paths() {
        let raw = r#"
default_channel = "general"

[[channels]]
name = "general"
description = "General feedback."
sinks = ["webhook"]

[providers.custom]
message = "data.content.message"
channel = "data.content.channel"

[[sinks]]
type = "webhook"
name = "webhook"
url = "https://example.com/vent"
provider = "custom"
"#;

        let config = AppConfig::from_toml_str(raw).expect("provider config");
        assert!(config.providers.contains_key("custom"));

        let missing = r#"
default_channel = "general"

[[channels]]
name = "general"
description = "General feedback."
sinks = ["webhook"]

[[sinks]]
type = "webhook"
name = "webhook"
url = "https://example.com/vent"
provider = "missing"
"#;
        let error = AppConfig::from_toml_str(missing).expect_err("provider should fail");
        assert!(matches!(
            error.into_validation(),
            Some(ConfigValidationError::UnknownWebhookProvider { .. })
        ));

        let invalid_field = r#"
default_channel = "general"

[[channels]]
name = "general"
description = "General feedback."
sinks = ["log"]

[providers.custom]
unknown = "data.content"

[[sinks]]
type = "jsonl"
name = "log"
"#;
        let error = AppConfig::from_toml_str(invalid_field).expect_err("field should fail");
        assert!(matches!(
            error.into_validation(),
            Some(ConfigValidationError::UnknownWebhookProviderField { .. })
        ));

        let invalid_path = r#"
default_channel = "general"

[[channels]]
name = "general"
description = "General feedback."
sinks = ["log"]

[providers.custom]
message = "data..content"

[[sinks]]
type = "jsonl"
name = "log"
"#;
        let error = AppConfig::from_toml_str(invalid_path).expect_err("path should fail");
        assert!(matches!(
            error.into_validation(),
            Some(ConfigValidationError::InvalidWebhookProviderPath { .. })
        ));

        let colliding_path = r#"
default_channel = "general"

[[channels]]
name = "general"
description = "General feedback."
sinks = ["log"]

[providers.bad]
message = "payload.body"
project = "payload"

[[sinks]]
type = "jsonl"
name = "log"
"#;
        let error =
            AppConfig::from_toml_str(colliding_path).expect_err("colliding path should fail");
        assert!(matches!(
            error.into_validation(),
            Some(ConfigValidationError::CollidingWebhookProviderPath { .. })
        ));

        let oversized_index = r#"
default_channel = "general"

[[channels]]
name = "general"
description = "General feedback."
sinks = ["log"]

[providers.bad]
message = "items.5000000"

[[sinks]]
type = "jsonl"
name = "log"
"#;
        let error =
            AppConfig::from_toml_str(oversized_index).expect_err("oversized index should fail");
        assert!(matches!(
            error.into_validation(),
            Some(ConfigValidationError::InvalidWebhookProviderPath { .. })
        ));

        let overflowing_index = r#"
default_channel = "general"

[[channels]]
name = "general"
description = "General feedback."
sinks = ["log"]

[providers.bad]
message = "items.999999999999999999999999999999999999999999"

[[sinks]]
type = "jsonl"
name = "log"
"#;
        let error =
            AppConfig::from_toml_str(overflowing_index).expect_err("overflowing index should fail");
        assert!(matches!(
            error.into_validation(),
            Some(ConfigValidationError::InvalidWebhookProviderPath { .. })
        ));

        let overflowing_root_index = r#"
default_channel = "general"

[[channels]]
name = "general"
description = "General feedback."
sinks = ["log"]

[providers.bad]
message = "999999999999999999999999999999999999999999"

[[sinks]]
type = "jsonl"
name = "log"
"#;
        let error = AppConfig::from_toml_str(overflowing_root_index)
            .expect_err("overflowing root index should fail");
        assert!(matches!(
            error.into_validation(),
            Some(ConfigValidationError::InvalidWebhookProviderPath { .. })
        ));
    }

    /// Rejects channels that would double-write the shared JSONL log file.
    #[test]
    fn channel_with_multiple_jsonl_sinks_is_rejected() {
        let config = r#"
default_channel = "feedback"

[[channels]]
name = "feedback"
description = "Feedback."
sinks = ["log", "audit"]

[[sinks]]
type = "jsonl"
name = "log"

[[sinks]]
type = "jsonl"
name = "audit"
"#;
        let error =
            AppConfig::from_toml_str(config).expect_err("duplicate jsonl sinks should fail");
        assert!(matches!(
            error.into_validation(),
            Some(ConfigValidationError::MultipleJsonlSinksInChannel { .. })
        ));
    }

    /// Empty or omitted jsonl_dir anchors JSONL output beside the config file.
    #[test]
    fn empty_jsonl_dir_falls_back_to_config_dir() {
        let config_dir = PathBuf::from("/home/user/.config/vent-mcp");

        for value in [None, Some(String::new()), Some("   ".to_string())] {
            let logging = super::LoggingConfig { jsonl_dir: value };
            assert_eq!(
                super::resolve_jsonl_dir(&logging, &config_dir).expect("should resolve"),
                config_dir,
                "empty/omitted jsonl_dir should anchor to the config directory"
            );
        }

        let explicit = super::LoggingConfig {
            jsonl_dir: Some("/var/log/vent".to_string()),
        };
        assert_eq!(
            super::resolve_jsonl_dir(&explicit, &config_dir).expect("should resolve"),
            PathBuf::from("/var/log/vent")
        );
    }

    /// Tilde jsonl_dir paths fail closed when HOME cannot be resolved.
    #[test]
    fn tilde_expansion_without_home_errors() {
        let home = Some(PathBuf::from("/home/user"));
        assert_eq!(
            super::expand_tilde_with("~/.local/state/vent-mcp", home.clone()).expect("has home"),
            PathBuf::from("/home/user/.local/state/vent-mcp")
        );
        assert_eq!(
            super::expand_tilde_with("~", home).expect("has home"),
            PathBuf::from("/home/user")
        );

        assert!(super::expand_tilde_with("~/.local/state/vent-mcp", None).is_err());
        assert!(super::expand_tilde_with("~", None).is_err());
        assert_eq!(
            super::expand_tilde_with("/var/log/vent", None).expect("absolute"),
            PathBuf::from("/var/log/vent")
        );
    }

    /// Verifies implicit default config paths are created on first load.
    #[test]
    fn load_from_default_path_creates_default_config() {
        let dir = tempdir().expect("temp dir");
        let path = dir.path().join("vent-mcp").join("config.toml");

        let loaded = LoadedConfig::load_from_resolved_path(super::ResolvedConfigPath {
            path: path.clone(),
            source: ConfigPathSource::Home,
        })
        .expect("default config should be created");

        assert!(path.exists());
        assert_eq!(loaded.config().default_channel(), "feedback");
    }

    /// Verifies the default config ships the broad webhook provider set.
    #[test]
    fn default_config_includes_common_webhook_provider_maps() {
        let config = AppConfig::default();
        let expected = [
            "zapier",
            "make",
            "n8n",
            "pipedream",
            "workato",
            "ifttt",
            "slack",
            "mattermost",
            "discord",
            "microsoft_teams",
            "google_chat",
            "webex",
        ];

        for provider in expected {
            assert!(
                config.providers.contains_key(provider),
                "missing default provider {provider}"
            );
        }
        assert_eq!(
            config.providers["microsoft_teams"].fields["message"],
            "text"
        );
        assert_eq!(config.providers["ifttt"].fields["message"], "value1");
        assert_eq!(config.channels[0].sinks, [super::DEFAULT_LOG_SINK_NAME]);
        assert_eq!(config.sinks[0].name(), super::DEFAULT_LOG_SINK_NAME);
        assert!(!config.providers["discord"].fields.contains_key("channel"));
        assert!(!config.providers["slack"].fields.contains_key("channel"));
    }

    trait ConfigErrorExt {
        /// Extracts validation errors from the top-level config error wrapper.
        fn into_validation(self) -> Option<ConfigValidationError>;
    }

    impl ConfigErrorExt for super::ConfigError {
        /// Returns the inner validation error when this is a validation failure.
        fn into_validation(self) -> Option<ConfigValidationError> {
            match self {
                super::ConfigError::Validation(error) => Some(error),
                _ => None,
            }
        }
    }
}