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
//! AI Manager - Orchestrates template generation
//!
//! The AIManager is the main entry point for AI-powered template generation.
//! It coordinates between configuration, providers, prompt engineering, parsing,
//! and validation to produce high-quality security scanning templates.
use crate::types::TemplateLanguage;
use anyhow::{Context, Result};
use std::path::PathBuf;
use tracing::{debug, info};
use super::config::AIConfig;
use super::parser::ResponseParser;
use super::prompt::PromptBuilder;
use super::providers::{
AnthropicProvider, DeepSeekProvider, GenerationOptions, LLMProvider, OllamaProvider,
OpenAIProvider, ProviderHealthStatus,
};
use super::validator::TemplateValidator;
/// Main AI manager for template generation
#[derive(Debug)]
pub struct AIManager {
/// AI configuration
config: AIConfig,
/// Template output directory
output_dir: PathBuf,
/// Prompt builder for generating context-aware prompts
prompt_builder: PromptBuilder,
/// Response parser for cleaning LLM output
parser: ResponseParser,
/// Template validator for syntax checking
validator: TemplateValidator,
}
impl AIManager {
/// Create a new AI manager with default configuration
pub fn new() -> Result<Self> {
let config = AIConfig::load()?;
let output_dir = Self::default_output_dir()?;
let prompt_builder = PromptBuilder::new();
let parser = ResponseParser::new();
let validator = TemplateValidator::new();
// Ensure output directory exists
std::fs::create_dir_all(&output_dir).with_context(|| {
format!(
"Failed to create output directory: {}",
output_dir.display()
)
})?;
info!(
"Initialized AI manager with default provider: {}",
config.default_provider_name()
);
Ok(Self {
config,
output_dir,
prompt_builder,
parser,
validator,
})
}
/// Create a new AI manager with custom configuration
pub fn with_config(config: AIConfig) -> Result<Self> {
let output_dir = Self::default_output_dir()?;
let prompt_builder = PromptBuilder::new();
let parser = ResponseParser::new();
let validator = TemplateValidator::new();
std::fs::create_dir_all(&output_dir).with_context(|| {
format!(
"Failed to create output directory: {}",
output_dir.display()
)
})?;
Ok(Self {
config,
output_dir,
prompt_builder,
parser,
validator,
})
}
/// Get the default output directory for AI-generated templates
fn default_output_dir() -> Result<PathBuf> {
let home = dirs::home_dir().context("Failed to determine home directory")?;
Ok(home
.join(".cert-x-gen")
.join("templates")
.join("ai-generated"))
}
/// Set custom output directory
pub fn set_output_dir<P: Into<PathBuf>>(&mut self, dir: P) {
self.output_dir = dir.into();
}
/// Get the current output directory
pub fn output_dir(&self) -> &PathBuf {
&self.output_dir
}
/// Generate a template from a natural language prompt
///
/// # Arguments
///
/// * `prompt` - Natural language description of what to detect
/// * `language` - Target template language
/// * `provider_name` - Optional provider name (uses default if None)
///
/// # Returns
///
/// Generated template code as a string
///
/// # Example
///
/// ```no_run
/// use cert_x_gen::ai::AIManager;
/// use cert_x_gen::types::TemplateLanguage;
///
/// # async fn example() -> anyhow::Result<()> {
/// let manager = AIManager::new()?;
/// let template = manager.generate_template(
/// "detect Redis without authentication",
/// TemplateLanguage::Python,
/// None,
/// ).await?;
/// # Ok(())
/// # }
/// ```
pub async fn generate_template(
&self,
prompt: &str,
language: TemplateLanguage,
provider_name: Option<&str>,
) -> Result<String> {
// Determine which provider to use
let provider = provider_name.unwrap_or_else(|| self.config.default_provider_name());
info!(
"Generating {} template for: '{}' using provider: {}",
language, prompt, provider
);
// Check if provider is configured and enabled
if !self.config.is_provider_enabled(provider) {
anyhow::bail!(
"Provider '{}' is not enabled. Check your AI configuration at {}",
provider,
AIConfig::config_path()?.display()
);
}
// Create the provider instance
let llm_provider: Box<dyn LLMProvider> = match provider {
"ollama" => {
let provider_config = self
.config
.get_provider("ollama")
.context("Ollama provider configuration not found")?;
let endpoint = provider_config
.endpoint
.clone()
.unwrap_or_else(|| "http://localhost:11434".to_string());
let model = provider_config.model.clone();
Box::new(OllamaProvider::new(endpoint, model))
}
"openai" => {
let provider_config = self
.config
.get_provider("openai")
.context("OpenAI provider configuration not found")?;
let api_key = provider_config.api_key
.clone()
.context("OpenAI API key not configured. Set OPENAI_API_KEY environment variable or add to config.")?;
let model = provider_config.model.clone();
Box::new(OpenAIProvider::new(api_key, model))
}
"anthropic" => {
let provider_config = self
.config
.get_provider("anthropic")
.context("Anthropic provider configuration not found")?;
let api_key = provider_config.api_key
.clone()
.context("Anthropic API key not configured. Set ANTHROPIC_API_KEY environment variable or add to config.")?;
let model = provider_config.model.clone();
Box::new(AnthropicProvider::new(api_key, model))
}
"deepseek" => {
let provider_config = self
.config
.get_provider("deepseek")
.context("DeepSeek provider configuration not found")?;
let api_key = provider_config
.api_key
.clone()
.context("DeepSeek API key not configured")?;
let model = provider_config.model.clone();
Box::new(DeepSeekProvider::new(api_key, model))
}
_ => {
anyhow::bail!(
"Provider '{}' is not yet implemented. Currently supported: ollama, openai, anthropic, deepseek. \
Other providers (Google, Groq) will be added in future updates.",
provider
);
}
};
// Check if the provider is actually available
if !llm_provider.is_available() {
anyhow::bail!(
"Provider '{}' is not available. For Ollama, ensure it's running with: ollama serve",
provider
);
}
// Build a context-aware prompt using the PromptBuilder (Task 1.4)
info!("Building context-aware prompt for {} template...", language);
let llm_prompt = self
.prompt_builder
.build_generation_prompt(prompt, language);
debug!("Generated prompt length: {} chars", llm_prompt.len());
// Configure generation options from provider config
let provider_config = self.config.get_provider(provider).unwrap();
let options = GenerationOptions {
max_tokens: provider_config.max_tokens,
temperature: provider_config.temperature,
timeout: provider_config
.timeout_secs
.map(std::time::Duration::from_secs),
};
// Generate the template
info!("Calling LLM provider for generation...");
let generated_code = llm_provider.generate(&llm_prompt, options).await?; // Show actual error
info!(
"Template generated successfully ({} chars)",
generated_code.len()
);
// Task 1.5: Parse the response to extract clean template code
info!("Parsing response to extract clean template code...");
let parsed_code = self
.parser
.parse(&generated_code, language)
.context("Failed to parse LLM response")?;
debug!("Parsed template length: {} chars", parsed_code.len());
// Task 1.6: Validate the template
info!("Validating template syntax and structure...");
self.validator
.validate(&parsed_code, language)
.context("Template validation failed")?;
info!("Template validation passed successfully!");
Ok(parsed_code)
}
/// List available providers
pub fn list_providers(&self) -> Vec<(String, bool)> {
self.config
.providers
.iter()
.map(|(name, config)| (name.clone(), config.enabled))
.collect()
}
/// Check if a specific provider is available
///
/// This checks both configuration and actual availability (e.g., is Ollama running?)
pub async fn is_provider_available(&self, provider_name: &str) -> Result<bool> {
if !self.config.is_provider_enabled(provider_name) {
return Ok(false);
}
// Create the provider and check availability
let provider: Box<dyn LLMProvider> = match provider_name {
"ollama" => {
let provider_config = self
.config
.get_provider("ollama")
.context("Ollama provider configuration not found")?;
let endpoint = provider_config
.endpoint
.clone()
.unwrap_or_else(|| "http://localhost:11434".to_string());
let model = provider_config.model.clone();
Box::new(OllamaProvider::new(endpoint, model))
}
"openai" => {
let provider_config = self
.config
.get_provider("openai")
.context("OpenAI provider configuration not found")?;
let api_key = provider_config.api_key.clone().unwrap_or_default();
let model = provider_config.model.clone();
Box::new(OpenAIProvider::new(api_key, model))
}
"anthropic" => {
let provider_config = self
.config
.get_provider("anthropic")
.context("Anthropic provider configuration not found")?;
let api_key = provider_config.api_key.clone().unwrap_or_default();
let model = provider_config.model.clone();
Box::new(AnthropicProvider::new(api_key, model))
}
"deepseek" => {
let provider_config = self
.config
.get_provider("deepseek")
.context("DeepSeek provider configuration not found")?;
let api_key = provider_config.api_key.clone().unwrap_or_default();
let model = provider_config.model.clone();
Box::new(DeepSeekProvider::new(api_key, model))
}
_ => {
// Provider not yet implemented
return Ok(false);
}
};
Ok(provider.is_available())
}
/// Get current configuration
pub fn config(&self) -> &AIConfig {
&self.config
}
/// Get the prompt builder
pub fn prompt_builder(&self) -> &PromptBuilder {
&self.prompt_builder
}
/// Save a generated template to a file
///
/// # Arguments
///
/// * `template_code` - The template code to save
/// * `filename` - Filename (without path)
/// * `language` - Template language (for validation)
///
/// # Returns
///
/// Path to the saved file
pub fn save_template(
&self,
template_code: &str,
filename: &str,
language: TemplateLanguage,
) -> Result<PathBuf> {
let file_path = self.output_dir.join(filename);
debug!("Saving {} template to: {}", language, file_path.display());
std::fs::write(&file_path, template_code)
.with_context(|| format!("Failed to save template to {}", file_path.display()))?;
info!("Successfully saved template: {}", file_path.display());
Ok(file_path)
}
/// Generate a filename for a template based on the prompt
///
/// This is a public wrapper around the private filename generation logic.
///
/// # Arguments
///
/// * `prompt` - The prompt used to generate the template
/// * `language` - Template language
///
/// # Returns
///
/// A safe filename with appropriate extension
pub fn generate_filename(&self, prompt: &str, language: TemplateLanguage) -> String {
self.create_filename_from_prompt(prompt, language)
}
/// Generate and save a template in one operation
///
/// This is a convenience method that combines generation and saving.
pub async fn generate_and_save(
&self,
prompt: &str,
language: TemplateLanguage,
provider_name: Option<&str>,
custom_filename: Option<&str>,
) -> Result<PathBuf> {
// Generate the template
let template_code = self
.generate_template(prompt, language, provider_name)
.await?;
// Create filename from prompt if not provided
let filename = match custom_filename {
Some(name) => name.to_string(),
None => self.create_filename_from_prompt(prompt, language),
};
// Save and return path
self.save_template(&template_code, &filename, language)
}
/// Create a safe filename from a prompt
fn create_filename_from_prompt(&self, prompt: &str, language: TemplateLanguage) -> String {
// Convert prompt to kebab-case
let safe_name = prompt
.to_lowercase()
.chars()
.map(|c| if c.is_alphanumeric() { c } else { '-' })
.collect::<String>();
// Remove consecutive dashes
let safe_name = safe_name
.split('-')
.filter(|s| !s.is_empty())
.collect::<Vec<_>>()
.join("-");
// Truncate if too long
let safe_name = if safe_name.len() > 50 {
&safe_name[..50]
} else {
&safe_name
};
// Add timestamp for uniqueness
let timestamp = chrono::Utc::now().format("%Y%m%d%H%M%S");
// Add appropriate extension
let extension = match language {
TemplateLanguage::Python => "py",
TemplateLanguage::JavaScript => "js",
TemplateLanguage::Rust => "rs",
TemplateLanguage::Shell => "sh",
TemplateLanguage::Yaml => "yaml",
TemplateLanguage::C => "c",
TemplateLanguage::Cpp => "cpp",
TemplateLanguage::Java => "java",
TemplateLanguage::Go => "go",
TemplateLanguage::Ruby => "rb",
TemplateLanguage::Perl => "pl",
TemplateLanguage::Php => "php",
};
format!("{}-{}.{}", safe_name, timestamp, extension)
}
}
impl Default for AIManager {
fn default() -> Self {
Self::new().expect("Failed to create default AI manager")
}
}
impl AIManager {
/// Test a specific provider's health
///
/// Performs comprehensive health checks on the specified provider including:
/// - Connection testing
/// - Authentication verification
/// - Response time measurement
/// - Model availability check
///
/// # Arguments
///
/// * `provider_name` - Name of the provider to test ("ollama", "openai", "anthropic", "deepseek")
///
/// # Returns
///
/// A `ProviderHealthStatus` struct with detailed diagnostics
///
/// # Example
///
/// ```no_run
/// use cert_x_gen::ai::AIManager;
///
/// # async fn example() -> anyhow::Result<()> {
/// let manager = AIManager::new()?;
/// let status = manager.test_provider("ollama").await?;
///
/// if status.healthy {
/// println!("✓ Provider is healthy");
/// } else {
/// println!("✗ Provider has issues");
/// for msg in status.messages {
/// println!(" - {}", msg);
/// }
/// }
/// # Ok(())
/// # }
/// ```
pub async fn test_provider(&self, provider_name: &str) -> Result<ProviderHealthStatus> {
use crate::ai::providers::*;
match provider_name.to_lowercase().as_str() {
"ollama" => {
let provider_config = self
.config
.get_provider("ollama")
.ok_or_else(|| anyhow::anyhow!("Ollama provider not configured"))?;
let endpoint = provider_config
.endpoint
.clone()
.unwrap_or_else(|| "http://localhost:11434".to_string());
let model = provider_config.model.clone();
let provider = OllamaProvider::new(endpoint, model);
provider.health_check().await
}
"openai" => {
let provider_config = self
.config
.get_provider("openai")
.ok_or_else(|| anyhow::anyhow!("OpenAI provider not configured"))?;
let api_key = provider_config
.api_key
.clone()
.unwrap_or_else(|| "${OPENAI_API_KEY}".to_string());
let model = provider_config.model.clone();
let provider = OpenAIProvider::new(api_key, model);
provider.health_check().await
}
"anthropic" => {
let provider_config = self
.config
.get_provider("anthropic")
.ok_or_else(|| anyhow::anyhow!("Anthropic provider not configured"))?;
let api_key = provider_config
.api_key
.clone()
.unwrap_or_else(|| "${ANTHROPIC_API_KEY}".to_string());
let model = provider_config.model.clone();
let provider = AnthropicProvider::new(api_key, model);
provider.health_check().await
}
"deepseek" => {
let provider_config = self
.config
.get_provider("deepseek")
.ok_or_else(|| anyhow::anyhow!("DeepSeek provider not configured"))?;
let api_key = provider_config
.api_key
.clone()
.unwrap_or_else(|| "${DEEPSEEK_API_KEY}".to_string());
let model = provider_config.model.clone();
let provider = DeepSeekProvider::new(api_key, model);
provider.health_check().await
}
_ => {
anyhow::bail!("Unknown provider: {}", provider_name)
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_create_manager() {
let manager = AIManager::new();
assert!(manager.is_ok());
let manager = manager.unwrap();
assert!(manager.output_dir().exists() || !manager.output_dir().exists());
// Just check it's a valid path
}
#[test]
fn test_filename_generation() {
let manager = AIManager::new().unwrap();
let filename = manager.create_filename_from_prompt(
"detect Redis without authentication",
TemplateLanguage::Python,
);
assert!(filename.contains("detect"));
assert!(filename.contains("redis"));
assert!(filename.ends_with(".py"));
assert!(filename.len() < 100); // Reasonable length
}
#[test]
fn test_list_providers() {
// Use an explicit in-memory default config rather than AIManager::new(),
// which calls AIConfig::load() and reads (or creates) the on-disk config at
// config_path(). On a runner with a pre-existing/empty config file that read
// yields an empty providers map, so the assertions below would fail for
// environmental reasons unrelated to this code. with_config() keeps the test
// deterministic and free of filesystem side effects.
let manager = AIManager::with_config(AIConfig::default()).unwrap();
let providers = manager.list_providers();
assert!(!providers.is_empty());
assert!(providers.iter().any(|(name, _)| name == "ollama"));
}
#[test]
fn test_prompt_builder_integration() {
// with_config avoids the AIConfig::load() disk read/write that new() performs;
// this test only exercises the prompt builder, which is config-independent.
let manager = AIManager::with_config(AIConfig::default()).unwrap();
// Verify prompt builder is accessible
let builder = manager.prompt_builder();
// Test that it can build prompts for all languages
let languages = vec![
TemplateLanguage::Python,
TemplateLanguage::JavaScript,
TemplateLanguage::Yaml,
TemplateLanguage::Rust,
];
for language in languages {
let prompt =
builder.build_generation_prompt("detect Redis without authentication", language);
// Verify prompt contains key elements
assert!(!prompt.is_empty());
assert!(prompt.contains("Redis"));
assert!(prompt.contains("authentication") || prompt.contains("unauth"));
assert!(prompt.len() > 500); // Substantial prompt
}
}
#[test]
fn test_prompt_builder_skeletons() {
// with_config avoids the AIConfig::load() disk read/write that new() performs;
// this test only exercises the prompt builder, which is config-independent.
let manager = AIManager::with_config(AIConfig::default()).unwrap();
let builder = manager.prompt_builder();
// Verify all supported languages have skeletons except YAML
assert!(builder.has_skeleton(TemplateLanguage::Python));
assert!(builder.has_skeleton(TemplateLanguage::JavaScript));
assert!(builder.has_skeleton(TemplateLanguage::Rust));
assert!(builder.has_skeleton(TemplateLanguage::C));
assert!(builder.has_skeleton(TemplateLanguage::Cpp));
assert!(builder.has_skeleton(TemplateLanguage::Java));
assert!(builder.has_skeleton(TemplateLanguage::Go));
assert!(builder.has_skeleton(TemplateLanguage::Ruby));
assert!(builder.has_skeleton(TemplateLanguage::Perl));
assert!(builder.has_skeleton(TemplateLanguage::Php));
assert!(builder.has_skeleton(TemplateLanguage::Shell));
// YAML doesn't have a skeleton (it's declarative)
assert!(!builder.has_skeleton(TemplateLanguage::Yaml));
}
#[tokio::test]
async fn test_generate_template_ollama_check() {
let manager = AIManager::new().unwrap();
// Check if Ollama is available
let is_available = manager.is_provider_available("ollama").await.unwrap();
if !is_available {
// If Ollama is not running, generation should fail with helpful error
// Explicitly request ollama provider to ensure we test the right code path
let result = manager
.generate_template("test prompt", TemplateLanguage::Python, Some("ollama"))
.await;
assert!(result.is_err());
let err_msg = result.unwrap_err().to_string().to_lowercase();
// Check for various error patterns that indicate Ollama is not available
let has_expected_error = err_msg.contains("not available")
|| err_msg.contains("not enabled")
|| err_msg.contains("ollama serve")
|| err_msg.contains("not running")
|| err_msg.contains("connection refused")
|| err_msg.contains("failed to connect");
assert!(
has_expected_error,
"Expected error about Ollama not being available, got: {}",
err_msg
);
} else {
// If Ollama is available, we can't test actual generation here
// (would be too slow for unit tests)
println!("Ollama is available - integration tests can run");
}
}
#[tokio::test]
#[ignore] // Only run with --ignored when Ollama is available
async fn test_real_generation_with_ollama() {
let manager = AIManager::new().unwrap();
// Check if Ollama is available
if !manager.is_provider_available("ollama").await.unwrap() {
eprintln!("Skipping: Ollama not available");
return;
}
// Try generating a simple template
let result = manager
.generate_template(
"write a one-line Python comment",
TemplateLanguage::Python,
Some("ollama"),
)
.await;
assert!(result.is_ok());
let template = result.unwrap();
assert!(!template.is_empty());
println!("Generated template:\n{}", template);
}
}