vtcode-core 0.98.4

Core library for VT Code - a Rust-based terminal coding agent
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
//! Skill Validation System
//!
//! Validates skill definitions, configurations, and executions to ensure:
//! - Proper SKILL.md format and metadata
//! - Valid JSON schemas for tool arguments
//! - Executable scripts and tools
//! - Security and safety checks
//! - Performance and resource usage validation

use crate::skills::cli_bridge::CliToolConfig;
use crate::skills::manifest::parse_skill_file;
use crate::utils::file_utils::read_file_with_context_sync;
use anyhow::Result;
use hashbrown::HashMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::path::{Path, PathBuf};
use std::time::{Instant, SystemTime};
use tracing::info;

/// Validation configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationConfig {
    /// Enable security checks
    pub enable_security_checks: bool,

    /// Enable performance validation
    pub enable_performance_checks: bool,

    /// Maximum execution time for validation tests (seconds)
    pub max_validation_time: u64,

    /// Maximum script size (bytes)
    pub max_script_size: usize,

    /// Allowed script extensions
    pub allowed_script_extensions: Vec<String>,

    /// Blocked commands/patterns
    pub blocked_commands: Vec<String>,

    /// Required metadata fields
    pub required_metadata_fields: Vec<String>,

    /// Enable JSON schema validation
    pub enable_schema_validation: bool,

    /// Strict mode (fail on warnings)
    pub strict_mode: bool,
}

impl Default for ValidationConfig {
    fn default() -> Self {
        Self {
            enable_security_checks: true,
            enable_performance_checks: true,
            max_validation_time: 30,
            max_script_size: 1024 * 1024, // 1MB
            allowed_script_extensions: vec![
                "py".to_string(),
                "sh".to_string(),
                "bash".to_string(),
                "js".to_string(),
                "ts".to_string(),
                "rb".to_string(),
                "pl".to_string(),
                "go".to_string(),
                "rs".to_string(),
            ],
            blocked_commands: vec![
                "rm -rf /".to_string(),
                "sudo".to_string(),
                "chmod 777".to_string(),
                "curl.*|.*sh".to_string(),
                "wget.*|.*sh".to_string(),
            ],
            required_metadata_fields: vec!["name".to_string(), "description".to_string()],
            enable_schema_validation: true,
            strict_mode: false,
        }
    }
}

/// Validation result with detailed report
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationReport {
    /// Overall validation status
    pub status: ValidationStatus,

    /// Skill name
    pub skill_name: String,

    /// Validation timestamp
    pub timestamp: chrono::DateTime<chrono::Utc>,

    /// Individual check results
    pub checks: HashMap<String, CheckResult>,

    /// Performance metrics
    pub performance: PerformanceMetrics,

    /// Security assessment
    pub security: SecurityAssessment,

    /// Recommendations for improvement
    pub recommendations: Vec<String>,
}

/// Validation status
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ValidationStatus {
    /// All checks passed
    Valid,
    /// Some warnings, but skill is usable
    Warning,
    /// Critical issues, skill should not be used
    Invalid,
}

/// Individual check result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CheckResult {
    /// Check name
    pub name: String,

    /// Check status
    pub status: CheckStatus,

    /// Detailed message
    pub message: String,

    /// Additional details
    pub details: Option<Value>,

    /// Execution time
    pub execution_time_ms: u64,
}

/// Check status
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum CheckStatus {
    /// Check passed
    Passed,
    /// Check passed with warnings
    Warning,
    /// Check failed
    Failed,
    /// Check was skipped
    Skipped,
}

/// Performance metrics
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PerformanceMetrics {
    /// Total validation time
    pub total_time_ms: u64,

    /// Skill loading time
    pub loading_time_ms: u64,

    /// Schema validation time
    pub schema_validation_time_ms: u64,

    /// Script validation time
    pub script_validation_time_ms: u64,

    /// Memory usage estimate (bytes)
    pub memory_usage_bytes: usize,

    /// Token usage estimate
    pub token_usage_estimate: usize,
}

/// Security assessment
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SecurityAssessment {
    /// Overall security level
    pub security_level: SecurityLevel,

    /// Security warnings
    pub warnings: Vec<SecurityWarning>,

    /// Blocked content found
    pub blocked_content: Vec<String>,

    /// Safe to execute
    pub safe_to_execute: bool,
}

