enact-config 0.0.2

Unified configuration management for Enact - secure storage with keychain and encrypted files
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
//! Configuration health check — validates ENACT_HOME structure, YAML files, and provider readiness.
//! Used by `enact doctor`, pre-commit hook, and gateway startup.

use std::path::Path;

use serde_yaml::Value as YamlValue;

use crate::agent_def::{AgentDef, AgentRegistry};
use crate::config::Config;
use crate::encrypted_store::EncryptedStore;
use crate::medic;
use crate::project_def::{ProjectDef, ProjectRegistry, TaskBoard};

/// Status of a single check.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CheckStatus {
    Pass,
    Warn,
    Fail,
}

/// A single check result.
#[derive(Debug, Clone)]
pub struct Check {
    pub category: String,
    pub item: String,
    pub status: CheckStatus,
    pub message: String,
}

/// Full report from running all checks.
#[derive(Debug, Clone, Default)]
pub struct DoctorReport {
    pub checks: Vec<Check>,
}

impl DoctorReport {
    pub fn has_failures(&self) -> bool {
        self.checks.iter().any(|c| c.status == CheckStatus::Fail)
    }

    pub fn has_warnings(&self) -> bool {
        self.checks.iter().any(|c| c.status == CheckStatus::Warn)
    }

    fn add(&mut self, category: &str, item: &str, status: CheckStatus, message: &str) {
        self.checks.push(Check {
            category: category.to_string(),
            item: item.to_string(),
            status,
            message: message.to_string(),
        });
    }
}

/// Run all configuration checks against the given ENACT_HOME directory.
pub fn run_checks(home: &Path) -> DoctorReport {
    let mut report = DoctorReport::default();

    check_home_dirs(home, &mut report);
    check_global_config(home, &mut report);
    check_server_config(home, &mut report);
    check_providers_yaml(home, &mut report);
    check_channels_yaml(home, &mut report);
    check_tools_yaml(home, &mut report);
    check_cron_yaml(home, &mut report);
    check_mcp_yaml(home, &mut report);
    check_a2a_yaml(home, &mut report);
    check_skills_yaml(home, &mut report);
    check_context_yaml(home, &mut report);
    check_memory_yaml(home, &mut report);
    check_hooks_yaml(home, &mut report);
    check_commands_dir(home, &mut report);
    check_plugins_dir(home, &mut report);
    check_enact_md(home, &mut report);
    check_agents(home, &mut report);
    check_projects(home, &mut report);
    check_taskboards(home, &mut report);
    check_providers(home, &mut report);
    check_secrets(home, &mut report);
    check_state(home, &mut report);
    check_boundaries(home, &mut report);

    report
}

/// Check nested channel configs (telegram, whatsapp, teams) for extra keys not in reference.
fn check_nested_channel_configs(
    user_val: &YamlValue,
    allowed_keys: &std::collections::HashSet<String>,
    path_str: &str,
    report: &mut DoctorReport,
) {
    let channels = ["telegram", "whatsapp", "teams"];

    for channel in &channels {
        if let Some(channel_config) = user_val.get(channel) {
            if let Some(nested_map) = channel_config.as_mapping() {
                for (key, _) in nested_map {
                    if let Some(key_str) = key.as_str() {
                        let full_path = format!("{}.{}", channel, key_str);
                        if !allowed_keys.contains(&full_path) {
                            report.add(
                                "schema_boundary",
                                path_str,
                                CheckStatus::Warn,
                                &format!(
                                    "extra key in {} config (not in reference): {}",
                                    channel, key_str
                                ),
                            );
                        }
                    }
                }
            }
        }
    }
}

