# AI Distiller (`aid`) > **Note:** This is the very first version of this tool. We would be very grateful for any feedback in the form of a discussion or by creating an issue on [GitHub](https://github.com/janreges/ai-distiller/issues). Thank you\! πŸš€ **MCP Server Available**: Install the Model Context Protocol server for AI Distiller from NPM: [`@janreges/ai-distiller-mcp`](https://www.npmjs.com/package/@janreges/ai-distiller-mcp) - seamlessly integrate with Claude, Cursor, and other MCP-compatible AI tools!

AI Distiller (aid) Mascot

12+ Languages Performance Compression

/.aid/` from anywhere inside the project - **Easy cleanup**: Add `.aid/` to `.gitignore` to keep outputs out of version control **Detection order:** the nearest directory at or above the working directory (at most 12 levels, not above your home directory) that holds one of these markers is the root; within one directory they are checked in this order: 1. **`.aidrc` file** - Create this empty file to explicitly mark your project root 2. **Language markers** - `go.mod`, `package.json`, `pyproject.toml`, etc. 3. **Version control** - `.git` directory Without a marker, `AID_PROJECT_ROOT` is used, and without that the current directory (with a warning). Details: [project-root-detection.md](docs/user/project-root-detection.md). `AID_CONFINE_ROOT` (the MCP server sets it to the real path of `AID_ROOT`; unset, it changes nothing) confines aid to one directory: aid reads no file whose real path lies outside it (a path argument outside it is an error, a directory walk skips symlinks that lead out), the search for markers stops at it, and without a marker inside it the root is `AID_PROJECT_ROOT` when that lies inside, else the confine root itself. ```bash # Mark a specific directory as project root (recommended) touch /my/project/.aidrc # Run from anywhere in your project - outputs always go to project root cd deep/nested/directory aid ../../../src # Output: /.aid/aid.src.txt # Use environment variable as fallback (useful for CI/CD) AID_PROJECT_ROOT=/build/workspace aid src/ ``` ### 🌍 Language Support Currently supports 12 languages: - **Full Support**: Python, Go, JavaScript, PHP, Ruby - **Beta**: TypeScript, Java, C#, Rust, Kotlin, Swift, C++ - **Coming Soon**: Zig, Scala, Clojure #### Language-Specific Documentation: - [C++](docs/lang/cpp.md) - Classes, templates, out-of-class definitions, Doxygen docs - [C#](docs/lang/csharp.md) - Classes, records, generics with constraints, nullable reference types - [Go](docs/lang/go.md) - Full Go support with interfaces, goroutines, generics (1.18+) - [Java](docs/lang/java.md) - Java 8-21 support with records, sealed classes, pattern matching - [JavaScript](docs/lang/javascript.md) - ES6+ support with classes, modules, async/await - [Kotlin](docs/lang/kotlin.md) - Kotlin 1.x support with coroutines, data classes, sealed classes - [PHP](docs/lang/php.md) - PHP 7.4+ with PHP 8.x features (attributes, union types, enums) - [Python](docs/lang/python.md) - Python 3.x support with type hints, decorators, dataclasses, docstrings - [Ruby](docs/lang/ruby.md) - Ruby 2.x/3.x support with modules, mixins, visibility sections - [Rust](docs/lang/rust.md) - Rust 2018/2021 editions with traits, lifetimes, async - [Swift](docs/lang/swift.md) - Swift 5.x support with protocols, extensions, access control - [TypeScript](docs/lang/typescript.md) - TypeScript 4.x/5.x with generics, decorators, type system ## 🎯 How It Works 1. **Scans** your codebase recursively for supported file types (12 languages) 2. **Parses** each file with a language-specific parser, all bundled in the binary with no external dependencies: ten languages (Python, JavaScript, TypeScript, PHP, Ruby, Java, C#, Kotlin, C++, Rust) use tree-sitter, Go uses the Go standard library parser, and Swift uses a line-based parser 3. **Extracts** only what you need: public APIs, type signatures, class hierarchies 4. **Outputs** in your preferred format: compact text, markdown, or structured JSON The tree-sitter grammars are compiled into the `aid` binary through cgo - zero external dependencies at run time. ## πŸ”— Dependency-Aware Distillation (experimental) `--dependency-aware` distils a file together with the project files it imports. aid prints the entry file exactly as it prints it without the flag, then follows its imports, breadth-first, and distils every file it reaches with the same flags (visibility, `--implementation`, `--comments`, ...). `--max-depth` (default 2) is the number of import levels: `1` adds the files the entry file imports, `2` also the files those import, and so on. Each file appears once, with its path relative to the entry file's directory (`../lib/util.ts` for a file outside it). The analysis is heuristic: imports are found with regular expressions (Go imports with `go/parser`, JavaScript and TypeScript imports from the tree-sitter tree, so text in strings and comments never counts) and resolved to files on disk. It does not work out which symbols the entry file uses, so a followed file is distilled whole. Imports of the standard library and of installed packages are not followed. When no import resolves to a project file aid can distill, aid prints the entry file alone and says so in one line on stderr. Go follows packages, not files, because a Go package is the unit that compiles together: a Go file brings the other files of its package (same directory and `package` clause, no `_test.go`) at the first level, and an imported package of the module brings all its non-test files. In chi, `middleware/logger.go` adds the 30 other files of `middleware` at depth 1. When files were followed, one line on stderr says how many, from how many levels of imports, and how large the whole output is; when they came from below the direct imports it adds that `--max-depth=1` keeps only those: ```text Note: --dependency-aware added 102 imported files from 2 levels of imports (--max-depth=2); the output is 472 kB; --max-depth=1 keeps only the direct imports ``` Following never leaves the repository: a file whose real path (symlinks resolved) lies outside the nearest directory above the input that holds `.git` is not read, and neither are the `go.mod`, `Cargo.toml`, `tsconfig.json` or `composer.json` files there. Without `.git`, the boundary is the [project root](#-smart-project-root-detection) aid detects from the working directory (a marker or `AID_PROJECT_ROOT`) when it holds the input, else the input's directory; the working directory that aid falls back to without a marker is never a boundary. With `AID_CONFINE_ROOT` set (as the MCP server does), following also stays inside that directory, and project files above it are not read. Followed files pass the selection rules of a directory walk: `--include`, `--exclude`, every `.aidignore` from the repository top down to the file's directory, and the directories a walk skips by default (`node_modules`, `vendor`, `build`, ...). The patterns match the path aid prints without its leading `../`, so the directories that hold the input never match. A file the rules leave out is not read, so its imports are not followed either. The input itself is not filtered, as without the flag, and `--recursive=0` limits only the walk of a directory input. `-v` names every import skipped for either reason. When nothing is followed, the one-line note on stderr names the first three skipped imports with their reason (`skipped ../shared/x.js (outside the repository), ...`), each once, and how many more there are. Given a directory, aid distils every file of it as without the flag and adds the files outside the directory that they import. Given several paths, it follows the imports of every one, each inside its own boundary, and prints each file once. ```bash # The entry file and what it imports, two levels deep aid cmd/server/main.go --dependency-aware # Only the files the entry file imports directly aid src/app.ts --dependency-aware --max-depth=1 # With function bodies aid src/app.ts --dependency-aware --implementation=1 # A directory plus the files outside it that it imports aid src/components --dependency-aware ``` ### What is followed, per language "Measured" counts the files aid added to the entry file in public repositories (`git clone --depth 1`, 2026-11-16) at the given `--max-depth`; the note on stderr prints the count. A followed file whose distillation is empty prints no block. Languages without a measurement have not been checked on a real project. | Language | Imports that are followed | Measured | |---|---|---| | Python | `import x`, `from x import y` (a module next to the importing file), relative `from .x import y` | not checked | | JavaScript, TypeScript | `import`/`export ... from` (also over several lines), `import 'x'`, `import('x')` and `require('x')` with a relative path or one that `compilerOptions.paths` or `baseUrl` of the nearest `tsconfig.json`/`jsconfig.json` maps (relative `extends` and `references` are read); `./x.js` finds `x.ts`, `./x` finds `x.ts`, `x.tsx`, ..., then the directory `x` (the file its `package.json` `main` names, else `x/index.*`); `./x/` names only the directory | files at depth 1 / 2 / 3: react-redux-realworld-example-app `src/index.js` 2 / 15 / 30; bulletproof-react `apps/react-vite/src/main.tsx` 2 / 7 / 24 (`@/*` paths, lazy `import()`); zod `packages/zod/src/index.ts` 1 / 15 / 95, `v4/classic/schemas.ts` 9 / 24 / 86 | | Go | the other files of the package (same directory and `package` clause, no `_test.go`), then the packages, read by `go/parser` from the import declarations in any layout, of the file's module (the module path in the nearest `go.mod`) and of modules that `go.mod` replaces with a local directory | files at depth 1 / 2 / 3: chi `mux.go` 4 / 4 / 4 (its package); `middleware/logger.go` 30 / 35 / 35; bubbletea `examples/simple/main.go` 36 / 36 / 36 (bubbletea itself, through `replace ... => ../`) | | Rust | `mod x;` (not under `#[cfg(test)]`), and paths starting with `crate::`, `super::`, `self::`, the crate's library name or a path dependency's name, in `use` and in code, to the deepest module that exists as `x.rs` or `x/mod.rs` (the nearest `Cargo.toml` names the crate) | files at depth 1 / 2 / 3: siteone-crawler `src/main.rs` 10 / 61 / 156 | | PHP | classes named in `use` imports (also grouped and aliased; not `use function`/`use const`), trait `use` in a class, `extends` and `implements`, found through the PSR-4 `autoload` and `autoload-dev` of every `composer.json` from the file up to the repository top; `require`/`include` (`_once`) of a literal path, also `__DIR__ . '/x.php'`. Classes under `vendor/` are not followed | files at depth 1 / 2 / 3: laravel `src/Illuminate/Database/Eloquent/Model.php` 39 / 102 / 137 | | Ruby | `require_relative`, `require` of a file next to the importing file | not checked | | Java, C# | an imported class `X` as `X.java`/`X.cs` next to the file, plus every file of the same directory | not checked | | Kotlin | `import a.b.X` as an `X.kt` file near the importing file | not checked | | Swift | every `.swift` file of the same directory | not checked | | C++ | `#include "x.h"` next to the file, plus `x.cpp` | not checked | ### πŸš€ Transform Massive Codebases Into AI-Friendly Context > **The Problem**: Modern codebases contain thousands of files with millions of lines. But for AI to understand your code architecture, suggest improvements, or help with development, it doesn't need to see every implementation detail - it needs the **structure and public interfaces**. > **The Solution**: AI Distiller extracts only what matters - public APIs, types, and signatures - reducing codebase size by 90-98% while preserving all essential information for AI comprehension.
Project Files Original Tokens Distilled Tokens Fits in Context1 Speed2
βš›οΈ react 1,781 ~5.5M 250K (-95%) βœ… Gemini3 2,875 files/s
🎨 vscode 4,768 ~22.5M 2M (-91%) ⚠️ Needs chunking 5,072 files/s
🐍 django 970 ~10M 256K (-97%) βœ… Gemini3 4,199 files/s
πŸ“¦ prometheus 685 ~8.5M 154K (-98%) βœ… Claude/Gemini 3,071 files/s
πŸ¦€ rust-analyzer 1,275 ~5.5M 172K (-97%) βœ… Claude/Gemini 10,451 files/s
πŸš€ astro 1,058 ~10.5M 149K (-99%) βœ… Claude/Gemini 5,212 files/s
πŸ’Ž rails 394 ~1M 104K (-90%) βœ… ChatGPT-4o 4,864 files/s
🐘 laravel 1,443 ~3M 238K (-92%) βœ… Gemini3 4,613 files/s
⚑ nestjs 802 ~1.5M 107K (-93%) βœ… ChatGPT-4o 8,813 files/s
πŸ‘» ghost 2,184 ~8M 235K (-97%) βœ… Gemini3 4,719 files/s
Project sizes and percentages in this table are approximate. They were gathered with an earlier summary that estimated the source size instead of measuring it, and the exact input snapshots are not part of this repository.
1 Context windows: ChatGPT-4o (128K), Claude (200K), Gemini (1M). βœ… = fits completely, ⚠️ = needs splitting
2 Processing speed with 12 parallel workers on AMD Ryzen 7945HX. Use `-w 1` for serial mode or `-w N` for custom workers.
3 These frameworks exceed 200K tokens and work only with Gemini due to its larger 1M token context window. ### 🎯 Why This Matters for AI-Assisted Development **Large codebases are overwhelming for AI models.** A typical web framework like Django has ~10 million tokens of source code. Even with Claude's 200K context window, you'd need to split it into 50+ chunks, losing coherence and relationships between components. **But here's the good news**: Most real-world projects that teams have invested hundreds to thousands of hours developing are much smaller. Thanks to AI Distiller, the vast majority of typical business applications, SaaS products, and internal tools can fit entirely within AI context windows, enabling unprecedented AI assistance quality. ### ⚠️ The Hidden Problem with AI Coding Tools **Most AI agents and IDEs are "context misers"** - they try to save tokens at the expense of actual codebase knowledge. They rely on: - πŸ” **Grep/search** to find relevant code snippets - πŸ“„ **Limited context** showing only 10-50 lines around matches - 🎲 **Guessing interfaces** based on partial information **This is why AI-generated code often fails on first attempts** - the AI is literally guessing method signatures, parameter types, and return values because it can't see the full picture. **AI Distiller changes the game** by giving AI complete knowledge of: - βœ… **Exact interfaces** of all classes, methods, and functions - βœ… **All parameter types** and their expected values - βœ… **Return types** and data structures - βœ… **Full inheritance hierarchies** and relationships Instead of playing "code roulette", AI can now write correct code from the start. **Result**: Django's 10M tokens compress to just 256K tokens - suddenly the **entire framework fits in a single AI conversation**, leading to: - 🎯 **More accurate suggestions** - AI sees all available APIs at once - πŸš€ **Less hallucination** - No more inventing methods that don't exist - πŸ’‘ **Better architecture advice** - AI understands the full system design - ⚑ **Faster development** - Especially for "vibe coding" with AI assistance - πŸ’° **40x cost reduction** - Pay for 256K tokens instead of 10M on API calls ### πŸ”§ Flexible for Different Use Cases ```bash # Process entire codebase (default: public APIs only) aid ./my-project # Process specific directory or module aid ./my-project/src/auth aid ./my-project/src/api # Process a directory aid ./my-project/core/ # Process individual file aid src/main.py # Several files and directories in one output, in argument order aid src/main.py src/auth src/api/routes.py # Include protected/private for deeper analysis aid ./my-project --private=1 --protected=1 # Include implementations for small projects aid ./my-small-lib --implementation=1 # Everything for complete understanding aid ./micro-service --private=1 --protected=1 --implementation=1 ``` **Granular Control**: Process your entire codebase, specific modules, directories, or even individual files. Perfect for focusing AI on the exact context it needs - whether that's understanding the whole system architecture or diving deep into a specific authentication module. ## πŸš€ Quick Start ### One-Line Installation **macOS / Linux / WSL:** ```bash # Install to ~/.aid/bin (recommended, no sudo required) curl -sSL https://raw.githubusercontent.com/janreges/ai-distiller/main/install.sh | bash # Install to /usr/local/bin (requires sudo) curl -sSL https://raw.githubusercontent.com/janreges/ai-distiller/main/install.sh | bash -s -- --sudo ``` **Windows PowerShell:** ```powershell iwr https://raw.githubusercontent.com/janreges/ai-distiller/main/install.ps1 -useb | iex ``` The installer will: - Detect your OS and architecture automatically - Download the appropriate pre-built binary - Install to `~/.aid/bin/aid` by default (no sudo required) - Or to `/usr/local/bin/aid` with `--sudo` flag - Verify the download against the release's `checksums.txt` - Guide you through PATH configuration if needed The installer resolves the latest release when it runs. To pin a version, pass it to `install.sh` (`bash -s -- v1.4.0`, also with `--sudo`) or set `$env:AID_VERSION` before running `install.ps1`. `AID_INSTALL_ROOT` changes the install root (default `~/.aid`). ### Basic Usage ```bash # Basic usage aid . # Current directory, output is saved to .aid/aid..txt in the project root aid . --stdout # Current directory, output is printed to STDOUT aid src/ # Specific directory aid main.py # Specific file aid main.py lib/ --stdout # Several paths, one output in argument order ``` ## πŸ“– Example Output
Python Class Example **Input** (`car.py`): ```python class Car: """A car with basic attributes and methods.""" def __init__(self, make: str, model: str): self.make = make self.model = model self._mileage = 0 # Private def drive(self, distance: int) -> None: """Drive the car.""" if distance > 0: self._mileage += distance ``` **Output** (`aid car.py --stdout`): ``` class Car: """A car with basic attributes and methods.""" make = make model = model __init__(self, make: str, model: str) drive(self, distance: int) -> None """Drive the car.""" ```
TypeScript Interface Example **Input** (`api.ts`): ```typescript export interface User { id: number; name: string; email?: string; } export class UserService { private cache = new Map(); async getUser(id: number): Promise { return this.cache.get(id) || null; } } ``` **Output** (`aid api.ts --stdout`): ``` export interface User { property id: number property name: string property email: string } export class UserService { public async getUser(id: number): Promise } ``` The private `cache` field is hidden by default; the `?` of `email` is not printed (see [TypeScript limitations](docs/lang/typescript.md#known-limitations)).
## πŸ“– Guides & Examples ### Deep Code Analysis Prompt Generation AI Distiller generates sophisticated analysis prompts that AI assistants can execute for comprehensive codebase understanding: ```bash aid internal \ --private=1 --protected=1 --implementation=1 \ --ai-action=flow-for-deep-file-to-file-analysis βœ… AI Analysis Task List generated successfully! πŸ“‹ Task List: .aid/ANALYSIS-TASK-LIST.internal.2025-06-20.md πŸ“Š Summary File: .aid/ANALYSIS-SUMMARY.internal.2025-06-20.md πŸ“ Analysis Reports Directory: .aid/analysis.internal/2025-06-20 πŸ€– Ready for AI-driven analysis workflow! πŸ“‚ Files to analyze: 158 πŸ’‘ If you are an AI agent, please read the Task List above and carefully follow all instructions to systematically analyze each file. ``` **What AI Distiller generates**: - πŸ“‹ **Task list prompt** - A structured checklist for AI to follow (`.aid/ANALYSIS-TASK-LIST.PROJECT.DATE.md`) - 🎯 **Analysis instructions** - Detailed prompts guiding AI through security, performance, and quality checks - πŸ“Š **Code structure** - Distilled code included in the prompt files for AI to analyze - πŸ“ **Directory structure** - Pre-created folders where AI agents can save their analysis results **How to use the generated prompts**: 1. **For AI agents**: Direct the agent to read the generated task list file and follow instructions 2. **For web AI tools**: Copy the content of generated files and paste into Gemini (best for large codebases due to 1M context) 3. **For small codebases**: Add `--stdout` to also print the prompt (the file is written either way) **Note**: The analysis dimensions (Security, Performance, Maintainability, Readability) are part of the prompts that guide the AI - AI Distiller itself doesn't perform any analysis. ### πŸ€– Use with Claude Code/Desktop (MCP) AI Distiller now integrates seamlessly with Claude Code/Desktop through the Model Context Protocol (MCP), enabling AI agents to analyze and understand codebases directly within conversations. ```bash # One-line installation claude mcp add aid -- npx -y @janreges/ai-distiller-mcp ``` πŸ“¦ **NPM Package**: [`@janreges/ai-distiller-mcp`](https://www.npmjs.com/package/@janreges/ai-distiller-mcp) - Full documentation and examples available #### Available MCP Tools The server registers 16 tools. Parameters per tool are in [`mcp-npm/README.md`](mcp-npm/README.md) and [`mcp-tools.md`](.claude/skills/aid-release-mcp/references/mcp-tools.md). The tools read and list only files under `AID_ROOT` (the server's environment; default: its working directory). The server refuses a path parameter whose real path is outside it, also one that leaves it through a symlink, with an error that names `AID_ROOT`; to work with files elsewhere, start the server with `AID_ROOT` set to a directory that contains them. It also runs `aid` with `AID_CONFINE_ROOT` set to the real path of `AID_ROOT`, so `aid` itself reads nothing outside it (a directory walk skips a symlinked file whose target is outside, and imports are not followed out of it) and writes its `.aid/` files inside it. That needs an `aid` of the same release as the package, which is what its postinstall downloads. **Code structure tools:** - `distill_file` - Extract structure from a single file - `distill_directory` - Extract structure from entire directories - `distill_with_dependencies` - **EXPERIMENTAL**: distill a file together with the files it depends on (heuristic, regex-based analysis) - `list_files` - Browse directories with file statistics - `get_capabilities` - Get info about AI Distiller capabilities **AI analysis prompt tools:** - `aid_hunt_bugs`, `aid_suggest_refactoring`, `aid_generate_diagram`, `aid_analyze_security`, `aid_generate_docs`, `aid_deep_file_analysis`, `aid_multi_file_docs`, `aid_complex_analysis`, `aid_performance_analysis`, `aid_best_practices` - each generates a specialized prompt for that kind of analysis, with the distilled code - `aid_analyze` - Direct access to all AI actions for custom workflows **Important**: AI Distiller **generates analysis prompts** with distilled code - it does NOT perform the actual analysis! The output is a specialized prompt + distilled code that AI agents (like Claude) then execute. For large codebases, you can copy the output to tools like Gemini 2.0 with 1M context window. **Smart Context Management**: AI agents can analyze your entire project for understanding the big picture, then zoom into specific modules (auth, API, database) for detailed work. No more overwhelming AI with irrelevant code! ## πŸ“– Complete CLI Reference ### Command Synopsis ```bash aid ... [OPTIONS] ``` ### Core Arguments and Options #### 🎯 Primary Arguments | Argument | Type | Default | Description | |----------|------|---------|-------------| | `...` | String | *(required)* | Paths to source files or directories to analyze. Several paths are one output: each is distilled as it is alone, the files follow in argument order, a file named twice or inside a named directory prints once, paths are relative to the deepest directory that holds them all, and the default output file is `aid.+-more[.].` ([details](docs/user/COMMAND-LINE-OPTIONS.md#several-paths)). Use `.git` for git history mode, `-` (or empty) for stdin input; these and `--ai-action` take one path | #### πŸ“ Output Options | Option | Type | Default | Description | |--------|------|---------|-------------| | `-o, --output` | String | `.aid/aid.[.].` | Output file path. Without `-o`, the name is built from the input's basename and the non-default options (`aid.src.priv.impl.txt`), in the project root | | `--stdout` | Flag | `false` | Print to stdout; no file is written unless `-o` is also given; AI actions always write to `--ai-output` and reject `-o` | | `--format` | String | `text` | Output format: `text` (ultra-compact), `md` (clean Markdown), `jsonl` (one JSON per file), `json-structured` (rich semantic data), `xml` (structured XML). In `text`, a file whose distillation is empty (only unused imports, or nothing at the chosen visibility) prints no `` block, and a run of several files says on stderr how many were left out | #### πŸ€– AI Actions | Option | Type | Default | Description | |--------|------|---------|-------------| | `--ai-action` | String | *(none)* | Generate pre-configured prompts with distilled code for AI analysis. See [AI Actions](#ai-actions-detailed) section below | | `--ai-output` | String | `.aid/....md` | Custom output path for generated AI prompt files (for example `.aid/BUG-HUNTING-ANALYSIS.2026-11-15.19-03-24.src.md`); must be inside the project | #### πŸ‘οΈ Visibility Filtering | Option | Type | Default | Description | |--------|------|---------|-------------| | `--public` | 0\|1 | `1` | Include public members (methods, functions, classes) | | `--protected` | 0\|1 | `0` | Include protected members | | `--internal` | 0\|1 | `0` | Include internal/package-private members | | `--private` | 0\|1 | `0` | Include private members | #### πŸ“ Content Filtering | Option | Type | Default | Description | |--------|------|---------|-------------| | `--comments` | 0\|1 | `0` | Include inline and block comments | | `--docstrings` | 0\|1 | `1` | Include documentation comments (docstrings, JSDoc, etc.) | | `--implementation` | 0\|1 | `0` | Include function/method bodies (implementation details) | | `--expand` | String | *(none)* | Keep full implementation **only** for symbols whose name matches these globs (comma-separated / repeatable). Matches a function/method name; matching a type name (class, struct, interface or enum) expands the methods nested inside it (Python/TypeScript/Java/C# etc.) and the ones declared for it outside it: Go methods whose receiver is that type (`--expand Server` expands `func (s *Server) Run()`) and Rust `impl Type` / `impl Trait for Type` blocks. For Swift extensions and C++ out-of-class definitions, match the method name; a Kotlin extension function is named with its receiver type, so match `Point.moved` or `*.moved`. A JavaScript/TypeScript getter, setter or generator matches by its bare name (`size` expands `get size()` and `set size(v)`, `items` expands `*items()`), and a computed or quoted member name by the text inside its brackets or quotes (`Symbol.iterator` expands `[Symbol.iterator]()`). e.g. `--expand "GetUser"`, `--expand "*Service*"`. Signatures everywhere else β€” great for agent-driven context building. A pattern that matches no symbol the output shows is named in a `Note:` line on stderr | | `--imports` | 0\|1 | `1` | Include import/require statements | | `--annotations` | 0\|1 | `1` | Include decorators and annotations | | `--fields` | 0\|1 | `1` | Include class fields and properties | | `--methods` | 0\|1 | `1` | Include methods and functions | #### πŸŽ›οΈ Alternative Filtering Syntax | Option | Type | Default | Description | |--------|------|---------|-------------| | `--include-only` | String | *(none)* | Include ONLY these categories (comma-separated: `public,methods,fields,imports`); starts from nothing, so list `methods` and/or `fields` or classes print empty | | `--exclude-items` | String | *(none)* | Start from everything (all visibility levels, comments, bodies) and exclude these categories (comma-separated: `private,comments,implementation`) | #### πŸ“‚ File Selection | Option | Type | Default | Description | |--------|------|---------|-------------| | `--include` | String | *(all files)* | Include file patterns (comma-separated: `*.go,*.py` or multiple: `--include "*.go" --include "*.py"`) | | `--exclude` | String | *(none)* | Exclude file patterns (comma-separated: `*test*,*.json` or multiple: `--exclude "*test*" --exclude "vendor/**"`) | | `-r, --recursive` | 0\|1 | `1` | Process directories recursively. Set to 0 to process only immediate directory contents | #### πŸ”§ Processing Options | Option | Type | Default | Description | |--------|------|---------|-------------| | `--raw` | Flag | `false` | Process all text files without language parsing. Overrides all content filters | | `--lang` | String | `auto` | Language of stdin input (ignored with a file or directory path): `auto`, `python`, `typescript`, `javascript`, `go`, `rust`, `java`, `csharp`, `kotlin`, `cpp`, `php`, `ruby`, `swift`; aliases `c#`, `c++`, `cc`, `cs`, `cxx`, `golang`, `js`, `jsx`, `kt`, `py`, `rb`, `rs`, `ts`, `tsx` | #### πŸ“ Path Control | Option | Type | Default | Description | |--------|------|---------|-------------| | `--file-path-type` | String | `relative` | Path format in output: `relative` or `absolute` | | `--relative-path-prefix` | String | *(empty)* | Custom prefix for relative paths (e.g., `module/` β†’ `module/src/file.go`) | #### ⚑ Performance Options | Option | Type | Default | Description | |--------|------|---------|-------------| | `-w, --workers` | Integer | `0` | Number of parallel workers. `0` = auto (80% of CPU cores), `1` = serial processing, `2+` = specific worker count | #### πŸ“Š Summary Output Options | Option | Type | Default | Description | |--------|------|---------|-------------| | `--summary-type` | String | `visual-progress-bar` | Summary format after processing. See [Summary Types](#summary-types) below | | `--no-emoji` | Flag | `false` | Disable emojis in summary output for plain text terminals | #### πŸ“œ Git Mode Options (when path is `.git`) | Option | Type | Default | Description | |--------|------|---------|-------------| | `--git-limit` | Integer | `200` | Number of commits to analyze. Use `0` for all commits | | `--with-analysis-prompt` | Flag | `false` | Add comprehensive AI analysis prompt for commit quality, patterns, and insights | #### πŸ› Diagnostic Options | Option | Type | Default | Description | |--------|------|---------|-------------| | `-v, --verbose` | Count | `0` | Verbose output. Use `-vv` for detailed info, `-vvv` for full trace with data dumps | | `--version` | Flag | `false` | Show version information and exit | | `--help` | Flag | `false` | Show help message | | `--help-extended` | Flag | `false` | Show complete documentation (man page style) | | `--cheat` | Flag | `false` | Show quick reference card | ### AI Actions Detailed AI actions generate pre-configured prompts combined with distilled code that AI agents can then execute for specific analysis tasks: | Action | Generated Prompt Type | AI Agent Will | |--------|-------------|----------| | `prompt-for-refactoring-suggestion` | Refactoring analysis prompt with distilled code | Analyze code for improvements, technical debt, effort sizing | | `prompt-for-complex-codebase-analysis` | Enterprise-grade analysis prompt with full codebase | Generate architecture diagrams, compliance checks, findings | | `prompt-for-security-analysis` | Security audit prompt with OWASP Top 10 guidelines | Detect vulnerabilities, suggest remediation steps | | `prompt-for-performance-analysis` | Performance optimization prompt with complexity focus | Identify bottlenecks, analyze scalability issues | | `prompt-for-best-practices-analysis` | Code quality prompt with industry standards | Assess code quality, suggest improvements | | `prompt-for-bug-hunting` | Bug detection prompt with pattern analysis | Find bugs, analyze quality metrics | | `prompt-for-single-file-docs` | Documentation generation prompt for single file | Create comprehensive API documentation | | `prompt-for-diagrams` | Diagram generation prompt with Mermaid syntax | Generate 10+ architecture and process diagrams | | `flow-for-deep-file-to-file-analysis` | Systematic analysis task list with directory structure | Perform file-by-file deep analysis | | `flow-for-multi-file-docs` | Documentation workflow with file relationships | Create interconnected documentation | ### Summary Types | Type | Description | Example Output | |------|-------------|----------------| | `visual-progress-bar` | Default. Shows compression progress bar, coloured in a terminal unless `NO_COLOR` is set | `πŸš€ Distilled 241 files [β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘] 93% (2.4 MB β†’ 166 kB) in 163ms πŸ’° ~570k tokens saved (~42k remaining)` | | `stock-ticker` | Compact stock market style | `πŸ“Š AID 93.2% β–² β”‚ SIZE: 2.4 MBβ†’166 kB β”‚ TIME: 161ms β”‚ EST: ~570k tokens saved` | | `speedometer-dashboard` | Multi-line dashboard with detailed metrics | Speed, saved percentage and sizes, and tokens saved in a box | | `minimalist-sparkline` | Single line with all essential info | `✨ Distilled in 160ms. πŸ“¦ 2.4 MB β†’ 166 kB (93.2% saved). 🎟️ Tokens: ~611k β†’ ~42k.` | | `ci-friendly` | Clean format for CI/CD pipelines | `[aid] βœ“ 93.2% saved \| 2.4 MB β†’ 166 kB \| 163ms \| ~570k tokens saved` | | `json` | Machine-readable JSON output | `{"original_bytes":2445701,"distilled_bytes":166012,...}` | | `off` | Disable summary output | No summary displayed | ### Exit Codes | Code | Meaning | |------|---------| | `0` | Success. A file that does not parse does not fail the run (its output may be empty), except Go: see `1` | | `1` | Any error: nonexistent path, a single Go file or Go stdin that does not parse (in a directory run such a file is skipped with a warning), invalid or conflicting options, undetected stdin language, etc. The full list is in [COMMAND-LINE-OPTIONS.md](docs/user/COMMAND-LINE-OPTIONS.md#exit-codes) | ### Examples ```bash # Basic usage - distill with default settings (public APIs only) aid ./src # Include all visibility levels and implementation aid ./src --private=1 --protected=1 --internal=1 --implementation=1 # Generate security analysis prompt (AI agent will execute the analysis) aid --ai-action prompt-for-security-analysis ./api --private=1 # Process only Python and Go files, exclude tests aid --include "*.py,*.go" --exclude "*test*,*spec*" ./ # Git history analysis with AI insights aid .git --with-analysis-prompt --git-limit=500 # Raw text processing for documentation aid ./docs --raw # Force single-threaded processing for debugging (-v, -vv, -vvv) aid ./complex-code -w 1 -vv # Custom output with absolute paths aid ./lib --output=/tmp/analysis.txt --file-path-type=absolute # CI/CD integration with clean output aid ./internal --summary-type=ci-friendly --no-emoji ``` ## ⚠️ Limitations - **Syntax Errors**: Files with syntax errors may be skipped or partially processed - **Dynamic Features**: Runtime-determined types/interfaces in dynamic languages are not resolved - **Macro Expansion**: Complex macros (Rust, C++) show pre-expansion source - **Generated Code**: Consider using `.aidignore` to skip generated files - **Known gaps**: none today (every conformance check passes); a language behaviour that differs from the others is listed in [`internal/conformance/known_gaps_test.go`](internal/conformance/known_gaps_test.go) ## πŸ”’ Security Considerations **⚠️ Important**: AI Distiller extracts code structure which may include: - Function and variable names that could reveal business logic (e.g., `processPayment`, `calculateTaxEvasion`) - API endpoints and internal routes (e.g., `/api/v1/internal/user-data`) - Type information and data structures - Comments and docstrings (unless stripped) - File paths revealing project structure or codenames **Recommendations**: 1. Always review output before sending to external services 2. Use `--docstrings=0` to remove potentially sensitive documentation (regular comments are already off by default, `--comments=0`) 3. Consider running a secrets scanner on your codebase first 4. For maximum security, run AI Distiller in an isolated environment 5. Future: We're exploring an `--obfuscate` flag to anonymize sensitive identifiers ## πŸ› οΈ Advanced Usage ### ⚑ Parallel Processing AI Distiller now supports parallel processing for significantly faster analysis of large codebases: ```bash # Use default parallel processing (80% of CPU cores) aid ./src # Force serial processing (original behavior) aid ./src -w 1 # Use specific number of workers aid ./src -w 16 # Check performance with verbose output aid ./src -v # Shows on stderr: "INFO: Using 25 parallel workers (32 CPU cores available)" ``` **Performance Benefits**: - React packages: 3.5s β†’ 0.5s (7x faster) - Large codebases: Near-linear speedup with CPU cores - Maintains identical output order as serial processing ### Processing from stdin AI Distiller can process code directly from stdin, perfect for: - Quick code snippet analysis - Pipeline integration - Testing without creating files - Dynamic code generation workflows ```bash # Auto-detect language from stdin printf 'class User:\n def get_name(self) -> str:\n return self.name\n' | aid # Explicit language specification cat mycode.php | aid --lang php --private=1 # Use "-" to explicitly read from stdin aid - --lang python < snippet.py # Pipeline example: extract structure from generated code generate-code.sh | aid --lang typescript --format json-structured ``` Stdin output goes to stdout. A path argument wins over piped stdin, so detach stdin (` classes.txt # Extract API surface for documentation aid ./api --docstrings=0 --format md -o api-ref.md # Extract only method signatures (no fields/properties) - great for large codebases aid ./src --fields=0 -o methods-only.txt # Extract only data structures (no method noise) aid ./models --methods=0 --stdout > data-structures.txt # Focus on public API methods only aid ./services --fields=0 --stdout ``` ### 🚫 Ignoring Files with .aidignore AI Distiller respects `.aidignore` files for excluding files and directories from processing. The syntax is similar to `.gitignore`. #### Important: What AI Distiller Processes AI Distiller only processes source code files with these extensions: - **Python**: `.py`, `.pyw`, `.pyi` - **JavaScript**: `.js`, `.mjs`, `.cjs`, `.jsx` - **TypeScript**: `.ts`, `.tsx`, `.d.ts` - **Go**: `.go` - **Rust**: `.rs` - **Ruby**: `.rb`, `.rake`, `.gemspec` - **Java**: `.java` - **C#**: `.cs` - **Kotlin**: `.kt`, `.kts` - **C++**: `.cpp`, `.cc`, `.cxx`, `.c++`, `.h`, `.hpp`, `.hh`, `.hxx`, `.h++` - **PHP**: `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, `.php7`, `.phps`, `.inc` - **Swift**: `.swift` **Note**: Files like `.log`, `.txt`, `.md`, images, PDFs, and other non-source files are automatically ignored by AI Distiller, so you don't need to add them to `.aidignore`. #### Default Ignored Directories AI Distiller automatically ignores these common dependency and build directories: - `node_modules/` - npm packages - `vendor/` - Go and PHP dependencies - `target/` - Rust build output - `build/`, `dist/` - Common build directories - `__pycache__/`, `.pytest_cache/`, `venv/`, `.venv/`, `env/`, `.env/` - Python - `.gradle/`, `gradle/` - Java/Kotlin - `Pods/` - Swift/iOS dependencies - `.bundle/` - Ruby bundler - `bin/`, `obj/` - Compiled binaries - `.vs/`, `.idea/`, `.vscode/` - IDE directories - `coverage/`, `.nyc_output/` - Test coverage - `bower_components/` - Legacy JavaScript - `.terraform/` - Terraform - `.git/`, `.svn/`, `.hg/` - Version control You can override these defaults using `!` patterns in `.aidignore` (see Advanced Usage below). #### Basic Syntax Create a `.aidignore` file in your project root or any subdirectory: ```bash # Comments start with hash *.test.js # Ignore test files *.spec.ts # Ignore spec files temp/ # Ignore temp directory build/ # Ignore build directory /secrets.py # Ignore secrets.py only in root node_modules/ # Ignore node_modules everywhere **/*.bak # Ignore .bak files in any directory src/test_* # Ignore test_* files in src/ !important.test.js # Don't ignore important.test.js (negation) ``` #### How It Works - `.aidignore` files work recursively - place them in any directory - Patterns are relative to the directory containing the `.aidignore` file - Use `/` prefix for patterns relative to the `.aidignore` location - Use `**` for recursive matching - Directory patterns should end with `/` - Use `!` prefix to negate a pattern (re-include previously ignored files) #### Examples ```bash # .aidignore in project root node_modules/ # Excludes all node_modules directories *.test.js # Excludes all test files *.spec.ts # Excludes all spec files dist/ # Excludes dist directory .env.py # Excludes environment config files vendor/ # Excludes vendor directory # More specific patterns src/**/test_*.py # Test files in src subdirectories !src/test_utils.py # But include this specific test file /config/*.local.py # Local config files in root config dir **/*_generated.go # Generated Go files anywhere ``` #### Advanced Usage: Including Normally Ignored Content ##### Include Default-Ignored Directories Use `!` patterns to include directories that are ignored by default: ```bash # Include vendor directory for analysis !vendor/ # Include specific node_modules package !node_modules/my-local-package/ # Include Python virtual environment !venv/ ``` ##### Include Non-Source Files You can also include files that AI Distiller normally doesn't process: ```bash # Include all markdown files !*.md !**/*.md # Include configuration files !*.yaml !*.json !.env # Include specific documentation !docs/**/*.txt !README.md !CHANGELOG.md ``` When you include non-source files with `!` patterns, AI Distiller will include their raw content in the output. #### Nested .aidignore Files You can place `.aidignore` files in subdirectories for more specific control: ```bash # project/.aidignore *.test.py !vendor/ # Include vendor in this project # project/src/.aidignore test_*.go *.mock.ts !test_helpers.ts # Exception: include test_helpers.ts ``` ### 🎯 Git History Analysis Mode AI Distiller includes a special mode for analyzing git repositories. When you pass a `.git` directory, it switches to git log mode: ```bash # View formatted git history aid .git # Limit to recent commits (default is 200) aid .git --git-limit=500 # Include AI analysis prompt for comprehensive insights aid .git --git-limit=1000 --with-analysis-prompt ``` The `--with-analysis-prompt` flag adds a sophisticated prompt combined with git history that AI agents can use to generate: - **Contributor statistics** with expertise areas and collaboration patterns - **Timeline analysis** with development phases and activity visualization - **Functional categorization** of commits (features, fixes, refactoring) - **Codebase evolution insights** including technology shifts - **Actionable recommendations** based on discovered patterns The output file contains both the analysis prompt and formatted git history, ready for AI agents to process. Perfect for understanding project history, identifying knowledge silos, or generating impressive development reports. ## ❓ FAQ
How accurate are the token counts? Token counts are estimates, not tokenizer output: they are computed as bytes / 4 (1 token β‰ˆ 4 characters). Sizes in the summary are measured (the source file size on disk and the size of the distilled output). Actual token usage varies by model and by language, typically by around Β±10% or more.
Can AI Distiller handle very large repositories? Yes! We've tested on repositories with 50,000+ files. The parallel processing mode (`-w` flag) scales linearly with CPU cores. Memory usage is bounded - large files are processed in streaming chunks.
What about generated code and vendor directories? Create a `.aidignore` file (same syntax as `.gitignore`) to exclude generated files, vendor directories, or any paths you don't want processed.
What happens with unsupported file types? Files with unknown or unsupported extensions are automatically skipped - no errors, no interruption. AI Distiller only processes files it has parsers for, ensuring clean and relevant output. This means you can safely run it on mixed repositories containing documentation, images, configs, etc.
Is my code sent anywhere? No! AI Distiller runs 100% locally. It only extracts and formats your code structure - you decide what to do with the output. The tool itself makes no network connections.
Which programming languages are supported? Currently 12 languages: Python, TypeScript, JavaScript, Go, Java, C#, Rust, Ruby, Swift, Kotlin, PHP, C++. Parsers are bundled in the binary - no external dependencies needed. See [How It Works](#-how-it-works) for which parser each language uses.
## 🀝 Contributing We welcome contributions! See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines. ### Development Setup Prerequisites, build and test commands are in [CONTRIBUTING.md](CONTRIBUTING.md). ### Releases Releases are built by [`.github/workflows/release.yml`](.github/workflows/release.yml), which runs when a maintainer pushes a `vX.Y.Z` tag (or starts the workflow manually with that tag). The procedure is in [`.claude/skills/aid-release-mcp/SKILL.md`](.claude/skills/aid-release-mcp/SKILL.md) and [`release-runbook.md`](.claude/skills/aid-release-mcp/references/release-runbook.md). ## πŸ“„ License MIT License - see [LICENSE](LICENSE) for details. ## πŸ™ Acknowledgments - Built on [tree-sitter](https://tree-sitter.github.io/) for accurate parsing - Inspired by the need for better AI-code interaction - Created with ❀️ by Claude Code & JΓ‘n RegeΕ‘ from [SiteOne](https://www.siteone.io/) (Czech Republic).