Skip to main content

vtcode_core/skills/validation/
mod.rs

1//! Skill Validation System
2//!
3//! Validates skill definitions, configurations, and executions to ensure:
4//! - Proper SKILL.md format and metadata
5//! - Valid JSON schemas for tool arguments
6//! - Executable scripts and tools
7//! - Security and safety checks
8//! - Performance and resource usage validation
9
10use crate::skills::cli_bridge::CliToolConfig;
11use crate::skills::manifest::parse_skill_file;
12use crate::utils::file_utils::read_file_with_context_sync;
13use anyhow::Result;
14use hashbrown::HashMap;
15use serde::{Deserialize, Serialize};
16use serde_json::Value;
17use std::path::{Path, PathBuf};
18use std::time::{Instant, SystemTime};
19use tracing::info;
20
21mod checks;
22
23/// Validation configuration
24#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct ValidationConfig {
26    /// Enable security checks
27    pub enable_security_checks: bool,
28
29    /// Enable performance validation
30    pub enable_performance_checks: bool,
31
32    /// Maximum execution time for validation tests (seconds)
33    pub max_validation_time: u64,
34
35    /// Maximum script size (bytes)
36    pub max_script_size: usize,
37
38    /// Allowed script extensions
39    pub allowed_script_extensions: Vec<String>,
40
41    /// Blocked commands/patterns
42    pub blocked_commands: Vec<String>,
43
44    /// Required metadata fields
45    pub required_metadata_fields: Vec<String>,
46
47    /// Enable JSON schema validation
48    pub enable_schema_validation: bool,
49
50    /// Strict mode (fail on warnings)
51    pub strict_mode: bool,
52}
53
54impl Default for ValidationConfig {
55    fn default() -> Self {
56        Self {
57            enable_security_checks: true,
58            enable_performance_checks: true,
59            max_validation_time: 30,
60            max_script_size: 1024 * 1024, // 1MB
61            allowed_script_extensions: vec![
62                "py".to_string(),
63                "sh".to_string(),
64                "bash".to_string(),
65                "js".to_string(),
66                "ts".to_string(),
67                "rb".to_string(),
68                "pl".to_string(),
69                "go".to_string(),
70                "rs".to_string(),
71            ],
72            blocked_commands: vec![
73                "rm -rf /".to_string(),
74                "sudo".to_string(),
75                "chmod 777".to_string(),
76                "curl.*|.*sh".to_string(),
77                "wget.*|.*sh".to_string(),
78            ],
79            required_metadata_fields: vec!["name".to_string(), "description".to_string()],
80            enable_schema_validation: true,
81            strict_mode: false,
82        }
83    }
84}
85
86/// Validation result with detailed report
87#[derive(Debug, Clone, Serialize, Deserialize)]
88pub struct ValidationReport {
89    /// Overall validation status
90    pub status: ValidationStatus,
91
92    /// Skill name
93    pub skill_name: String,
94
95    /// Validation timestamp
96    pub timestamp: chrono::DateTime<chrono::Utc>,
97
98    /// Individual check results
99    pub checks: HashMap<String, CheckResult>,
100
101    /// Performance metrics
102    pub performance: PerformanceMetrics,
103
104    /// Security assessment
105    pub security: SecurityAssessment,
106
107    /// Recommendations for improvement
108    pub recommendations: Vec<String>,
109}
110
111/// Validation status
112#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
113pub enum ValidationStatus {
114    /// All checks passed
115    Valid,
116    /// Some warnings, but skill is usable
117    Warning,
118    /// Critical issues, skill should not be used
119    Invalid,
120}
121
122/// Individual check result
123#[derive(Debug, Clone, Serialize, Deserialize)]
124pub struct CheckResult {
125    /// Check name
126    pub name: String,
127
128    /// Check status
129    pub status: CheckStatus,
130
131    /// Detailed message
132    pub message: String,
133
134    /// Additional details
135    pub details: Option<Value>,
136
137    /// Execution time
138    pub execution_time_ms: u64,
139}
140
141/// Check status
142#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
143pub enum CheckStatus {
144    /// Check passed
145    Passed,
146    /// Check passed with warnings
147    Warning,
148    /// Check failed
149    Failed,
150    /// Check was skipped
151    Skipped,
152}
153
154/// Performance metrics
155#[derive(Debug, Clone, Default, Serialize, Deserialize)]
156pub struct PerformanceMetrics {
157    /// Total validation time
158    pub total_time_ms: u64,
159
160    /// Skill loading time
161    pub loading_time_ms: u64,
162
163    /// Schema validation time
164    pub schema_validation_time_ms: u64,
165
166    /// Script validation time
167    pub script_validation_time_ms: u64,
168
169    /// Memory usage estimate (bytes)
170    pub memory_usage_bytes: usize,
171
172    /// Token usage estimate
173    pub token_usage_estimate: usize,
174}
175
176/// Security assessment
177#[derive(Debug, Clone, Default, Serialize, Deserialize)]
178pub struct SecurityAssessment {
179    /// Overall security level
180    pub security_level: SecurityLevel,
181
182    /// Security warnings
183    pub warnings: Vec<SecurityWarning>,
184
185    /// Blocked content found
186    pub blocked_content: Vec<String>,
187
188    /// Safe to execute
189    pub safe_to_execute: bool,
190}
191
192/// Security level
193#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
194pub enum SecurityLevel {
195    /// No security concerns
196    #[default]
197    Safe,
198    /// Minor concerns, generally safe
199    LowRisk,
200    /// Moderate concerns, review recommended
201    MediumRisk,
202    /// High concerns, not recommended
203    HighRisk,
204}
205
206/// Security warning
207#[derive(Debug, Clone, Serialize, Deserialize)]
208pub struct SecurityWarning {
209    /// Warning type
210    pub warning_type: String,
211
212    /// Warning message
213    pub message: String,
214
215    /// Severity level
216    pub severity: SecurityLevel,
217
218    /// Suggested remediation
219    pub suggestion: Option<String>,
220}
221
222/// Skill validator
223pub struct SkillValidator {
224    config: ValidationConfig,
225    // Note: Validator from jsonschema crate doesn't implement Clone,
226    // so we cache the validation result keyed by path and mtime instead.
227    schema_validation_cache: HashMap<PathBuf, (SystemTime, CheckResult)>,
228}
229
230impl SkillValidator {
231    /// Create new validator with default configuration
232    pub fn new() -> Self {
233        Self::with_config(ValidationConfig::default())
234    }
235}
236
237impl Default for SkillValidator {
238    fn default() -> Self {
239        Self::new()
240    }
241}
242
243impl SkillValidator {
244    /// Create new validator with custom configuration
245    pub fn with_config(config: ValidationConfig) -> Self {
246        Self { config, schema_validation_cache: HashMap::new() }
247    }
248
249    /// Validate a traditional skill from directory
250    pub async fn validate_skill_directory(&mut self, skill_path: &Path) -> Result<ValidationReport> {
251        let start_time = Instant::now();
252        let mut checks = HashMap::new();
253        // Performance tracking initialized at end
254
255        info!("Validating skill directory: {}", skill_path.display());
256
257        // Check if directory exists
258        let check_result = self.check_directory_exists(skill_path).await;
259        checks.insert("directory_exists".to_string(), check_result);
260
261        // Validate SKILL.md file
262        let skill_file = skill_path.join("SKILL.md");
263        let check_result = self.validate_skill_file(&skill_file).await;
264        checks.insert("skill_file_valid".to_string(), check_result.clone());
265
266        let skill_name = if let Some(manifest) = &check_result.details {
267            manifest.get("name").and_then(|v| v.as_str()).unwrap_or("unknown").to_string()
268        } else {
269            "unknown".to_string()
270        };
271
272        // Validate scripts directory
273        let scripts_dir = skill_path.join("scripts");
274        if scripts_dir.exists() {
275            let check_result = self.validate_scripts_directory(&scripts_dir).await;
276            checks.insert("scripts_valid".to_string(), check_result);
277        }
278
279        // Validate resources
280        let resources_result = self.validate_resources(skill_path).await;
281        for (name, result) in resources_result {
282            checks.insert(format!("resource_{name}"), result);
283        }
284
285        // Security assessment
286        let security = self.assess_security(&checks);
287
288        // Generate recommendations
289        let recommendations = self.generate_recommendations(&checks, &security);
290
291        // Determine overall status
292        let status = self.determine_overall_status(&checks, &security);
293
294        let performance = PerformanceMetrics {
295            total_time_ms: start_time.elapsed().as_millis() as u64,
296            ..Default::default()
297        };
298
299        Ok(ValidationReport {
300            status,
301            skill_name,
302            timestamp: chrono::Utc::now(),
303            checks,
304            performance,
305            security,
306            recommendations,
307        })
308    }
309
310    /// Validate CLI tool configuration
311    pub async fn validate_cli_tool(&mut self, config: &CliToolConfig) -> Result<ValidationReport> {
312        let start_time = Instant::now();
313        let mut checks = HashMap::new();
314
315        info!("Validating CLI tool: {}", config.name);
316
317        // Check executable exists
318        let check_result = self.check_executable_exists(&config.executable_path).await;
319        checks.insert("executable_exists".to_string(), check_result);
320
321        // Check executable permissions
322        let check_result = self.check_executable_permissions(&config.executable_path).await;
323        checks.insert("executable_permissions".to_string(), check_result);
324
325        // Validate README if present
326        if let Some(readme_path) = &config.readme_path {
327            let check_result = self.validate_readme_file(readme_path).await;
328            checks.insert("readme_valid".to_string(), check_result);
329        }
330
331        // Validate JSON schema if present
332        if let Some(schema_path) = &config.schema_path {
333            let check_result = self.validate_json_schema(schema_path).await;
334            checks.insert("schema_valid".to_string(), check_result);
335        }
336
337        // Test tool execution (basic)
338        let check_result = self.test_tool_execution(config).await;
339        checks.insert("tool_executable".to_string(), check_result);
340
341        // Security assessment
342        let security = self.assess_security(&checks);
343
344        // Generate recommendations
345        let recommendations = self.generate_recommendations(&checks, &security);
346
347        // Determine overall status
348        let status = self.determine_overall_status(&checks, &security);
349
350        let performance = PerformanceMetrics {
351            total_time_ms: start_time.elapsed().as_millis() as u64,
352            ..Default::default()
353        };
354
355        Ok(ValidationReport {
356            status,
357            skill_name: config.name.clone(),
358            timestamp: chrono::Utc::now(),
359            checks,
360            performance,
361            security,
362            recommendations,
363        })
364    }
365
366    /// Validate JSON schema
367    async fn validate_json_schema(&mut self, schema_path: &Path) -> CheckResult {
368        let start_time = Instant::now();
369
370        if !schema_path.exists() {
371            return CheckResult {
372                name: "schema_valid".to_string(),
373                status: CheckStatus::Warning,
374                message: "Schema file not found".to_string(),
375                details: None,
376                execution_time_ms: start_time.elapsed().as_millis() as u64,
377            };
378        }
379
380        // Check cache
381        if let Ok(metadata) = tokio::fs::metadata(schema_path).await
382            && let Ok(mtime) = metadata.modified()
383            && let Some((cached_mtime, cached_result)) = self.schema_validation_cache.get(schema_path)
384            && *cached_mtime == mtime
385        {
386            let mut result = cached_result.clone();
387            // Update execution time to reflect cache hit (near zero)
388            result.execution_time_ms = start_time.elapsed().as_millis() as u64;
389            result.message = format!("{} (cached)", result.message);
390            return result;
391        }
392
393        let result = match read_file_with_context_sync(schema_path, "skill JSON schema") {
394            Ok(content) => {
395                match serde_json::from_str::<Value>(&content) {
396                    Ok(schema_json) => {
397                        // Validate that it's a proper JSON Schema by attempting to compile it
398                        match jsonschema::validator_for(&schema_json) {
399                            Ok(_validator) => CheckResult {
400                                name: "schema_valid".to_string(),
401                                status: CheckStatus::Passed,
402                                message: "JSON schema is valid and compilable".to_string(),
403                                details: None,
404                                execution_time_ms: start_time.elapsed().as_millis() as u64,
405                            },
406                            Err(e) => CheckResult {
407                                name: "schema_valid".to_string(),
408                                status: CheckStatus::Failed,
409                                message: format!("Invalid JSON Schema: {e}"),
410                                details: Some(
411                                    serde_json::json!({"error": format!("Schema compilation failed: {}", e)}),
412                                ),
413                                execution_time_ms: start_time.elapsed().as_millis() as u64,
414                            },
415                        }
416                    }
417                    Err(e) => CheckResult {
418                        name: "schema_valid".to_string(),
419                        status: CheckStatus::Failed,
420                        message: format!("Invalid JSON in schema file: {e}"),
421                        details: None,
422                        execution_time_ms: start_time.elapsed().as_millis() as u64,
423                    },
424                }
425            }
426            Err(e) => CheckResult {
427                name: "schema_valid".to_string(),
428                status: CheckStatus::Failed,
429                message: format!("Failed to read schema file: {e}"),
430                details: None,
431                execution_time_ms: start_time.elapsed().as_millis() as u64,
432            },
433        };
434
435        // Update cache
436        if let Ok(metadata) = tokio::fs::metadata(schema_path).await
437            && let Ok(mtime) = metadata.modified()
438        {
439            self.schema_validation_cache
440                .insert(schema_path.to_path_buf(), (mtime, result.clone()));
441        }
442
443        result
444    }
445
446    /// Test basic tool execution
447    async fn test_tool_execution(&self, config: &CliToolConfig) -> CheckResult {
448        let start_time = Instant::now();
449
450        // Execute tool off the async executor — `Command::output()` blocks
451        // until the subprocess exits. See the `# Blocking` docs in
452        // `src/agent/runloop/git.rs` for the pattern.
453        let exec_path = config.executable_path.clone();
454
455        // Try --help first
456        let output =
457            tokio::task::spawn_blocking(move || std::process::Command::new(&exec_path).arg("--help").output()).await;
458
459        match output {
460            Ok(Ok(output)) if output.status.success() => CheckResult {
461                name: "tool_executable".to_string(),
462                status: CheckStatus::Passed,
463                message: "Tool executed successfully with --help".to_string(),
464                details: None,
465                execution_time_ms: start_time.elapsed().as_millis() as u64,
466            },
467            Ok(Ok(_)) => {
468                // --help failed, try -h
469                let exec_path = config.executable_path.clone();
470                match tokio::task::spawn_blocking(move || std::process::Command::new(&exec_path).arg("-h").output())
471                    .await
472                {
473                    Ok(Ok(output)) if output.status.success() => CheckResult {
474                        name: "tool_executable".to_string(),
475                        status: CheckStatus::Passed,
476                        message: "Tool executed successfully with -h".to_string(),
477                        details: None,
478                        execution_time_ms: start_time.elapsed().as_millis() as u64,
479                    },
480                    Ok(Ok(_)) => CheckResult {
481                        name: "tool_executable".to_string(),
482                        status: CheckStatus::Warning,
483                        message: "Tool executed but returned non-zero exit code".to_string(),
484                        details: None,
485                        execution_time_ms: start_time.elapsed().as_millis() as u64,
486                    },
487                    Ok(Err(e)) => CheckResult {
488                        name: "tool_executable".to_string(),
489                        status: CheckStatus::Failed,
490                        message: format!("Failed to execute tool: {e}"),
491                        details: None,
492                        execution_time_ms: start_time.elapsed().as_millis() as u64,
493                    },
494                    Err(e) => CheckResult {
495                        name: "tool_executable".to_string(),
496                        status: CheckStatus::Failed,
497                        message: format!("Validation task failed: {e}"),
498                        details: None,
499                        execution_time_ms: start_time.elapsed().as_millis() as u64,
500                    },
501                }
502            }
503            Ok(Err(e)) => CheckResult {
504                name: "tool_executable".to_string(),
505                status: CheckStatus::Failed,
506                message: format!("Failed to execute tool: {e}"),
507                details: None,
508                execution_time_ms: start_time.elapsed().as_millis() as u64,
509            },
510            Err(e) => CheckResult {
511                name: "tool_executable".to_string(),
512                status: CheckStatus::Failed,
513                message: format!("Validation task failed: {e}"),
514                details: None,
515                execution_time_ms: start_time.elapsed().as_millis() as u64,
516            },
517        }
518    }
519
520    /// Assess security based on checks
521    fn assess_security(&self, checks: &HashMap<String, CheckResult>) -> SecurityAssessment {
522        let mut warnings = vec![];
523        let blocked_content = vec![];
524        let mut security_level = SecurityLevel::Safe;
525
526        // Check for script security issues
527        if let Some(scripts_check) = checks.get("scripts_valid")
528            && scripts_check.status == CheckStatus::Warning
529            && let Some(details) = &scripts_check.details
530            && let Some(issues) = details.as_array()
531        {
532            for issue in issues {
533                if let Some(issue_str) = issue.as_str()
534                    && issue_str.contains("dangerous")
535                {
536                    warnings.push(SecurityWarning {
537                        warning_type: "dangerous_content".to_string(),
538                        message: issue_str.to_string(),
539                        severity: SecurityLevel::HighRisk,
540                        suggestion: Some("Review script content for security issues".to_string()),
541                    });
542                    security_level = SecurityLevel::HighRisk;
543                }
544            }
545        }
546
547        let safe_to_execute = security_level != SecurityLevel::HighRisk;
548
549        SecurityAssessment {
550            security_level,
551            warnings,
552            blocked_content,
553            safe_to_execute,
554        }
555    }
556
557    /// Generate recommendations based on validation results
558    fn generate_recommendations(
559        &self,
560        checks: &HashMap<String, CheckResult>,
561        security: &SecurityAssessment,
562    ) -> Vec<String> {
563        let mut recommendations = vec![];
564
565        // General recommendations based on check results
566        for check in checks.values() {
567            match check.status {
568                CheckStatus::Warning => {
569                    recommendations.push(format!("Address warning in {}: {}", check.name, check.message));
570                }
571                CheckStatus::Failed => {
572                    recommendations.push(format!("Fix failed check {}: {}", check.name, check.message));
573                }
574                _ => {}
575            }
576        }
577
578        // Security recommendations
579        if security.security_level == SecurityLevel::HighRisk {
580            recommendations.push("Review and fix security issues before using this skill".to_string());
581        }
582
583        // Performance recommendations
584        if let Some(loading_check) = checks.get("skill_file_valid")
585            && loading_check.execution_time_ms > 1000
586        {
587            recommendations.push("Consider optimizing skill file parsing performance".to_string());
588        }
589
590        recommendations
591    }
592
593    /// Determine overall validation status
594    fn determine_overall_status(
595        &self,
596        checks: &HashMap<String, CheckResult>,
597        security: &SecurityAssessment,
598    ) -> ValidationStatus {
599        let has_failures = checks.values().any(|check| check.status == CheckStatus::Failed);
600        let has_warnings = checks.values().any(|check| check.status == CheckStatus::Warning);
601        let has_high_risk = security.security_level == SecurityLevel::HighRisk;
602
603        if has_failures || has_high_risk {
604            ValidationStatus::Invalid
605        } else if has_warnings {
606            ValidationStatus::Warning
607        } else {
608            ValidationStatus::Valid
609        }
610    }
611
612    /// Validate multiple skills in batch
613    pub async fn validate_batch(&mut self, skill_paths: Vec<&Path>) -> Vec<Result<ValidationReport>> {
614        let mut results = vec![];
615
616        for path in skill_paths {
617            let result = self.validate_skill_directory(path).await;
618            results.push(result);
619        }
620
621        results
622    }
623}
624
625/// Batch validation result
626#[derive(Debug, Clone, Serialize, Deserialize)]
627pub struct BatchValidationResult {
628    /// Total skills validated
629    pub total_skills: usize,
630
631    /// Valid skills
632    pub valid_skills: Vec<String>,
633
634    /// Skills with warnings
635    pub warning_skills: Vec<String>,
636
637    /// Invalid skills
638    pub invalid_skills: Vec<String>,
639
640    /// Average validation time
641    pub average_validation_time_ms: u64,
642
643    /// Validation reports
644    pub reports: Vec<ValidationReport>,
645}
646
647/// Validate a batch of skills and summarize results
648pub async fn validate_skill_batch(skill_paths: Vec<&Path>) -> Result<BatchValidationResult> {
649    let mut validator = SkillValidator::new();
650    let mut reports = vec![];
651    let mut total_time = 0u64;
652
653    for path in skill_paths {
654        match validator.validate_skill_directory(path).await {
655            Ok(report) => {
656                total_time += report.performance.total_time_ms;
657                reports.push(report);
658            }
659            Err(e) => {
660                // Create error report
661                let error_report = ValidationReport {
662                    status: ValidationStatus::Invalid,
663                    skill_name: path.to_string_lossy().to_string(),
664                    timestamp: chrono::Utc::now(),
665                    checks: HashMap::new(),
666                    performance: PerformanceMetrics::default(),
667                    security: SecurityAssessment::default(),
668                    recommendations: vec![format!("Validation failed: {}", e)],
669                };
670                reports.push(error_report);
671            }
672        }
673    }
674
675    let valid_skills: Vec<String> = reports
676        .iter()
677        .filter(|r| r.status == ValidationStatus::Valid)
678        .map(|r| r.skill_name.clone())
679        .collect();
680
681    let warning_skills: Vec<String> = reports
682        .iter()
683        .filter(|r| r.status == ValidationStatus::Warning)
684        .map(|r| r.skill_name.clone())
685        .collect();
686
687    let invalid_skills: Vec<String> = reports
688        .iter()
689        .filter(|r| r.status == ValidationStatus::Invalid)
690        .map(|r| r.skill_name.clone())
691        .collect();
692
693    let average_time = if !reports.is_empty() {
694        total_time / reports.len() as u64
695    } else {
696        0
697    };
698
699    Ok(BatchValidationResult {
700        total_skills: reports.len(),
701        valid_skills,
702        warning_skills,
703        invalid_skills,
704        average_validation_time_ms: average_time,
705        reports,
706    })
707}
708
709#[cfg(test)]
710mod tests;