/// Security level
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub enum SecurityLevel {
    /// No security concerns
    #[default]
    Safe,
    /// Minor concerns, generally safe
    LowRisk,
    /// Moderate concerns, review recommended
    MediumRisk,
    /// High concerns, not recommended
    HighRisk,
}

/// Security warning
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityWarning {
    /// Warning type
    pub warning_type: String,

    /// Warning message
    pub message: String,

    /// Severity level
    pub severity: SecurityLevel,

    /// Suggested remediation
    pub suggestion: Option<String>,
}

/// Skill validator
pub struct SkillValidator {
    config: ValidationConfig,
    // Note: Validator from jsonschema crate doesn't implement Clone,
    // so we cache the validation result keyed by path and mtime instead.
    schema_validation_cache: HashMap<PathBuf, (SystemTime, CheckResult)>,
}

impl SkillValidator {
    /// Create new validator with default configuration
    pub fn new() -> Self {
        Self::with_config(ValidationConfig::default())
    }
}

impl Default for SkillValidator {
    fn default() -> Self {
        Self::new()
    }
}

impl SkillValidator {
    /// Create new validator with custom configuration
    pub fn with_config(config: ValidationConfig) -> Self {
        Self {
            config,
            schema_validation_cache: HashMap::new(),
        }
    }

    /// Validate a traditional skill from directory
    pub async fn validate_skill_directory(
        &mut self,
        skill_path: &Path,
    ) -> Result<ValidationReport> {
        let start_time = Instant::now();
        let mut checks = HashMap::new();
        // Performance tracking initialized at end

        info!("Validating skill directory: {}", skill_path.display());

        // Check if directory exists
        let check_result = self.check_directory_exists(skill_path).await;
        checks.insert("directory_exists".to_string(), check_result);

        // Validate SKILL.md file
        let skill_file = skill_path.join("SKILL.md");
        let check_result = self.validate_skill_file(&skill_file).await;
        checks.insert("skill_file_valid".to_string(), check_result.clone());

        let skill_name = if let Some(manifest) = &check_result.details {
            manifest
                .get("name")
                .and_then(|v| v.as_str())
                .unwrap_or("unknown")
                .to_string()
        } else {
            "unknown".to_string()
        };

        // Validate scripts directory
        let scripts_dir = skill_path.join("scripts");
        if scripts_dir.exists() {
            let check_result = self.validate_scripts_directory(&scripts_dir).await;
            checks.insert("scripts_valid".to_string(), check_result);
        }

        // Validate resources
        let resources_result = self.validate_resources(skill_path).await;
        for (name, result) in resources_result {
            checks.insert(format!("resource_{}", name), result);
        }

        // Security assessment
        let security = self.assess_security(&checks);

        // Generate recommendations
        let recommendations = self.generate_recommendations(&checks, &security);

        // Determine overall status
        let status = self.determine_overall_status(&checks, &security);

        let performance = PerformanceMetrics {
            total_time_ms: start_time.elapsed().as_millis() as u64,
            ..Default::default()
        };

        Ok(ValidationReport {
            status,
            skill_name,
            timestamp: chrono::Utc::now(),
            checks,
            performance,
            security,
            recommendations,
        })
    }

    /// Validate CLI tool configuration
    pub async fn validate_cli_tool(&mut self, config: &CliToolConfig) -> Result<ValidationReport> {
        let start_time = Instant::now();
        let mut checks = HashMap::new();

        info!("Validating CLI tool: {}", config.name);

        // Check executable exists
        let check_result = self.check_executable_exists(&config.executable_path).await;
        checks.insert("executable_exists".to_string(), check_result);

        // Check executable permissions
        let check_result = self
            .check_executable_permissions(&config.executable_path)
            .await;
        checks.insert("executable_permissions".to_string(), check_result);

        // Validate README if present
        if let Some(readme_path) = &config.readme_path {
            let check_result = self.validate_readme_file(readme_path).await;
            checks.insert("readme_valid".to_string(), check_result);
        }

        // Validate JSON schema if present
        if let Some(schema_path) = &config.schema_path {
            let check_result = self.validate_json_schema(schema_path).await;
            checks.insert("schema_valid".to_string(), check_result);
        }

        // Test tool execution (basic)
        let check_result = self.test_tool_execution(config).await;
        checks.insert("tool_executable".to_string(), check_result);

        // Security assessment
        let security = self.assess_security(&checks);

        // Generate recommendations
        let recommendations = self.generate_recommendations(&checks, &security);

        // Determine overall status
        let status = self.determine_overall_status(&checks, &security);

        let performance = PerformanceMetrics {
            total_time_ms: start_time.elapsed().as_millis() as u64,
            ..Default::default()
        };

        Ok(ValidationReport {
            status,
            skill_name: config.name.clone(),
            timestamp: chrono::Utc::now(),
            checks,
            performance,
            security,
            recommendations,
        })
    }

