ggen-domain 5.1.3

Domain logic layer for ggen - pure business logic without CLI dependencies
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
//! AI Integration Layer - Async coordination for AI operations
//!
//! **Layer 2: Integration**
//!
//! This module provides async coordination, resource management, and error handling
//! for AI domain functions. It sits between the CLI layer (ggen-cli) and the pure
//! domain logic (ggen-domain/ai).
//!
//! ## Architecture
//!
//! ```text
//! CLI (Layer 3) → Execute (Layer 2) → Domain (Layer 1)
//!   - Input validation    - Async coordination   - Pure business logic
//!   - Output formatting   - Resource management  - Core algorithms
//!   - JSON serialization  - Error transformation  - No I/O
//! ```
//!
//! ## Execute Functions
//!
//! - `execute_generate` - AI code generation with prompts
//! - `execute_analyze` - Code and project analysis
//! - `execute_chat` - Interactive AI chat sessions
//! - FUTURE: `execute_refactor`, `execute_explain`, `execute_suggest`

use crate::ai::{analyze, generate};
use ggen_ai::{AiConfig, GenAiClient, LlmClient};
use ggen_utils::error::Result;
use serde_json::json;
use std::fs::OpenOptions;
use std::io::Write;
use std::path::Path;

// ============================================================================
// Result Types (Layer 2 - Enriched domain results for CLI)
// ============================================================================

/// Result of AI code generation execution
#[derive(Debug, Clone)]
pub struct ExecuteGenerateResult {
    /// Generated analysis or code
    pub analysis: String,
    /// Suggestions for improvement (if requested)
    pub suggestions: Vec<String>,
    /// Model used for generation
    pub model_used: String,
    /// Processing time in milliseconds
    pub processing_time_ms: u64,
}

/// Result of code analysis execution
#[derive(Debug, Clone)]
pub struct ExecuteAnalyzeResult {
    /// Analysis insights and recommendations
    pub analysis: String,
    /// Path to file analyzed (if file-based)
    pub file_analyzed: Option<String>,
}

/// Result of chat execution
#[derive(Debug, Clone)]
pub struct ExecuteChatResult {
    /// AI response message
    pub response: String,
    /// Model used for chat
    pub model_used: String,
}

// ============================================================================
// Execute Functions (Layer 2 - Async coordination and resource management)
// ============================================================================

// #region agent log helper
fn log_debug(
    session_id: &str, run_id: &str, hypothesis_id: &str, location: &str, message: &str,
    data: serde_json::Value,
) {
    if let Ok(mut file) = OpenOptions::new()
        .create(true)
        .append(true)
        .open("/Users/sac/ggen/.cursor/debug.log")
    {
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis())
            .unwrap_or(0);
        let entry = json!({
            "sessionId": session_id,
            "runId": run_id,
            "hypothesisId": hypothesis_id,
            "location": location,
            "message": message,
            "data": data,
            "timestamp": timestamp,
        });
        let _ = writeln!(file, "{}", entry);
    }
}
// #endregion

/// Execute AI code generation with prompt and options
///
/// **Layer 2 responsibilities**:
/// - Async coordination: Orchestrates async AI API calls
/// - Resource management: Handles API rate limiting, connection pooling
/// - Error transformation: Converts domain errors to CLI-friendly format
/// - Result enrichment: Adds metadata (processing time, model info)
///
/// # Arguments
///
/// * `prompt` - User prompt describing what to generate
/// * `code` - Optional code snippet to analyze or refactor
/// * `model` - Optional model to use (defaults to domain-configured model)
/// * `suggestions` - Whether to include improvement suggestions
///
/// # Returns
///
/// * `Ok(ExecuteGenerateResult)` - Generation succeeded with result data
/// * `Err(Error)` - Generation failed (API error, validation, timeout)
///
/// # Examples
///
/// ```rust,no_run
/// # use ggen_domain::ai::execute;
/// # async fn example() -> ggen_utils::error::Result<()> {
/// let result = execute::execute_generate(
///     "write a hello world function",
///     None,
///     None,
///     true,
/// ).await?;
///
/// println!("Generated: {}", result.analysis);
/// println!("Suggestions: {:?}", result.suggestions);
/// # Ok(())
/// # }
/// ```
pub async fn execute_generate(
    prompt: &str, code: Option<&str>, model: Option<&str>, suggestions: bool,
) -> Result<ExecuteGenerateResult> {
    // #region agent log
    log_debug(
        "debug-session",
        "run1",
        "H1",
        "ai/execute.rs:execute_generate:entry",
        "entered execute_generate",
        json!({
            "prompt_len": prompt.len(),
            "prompt_trimmed_empty": prompt.trim().is_empty(),
            "has_code": code.is_some(),
            "model": model.map(|m| m.to_string()),
            "suggestions": suggestions,
        }),
    );
    // #endregion

    // Layer 2: Input validation (additional validation beyond CLI)
    if prompt.trim().is_empty() {
        return Err(ggen_utils::error::Error::new("Prompt cannot be empty"));
    }

    // Layer 2: Build domain options with builder pattern
    let mut options =
        generate::GenerateOptions::new(prompt).with_format(generate::OutputFormat::Json);

    if suggestions {
        options = options.with_suggestions();
    }

    if let Some(code_content) = code {
        options = options.with_code(code_content.to_string());
    }

    if let Some(model_name) = model {
        options = options.with_model(model_name);
    }

    // Layer 2: Track execution time
    let start = std::time::Instant::now();

    // Call Layer 1 domain function (pure business logic)
    let result = generate::generate_code(&options).await?;

    let processing_time_ms = start.elapsed().as_millis() as u64;

    // Layer 2: Transform domain result to execute result
    // #region agent log
    log_debug(
        "debug-session",
        "run1",
        "H1",
        "ai/execute.rs:execute_generate:ok",
        "execute_generate succeeded",
        json!({
            "model_used": result.metadata.model_used,
            "processing_time_ms": processing_time_ms,
            "suggestions_count": result.suggestions.as_ref().map(|s| s.len()).unwrap_or(0),
        }),
    );
    // #endregion
    Ok(ExecuteGenerateResult {
        analysis: result.analysis,
        suggestions: result.suggestions.unwrap_or_default(),
        model_used: result.metadata.model_used,
        processing_time_ms,
    })
}