/// Validate channel-specific configuration values for an agent.
fn validate_agent_channel_configs(agent_def: &AgentDef, path_str: &str, report: &mut DoctorReport) {
    // Validate Telegram config
    if let Some(ref telegram) = agent_def.telegram {
        // bot_token should be a valid environment variable name
        if let Some(ref token_env) = telegram.bot_token {
            if token_env.is_empty() {
                report.add(
                    "agent_config",
                    path_str,
                    CheckStatus::Warn,
                    "telegram.bot_token is empty",
                );
            } else if !is_valid_env_var_name(token_env) {
                report.add(
                    "agent_config",
                    path_str,
                    CheckStatus::Warn,
                    &format!(
                        "telegram.bot_token '{}' is not a valid environment variable name",
                        token_env
                    ),
                );
            }
        }

        // bot_name should not be empty if provided
        if let Some(ref bot_name) = telegram.bot_name {
            if bot_name.is_empty() {
                report.add(
                    "agent_config",
                    path_str,
                    CheckStatus::Warn,
                    "telegram.bot_name is empty",
                );
            }
        }
    }

    // Validate WhatsApp config
    if let Some(ref whatsapp) = agent_def.whatsapp {
        if let Some(ref token_env) = whatsapp.bot_token {
            if token_env.is_empty() {
                report.add(
                    "agent_config",
                    path_str,
                    CheckStatus::Warn,
                    "whatsapp.bot_token is empty",
                );
            } else if !is_valid_env_var_name(token_env) {
                report.add(
                    "agent_config",
                    path_str,
                    CheckStatus::Warn,
                    &format!(
                        "whatsapp.bot_token '{}' is not a valid environment variable name",
                        token_env
                    ),
                );
            }
        }

        if let Some(ref bot_name) = whatsapp.bot_name {
            if bot_name.is_empty() {
                report.add(
                    "agent_config",
                    path_str,
                    CheckStatus::Warn,
                    "whatsapp.bot_name is empty",
                );
            }
        }
    }

    // Validate Teams config
    if let Some(ref teams) = agent_def.teams {
        if let Some(ref token_env) = teams.bot_token {
            if token_env.is_empty() {
                report.add(
                    "agent_config",
                    path_str,
                    CheckStatus::Warn,
                    "teams.bot_token is empty",
                );
            } else if !is_valid_env_var_name(token_env) {
                report.add(
                    "agent_config",
                    path_str,
                    CheckStatus::Warn,
                    &format!(
                        "teams.bot_token '{}' is not a valid environment variable name",
                        token_env
                    ),
                );
            }
        }

        if let Some(ref bot_name) = teams.bot_name {
            if bot_name.is_empty() {
                report.add(
                    "agent_config",
                    path_str,
                    CheckStatus::Warn,
                    "teams.bot_name is empty",
                );
            }
        }
    }
}

/// Check if a string is a valid environment variable name.
fn is_valid_env_var_name(name: &str) -> bool {
    if name.is_empty() {
        return false;
    }

    // First character must be alphabetic or underscore
    let first = name.chars().next().unwrap();
    if !first.is_alphabetic() && first != '_' {
        return false;
    }

    // Rest must be alphanumeric or underscore
    name.chars().all(|c| c.is_alphanumeric() || c == '_')
}

/// Check that config files do not contain keys beyond the medic reference (boundary guardrail).
/// Validates both top-level and nested keys (one level deep).
fn check_boundaries(home: &Path, report: &mut DoctorReport) {
    for filename in medic::REFERENCE_FILES {
        if *filename == "agent.yaml" || *filename == "workflow.yaml" {
            // Per-agent files are checked per agent in check_agents / CLI workflow pass
            continue;
        }
        let path = home.join(filename);
        if !path.exists() {
            continue;
        }
        let content = match std::fs::read_to_string(&path) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let user_val: YamlValue = match serde_yaml::from_str(&content) {
            Ok(v) => v,
            Err(_) => continue,
        };
        let reference_str = match medic::reference_yaml(filename) {
            Some(s) => s,
            None => continue,
        };
        let reference_val: YamlValue = match serde_yaml::from_str(reference_str) {
            Ok(v) => v,
            Err(_) => continue,
        };

        // Check top-level keys
        let extra_top = medic::disallowed_top_level_keys(&user_val, &reference_val);
        if !extra_top.is_empty() {
            report.add(
                "schema_boundary",
                path.to_string_lossy().as_ref(),
                CheckStatus::Warn,
                &format!(
                    "extra top-level keys (not in reference): {}",
                    extra_top.join(", ")
                ),
            );
        }

        // Check nested keys (one level deep)
        // Skip providers.yaml since it has dynamic model names that can't be predefined
        if *filename != "providers.yaml" {
            let allowed_nested_keys = medic::allowed_key_paths_shallow(&reference_val);
            check_nested_keys_recursive(
                &user_val,
                &allowed_nested_keys,
                "",
                path.to_string_lossy().as_ref(),
                report,
            );
        }
    }
}