    /// Check if directory exists
    async fn check_directory_exists(&self, path: &Path) -> CheckResult {
        let start_time = Instant::now();

        let status = if path.exists() && path.is_dir() {
            CheckStatus::Passed
        } else {
            CheckStatus::Failed
        };

        let message = if status == CheckStatus::Passed {
            format!("Directory exists: {}", path.display())
        } else {
            format!("Directory does not exist: {}", path.display())
        };

        CheckResult {
            name: "directory_exists".to_string(),
            status,
            message,
            details: None,
            execution_time_ms: start_time.elapsed().as_millis() as u64,
        }
    }

    /// Validate SKILL.md file
    async fn validate_skill_file(&mut self, skill_file: &Path) -> CheckResult {
        let start_time = Instant::now();

        if !skill_file.exists() {
            return CheckResult {
                name: "skill_file_valid".to_string(),
                status: CheckStatus::Failed,
                message: format!("SKILL.md file not found: {}", skill_file.display()),
                details: None,
                execution_time_ms: start_time.elapsed().as_millis() as u64,
            };
        }

        match parse_skill_file(skill_file.parent().unwrap_or_else(|| Path::new("."))) {
            Ok((manifest, _instructions)) => {
                if let Err(err) = manifest.validate() {
                    let mut details = serde_json::Map::new();
                    details.insert("name".to_string(), Value::String(manifest.name.clone()));
                    details.insert(
                        "description".to_string(),
                        Value::String(manifest.description.clone()),
                    );
                    return CheckResult {
                        name: "skill_file_valid".to_string(),
                        status: CheckStatus::Failed,
                        message: format!("SKILL.md validation failed: {}", err),
                        details: Some(Value::Object(details)),
                        execution_time_ms: start_time.elapsed().as_millis() as u64,
                    };
                }

                // Validate required fields
                let mut warnings = vec![];

                for field in &self.config.required_metadata_fields {
                    match field.as_str() {
                        "name" => {
                            if manifest.name.is_empty() {
                                warnings.push("Skill name is empty");
                            }
                        }
                        "description" => {
                            if manifest.description.is_empty() {
                                warnings.push("Skill description is empty");
                            }
                        }
                        _ => {}
                    }
                }

                let status = if warnings.is_empty() {
                    CheckStatus::Passed
                } else {
                    CheckStatus::Warning
                };

                let message = if status == CheckStatus::Passed {
                    format!("SKILL.md is valid: {}", manifest.name)
                } else {
                    format!("SKILL.md has warnings: {}", warnings.join(", "))
                };

                let mut details = serde_json::Map::new();
                details.insert("name".to_string(), Value::String(manifest.name.clone()));
                details.insert(
                    "description".to_string(),
                    Value::String(manifest.description.clone()),
                );
                details.insert(
                    "warnings".to_string(),
                    serde_json::to_value(&warnings).unwrap_or_else(|_| Value::Array(vec![])),
                );

                CheckResult {
                    name: "skill_file_valid".to_string(),
                    status,
                    message,
                    details: Some(Value::Object(details)),
                    execution_time_ms: start_time.elapsed().as_millis() as u64,
                }
            }
            Err(e) => CheckResult {
                name: "skill_file_valid".to_string(),
                status: CheckStatus::Failed,
                message: format!("Failed to parse SKILL.md: {:#}", e),
                details: None,
                execution_time_ms: start_time.elapsed().as_millis() as u64,
            },
        }
    }

