agentic-codebase 0.3.0

Semantic code compiler for AI agents - transforms codebases into navigable concept graphs
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
//! Architecture Inference — Invention 8.
//!
//! Infer architecture from the code structure itself. No documentation needed.
//! Detects patterns like Layered, MVC, Microservices, etc. from module structure
//! and dependency directions.

use std::collections::{HashMap, HashSet};

use serde::{Deserialize, Serialize};

use crate::graph::CodeGraph;
use crate::types::{CodeUnitType, EdgeType};

// ── Types ────────────────────────────────────────────────────────────────────

/// Inferred architecture.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InferredArchitecture {
    /// Overall pattern detected.
    pub pattern: ArchitecturePattern,
    /// Layers/tiers.
    pub layers: Vec<ArchitectureLayer>,
    /// Key components.
    pub components: Vec<ArchitectureComponent>,
    /// Data flows.
    pub flows: Vec<DataFlow>,
    /// Confidence in inference.
    pub confidence: f64,
    /// Anomalies (violations of pattern).
    pub anomalies: Vec<ArchitectureAnomaly>,
}

/// Detected architecture pattern.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ArchitecturePattern {
    Monolith,
    Microservices,
    Layered,
    Hexagonal,
    EventDriven,
    CQRS,
    Serverless,
    MVC,
    Unknown,
}

/// An architectural layer.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ArchitectureLayer {
    pub name: String,
    pub purpose: String,
    pub modules: Vec<String>,
    pub depends_on: Vec<String>,
}

/// An architectural component.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ArchitectureComponent {
    pub name: String,
    pub role: ComponentRole,
    pub node_ids: Vec<u64>,
    pub external_deps: Vec<String>,
}

/// Role of an architectural component.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ComponentRole {
    Entrypoint,
    Controller,
    Service,
    Repository,
    Model,
    Utility,
    Configuration,
    Test,
}

/// A data flow between components.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataFlow {
    pub name: String,
    pub source: String,
    pub destination: String,
    pub via: Vec<String>,
    pub data_type: String,
}

/// An architecture anomaly.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ArchitectureAnomaly {
    pub description: String,
    pub node_id: u64,
    pub expected: String,
    pub actual: String,
    pub severity: AnomalySeverity,
}

/// Severity of an anomaly.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AnomalySeverity {
    Info,
    Warning,
    Error,
    Critical,
}

// ── ArchitectureInferrer ─────────────────────────────────────────────────────

/// Infers architecture from code structure.
pub struct ArchitectureInferrer<'g> {
    graph: &'g CodeGraph,
}

impl<'g> ArchitectureInferrer<'g> {
    pub fn new(graph: &'g CodeGraph) -> Self {
        Self { graph }
    }

    /// Infer the architecture from the code graph.
    pub fn infer(&self) -> InferredArchitecture {
        let components = self.detect_components();
        let layers = self.detect_layers(&components);
        let flows = self.detect_flows(&components);
        let pattern = self.classify_pattern(&components, &layers);
        let anomalies = self.detect_anomalies(&components, &pattern);
        let confidence = self.compute_confidence(&components, &layers);

        InferredArchitecture {
            pattern,
            layers,
            components,
            flows,
            confidence,
            anomalies,
        }
    }

    /// Generate diagram-ready data.
    pub fn diagram(&self, arch: &InferredArchitecture) -> serde_json::Value {
        serde_json::json!({
            "pattern": format!("{:?}", arch.pattern),
            "layers": arch.layers.iter().map(|l| serde_json::json!({
                "name": l.name,
                "purpose": l.purpose,
                "modules": l.modules,
                "depends_on": l.depends_on,
            })).collect::<Vec<_>>(),
            "components": arch.components.iter().map(|c| serde_json::json!({
                "name": c.name,
                "role": format!("{:?}", c.role),
                "size": c.node_ids.len(),
            })).collect::<Vec<_>>(),
            "flows": arch.flows.iter().map(|f| serde_json::json!({
                "from": f.source,
                "to": f.destination,
                "via": f.via,
            })).collect::<Vec<_>>(),
        })
    }

