organizational-intelligence-plugin 0.3.4

Organizational Intelligence Plugin - Defect pattern analysis for GitHub organizations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
//! Configuration Management
//!
//! PROD-004: Centralized configuration with file and environment support
//! Supports YAML files with environment variable overrides

use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::path::Path;

/// Main configuration structure
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
    /// Analysis settings
    pub analysis: AnalysisConfig,

    /// ML model settings
    pub ml: MlConfig,

    /// Storage settings
    pub storage: StorageConfig,

    /// GPU/compute settings
    pub compute: ComputeConfig,

    /// Logging settings
    pub logging: LoggingConfig,
}

/// Analysis configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AnalysisConfig {
    /// Maximum commits to analyze per repository
    pub max_commits: usize,

    /// Number of parallel workers
    pub workers: usize,

    /// Cache directory for cloned repos
    pub cache_dir: String,

    /// Include merge commits
    pub include_merges: bool,
}

impl Default for AnalysisConfig {
    fn default() -> Self {
        Self {
            max_commits: 1000,
            workers: num_cpus::get().max(1),
            cache_dir: ".oip-cache".to_string(),
            include_merges: false,
        }
    }
}

/// ML model configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct MlConfig {
    /// Number of trees for Random Forest
    pub n_trees: usize,

    /// Maximum tree depth
    pub max_depth: usize,

    /// Number of clusters for K-means
    pub k_clusters: usize,

    /// K-means max iterations
    pub max_iterations: usize,

    /// SMOTE k-neighbors
    pub smote_k: usize,

    /// Target minority ratio for SMOTE
    pub smote_ratio: f32,
}

impl Default for MlConfig {
    fn default() -> Self {
        Self {
            n_trees: 100,
            max_depth: 10,
            k_clusters: 5,
            max_iterations: 100,
            smote_k: 5,
            smote_ratio: 0.5,
        }
    }
}

/// Storage configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct StorageConfig {
    /// Default output file
    pub default_output: String,

    /// Enable compression
    pub compress: bool,

    /// Batch size for bulk operations
    pub batch_size: usize,
}

impl Default for StorageConfig {
    fn default() -> Self {
        Self {
            default_output: "oip-gpu.db".to_string(),
            compress: true,
            batch_size: 1000,
        }
    }
}

/// Compute/GPU configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ComputeConfig {
    /// Preferred backend: "auto", "gpu", "simd", "cpu"
    pub backend: String,

    /// GPU workgroup size
    pub workgroup_size: usize,

    /// Enable GPU if available
    pub gpu_enabled: bool,
}

impl Default for ComputeConfig {
    fn default() -> Self {
        Self {
            backend: "auto".to_string(),
            workgroup_size: 256,
            gpu_enabled: true,
        }
    }
}

/// Logging configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct LoggingConfig {
    /// Log level: "trace", "debug", "info", "warn", "error"
    pub level: String,

    /// Enable JSON output
    pub json: bool,

    /// Log file path (optional)
    pub file: Option<String>,
}

impl Default for LoggingConfig {
    fn default() -> Self {
        Self {
            level: "info".to_string(),
            json: false,
            file: None,
        }
    }
}

impl Config {
    /// Load configuration from file
    pub fn from_file(path: &Path) -> Result<Self> {
        let content = std::fs::read_to_string(path)?;
        let config: Config = serde_yaml::from_str(&content)?;
        Ok(config)
    }

    /// Load configuration with environment overrides
    pub fn load(path: Option<&Path>) -> Result<Self> {
        let mut config = if let Some(p) = path {
            if p.exists() {
                Self::from_file(p)?
            } else {
                Self::default()
            }
        } else {
            // Try default locations
            let default_paths = [".oip.yaml", ".oip.yml", "oip.yaml", "oip.yml"];
            let mut found = None;
            for p in &default_paths {
                let path = Path::new(p);
                if path.exists() {
                    found = Some(Self::from_file(path)?);
                    break;
                }
            }
            found.unwrap_or_default()
        };

        // Apply environment overrides
        config.apply_env_overrides();

        Ok(config)
    }

    /// Apply environment variable overrides
    fn apply_env_overrides(&mut self) {
        // Analysis
        if let Ok(val) = std::env::var("OIP_MAX_COMMITS") {
            if let Ok(n) = val.parse() {
                self.analysis.max_commits = n;
            }
        }
        if let Ok(val) = std::env::var("OIP_WORKERS") {
            if let Ok(n) = val.parse() {
                self.analysis.workers = n;
            }
        }
        if let Ok(val) = std::env::var("OIP_CACHE_DIR") {
            self.analysis.cache_dir = val;
        }

        // ML
        if let Ok(val) = std::env::var("OIP_K_CLUSTERS") {
            if let Ok(n) = val.parse() {
                self.ml.k_clusters = n;
            }
        }

        // Compute
        if let Ok(val) = std::env::var("OIP_BACKEND") {
            self.compute.backend = val;
        }
        if let Ok(val) = std::env::var("OIP_GPU_ENABLED") {
            self.compute.gpu_enabled = val == "1" || val.to_lowercase() == "true";
        }

        // Logging
        if let Ok(val) = std::env::var("OIP_LOG_LEVEL") {
            self.logging.level = val;
        }
        if let Ok(val) = std::env::var("OIP_LOG_JSON") {
            self.logging.json = val == "1" || val.to_lowercase() == "true";
        }
    }