    /// Validate scripts directory
    async fn validate_scripts_directory(&self, scripts_dir: &Path) -> CheckResult {
        let start_time = Instant::now();
        let mut issues = vec![];

        let entries = match std::fs::read_dir(scripts_dir) {
            Ok(entries) => entries,
            Err(error) => {
                return CheckResult {
                    name: "scripts_valid".to_string(),
                    status: CheckStatus::Failed,
                    message: format!(
                        "Failed to read scripts directory {}: {}",
                        scripts_dir.display(),
                        error
                    ),
                    details: None,
                    execution_time_ms: start_time.elapsed().as_millis() as u64,
                };
            }
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_file() {
                // Check file size
                if let Some(metadata) = entry
                    .metadata()
                    .ok()
                    .filter(|m| m.len() > self.config.max_script_size as u64)
                {
                    issues.push(format!(
                        "Script too large: {} ({} bytes)",
                        path.display(),
                        metadata.len()
                    ));
                }

                // Check extension
                if let Some(ext) = path.extension().and_then(|e| e.to_str()).filter(|e| {
                    !self
                        .config
                        .allowed_script_extensions
                        .contains(&e.to_string())
                }) {
                    issues.push(format!("Unsupported script type: {}", ext));
                }

                // Security check
                if self.config.enable_security_checks
                    && let Ok(content) = read_file_with_context_sync(&path, "skill script")
                {
                    for blocked in &self.config.blocked_commands {
                        if content.contains(blocked) {
                            issues
                                .push(format!("Potentially dangerous content found: {}", blocked));
                        }
                    }
                }
            }
        }

        let status = if issues.is_empty() {
            CheckStatus::Passed
        } else {
            CheckStatus::Warning
        };

        let message = if status == CheckStatus::Passed {
            "Scripts directory is valid".to_string()
        } else {
            format!("Scripts directory has issues: {}", issues.join(", "))
        };

        CheckResult {
            name: "scripts_valid".to_string(),
            status,
            message,
            details: Some(serde_json::to_value(&issues).unwrap_or_else(|_| Value::Array(vec![]))),
            execution_time_ms: start_time.elapsed().as_millis() as u64,
        }
    }

    /// Validate resources
    async fn validate_resources(&self, skill_path: &Path) -> HashMap<String, CheckResult> {
        let mut results = HashMap::new();

        // Check for common resource directories
        for resource_dir in &["templates", "data", "config"] {
            let dir_path = skill_path.join(resource_dir);
            if dir_path.exists() {
                let result = self
                    .validate_resource_directory(&dir_path, resource_dir)
                    .await;
                results.insert(resource_dir.to_string(), result);
            }
        }

        results
    }

    /// Validate resource directory
    async fn validate_resource_directory(
        &self,
        dir_path: &Path,
        resource_type: &str,
    ) -> CheckResult {
        let start_time = Instant::now();

        let mut issues = vec![];

        let entries = match std::fs::read_dir(dir_path) {
            Ok(entries) => entries,
            Err(error) => {
                return CheckResult {
                    name: format!("resource_{}", resource_type),
                    status: CheckStatus::Failed,
                    message: format!(
                        "Failed to read resource directory {}: {}",
                        dir_path.display(),
                        error
                    ),
                    details: None,
                    execution_time_ms: start_time.elapsed().as_millis() as u64,
                };
            }
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_file() {
                // Check file size
                if let Some(metadata) = entry.metadata().ok().filter(|m| m.len() > 10 * 1024 * 1024)
                {
                    // 10MB limit for resources
                    issues.push(format!(
                        "Resource file too large: {} ({} bytes)",
                        path.display(),
                        metadata.len()
                    ));
                }
            }
        }

        let status = if issues.is_empty() {
            CheckStatus::Passed
        } else {
            CheckStatus::Warning
        };

        let message = if status == CheckStatus::Passed {
            format!("{} directory is valid", resource_type)
        } else {
            format!(
                "{} directory has issues: {}",
                resource_type,
                issues.join(", ")
            )
        };

        CheckResult {
            name: format!("resource_{}", resource_type),
            status,
            message,
            details: Some(serde_json::to_value(&issues).unwrap_or_else(|_| Value::Array(vec![]))),
            execution_time_ms: start_time.elapsed().as_millis() as u64,
        }
    }

