cersei-tools 0.1.9

Tool trait, built-in tools, and permission system for the Cersei SDK
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
//! Code intelligence via tree-sitter: extract imports, symbols, and build dependency graphs.
//!
//! Supports: Rust, TypeScript/JavaScript, Python, Go.
//! Used to intelligently select which files to read for codebase analysis.

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use tree_sitter::{Parser, Query, QueryCursor};

/// A file's extracted metadata.
#[derive(Debug, Clone, Default)]
pub struct FileIntel {
    pub path: PathBuf,
    pub language: Language,
    pub imports: Vec<String>,
    pub symbols: Vec<Symbol>,
}

/// A symbol extracted from source code.
#[derive(Debug, Clone)]
pub struct Symbol {
    pub name: String,
    pub kind: SymbolKind,
    pub line: usize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SymbolKind {
    Function,
    Struct,
    Class,
    Interface,
    Enum,
    Module,
    Type,
    Constant,
}

impl SymbolKind {
    pub fn label(&self) -> &'static str {
        match self {
            Self::Function => "fn",
            Self::Struct => "struct",
            Self::Class => "class",
            Self::Interface => "interface",
            Self::Enum => "enum",
            Self::Module => "mod",
            Self::Type => "type",
            Self::Constant => "const",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Language {
    Rust,
    TypeScript,
    JavaScript,
    Python,
    Go,
    #[default]
    Unknown,
}

impl Language {
    pub fn from_extension(ext: &str) -> Self {
        match ext {
            "rs" => Self::Rust,
            "ts" | "tsx" => Self::TypeScript,
            "js" | "jsx" | "mjs" | "cjs" => Self::JavaScript,
            "py" | "pyi" => Self::Python,
            "go" => Self::Go,
            _ => Self::Unknown,
        }
    }
}

/// Extract imports and symbols from a source file.
pub fn analyze_file(path: &Path, source: &str) -> Option<FileIntel> {
    let ext = path.extension()?.to_str()?;
    let lang = Language::from_extension(ext);
    if lang == Language::Unknown {
        return None;
    }

    let mut parser = Parser::new();
    let ts_lang = match lang {
        Language::Rust => tree_sitter_rust::LANGUAGE.into(),
        Language::TypeScript | Language::JavaScript => {
            tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()
        }
        Language::Python => tree_sitter_python::LANGUAGE.into(),
        Language::Go => tree_sitter_go::LANGUAGE.into(),
        Language::Unknown => return None,
    };
    parser.set_language(&ts_lang).ok()?;
    let tree = parser.parse(source, None)?;
    let root = tree.root_node();
    let bytes = source.as_bytes();

    let mut imports = Vec::new();
    let mut symbols = Vec::new();

    // Walk AST and extract imports + symbols
    let mut stack = vec![root];
    while let Some(node) = stack.pop() {
        let kind = node.kind();

        match lang {
            Language::Rust => match kind {
                "use_declaration" => {
                    if let Ok(text) = node.utf8_text(bytes) {
                        imports.push(text.trim().to_string());
                    }
                }
                "function_item" => {
                    if let Some(name) = node.child_by_field_name("name") {
                        if let Ok(n) = name.utf8_text(bytes) {
                            symbols.push(Symbol {
                                name: n.to_string(),
                                kind: SymbolKind::Function,
                                line: node.start_position().row + 1,
                            });
                        }
                    }
                }
                "struct_item" => {
                    if let Some(name) = node.child_by_field_name("name") {
                        if let Ok(n) = name.utf8_text(bytes) {
                            symbols.push(Symbol {
                                name: n.to_string(),
                                kind: SymbolKind::Struct,
                                line: node.start_position().row + 1,
                            });
                        }
                    }
                }
                "enum_item" => {
                    if let Some(name) = node.child_by_field_name("name") {
                        if let Ok(n) = name.utf8_text(bytes) {
                            symbols.push(Symbol {
                                name: n.to_string(),
                                kind: SymbolKind::Enum,
                                line: node.start_position().row + 1,
                            });
                        }
                    }
                }
                "mod_item" => {
                    if let Some(name) = node.child_by_field_name("name") {
                        if let Ok(n) = name.utf8_text(bytes) {
                            symbols.push(Symbol {
                                name: n.to_string(),
                                kind: SymbolKind::Module,
                                line: node.start_position().row + 1,
                            });
                        }
                    }
                }
                "trait_item" => {
                    if let Some(name) = node.child_by_field_name("name") {
                        if let Ok(n) = name.utf8_text(bytes) {
                            symbols.push(Symbol {
                                name: n.to_string(),
                                kind: SymbolKind::Interface,
                                line: node.start_position().row + 1,
                            });
                        }
                    }
                }
                "type_item" => {
                    if let Some(name) = node.child_by_field_name("name") {
                        if let Ok(n) = name.utf8_text(bytes) {
                            symbols.push(Symbol {
                                name: n.to_string(),
                                kind: SymbolKind::Type,
                                line: node.start_position().row + 1,
                            });
                        }
                    }
                }
                _ => {}
            },
            Language::TypeScript | Language::JavaScript => match kind {
                "import_statement" => {
                    if let Some(source_node) = node.child_by_field_name("source") {
                        if let Ok(text) = source_node.utf8_text(bytes) {
                            imports.push(text.trim_matches(|c| c == '"' || c == '\'').to_string());
                        }
                    }
                }
                "function_declaration" => {
                    if let Some(name) = node.child_by_field_name("name") {
                        if let Ok(n) = name.utf8_text(bytes) {
                            symbols.push(Symbol {
                                name: n.to_string(),
                                kind: SymbolKind::Function,
                                line: node.start_position().row + 1,
                            });
                        }
                    }
                }
                "class_declaration" => {
                    if let Some(name) = node.child_by_field_name("name") {
                        if let Ok(n) = name.utf8_text(bytes) {
                            symbols.push(Symbol {
                                name: n.to_string(),
                                kind: SymbolKind::Class,
                                line: node.start_position().row + 1,
                            });
                        }
                    }
                }
                "interface_declaration" => {
                    if let Some(name) = node.child_by_field_name("name") {
                        if let Ok(n) = name.utf8_text(bytes) {
                            symbols.push(Symbol {
                                name: n.to_string(),
                                kind: SymbolKind::Interface,
                                line: node.start_position().row + 1,
                            });
                        }
                    }
                }
                "type_alias_declaration" => {
                    if let Some(name) = node.child_by_field_name("name") {
                        if let Ok(n) = name.utf8_text(bytes) {
                            symbols.push(Symbol {
                                name: n.to_string(),
                                kind: SymbolKind::Type,
                                line: node.start_position().row + 1,
                            });
                        }
                    }
                }
                "enum_declaration" => {
                    if let Some(name) = node.child_by_field_name("name") {
                        if let Ok(n) = name.utf8_text(bytes) {
                            symbols.push(Symbol {
                                name: n.to_string(),
                                kind: SymbolKind::Enum,
                                line: node.start_position().row + 1,
                            });
                        }
                    }
                }
                "export_statement" => {
                    // Also extract exported declarations
                    if let Some(decl) = node.child_by_field_name("declaration") {
                        stack.push(decl);
                    }
                }
                _ => {}
            },
            Language::Python => match kind {
                "import_statement" | "import_from_statement" => {
                    if let Ok(text) = node.utf8_text(bytes) {
                        imports.push(text.trim().to_string());
                    }
                }
                "function_definition" => {
                    if let Some(name) = node.child_by_field_name("name") {
                        if let Ok(n) = name.utf8_text(bytes) {
                            symbols.push(Symbol {
                                name: n.to_string(),
                                kind: SymbolKind::Function,
                                line: node.start_position().row + 1,
                            });
                        }
                    }
                }
                "class_definition" => {
                    if let Some(name) = node.child_by_field_name("name") {
                        if let Ok(n) = name.utf8_text(bytes) {
                            symbols.push(Symbol {
                                name: n.to_string(),
                                kind: SymbolKind::Class,
                                line: node.start_position().row + 1,
                            });
                        }
                    }
                }
                _ => {}
            },
            Language::Go => match kind {
                "import_declaration" => {
                    if let Ok(text) = node.utf8_text(bytes) {
                        imports.push(text.trim().to_string());
                    }
                }
                "function_declaration" => {
                    if let Some(name) = node.child_by_field_name("name") {
                        if let Ok(n) = name.utf8_text(bytes) {
                            symbols.push(Symbol {
                                name: n.to_string(),
                                kind: SymbolKind::Function,
                                line: node.start_position().row + 1,
                            });
                        }
                    }
                }
                "method_declaration" => {
                    if let Some(name) = node.child_by_field_name("name") {
                        if let Ok(n) = name.utf8_text(bytes) {
                            symbols.push(Symbol {
                                name: n.to_string(),
                                kind: SymbolKind::Function,
                                line: node.start_position().row + 1,
                            });
                        }
                    }
                }
                "type_declaration" => {
                    // Type declarations contain type_spec children
                }
                "type_spec" => {
                    if let Some(name) = node.child_by_field_name("name") {
                        if let Ok(n) = name.utf8_text(bytes) {
                            let sk = if node
                                .child_by_field_name("type")
                                .map(|t| t.kind() == "struct_type")
                                .unwrap_or(false)
                            {
                                SymbolKind::Struct
                            } else if node
                                .child_by_field_name("type")
                                .map(|t| t.kind() == "interface_type")
                                .unwrap_or(false)
                            {
                                SymbolKind::Interface
                            } else {
                                SymbolKind::Type
                            };
                            symbols.push(Symbol {
                                name: n.to_string(),
                                kind: sk,
                                line: node.start_position().row + 1,
                            });
                        }
                    }
                }
                _ => {}
            },
            Language::Unknown => {}
        }

        // Push children for traversal (only top-level for performance)
        if node.child_count() > 0 && is_container_node(kind) {
            for i in 0..node.child_count() {
                if let Some(child) = node.child(i) {
                    stack.push(child);
                }
            }
        }
    }

    Some(FileIntel {
        path: path.to_path_buf(),
        language: lang,
        imports,
        symbols,
    })
}

/// Only descend into container nodes (not function bodies, etc.)
fn is_container_node(kind: &str) -> bool {
    matches!(
        kind,
        "source_file"
            | "program"
            | "module"
            | "declaration_list"
            | "block"
            | "statement_block"
            | "export_statement"
            | "type_declaration"
            | "impl_item" // Rust impl blocks contain methods
    )
}

/// Scan a project directory and build a dependency-ordered list of important files.
/// Returns files sorted by importance: entry points first, then most-imported files.
pub fn scan_project(root: &Path, max_files: usize) -> Vec<FileIntel> {
    let files = discover_source_files(root, 200);
    if files.is_empty() {
        return vec![];
    }

    let mut intels: Vec<FileIntel> = Vec::new();
    let mut import_counts: HashMap<String, usize> = HashMap::new();

    for file_path in &files {
        if let Ok(source) = std::fs::read_to_string(file_path) {
            // Limit parsing to first 500 lines for performance
            let truncated: String = source.lines().take(500).collect::<Vec<_>>().join("\n");
            if let Some(intel) = analyze_file(file_path, &truncated) {
                // Count how often each file is imported
                for imp in &intel.imports {
                    *import_counts.entry(imp.clone()).or_insert(0) += 1;
                }
                intels.push(intel);
            }
        }
    }

    // Score files by importance
    let mut scored: Vec<(usize, &FileIntel)> = intels
        .iter()
        .map(|intel| {
            let mut score = 0usize;
            let path_str = intel.path.display().to_string();

            // Entry points get highest score
            let filename = intel
                .path
                .file_name()
                .and_then(|f| f.to_str())
                .unwrap_or("");
            if matches!(
                filename,
                "main.rs"
                    | "lib.rs"
                    | "mod.rs"
                    | "index.ts"
                    | "index.tsx"
                    | "App.tsx"
                    | "App.ts"
                    | "main.ts"
                    | "main.tsx"
                    | "main.py"
                    | "__init__.py"
                    | "main.go"
                    | "app.go"
            ) {
                score += 100;
            }

            // Config files
            if matches!(
                filename,
                "package.json"
                    | "Cargo.toml"
                    | "tsconfig.json"
                    | "pyproject.toml"
                    | "go.mod"
                    | "vite.config.ts"
            ) {
                score += 80;
            }

            // Store/state files (key architectural files)
            if path_str.contains("store")
                || path_str.contains("state")
                || path_str.contains("context")
                || path_str.contains("reducer")
            {
                score += 60;
            }

            // Type definition files
            if path_str.contains("types")
                || path_str.contains("interfaces")
                || filename.ends_with(".d.ts")
            {
                score += 40;
            }

            // Files that are imported by many others
            for imp in &intel.imports {
                if let Some(count) = import_counts.get(imp) {
                    score += count * 5;
                }
            }

            // Files with many symbols are more important
            score += intel.symbols.len() * 3;

            score
        })
        .enumerate()
        .map(|(i, score)| (score, &intels[i]))
        .collect();

    scored.sort_by(|a, b| b.0.cmp(&a.0));

    scored
        .into_iter()
        .take(max_files)
        .map(|(_, intel)| intel.clone())
        .collect()
}

/// Discover source files in a project (respects .gitignore via git ls-files).
fn discover_source_files(root: &Path, max: usize) -> Vec<PathBuf> {
    use std::process::Command;

    // Try git ls-files first
    let output = Command::new("git")
        .args(["ls-files", "--cached", "--others", "--exclude-standard"])
        .current_dir(root)
        .output()
        .ok();

    let files: Vec<PathBuf> = if let Some(out) = output {
        if out.status.success() {
            String::from_utf8_lossy(&out.stdout)
                .lines()
                .filter(|l| {
                    let ext = l.rsplit('.').next().unwrap_or("");
                    matches!(
                        ext,
                        "rs" | "ts" | "tsx" | "js" | "jsx" | "py" | "go" | "mjs" | "cjs" | "mts"
                    )
                })
                .take(max)
                .map(|l| root.join(l))
                .collect()
        } else {
            vec![]
        }
    } else {
        vec![]
    };

    if files.is_empty() {
        // Fallback: walkdir
        walkdir_source_files(root, max)
    } else {
        files
    }
}

fn walkdir_source_files(root: &Path, max: usize) -> Vec<PathBuf> {
    let excluded = [
        "node_modules",
        "target",
        ".git",
        "__pycache__",
        "venv",
        ".venv",
        "dist",
        "build",
    ];
    let mut files = Vec::new();

    fn walk(dir: &Path, excluded: &[&str], files: &mut Vec<PathBuf>, max: usize) {
        if files.len() >= max {
            return;
        }
        let entries = match std::fs::read_dir(dir) {
            Ok(e) => e,
            Err(_) => return,
        };
        for entry in entries.flatten() {
            if files.len() >= max {
                return;
            }
            let name = entry.file_name().to_string_lossy().to_string();
            if name.starts_with('.') || excluded.contains(&name.as_str()) {
                continue;
            }
            let path = entry.path();
            if path.is_file() {
                let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
                if matches!(ext, "rs" | "ts" | "tsx" | "js" | "jsx" | "py" | "go") {
                    files.push(path);
                }
            } else if path.is_dir() {
                walk(&path, excluded, files, max);
            }
        }
    }

    walk(root, &excluded, &mut files, max);
    files
}

/// Format a project scan as a concise summary for injection into the system prompt.
pub fn format_project_intel(intels: &[FileIntel]) -> String {
    let mut out = String::new();

    for intel in intels {
        let rel_path = intel
            .path
            .file_name()
            .and_then(|f| f.to_str())
            .unwrap_or("?");

        // Format: path (lang) — symbols: fn foo, struct Bar; imports: ...
        let symbols_str: Vec<String> = intel
            .symbols
            .iter()
            .take(8)
            .map(|s| format!("{} {}", s.kind.label(), s.name))
            .collect();

        let imports_str: Vec<String> = intel.imports.iter().take(5).cloned().collect();

        out.push_str(&format!("{}", intel.path.display()));
        if !symbols_str.is_empty() {
            out.push_str(&symbols_str.join(", "));
        }
        if !imports_str.is_empty() {
            if !symbols_str.is_empty() {
                out.push_str(" | imports: ");
            }
            out.push_str(&imports_str.join(", "));
        }
        out.push('\n');
    }

    out
}

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

    #[test]
    fn test_analyze_rust_file() {
        let source = r#"
use std::collections::HashMap;
use serde::Serialize;

pub struct Config {
    pub name: String,
}

pub fn load_config() -> Config {
    Config { name: "test".into() }
}

enum Mode { Fast, Slow }
"#;
        let intel = analyze_file(Path::new("test.rs"), source).unwrap();
        assert_eq!(intel.language, Language::Rust);
        assert!(intel.imports.len() >= 2);
        assert!(intel
            .symbols
            .iter()
            .any(|s| s.name == "Config" && s.kind == SymbolKind::Struct));
        assert!(intel
            .symbols
            .iter()
            .any(|s| s.name == "load_config" && s.kind == SymbolKind::Function));
    }

    #[test]
    fn test_analyze_typescript_file() {
        let source = r#"
import { useState } from "react";
import { create } from "zustand";

interface AppState {
    count: number;
}

function increment() {}

class App {}

export type Config = { name: string };
"#;
        let intel = analyze_file(Path::new("test.ts"), source).unwrap();
        assert_eq!(intel.language, Language::TypeScript);
        assert!(intel.imports.iter().any(|i| i.contains("react")));
        assert!(intel
            .symbols
            .iter()
            .any(|s| s.name == "AppState" && s.kind == SymbolKind::Interface));
        assert!(intel
            .symbols
            .iter()
            .any(|s| s.name == "increment" && s.kind == SymbolKind::Function));
    }

    #[test]
    fn test_analyze_python_file() {
        let source = r#"
import os
from pathlib import Path

class MyModel:
    pass

def train():
    pass
"#;
        let intel = analyze_file(Path::new("test.py"), source).unwrap();
        assert_eq!(intel.language, Language::Python);
        assert!(intel.imports.len() >= 2);
        assert!(intel
            .symbols
            .iter()
            .any(|s| s.name == "MyModel" && s.kind == SymbolKind::Class));
        assert!(intel
            .symbols
            .iter()
            .any(|s| s.name == "train" && s.kind == SymbolKind::Function));
    }

    #[test]
    fn test_language_detection() {
        assert_eq!(Language::from_extension("rs"), Language::Rust);
        assert_eq!(Language::from_extension("tsx"), Language::TypeScript);
        assert_eq!(Language::from_extension("py"), Language::Python);
        assert_eq!(Language::from_extension("go"), Language::Go);
        assert_eq!(Language::from_extension("md"), Language::Unknown);
    }
}