Code-Reducer

Code-Reducer is a lightweight, high-performance command-line tool written in Go that automatically generates, validates, and queries developer-friendly, comprehensive wikis for extensive repositories.
Designed specifically for local development and private LLMs, Code-Reducer uses a custom Hierarchical Map-Reduce Strategy to analyze large codebases using small, local LLM models (e.g., 7B, 9B, or 26B parameters) via Ollama without exceeding context windows or degrading output quality.
🚀 Key Strengths
- Hierarchical Map-Reduce Pipeline: Breaks codebase synthesis into a structured Map-Reduce pipeline to document large directories recursively, staying strictly within local LLM context limits (
numCtx * 2 - runeCount(promptOverhead) characters).
- Optimized for Private & Local LLMs: Built specifically to leverage Ollama (e.g.,
ornith:9b or gemma4:26b), eliminating expensive cloud API costs and keeping proprietary code local.
- Smart Incremental Updates: Uses a filesystem SHA-256 hash cache and fact-level comparison to skip module re-synthesis when code edits do not alter extracted technical facts, and skips global documentation regeneration when top-level module summaries and directory structure remain unchanged.
- Deterministic Wiki Finalizer (
finalizeWiki): Automatically sanitizes and heuristically validates Mermaid diagrams (degrading unrecoverable blocks to text fences), generates <docs_dir>/index.md, stamps module provenance headers, and validates/auto-repairs internal Markdown links and GitHub heading anchors.
- Built-In Section-Level BM25 Search & Read: Provides
code-reducer search and code-reducer read commands for fast, zero-LLM-cost retrieval of documentation sections by keyword and source path hints.
- Multi-Language Documentation & Customizable Prompts: Supports generating documentation prose in any target language (
--language / CODE_REDUCER_LANGUAGE) while preserving code identifiers, and allows overriding all system, synthesis, quickstart, consolidation, and extraction prompts via .code-reducer.yaml.
- Enterprise-Grade Security Sandbox: Features path traversal guards, atomic process locking, and TOCTOU symlink hijacking defenses for safe workspace operations.
🏃 Quick Start
Prerequisites
- Go: Version 1.26 or higher.
- Ollama: Running locally with a compatible model downloaded (e.g.,
ornith:9b or gemma4:26b).
1. Build from Source (or Download Release)
Note: Precompiled binaries are available attached to each release.
Compile the executable binary inside the repository root:
go build -o code-reducer main.go
2. Run the Tool (Implicit Setup)
If you run code-reducer init or code-reducer update in a terminal (TTY) and the .code-reducer.yaml configuration file does not exist, the interactive configuration wizard will launch automatically.
Alternatively, you can manually run the setup wizard first:
./code-reducer setup
3. Generate the Wiki
Initialize the documentation cache and build the initial markdown files:
./code-reducer init
4. Keep Docs Updated
Incrementally update the wiki whenever code files change:
./code-reducer update
5. Search and Read the Wiki
Query ranked sections across the generated wiki and read specific pages or heading anchors:
./code-reducer search "context limit chunking" -p internal/engine -n 5
./code-reducer read modules/internal/engine/README.md
🛠️ CLI Command Reference
Global Persistent Flags
Available across commands (init, update, search, read):
--model-id <string>: Override the LLM model ID (e.g., --model-id gemma4:26b).
--num-ctx <int>: Override the Ollama context window size in tokens (e.g., --num-ctx 20000).
--language <string>: Target language for generated documentation prose (e.g., English, Spanish, es, en).
1. code-reducer setup
Runs an interactive setup flow in the current directory to generate the .code-reducer.yaml configuration file. If a .code-reducer.yaml file already exists, all prompts default to its current values:
- LLM Model ID (defaults to
ornith:9b)
- Ollama Base URL (defaults to
http://localhost:11434)
- Ollama Context Size (defaults to
8192)
- Custom directories, files, or glob patterns to ignore (comma-separated; enter
clear or none to reset)
- Documentation output folder name (defaults to
wiki)
- Output Language (leave empty for default English)
2. code-reducer init
Scans the repository, builds the hierarchical directory tree, and generates the initial set of wiki markdown pages:
- Generates module pages under
<docs_dir>/modules/<module>/README.md with provenance headers (> **Module:** ... | **Source Files:** ...).
- Synthesizes global
<docs_dir>/architecture.md and <docs_dir>/quickstart.md (including a developer Task Routing table).
- Runs the deterministic finalizer to sanitize/validate Mermaid blocks, generate
<docs_dir>/index.md, and validate/auto-repair internal links and heading anchors.
- Persists the metadata cache in
<docs_dir>/.metadata.json.
- Creates or idempotently updates the
<!-- CODE-REDUCER:START --> ... <!-- CODE-REDUCER:END --> block in AGENTS.md in the repository root.
- Note: Implicitly launches the interactive setup wizard if
.code-reducer.yaml is missing in a TTY session. Fails if the project has already been initialized.
3. code-reducer update
Detects files added, modified, or deleted since the last run and performs a smart incremental documentation refresh:
- Configuration & Prompt Hash Invalidation: Compares
cache.StepsHash against computeStepsHash(cfg) (which hashes model_id, language, all prompt templates, and all extraction_steps). Any change invalidates the cache and triggers a full rebuild.
- Fact-Level Short-Circuit: Re-extracts facts for modified files and compares them with cached
Facts. If the extracted facts are identical, only the file's SHA-256 hash is updated in .metadata.json and directory re-synthesis is skipped.
- Bottom-Up Propagation: Rebuilds only directories affected by effective file changes (or missing module docs) and propagates affected status upward to parent directories.
- Global Docs Short-Circuit: Skips regenerating
architecture.md and quickstart.md if no files were added or deleted, all global docs exist on disk, and the root (.) and top-level child module summaries are unchanged.
- Finalization & Pruning: Prunes deleted files and orphaned module docs, then runs
finalizeWiki to refresh <docs_dir>/index.md, validate Mermaid blocks, and check internal links.
4. code-reducer search <query> [--path/-p <file>] [--limit/-n <N>]
Searches generated wiki markdown pages (<docs_dir>/, excluding index.md and hidden files) at ATX heading section granularity using weighted BM25 ranking:
--path, -p <path> (repeatable / comma-separated): Boosts sections whose page path, module path, or provenance source files match the given path hint (2.0x score multiplier).
--limit, -n <int>: Maximum number of ranked results to return (defaults to 5).
- Outputs ranked
<page>#<anchor> targets ready to pass directly to code-reducer read, along with the section heading, provenance source files, and a matching snippet.
5. code-reducer read <page[#section]>
Reads a full markdown documentation page or extracts a specific heading section from <docs_dir>:
- Accepts targets with or without a leading
<docs_dir>/ prefix (e.g., architecture.md, wiki/quickstart.md#task-routing, or modules/internal/engine/README.md#synthesis-pipeline).
- Enforces
security.SafeResolve containment within <docs_dir>, rejecting path traversal (..), hidden files/directories, and non-.md files.
- When
#<anchor> is specified, extracts the matching ATX heading section up to the next heading of equal or higher level; if the anchor is not found, returns an error listing all available anchors on that page.
⚙️ Configuration (.code-reducer.yaml & Environment Variables)
Code-Reducer stores configuration parameters in .code-reducer.yaml in the root of the repository (saved with 0600 permissions).
Example Configuration