    /// Check if executable exists
    async fn check_executable_exists(&self, path: &Path) -> CheckResult {
        let start_time = Instant::now();

        let status = if path.exists() {
            CheckStatus::Passed
        } else {
            CheckStatus::Failed
        };

        let message = if status == CheckStatus::Passed {
            format!("Executable exists: {}", path.display())
        } else {
            format!("Executable not found: {}", path.display())
        };

        CheckResult {
            name: "executable_exists".to_string(),
            status,
            message,
            details: None,
            execution_time_ms: start_time.elapsed().as_millis() as u64,
        }
    }

    /// Check executable permissions
    #[allow(unused_variables)]
    async fn check_executable_permissions(&self, path: &Path) -> CheckResult {
        let start_time = Instant::now();

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;

            if let Ok(metadata) = std::fs::metadata(path) {
                let permissions = metadata.permissions();
                let is_executable = permissions.mode() & 0o111 != 0;

                let status = if is_executable {
                    CheckStatus::Passed
                } else {
                    CheckStatus::Failed
                };

                let message = if status == CheckStatus::Passed {
                    "Executable has proper permissions".to_string()
                } else {
                    "Executable lacks execute permissions".to_string()
                };

                return CheckResult {
                    name: "executable_permissions".to_string(),
                    status,
                    message,
                    details: None,
                    execution_time_ms: start_time.elapsed().as_millis() as u64,
                };
            }
        }