    /// Validate code against an expected architecture pattern.
    pub fn validate(&self, expected: ArchitecturePattern) -> Vec<ArchitectureAnomaly> {
        let inferred = self.infer();
        let mut anomalies = inferred.anomalies;

        if inferred.pattern != expected {
            anomalies.push(ArchitectureAnomaly {
                description: format!(
                    "Expected {:?} architecture but detected {:?}",
                    expected, inferred.pattern
                ),
                node_id: 0,
                expected: format!("{:?}", expected),
                actual: format!("{:?}", inferred.pattern),
                severity: AnomalySeverity::Warning,
            });
        }

        anomalies
    }

    // ── Internal ─────────────────────────────────────────────────────────

    fn detect_components(&self) -> Vec<ArchitectureComponent> {
        let mut role_map: HashMap<ComponentRole, Vec<u64>> = HashMap::new();

        for unit in self.graph.units() {
            let name_lower = unit.name.to_lowercase();
            let qname_lower = unit.qualified_name.to_lowercase();
            let path_lower = unit.file_path.display().to_string().to_lowercase();

            let role = if Self::matches_any(
                &[&name_lower, &qname_lower, &path_lower],
                &["controller", "handler", "view", "endpoint"],
            ) {
                ComponentRole::Controller
            } else if Self::matches_any(
                &[&name_lower, &qname_lower, &path_lower],
                &["service", "usecase", "interactor"],
            ) {
                ComponentRole::Service
            } else if Self::matches_any(
                &[&name_lower, &qname_lower, &path_lower],
                &["repository", "repo", "dao", "store", "adapter"],
            ) {
                ComponentRole::Repository
            } else if Self::matches_any(
                &[&name_lower, &qname_lower, &path_lower],
                &["model", "entity", "schema", "dto"],
            ) {
                ComponentRole::Model
            } else if Self::matches_any(
                &[&name_lower, &qname_lower, &path_lower],
                &["config", "setting", "env"],
            ) {
                ComponentRole::Configuration
            } else if unit.unit_type == CodeUnitType::Test {
                ComponentRole::Test
            } else if Self::matches_any(
                &[&name_lower, &qname_lower, &path_lower],
                &["main", "app", "server", "cli", "entry"],
            ) {
                ComponentRole::Entrypoint
            } else {
                ComponentRole::Utility
            };

            role_map.entry(role).or_default().push(unit.id);
        }

        role_map
            .into_iter()
            .map(|(role, ids)| {
                let name = format!("{:?}", role);
                let external_deps = self.find_external_deps(&ids);
                ArchitectureComponent {
                    name,
                    role,
                    node_ids: ids,
                    external_deps,
                }
            })
            .collect()
    }

    fn detect_layers(&self, components: &[ArchitectureComponent]) -> Vec<ArchitectureLayer> {
        let mut layers = Vec::new();

        let has_controllers = components
            .iter()
            .any(|c| c.role == ComponentRole::Controller);
        let has_services = components.iter().any(|c| c.role == ComponentRole::Service);
        let has_repos = components
            .iter()
            .any(|c| c.role == ComponentRole::Repository);

        if has_controllers {
            layers.push(ArchitectureLayer {
                name: "Presentation".to_string(),
                purpose: "Handle external requests and responses".to_string(),
                modules: self.modules_for_role(components, ComponentRole::Controller),
                depends_on: vec!["Business Logic".to_string()],
            });
        }

        if has_services {
            layers.push(ArchitectureLayer {
                name: "Business Logic".to_string(),
                purpose: "Core business rules and workflows".to_string(),
                modules: self.modules_for_role(components, ComponentRole::Service),
                depends_on: vec!["Data Access".to_string()],
            });
        }

        if has_repos {
            layers.push(ArchitectureLayer {
                name: "Data Access".to_string(),
                purpose: "Data persistence and retrieval".to_string(),
                modules: self.modules_for_role(components, ComponentRole::Repository),
                depends_on: Vec::new(),
            });
        }

        layers
    }