/// Recursively check nested keys in user config against allowed keys from reference.
/// Validates keys at depth 1 (e.g., "channels.telegram", "runtime.max_concurrent").
/// If a parent key exists in the reference, all its children are considered valid.
fn check_nested_keys_recursive(
    user_val: &YamlValue,
    allowed_keys: &std::collections::HashSet<String>,
    prefix: &str,
    path_str: &str,
    report: &mut DoctorReport,
) {
    if let Some(user_map) = user_val.as_mapping() {
        for (key, value) in user_map {
            if let Some(key_str) = key.as_str() {
                let full_path = if prefix.is_empty() {
                    key_str.to_string()
                } else {
                    format!("{}.{}", prefix, key_str)
                };

                // Only check nested keys (depth >= 1)
                if !prefix.is_empty() {
                    // Check if the parent path is in allowed_keys
                    // If parent exists, all children are valid
                    let parent_allowed = prefix.is_empty() || allowed_keys.contains(prefix);
                    let exact_allowed = allowed_keys.contains(&full_path);

                    // Report only if neither parent nor exact path is allowed
                    if !parent_allowed && !exact_allowed {
                        report.add(
                            "schema_boundary",
                            path_str,
                            CheckStatus::Warn,
                            &format!("extra key (not in reference): {}", full_path),
                        );
                    }
                }

                // Recurse into nested mappings (limit to depth 2 to avoid noise)
                if prefix.split('.').count() < 2 && value.as_mapping().is_some() {
                    check_nested_keys_recursive(value, allowed_keys, &full_path, path_str, report);
                }
            }
        }
    }
}

fn check_home_dirs(home: &Path, report: &mut DoctorReport) {
    if !home.exists() {
        report.add(
            "home_dir",
            home.to_string_lossy().as_ref(),
            CheckStatus::Fail,
            "ENACT_HOME directory does not exist",
        );
        return;
    }
    if !home.is_dir() {
        report.add(
            "home_dir",
            home.to_string_lossy().as_ref(),
            CheckStatus::Fail,
            "ENACT_HOME is not a directory",
        );
        return;
    }
    // Required dirs (created by ensure_home_dirs; fail if missing after setup)
    for sub in &["agents", "projects", "state", "logs"] {
        let p = home.join(sub);
        if p.exists() && p.is_dir() {
            report.add("home_dir", sub, CheckStatus::Pass, "ok");
        } else {
            report.add(
                "home_dir",
                sub,
                CheckStatus::Fail,
                "missing or not a directory",
            );
        }
    }
    // Extension dirs (created by ensure_home_dirs; warn if missing so old installs are prompted)
    for sub in &["commands", "plugins", "skills"] {
        let p = home.join(sub);
        if p.exists() && p.is_dir() {
            report.add("home_dir", sub, CheckStatus::Pass, "ok");
        } else {
            report.add(
                "home_dir",
                sub,
                CheckStatus::Warn,
                "missing — run `enact doctor` or any enact command to create it",
            );
        }
    }
}

fn check_global_config(home: &Path, report: &mut DoctorReport) {
    let path = home.join("config.yaml");
    if !path.exists() {
        report.add(
            "global_config",
            "config.yaml",
            CheckStatus::Warn,
            "missing (using defaults)",
        );
        return;
    }
    match Config::load_from_yaml_path(&path) {
        Ok(_) => report.add("global_config", "config.yaml", CheckStatus::Pass, "valid"),
        Err(e) => report.add(
            "global_config",
            "config.yaml",
            CheckStatus::Fail,
            &format!("parse error: {}", e),
        ),
    }
}

fn check_server_config(home: &Path, report: &mut DoctorReport) {
    let path = home.join("config.yaml");
    match Config::load_from_yaml_path(&path) {
        Ok(config) => {
            let port = config.server.port;
            let host = &config.server.host;
            let grpc_port = config.server.grpc_port;
            report.add(
                "server",
                "config.yaml",
                CheckStatus::Pass,
                &format!("host={host} port={port} grpc_port={grpc_port}"),
            );
        }
        Err(_) => {
            report.add(
                "server",
                "config.yaml",
                CheckStatus::Pass,
                "using defaults (host=0.0.0.0 port=8080 grpc_port=50051)",
            );
        }
    }
}