        // Windows or metadata error - assume valid
        CheckResult {
            name: "executable_permissions".to_string(),
            status: CheckStatus::Passed,
            message: "Permission check skipped (Windows or metadata error)".to_string(),
            details: None,
            execution_time_ms: start_time.elapsed().as_millis() as u64,
        }
    }

    /// Validate README file
    async fn validate_readme_file(&self, readme_path: &Path) -> CheckResult {
        let start_time = Instant::now();

        if !readme_path.exists() {
            return CheckResult {
                name: "readme_valid".to_string(),
                status: CheckStatus::Warning,
                message: "README file not found".to_string(),
                details: None,
                execution_time_ms: start_time.elapsed().as_millis() as u64,
            };
        }

        match read_file_with_context_sync(readme_path, "skill README") {
            Ok(content) => {
                if content.len() < 100 {
                    CheckResult {
                        name: "readme_valid".to_string(),
                        status: CheckStatus::Warning,
                        message: "README file is very short".to_string(),
                        details: Some(serde_json::json!({"length": content.len()})),
                        execution_time_ms: start_time.elapsed().as_millis() as u64,
                    }
                } else {
                    CheckResult {
                        name: "readme_valid".to_string(),
                        status: CheckStatus::Passed,
                        message: "README file is valid".to_string(),
                        details: Some(serde_json::json!({"length": content.len()})),
                        execution_time_ms: start_time.elapsed().as_millis() as u64,
                    }
                }
            }
            Err(e) => CheckResult {
                name: "readme_valid".to_string(),
                status: CheckStatus::Failed,
                message: format!("Failed to read README: {}", e),
                details: None,
                execution_time_ms: start_time.elapsed().as_millis() as u64,
            },
        }
    }

    /// Validate JSON schema
    async fn validate_json_schema(&mut self, schema_path: &Path) -> CheckResult {
        let start_time = Instant::now();

        if !schema_path.exists() {
            return CheckResult {
                name: "schema_valid".to_string(),
                status: CheckStatus::Warning,
                message: "Schema file not found".to_string(),
                details: None,
                execution_time_ms: start_time.elapsed().as_millis() as u64,
            };
        }

        // Check cache
        if let Ok(metadata) = std::fs::metadata(schema_path)
            && let Ok(mtime) = metadata.modified()
            && let Some((cached_mtime, cached_result)) =
                self.schema_validation_cache.get(schema_path)
            && *cached_mtime == mtime
        {
            let mut result = cached_result.clone();
            // Update execution time to reflect cache hit (near zero)
            result.execution_time_ms = start_time.elapsed().as_millis() as u64;
            result.message = format!("{} (cached)", result.message);
            return result;
        }

        let result = match read_file_with_context_sync(schema_path, "skill JSON schema") {
            Ok(content) => {
                match serde_json::from_str::<Value>(&content) {
                    Ok(schema_json) => {
                        // Validate that it's a proper JSON Schema by attempting to compile it
                        match jsonschema::validator_for(&schema_json) {
                            Ok(_validator) => CheckResult {
                                name: "schema_valid".to_string(),
                                status: CheckStatus::Passed,
                                message: "JSON schema is valid and compilable".to_string(),
                                details: None,
                                execution_time_ms: start_time.elapsed().as_millis() as u64,
                            },
                            Err(e) => CheckResult {
                                name: "schema_valid".to_string(),
                                status: CheckStatus::Failed,
                                message: format!("Invalid JSON Schema: {}", e),
                                details: Some(
                                    serde_json::json!({"error": format!("Schema compilation failed: {}", e)}),
                                ),
                                execution_time_ms: start_time.elapsed().as_millis() as u64,
                            },
                        }
                    }
                    Err(e) => CheckResult {
                        name: "schema_valid".to_string(),
                        status: CheckStatus::Failed,
                        message: format!("Invalid JSON in schema file: {}", e),
                        details: None,
                        execution_time_ms: start_time.elapsed().as_millis() as u64,
                    },
                }
            }
            Err(e) => CheckResult {
                name: "schema_valid".to_string(),
                status: CheckStatus::Failed,
                message: format!("Failed to read schema file: {}", e),
                details: None,
                execution_time_ms: start_time.elapsed().as_millis() as u64,
            },
        };

        // Update cache
        if let Ok(metadata) = std::fs::metadata(schema_path)
            && let Ok(mtime) = metadata.modified()
        {
            self.schema_validation_cache
                .insert(schema_path.to_path_buf(), (mtime, result.clone()));
        }

        result
    }

    /// Test basic tool execution
    async fn test_tool_execution(&self, config: &CliToolConfig) -> CheckResult {
        let start_time = Instant::now();

        // Try to execute with --help or -h
        let output = std::process::Command::new(&config.executable_path)
            .arg("--help")
            .output();

        match output {
            Ok(output) => {
                if output.status.success() {
                    CheckResult {
                        name: "tool_executable".to_string(),
                        status: CheckStatus::Passed,
                        message: "Tool executed successfully with --help".to_string(),
                        details: None,
                        execution_time_ms: start_time.elapsed().as_millis() as u64,
                    }
                } else {
                    // Try -h
                    let output = std::process::Command::new(&config.executable_path)
                        .arg("-h")
                        .output();

                    match output {
                        Ok(output) => {
                            if output.status.success() {
                                CheckResult {
                                    name: "tool_executable".to_string(),
                                    status: CheckStatus::Passed,
                                    message: "Tool executed successfully with -h".to_string(),
                                    details: None,
                                    execution_time_ms: start_time.elapsed().as_millis() as u64,
                                }
                            } else {
                                CheckResult {
                                    name: "tool_executable".to_string(),
                                    status: CheckStatus::Warning,
                                    message: "Tool executed but returned non-zero exit code"
                                        .to_string(),
                                    details: None,
                                    execution_time_ms: start_time.elapsed().as_millis() as u64,
                                }
                            }
                        }
                        Err(e) => CheckResult {
                            name: "tool_executable".to_string(),
                            status: CheckStatus::Failed,
                            message: format!("Failed to execute tool: {}", e),
                            details: None,
                            execution_time_ms: start_time.elapsed().as_millis() as u64,
                        },
                    }
                }
            }
            Err(e) => CheckResult {
                name: "tool_executable".to_string(),
                status: CheckStatus::Failed,
                message: format!("Failed to execute tool: {}", e),
                details: None,
                execution_time_ms: start_time.elapsed().as_millis() as u64,
            },
        }
    }

    /// Assess security based on checks
    fn assess_security(&self, checks: &HashMap<String, CheckResult>) -> SecurityAssessment {
        let mut warnings = vec![];
        let blocked_content = vec![];
        let mut security_level = SecurityLevel::Safe;

        // Check for script security issues
        if let Some(scripts_check) = checks.get("scripts_valid")
            && scripts_check.status == CheckStatus::Warning
            && let Some(details) = &scripts_check.details
            && let Some(issues) = details.as_array()
        {
            for issue in issues {
                if let Some(issue_str) = issue.as_str()
                    && issue_str.contains("dangerous")
                {
                    warnings.push(SecurityWarning {
                        warning_type: "dangerous_content".to_string(),
                        message: issue_str.to_string(),
                        severity: SecurityLevel::HighRisk,
                        suggestion: Some("Review script content for security issues".to_string()),
                    });
                    security_level = SecurityLevel::HighRisk;
                }
            }
        }

        let safe_to_execute = security_level != SecurityLevel::HighRisk;

        SecurityAssessment {
            security_level,
            warnings,
            blocked_content,
            safe_to_execute,
        }
    }

    /// Generate recommendations based on validation results
    fn generate_recommendations(
        &self,
        checks: &HashMap<String, CheckResult>,
        security: &SecurityAssessment,
    ) -> Vec<String> {
        let mut recommendations = vec![];

        // General recommendations based on check results
        for check in checks.values() {
            match check.status {
                CheckStatus::Warning => {
                    recommendations.push(format!(
                        "Address warning in {}: {}",
                        check.name, check.message
                    ));
                }
                CheckStatus::Failed => {
                    recommendations.push(format!(
                        "Fix failed check {}: {}",
                        check.name, check.message
                    ));
                }
                _ => {}
            }
        }

        // Security recommendations
        if security.security_level == SecurityLevel::HighRisk {
            recommendations
                .push("Review and fix security issues before using this skill".to_string());
        }

        // Performance recommendations
        if let Some(loading_check) = checks.get("skill_file_valid")
            && loading_check.execution_time_ms > 1000
        {
            recommendations.push("Consider optimizing skill file parsing performance".to_string());
        }

        recommendations
    }

    /// Determine overall validation status
    fn determine_overall_status(
        &self,
        checks: &HashMap<String, CheckResult>,
        security: &SecurityAssessment,
    ) -> ValidationStatus {
        let has_failures = checks
            .values()
            .any(|check| check.status == CheckStatus::Failed);
        let has_warnings = checks
            .values()
            .any(|check| check.status == CheckStatus::Warning);
        let has_high_risk = security.security_level == SecurityLevel::HighRisk;

        if has_failures || has_high_risk {
            ValidationStatus::Invalid
        } else if has_warnings {
            ValidationStatus::Warning
        } else {
            ValidationStatus::Valid
        }
    }

    /// Validate multiple skills in batch
    pub async fn validate_batch(
        &mut self,
        skill_paths: Vec<&Path>,
    ) -> Vec<Result<ValidationReport>> {
        let mut results = vec![];

        for path in skill_paths {
            let result = self.validate_skill_directory(path).await;
            results.push(result);
        }

        results
    }
}

