ggen-config 26.7.3

Configuration parser and validator for ggen.toml 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
//! Configuration validation
//!
//! This module provides validation logic for ggen configuration.

use crate::config_lib::{ConfigError, GgenConfig, Result};
use star_toml::Validate;
use std::collections::HashSet;

/// Configuration validator
pub struct ConfigValidator<'a> {
    config: &'a GgenConfig,
    errors: Vec<String>,
}

impl<'a> ConfigValidator<'a> {
    /// Create a new validator for a configuration
    #[must_use]
    pub const fn new(config: &'a GgenConfig) -> Self {
        Self {
            config,
            errors: Vec::new(),
        }
    }

    /// Validate the configuration
    ///
    /// # Errors
    ///
    /// Returns an error if validation fails with details of all issues found
    ///
    /// # Example
    ///
    /// ```
    /// use ggen_config::config_lib::{ConfigLoader, ConfigValidator};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let toml = r#"
    ///     [project]
    ///     name = "my-project"
    ///     version = "1.0.0"
    /// "#;
    ///
    /// let config = ConfigLoader::from_str(toml)?;
    /// let result = ConfigValidator::validate(&config);
    /// assert!(result.is_ok());
    /// # Ok(())
    /// # }
    /// ```
    pub fn validate(config: &'a GgenConfig) -> Result<()> {
        config.check().map_err(|errs| {
            ConfigError::Validation(crate::config_lib::error::format_star_toml_errors(&errs))
        })
    }

    /// Run all validation checks
    fn validate_all(&mut self) -> Result<()> {
        if let Err(errs) = self.config.check() {
            for err in errs.errors() {
                let formatted = crate::config_lib::error::format_single_star_toml_error(err);
                self.errors.push(formatted);
            }
        }

        if self.errors.is_empty() {
            Ok(())
        } else {
            Err(ConfigError::Validation(self.errors.join("; ")))
        }
    }

    /// Validate project configuration
    fn validate_project(&mut self) {
        let project = &self.config.project;

        // Name validation
        if project.name.is_empty() {
            self.errors.push("Project name cannot be empty".to_string());
        }

        // Version validation (basic semver check)
        if !is_valid_version(&project.version) {
            self.errors.push(format!(
                "Invalid version format: '{}'. Expected semver format (e.g., 1.0.0)",
                project.version
            ));
        }
    }

    /// Validate AI configuration
    fn validate_ai(&mut self) {
        if let Some(ai) = &self.config.ai {
            // Provider validation
            let valid_providers = ["openai", "ollama", "anthropic", "cohere", "huggingface"];
            if !valid_providers.contains(&ai.provider.as_str()) {
                self.errors.push(format!(
                    "Unknown AI provider: '{}'. Valid providers: {:?}",
                    ai.provider, valid_providers
                ));
            }

            // Temperature validation (0.0 - 1.0)
            if !(0.0..=1.0).contains(&ai.temperature) {
                self.errors.push(format!(
                    "AI temperature must be between 0.0 and 1.0, got {}",
                    ai.temperature
                ));
            }

            // Max tokens validation
            if ai.max_tokens == 0 {
                self.errors
                    .push("AI max_tokens must be greater than 0".to_string());
            }

            // Timeout validation
            if ai.timeout == 0 {
                self.errors
                    .push("AI timeout must be greater than 0".to_string());
            }

            // Validation settings
            if let Some(validation) = &ai.validation {
                if !(0.0..=1.0).contains(&validation.quality_threshold) {
                    self.errors.push(format!(
                        "AI validation quality_threshold must be between 0.0 and 1.0, got {}",
                        validation.quality_threshold
                    ));
                }
            }
        }
    }

    /// Validate templates configuration
    fn validate_templates(&mut self) {
        if let Some(templates) = &self.config.templates {
            // Check that directories are not empty strings
            if let Some(dir) = &templates.directory {
                if dir.is_empty() {
                    self.errors
                        .push("Templates directory cannot be empty".to_string());
                }
            }
        }
    }

    /// Validate security configuration
    const fn validate_security() {
        // Security settings are all boolean flags, no complex validation needed
        // Could add checks for conflicting settings if needed
    }

    /// Validate performance configuration
    fn validate_performance(&mut self) {
        if let Some(perf) = &self.config.performance {
            // Validate max_workers
            if perf.parallel_execution && perf.max_workers == 0 {
                self.errors.push(
                    "Performance max_workers must be greater than 0 when parallel_execution is enabled"
                        .to_string(),
                );
            }

            // Validate cache_size format
            if let Some(cache_size) = &perf.cache_size {
                if !is_valid_size_format(cache_size) {
                    self.errors.push(format!(
                        "Invalid cache_size format: '{cache_size}'. Expected format like '1GB', '512MB'"
                    ));
                }
            }
        }
    }

