soma-core 2.0.0

World's first production-ready self-aware development system with meta-cognitive capabilities and cognitive reasoning engine for intelligent development platforms
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
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
// LLMOperator: Universal symbolic operator for all LLM providers
// Implements SomaOperator for GPT, Claude, Gemini, DeepSeek, Mistral, Grok, etc.
// All comments in English (US) per coding_guidelines.md

use crate::memory::SymbolicContext;
use crate::ops::{OperatorMetadata, SomaOperator, UncertaintyModel};
use anyhow::{anyhow, Result};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::env;

/// Universal LLM operator for symbolic cognitive DAGs
pub struct LLMOperator {
    pub id: String,
    pub model: String,
    pub provider: String, // "gpt", "claude", "gemini", etc.
    pub api_key: String,
}

impl SomaOperator for LLMOperator {
    fn execute(&self, inputs: &SymbolicContext) -> Result<SymbolicContext> {
        let prompt = inputs.resolve_or_default("prompt", "");

        // 🔒 SECURITY: Never log the prompt or API key in production
        if env::var("DEBUG_MODE").unwrap_or_default() == "true"
            && env::var("ENVIRONMENT").unwrap_or_default() == "dev"
        {
            println!(
                "🔍 [DEBUG] Processing prompt for provider: {}",
                self.provider
            );
        }

        // Check if we should use mock responses (for testing)
        let use_mock = env::var("USE_MOCK_RESPONSES").unwrap_or_default() == "true";

        let output = if use_mock {
            format!(
                "[MOCK_{}:{}] Mock response generated",
                self.provider.to_uppercase(),
                self.model
            )
        } else {
            // 🔒 SECURITY: Validate API key before making requests
            if !is_api_key_valid(&self.api_key, &self.provider) {
                return Err(anyhow!(
                    "Invalid or missing API key for provider: {}",
                    self.provider
                ));
            }

            match self.provider.as_str() {
                "gpt" => call_openai(&self.model, &self.api_key, &prompt)?,
                "claude" => call_anthropic(&self.model, &self.api_key, &prompt)?,
                "gemini" => call_google(&self.model, &self.api_key, &prompt)?,
                "deepseek" => call_deepseek(&self.model, &self.api_key, &prompt)?,
                "mistral" => call_mistral(&self.model, &self.api_key, &prompt)?,
                "grok" => call_grok(&self.model, &self.api_key, &prompt)?,
                _ => return Err(anyhow!("Unknown LLM provider: {}", self.provider)),
            }
        };

        let mut ctx = SymbolicContext::new();
        ctx.set("response", &output);
        Ok(ctx)
    }

    fn metadata(&self) -> OperatorMetadata {
        OperatorMetadata {
            name: self.id.clone(),
            description: format!("LLM operator for {}", self.provider),
            category: "llm".to_string(),
        }
    }

    fn cognitive_cost(&self) -> f64 {
        3.0 // Estimate for LLM call
    }

    fn uncertainty_propagation(&self) -> UncertaintyModel {
        UncertaintyModel {
            entropy: 0.15,
            source: self.provider.clone(),
        }
    }
}

/// 🔒 SECURITY: Validate API key format without exposing the key
fn is_api_key_valid(api_key: &str, provider: &str) -> bool {
    if api_key.is_empty() {
        return false;
    }

    // Check for placeholder values (never use these in production)
    let placeholder_patterns = [
        "your_",
        "placeholder",
        "example",
        "test_key",
        "fake_key",
        "demo_key",
    ];

    for pattern in &placeholder_patterns {
        if api_key.to_lowercase().contains(pattern) {
            return false;
        }
    }

    // Validate API key format by provider (without exposing the key)
    match provider {
        "gpt" => api_key.starts_with("sk-") && api_key.len() > 20,
        "claude" => api_key.starts_with("sk-ant-") && api_key.len() > 30,
        "gemini" => api_key.starts_with("AIza") && api_key.len() > 30,
        "deepseek" => api_key.len() > 20, // Generic validation
        "mistral" => api_key.len() > 20,  // Generic validation
        "grok" => api_key.len() > 20,     // Generic validation
        _ => false,
    }
}

