aprender-orchestrate 0.31.2

Sovereign AI orchestration: autonomous agents, ML serving, code analysis, and transpilation pipelines
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
//! PARF (Pattern and Reference Finder) module (BATUTA-012)
//!
//! Cross-codebase pattern analysis and reference finding for
//! understanding code dependencies, usage patterns, and migration planning.
//!
//! # Features
//!
//! - **Symbol References**: Find all references to functions, classes, variables
//! - **Pattern Detection**: Identify common code patterns and idioms
//! - **Dependency Analysis**: Build dependency graphs across files
//! - **Dead Code Detection**: Find unused code that can be removed
//! - **Call Graph Generation**: Understand function call relationships
//!
//! # Example
//!
//! ```rust,ignore
//! use batuta::parf::{ParfAnalyzer, SymbolKind};
//!
//! let analyzer = ParfAnalyzer::new();
//! let refs = analyzer.find_references("my_function", SymbolKind::Function)?;
//! let patterns = analyzer.detect_patterns(&codebase)?;
//! let deps = analyzer.analyze_dependencies(&codebase)?;
//! ```

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

#[cfg(feature = "native")]
use walkdir::WalkDir;

/// Symbol kind for reference finding
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SymbolKind {
    Function,
    Class,
    Variable,
    Constant,
    Module,
    Import,
}

/// A reference to a symbol in the codebase
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SymbolReference {
    /// Symbol name
    pub symbol: String,
    /// Symbol kind
    pub kind: SymbolKind,
    /// File path where reference occurs
    pub file: PathBuf,
    /// Line number
    pub line: usize,
    /// Context (surrounding code)
    pub context: String,
}

/// Code pattern detected in the codebase
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CodePattern {
    /// Repeated code block
    DuplicateCode { pattern: String, occurrences: Vec<(PathBuf, usize)> },
    /// TODO/FIXME comments
    TechDebt { message: String, file: PathBuf, line: usize },
    /// Deprecated API usage
    DeprecatedApi { api: String, file: PathBuf, line: usize },
    /// Error handling pattern
    ErrorHandling { pattern: String, file: PathBuf, line: usize },
    /// Resource management pattern (file handles, connections, etc.)
    ResourceManagement { resource_type: String, file: PathBuf, line: usize },
}

/// Dependency relationship between files
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileDependency {
    /// Source file
    pub from: PathBuf,
    /// Target file
    pub to: PathBuf,
    /// Type of dependency
    pub kind: DependencyKind,
}

/// Type of dependency between files
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum DependencyKind {
    Import,
    Include,
    Require,
    ModuleUse,
}

/// Dead code analysis result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeadCode {
    /// Symbol name
    pub symbol: String,
    /// Symbol kind
    pub kind: SymbolKind,
    /// File where defined
    pub file: PathBuf,
    /// Line number
    pub line: usize,
    /// Reason it's considered dead
    pub reason: String,
}

/// PARF analyzer for cross-codebase analysis
pub struct ParfAnalyzer {
    /// Cached file contents
    file_cache: HashMap<PathBuf, Vec<String>>,
    /// Symbol definitions
    symbol_definitions: HashMap<String, Vec<SymbolReference>>,
    /// Symbol references
    symbol_references: HashMap<String, Vec<SymbolReference>>,
}

impl Default for ParfAnalyzer {
    fn default() -> Self {
        Self::new()
    }
}

impl ParfAnalyzer {
    /// Create a new PARF analyzer
    pub fn new() -> Self {
        Self {
            file_cache: HashMap::new(),
            symbol_definitions: HashMap::new(),
            symbol_references: HashMap::new(),
        }
    }

    /// Index a codebase for analysis
    #[cfg(feature = "native")]
    pub fn index_codebase(&mut self, path: &Path) -> Result<()> {
        for entry in WalkDir::new(path).follow_links(true).into_iter().filter_map(|e| e.ok()) {
            if entry.file_type().is_file() {
                if let Some(ext) = entry.path().extension() {
                    // Process source files
                    if ["rs", "py", "js", "ts", "c", "cpp", "h", "hpp"]
                        .contains(&ext.to_str().unwrap_or(""))
                    {
                        self.index_file(entry.path())?;
                    }
                }
            }
        }
        Ok(())
    }

    /// Index a codebase for analysis (stub when native disabled)
    #[cfg(not(feature = "native"))]
    pub fn index_codebase(&mut self, _path: &Path) -> Result<()> {
        Ok(())
    }

