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
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
//! Cross-file symbol resolution.
//!
//! Builds a symbol table from raw code units and resolves references:
//! local names, imported symbols, and external library references.

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

use crate::parse::{RawCodeUnit, RawReference, ReferenceKind};
use crate::types::{AcbResult, CodeUnitType, Language};

/// A hierarchical symbol table for name resolution.
#[derive(Debug)]
pub struct SymbolTable {
    /// Qualified name → temp_id mapping.
    symbol_map: HashMap<String, u64>,
    /// Simple name → vec of temp_ids (handles overloading/shadowing).
    name_map: HashMap<String, Vec<u64>>,
    /// File path → vec of temp_ids.
    file_map: HashMap<String, Vec<u64>>,
    /// temp_id → qualified_name.
    id_to_qname: HashMap<u64, String>,
    /// Import target name → unit that imports it.
    import_targets: HashMap<String, Vec<u64>>,
}

impl SymbolTable {
    /// Create an empty symbol table.
    pub fn new() -> Self {
        Self {
            symbol_map: HashMap::new(),
            name_map: HashMap::new(),
            file_map: HashMap::new(),
            id_to_qname: HashMap::new(),
            import_targets: HashMap::new(),
        }
    }

    /// Build symbol table from raw units.
    pub fn build(units: &[RawCodeUnit]) -> AcbResult<Self> {
        let mut table = Self::new();

        for unit in units {
            // Register by qualified name
            table
                .symbol_map
                .insert(unit.qualified_name.clone(), unit.temp_id);
            table
                .id_to_qname
                .insert(unit.temp_id, unit.qualified_name.clone());

            // Register by simple name
            table
                .name_map
                .entry(unit.name.clone())
                .or_default()
                .push(unit.temp_id);

            // Register by file
            let file_key = unit.file_path.to_string_lossy().to_string();
            table
                .file_map
                .entry(file_key)
                .or_default()
                .push(unit.temp_id);

            // Track import targets
            if unit.unit_type == CodeUnitType::Import {
                for ref_info in &unit.references {
                    if ref_info.kind == ReferenceKind::Import {
                        table
                            .import_targets
                            .entry(ref_info.name.clone())
                            .or_default()
                            .push(unit.temp_id);
                    }
                }
            }
        }

        Ok(table)
    }

    /// Look up a unit by qualified name.
    pub fn lookup_qualified(&self, qname: &str) -> Option<u64> {
        self.symbol_map.get(qname).copied()
    }

    /// Look up units by simple name.
    pub fn lookup_name(&self, name: &str) -> &[u64] {
        self.name_map.get(name).map(|v| v.as_slice()).unwrap_or(&[])
    }

    /// Look up units in the same file.
    pub fn units_in_file(&self, file_path: &str) -> &[u64] {
        self.file_map
            .get(file_path)
            .map(|v| v.as_slice())
            .unwrap_or(&[])
    }

    /// Get the qualified name for a temp_id.
    pub fn qname_for_id(&self, id: u64) -> Option<&str> {
        self.id_to_qname.get(&id).map(|s| s.as_str())
    }

    /// Get all symbol entries.
    pub fn all_symbols(&self) -> &HashMap<String, u64> {
        &self.symbol_map
    }

    /// Number of symbols.
    pub fn len(&self) -> usize {
        self.symbol_map.len()
    }

    /// Check if empty.
    pub fn is_empty(&self) -> bool {
        self.symbol_map.is_empty()
    }
}

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

/// Resolves references from raw units to concrete targets.
pub struct Resolver {
    /// Known external libraries.
    external_libs: HashMap<String, ExternalLibrary>,
}

/// An external library with known symbols.
#[derive(Debug)]
pub struct ExternalLibrary {
    /// Library name.
    pub name: String,
    /// Language.
    pub language: Language,
    /// Known exported symbols.
    pub known_symbols: HashSet<String>,
    /// Is this a standard library?
    pub is_stdlib: bool,
}

impl Resolver {
    /// Create a new resolver with standard library knowledge.
    pub fn new() -> Self {
        let mut resolver = Self {
            external_libs: HashMap::new(),
        };
        resolver.register_python_stdlib();
        resolver.register_rust_stdlib();
        resolver.register_node_builtins();
        resolver.register_go_stdlib();
        resolver
    }

    /// Resolve all references in the raw units.
    pub fn resolve_all(
        &self,
        units: &[RawCodeUnit],
        symbol_table: &SymbolTable,
    ) -> AcbResult<Vec<ResolvedUnit>> {
        let mut resolved = Vec::with_capacity(units.len());

        for unit in units {
            let resolved_refs = self.resolve_unit_references(unit, units, symbol_table)?;
            resolved.push(ResolvedUnit {
                unit: unit.clone(),
                resolved_refs,
            });
        }

        Ok(resolved)
    }