/// 🔒 SECURITY: Sanitize API key for logging (show only first/last chars)
#[allow(dead_code)]
fn sanitize_api_key_for_logging(api_key: &str) -> String {
    if api_key.len() < 8 {
        return "***".to_string();
    }
    format!("{}***{}", &api_key[..4], &api_key[api_key.len() - 4..])
}

// --- Provider HTTP implementations ---

async fn call_openai_async(model: &str, api_key: &str, prompt: &str) -> Result<String> {
    let client = reqwest::Client::new();
    let max_tokens: u32 = env::var("MAX_TOKENS")
        .unwrap_or_default()
        .parse()
        .unwrap_or(2000);
    let temperature: f32 = env::var("TEMPERATURE")
        .unwrap_or_default()
        .parse()
        .unwrap_or(0.7);
    let timeout_secs: u64 = env::var("API_TIMEOUT")
        .unwrap_or_default()
        .parse()
        .unwrap_or(30);

    let request_body = json!({
        "model": model,
        "messages": [
            {
                "role": "user",
                "content": prompt
            }
        ],
        "max_tokens": max_tokens,
        "temperature": temperature
    });

    let response = client
        .post("https://api.openai.com/v1/chat/completions")
        .header("Authorization", format!("Bearer {}", api_key))
        .header("Content-Type", "application/json")
        .timeout(std::time::Duration::from_secs(timeout_secs))
        .json(&request_body)
        .send()
        .await
        .map_err(|e| anyhow!("OpenAI API request failed: {}", e))?;

    if !response.status().is_success() {
        let status = response.status();
        let error_text = response.text().await.unwrap_or_default();

        // 🔒 SECURITY: Log error without exposing API key
        if env::var("LOG_API_REQUESTS").unwrap_or_default() == "true" {
            println!("❌ OpenAI API Error [{}]: {}", status, error_text);
        }

        return Err(anyhow!(
            "OpenAI API error [{}]: Authentication or quota issue",
            status
        ));
    }

    let response_json: Value = response
        .json()
        .await
        .map_err(|e| anyhow!("Failed to parse OpenAI response: {}", e))?;

    let content = response_json["choices"][0]["message"]["content"]
        .as_str()
        .unwrap_or("No response")
        .to_string();

    Ok(content)
}

fn call_openai(model: &str, api_key: &str, prompt: &str) -> Result<String> {
    tokio::runtime::Runtime::new()?.block_on(call_openai_async(model, api_key, prompt))
}

async fn call_anthropic_async(model: &str, api_key: &str, prompt: &str) -> Result<String> {
    let client = reqwest::Client::new();
    let max_tokens: u32 = env::var("MAX_TOKENS")
        .unwrap_or_default()
        .parse()
        .unwrap_or(2000);
    let timeout_secs: u64 = env::var("API_TIMEOUT")
        .unwrap_or_default()
        .parse()
        .unwrap_or(30);

    let request_body = json!({
        "model": model,
        "max_tokens": max_tokens,
        "messages": [
            {
                "role": "user",
                "content": prompt
            }
        ]
    });

    let response = client
        .post("https://api.anthropic.com/v1/messages")
        .header("x-api-key", api_key)
        .header("Content-Type", "application/json")
        .header("anthropic-version", "2023-06-01")
        .timeout(std::time::Duration::from_secs(timeout_secs))
        .json(&request_body)
        .send()
        .await
        .map_err(|e| anyhow!("Anthropic API request failed: {}", e))?;

    if !response.status().is_success() {
        let status = response.status();
        let error_text = response.text().await.unwrap_or_default();

        // 🔒 SECURITY: Log error without exposing API key
        if env::var("LOG_API_REQUESTS").unwrap_or_default() == "true" {
            println!("❌ Anthropic API Error [{}]: {}", status, error_text);
        }

        return Err(anyhow!(
            "Anthropic API error [{}]: Authentication or quota issue",
            status
        ));
    }

    let response_json: Value = response
        .json()
        .await
        .map_err(|e| anyhow!("Failed to parse Anthropic response: {}", e))?;

    let content = response_json["content"][0]["text"]
        .as_str()
        .unwrap_or("No response")
        .to_string();

    Ok(content)
}

