Rust based smart code reader for AI agents - Strip implementation, keep structure
Skim transforms source code by removing implementation details while preserving structure, signatures, and types. Built with tree-sitter for fast, accurate multi-language parsing.
Take a typical 80-file TypeScript project: 63,000 tokens. Modern LLMs handle 200k+ context, so capacity isn't the issue.
But context capacity isn't the bottleneck β attention is. That 63k contains maybe 5k of actual signal. The rest? Implementation noise: loop bodies, error handlers, validation chains the model doesn't need to reason about architecture.
Large contexts degrade model performance. Research consistently shows attention dilution in long contexts β models lose track of critical details even within their window. More tokens means higher latency, degraded recall, and weaker reasoning. The inverse scaling problem: past a threshold, adding context makes outputs worse.
80% of the time, the model doesn't need implementation details. It doesn't care how you loop through users or validate emails. It needs to understand what your code does and how pieces connect.
That's where Skim comes in.
| Mode | Tokens | Reduction | Use Case |
|---|---|---|---|
| Full | 63,198 | 0% | Original source code |
| Structure | 25,119 | 60.3% | Understanding architecture |
| Signatures | 7,328 | 88.4% | API documentation |
| Types | 5,181 | 91.8% | Type system analysis |
For example:
// Before: Full implementation (100 tokens)
export function processUser(user: User): Result {
const validated = validateUser(user);
if (!validated) throw new Error("Invalid");
const normalized = normalizeData(user);
return await saveToDatabase(normalized);
}
// After: Structure only (12 tokens)
export function processUser(user: User): Result { /* ... */ }One command. 60-90% smaller. Your 63,000-token codebase? Now 5,000 tokens. Fits comfortably in a single prompt with room for your question.
That same 80-file project that wouldn't fit? Now you can ask: "Explain the entire authentication flow" or "How do these services interact?" β and the AI actually has enough context to answer.
- π Fast - 14.6ms for 3000-line files (powered by tree-sitter)
- β‘ Cached - 40-50x faster on repeated processing (enabled by default)
- π Multi-language - TypeScript, JavaScript, Python, Rust, Go, Java, Markdown, JSON, YAML
- π― Multiple modes - Structure, signatures, types, or full code
- π Directory support - Process entire directories recursively (
skim src/) - π Multi-file - Glob patterns (
src/**/*.ts) with parallel processing - π€ Auto-detection - Automatically detects language from file extension
- π DoS-resistant - Built-in limits prevent stack overflow and memory exhaustion
- π§ Streaming - Outputs to stdout for pipe workflows
npx rskim file.ts# Via npm
npm install -g rskim
# Via Cargo
cargo install rskimNote: Use
npxfor trying it out. For regular use, install globally to avoid npx overhead (~100-500ms per invocation).
git clone https://github.com/dean0x/skim.git
cd skim
cargo build --release
# Binary at target/release/skim# Try it with npx (no install)
npx rskim src/app.ts
# Or install globally for better performance
npm install -g rskim
# Extract structure from single file (auto-detects language)
skim src/app.ts
# Process entire directory recursively (auto-detects all languages)
skim src/
# Process current directory
skim .
# Process multiple files with glob patterns
skim 'src/**/*.ts'
# Process all TypeScript files with custom parallelism
skim '*.{js,ts}' --jobs 4
# Get only function signatures from multiple files
skim 'src/*.ts' --mode signatures --no-header
# Extract type definitions
skim src/types.ts --mode types
# Extract markdown headers (H1-H3 for structure, H1-H6 for signatures/types)
skim README.md --mode structure
# Pipe to other tools
skim src/app.ts | bat -l typescript
# Read from stdin (REQUIRES --language flag)
cat app.ts | skim - --language=typescript
# Override language detection for unusual file extensions
skim weird.inc --language=typescript
# Clear cache
skim --clear-cache
# Disable caching for pure transformation
skim file.ts --no-cache
# Show token reduction statistics
skim file.ts --show-stats# Basic usage (auto-detects language)
skim file.ts # Single file
skim src/ # Directory (recursive)
skim 'src/**/*.ts' # Glob pattern
# With options
skim file.ts --mode signatures # Different mode
skim src/ --jobs 8 # Parallel processing
skim - --language typescript # Stdin (requires --language)Common options:
-m, --mode- Transformation mode:structure(default),signatures,types,full-l, --language- Override auto-detection (required for stdin only)-j, --jobs- Parallel processing threads (default: CPU cores)--no-cache- Disable caching--show-stats- Show token reduction stats
π Full Usage Guide β
Skim offers four modes with different levels of aggressiveness:
| Mode | Reduction | What's Kept | Use Case |
|---|---|---|---|
| Structure | 70-80% | Signatures, types, classes, imports | Understanding architecture |
| Signatures | 85-92% | Only callable signatures | API documentation |
| Types | 90-95% | Only type definitions | Type system analysis |
| Full | 0% | Everything (original source) | Testing/comparison |
skim file.ts --mode structure # Default
skim file.ts --mode signatures # More aggressive
skim file.ts --mode types # Most aggressive
skim file.ts --mode full # No transformationNote on JSON/YAML files: JSON and YAML always use structure extraction regardless of mode. Since they are data (not code), there are no "signatures" or "types" to extractβonly structure. All modes produce identical output for JSON and YAML files.
| Language | Status | Extensions | Notes |
|---|---|---|---|
| TypeScript | β | .ts, .tsx |
Excellent grammar |
| JavaScript | β | .js, .jsx |
Full ES2024 support |
| Python | β | .py, .pyi |
Complete coverage |
| Rust | β | .rs |
Up-to-date grammar |
| Go | β | .go |
Stable |
| Java | β | .java |
Good coverage |
| Markdown | β | .md, .markdown |
Header extraction |
| JSON | β | .json |
Structure extraction (serde) |
| YAML | β | .yaml, .yml |
Multi-document support (serde) |
// Input
class UserService {
async findUser(id: string): Promise<User> {
const user = await db.users.findOne({ id });
if (!user) throw new NotFoundError();
return user;
}
}
// Output (structure mode)
class UserService {
async findUser(id: string): Promise<User> { /* ... */ }
}# Input
def process_data(items: List[Item]) -> Dict[str, Any]:
"""Process items and return statistics"""
results = {}
for item in items:
results[item.id] = calculate_metrics(item)
return results
# Output (structure mode)
def process_data(items: List[Item]) -> Dict[str, Any]: { /* ... */ }// Input
{
"user": {
"profile": {
"name": "Jane Smith",
"age": 28,
"tags": ["admin", "verified"]
},
"settings": {
"theme": "dark",
"notifications": true
}
},
"items": [
{"id": 1, "price": 100},
{"id": 2, "price": 200}
]
}
// Output (structure mode)
{
user: {
profile: {
name,
age,
tags
},
settings: {
theme,
notifications
}
},
items: {
id,
price
}
}# Input (Kubernetes manifests)
---
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
database_url: postgres://localhost:5432
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-app
spec:
replicas: 3
# Output (structure mode)
apiVersion
kind
metadata:
name
data:
database_url
---
apiVersion
kind
metadata:
name
spec:
replicasπ More Examples (All Languages) β
Reduce codebase size by 60-90% to fit in LLM context windows:
skim src/ --no-header | llm "Analyze this codebase"
skim src/app.ts | llm "Review this architecture"Extract function signatures for documentation:
skim src/ --mode signatures > api-docs.txt
skim 'lib/**/*.py' --mode signatures > python-api.txtFocus on type definitions and interfaces:
skim src/ --mode types --no-header
skim 'src/**/*.ts' --mode typesQuick overview without implementation details:
skim large-file.py | less
skim src/auth/ | lessπ 10 Detailed Use Cases β
Caching is enabled by default for 40-50x faster repeated processing.
| Scenario | Time | Speedup |
|---|---|---|
| First run (no cache) | 244ms | 1.0x |
| Second run (cached) | 5ms | 48.8x faster! |
ls ~/.cache/skim/ # View cache
skim --clear-cache # Clear cache
skim file.ts --no-cache # Disable for one runHow it works:
- Cache key: SHA256(file path + mtime + mode)
- Automatic invalidation when files change
- Platform-specific cache directory
When to disable caching:
- One-time LLM transformations
- Stdin processing
- Disk-constrained environments
See exactly how much context you're saving with --show-stats:
skim file.ts --show-stats
# [skim] 1,000 tokens β 200 tokens (80.0% reduction)
skim 'src/**/*.ts' --show-stats
# [skim] 15,000 tokens β 3,000 tokens (80.0% reduction) across 50 file(s)Uses OpenAI's tiktoken (cl100k_base for GPT-3.5/GPT-4). Output to stderr for clean piping.
Skim includes built-in DoS protections:
- Max recursion depth: 500 levels
- Max input size: 50MB per file
- Max AST nodes: 100,000 nodes
- Path traversal protection: Rejects malicious paths
- No code execution: Only parses, never runs code
π Security Details & Best Practices β π Vulnerability Disclosure β
Skim uses a clean, streaming architecture:
Language Detection β tree-sitter Parser β Transformation β Streaming Output
Design principles:
- Streaming-first: Output to stdout, no intermediate files
- Zero-copy: Uses
&strslices to minimize allocations - Error-tolerant: Handles incomplete/broken code gracefully
- Type-safe: Explicit error handling, no panics
π Architecture Deep Dive β
Target: <50ms for 1000-line files β Exceeded (14.6ms for 3000-line files)
| File Size | Lines | Time | Speed |
|---|---|---|---|
| Small | 300 | 1.3ms | 4.3Β΅s/line |
| Medium | 1500 | 6.4ms | 4.3Β΅s/line |
| Large | 3000 | 14.6ms | 4.9Β΅s/line |
Production TypeScript Codebase:
| Mode | Tokens | Reduction | LLM Context Multiplier |
|---|---|---|---|
| Full | 63,198 | 0% | 1.0x |
| Structure | 25,119 | 60.3% | 2.5x more code |
| Signatures | 7,328 | 88.4% | 8.6x more code |
| Types | 5,181 | 91.8% | 12.2x more code |
π Full Performance Benchmarks β
# Build and test
cargo build --release
cargo test --all-features
# Lint
cargo clippy -- -D warnings
cargo fmt -- --check
# Benchmark
cargo bench~30 minutes per language:
- Add tree-sitter grammar to
Cargo.toml - Update
Languageenum insrc/types.rs - Add file extension mapping
- Add test fixtures
- Run tests
Current: Production ready (v0.6.0+)
β Implemented:
- TypeScript/JavaScript/Python/Rust/Go/Java/Markdown/JSON/YAML support
- Structure/signatures/types/full modes
- CLI with stdin support
- Directory support (
skim src/- recursively processes all files) - Multi-file glob support (
skim 'src/**/*.ts') - Automatic language detection from file extensions
- Parallel processing with rayon (
--jobsflag) - Caching layer with mtime-based invalidation (enabled by default)
- Token counting with
--show-stats(GPT-3.5/GPT-4 compatible) - DoS protections
- Comprehensive test suite (151 tests passing)
- Performance benchmarks (verified: 14.6ms for 3000-line files, 5ms cached)
- npm and cargo distribution
See CHANGELOG.md for version history.
Comprehensive guides for all aspects of Skim:
- π Usage Guide - Complete CLI reference and options
- π― Transformation Modes - Detailed mode comparison and examples
- π‘ Examples - Language-specific transformation examples
- π Use Cases - 10 practical scenarios with commands
- β‘ Caching - Caching internals and best practices
- π Security - DoS protections and security best practices
- ποΈ Architecture - System design and technical details
- β±οΈ Performance - Benchmarks and optimization guide
- π οΈ Development - Contributing and adding languages
Contributions welcome! Please:
- Check issues for existing work
- Open an issue to discuss major changes
- Follow existing code style (
cargo fmt,cargo clippy) - Add tests for new features
- Update documentation
π See Development Guide for detailed instructions
skim/
βββ crates/
β βββ rskim-core/ # Core library (language-agnostic)
β βββ rskim/ # CLI binary (I/O layer)
βββ tests/fixtures/ # Test files for each language
βββ benches/ # Performance benchmarks (planned)
MIT License - see LICENSE for details.
- tree-sitter - Fast, incremental parsing library
- clap - Command-line argument parsing
- ripgrep, bat, fd - Inspiration for Rust CLI design
- Repository: https://github.com/dean0x/skim
- Issues: https://github.com/dean0x/skim/issues
- Crates.io: https://crates.io/crates/rskim
- npm: https://www.npmjs.com/package/rskim
Built with β€οΈ in Rust