/// Execute code analysis on snippet or project
///
/// **Layer 2 responsibilities**:
/// - Async coordination: Orchestrates file I/O and AI analysis
/// - Resource management: Handles large file analysis with chunking
/// - Error transformation: Provides clear error messages for file not found, permissions
/// - Result enrichment: Adds file path metadata
///
/// # Arguments
///
/// * `code` - Optional code snippet to analyze
/// * `file` - Optional file/directory path to analyze
///
/// # Returns
///
/// * `Ok(ExecuteAnalyzeResult)` - Analysis succeeded with insights
/// * `Err(Error)` - Analysis failed (no input, file not found, API error)
///
/// # Examples
///
/// ```rust,no_run
/// # use ggen_domain::ai::execute;
/// # use std::path::Path;
/// # async fn example() -> ggen_utils::error::Result<()> {
/// // Analyze code snippet
/// let result = execute::execute_analyze(
///     Some("fn main() { println!(\"hello\"); }"),
///     None,
/// ).await?;
///
/// // Analyze project directory
/// let result = execute::execute_analyze(
///     None,
///     Some(Path::new("./src")),
/// ).await?;
/// # Ok(())
/// # }
/// ```
pub async fn execute_analyze(
    code: Option<&str>, file: Option<&Path>,
) -> Result<ExecuteAnalyzeResult> {
    // #region agent log
    log_debug(
        "debug-session",
        "run1",
        "H3",
        "ai/execute.rs:execute_analyze:entry",
        "entered execute_analyze",
        json!({
            "has_code": code.is_some(),
            "code_len": code.map(|c| c.len()),
            "has_file": file.is_some(),
            "file": file.map(|p| p.display().to_string()),
        }),
    );
    // #endregion

    // Layer 2: Input validation - Must have either code or file
    if code.is_none() && file.is_none() {
        return Err(ggen_utils::error::Error::new(
            "Must provide either code or file to analyze",
        ));
    }

    // Call Layer 1 domain functions based on input type
    let analysis_text = if let Some(code_content) = code {
        // Analyze code snippet
        if code_content.trim().is_empty() {
            return Err(ggen_utils::error::Error::new("Code cannot be empty"));
        }
        // #region agent log
        log_debug(
            "debug-session",
            "run1",
            "H3",
            "ai/execute.rs:execute_analyze:branch",
            "analyzing code snippet",
            json!({
                "trimmed_empty": code_content.trim().is_empty(),
                "code_len": code_content.len(),
            }),
        );
        // #endregion
        analyze::analyze_code(code_content).await?
    } else if let Some(file_path) = file {
        // Layer 2: Validate file exists before calling domain
        if !file_path.exists() {
            return Err(ggen_utils::error::Error::new(&format!(
                "Path does not exist: {}",
                file_path.display()
            )));
        }
        // #region agent log
        log_debug(
            "debug-session",
            "run1",
            "H3",
            "ai/execute.rs:execute_analyze:branch",
            "analyzing file path",
            json!({
                "path": file_path.display().to_string(),
                "exists": file_path.exists(),
            }),
        );
        // #endregion
        analyze::analyze_project(file_path).await?
    } else {
        unreachable!("Already validated input above")
    };

    // Layer 2: Transform domain result to execute result
    // #region agent log
    log_debug(
        "debug-session",
        "run1",
        "H3",
        "ai/execute.rs:execute_analyze:ok",
        "execute_analyze succeeded",
        json!({
            "analysis_len": analysis_text.len(),
            "file_analyzed": file.map(|p| p.display().to_string()),
        }),
    );
    // #endregion
    Ok(ExecuteAnalyzeResult {
        analysis: analysis_text,
        file_analyzed: file.map(|p| p.display().to_string()),
    })
}