fn check_providers_yaml(home: &Path, report: &mut DoctorReport) {
    let path = home.join("providers.yaml");
    if !path.exists() {
        report.add(
            "providers_yaml",
            "providers.yaml",
            CheckStatus::Warn,
            "missing — copy crates/enact-providers/providers.yaml to ~/.enact/",
        );
        return;
    }
    match std::fs::read_to_string(&path)
        .map_err(|e| e.to_string())
        .and_then(|s| serde_yaml::from_str::<YamlValue>(&s).map_err(|e| e.to_string()))
    {
        Ok(val) => {
            let count = val
                .get("models")
                .and_then(|m| m.as_mapping())
                .map(|m| m.len())
                .unwrap_or(0);
            report.add(
                "providers_yaml",
                "providers.yaml",
                CheckStatus::Pass,
                &format!("{} models loaded", count),
            );
        }
        Err(e) => report.add(
            "providers_yaml",
            "providers.yaml",
            CheckStatus::Fail,
            &format!("parse error: {}", e),
        ),
    }
}

fn check_agents(home: &Path, report: &mut DoctorReport) {
    let agents_dir = home.join("agents");
    if !agents_dir.exists() || !agents_dir.is_dir() {
        return;
    }
    let names = match AgentRegistry::list(home) {
        Ok(n) => n,
        Err(e) => {
            report.add(
                "agents",
                "agents/",
                CheckStatus::Fail,
                &format!("list error: {}", e),
            );
            return;
        }
    };
    let agent_ref =
        medic::reference_yaml("agent.yaml").and_then(|s| serde_yaml::from_str::<YamlValue>(s).ok());

    // Collect allowed nested keys for channel configs from reference
    let allowed_nested_keys: std::collections::HashSet<String> = agent_ref
        .as_ref()
        .map(medic::allowed_key_paths_shallow)
        .unwrap_or_default();

    for name in &names {
        let path = AgentDef::agent_yaml_path(home, name);
        match AgentDef::load(home, name) {
            Ok(Some(def)) => {
                if def.name == *name {
                    report.add(
                        "agents",
                        path.to_string_lossy().as_ref(),
                        CheckStatus::Pass,
                        "valid",
                    );
                } else {
                    report.add(
                        "agents",
                        path.to_string_lossy().as_ref(),
                        CheckStatus::Fail,
                        &format!("name '{}' does not match directory '{}'", def.name, name),
                    );
                }

                // Boundary check: extra keys in agent.yaml (top-level)
                if let (Ok(content), Some(ref_val)) =
                    (std::fs::read_to_string(&path), agent_ref.as_ref())
                {
                    if let Ok(user_val) = serde_yaml::from_str::<YamlValue>(&content) {
                        let extra = medic::disallowed_top_level_keys(&user_val, ref_val);
                        if !extra.is_empty() {
                            report.add(
                                "schema_boundary",
                                path.to_string_lossy().as_ref(),
                                CheckStatus::Warn,
                                &format!(
                                    "extra top-level keys (not in reference): {}",
                                    extra.join(", ")
                                ),
                            );
                        }

                        // Check nested channel configs for extra keys
                        check_nested_channel_configs(
                            &user_val,
                            &allowed_nested_keys,
                            path.to_string_lossy().as_ref(),
                            report,
                        );
                    }
                }

                // Validate channel-specific configuration
                validate_agent_channel_configs(&def, path.to_string_lossy().as_ref(), report);
            }
            Ok(None) => {}
            Err(e) => report.add(
                "agents",
                path.to_string_lossy().as_ref(),
                CheckStatus::Fail,
                &format!("parse error: {}", e),
            ),
        }
    }
}

fn check_projects(home: &Path, report: &mut DoctorReport) {
    let slugs = match ProjectRegistry::list(home) {
        Ok(s) => s,
        Err(e) => {
            report.add(
                "projects",
                "projects/",
                CheckStatus::Fail,
                &format!("list error: {}", e),
            );
            return;
        }
    };
    let agent_names: std::collections::HashSet<_> = AgentRegistry::list(home)
        .unwrap_or_default()
        .into_iter()
        .collect();

    for slug in &slugs {
        let path = ProjectDef::project_yaml_path(home, slug);
        match ProjectDef::load(home, slug) {
            Ok(Some(def)) => {
                if def.slug != *slug {
                    report.add(
                        "projects",
                        path.to_string_lossy().as_ref(),
                        CheckStatus::Fail,
                        &format!("slug '{}' does not match directory '{}'", def.slug, slug),
                    );
                } else {
                    report.add(
                        "projects",
                        path.to_string_lossy().as_ref(),
                        CheckStatus::Pass,
                        "valid",
                    );
                    for agent in &def.agents {
                        if !agent_names.contains(agent) {
                            report.add(
                                "projects",
                                path.to_string_lossy().as_ref(),
                                CheckStatus::Warn,
                                &format!("referenced agent '{}' not found", agent),
                            );
                        }
                    }
                }
            }
            Ok(None) => {}
            Err(e) => report.add(
                "projects",
                path.to_string_lossy().as_ref(),
                CheckStatus::Fail,
                &format!("parse error: {}", e),
            ),
        }
    }
}

