bevy-agent 0.1.0

AI-powered Bevy game development assistant with GPT/Claude integration
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
//! Utility functions for Bevy AI

use crate::error::{BevyAIError, Result};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use walkdir::WalkDir;

/// Code analysis utilities
pub mod code_analysis {
    use super::*;
    use syn::{File, Item, ItemFn, ItemStruct, ItemEnum, ItemImpl};
    
    /// Analyze Rust code structure
    pub struct CodeAnalyzer;
    
    /// Code structure information
    #[derive(Debug, Clone)]
    pub struct CodeStructure {
        /// Functions found in the code
        pub functions: Vec<FunctionInfo>,
        /// Structs found in the code
        pub structs: Vec<StructInfo>,
        /// Enums found in the code
        pub enums: Vec<EnumInfo>,
        /// Implementation blocks found in the code
        pub impls: Vec<ImplInfo>,
        /// Import statements found in the code
        pub imports: Vec<String>,
        /// Bevy features used in the code
        pub features_used: Vec<String>,
    }
    
    /// Information about a function
    #[derive(Debug, Clone)]
    pub struct FunctionInfo {
        /// Name of the function
        pub name: String,
        /// Whether the function is public
        pub is_public: bool,
        /// Whether the function is async
        pub is_async: bool,
        /// Function parameters
        pub parameters: Vec<String>,
        /// Return type (if any)
        pub return_type: Option<String>,
        /// Line number where the function is defined
        pub line_number: usize,
    }
    
    /// Information about a struct
    #[derive(Debug, Clone)]
    pub struct StructInfo {
        /// Name of the struct
        pub name: String,
        /// Whether the struct is public
        pub is_public: bool,
        /// Fields of the struct
        pub fields: Vec<String>,
        /// Derive attributes on the struct
        pub derives: Vec<String>,
        /// Line number where the struct is defined
        pub line_number: usize,
    }
    
    /// Information about an enum
    #[derive(Debug, Clone)]
    pub struct EnumInfo {
        /// Name of the enum
        pub name: String,
        /// Whether the enum is public
        pub is_public: bool,
        /// Variants of the enum
        pub variants: Vec<String>,
        /// Derive attributes on the enum
        pub derives: Vec<String>,
        /// Line number where the enum is defined
        pub line_number: usize,
    }
    
    /// Information about an implementation block
    #[derive(Debug, Clone)]
    pub struct ImplInfo {
        /// Target type being implemented
        pub target: String,
        /// Trait being implemented (if any)
        pub trait_name: Option<String>,
        /// Methods in the implementation
        pub methods: Vec<String>,
        /// Line number where the impl block starts
        pub line_number: usize,
    }
    
    impl CodeAnalyzer {
        /// Analyze a Rust source file
        pub fn analyze_file<P: AsRef<Path>>(path: P) -> Result<CodeStructure> {
            let content = fs::read_to_string(&path)?;
            Self::analyze_code(&content)
        }
        