    /// Validate logging configuration
    fn validate_logging(&mut self) {
        if let Some(logging) = &self.config.logging {
            // Validate log level
            let valid_levels = ["trace", "debug", "info", "warn", "error"];
            if !valid_levels.contains(&logging.level.to_lowercase().as_str()) {
                self.errors.push(format!(
                    "Invalid log level: '{}'. Valid levels: {:?}",
                    logging.level, valid_levels
                ));
            }

            // Validate log format
            let valid_formats = ["json", "text", "pretty"];
            if !valid_formats.contains(&logging.format.to_lowercase().as_str()) {
                self.errors.push(format!(
                    "Invalid log format: '{}'. Valid formats: {:?}",
                    logging.format, valid_formats
                ));
            }
        }
    }

    /// Validate MCP configuration
    fn validate_mcp(&mut self) {
        if let Some(mcp) = &self.config.mcp {
            // Validate transport type if specified
            if let Some(transport) = &mcp.transport {
                let valid_transports = ["stdio", "http", "websocket"];
                if !valid_transports.contains(&transport.transport_type.as_str()) {
                    self.errors.push(format!(
                        "Invalid MCP transport type: '{}'. Valid types: {:?}",
                        transport.transport_type, valid_transports
                    ));
                }

                // Validate port if specified (port is u16, so just check for 0)
                if let Some(port) = transport.port {
                    if port == 0 {
                        self.errors.push(format!(
                            "Invalid MCP port: {port}. Must be between 1 and 65535"
                        ));
                    }
                }
            }

            // Validate tool timeout
            if mcp.tool_timeout_ms == 0 {
                self.errors
                    .push("MCP tool_timeout_ms must be greater than 0".to_string());
            }

            // Validate max concurrent requests
            if mcp.max_concurrent_requests == 0 {
                self.errors
                    .push("MCP max_concurrent_requests must be greater than 0".to_string());
            }
        }
    }

    /// Validate A2A configuration
    fn validate_a2a(&mut self) {
        if let Some(a2a) = &self.config.a2a {
            // Validate transport type if specified
            if let Some(transport) = &a2a.transport {
                let valid_transports = ["memory", "http", "websocket", "amqp"];
                if !valid_transports.contains(&transport.transport_type.as_str()) {
                    self.errors.push(format!(
                        "Invalid A2A transport type: '{}'. Valid types: {:?}",
                        transport.transport_type, valid_transports
                    ));
                }

                // Validate port if specified (port is u16, so just check for 0)
                if let Some(port) = transport.port {
                    if port == 0 {
                        self.errors.push(format!(
                            "Invalid A2A port: {port}. Must be between 1 and 65535"
                        ));
                    }
                }
            }

            // Validate orchestration mode if specified
            if let Some(orchestration) = &a2a.orchestration {
                let valid_modes = ["centralized", "decentralized", "hierarchical"];
                if !valid_modes.contains(&orchestration.mode.as_str()) {
                    self.errors.push(format!(
                        "Invalid A2A orchestration mode: '{}'. Valid modes: {:?}",
                        orchestration.mode, valid_modes
                    ));
                }

                // Validate consensus algorithm if consensus enabled
                if orchestration.consensus_enabled {
                    if let Some(algorithm) = &orchestration.consensus_algorithm {
                        let valid_algorithms = ["raft", "pbft", "naive"];
                        if !valid_algorithms.contains(&algorithm.as_str()) {
                            self.errors.push(format!(
                                "Invalid A2A consensus algorithm: '{algorithm}'. Valid: {valid_algorithms:?}"
                            ));
                        }
                    }
                }
            }
        }
    }
}

/// Validate version string (basic semver check)
fn is_valid_version(version: &str) -> bool {
    let parts: Vec<&str> = version.split('.').collect();
    if parts.len() != 3 {
        return false;
    }

    parts.iter().all(|part| part.parse::<u32>().is_ok())
}

/// Validate size format (e.g., "1GB", "512MB")
fn is_valid_size_format(size: &str) -> bool {
    let size = size.to_uppercase();
    let valid_suffixes = ["B", "KB", "MB", "GB", "TB"];

    valid_suffixes.iter().any(|suffix| {
        size.strip_suffix(suffix)
            .is_some_and(|num_str| num_str.parse::<u32>().is_ok())
    })
}