fn call_anthropic(model: &str, api_key: &str, prompt: &str) -> Result<String> {
    tokio::runtime::Runtime::new()?.block_on(call_anthropic_async(model, api_key, prompt))
}

async fn call_google_async(model: &str, api_key: &str, prompt: &str) -> Result<String> {
    let client = reqwest::Client::new();
    let timeout_secs: u64 = env::var("API_TIMEOUT")
        .unwrap_or_default()
        .parse()
        .unwrap_or(30);

    let request_body = json!({
        "contents": [
            {
                "parts": [
                    {
                        "text": prompt
                    }
                ]
            }
        ]
    });

    let url = format!(
        "https://generativelanguage.googleapis.com/v1/models/{}:generateContent?key={}",
        model, api_key
    );

    let response = client
        .post(&url)
        .header("Content-Type", "application/json")
        .timeout(std::time::Duration::from_secs(timeout_secs))
        .json(&request_body)
        .send()
        .await
        .map_err(|e| anyhow!("Google API request failed: {}", e))?;

    if !response.status().is_success() {
        let status = response.status();
        let error_text = response.text().await.unwrap_or_default();

        // 🔒 SECURITY: Log error without exposing API key
        if env::var("LOG_API_REQUESTS").unwrap_or_default() == "true" {
            println!("❌ Google API Error [{}]: {}", status, error_text);
        }

        return Err(anyhow!(
            "Google API error [{}]: Authentication or quota issue",
            status
        ));
    }

    let response_json: Value = response
        .json()
        .await
        .map_err(|e| anyhow!("Failed to parse Google response: {}", e))?;

    let content = response_json["candidates"][0]["content"]["parts"][0]["text"]
        .as_str()
        .unwrap_or("No response")
        .to_string();

    Ok(content)
}

fn call_google(model: &str, api_key: &str, prompt: &str) -> Result<String> {
    tokio::runtime::Runtime::new()?.block_on(call_google_async(model, api_key, prompt))
}

// Placeholder implementations for other providers (implement as needed)
async fn call_deepseek_async(model: &str, api_key: &str, prompt: &str) -> Result<String> {
    let client = reqwest::Client::new();
    let max_tokens: u32 = env::var("MAX_TOKENS")
        .unwrap_or_default()
        .parse()
        .unwrap_or(2000);
    let temperature: f32 = env::var("TEMPERATURE")
        .unwrap_or_default()
        .parse()
        .unwrap_or(0.7);
    let timeout_secs: u64 = env::var("API_TIMEOUT")
        .unwrap_or_default()
        .parse()
        .unwrap_or(30);

    let request_body = json!({
        "model": model,
        "messages": [
            {
                "role": "user",
                "content": prompt
            }
        ],
        "max_tokens": max_tokens,
        "temperature": temperature,
        "stream": false
    });

    let response = client
        .post("https://api.deepseek.com/v1/chat/completions")
        .header("Authorization", format!("Bearer {}", api_key))
        .header("Content-Type", "application/json")
        .timeout(std::time::Duration::from_secs(timeout_secs))
        .json(&request_body)
        .send()
        .await
        .map_err(|e| anyhow!("DeepSeek API request failed: {}", e))?;

    if !response.status().is_success() {
        let status = response.status();
        let error_text = response.text().await.unwrap_or_default();

        if env::var("LOG_API_REQUESTS").unwrap_or_default() == "true" {
            println!("❌ DeepSeek API Error [{}]: {}", status, error_text);
        }

        return Err(anyhow!(
            "DeepSeek API error [{}]: Authentication or quota issue",
            status
        ));
    }

    let response_json: Value = response
        .json()
        .await
        .map_err(|e| anyhow!("Failed to parse DeepSeek response: {}", e))?;

    let content = response_json["choices"][0]["message"]["content"]
        .as_str()
        .unwrap_or("No response")
        .to_string();

    Ok(content)
}