        /// Analyze Rust code from a string
        pub fn analyze_code(code: &str) -> Result<CodeStructure> {
            let syntax_tree: File = syn::parse_str(code)
                .map_err(|e| BevyAIError::CodeParsing(format!("Failed to parse Rust code: {}", e)))?;
            
            let mut structure = CodeStructure {
                functions: Vec::new(),
                structs: Vec::new(),
                enums: Vec::new(),
                impls: Vec::new(),
                imports: Vec::new(),
                features_used: Vec::new(),
            };
            
            for item in syntax_tree.items {
                match item {
                    Item::Fn(func) => {
                        structure.functions.push(Self::analyze_function(&func));
                    }
                    Item::Struct(struct_item) => {
                        structure.structs.push(Self::analyze_struct(&struct_item));
                    }
                    Item::Enum(enum_item) => {
                        structure.enums.push(Self::analyze_enum(&enum_item));
                    }
                    Item::Impl(impl_item) => {
                        structure.impls.push(Self::analyze_impl(&impl_item));
                    }
                    Item::Use(use_item) => {
                        structure.imports.push(quote::quote!(#use_item).to_string());
                    }
                    _ => {}
                }
            }
            
            // Analyze Bevy features being used
            structure.features_used = Self::detect_bevy_features(code);
            
            Ok(structure)
        }
        
        fn analyze_function(func: &ItemFn) -> FunctionInfo {
            FunctionInfo {
                name: func.sig.ident.to_string(),
                is_public: matches!(func.vis, syn::Visibility::Public(_)),
                is_async: func.sig.asyncness.is_some(),
                parameters: func.sig.inputs.iter()
                    .map(|param| quote::quote!(#param).to_string())
                    .collect(),
                return_type: Self::extract_return_type(func.sig.output.clone()),
                line_number: 0, // TODO: Extract line numbers
            }
        }
        
        fn analyze_struct(struct_item: &ItemStruct) -> StructInfo {
            StructInfo {
                name: struct_item.ident.to_string(),
                is_public: matches!(struct_item.vis, syn::Visibility::Public(_)),
                fields: struct_item.fields.iter()
                    .map(|field| {
                        field.ident.as_ref()
                            .map(|i| i.to_string())
                            .unwrap_or_else(|| "unnamed".to_string())
                    })
                    .collect(),
                derives: struct_item.attrs.iter()
                    .filter_map(|attr| {
                        if attr.path().is_ident("derive") {
                            Some(quote::quote!(#attr).to_string())
                        } else {
                            None
                        }
                    })
                    .collect(),
                line_number: 0,
            }
        }
        
        fn analyze_enum(enum_item: &ItemEnum) -> EnumInfo {
            EnumInfo {
                name: enum_item.ident.to_string(),
                is_public: matches!(enum_item.vis, syn::Visibility::Public(_)),
                variants: enum_item.variants.iter()
                    .map(|variant| variant.ident.to_string())
                    .collect(),
                derives: enum_item.attrs.iter()
                    .filter_map(|attr| {
                        if attr.path().is_ident("derive") {
                            Some(quote::quote!(#attr).to_string())
                        } else {
                            None
                        }
                    })
                    .collect(),
                line_number: 0,
            }
        }
        
        fn analyze_impl(impl_item: &ItemImpl) -> ImplInfo {
            ImplInfo {
                target: quote::quote!(#impl_item.self_ty).to_string(),
                trait_name: impl_item.trait_.as_ref()
                    .map(|(_, path, _)| quote::quote!(#path).to_string()),
                methods: impl_item.items.iter()
                    .filter_map(|item| {
                        if let syn::ImplItem::Fn(method) = item {
                            Some(method.sig.ident.to_string())
                        } else {
                            None
                        }
                    })
                    .collect(),
                line_number: 0,
            }
        }
        
        fn detect_bevy_features(code: &str) -> Vec<String> {
            let mut features = Vec::new();
            
            let feature_patterns = [
                ("2D Rendering", vec!["Camera2dBundle", "Sprite", "SpriteBundle"]),
                ("3D Rendering", vec!["Camera3dBundle", "PbrBundle", "Mesh"]),
                ("UI", vec!["ButtonBundle", "TextBundle", "NodeBundle"]),
                ("Audio", vec!["AudioBundle", "AudioSource"]),
                ("Physics", vec!["RigidBody", "Collider", "Velocity"]),
                ("Animation", vec!["AnimationPlayer", "AnimationClip"]),
                ("Networking", vec!["NetworkEvent", "Connection"]),
                ("Input", vec!["ButtonInput", "KeyCode", "MouseButton"]),
                ("ECS", vec!["Component", "Resource", "System"]),
                ("Transform", vec!["Transform", "GlobalTransform"]),
                ("Time", vec!["Time", "Timer"]),
                ("Events", vec!["EventReader", "EventWriter"]),
                ("Assets", vec!["Assets", "Handle", "AssetServer"]),
                ("Scene", vec!["Scene", "SceneBundle"]),
                ("Lighting", vec!["DirectionalLight", "PointLight", "SpotLight"]),
            ];
            
            for (feature_name, patterns) in &feature_patterns {
                for pattern in patterns {
                    if code.contains(pattern) {
                        features.push(feature_name.to_string());
                        break;
                    }
                }
            }
            
            features
        }
    
        // Helper function to extract return type
        fn extract_return_type(return_type: syn::ReturnType) -> Option<String> {
            match return_type {
                syn::ReturnType::Default => None,
                syn::ReturnType::Type(_, ty) => Some(quote::quote!(#ty).to_string()),
            }
        }
    }
}

/// File system utilities
pub mod fs_utils {
    use super::*;
    
    /// Find all Rust files in a directory
    pub fn find_rust_files<P: AsRef<Path>>(dir: P) -> Result<Vec<PathBuf>> {
        let mut rust_files = Vec::new();
        
        for entry in WalkDir::new(dir) {
            let entry = entry?;
            if entry.path().extension().map_or(false, |ext| ext == "rs") {
                rust_files.push(entry.path().to_path_buf());
            }
        }
        
        Ok(rust_files)
    }
    
    /// Get file extension
    pub fn get_extension<P: AsRef<Path>>(path: P) -> Option<String> {
        path.as_ref()
            .extension()
            .and_then(|ext| ext.to_str())
            .map(|s| s.to_string())
    }
    
    /// Create a backup of a file
    pub fn backup_file<P: AsRef<Path>>(path: P) -> Result<PathBuf> {
        let path = path.as_ref();
        let backup_path = path.with_extension(
            format!("{}.backup.{}", 
                path.extension().unwrap_or_default().to_string_lossy(),
                chrono::Utc::now().timestamp()
            )
        );
        
        fs::copy(path, &backup_path)?;
        Ok(backup_path)
    }
    
    /// Calculate MD5 hash of a file
    pub fn calculate_file_hash<P: AsRef<Path>>(path: P) -> Result<String> {
        let content = fs::read(path)?;
        Ok(format!("{:x}", md5::compute(&content)))
    }
    
    /// Count lines in a file
    pub fn count_lines<P: AsRef<Path>>(path: P) -> Result<usize> {
        let content = fs::read_to_string(path)?;
        Ok(content.lines().count())
    }
}

/// Build system utilities
pub mod build_utils {
    use super::*;
    
    /// Check if Rust toolchain is available
    pub fn check_rust_toolchain() -> Result<String> {
        let output = Command::new("rustc")
            .arg("--version")
            .output()?;
        
        if output.status.success() {
            Ok(String::from_utf8_lossy(&output.stdout).to_string())
        } else {
            Err(BevyAIError::build_system("Rust toolchain not found".to_string()))
        }
    }
    
    /// Check if Cargo is available
    pub fn check_cargo() -> Result<String> {
        let output = Command::new("cargo")
            .arg("--version")
            .output()?;
        
        if output.status.success() {
            Ok(String::from_utf8_lossy(&output.stdout).to_string())
        } else {
            Err(BevyAIError::build_system("Cargo not found".to_string()))
        }
    }
    
    /// Run cargo check
    pub fn cargo_check<P: AsRef<Path>>(project_path: P) -> Result<String> {
        let output = Command::new("cargo")
            .arg("check")
            .current_dir(project_path)
            .output()?;
        
        Ok(format!("{}\n{}", 
           String::from_utf8_lossy(&output.stdout),
           String::from_utf8_lossy(&output.stderr)))
    }
    
    /// Run cargo clippy
    pub fn cargo_clippy<P: AsRef<Path>>(project_path: P) -> Result<String> {
        let output = Command::new("cargo")
            .args(&["clippy", "--", "-D", "warnings"])
            .current_dir(project_path)
            .output()?;
        
        Ok(format!("{}\n{}", 
           String::from_utf8_lossy(&output.stdout),
           String::from_utf8_lossy(&output.stderr)))
    }
    
    /// Run cargo fmt
    pub fn cargo_fmt<P: AsRef<Path>>(project_path: P) -> Result<String> {
        let output = Command::new("cargo")
            .arg("fmt")
            .current_dir(project_path)
            .output()?;
        
        if output.status.success() {
            Ok("Code formatted successfully".to_string())
        } else {
            Err(BevyAIError::build_system(
                String::from_utf8_lossy(&output.stderr).to_string()
            ))
        }
    }
}

/// Text processing utilities
pub mod text_utils {
    use super::*;
    
    /// Extract code blocks from markdown text
    pub fn extract_code_blocks(text: &str) -> Vec<(Option<String>, String)> {
        let mut code_blocks = Vec::new();
        let lines: Vec<&str> = text.lines().collect();
        let mut i = 0;
        
        while i < lines.len() {
            if lines[i].starts_with("```") {
                let language = if lines[i].len() > 3 {
                    Some(lines[i][3..].trim().to_string())
                } else {
                    None
                };
                
                let mut code = String::new();
                i += 1;
                
                while i < lines.len() && !lines[i].starts_with("```") {
                    code.push_str(lines[i]);
                    code.push('\n');
                    i += 1;
                }
                
                code_blocks.push((language, code.trim().to_string()));
            }
            i += 1;
        }
        
        code_blocks
    }
    
    /// Clean up AI-generated code
    pub fn clean_ai_code(code: &str) -> String {
        // Remove common AI artifacts
        let mut cleaned = code.to_string();
        
        // Remove explanatory comments that start with "Note:" or "TODO:"
        cleaned = cleaned.lines()
            .filter(|line| {
                let trimmed = line.trim();
                !trimmed.starts_with("// Note:") && 
                !trimmed.starts_with("// TODO: Add") &&
                !trimmed.starts_with("// TODO: Implement")
            })
            .collect::<Vec<_>>()
            .join("\n");
        
        // Normalize whitespace
        cleaned = cleaned.trim().to_string();
        
        cleaned
    }
    
    /// Format Rust code using rustfmt
    pub fn format_rust_code(code: &str) -> Result<String> {
        use std::io::Write;
        use std::process::Stdio;
        
        let mut child = Command::new("rustfmt")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()?;
        
        if let Some(stdin) = child.stdin.as_mut() {
            stdin.write_all(code.as_bytes())?;
        }
        
        let output = child.wait_with_output()?;
        
        if output.status.success() {
            Ok(String::from_utf8_lossy(&output.stdout).to_string())
        } else {
            // If rustfmt fails, return original code
            Ok(code.to_string())
        }
    }
    
    /// Convert snake_case to PascalCase
    pub fn snake_to_pascal(input: &str) -> String {
        input.split('_')
            .map(|word| {
                let mut chars = word.chars();
                match chars.next() {
                    None => String::new(),
                    Some(first) => first.to_uppercase().collect::<String>() + &chars.as_str().to_lowercase(),
                }
            })
            .collect()
    }
    
    /// Convert PascalCase to snake_case
    pub fn pascal_to_snake(input: &str) -> String {
        let mut result = String::new();
        let mut prev_was_upper = false;
        
        for (i, c) in input.chars().enumerate() {
            if c.is_uppercase() && i > 0 && !prev_was_upper {
                result.push('_');
            }
            result.push(c.to_lowercase().next().unwrap_or(c));
            prev_was_upper = c.is_uppercase();
        }
        
        result
    }
}

/// Configuration utilities
pub mod config_utils {
    use super::*;
    use crate::config::AIConfig;
    
    /// Validate AI configuration
    pub fn validate_config(config: &AIConfig) -> Result<Vec<String>> {
        let mut warnings = Vec::new();
        
        if config.openai.is_none() && config.anthropic.is_none() && config.google.is_none() {
            warnings.push("No AI providers configured".to_string());
        }
        
        if config.generation.temperature < 0.0 || config.generation.temperature > 2.0 {
            warnings.push("Temperature should be between 0.0 and 2.0".to_string());
        }
        
        if config.generation.max_tokens < 100 {
            warnings.push("Max tokens is very low, may result in incomplete responses".to_string());
        }
        
        Ok(warnings)
    }
    
    /// Get default Bevy version
    pub fn get_latest_bevy_version() -> Result<String> {
        // In a real implementation, this would query crates.io API
        Ok("0.12".to_string())
    }
    
    /// Get recommended dependencies for a game type
    pub fn get_recommended_dependencies(game_type: &str) -> Vec<String> {
        match game_type.to_lowercase().as_str() {
            "platformer" | "2d" => vec![
                "bevy".to_string(),
            ],
            "fps" | "3d" | "shooter" => vec![
                "bevy".to_string(),
                "bevy_rapier3d".to_string(),
            ],
            "physics" => vec![
                "bevy".to_string(),
                "bevy_rapier2d".to_string(),
                "bevy_rapier3d".to_string(),
            ],
            "ui" | "menu" => vec![
                "bevy".to_string(),
                "bevy_egui".to_string(),
            ],
            _ => vec![
                "bevy".to_string(),
            ],
        }
    }
}