Smart context assembly tool for AI agents - intelligently packs relevant code context within strict token budgets using multi-factor relevance ranking.
context-packer is the capstone integration layer that combines code-index, code-summarizer, and context-query to create optimized context for AI agents. It solves the fundamental problem of balancing comprehensive code understanding with strict token limits.
AI agents need context to work effectively, but:
- Token limits are strict (8K-200K depending on model)
- Manually selecting files is inefficient and error-prone
- Including too much code wastes tokens on irrelevant information
- Excluding dependencies breaks understanding
context-packer uses intelligent relevance ranking and greedy packing algorithms to:
- Never exceed token budgets - Strict enforcement with real-time tracking
- Maximize relevance - Multi-factor scoring (query match, dependencies, hotness, recency)
- Hierarchical loading - Architecture summary → Primary files → Dependencies → Callers
- Model-specific formatting - Optimized output for Claude, GPT-4, Gemini
- Smart caching - Avoid re-sending unchanged code across sessions
┌──────────────┐
│ code-index │ ← Provides: Symbol lookup, dependencies, hotness scores
└──────┬───────┘
│
├──> ┌────────────────┐
│ │code-summarizer │ ← Provides: Architecture summaries
│ └────────┬───────┘
│ │
├─────────────┼──> ┌───────────────┐
│ │ │context-query │ ← Provides: Relevant file search
│ │ └───────┬───────┘
│ │ │
▼ ▼ ▼
┌─────────────────────────────────┐
│ context-packer │ ← Combines all tools
│ (Smart context assembly) │
└─────────────────┬───────────────┘
│
▼
AI Agent receives
optimized context
- Token Budget Management - Strict enforcement, never exceeds limits
- Multi-Factor Relevance Scoring - Query match + dependencies + hotness + recency + centrality
- Hierarchical Loading - Prioritizes architecture summary, primary files, then dependencies
- Multi-Model Support - Claude, GPT-4, GPT-3.5, Gemini with model-specific tokenizers
- Smart Caching - Content-hash based caching with automatic invalidation
- Interactive Mode - Guided workflow for building context
- Dependency Tracking - Automatically includes imported files and callers
- Partial File Inclusion - Extracts key functions when full file won't fit
- Rust 1.75+ (
rustuprecommended) - code-index installed and indexed
- context-query installed
- code-summarizer installed (optional but recommended)
git clone https://github.com/yourusername/context-packer.git
cd context-packer
cargo build --release
sudo cp target/release/context-packer /usr/local/bin/context-packer --version# Pack context for a task
context-packer pack --query "implement authentication"
# With specific budget and model
context-packer pack \
--query "optimize search performance" \
--budget 8000 \
--model claude
# Focus on specific file with dependencies
context-packer pack \
--file src/auth/login.ts \
--include-dependencies \
--include-callerscontext-packer interactiveThe interactive mode will prompt you for:
- What are you working on? (query)
- Token budget? (default: 8000)
- Target model? (default: claude)
- Include dependencies? (y/n)
- Include callers? (y/n)
context-packer pack \
--query "review authentication changes" \
--budget 10000 \
--model claude \
--output review-context.md# GPT-4 with tight budget
context-packer pack \
--query "add logging to API endpoints" \
--budget 6000 \
--model gpt4
# Gemini with large budget
context-packer pack \
--query "refactor database layer" \
--budget 50000 \
--model geminicontext-packer pack \
--file src/core/engine.rs \
--include-dependencies \
--include-callers \
--depth 2 \
--budget 15000context-packer pack \
--query "add feature flags" \
--dry-runOutput shows:
- Files ranked by relevance score
- Which files will be included (✓)
- Which files will be omitted (✗)
- Token usage breakdown
context-packer pack \
--query "implement caching" \
--format json \
--output context.json--config <PATH> Custom config file
--project-root <PATH> Project root (default: current dir)
--verbose, -v Verbose logging
--quiet, -q Quiet mode (errors only)
--no-cache Disable caching
--help, -h Show help
--version, -V Show version
context-packer pack [OPTIONS]
OPTIONS:
--query, -q <TEXT> Task/query description
--file, -f <PATH> Focus on specific file
--budget, -b <N> Token budget (default: 8000)
--model, -m <MODEL> claude|gpt4|gpt35|gemini (default: claude)
--output, -o <PATH> Output file (default: stdout)
--format <FMT> markdown|json (default: markdown)
--include-dependencies Include imported files
--include-callers Include calling code
--include-types Include type definitions
--depth <N> Dependency depth (1-3, default: 1)
--dry-run Preview without generating output
# View cache statistics
context-packer cache stats
# Clear all cache
context-packer cache clear
# Clear old entries (>7 days)
context-packer cache clear --older-than 7
# Invalidate specific patterns
context-packer cache invalidate "src/auth/*.ts"Default config location: ~/.config/ai-tools/config.toml
[context-packer]
default_budget = 8000
default_model = "claude"
cache_dir = "~/.cache/ai-tools/context-packer"
cache_max_size_mb = 100
cache_max_age_days = 7
[context-packer.ranking]
query_match_weight = 3.0
dep_proximity_weight = 2.0
hotness_weight = 1.5
recency_weight = 1.0
centrality_weight = 0.5
[context-packer.packing]
reserve_for_architecture = 500
min_remaining_to_continue = 100
enable_partial_files = true
max_dependency_depth = 3score = (query_match × 3.0) +
(dep_proximity × 2.0) +
(hotness × 1.5) +
(recency × 1.0) +
(centrality × 0.5)
Factors:
- query_match - How well file content matches the query
- dep_proximity - Direct dependency=1.0, transitive=0.5
- hotness - From code-index (complexity + change frequency)
- recency - Exponential decay based on last modified
- centrality - Files with many connections (hubs)
- Reserve 200-500 tokens for architecture summary
- Find relevant files using context-query
- Score files using multi-factor formula
- Sort by score (descending)
- Pack greedily until budget full:
- Add highest scored file
- Count tokens
- If exceeds budget: try partial or skip
- Continue until <100 tokens remain
- Format for target model
- Cache result with file content hashes
Languages: Rust Project Type: CLI tool
git clone https://github.com/yourusername/context-packer.git
cd context-packer
cargo build
cargo test
cargo run -- pack --query "test"# All tests
cargo test
# Integration tests only
cargo test --test integration_test
# With logging
RUST_LOG=debug cargo test
# Performance benchmarks
cargo benchsrc/
├── main.rs # CLI entry point
├── cli.rs # Argument parsing
├── tokens/ # Token counting (Claude, GPT, Gemini)
├── query/ # Query processing & expansion
├── rank/ # Relevance scoring
├── pack/ # Greedy packing algorithm
├── format/ # Model-specific formatters
├── cache/ # Cache management
└── tools/ # Tool integration (code-index, etc.)
This project is configured for AI agent workflows:
CLAUDE.md- Detailed AI agent instructions.ai/TOOLS.md- Available custom tooling.ai/ARCHITECTURE.md- System architecture.ai/CONVENTIONS.md- Coding conventions
- Pack 500-file project: < 3 seconds
- Cache hit: < 50ms
- Token counting per file: < 10ms
- Relevance scoring (100 files): < 500ms
Ensure code-index is installed and you've run code-index index in your project.
Try:
- Increase budget:
--budget 15000 - Enable partial files in config
- Use more specific query to reduce matches
Clear and rebuild:
context-packer cache clear- Check if code-index is up to date
- Clear old cache entries
- Reduce
--depthfor dependencies
MIT License - see LICENSE file for details