    fn detect_flows(&self, components: &[ArchitectureComponent]) -> Vec<DataFlow> {
        let mut flows = Vec::new();

        // Detect flows from call edges between component roles
        let role_names: Vec<(ComponentRole, &str)> = components
            .iter()
            .map(|c| (c.role, c.name.as_str()))
            .collect();

        for comp in components {
            for &node_id in &comp.node_ids {
                for edge in self.graph.edges_from(node_id) {
                    if edge.edge_type != EdgeType::Calls {
                        continue;
                    }
                    // Find which component the target belongs to
                    for other in components {
                        if other.role != comp.role && other.node_ids.contains(&edge.target_id) {
                            let flow_name = format!("{:?} -> {:?}", comp.role, other.role);
                            if !flows.iter().any(|f: &DataFlow| f.name == flow_name) {
                                flows.push(DataFlow {
                                    name: flow_name,
                                    source: format!("{:?}", comp.role),
                                    destination: format!("{:?}", other.role),
                                    via: Vec::new(),
                                    data_type: "function call".to_string(),
                                });
                            }
                            break;
                        }
                    }
                }
            }
        }

        let _ = role_names; // suppress unused warning
        flows
    }

    fn classify_pattern(
        &self,
        components: &[ArchitectureComponent],
        layers: &[ArchitectureLayer],
    ) -> ArchitecturePattern {
        let has_controllers = components
            .iter()
            .any(|c| c.role == ComponentRole::Controller);
        let has_services = components.iter().any(|c| c.role == ComponentRole::Service);
        let has_repos = components
            .iter()
            .any(|c| c.role == ComponentRole::Repository);
        let has_models = components.iter().any(|c| c.role == ComponentRole::Model);

        // MVC: controllers + models + views
        if has_controllers && has_models && !has_repos {
            return ArchitecturePattern::MVC;
        }

        // Layered: clear layer separation
        if layers.len() >= 3 && has_controllers && has_services && has_repos {
            return ArchitecturePattern::Layered;
        }

        // Hexagonal: services + repositories with clear interfaces
        if has_services && has_repos && !has_controllers {
            return ArchitecturePattern::Hexagonal;
        }

        // If only utilities and entrypoints, likely monolith
        let non_utility = components
            .iter()
            .filter(|c| c.role != ComponentRole::Utility && c.role != ComponentRole::Test)
            .count();
        if non_utility <= 2 {
            return ArchitecturePattern::Monolith;
        }

        ArchitecturePattern::Unknown
    }

    fn detect_anomalies(
        &self,
        components: &[ArchitectureComponent],
        _pattern: &ArchitecturePattern,
    ) -> Vec<ArchitectureAnomaly> {
        let mut anomalies = Vec::new();

        // Check for bidirectional dependencies between layers (layer violation)
        let controller_ids: HashSet<u64> = components
            .iter()
            .filter(|c| c.role == ComponentRole::Controller)
            .flat_map(|c| c.node_ids.iter().copied())
            .collect();

        let repo_ids: HashSet<u64> = components
            .iter()
            .filter(|c| c.role == ComponentRole::Repository)
            .flat_map(|c| c.node_ids.iter().copied())
            .collect();

        // Repos should not call controllers
        for &repo_id in &repo_ids {
            for edge in self.graph.edges_from(repo_id) {
                if edge.edge_type == EdgeType::Calls && controller_ids.contains(&edge.target_id) {
                    anomalies.push(ArchitectureAnomaly {
                        description: "Repository layer calls presentation layer (layer violation)"
                            .to_string(),
                        node_id: repo_id,
                        expected: "Data Access should not depend on Presentation".to_string(),
                        actual: "Upward dependency detected".to_string(),
                        severity: AnomalySeverity::Error,
                    });
                }
            }
        }

        anomalies
    }