fn call_deepseek(model: &str, api_key: &str, prompt: &str) -> Result<String> {
    if !is_api_key_valid(api_key, "deepseek") {
        return Err(anyhow!("DeepSeek API key not configured or invalid"));
    }
    tokio::runtime::Runtime::new()?.block_on(call_deepseek_async(model, api_key, prompt))
}

async fn call_mistral_async(model: &str, api_key: &str, prompt: &str) -> Result<String> {
    let client = reqwest::Client::new();
    let max_tokens: u32 = env::var("MAX_TOKENS")
        .unwrap_or_default()
        .parse()
        .unwrap_or(2000);
    let temperature: f32 = env::var("TEMPERATURE")
        .unwrap_or_default()
        .parse()
        .unwrap_or(0.7);
    let timeout_secs: u64 = env::var("API_TIMEOUT")
        .unwrap_or_default()
        .parse()
        .unwrap_or(30);

    let request_body = json!({
        "model": model,
        "messages": [
            {
                "role": "user",
                "content": prompt
            }
        ],
        "max_tokens": max_tokens,
        "temperature": temperature,
        "stream": false
    });

    let response = client
        .post("https://api.mistral.ai/v1/chat/completions")
        .header("Authorization", format!("Bearer {}", api_key))
        .header("Content-Type", "application/json")
        .timeout(std::time::Duration::from_secs(timeout_secs))
        .json(&request_body)
        .send()
        .await
        .map_err(|e| anyhow!("Mistral API request failed: {}", e))?;

    if !response.status().is_success() {
        let status = response.status();
        let error_text = response.text().await.unwrap_or_default();

        if env::var("LOG_API_REQUESTS").unwrap_or_default() == "true" {
            println!("❌ Mistral API Error [{}]: {}", status, error_text);
        }

        return Err(anyhow!(
            "Mistral API error [{}]: Authentication or quota issue",
            status
        ));
    }

    let response_json: Value = response
        .json()
        .await
        .map_err(|e| anyhow!("Failed to parse Mistral response: {}", e))?;

    let content = response_json["choices"][0]["message"]["content"]
        .as_str()
        .unwrap_or("No response")
        .to_string();

    Ok(content)
}

fn call_mistral(model: &str, api_key: &str, prompt: &str) -> Result<String> {
    if !is_api_key_valid(api_key, "mistral") {
        return Err(anyhow!("Mistral API key not configured or invalid"));
    }
    tokio::runtime::Runtime::new()?.block_on(call_mistral_async(model, api_key, prompt))
}

async fn call_grok_async(model: &str, api_key: &str, prompt: &str) -> Result<String> {
    let client = reqwest::Client::new();
    let max_tokens: u32 = env::var("MAX_TOKENS")
        .unwrap_or_default()
        .parse()
        .unwrap_or(2000);
    let temperature: f32 = env::var("TEMPERATURE")
        .unwrap_or_default()
        .parse()
        .unwrap_or(0.7);
    let timeout_secs: u64 = env::var("API_TIMEOUT")
        .unwrap_or_default()
        .parse()
        .unwrap_or(30);

    let request_body = json!({
        "model": model,
        "messages": [
            {
                "role": "user",
                "content": prompt
            }
        ],
        "max_tokens": max_tokens,
        "temperature": temperature,
        "stream": false
    });

    let response = client
        .post("https://api.x.ai/v1/chat/completions")
        .header("Authorization", format!("Bearer {}", api_key))
        .header("Content-Type", "application/json")
        .timeout(std::time::Duration::from_secs(timeout_secs))
        .json(&request_body)
        .send()
        .await
        .map_err(|e| anyhow!("Grok API request failed: {}", e))?;

    if !response.status().is_success() {
        let status = response.status();
        let error_text = response.text().await.unwrap_or_default();

        if env::var("LOG_API_REQUESTS").unwrap_or_default() == "true" {
            println!("❌ Grok API Error [{}]: {}", status, error_text);
        }

        return Err(anyhow!(
            "Grok API error [{}]: Authentication or quota issue",
            status
        ));
    }

    let response_json: Value = response
        .json()
        .await
        .map_err(|e| anyhow!("Failed to parse Grok response: {}", e))?;

    let content = response_json["choices"][0]["message"]["content"]
        .as_str()
        .unwrap_or("No response")
        .to_string();

    Ok(content)
}