fn check_taskboards(home: &Path, report: &mut DoctorReport) {
    let slugs = match ProjectRegistry::list(home) {
        Ok(s) => s,
        Err(_) => return,
    };
    for slug in &slugs {
        let path = ProjectDef::taskboard_path(home, slug);
        if !path.exists() {
            continue;
        }
        match TaskBoard::load(home, slug) {
            Ok(_) => report.add(
                "taskboards",
                path.to_string_lossy().as_ref(),
                CheckStatus::Pass,
                "valid",
            ),
            Err(e) => report.add(
                "taskboards",
                path.to_string_lossy().as_ref(),
                CheckStatus::Warn,
                &format!("parse error: {}", e),
            ),
        }
    }
}

fn check_providers(home: &Path, report: &mut DoctorReport) {
    // Check for any common API key env vars (AZURE_API_KEY is used in config.yml)
    let has_env_key = std::env::var("AZURE_API_KEY").is_ok()
        || std::env::var("OPENAI_API_KEY").is_ok()
        || std::env::var("AZURE_OPENAI_API_KEY").is_ok();

    if has_env_key {
        report.add("providers", "env", CheckStatus::Pass, "API key set via env");
        return;
    }

    let config_path = home.join("config.yaml");
    if config_path.exists() {
        if let Ok(config) = Config::load_from_yaml_path(&config_path) {
            let has_azure = config
                .providers
                .azure
                .as_ref()
                .and_then(|a| a.api_key.as_deref())
                .is_some_and(|k| !k.is_empty());
            let has_openai = config
                .providers
                .openai
                .as_ref()
                .and_then(|a| a.api_key.as_deref())
                .is_some_and(|k| !k.is_empty());
            if has_azure || has_openai {
                report.add(
                    "providers",
                    "config.yaml",
                    CheckStatus::Pass,
                    "API key in config",
                );
                return;
            }
        }
    }

    report.add(
        "providers",
        "env/config",
        CheckStatus::Warn,
        "No API key found (set AZURE_API_KEY, OPENAI_API_KEY, or AZURE_OPENAI_API_KEY, or add to config.yaml)",
    );
}

fn check_secrets(home: &Path, report: &mut DoctorReport) {
    let path = home.join("config.encrypted");
    if !path.exists() {
        report.add(
            "secrets",
            "config.encrypted",
            CheckStatus::Pass,
            "not present (optional)",
        );
        return;
    }
    match EncryptedStore::new(&path) {
        Ok(store) => {
            if store.load().is_ok() {
                report.add("secrets", "config.encrypted", CheckStatus::Pass, "readable");
            } else {
                report.add(
                    "secrets",
                    "config.encrypted",
                    CheckStatus::Warn,
                    "exists but decryption failed (check ENACT_CONFIG_ENCRYPTION_KEY)",
                );
            }
        }
        Err(e) => report.add(
            "secrets",
            "config.encrypted",
            CheckStatus::Warn,
            &format!("open error: {}", e),
        ),
    }
}

fn check_state(home: &Path, report: &mut DoctorReport) {
    let pid_file = home.join("state").join("daemon.pid");
    if !pid_file.exists() {
        report.add(
            "state",
            "state/daemon.pid",
            CheckStatus::Pass,
            "not present",
        );
        return;
    }
    let content = match std::fs::read_to_string(&pid_file) {
        Ok(c) => c,
        Err(e) => {
            report.add(
                "state",
                "state/daemon.pid",
                CheckStatus::Warn,
                &format!("read error: {}", e),
            );
            return;
        }
    };
    let pid: u32 = match content.trim().parse() {
        Ok(p) => p,
        Err(_) => {
            report.add(
                "state",
                "state/daemon.pid",
                CheckStatus::Warn,
                "invalid PID",
            );
            return;
        }
    };
    if !is_process_running(pid) {
        report.add(
            "state",
            "state/daemon.pid",
            CheckStatus::Warn,
            "stale PID file (process not running)",
        );
    } else {
        report.add(
            "state",
            "state/daemon.pid",
            CheckStatus::Pass,
            "daemon running",
        );
    }
}