    fn compute_confidence(
        &self,
        components: &[ArchitectureComponent],
        layers: &[ArchitectureLayer],
    ) -> f64 {
        let total_units = self.graph.unit_count();
        if total_units == 0 {
            return 0.0;
        }

        let classified = components
            .iter()
            .filter(|c| c.role != ComponentRole::Utility)
            .map(|c| c.node_ids.len())
            .sum::<usize>();

        let classification_ratio = classified as f64 / total_units as f64;
        let layer_bonus = (layers.len() as f64 * 0.1).min(0.3);

        (classification_ratio * 0.7 + layer_bonus).min(1.0)
    }

    fn find_external_deps(&self, ids: &[u64]) -> Vec<String> {
        let id_set: HashSet<u64> = ids.iter().copied().collect();
        let mut external = HashSet::new();

        for &id in ids {
            for edge in self.graph.edges_from(id) {
                if edge.edge_type == EdgeType::Imports && !id_set.contains(&edge.target_id) {
                    if let Some(unit) = self.graph.get_unit(edge.target_id) {
                        external.insert(unit.qualified_name.clone());
                    }
                }
            }
        }

        external.into_iter().collect()
    }

    fn modules_for_role(
        &self,
        components: &[ArchitectureComponent],
        role: ComponentRole,
    ) -> Vec<String> {
        let mut modules = HashSet::new();
        for comp in components {
            if comp.role == role {
                for &id in &comp.node_ids {
                    if let Some(unit) = self.graph.get_unit(id) {
                        if let Some(last_sep) = unit
                            .qualified_name
                            .rfind("::")
                            .or_else(|| unit.qualified_name.rfind('.'))
                        {
                            modules.insert(unit.qualified_name[..last_sep].to_string());
                        }
                    }
                }
            }
        }
        modules.into_iter().collect()
    }

    fn matches_any(targets: &[&str], keywords: &[&str]) -> bool {
        targets
            .iter()
            .any(|t| keywords.iter().any(|k| t.contains(k)))
    }
}

// ── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{CodeUnit, CodeUnitType, Language, Span};
    use std::path::PathBuf;

    fn test_graph() -> CodeGraph {
        let mut graph = CodeGraph::with_default_dimension();
        graph.add_unit(CodeUnit::new(
            CodeUnitType::Function,
            Language::Python,
            "user_controller".to_string(),
            "app.controllers.user_controller".to_string(),
            PathBuf::from("src/controllers/user.py"),
            Span::new(1, 0, 30, 0),
        ));
        graph.add_unit(CodeUnit::new(
            CodeUnitType::Function,
            Language::Python,
            "user_service".to_string(),
            "app.services.user_service".to_string(),
            PathBuf::from("src/services/user.py"),
            Span::new(1, 0, 40, 0),
        ));
        graph.add_unit(CodeUnit::new(
            CodeUnitType::Function,
            Language::Python,
            "user_repository".to_string(),
            "app.repos.user_repository".to_string(),
            PathBuf::from("src/repos/user.py"),
            Span::new(1, 0, 25, 0),
        ));
        graph
    }

    #[test]
    fn infer_detects_components() {
        let graph = test_graph();
        let inferrer = ArchitectureInferrer::new(&graph);
        let arch = inferrer.infer();
        assert!(!arch.components.is_empty());
    }

    #[test]
    fn infer_detects_layered_pattern() {
        let graph = test_graph();
        let inferrer = ArchitectureInferrer::new(&graph);
        let arch = inferrer.infer();
        // Should detect layered or at least not Unknown
        assert!(arch.layers.len() >= 2);
    }

    #[test]
    fn diagram_produces_json() {
        let graph = test_graph();
        let inferrer = ArchitectureInferrer::new(&graph);
        let arch = inferrer.infer();
        let diagram = inferrer.diagram(&arch);
        assert!(diagram.get("pattern").is_some());
    }
}