fn call_grok(model: &str, api_key: &str, prompt: &str) -> Result<String> {
    if !is_api_key_valid(api_key, "grok") {
        return Err(anyhow!("Grok API key not configured or invalid"));
    }
    tokio::runtime::Runtime::new()?.block_on(call_grok_async(model, api_key, prompt))
}

/// Initialize environment variables from .env file
pub fn init_env() {
    dotenv::dotenv().ok(); // Load .env file if it exists

    // 🔒 SECURITY: Validate critical environment setup
    if env::var("VALIDATE_API_KEYS").unwrap_or_default() == "true" {
        validate_environment_security();
    }
}

/// 🔒 SECURITY: Validate environment security without exposing keys
fn validate_environment_security() {
    let environment = env::var("ENVIRONMENT").unwrap_or_else(|_| "dev".to_string());

    // Check for development safety measures
    if environment == "prod" {
        if env::var("USE_MOCK_RESPONSES").unwrap_or_default() == "true" {
            println!("⚠️  WARNING: Mock responses enabled in production environment!");
        }

        if env::var("DEBUG_MODE").unwrap_or_default() == "true" {
            println!("⚠️  WARNING: Debug mode enabled in production environment!");
        }

        if env::var("LOG_API_REQUESTS").unwrap_or_default() == "true" {
            println!("⚠️  WARNING: API request logging enabled in production - may expose sensitive data!");
        }
    }

    // Validate at least one API key is configured (without exposing it)
    let providers = ["OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GOOGLE_API_KEY"];
    let configured_providers: Vec<_> = providers
        .iter()
        .filter(|&&key| {
            let value = env::var(key).unwrap_or_default();
            !value.is_empty() && !value.contains("your_") && !value.contains("placeholder")
        })
        .collect();

    if configured_providers.is_empty() {
        println!(
            "⚠️  WARNING: No valid API keys configured. Set USE_MOCK_RESPONSES=true for testing."
        );
    } else {
        println!(
            "✅ Environment validation complete. {} provider(s) configured.",
            configured_providers.len()
        );
    }
}