fn check_hooks_yaml(home: &Path, report: &mut DoctorReport) {
    let path = home.join("hooks.yaml");
    if !path.exists() {
        report.add(
            "hooks_yaml",
            "hooks.yaml",
            CheckStatus::Pass,
            "not present (optional — no global lifecycle hooks configured)",
        );
        return;
    }
    match std::fs::read_to_string(&path)
        .map_err(|e| e.to_string())
        .and_then(|s| serde_yaml::from_str::<YamlValue>(&s).map_err(|e| e.to_string()))
    {
        Ok(val) => {
            let count = val
                .get("hooks")
                .and_then(|h| h.as_sequence())
                .map(|s| s.len())
                .unwrap_or(0);
            report.add(
                "hooks_yaml",
                "hooks.yaml",
                CheckStatus::Pass,
                &format!("{} hook(s) configured", count),
            );
        }
        Err(e) => report.add(
            "hooks_yaml",
            "hooks.yaml",
            CheckStatus::Fail,
            &format!("parse error: {}", e),
        ),
    }
}

fn check_commands_dir(home: &Path, report: &mut DoctorReport) {
    let dir = home.join("commands");
    if !dir.exists() {
        return;
    }
    let count = std::fs::read_dir(&dir)
        .map(|rd| {
            rd.flatten()
                .filter(|e| e.path().extension().is_some_and(|ext| ext == "md"))
                .count()
        })
        .unwrap_or(0);
    report.add(
        "commands_dir",
        "commands/",
        CheckStatus::Pass,
        &format!("{} slash command(s) available", count),
    );
}

fn check_plugins_dir(home: &Path, report: &mut DoctorReport) {
    let dir = home.join("plugins");
    if !dir.exists() {
        return;
    }
    let count = std::fs::read_dir(&dir)
        .map(|rd| {
            rd.flatten()
                .filter(|e| {
                    e.path().is_dir() && e.path().join(".enact-plugin").join("plugin.json").exists()
                })
                .count()
        })
        .unwrap_or(0);
    report.add(
        "plugins_dir",
        "plugins/",
        CheckStatus::Pass,
        &format!("{} plugin(s) installed", count),
    );
}

fn check_enact_md(home: &Path, report: &mut DoctorReport) {
    let path = home.join("ENACT.md");
    if !path.exists() {
        report.add(
            "enact_md",
            "ENACT.md",
            CheckStatus::Pass,
            "not present (optional — global agent system prompt context)",
        );
        return;
    }
    let size = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
    report.add(
        "enact_md",
        "ENACT.md",
        CheckStatus::Pass,
        &format!(
            "present ({} bytes) — injected into system prompt at session start",
            size
        ),
    );
}

fn check_channels_yaml(home: &Path, report: &mut DoctorReport) {
    let path = home.join("channels.yaml");
    if !path.exists() {
        report.add(
            "channels_yaml",
            "channels.yaml",
            CheckStatus::Warn,
            "missing (using defaults)",
        );
        return;
    }
    match std::fs::read_to_string(&path)
        .map_err(|e| e.to_string())
        .and_then(|s| serde_yaml::from_str::<YamlValue>(&s).map_err(|e| e.to_string()))
    {
        Ok(val) => {
            let channels = val
                .get("channels")
                .and_then(|c| c.as_mapping())
                .map(|m| m.len())
                .unwrap_or(0);
            report.add(
                "channels_yaml",
                "channels.yaml",
                CheckStatus::Pass,
                &format!("{} channel(s) configured", channels),
            );
        }
        Err(e) => report.add(
            "channels_yaml",
            "channels.yaml",
            CheckStatus::Fail,
            &format!("parse error: {}", e),
        ),
    }
}