/// Execute interactive chat session
///
/// **Layer 2 responsibilities**:
/// - Async coordination: Manages conversation state and history
/// - Resource management: Handles chat session lifecycle
/// - Error transformation: Provides user-friendly chat error messages
///
/// # Arguments
///
/// * `message` - User message to send to AI
/// * `model` - Optional model to use for chat
///
/// # Returns
///
/// * `Ok(ExecuteChatResult)` - Chat response received
/// * `Err(Error)` - Chat failed (API error, rate limiting)
///
/// # Notes
///
/// This is currently a STUB implementation. Full chat functionality requires:
/// - Domain function: `crate::ai::chat::execute_chat()`
/// - Conversation history management
/// - Streaming response support
/// - Session persistence
///
/// # Examples
///
/// ```rust,no_run
/// # use ggen_domain::ai::execute;
/// # async fn example() -> ggen_utils::error::Result<()> {
/// let result = execute::execute_chat(
///     "explain what RDF is",
///     Some("gpt-4"),
/// ).await?;
///
/// println!("AI: {}", result.response);
/// # Ok(())
/// # }
/// ```
pub async fn execute_chat(message: &str, model: Option<&str>) -> Result<ExecuteChatResult> {
    // #region agent log
    log_debug(
        "debug-session",
        "run1",
        "H4",
        "ai/execute.rs:execute_chat:entry",
        "entered execute_chat",
        json!({
            "message_len": message.len(),
            "message_trimmed_empty": message.trim().is_empty(),
            "model": model.map(|m| m.to_string()),
        }),
    );
    // #endregion

    // Layer 2: Input validation
    if message.trim().is_empty() {
        return Err(ggen_utils::error::Error::new("Message cannot be empty"));
    }

    let mut config = AiConfig::from_env().unwrap_or_else(|_| AiConfig::new()).llm;
    if let Some(m) = model {
        config.model = m.to_string();
    }
    if config.max_tokens.is_none() {
        config.max_tokens = Some(512);
    }
    if config.temperature.is_none() {
        config.temperature = Some(0.7);
    }

    let client = GenAiClient::new(config)
        .map_err(|e| ggen_utils::error::Error::new(&format!("Failed to create LLM client: {e}")))?;

    let prompt = format!(
        "You are a concise Rust assistant. Respond helpfully to the user.
User: {}",
        message
    );

    let resp = client
        .complete(&prompt)
        .await
        .map_err(|e| ggen_utils::error::Error::new(&format!("Chat failed: {e}")))?;

    // #region agent log
    log_debug(
        "debug-session",
        "run1",
        "H4",
        "ai/execute.rs:execute_chat:ok",
        "execute_chat response",
        json!({
            "model_used": resp.model,
            "response_preview": resp.content.chars().take(80).collect::<String>(),
        }),
    );
    // #endregion

    Ok(ExecuteChatResult {
        response: resp.content,
        model_used: resp.model,
    })
}

// ============================================================================
// FUTURE: Additional Execute Functions
// ============================================================================

// FUTURE: execute_refactor - Refactor code with AI assistance
// FUTURE: execute_explain - Explain code functionality
// FUTURE: execute_suggest - Suggest improvements and best practices

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

    #[tokio::test]
    async fn test_execute_generate_validation() {
        // Empty prompt should fail
        let result = execute_generate("", None, None, false).await;
        assert!(result.is_err());

        // Whitespace-only prompt should fail
        let result = execute_generate("   ", None, None, false).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_execute_analyze_validation() {
        // No input should fail
        let result = execute_analyze(None, None).await;
        assert!(result.is_err());

        // Empty code should fail
        let result = execute_analyze(Some(""), None).await;
        assert!(result.is_err());

        // Non-existent path should fail
        let result = execute_analyze(None, Some(Path::new("/nonexistent/path"))).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_execute_chat_validation() {
        // Empty message should fail
        let result = execute_chat("", None).await;
        assert!(result.is_err());

        // Whitespace-only message should fail
        let result = execute_chat("   ", None).await;
        assert!(result.is_err());
    }

    #[ignore = "Requires API key and network access - integration test"]
    #[tokio::test]
    async fn test_execute_chat_placeholder() {
        // Placeholder implementation should work for valid input
        let result = execute_chat("hello", Some("gpt-4")).await;
        assert!(result.is_ok());

        let chat_result = result.unwrap();
        assert!(!chat_result.response.is_empty());
        assert_eq!(chat_result.model_used, "gpt-4");
    }
}