/// Returns a registry of all LLM operators, ready for plug-and-play use in the DAG.
pub fn llm_registry() -> HashMap<String, Box<dyn SomaOperator>> {
    // Initialize environment variables
    init_env();

    let mut reg = HashMap::new();

    // 🔒 SECURITY: Load API keys securely without exposing them
    let openai_key = env::var("OPENAI_API_KEY").unwrap_or_default();
    let anthropic_key = env::var("ANTHROPIC_API_KEY").unwrap_or_default();
    let google_key = env::var("GOOGLE_API_KEY").unwrap_or_default();
    let deepseek_key = env::var("DEEPSEEK_API_KEY").unwrap_or_default();
    let mistral_key = env::var("MISTRAL_API_KEY").unwrap_or_default();
    let grok_key = env::var("GROK_API_KEY").unwrap_or_default();

    // Use environment variables for model selection with secure defaults
    let gpt_model = env::var("DEFAULT_GPT_MODEL").unwrap_or_else(|_| "gpt-4o-mini".to_string());
    let claude_model = env::var("DEFAULT_CLAUDE_MODEL")
        .unwrap_or_else(|_| "claude-3-5-sonnet-20241022".to_string());
    let gemini_model =
        env::var("DEFAULT_GEMINI_MODEL").unwrap_or_else(|_| "gemini-1.5-flash".to_string());

    reg.insert(
        "gpt_reflect".into(),
        Box::new(LLMOperator {
            id: "gpt_reflect".into(),
            model: gpt_model.clone(),
            provider: "gpt".into(),
            api_key: openai_key.clone(),
        }) as Box<dyn SomaOperator>,
    );

    reg.insert(
        "claude_plan".into(),
        Box::new(LLMOperator {
            id: "claude_plan".into(),
            model: claude_model.clone(),
            provider: "claude".into(),
            api_key: anthropic_key.clone(),
        }) as Box<dyn SomaOperator>,
    );

    reg.insert(
        "gemini_insight".into(),
        Box::new(LLMOperator {
            id: "gemini_insight".into(),
            model: gemini_model.clone(),
            provider: "gemini".into(),
            api_key: google_key.clone(),
        }) as Box<dyn SomaOperator>,
    );

    reg.insert(
        "deepseek_reason".into(),
        Box::new(LLMOperator {
            id: "deepseek_reason".into(),
            model: "deepseek-coder".into(),
            provider: "deepseek".into(),
            api_key: deepseek_key,
        }) as Box<dyn SomaOperator>,
    );

    reg.insert(
        "mistral_solve".into(),
        Box::new(LLMOperator {
            id: "mistral_solve".into(),
            model: "mistral-large-latest".into(),
            provider: "mistral".into(),
            api_key: mistral_key,
        }) as Box<dyn SomaOperator>,
    );

    reg.insert(
        "grok_judge".into(),
        Box::new(LLMOperator {
            id: "grok_judge".into(),
            model: "grok-1.5".into(),
            provider: "grok".into(),
            api_key: grok_key,
        }) as Box<dyn SomaOperator>,
    );

    reg
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::memory::SymbolicContext;

    #[test]
    fn test_llm_operator_registry_and_execution() {
        // 🔒 SECURITY: Set mock mode for testing (never use real keys in tests)
        env::set_var("USE_MOCK_RESPONSES", "true");
        env::set_var("ENVIRONMENT", "test");

        let registry = llm_registry();
        let mut ctx = SymbolicContext::new();
        ctx.set("prompt", "Test prompt for unit testing");

        // Test GPT
        let gpt = registry.get("gpt_reflect").unwrap();
        let result_ctx = gpt.execute(&ctx).unwrap();
        let response = result_ctx.get("response").unwrap();
        assert!(response.contains("MOCK_GPT"));

        // Test Claude
        let claude = registry.get("claude_plan").unwrap();
        let result_ctx = claude.execute(&ctx).unwrap();
        let response = result_ctx.get("response").unwrap();
        assert!(response.contains("MOCK_CLAUDE"));
    }

    #[test]
    fn test_api_key_validation() {
        // Test valid formats
        assert!(is_api_key_valid(
            "sk-proj-1234567890abcdefghijklmnop",
            "gpt"
        ));
        assert!(is_api_key_valid(
            "sk-ant-1234567890abcdefghijklmnopqrstuvwxyz",
            "claude"
        ));
        assert!(is_api_key_valid(
            "AIza1234567890abcdefghijklmnopqrstuvwxyz",
            "gemini"
        ));

        // Test invalid formats
        assert!(!is_api_key_valid("", "gpt"));
        assert!(!is_api_key_valid("your_openai_api_key_here", "gpt"));
        assert!(!is_api_key_valid("placeholder_key", "claude"));
        assert!(!is_api_key_valid("sk-", "gpt")); // Too short
    }

    #[test]
    fn test_env_initialization() {
        env::set_var("ENVIRONMENT", "test");
        init_env();
        // Test passes if no panic occurs
        assert!(true);
    }
}