infiniloom_engine/
lib.rs

1//! # Infiniloom Engine - Repository Context Generation for LLMs
2//!
3//! `infiniloom_engine` is a high-performance library for generating optimized
4//! repository context for Large Language Models. It transforms codebases into
5//! structured formats optimized for Claude, GPT-4, Gemini, and other LLMs.
6//!
7//! ## Features
8//!
9//! - **AST-based symbol extraction** via Tree-sitter (21 programming languages)
10//! - **PageRank-based importance ranking** for intelligent code prioritization
11//! - **Model-specific output formats** (XML for Claude, Markdown for GPT, YAML for Gemini)
12//! - **Automatic secret detection** and redaction (API keys, credentials, tokens)
13//! - **Accurate token counting** using tiktoken-rs for OpenAI models (~95% accuracy)
14//! - **Full dependency resolution** with transitive dependency analysis
15//! - **Remote Git repository support** (GitHub, GitLab, Bitbucket)
16//! - **Incremental scanning** with content-addressed caching
17//! - **Semantic compression** for intelligent code summarization
18//! - **Token budget enforcement** with smart truncation strategies
19//!
20//! ## Quick Start
21//!
22//! ```rust,ignore
23//! use infiniloom_engine::{Repository, RepoMapGenerator, OutputFormatter, OutputFormat};
24//!
25//! // Create a repository from scanned files
26//! let repo = Repository::new("my-project", "/path/to/project");
27//!
28//! // Generate a repository map with key symbols ranked by importance
29//! let map = RepoMapGenerator::new(2000).generate(&repo);
30//!
31//! // Format for Claude (XML output)
32//! let formatter = OutputFormatter::by_format(OutputFormat::Xml);
33//! let output = formatter.format(&repo, &map);
34//! ```
35//!
36//! ## Output Formats
37//!
38//! Each LLM has an optimal input format:
39//!
40//! | Format | Best For | Notes |
41//! |--------|----------|-------|
42//! | XML | Claude | Optimized structure, CDATA sections |
43//! | Markdown | GPT-4 | Fenced code blocks with syntax highlighting |
44//! | YAML | Gemini | Query at end (Gemini best practice) |
45//! | TOON | All | Token-efficient, 30-40% fewer tokens |
46//! | JSON | APIs | Machine-readable, fully structured |
47//!
48//! ## Token Counting
49//!
50//! The library provides accurate token counts for multiple LLM families:
51//!
52//! ```rust,ignore
53//! use infiniloom_engine::{Tokenizer, TokenModel};
54//!
55//! let tokenizer = Tokenizer::new();
56//! let content = "fn main() { println!(\"Hello\"); }";
57//!
58//! // Exact counts via tiktoken for OpenAI models
59//! let gpt4o_tokens = tokenizer.count(content, TokenModel::Gpt4o);
60//!
61//! // Calibrated estimation for other models
62//! let claude_tokens = tokenizer.count(content, TokenModel::Claude);
63//! ```
64//!
65//! ## Security Scanning
66//!
67//! Automatically detect and redact sensitive information:
68//!
69//! ```rust,ignore
70//! use infiniloom_engine::SecurityScanner;
71//!
72//! let scanner = SecurityScanner::new();
73//! let content = "AWS_KEY=AKIAIOSFODNN7EXAMPLE";
74//!
75//! // Check if content is safe
76//! if !scanner.is_safe(content, "config.env") {
77//!     // Redact sensitive content
78//!     let redacted = scanner.redact_content(content, "config.env");
79//! }
80//! ```
81//!
82//! ## Feature Flags
83//!
84//! Enable optional functionality:
85//!
86//! - `async` - Async/await support with Tokio
87//! - `embeddings` - Character-frequency similarity (NOT neural - see semantic module docs)
88//! - `watch` - File watching for incremental updates
89//! - `full` - All features enabled
90//!
91//! Note: Git operations use the system `git` CLI via `std::process::Command`.
92//!
93//! ## Module Overview
94//!
95//! | Module | Description |
96//! |--------|-------------|
97//! | [`parser`] | AST-based symbol extraction using Tree-sitter |
98//! | [`repomap`] | PageRank-based symbol importance ranking |
99//! | [`output`] | Model-specific formatters (XML, Markdown, etc.) |
100//! | [`content_processing`] | Content transformation utilities (base64 truncation) |
101//! | [`content_transformation`] | Code compression (comment removal, signature extraction) |
102//! | [`filtering`] | Centralized file filtering and pattern matching |
103//! | [`security`] | Secret detection and redaction |
104//! | [`tokenizer`] | Multi-model token counting |
105//! | [`chunking`] | Semantic code chunking |
106//! | [`budget`] | Token budget enforcement |
107//! | [`incremental`] | Caching and incremental scanning |
108//! | [`semantic`] | Heuristic-based compression (char-frequency, NOT neural) |
109//! | [`error`] | Unified error types |
110
111// Core modules
112pub mod chunking;
113pub mod constants;
114pub mod content_processing;
115pub mod content_transformation;
116pub mod default_ignores;
117pub mod filtering;
118pub mod newtypes;
119pub mod output;
120pub mod parser;
121pub mod ranking;
122pub mod repomap;
123pub mod scanner;
124pub mod security;
125pub mod types;
126
127// New modules
128pub mod config;
129pub mod dependencies;
130pub mod git;
131pub mod remote;
132pub mod tokenizer;
133
134// Git context index module
135pub mod index;
136
137// Memory-mapped file scanner for large files
138pub mod mmap_scanner;
139
140// Semantic analysis module (always available, embeddings feature enables neural compression)
141pub mod semantic;
142
143// Smart token budget enforcement
144pub mod budget;
145
146// Incremental scanning and caching
147pub mod incremental;
148
149// Unified error types
150pub mod error;
151
152// Re-exports from core modules
153pub use chunking::{Chunk, ChunkStrategy, Chunker};
154pub use constants::{
155    budget as budget_constants, compression as compression_constants, files as file_constants,
156    index as index_constants, pagerank as pagerank_constants, parser as parser_constants,
157    repomap as repomap_constants, security as security_constants, timeouts as timeout_constants,
158};
159pub use content_transformation::{
160    extract_key_symbols, extract_key_symbols_with_context, extract_signatures, remove_comments,
161    remove_empty_lines,
162};
163pub use filtering::{
164    apply_exclude_patterns, apply_include_patterns, compile_patterns, matches_exclude_pattern,
165    matches_include_pattern,
166};
167pub use newtypes::{ByteOffset, FileSize, ImportanceScore, LineNumber, SymbolId, TokenCount};
168pub use output::{OutputFormat, OutputFormatter};
169pub use parser::{
170    detect_file_language, parse_file_symbols, parse_with_language, Language, Parser, ParserError,
171};
172pub use ranking::{count_symbol_references, rank_files, sort_files_by_importance, SymbolRanker};
173pub use repomap::{RepoMap, RepoMapGenerator};
174pub use security::SecurityScanner;
175pub use types::*;
176
177// Re-exports from new modules
178pub use budget::{BudgetConfig, BudgetEnforcer, EnforcementResult, TruncationStrategy};
179pub use config::{
180    Config, OutputConfig, PerformanceConfig, ScanConfig, SecurityConfig, SymbolConfig,
181};
182pub use dependencies::{DependencyEdge, DependencyGraph, DependencyNode, ResolvedImport};
183pub use git::{ChangedFile, Commit, FileStatus, GitError, GitRepo};
184pub use incremental::{CacheError, CacheStats, CachedFile, CachedSymbol, RepoCache};
185pub use mmap_scanner::{MappedFile, MmapScanner, ScanStats, ScannedFile, StreamingProcessor};
186pub use remote::{GitProvider, RemoteError, RemoteRepo};
187pub use semantic::{
188    CodeChunk,
189    HeuristicCompressionConfig,
190    // Note: SemanticAnalyzer and CharacterFrequencyAnalyzer are available via semantic:: module
191    // but not re-exported at top level since they're primarily internal implementation details
192    // Honest type aliases - recommended for new code
193    HeuristicCompressor,
194    SemanticCompressor,
195    SemanticConfig,
196    SemanticError,
197};
198/// Backward-compatible alias for TokenCounts
199pub use tokenizer::TokenCounts as AccurateTokenCounts;
200pub use tokenizer::Tokenizer;
201// Note: IncrementalScanner is available via incremental:: module but not re-exported
202// at top level since CLI uses RepoCache directly
203pub use error::{InfiniloomError, Result as InfiniloomResult};
204
205/// Library version
206pub const VERSION: &str = env!("CARGO_PKG_VERSION");
207
208/// Default token budget for repository maps
209pub const DEFAULT_MAP_BUDGET: u32 = budget_constants::DEFAULT_MAP_BUDGET;
210
211/// Default chunk size in tokens
212pub const DEFAULT_CHUNK_SIZE: u32 = budget_constants::DEFAULT_CHUNK_SIZE;
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217
218    #[test]
219    fn test_version() {
220        // Verify version follows semver format (at least has a number)
221        assert!(VERSION.chars().any(|c| c.is_ascii_digit()));
222    }
223}