    fn resolve_unit_references(
        &self,
        unit: &RawCodeUnit,
        all_units: &[RawCodeUnit],
        symbol_table: &SymbolTable,
    ) -> AcbResult<Vec<ResolvedReference>> {
        let mut resolved = Vec::new();

        for raw_ref in &unit.references {
            let resolution = self.resolve_reference(raw_ref, unit, all_units, symbol_table);
            resolved.push(ResolvedReference {
                raw: raw_ref.clone(),
                resolution,
            });
        }

        Ok(resolved)
    }

    fn resolve_reference(
        &self,
        raw_ref: &RawReference,
        unit: &RawCodeUnit,
        all_units: &[RawCodeUnit],
        symbol_table: &SymbolTable,
    ) -> Resolution {
        // Strategy 1: Try exact qualified name match
        if let Some(target_id) = symbol_table.lookup_qualified(&raw_ref.name) {
            if target_id != unit.temp_id {
                return Resolution::Local(target_id);
            }
        }

        // Strategy 2: Try local resolution (same file, then by simple name)
        if let Some(local_id) = self.resolve_local(&raw_ref.name, unit, all_units, symbol_table) {
            return Resolution::Local(local_id);
        }

        // Strategy 3: Try imported symbol resolution
        if let Some(imported) = self.resolve_imported(&raw_ref.name, unit, all_units, symbol_table)
        {
            return Resolution::Imported(imported);
        }

        // Strategy 4: Try external library match
        if let Some(external) = self.resolve_external(&raw_ref.name, unit.language) {
            return Resolution::External(external);
        }

        Resolution::Unresolved
    }

    fn resolve_local(
        &self,
        name: &str,
        unit: &RawCodeUnit,
        _all_units: &[RawCodeUnit],
        symbol_table: &SymbolTable,
    ) -> Option<u64> {
        let file_key = unit.file_path.to_string_lossy().to_string();
        let file_units = symbol_table.units_in_file(&file_key);

        // Look for a matching name in the same file
        for &id in file_units {
            if id == unit.temp_id {
                continue;
            }
            if let Some(qname) = symbol_table.qname_for_id(id) {
                // Match on the simple name part of the qname
                let simple = qname.rsplit('.').next().unwrap_or(qname);
                let simple2 = qname.rsplit("::").next().unwrap_or(qname);
                if simple == name || simple2 == name || qname == name {
                    return Some(id);
                }
            }
        }

        // Also look globally by simple name
        let candidates = symbol_table.lookup_name(name);
        candidates.iter().find(|&&cid| cid != unit.temp_id).copied()
    }

    fn resolve_imported(
        &self,
        name: &str,
        unit: &RawCodeUnit,
        all_units: &[RawCodeUnit],
        symbol_table: &SymbolTable,
    ) -> Option<ImportedSymbol> {
        // Check if any import in the same file matches this name
        let file_key = unit.file_path.to_string_lossy().to_string();
        let file_unit_ids = symbol_table.units_in_file(&file_key);

        for &fid in file_unit_ids {
            // Find the unit for this ID
            if let Some(file_unit) = all_units.iter().find(|u| u.temp_id == fid) {
                if file_unit.unit_type == CodeUnitType::Import {
                    // Check if this import's name matches the reference
                    let import_name = &file_unit.name;
                    if import_name.contains(name)
                        || name.contains(import_name.rsplit('/').next().unwrap_or(import_name))
                    {
                        return Some(ImportedSymbol {
                            unit_id: fid,
                            import_path: import_name.clone(),
                        });
                    }
                }
            }
        }

        None
    }

    fn resolve_external(&self, name: &str, language: Language) -> Option<ExternalSymbol> {
        for lib in self.external_libs.values() {
            if lib.language == language && lib.known_symbols.contains(name) {
                return Some(ExternalSymbol {
                    library: lib.name.clone(),
                    symbol: name.to_string(),
                    is_stdlib: lib.is_stdlib,
                });
            }
        }
        None
    }