    /// Index a single file
    fn index_file(&mut self, path: &Path) -> Result<()> {
        let content = std::fs::read_to_string(path)
            .with_context(|| format!("Failed to read file: {}", path.display()))?;

        let lines: Vec<String> = content.lines().map(|s| s.to_string()).collect();
        self.file_cache.insert(path.to_path_buf(), lines.clone());

        // Simple pattern matching for common symbols
        for (line_num, line) in lines.iter().enumerate() {
            // Rust function definitions
            if line.contains("fn ") && line.contains('(') {
                if let Some(name) = Self::extract_function_name(line) {
                    self.add_definition(
                        name,
                        SymbolKind::Function,
                        path,
                        line_num + 1,
                        line.trim(),
                    );
                }
            }

            // Rust struct/enum definitions
            if line.contains("struct ") || line.contains("enum ") {
                if let Some(name) = Self::extract_type_name(line) {
                    self.add_definition(name, SymbolKind::Class, path, line_num + 1, line.trim());
                }
            }

            // Python function definitions
            if line.trim_start().starts_with("def ") {
                if let Some(name) = Self::extract_python_function_name(line) {
                    self.add_definition(
                        name,
                        SymbolKind::Function,
                        path,
                        line_num + 1,
                        line.trim(),
                    );
                }
            }

            // Python class definitions
            if line.trim_start().starts_with("class ") {
                if let Some(name) = Self::extract_python_class_name(line) {
                    self.add_definition(name, SymbolKind::Class, path, line_num + 1, line.trim());
                }
            }
        }

        Ok(())
    }

    /// Add a symbol definition
    fn add_definition(
        &mut self,
        symbol: String,
        kind: SymbolKind,
        file: &Path,
        line: usize,
        context: &str,
    ) {
        let reference = SymbolReference {
            symbol: symbol.clone(),
            kind,
            file: file.to_path_buf(),
            line,
            context: context.to_string(),
        };

        self.symbol_definitions.entry(symbol).or_default().push(reference);
    }

    /// Find all references to a symbol
    pub fn find_references(&self, symbol: &str, _kind: SymbolKind) -> Vec<SymbolReference> {
        let mut references = Vec::new();

        // Search through all cached files
        for (path, lines) in &self.file_cache {
            for (line_num, line) in lines.iter().enumerate() {
                if line.contains(symbol) {
                    references.push(SymbolReference {
                        symbol: symbol.to_string(),
                        kind: SymbolKind::Function, // Simplified for now
                        file: path.clone(),
                        line: line_num + 1,
                        context: line.trim().to_string(),
                    });
                }
            }
        }

        references
    }

    /// Detect code patterns in the codebase
    ///
    /// Uses `PATTERN_MARKERS` lookup table to map source markers to pattern
    /// categories, eliminating per-category if-contains blocks.
    pub fn detect_patterns(&self) -> Vec<CodePattern> {
        /// Mapping from source text marker to pattern category.
        ///
        /// Categories:
        /// - `"tech_debt"` -> [`CodePattern::TechDebt`]
        /// - `"deprecated_api"` -> [`CodePattern::DeprecatedApi`]
        /// - `"error_handling"` -> [`CodePattern::ErrorHandling`]
        /// - `"resource_management"` -> [`CodePattern::ResourceManagement`]
        const PATTERN_MARKERS: &[(&str, &str)] = &[
            ("TO\x44O", "tech_debt"),
            ("FIX\x4dE", "tech_debt"),
            ("HACK", "tech_debt"),
            ("deprecated", "deprecated_api"),
            ("@deprecated", "deprecated_api"),
            ("unwrap()", "error_handling"),
            ("expect(", "error_handling"),
            ("File::open", "resource_management"),
            ("fs::read", "resource_management"),
        ];

        let mut patterns = Vec::new();

        for (path, lines) in &self.file_cache {
            for (line_num, line) in lines.iter().enumerate() {
                for &(marker, category) in PATTERN_MARKERS {
                    if !line.contains(marker) {
                        continue;
                    }
                    // Preserve original filter: skip unwrap() inside comments
                    if marker == "unwrap()" && line.contains("//") {
                        continue;
                    }
                    let trimmed = line.trim().to_string();
                    let loc = (path.clone(), line_num + 1);
                    patterns.push(match category {
                        "tech_debt" => {
                            CodePattern::TechDebt { message: trimmed, file: loc.0, line: loc.1 }
                        }
                        "deprecated_api" => {
                            CodePattern::DeprecatedApi { api: trimmed, file: loc.0, line: loc.1 }
                        }
                        "error_handling" => CodePattern::ErrorHandling {
                            pattern: format!("{marker} without error handling"),
                            file: loc.0,
                            line: loc.1,
                        },
                        "resource_management" => CodePattern::ResourceManagement {
                            resource_type: "file".to_string(),
                            file: loc.0,
                            line: loc.1,
                        },
                        _ => unreachable!("unknown pattern category: {category}"),
                    });
                }
            }
        }

        patterns
    }