/// Validate that there are no duplicate keys in a collection
#[allow(dead_code)]
fn has_duplicates<T: Eq + std::hash::Hash>(items: &[T]) -> bool {
    let mut seen = HashSet::new();
    items.iter().any(|item| !seen.insert(item))
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::config_lib::{ConfigLoader, ProjectConfig};

    #[test]
    fn test_valid_minimal_config() {
        let config = GgenConfig {
            project: ProjectConfig {
                name: "test".to_string(),
                version: "1.0.0".to_string(),
                description: None,
                authors: None,
                license: None,
                repository: None,
            },
            ..Default::default()
        };

        assert!(ConfigValidator::validate(&config).is_ok());
    }

    #[test]
    fn test_invalid_empty_name() {
        let config = GgenConfig {
            project: ProjectConfig {
                name: String::new(),
                version: "1.0.0".to_string(),
                description: None,
                authors: None,
                license: None,
                repository: None,
            },
            ..Default::default()
        };

        assert!(ConfigValidator::validate(&config).is_err());
    }

    #[test]
    fn test_invalid_version() {
        let config = GgenConfig {
            project: ProjectConfig {
                name: "test".to_string(),
                version: "invalid".to_string(),
                description: None,
                authors: None,
                license: None,
                repository: None,
            },
            ..Default::default()
        };

        assert!(ConfigValidator::validate(&config).is_err());
    }

    #[test]
    fn test_version_validation() {
        assert!(is_valid_version("1.0.0"));
        assert!(is_valid_version("0.1.0"));
        assert!(is_valid_version("10.20.30"));

        assert!(!is_valid_version("1.0"));
        assert!(!is_valid_version("invalid"));
        assert!(!is_valid_version("1.0.0.0"));
    }

    #[test]
    fn test_size_format_validation() {
        assert!(is_valid_size_format("1GB"));
        assert!(is_valid_size_format("512MB"));
        assert!(is_valid_size_format("100kb"));

        assert!(!is_valid_size_format("invalid"));
        assert!(!is_valid_size_format("GB"));
        assert!(!is_valid_size_format("100"));
    }

    #[test]
    fn test_validate_ai_temperature() {
        let toml = r#"
            [project]
            name = "test"
            version = "1.0.0"

            [ai]
            provider = "openai"
            model = "gpt-4"
            temperature = 1.5
        "#;

        let config = ConfigLoader::from_str(toml).unwrap();
        assert!(ConfigValidator::validate(&config).is_err());
    }

    #[test]
    fn test_validate_log_level() {
        let toml = r#"
            [project]
            name = "test"
            version = "1.0.0"

            [logging]
            level = "invalid"
            format = "json"
        "#;

        let config = ConfigLoader::from_str(toml).unwrap();
        assert!(ConfigValidator::validate(&config).is_err());
    }

    #[test]
    fn test_validate_mcp_transport_type() {
        let toml = r#"
            [project]
            name = "test"
            version = "1.0.0"

            [mcp]
            enabled = true

            [mcp.transport]
            transport_type = "invalid"
        "#;

        let config = ConfigLoader::from_str(toml).unwrap();
        assert!(ConfigValidator::validate(&config).is_err());
    }

    #[test]
    fn test_validate_a2a_orchestration_mode() {
        let toml = r#"
            [project]
            name = "test"
            version = "1.0.0"

            [a2a]
            enabled = true

            [a2a.orchestration]
            mode = "invalid"
        "#;

        let config = ConfigLoader::from_str(toml).unwrap();
        assert!(ConfigValidator::validate(&config).is_err());
    }

    #[test]
    fn test_valid_mcp_config() {
        let toml = r#"
            [project]
            name = "test"
            version = "1.0.0"

            [mcp]
            enabled = true
            name = "test-mcp"
            version = "0.1.0"

            [mcp.transport]
            transport_type = "stdio"

            [mcp.zai]
            enabled = true
            provider_url = "http://localhost:8080"
        "#;

        let config = ConfigLoader::from_str(toml).unwrap();
        assert!(ConfigValidator::validate(&config).is_ok());
    }

    #[test]
    fn test_valid_a2a_config() {
        let toml = r#"
            [project]
            name = "test"
            version = "1.0.0"

            [a2a]
            enabled = true
            agent_id = "agent-001"
            agent_name = "TestAgent"
            agent_type = "coordinator"

            [a2a.transport]
            transport_type = "memory"

            [a2a.orchestration]
            mode = "decentralized"
            consensus_enabled = true
            consensus_algorithm = "raft"
        "#;

        let config = ConfigLoader::from_str(toml).unwrap();
        assert!(ConfigValidator::validate(&config).is_ok());
    }

    #[test]
    fn test_env_zai_override() {
        let toml = r#"
            [project]
            name = "test"
            version = "1.0.0"

            [ai]
            provider = "anthropic"
            model = "claude-3-opus-20240229"

            [env.zai]
            "ai.provider" = "zai"
            "ai.model" = "zai-chat"
            "mcp.enabled" = true
        "#;

        let config = ConfigLoader::from_str(toml).unwrap();
        assert_eq!(config.ai.as_ref().unwrap().provider, "anthropic");
        assert_eq!(config.ai.as_ref().unwrap().model, "claude-3-opus-20240229");

        // Apply ZAI environment override using direct parsing and manual override
        let mut config_with_zai = ConfigLoader::from_str(toml).unwrap();
        if let Some(ai_config) = config_with_zai.ai.as_mut() {
            ai_config.provider = "zai".to_string();
            ai_config.model = "zai-chat".to_string();
        }
        if config_with_zai.mcp.is_none() {
            config_with_zai.mcp = Some(crate::config_lib::schema::McpConfig {
                name: None,
                version: None,
                tool_timeout_ms: 30000,
                max_concurrent_requests: 100,
                transport: None,
                tools: None,
                zai: None,
                enabled: true,
                discovery: None,
            });
        } else if let Some(mcp) = config_with_zai.mcp.as_mut() {
            mcp.enabled = true;
        }

        assert_eq!(config_with_zai.ai.as_ref().unwrap().provider, "zai");
        assert_eq!(config_with_zai.ai.as_ref().unwrap().model, "zai-chat");
    }
}