    fn register_python_stdlib(&mut self) {
        let symbols: HashSet<String> = [
            "print",
            "len",
            "range",
            "int",
            "str",
            "float",
            "bool",
            "list",
            "dict",
            "set",
            "tuple",
            "type",
            "isinstance",
            "issubclass",
            "hasattr",
            "getattr",
            "setattr",
            "delattr",
            "super",
            "object",
            "open",
            "input",
            "sorted",
            "reversed",
            "enumerate",
            "zip",
            "map",
            "filter",
            "any",
            "all",
            "min",
            "max",
            "sum",
            "abs",
            "round",
            "format",
            "repr",
            "id",
            "hash",
            "iter",
            "next",
            "Exception",
            "ValueError",
            "TypeError",
            "KeyError",
            "IndexError",
            "AttributeError",
            "RuntimeError",
            "StopIteration",
            "OSError",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();

        self.external_libs.insert(
            "python_stdlib".to_string(),
            ExternalLibrary {
                name: "python_stdlib".to_string(),
                language: Language::Python,
                known_symbols: symbols,
                is_stdlib: true,
            },
        );
    }

    fn register_rust_stdlib(&mut self) {
        let symbols: HashSet<String> = [
            "println",
            "eprintln",
            "format",
            "vec",
            "String",
            "Vec",
            "HashMap",
            "HashSet",
            "BTreeMap",
            "BTreeSet",
            "Option",
            "Result",
            "Ok",
            "Err",
            "Some",
            "None",
            "Box",
            "Rc",
            "Arc",
            "RefCell",
            "Mutex",
            "RwLock",
            "Clone",
            "Debug",
            "Display",
            "Default",
            "Iterator",
            "IntoIterator",
            "From",
            "Into",
            "TryFrom",
            "TryInto",
            "AsRef",
            "AsMut",
            "Drop",
            "Fn",
            "FnMut",
            "FnOnce",
            "Send",
            "Sync",
            "Sized",
            "Unpin",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();

        self.external_libs.insert(
            "rust_stdlib".to_string(),
            ExternalLibrary {
                name: "rust_stdlib".to_string(),
                language: Language::Rust,
                known_symbols: symbols,
                is_stdlib: true,
            },
        );
    }

    fn register_node_builtins(&mut self) {
        let symbols: HashSet<String> = [
            "console",
            "setTimeout",
            "setInterval",
            "clearTimeout",
            "clearInterval",
            "Promise",
            "fetch",
            "JSON",
            "Math",
            "Date",
            "RegExp",
            "Error",
            "TypeError",
            "RangeError",
            "Array",
            "Object",
            "Map",
            "Set",
            "WeakMap",
            "WeakSet",
            "Symbol",
            "Proxy",
            "Reflect",
            "require",
            "module",
            "exports",
            "process",
            "Buffer",
            "__dirname",
            "__filename",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();

        self.external_libs.insert(
            "node_builtins".to_string(),
            ExternalLibrary {
                name: "node_builtins".to_string(),
                language: Language::JavaScript,
                known_symbols: symbols.clone(),
                is_stdlib: true,
            },
        );

        self.external_libs.insert(
            "ts_builtins".to_string(),
            ExternalLibrary {
                name: "ts_builtins".to_string(),
                language: Language::TypeScript,
                known_symbols: symbols,
                is_stdlib: true,
            },
        );
    }

    fn register_go_stdlib(&mut self) {
        let symbols: HashSet<String> = [
            "fmt", "os", "io", "strings", "strconv", "errors", "context", "sync", "time", "net",
            "http", "json", "log", "testing", "reflect", "sort", "math", "crypto", "path",
            "filepath", "bytes", "bufio", "regexp",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();

        self.external_libs.insert(
            "go_stdlib".to_string(),
            ExternalLibrary {
                name: "go_stdlib".to_string(),
                language: Language::Go,
                known_symbols: symbols,
                is_stdlib: true,
            },
        );
    }
}

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

/// A raw unit with its resolved references.
#[derive(Debug, Clone)]
pub struct ResolvedUnit {
    /// The original raw code unit.
    pub unit: RawCodeUnit,
    /// Resolved references.
    pub resolved_refs: Vec<ResolvedReference>,
}

/// A resolved reference.
#[derive(Debug, Clone)]
pub struct ResolvedReference {
    /// The original raw reference.
    pub raw: RawReference,
    /// Resolution result.
    pub resolution: Resolution,
}

/// Result of resolving a reference.
#[derive(Debug, Clone)]
pub enum Resolution {
    /// Resolved to a local unit by temp_id.
    Local(u64),
    /// Resolved to an imported unit.
    Imported(ImportedSymbol),
    /// Resolved to an external library.
    External(ExternalSymbol),
    /// Could not resolve.
    Unresolved,
}

/// A symbol resolved through an import.
#[derive(Debug, Clone)]
pub struct ImportedSymbol {
    /// The import unit temp_id.
    pub unit_id: u64,
    /// The import path string.
    pub import_path: String,
}

/// A symbol from an external library.
#[derive(Debug, Clone)]
pub struct ExternalSymbol {
    /// Library name.
    pub library: String,
    /// Symbol name.
    pub symbol: String,
    /// Is from standard library.
    pub is_stdlib: bool,
}