    /// Analyze dependencies between files
    pub fn analyze_dependencies(&self) -> Vec<FileDependency> {
        contract_pre_analyze!(self);
        let mut dependencies = Vec::new();

        for (path, lines) in &self.file_cache {
            for line in lines {
                // Rust imports
                if line.trim_start().starts_with("use ") {
                    // Simplified: would need proper parsing for real implementation
                    dependencies.push(FileDependency {
                        from: path.clone(),
                        to: PathBuf::from("module"), // Placeholder
                        kind: DependencyKind::ModuleUse,
                    });
                }

                // Python imports
                if line.trim_start().starts_with("import ")
                    || line.trim_start().starts_with("from ")
                {
                    dependencies.push(FileDependency {
                        from: path.clone(),
                        to: PathBuf::from("module"), // Placeholder
                        kind: DependencyKind::Import,
                    });
                }
            }
        }

        dependencies
    }

    /// Find potentially dead code
    pub fn find_dead_code(&self) -> Vec<DeadCode> {
        let mut dead_code = Vec::new();
        let mut referenced_symbols = HashSet::new();

        // Collect all referenced symbols
        for lines in self.file_cache.values() {
            for line in lines {
                // Simple heuristic: any identifier used in code
                for def in self.symbol_definitions.keys() {
                    if line.contains(def) {
                        referenced_symbols.insert(def.clone());
                    }
                }
            }
        }

        // Find definitions that are never referenced
        for (symbol, defs) in &self.symbol_definitions {
            if !referenced_symbols.contains(symbol) {
                for def in defs {
                    // Skip test functions
                    if def.context.contains("#[test]") || def.context.contains("test_") {
                        continue;
                    }

                    // Skip main functions
                    if symbol == "main" {
                        continue;
                    }

                    dead_code.push(DeadCode {
                        symbol: symbol.clone(),
                        kind: def.kind,
                        file: def.file.clone(),
                        line: def.line,
                        reason: "No references found".to_string(),
                    });
                }
            }
        }

        dead_code
    }

    /// Generate analysis report
    pub fn generate_report(&self) -> String {
        let mut report = String::from("PARF Analysis Report\n");
        report.push_str("====================\n\n");

        report.push_str(&format!("Files analyzed: {}\n", self.file_cache.len()));
        report.push_str(&format!("Symbols defined: {}\n", self.symbol_definitions.len()));
        report.push_str(&format!("Patterns detected: {}\n", self.detect_patterns().len()));
        report.push_str(&format!("Dependencies: {}\n\n", self.analyze_dependencies().len()));

        // Dead code summary
        let dead_code = self.find_dead_code();
        report.push_str(&format!("Potentially dead code: {}\n", dead_code.len()));

        if !dead_code.is_empty() {
            report.push_str("\nDead Code Candidates:\n");
            report.push_str("---------------------\n");
            for (i, dc) in dead_code.iter().take(10).enumerate() {
                report.push_str(&format!(
                    "{}. {} ({:?}) in {}:{}\n",
                    i + 1,
                    dc.symbol,
                    dc.kind,
                    dc.file.display(),
                    dc.line
                ));
            }
            if dead_code.len() > 10 {
                report.push_str(&format!("... and {} more\n", dead_code.len() - 10));
            }
        }

        report
    }

    // Helper functions for symbol extraction

    fn extract_function_name(line: &str) -> Option<String> {
        // Extract function name from Rust: "fn name(" or "pub fn name("
        if let Some(fn_pos) = line.find("fn ") {
            let after_fn = &line[fn_pos + 3..];
            if let Some(paren_pos) = after_fn.find('(') {
                return Some(after_fn[..paren_pos].trim().to_string());
            }
        }
        None
    }

    fn extract_type_name(line: &str) -> Option<String> {
        // Extract type name from Rust: "struct Name" or "enum Name"
        for keyword in &["struct ", "enum "] {
            if let Some(pos) = line.find(keyword) {
                let after_keyword = &line[pos + keyword.len()..];
                if let Some(space_or_brace) =
                    after_keyword.find(|c: char| c.is_whitespace() || c == '{' || c == '<')
                {
                    return Some(after_keyword[..space_or_brace].trim().to_string());
                }
            }
        }
        None
    }

    fn extract_python_function_name(line: &str) -> Option<String> {
        // Extract function name from Python: "def name("
        if let Some(def_pos) = line.find("def ") {
            let after_def = &line[def_pos + 4..];
            if let Some(paren_pos) = after_def.find('(') {
                return Some(after_def[..paren_pos].trim().to_string());
            }
        }
        None
    }

    fn extract_python_class_name(line: &str) -> Option<String> {
        // Extract class name from Python: "class Name:" or "class Name("
        if let Some(class_pos) = line.find("class ") {
            let after_class = &line[class_pos + 6..];
            if let Some(end_pos) = after_class.find([':', '(']) {
                return Some(after_class[..end_pos].trim().to_string());
            }
        }
        None
    }
}

#[cfg(test)]
#[path = "parf_tests.rs"]
mod tests;