    /// Save configuration to file
    pub fn save(&self, path: &Path) -> Result<()> {
        let content = serde_yaml::to_string(self)?;
        std::fs::write(path, content)?;
        Ok(())
    }

    /// Validate configuration
    pub fn validate(&self) -> Result<()> {
        if self.analysis.max_commits == 0 {
            anyhow::bail!("max_commits must be > 0");
        }
        if self.analysis.workers == 0 {
            anyhow::bail!("workers must be > 0");
        }
        if self.ml.k_clusters == 0 {
            anyhow::bail!("k_clusters must be > 0");
        }
        if self.ml.smote_ratio <= 0.0 || self.ml.smote_ratio > 1.0 {
            anyhow::bail!("smote_ratio must be in (0, 1]");
        }
        Ok(())
    }

    /// Generate example configuration
    pub fn example_yaml() -> String {
        let config = Config::default();
        serde_yaml::to_string(&config).unwrap_or_default()
    }
}

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

    #[test]
    fn test_default_config() {
        let config = Config::default();
        assert_eq!(config.analysis.max_commits, 1000);
        assert_eq!(config.ml.k_clusters, 5);
        assert_eq!(config.compute.backend, "auto");
    }

    #[test]
    fn test_config_validation() {
        let config = Config::default();
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_invalid_config() {
        let mut config = Config::default();
        config.analysis.max_commits = 0;
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_config_save_load() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("test-config.yaml");

        let config = Config::default();
        config.save(&config_path).unwrap();

        let loaded = Config::from_file(&config_path).unwrap();
        assert_eq!(loaded.analysis.max_commits, config.analysis.max_commits);
        assert_eq!(loaded.ml.k_clusters, config.ml.k_clusters);
    }

    #[test]
    fn test_example_yaml() {
        let yaml = Config::example_yaml();
        assert!(yaml.contains("analysis"));
        assert!(yaml.contains("ml"));
        assert!(yaml.contains("compute"));
    }

    #[test]
    #[serial_test::serial]
    fn test_load_missing_file() {
        // Clean up any env vars from other tests
        std::env::remove_var("OIP_MAX_COMMITS");
        std::env::remove_var("OIP_GPU_ENABLED");

        let config = Config::load(Some(Path::new("nonexistent.yaml"))).unwrap();
        // Should return defaults when file doesn't exist
        assert_eq!(config.analysis.max_commits, 1000);
    }

    #[test]
    #[serial_test::serial]
    fn test_load_no_path_no_defaults() {
        // Clean up any env vars from other tests
        std::env::remove_var("OIP_MAX_COMMITS");
        std::env::remove_var("OIP_GPU_ENABLED");

        // Load with no path and no default files present
        let config = Config::load(None).unwrap();
        assert_eq!(config.analysis.max_commits, 1000); // Should use defaults
    }

    #[test]
    #[serial_test::serial]
    fn test_env_overrides_max_commits() {
        // Clean up first to ensure clean state
        std::env::remove_var("OIP_MAX_COMMITS");

        std::env::set_var("OIP_MAX_COMMITS", "500");
        let mut config = Config::default();
        config.apply_env_overrides();
        assert_eq!(config.analysis.max_commits, 500);
        std::env::remove_var("OIP_MAX_COMMITS");
    }

    #[test]
    #[serial_test::serial]
    fn test_env_overrides_workers() {
        std::env::remove_var("OIP_WORKERS");
        std::env::set_var("OIP_WORKERS", "8");
        let mut config = Config::default();
        config.apply_env_overrides();
        assert_eq!(config.analysis.workers, 8);
        std::env::remove_var("OIP_WORKERS");
    }

    #[test]
    #[serial_test::serial]
    fn test_env_overrides_cache_dir() {
        std::env::remove_var("OIP_CACHE_DIR");
        std::env::set_var("OIP_CACHE_DIR", "/tmp/custom-cache");
        let mut config = Config::default();
        config.apply_env_overrides();
        assert_eq!(config.analysis.cache_dir, "/tmp/custom-cache");
        std::env::remove_var("OIP_CACHE_DIR");
    }

    #[test]
    #[serial_test::serial]
    fn test_env_overrides_k_clusters() {
        std::env::remove_var("OIP_K_CLUSTERS");
        std::env::set_var("OIP_K_CLUSTERS", "10");
        let mut config = Config::default();
        config.apply_env_overrides();
        assert_eq!(config.ml.k_clusters, 10);
        std::env::remove_var("OIP_K_CLUSTERS");
    }

    #[test]
    #[serial_test::serial]
    fn test_env_overrides_backend() {
        std::env::remove_var("OIP_BACKEND");
        std::env::set_var("OIP_BACKEND", "simd");
        let mut config = Config::default();
        config.apply_env_overrides();
        assert_eq!(config.compute.backend, "simd");
        std::env::remove_var("OIP_BACKEND");
    }

    #[test]
    #[serial_test::serial]
    fn test_env_overrides_gpu_enabled_true() {
        std::env::remove_var("OIP_GPU_ENABLED");
        std::env::set_var("OIP_GPU_ENABLED", "true");
        let mut config = Config::default();
        config.apply_env_overrides();
        assert!(config.compute.gpu_enabled);
        std::env::remove_var("OIP_GPU_ENABLED");
    }

    #[test]
    #[serial_test::serial]
    fn test_env_overrides_gpu_enabled_1() {
        std::env::remove_var("OIP_GPU_ENABLED");
        std::env::set_var("OIP_GPU_ENABLED", "1");
        let mut config = Config::default();
        config.apply_env_overrides();
        assert!(config.compute.gpu_enabled);
        std::env::remove_var("OIP_GPU_ENABLED");
    }

    #[test]
    #[serial_test::serial]
    fn test_env_overrides_gpu_enabled_false() {
        // Clean up first to avoid interference from parallel tests
        std::env::remove_var("OIP_GPU_ENABLED");

        std::env::set_var("OIP_GPU_ENABLED", "false");
        let mut config = Config::default();
        config.compute.gpu_enabled = true; // Start with true
        config.apply_env_overrides();
        assert!(!config.compute.gpu_enabled);
        std::env::remove_var("OIP_GPU_ENABLED");
    }

    #[test]
    #[serial_test::serial]
    fn test_env_overrides_log_level() {
        std::env::remove_var("OIP_LOG_LEVEL");
        std::env::set_var("OIP_LOG_LEVEL", "debug");
        let mut config = Config::default();
        config.apply_env_overrides();
        assert_eq!(config.logging.level, "debug");
        std::env::remove_var("OIP_LOG_LEVEL");
    }

    #[test]
    #[serial_test::serial]
    fn test_env_overrides_log_json() {
        std::env::remove_var("OIP_LOG_JSON");
        std::env::set_var("OIP_LOG_JSON", "1");
        let mut config = Config::default();
        config.apply_env_overrides();
        assert!(config.logging.json);
        std::env::remove_var("OIP_LOG_JSON");
    }

    #[test]
    fn test_validation_workers_zero() {
        let mut config = Config::default();
        config.analysis.workers = 0;
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_validation_k_clusters_zero() {
        let mut config = Config::default();
        config.ml.k_clusters = 0;
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_validation_smote_ratio_zero() {
        let mut config = Config::default();
        config.ml.smote_ratio = 0.0;
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_validation_smote_ratio_over_one() {
        let mut config = Config::default();
        config.ml.smote_ratio = 1.5;
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_validation_smote_ratio_exactly_one() {
        let mut config = Config::default();
        config.ml.smote_ratio = 1.0;
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_analysis_config_defaults() {
        let config = AnalysisConfig::default();
        assert_eq!(config.max_commits, 1000);
        assert!(config.workers > 0); // At least 1
        assert_eq!(config.cache_dir, ".oip-cache");
        assert!(!config.include_merges);
    }

    #[test]
    fn test_ml_config_defaults() {
        let config = MlConfig::default();
        assert_eq!(config.n_trees, 100);
        assert_eq!(config.max_depth, 10);
        assert_eq!(config.k_clusters, 5);
        assert_eq!(config.max_iterations, 100);
        assert_eq!(config.smote_k, 5);
        assert_eq!(config.smote_ratio, 0.5);
    }

    #[test]
    fn test_storage_config_defaults() {
        let config = StorageConfig::default();
        assert_eq!(config.default_output, "oip-gpu.db");
        assert!(config.compress);
        assert_eq!(config.batch_size, 1000);
    }

    #[test]
    fn test_compute_config_defaults() {
        let config = ComputeConfig::default();
        assert_eq!(config.backend, "auto");
        assert_eq!(config.workgroup_size, 256);
        assert!(config.gpu_enabled);
    }

    #[test]
    fn test_logging_config_defaults() {
        let config = LoggingConfig::default();
        assert_eq!(config.level, "info");
        assert!(!config.json);
        assert!(config.file.is_none());
    }

    #[test]
    fn test_config_serialization() {
        let config = Config::default();
        let yaml = serde_yaml::to_string(&config).unwrap();
        let deserialized: Config = serde_yaml::from_str(&yaml).unwrap();
        assert_eq!(
            config.analysis.max_commits,
            deserialized.analysis.max_commits
        );
        assert_eq!(config.ml.k_clusters, deserialized.ml.k_clusters);
    }

    #[test]
    #[serial_test::serial]
    fn test_invalid_env_value_ignored() {
        // Clean up any env vars from other tests
        std::env::remove_var("OIP_GPU_ENABLED");

        std::env::set_var("OIP_MAX_COMMITS", "not-a-number");
        let config = Config::load(None).unwrap();
        assert_eq!(config.analysis.max_commits, 1000); // Should use default
        std::env::remove_var("OIP_MAX_COMMITS");
    }
}