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//! | [`embedding`] | Deterministic code chunks for vector databases |
110//! | [`error`] | Unified error types |
111
112// Core modules
113pub mod chunking;
114pub mod constants;
115pub mod content_processing;
116pub mod content_transformation;
117pub mod default_ignores;
118pub mod filtering;
119pub mod newtypes;
120pub mod output;
121pub mod parser;
122pub mod ranking;
123pub mod repomap;
124pub mod scanner;
125pub mod security;
126pub mod types;
127
128// New modules
129pub mod config;
130pub mod dependencies;
131pub mod git;
132pub mod remote;
133pub mod tokenizer;
134
135// Git context index module
136pub mod index;
137
138// Memory-mapped file scanner for large files
139pub mod mmap_scanner;
140
141// Semantic analysis module (always available, embeddings feature enables neural compression)
142pub mod semantic;
143
144// Smart token budget enforcement
145pub mod budget;
146
147// Incremental scanning and caching
148pub mod incremental;
149
150// Safe bincode deserialization with size limits
151pub mod bincode_safe;
152
153// Unified error types
154pub mod error;
155
156// Embedding chunk generation for vector databases
157pub mod embedding;
158
159// Audit logging for SOC2/GDPR/HIPAA compliance
160pub mod audit;
161
162// Semantic exit codes for CI/CD integration
163pub mod exit_codes;
164
165// License detection for compliance scanning
166pub mod license;
167
168// Re-exports from core modules
169pub use chunking::{Chunk, ChunkStrategy, Chunker};
170pub use constants::{
171    budget as budget_constants, compression as compression_constants, files as file_constants,
172    index as index_constants, pagerank as pagerank_constants, parser as parser_constants,
173    repomap as repomap_constants, security as security_constants, timeouts as timeout_constants,
174};
175pub use content_transformation::{
176    extract_key_symbols, extract_key_symbols_with_context, extract_signatures, remove_comments,
177    remove_empty_lines,
178};
179pub use filtering::{
180    apply_exclude_patterns, apply_include_patterns, compile_patterns, matches_exclude_pattern,
181    matches_include_pattern,
182};
183pub use newtypes::{ByteOffset, FileSize, ImportanceScore, LineNumber, SymbolId, TokenCount};
184pub use output::{OutputFormat, OutputFormatter};
185pub use parser::{
186    detect_file_language, parse_file_symbols, parse_with_language, Language, Parser, ParserError,
187};
188pub use ranking::{count_symbol_references, rank_files, sort_files_by_importance, SymbolRanker};
189pub use repomap::{RepoMap, RepoMapGenerator};
190pub use security::SecurityScanner;
191pub use types::*;
192
193// Re-exports from new modules
194pub use budget::{BudgetConfig, BudgetEnforcer, EnforcementResult, TruncationStrategy};
195pub use config::{
196    Config, OutputConfig, PerformanceConfig, ScanConfig, SecurityConfig, SymbolConfig,
197};
198pub use dependencies::{DependencyEdge, DependencyGraph, DependencyNode, ResolvedImport};
199pub use git::{ChangedFile, Commit, FileStatus, GitError, GitRepo};
200pub use incremental::{CacheError, CacheStats, CachedFile, CachedSymbol, RepoCache};
201pub use mmap_scanner::{MappedFile, MmapScanner, ScanStats, ScannedFile, StreamingProcessor};
202pub use remote::{GitProvider, RemoteError, RemoteRepo};
203pub use semantic::{
204    CodeChunk,
205    HeuristicCompressionConfig,
206    // Note: SemanticAnalyzer and CharacterFrequencyAnalyzer are available via semantic:: module
207    // but not re-exported at top level since they're primarily internal implementation details
208    // Honest type aliases - recommended for new code
209    HeuristicCompressor,
210    SemanticCompressor,
211    SemanticConfig,
212    SemanticError,
213};
214/// Backward-compatible alias for TokenCounts
215pub use tokenizer::TokenCounts as AccurateTokenCounts;
216pub use tokenizer::Tokenizer;
217// Note: IncrementalScanner is available via incremental:: module but not re-exported
218// at top level since CLI uses RepoCache directly
219pub use error::{InfiniloomError, Result as InfiniloomResult};
220pub use embedding::{
221    // Core types
222    EmbedChunk, EmbedChunker, EmbedSettings, ChunkKind, ChunkSource, ChunkContext, ChunkPart,
223    Visibility as EmbedVisibility,
224    // Manifest and diffing
225    EmbedManifest, EmbedDiff, DiffSummary, DiffBatch, BatchOperation, ManifestEntry,
226    ModifiedChunk, RemovedChunk, MANIFEST_VERSION,
227    // Error and limits
228    EmbedError, ResourceLimits,
229    // Hashing
230    hash_content, HashResult,
231    // Normalization
232    normalize_for_hash, needs_normalization,
233    // Progress reporting
234    ProgressReporter, QuietProgress, TerminalProgress,
235    // Repository identifier
236    RepoIdentifier,
237    // Hierarchical chunking
238    HierarchyBuilder, HierarchyConfig, HierarchySummary, ChildReference,
239    get_hierarchy_summary,
240    // Streaming API
241    ChunkStream, StreamConfig, StreamStats, CancellationHandle,
242    BatchIterator, Batches,
243};
244pub use audit::{
245    // Core types
246    AuditEvent, AuditEventKind, AuditSeverity, AuditLogger,
247    // Logger implementations
248    FileAuditLogger, MemoryAuditLogger, NullAuditLogger, MultiAuditLogger,
249    // Global logger functions
250    set_global_logger, get_global_logger, log_event,
251    // Convenience functions
252    log_scan_started, log_scan_completed, log_secret_detected, log_pii_detected,
253};
254pub use exit_codes::{
255    // Core types
256    ExitCode, ExitCodeCategory, ExitResult,
257    // Trait for error conversion
258    ToExitCode,
259};
260pub use license::{
261    // Core types
262    License, LicenseRisk, LicenseFinding, LicenseScanConfig, LicenseScanner, LicenseSummary,
263};
264
265/// Library version
266pub const VERSION: &str = env!("CARGO_PKG_VERSION");
267
268/// Default token budget for repository maps
269pub const DEFAULT_MAP_BUDGET: u32 = budget_constants::DEFAULT_MAP_BUDGET;
270
271/// Default chunk size in tokens
272pub const DEFAULT_CHUNK_SIZE: u32 = budget_constants::DEFAULT_CHUNK_SIZE;
273
274#[cfg(test)]
275mod tests {
276    use super::*;
277
278    #[test]
279    fn test_version() {
280        // Verify version follows semver format (at least has a number)
281        assert!(VERSION.chars().any(|c| c.is_ascii_digit()));
282    }
283}