/// Batch validation result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchValidationResult {
    /// Total skills validated
    pub total_skills: usize,

    /// Valid skills
    pub valid_skills: Vec<String>,

    /// Skills with warnings
    pub warning_skills: Vec<String>,

    /// Invalid skills
    pub invalid_skills: Vec<String>,

    /// Average validation time
    pub average_validation_time_ms: u64,

    /// Validation reports
    pub reports: Vec<ValidationReport>,
}

/// Validate a batch of skills and summarize results
pub async fn validate_skill_batch(skill_paths: Vec<&Path>) -> Result<BatchValidationResult> {
    let mut validator = SkillValidator::new();
    let mut reports = vec![];
    let mut total_time = 0u64;

    for path in skill_paths {
        match validator.validate_skill_directory(path).await {
            Ok(report) => {
                total_time += report.performance.total_time_ms;
                reports.push(report);
            }
            Err(e) => {
                // Create error report
                let error_report = ValidationReport {
                    status: ValidationStatus::Invalid,
                    skill_name: path.to_string_lossy().to_string(),
                    timestamp: chrono::Utc::now(),
                    checks: HashMap::new(),
                    performance: PerformanceMetrics::default(),
                    security: SecurityAssessment::default(),
                    recommendations: vec![format!("Validation failed: {}", e)],
                };
                reports.push(error_report);
            }
        }
    }

    let valid_skills: Vec<String> = reports
        .iter()
        .filter(|r| r.status == ValidationStatus::Valid)
        .map(|r| r.skill_name.clone())
        .collect();

    let warning_skills: Vec<String> = reports
        .iter()
        .filter(|r| r.status == ValidationStatus::Warning)
        .map(|r| r.skill_name.clone())
        .collect();

    let invalid_skills: Vec<String> = reports
        .iter()
        .filter(|r| r.status == ValidationStatus::Invalid)
        .map(|r| r.skill_name.clone())
        .collect();

    let average_time = if !reports.is_empty() {
        total_time / reports.len() as u64
    } else {
        0
    };

    Ok(BatchValidationResult {
        total_skills: reports.len(),
        valid_skills,
        warning_skills,
        invalid_skills,
        average_validation_time_ms: average_time,
        reports,
    })
}

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

    #[test]
    fn test_validation_config_default() {
        let config = ValidationConfig::default();
        assert!(config.enable_security_checks);
        assert!(config.enable_performance_checks);
        assert_eq!(config.max_validation_time, 30);
    }

    #[tokio::test]
    async fn test_validator_creation() {
        let _validator = SkillValidator::new();
        // assert_eq!(validator.schema_cache.len(), 0); // Commented out since schema_cache is disabled
    }

    #[tokio::test]
    async fn test_invalid_skill_directory() {
        let mut validator = SkillValidator::new();
        let temp_dir = TempDir::new().unwrap();
        let non_existent = temp_dir.path().join("non_existent");

        let result = validator.validate_skill_directory(&non_existent).await;
        assert!(result.is_ok());

        let report = result.unwrap();
        assert_eq!(report.status, ValidationStatus::Invalid);
    }

    #[tokio::test]
    async fn test_skill_validation_rejects_hooks() {
        let temp_dir = TempDir::new().unwrap();
        let skill_dir = temp_dir.path().join("hook-skill");
        std::fs::create_dir_all(&skill_dir).unwrap();

        let skill_md = r#"---
name: hook-skill
description: Skill with hooks
hooks:
  pre_tool_use:
    - command: "echo pre"
---
# Hook Skill
"#;
        std::fs::write(skill_dir.join("SKILL.md"), skill_md).unwrap();

        let mut validator = SkillValidator::new();
        let report = validator
            .validate_skill_directory(&skill_dir)
            .await
            .unwrap();

        assert_eq!(report.status, ValidationStatus::Invalid);
        let check = report.checks.get("skill_file_valid").unwrap();
        assert_eq!(check.status, CheckStatus::Failed);
        assert!(check.message.contains("hooks"));
    }

    #[tokio::test]
    async fn test_schema_validation_caching() {
        use std::fs::File;
        use std::io::Write;

        let temp_dir = TempDir::new().unwrap();
        let schema_path = temp_dir.path().join("schema.json");

        // precise sleep to ensure file system time resolution
        let sleep_fs = || std::thread::sleep(std::time::Duration::from_millis(50));

        // Create initial schema
        {
            let mut file = File::create(&schema_path).unwrap();
            write!(file, r#"{{"type": "string"}}"#).unwrap();
        }
        sleep_fs();

        let mut validator = SkillValidator::new();

        // 1. First validation - should cache
        let result1 = validator.validate_json_schema(&schema_path).await;
        assert_eq!(result1.status, CheckStatus::Passed);
        assert_eq!(validator.schema_validation_cache.len(), 1);

        // Capture mtime in cache
        let (cached_mtime, _) = validator.schema_validation_cache.get(&schema_path).unwrap();
        let cached_mtime = *cached_mtime;

        // 2. Second validation - should hit cache (mtime same)
        let result2 = validator.validate_json_schema(&schema_path).await;
        assert_eq!(result2.status, CheckStatus::Passed);
        // Verify we still have the same cache entry
        assert_eq!(
            validator
                .schema_validation_cache
                .get(&schema_path)
                .unwrap()
                .0,
            cached_mtime
        );

        // 3. Modify file - should invalidate cache
        sleep_fs();
        {
            let mut file = File::create(&schema_path).unwrap();
            write!(file, r#"{{"type": "integer"}}"#).unwrap();
        }
        sleep_fs();

        let result3 = validator.validate_json_schema(&schema_path).await;
        assert_eq!(result3.status, CheckStatus::Passed);

        let (new_mtime, _) = validator.schema_validation_cache.get(&schema_path).unwrap();
        assert_ne!(
            *new_mtime, cached_mtime,
            "Cache should have updated with new mtime"
        );
    }
}