fn check_tools_yaml(home: &Path, report: &mut DoctorReport) {
    let path = home.join("tools.yaml");
    if !path.exists() {
        report.add(
            "tools_yaml",
            "tools.yaml",
            CheckStatus::Warn,
            "missing (using defaults)",
        );
        return;
    }
    match std::fs::read_to_string(&path)
        .map_err(|e| e.to_string())
        .and_then(|s| serde_yaml::from_str::<YamlValue>(&s).map_err(|e| e.to_string()))
    {
        Ok(val) => {
            let sections: Vec<&str> = ["shell", "file", "http", "security", "git"]
                .iter()
                .filter(|&&k| val.get(k).is_some())
                .copied()
                .collect();
            report.add(
                "tools_yaml",
                "tools.yaml",
                CheckStatus::Pass,
                &format!("sections: {}", sections.join(", ")),
            );
        }
        Err(e) => report.add(
            "tools_yaml",
            "tools.yaml",
            CheckStatus::Fail,
            &format!("parse error: {}", e),
        ),
    }
}

fn check_cron_yaml(home: &Path, report: &mut DoctorReport) {
    let path = home.join("cron.yaml");
    if !path.exists() {
        report.add(
            "cron_yaml",
            "cron.yaml",
            CheckStatus::Warn,
            "missing (using defaults)",
        );
        return;
    }
    match std::fs::read_to_string(&path)
        .map_err(|e| e.to_string())
        .and_then(|s| serde_yaml::from_str::<YamlValue>(&s).map_err(|e| e.to_string()))
    {
        Ok(val) => {
            let db_path = val
                .get("store")
                .and_then(|s| s.get("db_path"))
                .and_then(|p| p.as_str())
                .unwrap_or("(default)");
            report.add(
                "cron_yaml",
                "cron.yaml",
                CheckStatus::Pass,
                &format!("db_path={}", db_path),
            );
        }
        Err(e) => report.add(
            "cron_yaml",
            "cron.yaml",
            CheckStatus::Fail,
            &format!("parse error: {}", e),
        ),
    }
}

fn check_mcp_yaml(home: &Path, report: &mut DoctorReport) {
    let path = home.join("mcp.yaml");
    if !path.exists() {
        report.add(
            "mcp_yaml",
            "mcp.yaml",
            CheckStatus::Warn,
            "missing (using defaults)",
        );
        return;
    }
    match std::fs::read_to_string(&path)
        .map_err(|e| e.to_string())
        .and_then(|s| serde_yaml::from_str::<YamlValue>(&s).map_err(|e| e.to_string()))
    {
        Ok(val) => {
            let servers = val
                .get("servers")
                .and_then(|s| s.as_sequence())
                .map(|s| s.len())
                .unwrap_or(0);
            let protocol = val
                .get("client")
                .and_then(|c| c.get("protocol_version"))
                .and_then(|v| v.as_str())
                .unwrap_or("unknown");
            report.add(
                "mcp_yaml",
                "mcp.yaml",
                CheckStatus::Pass,
                &format!("{} server(s), protocol={}", servers, protocol),
            );
        }
        Err(e) => report.add(
            "mcp_yaml",
            "mcp.yaml",
            CheckStatus::Fail,
            &format!("parse error: {}", e),
        ),
    }
}

fn check_a2a_yaml(home: &Path, report: &mut DoctorReport) {
    let path = home.join("a2a.yaml");
    if !path.exists() {
        report.add(
            "a2a_yaml",
            "a2a.yaml",
            CheckStatus::Warn,
            "missing (using defaults)",
        );
        return;
    }
    match std::fs::read_to_string(&path)
        .map_err(|e| e.to_string())
        .and_then(|s| serde_yaml::from_str::<YamlValue>(&s).map_err(|e| e.to_string()))
    {
        Ok(val) => {
            let provider = val
                .get("default_provider")
                .and_then(|p| p.as_str())
                .unwrap_or("(default)");
            let model = val
                .get("default_model")
                .and_then(|m| m.as_str())
                .unwrap_or("(default)");
            report.add(
                "a2a_yaml",
                "a2a.yaml",
                CheckStatus::Pass,
                &format!("provider={} model={}", provider, model),
            );
        }
        Err(e) => report.add(
            "a2a_yaml",
            "a2a.yaml",
            CheckStatus::Fail,
            &format!("parse error: {}", e),
        ),
    }
}

fn check_skills_yaml(home: &Path, report: &mut DoctorReport) {
    let path = home.join("skills.yaml");
    if !path.exists() {
        report.add(
            "skills_yaml",
            "skills.yaml",
            CheckStatus::Warn,
            "missing (using defaults)",
        );
        return;
    }
    match std::fs::read_to_string(&path)
        .map_err(|e| e.to_string())
        .and_then(|s| serde_yaml::from_str::<YamlValue>(&s).map_err(|e| e.to_string()))
    {
        Ok(val) => {
            let enabled = val.get("enabled").and_then(|e| e.as_bool()).unwrap_or(true);
            let repo = val
                .get("open_skills_repo_url")
                .and_then(|r| r.as_str())
                .is_some();
            report.add(
                "skills_yaml",
                "skills.yaml",
                CheckStatus::Pass,
                &format!("enabled={} repo_configured={}", enabled, repo),
            );
        }
        Err(e) => report.add(
            "skills_yaml",
            "skills.yaml",
            CheckStatus::Fail,
            &format!("parse error: {}", e),
        ),
    }
}

fn check_context_yaml(home: &Path, report: &mut DoctorReport) {
    let path = home.join("context.yaml");
    if !path.exists() {
        report.add(
            "context_yaml",
            "context.yaml",
            CheckStatus::Warn,
            "missing (using defaults)",
        );
        return;
    }
    match std::fs::read_to_string(&path)
        .map_err(|e| e.to_string())
        .and_then(|s| serde_yaml::from_str::<YamlValue>(&s).map_err(|e| e.to_string()))
    {
        Ok(val) => {
            let preset = val
                .get("default_preset")
                .and_then(|p| p.as_str())
                .unwrap_or("(default)");
            let total = val
                .get("budget")
                .and_then(|b| b.get("total_tokens"))
                .and_then(|t| t.as_u64())
                .unwrap_or(0);
            report.add(
                "context_yaml",
                "context.yaml",
                CheckStatus::Pass,
                &format!("preset={} budget={} tokens", preset, total),
            );
        }
        Err(e) => report.add(
            "context_yaml",
            "context.yaml",
            CheckStatus::Fail,
            &format!("parse error: {}", e),
        ),
    }
}

fn check_memory_yaml(home: &Path, report: &mut DoctorReport) {
    let path = home.join("memory.yaml");
    if !path.exists() {
        report.add(
            "memory_yaml",
            "memory.yaml",
            CheckStatus::Warn,
            "missing (using defaults)",
        );
        return;
    }
    match std::fs::read_to_string(&path)
        .map_err(|e| e.to_string())
        .and_then(|s| serde_yaml::from_str::<YamlValue>(&s).map_err(|e| e.to_string()))
    {
        Ok(val) => {
            let backend = val
                .get("backend")
                .and_then(|b| b.as_str())
                .unwrap_or("(default)");
            let db_path = val
                .get("db_path")
                .and_then(|p| p.as_str())
                .unwrap_or("(default)");
            report.add(
                "memory_yaml",
                "memory.yaml",
                CheckStatus::Pass,
                &format!("backend={} db_path={}", backend, db_path),
            );
        }
        Err(e) => report.add(
            "memory_yaml",
            "memory.yaml",
            CheckStatus::Fail,
            &format!("parse error: {}", e),
        ),
    }
}

#[cfg(unix)]
fn is_process_running(pid: u32) -> bool {
    use std::process::Command;
    let out = Command::new("kill").args(["-0", &pid.to_string()]).output();
    out.map(|o| o.status.success()).unwrap_or(false)
}

#[cfg(not(unix))]
fn is_process_running(_pid: u32) -> bool {
    // On Windows we could use tasklist; for now assume running to avoid false warn
    true
}

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

    #[test]
    fn report_has_failures() {
        let mut r = DoctorReport::default();
        assert!(!r.has_failures());
        r.add("a", "b", CheckStatus::Warn, "w");
        assert!(!r.has_failures());
        r.add("a", "c", CheckStatus::Fail, "f");
        assert!(r.has_failures());
    }

    #[test]
    fn run_checks_on_nonexistent_dir() {
        let report = run_checks(Path::new("/nonexistent_enact_home_12345"));
        assert!(report.has_failures());
        assert!(report
            .checks
            .iter()
            .any(|c| c.category == "home_dir" && c.status == CheckStatus::Fail));
    }
}