aeroxy/ast-bro
소개
A fast, AST-based code navigation toolkit that maps file shapes, public APIs, and call graphs across coding languages. Designed to help coding agents and humans explore codebases, analyze blast radius, and generate token-budgeted context with massive token savings.
개발 도구측정된 스타 증가
- in 24h
- 0
- in 7 days
- +1
- in 15 days
- +8
- in 1 month
- 기록 수집 중
서로 겹치는 기간의 순증가량이며 일별 합계가 아닙니다. 측정값이 없으면 비워 둡니다. 스타는 관심도를 나타내며 품질을 보장하지 않습니다.
README.md
Originalast-bro
Fast, AST-based code-navigation toolkit for source files — surface the shape of a file (signatures with line numbers, no method bodies), the true public API of a package, the dependency graph between files, the call graph between symbols, search the repo by symbol or behaviour, the blast radius of touching a symbol, a token-budgeted context pack for any symbol, what a change touched between two commits and the history of one declaration, and squeeze repetitive logs into a smaller, reversible form. Twenty-three analysis subcommands, one binary, built for LLM coding agents and humans who’d rather not waste tokens reading every file just to understand a codebase.
ast-bro is written in Rust and uses ast-grep’s incredibly fast tree-sitter bindings. Thanks to rayon, it parses your entire workspace concurrently—often in milliseconds. For Google- or ByteDance-scale monorepos, ast-bro benefits from the additional abstraction layer provided by repolayer.
Renamed from
ast-outline(v2.1.x and earlier). The project outgrew "outline" — it now ships dep graphs, call graphs, hybrid semantic search, true public API resolution, and a structural search/rewrite engine, not just structural outlining. The old name also collided with an unrelated VS Code extension and an npm package — too generic to keep.Upgrading from
ast-outline? Run anyast-brocommand once and it will auto-migrate.ast-outline/→.ast-bro/(cache),.ast-outline-ignore→.ast-bro-ignore(per-repo filter),~/.cache/ast-outline/→~/.cache/ast-bro/(model cache), and anyast-outlineentries in your MCP config →ast-bro. The legacyast-outlinebinary is still installed as a thin proxy that execs intoast-bro, and a shortersbalias ships alongside, so existing scripts keep working.
Purpose
ast-bro exists to make LLM coding agents faster, cheaper, and smarter when navigating unfamiliar code.
Modern agentic coding tools explore codebases by reading files directly. That's reliable but has a massive cost: on a 1000-line file, the agent pays for 1000 lines of tokens just to answer "what methods exist here?" — and reading is only one of several questions an agent has. "Who imports this?" "What's the public API?" "Are there cycles?" "Where in the repo is the login flow?" — each one historically required dozens of file reads or noisy greps.
ast-bro collapses each of those questions into a single command:
- Shape over bytes.
map/digest/showgive you signatures and line ranges instead of method bodies — typically a 95% token saving vs reading the file.implementsfinds subclasses with AST accuracy, nogrepfalse positives. - Published API in one call.
surfaceresolvespub usere-exports (Rust),__all__(Python), barrel files (TypeScript),exportclauses (Scala) so you see the surface a downstream user actually sees — not the union of every public item per file. - Dependency graph for free.
deps/reverse-deps/cycles/graphbuild a file-level import graph (Rust, Python, TS/JS, Java, C#, Kotlin, Scala, Go, Elixir) cached at.ast-bro/graph/. Usereverse-depsbefore refactoring to know the blast radius.cyclesexits non-zero — wire it into a CI gate.graphemits the full dependency graph (text by default,--jsonfor JSON). - Symbol-level call graph.
callers/calleesanswer "who calls X" and "what does X call" with AST accuracy across 13 languages (every supported language but SQL and Markdown) — nogrepfalse positives on overloaded names, comments, or string literals. Both are kind-aware: ask for a function and you get call-sites; ask for a type and you get implementors / constructions / ancestors. A three-pass resolver (same-file → global symbol table → dep-graph disambiguation) tags every edgeExact/Inferred/Ambiguousso you can filter by precision.trace <FROM> <TO>walks the shortest static call path between two symbols, inlining each hop's body — "how does X reach Y?" answered in one call instead of chainingcallees. Same on-disk cache as the dep graph. - Hybrid semantic search.
searchruns BM25 + dense embeddings viapotion-code-16M(a static, no-inference model — ~64 MB, runs on CPU in microseconds).find-relatedreturns chunks structurally similar to one you already have, with a dep-graph-aware boost when a graph cache exists. - Blast radius in one shot.
impact <symbol>combines callers, callees, file-level deps, file-level reverse-deps, transitive callers at--depth N, and test-file detection into one "what would break?" report — replaces a chain of four round-trips with a single call. Four--modevariants:all(default),deps,dependents,tests.--tests/--exclude-testsnarrow the filter. Works for both callables and types. - Token-budgeted context.
context <symbol> --budget Npacks "everything an LLM needs to understand this symbol" into a caller-supplied token budget: target body first, then direct callees (bodies while budget permits, signatures otherwise), direct callers (signatures), transitive callees/callers at depth 2 (signatures only). For types: type body, implementors, methods, callers-of-methods. Flagstruncatedwhen budget ran short andtarget_omittedwhen even the target body didn't fit. Same data as four or fiveshow/callers/calleescalls, one round-trip, budget-bounded. - Squeeze logs, not just code.
squeezecompresses a repetitive log/text file into a smaller, reversible form (a legend plus short tags) so a noisy log costs far fewer tokens to hand to an agent — and falls back to the raw text when squeezing wouldn't help. This is for logs/text, not code (for code,map/digest/showare the token win). - Review a change by declaration.
difflists the declarations a commit range (or your uncommitted work) added, removed, modified, moved or renamed, and which part of each changed —sig,vis,docs,attrs,bases,body,value, orformat(whitespace or comments only) — with both signatures when one changed: the table of contents of a change at a fraction ofgit diff's size.reviewreads that against the call graph: every call site of a changed signature and whether the change updated it, removed declarations still named, types whose members changed with their construction sites, and which tests statically reach what changed.logfollows one declaration through history by syntax tree (through renames and moves, wheregit log -Lfollows a line range),blamecredits each declaration to the last commit that changed it in more than formatting, and--revreadsmap/digest/showat any commit without checking it out. - Twenty-three native MCP tools. Every analysis command is also exposed as an MCP tool —
ast-bro install --target <agent> --mcpwires it into Claude Code, Cursor, Gemini, Codex, OpenCode, Pi, or VS Code Copilot in one line.
The workflow
Before ast-bro:
Agent: Read Player.cs # 1200 lines of tokens
Agent: Read Enemy.cs # 800 lines of tokens
Agent: Read DamageSystem.cs # 400 lines of tokens
Agent: grep "IDamageable" src/ # noisy, lots of false matches
...
With ast-bro:
Agent: ast-bro surface . # one-page true public API of the crate/package
Agent: ast-bro digest src/Combat # ~100 lines, whole module's structure
Agent: ast-bro implements IDamageable # precise list, no grep noise
Agent: ast-bro search "damage handling" # hybrid BM25 + dense semantic, ranked
Agent: ast-bro show Player.cs TakeDamage # just the method body
Agent: ast-bro reverse-deps Player.cs # who imports this — blast radius before refactor
Agent: ast-bro callers Player.TakeDamage # AST-accurate call sites — no grep false positives
Agent: ast-bro callees Player.TakeDamage # what TakeDamage itself calls
Agent: ast-bro impact Player.TakeDamage # callers + callees + file deps + tests, one call
Agent: ast-bro context Player.TakeDamage --budget 2000 # everything an LLM needs, token-bounded
Agent: ast-bro cycles src/ # find import cycles via Tarjan SCC
Agent: ast-bro review main # what this branch changed, and what that touches
Result: same understanding, a fraction of the tokens, a fraction of the round-trips.
For "what does this package actually expose?" — historically the most expensive question, since the answer was "read every file" — surface resolves the re-export graph and gives you the answer directly, often replacing dozens of file reads with a single call. For "what would break if I change this method?" — callers gives you the AST-accurate set of call sites in one shot, instead of grep-ing a homonym across the repo.
Supported languages
| Language | Extensions |
|---|---|
| Rust | .rs |
| C# | .cs |
| C++ | .cpp, .cc, .cxx, .hpp, .hh |
| Python | .py, .pyi |
| TypeScript | .ts, .tsx |
| JavaScript | .js, .jsx, .mjs, .cjs |
| Java | .java |
| Kotlin | .kt, .kts |
| Scala | .scala, .sc |
| Go | .go |
| PHP | .php |
| Ruby | .rb |
| Elixir | .ex, .exs |
| SQL | .sql, .ddl, .dml |
| Markdown | .md, .markdown, .mdx, .mdown |
More coming soon! Adding another language is a single new adapter file leveraging the massive ast-grep language ecosystem.
For Markdown the "symbols" are headings and fenced code blocks, plus a leading
YAML frontmatter block: --- frontmatter shows up in map and digest with
its line range, and frontmatter is a show handle
(ast-bro show tasks/ frontmatter collects every card's block in one call).
Only a --- fence on the file's first line counts — a --- further down stays
an ordinary horizontal rule. Trailing whitespace on either fence and a leading
UTF-8 BOM are tolerated; ... closes a block as well as ---. TOML
frontmatter (+++) is not surfaced.
What gets walked
ast-bro skips a lot of files when walking a directory — by design. Filters apply uniformly across every subcommand.
.gitignoreand friends — every level's.gitignore, your global gitignore,.git/info/exclude, and.ignorefiles (theignorecrate's convention used byripgrep/fd).Hardcoded denylist — directories almost no one wants walked, even if
.gitignoredoesn't list them:.git,node_modules,target,dist,build,__pycache__,.venv,venv,.cache,.idea,.vscode,.next,.nuxt,.turbo,.parcel-cache,.gradle,.tox,.mypy_cache,.pytest_cache,.ruff_cache,.eggs,.ast-bro, and a few others..ast-bro-ignore— per-repo escape hatch. Same syntax as.gitignore. Useful for excluding paths from ast-bro that you don't want excluded from git itself, e.g. test fixtures or vendored corpora:# .ast-bro-ignore tests/fixtures/large_corpus/ benches/data/ *.generated.rsExtension allowlist — files are only opened if their extension is one ast-bro knows how to parse (the table above for map/digest/show/implements; a broader set for the search commands). Explicitly-passed extensionless files fall back to shebang detection (
#!/usr/bin/env python3→ Python,#!/usr/bin/ruby→ Ruby,#!/usr/bin/env elixir→ Elixir,#!/usr/bin/env node→ TypeScript, etc.) — so CLI scripts like~/.local/bin/my-scriptorbin/deploywork without an extension. Directory walks do not open extensionless files; the shebang is only consulted for explicit inputs to keep the walk fast.
Want to see exactly what ast-bro walks? Compare ast-bro digest some/dir with rg --files some/dir — anything in rg but not the digest is being filtered by one of the layers above.
Install
Homebrew (macOS)
brew install aeroxy/tap/ast-bro
npm
npm install -g @ast-bro/cli
Pre-built binaries are available for macOS ARM64 and Windows x64. On Windows 10/11, run this command in PowerShell or Command Prompt with Node.js 18+ installed; Rust, Visual Studio, and a separate unzip installation are not required. All three commands (ast-bro, ast-outline, and sb) are installed.
pip
pip install ast-bro
Or install into an isolated tool environment with uv tool install ast-bro. The Python installer supports the same pre-built platforms and downloads the binary on first use.
Release builds and package smoke tests are documented in docs/releasing.md.
Cargo
cargo install ast-bro
This installs the ast-bro CLI globally into ~/.cargo/bin — make sure that's on your PATH.
Nix
You can run ast-bro directly with Nix without installing:
nix run github:aeroxy/ast-bro
Or add it as a dependency in your Nix flake:
{
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
ast-bro.url = "github:aeroxy/ast-bro";
};
outputs = { self, nixpkgs, ast-bro }:
let
system = "x86_64-linux";
pkgs = nixpkgs.legacyPackages.${system};
in {
devShells.${system}.default = pkgs.mkShell {
buildInputs = [ ast-bro.packages.${system}.default ];
};
};
}
Quick start
# Map the structure of one file
ast-bro map path/to/Player.rs
ast-bro map path/to/user_service.py
# Map a whole directory (recurses supported extensions in parallel)
ast-bro map src/
# Print the exact source of one specific method
ast-bro show Player.cs TakeDamage
# Don't know which file it's in? Point at the directory (or a quoted glob)
ast-bro show src/ TakeDamage
ast-bro show 'src/**/*.cs' TakeDamage
# Compact public-API map of a whole module
ast-bro digest src/Services
# True public surface (resolves `pub use` / `__all__`, not every `pub` item)
ast-bro surface . # auto-detect Cargo.toml / pyproject.toml / __init__.py
ast-bro surface --tree --include-chain mycrate/
# Every class that inherits/implements a given type
ast-bro implements IDamageable src/
# Dependency graph: forward, reverse, cycles, full
ast-bro deps src/auth.rs --depth 2 # what auth.rs imports (transitively)
ast-bro reverse-deps src/auth.rs # who imports auth.rs (refactor blast radius)
ast-bro cycles # find import cycles via Tarjan SCC
ast-bro graph . # full dependency graph (text)
ast-bro graph . --json # same, as JSON (ast-bro.graph.v1)
# Call graph: who calls X, what does X call (AST-accurate, 13 langs, not SQL or Markdown)
ast-bro callers TakeDamage # function/method: in-edges
ast-bro callers --tests TakeDamage # same, only test callers (test files, #[test], #[cfg(test)] modules)
ast-bro callers --hide-ambiguous TakeDamage # drop ambiguous call edges
ast-bro callers Player # type: implementors + constructions
ast-bro callees Player.TakeDamage # function/method: out-edges
ast-bro callees --hide-external Player.TakeDamage # drop unresolved + external callees
ast-bro callees Player --depth 2 # type: ancestor walk (transitive)
ast-bro callers src/Player.cs:TakeDamage
ast-bro trace handle_request render # shortest static call path, each hop inlined
# Blast radius of touching a symbol (one command: callers + callees + file deps + tests)
ast-bro impact TakeDamage # default --mode all (every section)
ast-bro impact Player --depth 3 # deeper transitive window
ast-bro impact TakeDamage --mode tests # only the affected tests section
ast-bro impact TakeDamage --tests # apply tests filter to every section
ast-bro impact TakeDamage --exclude-tests # drop test code from every section
# Token-budgeted context pack for a symbol (target + callees + callers + transitive)
ast-bro context TakeDamage # default budget 8000 tokens
ast-bro context TakeDamage --budget 2000 # tight pack for smaller LLM windows
ast-bro context Player --json # schema: ast-bro.context.v1
ast-bro context Job --kind type # a function and a type share the name: pick the type
# Hybrid BM25 + dense semantic search (builds an index on first call)
ast-bro search "how does login work"
ast-bro search "HandlerStack" -k 5
# Find code semantically similar to a given file:line
ast-bro find-related src/auth/login.rs:42
# Build / refresh / inspect the per-repo search index
ast-bro index # build or refresh
ast-bro index --stats # show chunk count, model, etc.
ast-bro index --rebuild # drop cache and rebuild
# Review a change, declaration by declaration
ast-bro diff # your uncommitted work (untracked files included) vs HEAD
ast-bro diff main # what this branch changed since it left main (main...HEAD)
ast-bro diff v1.2..v1.3 -- src/ # a range, limited to paths
ast-bro review main # callers left behind, constructions, tests that reach it
ast-bro log load_config # every commit that changed one declaration
ast-bro log Player.TakeDamage -p # with its own hunk on each commit
ast-bro blame src/player.rs # last real change per declaration (skips reformats)
ast-bro show --rev v1.2 src/player.rs TakeDamage # a symbol as it was, no checkout
# Squeeze a repetitive log/text file into a smaller, reversible form (logs, not code)
ast-bro squeeze app.log # compress; falls back to raw if it wouldn't help
ast-bro squeeze app.log 1000:2000 # only a line range
ast-bro squeeze app.log --raw # skip compression (raw + header, for diffing)
ast-bro squeeze app.log --json # ast-bro.squeeze.v1 (legend + body + sizes)
# Output a prompt snippet to steer LLM agents
ast-bro prompt >> AGENTS.md
# Machine-readable JSON (stable schema, great for tooling)
ast-bro map src/player.rs --json
ast-bro digest src/ --json
ast-bro show Player.cs TakeDamage --json
ast-bro implements IDamageable src/ --json
ast-bro search "json rendering" --json
Using with LLM coding agents
This is the main use case. The fastest path is ast-bro install,
which writes the agent prompt snippet (and, where supported, a real
Read-interceptor hook) into your coding agent's config.
# Install into every supported CLI it can detect on your system.
ast-bro install --all
# Or pick a single target.
ast-bro install --target claude-code
ast-bro install --target gemini --min-lines 150
# OpenCode prompt, MCP server, and native skill.
ast-bro install --target opencode
ast-bro install --target opencode --mcp --skills
# Pi prompt and read-interceptor extension, then MCP server and skill.
ast-bro install --target pi
ast-bro install --target pi --mcp --skills
# See exactly what would change before writing.
ast-bro install --all --dry-run
# Per-repo install (default is global).
ast-bro install --target claude-code --local
# Remove everything we wrote.
ast-bro uninstall --all
# Quick visibility.
ast-bro status
Supported targets: claude-code, gemini, tabnine, cursor,
aider, codex, copilot, opencode, pi. Claude Code, Gemini, and Tabnine also get
a tool-call hook that intercepts Read on supported source files above
--min-lines (default 200) and substitutes the map output. On Claude
Code it also covers a read the host refuses outright, at any line count.
Pi has no hook configuration, so its hook is a Pi extension
(<agent-dir>/extensions/ast-bro.ts, or .pi/extensions/ with --local)
that intercepts read the same way through ast-bro hook --protocol claude-code.
Pi's agent directory is $PI_CODING_AGENT_DIR, else ~/.pi/agent.
The other targets do not install a read-interceptor hook.
The substitution reaches the agent as a blocked tool call whose first line says that nothing failed. For a read that has not run yet, that is the only channel available: the map has to arrive instead of the file, so the read must be refused, and a refusal is what the host reports.
Claude Code has a second event that would report a success instead,
PostToolUse with hookSpecificOutput.updatedToolOutput, and
ast-bro install does not register it. Measured on Claude Code 2.1.223:
that field replaces the result of an MCP tool and is ignored for the
built-in Read, so registering it would deliver no map and send the
whole file to the model. Registering a PostToolUse entry by hand does
nothing useful for Read on that version, for the same reason. See
issue #34.
On Claude Code the hook also registers under PostToolUseFailure, for
the read the host refuses outright — measured against its file-size
limit, 256 KB on Claude Code 2.1.223. That limit counts bytes, not lines,
so it catches files no --min-lines threshold does: a 90-line file of
355 KB trips it. Without this the agent gets a bare error and nothing
else. That event cannot replace a result, only add context, which is all
the map needs when the result carries no file contents. Nothing is
blocked on that path: the host already failed the call, so the map
arrives beside the error rather than in place of anything.
The map is capped at 64 KB, notice included, except beside a failed
read: Claude Code caps a hook's additionalContext at 10,000 characters
and past that hands the model a file path and a 2,000-character preview
instead, so the PostToolUseFailure payload is held to 9,000 bytes. A
refusal's reason has no such cap; Claude Code 2.1.331 delivered a 65 KB
one whole. A map that would run over can shed detail — doc comments and attributes first, then fields and
private items, with a per-type member cap as a last backstop that rarely
comes up — or keep the detail and drop whole entries instead. Which one
you get is decided by how many declarations each delivers, not by which
fits first: a mostly-private file would fit the moment private items
went, and hand you the public few, so it is trimmed at a richer level
instead.
A trim spends the budget in the order that ladder ranks: whatever survives
furthest down it goes in first, so a file's public surface is what the
budget buys before anything else — all of it, unless the public surface
alone is over the cap. Filling in file order instead handed back 1733
private items and none of that file's 500 public ones, because the
publics ran to the end of a file twice the budget. What a
trim drops, it drops entire — a declaration leaves with its doc comment
and its members, rather than leaving them to read as someone else's. The
payload opens with a note saying what is missing and the ast-bro map
command that returns it, so a host that cuts a payload down to its start
still shows it.
Claude Code subagent shadowing
Claude Code has isolated subagents (Explore, Plan, general-purpose) that run in
their own context and cannot see the main CLAUDE.md. ast-bro install
automatically shadows these subagents with .claude/agents/<Name>.md files
containing the full ast-bro prompt.
When you run ast-bro install --target claude-code, you get:
CLAUDE.md— main agent prompt (global or local per-repo).claude/settings.json—Readhooks onPreToolUseandPostToolUseFailure.claude/agents/Explore.md— Explore subagent with the prompt injected
This solves the "why doesn't my subagent use ast-bro?" problem — subagents
now get the prompt automatically. Legacy manual ~/.claude/agents/Explore.md files
are wrapped in marker blocks in-place (non-breaking).
A new Explore.md limits the agent to tools: Read, Grep, Glob, Bash, so it
has no Edit or Write tool. It keeps Bash because it runs sb through it, and
Bash can still change files: the agent is a search agent by its tools and its
prompt, not read-only by guarantee. The file names no model, so the agent
runs on the model Claude Code gives it. A re-install replaces the frontmatter
an earlier version wrote, if it is still as written; a frontmatter you edited,
or your own tools line, stays as it is. If that frontmatter has no tools
line, install prints a # note: that says so and changes nothing.
Skills for manual installation
A skills/ folder is included in the repo for users who prefer manual setup:
# Clone or download the repo
git clone https://github.com/aeroxy/ast-bro.git
cd ast-bro
# Copy the skill to your user skills directory
cp -r skills/ast-bro ~/.claude/skills/ast-bro
# Then manually invoke from Claude Code
/ast-bro
This works alongside ast-bro install — the skill definition tells Claude Code
how to invoke the ast-bro CLI with proper tool schemas and documentation.
Manual install via ast-bro prompt (e.g. project-level):
ast-bro prompt >> AGENTS.md
ast-bro prompt | pbcopy # macOS clipboard
Works with
- Claude Code (+ custom subagents like
Explore,codebase-scout) - Cursor agent mode
- OpenCode
- Pi
- Aider
- Copilot Chat / Workspace
- Any custom agent on the Claude / OpenAI / Gemini APIs
- Humans (the colored terminal format is highly readable;
showis a nice alternative togrep -A 20)
Output format
The format is designed to be LLM-friendly: Python-style indentation,
line-number suffixes in L<start>-<end> form, doc-comments preserved.
The header summarises scale and flags partial parses.
When you run it yourself, you'll see a gorgeous ANSI-colored output. Don't worry, the terminal colors are automatically stripped when piped to a file or consumed by an agent's shell hook!
Rust
# src/core.rs (490 lines, 3 types, 12 methods, 5 fields)
pub struct Declaration L10-120
pub kind: DeclarationKind L12
pub name: String L15
pub fn lines_suffix(&self) -> String L30-48
show across a file, a directory, or a glob
A show target is a file, a directory, or a quoted glob, so you can extract a
symbol you can name from a tree you haven't mapped yet:
ast-bro show src/ TakeDamage # searches every parseable file
ast-bro show 'src/**/*.cs' TakeDamage # quote it — see below
ast-bro show a.java b.java greet # an explicit list works too
A multi-file answer leads with its coverage, and caps rendered bodies at
--limit 20 while still reporting the true total:
# 3 match(es) for 'greet' in 2 of 47 file(s) searched
With several names, every name that matched keeps at least one body under the
cap, so a common name cannot crowd out a rarer one, and a capped header names
what it cut (showing 3; new: 2 of 3); --json carries the same counts per
name in per_symbol.
Unquoted globs are recovered, not misread. The shell expands
show src/*.cs Widget before ast-bro starts, so the extra file names arrive
in the argument list; they are taken as targets rather than as symbol names,
and a note reminds you to quote the glob. Previously that spelling searched
only the first file and dropped the symbol's other definitions silently.
show with ancestor context
ast-bro show <target> <Symbol> prints a # in: ... breadcrumb
between the header and the body so you know what the extracted code is
nested inside, without a second map call:
# Player.cs:30-48 Game.Player.PlayerController.TakeDamage (method)
# in: namespace Game.Player → public class PlayerController : MonoBehaviour, IDamageable
/// <summary>Apply damage.</summary>
public void TakeDamage(int amount) { ... }
JSON output
Add --json to any command to get the full symbol graph as stable,
structured JSON instead of formatted text — ideal for editors, language
servers, CI tooling, or any script that needs to consume the data
programmatically.
ast-bro map src/player.rs --json # per-file map
ast-bro digest src/ --json # digest view
ast-bro show Player.cs TakeDamage --json
ast-bro implements IDamageable src/ --json
ast-bro map src/ --json --compact # single-line (no pretty-print)
Every JSON document includes a schema field that is bumped on breaking
changes, so downstream tooling can guard on it:
{
"schema": "ast-bro.map.v1",
"files": [
{
"path": "src/player.rs",
"language": "rust",
"line_count": 312,
"error_count": 0,
"declarations": [
{
"kind": "struct",
"name": "Player",
"signature": "pub struct Player",
"visibility": "pub",
"start_line": 10,
"end_line": 40,
"children": [ ... ]
}
]
}
]
}
| Schema | Command |
|---|---|
ast-bro.map.v1 |
map --json, digest --json |
ast-bro.show.v2 |
show --json |
ast-bro.implements.v1 |
implements --json |
ast-bro.surface.v1 |
surface --json |
ast-bro.deps.v1 |
deps --json |
ast-bro.reverse-deps.v1 |
reverse-deps --json |
ast-bro.cycles.v1 |
cycles --json |
ast-bro.graph.v1 |
graph --json |
ast-bro.callers.v1 |
callers --json |
ast-bro.callees.v1 |
callees --json |
ast-bro.trace.v1 |
trace --json |
ast-bro.impact.v1 |
impact --json |
ast-bro.context.v1 |
context --json |
ast-bro.search.v1 |
search --json |
ast-bro.related.v1 |
find-related --json |
ast-bro.index-stats.v1 |
index --stats --json |
ast-bro.run.v1 |
run --json |
ast-bro.squeeze.v1 |
squeeze --json |
ast-bro.error.v1 |
any rejected call under --json (on stderr) |
show is the one schema past v1. v1 → v2: the top-level path /
language / matches keys moved into a files array (one entry per file,
same three keys), because a target can now be several files rather than only
one. Alongside it, v2 adds the counters the text coverage header carries —
files_scanned, files_matched, total, shown, truncated — plus
unmatched, an array of the requested symbols that matched nothing. That one
is not a counter and is not in the text header: on the CLI it surfaces as a
stderr note. A v1 consumer reading one explicit file migrates by taking
files[0].
CLI contract
One rule set for every subcommand, so a consumer never needs a per-command table:
- Channel — stdout carries results only; every note, hint, and error goes to stderr.
--jsonoutput always parses without preprocessing. - Exit codes —
0: the query ran; the answer may be legitimately empty ("this symbol genuinely has no callers"), and any qualification — a path that didn't resolve, a display cap, a depth cutoff — is reported as a# note:on stderr, so read the notes before treating exit-0 output as exhaustive.2: the query could not run as asked — no such path, no such symbol, unknown flag, missing argument, or an empty argument list (e.g. a$(...)substitution that produced nothing).1: internal failure. Two deliberate additions:cyclesexits3when cycles exist, andrunexits1when a valid pattern matched nothing, following thegrep/ripgrepconvention — arunthat was rejected still exits 2 with empty stdout. - Machine-readable rejections — with
--json, a rejected call also emits anast-bro.error.v1object on stderr:{schema, command, kind, detail, hint}withkind∈no_input | path_not_found | symbol_not_found | unknown_flag | bad_argument | index_error. - Unknown flags exit 2 with the error on stderr; when the flag exists on a sibling subcommand, the message names it (
--glob is a map flag). - Truncation is never silent — when
--limit/--max-memberscut a list, the header reports the true total and the flag that lifts the cap, and JSON carriestotal/truncated;map --max-membersreports its cut astruncatedanddropped_membersper file.--limitbounds the display, not the work:callers/impact/reverse-depswalk the full reverse cone so the reported total is exact, which at--depth 5on a large repository is real work regardless of the cap. - A depth cutoff says so too — a walk that ran out of
--depthand one that ran out of graph both just stop, so every depth-bounded command reports which happened:frontier_truncatedin JSON (callers,callees,deps,reverse-deps,trace, and eachimpactreport), plus a stderr note in text mode. It is orthogonal totruncated:truncated: falsewithfrontier_truncated: truemeans nothing was cut from the display andtotalitself counts only the cone inside--depth. Ontrace, it separates "no path" from "no path within--depth".
map and digest are one command: digest is an alias for map --preset digest (= --detail names --no-private --no-fields --max-members 50), and both accept the full flag set — detail (--detail names|signatures|full), visibility (--no-private, --no-fields, --no-docs, --include-private, --include-fields, …), and scope (--glob, --max-members) are independent axes. Explicit flags override the preset. --no-fields covers every field-like member — a plain field, but also a C# property or event, a Python @property, and a Markdown code block — on all three renderers, so digest, which sets it, lists none of them unless you pass --include-fields. The projection flags shape the JSON payload as well as the text: --no-private and --no-fields drop declarations from it, --no-docs removes docs / docs_inside / doc_start_byte, --no-lines the line and byte offsets, --no-attrs the attrs key. Detail below full sheds doc comments the same way, which are routinely a third of the payload's weight — including under digest, where the preset opts in on the caller's behalf. Any payload with keys removed carries a projected object ({docs, line_numbers, attributes}) so a consumer can guard on it instead of inferring the absence; an unprojected payload has no such key and is byte-identical to before.
A [group] line in map output is a comment on the enclosing block, not on the symbol below it. Go's const ( … ), var ( … ) and type ( … ) take a doc comment of their own — one sentence covering every member — and printing it bare above the first member is how it gets mistaken for that member's own. In JSON it is group ({docs, start_line, end_line}), carried by every member of the block and by no member's docs, so "what documents this symbol" and "what documents the block it lives in" are two questions with two answers. Go merges the two answers in one place: go doc documents a type in a type ( … ) block that has no comment of its own with the block's comment, so for such a type read group where docs is empty. It is documentation, so it sheds with docs when documentation is projected out (--no-docs, --detail names|signatures), which projected.docs: false reports; --no-lines keeps its range, the only thing a block can be identified by.
MCP server
Run ast-bro as a Model Context Protocol server over stdio so any MCP-aware coding agent can call the same operations as native tools — no shell parsing required:
ast-bro mcp
The server speaks line-delimited JSON-RPC 2.0 on stdin/stdout and exposes twenty-three tools that map 1:1 to the CLI commands:
| Tool | Equivalent CLI | Returns |
|---|---|---|
map |
ast-bro map <paths> |
text, or ast-bro.map.v1 with json: true; rev reads the paths at a commit |
digest |
ast-bro digest <paths> |
text, or ast-bro.map.v1 with json: true; rev reads the paths at a commit |
show |
ast-bro show <target> <syms> |
text, or ast-bro.show.v2 with json: true; target may be a file, directory, or glob; rev reads it at a commit |
diff |
ast-bro diff [range] [-- paths] |
text, or ast-bro.diff.v1 with json: true |
review |
ast-bro review [range] [-- paths] |
text, or ast-bro.review.v1 with json: true |
log |
ast-bro log <symbol> [path] |
text, or ast-bro.log.v1 with json: true |
blame |
ast-bro blame <file> |
text, or ast-bro.blame.v1 with json: true |
implements |
ast-bro implements <type> <paths> |
text, or ast-bro.implements.v1 with json: true |
callers |
ast-bro callers <symbol> |
text, or ast-bro.callers.v1 with json: true |
callees |
ast-bro callees <symbol> |
text, or ast-bro.callees.v1 with json: true |
trace |
ast-bro trace <from> <to> |
text, or ast-bro.trace.v1 with json: true |
surface |
ast-bro surface [path] |
text, or ast-bro.surface.v1 with json: true |
impact |
ast-bro impact <symbol> |
text, or ast-bro.impact.v1 with json: true |
context |
ast-bro context <symbol> |
text, or ast-bro.context.v1 with json: true |
deps |
ast-bro deps <file> |
text, or ast-bro.deps.v1 with json: true |
reverse_deps |
ast-bro reverse-deps <file> |
text, or ast-bro.reverse-deps.v1 with json: true |
cycles |
ast-bro cycles [path] |
text, or ast-bro.cycles.v1 with json: true |
graph |
ast-bro graph [path] |
text by default; json: true for ast-bro.graph.v1 |
search |
ast-bro search "<query>" |
text, or ast-bro.search.v1 with json: true |
find_related |
ast-bro find-related <file>:<line> |
text, or ast-bro.related.v1 with json: true |
index |
ast-bro index |
text, or ast-bro.index-stats.v1 with json: true |
run |
ast-bro run -p <pattern> |
text diff, or ast-bro.run.v1 with json: true |
squeeze |
ast-bro squeeze <file> |
text, or ast-bro.squeeze.v1 with json: true |
Wire it into a client by pointing at the binary:
{
"mcpServers": {
"ast-bro": { "command": "ast-bro", "args": ["mcp"] }
}
}
The server is fully synchronous, has no extra runtime dependencies, and adds
roughly 1% to the binary size. The CLI itself is unaffected — none of the MCP
code runs unless you invoke the mcp subcommand.
Semantic search
ast-bro search runs hybrid retrieval over a per-repo index:
- BM25 for exact identifier matches and keyword density.
- Dense embeddings via
minishlab/potion-code-16M— a static (no inference)vocab × 256model that runs on CPU in microseconds. - Reciprocal Rank Fusion (k = 60) blends the two; alpha auto-resolves to 0.3 for symbol queries (
HandlerStack,Sinatra::Base— lean BM25) and 0.5 for natural language ("how does login work" — balanced). - A ranking pass adds definition boosts (3× for chunks that define a queried symbol), file-coherence boosts (multi-chunk hits in the same file lift the top chunk), file-stem matches for NL queries, and path-based penalties (test files 0.3×,
.d.tsstubs 0.7×,__init__.py0.5×).
ast-bro find-related <file>:<line> is the same engine in semantic-only mode, language-filtered, with the source chunk excluded — useful for "what else is structured like this?"
ast-bro search "request validation" -k 5
ast-bro search "HandlerStack" --json
ast-bro find-related src/auth/login.rs:42 -k 3
How indexing works
First call to search / find-related builds an index at .ast-bro/index/:
.ast-bro/
.gitignore # auto-written, contents: "*"
index/
meta.json # schema + model + chunk_count
chunks.bin # per-chunk content + line range + language
embeddings.f32 # chunk_count × 256 little-endian f32, mmap-friendly
bm25.bin # vocab + idf + postings
files.bin # per-file mtime + xxhash + chunk range
lock # advisory lock for concurrent writers
Subsequent calls walk the tree, compare (mtime, size) against files.bin, and only hash files where the cheap check fails. If anything changed, the index rebuilds automatically (a v2 will support partial updates against the same on-disk format). Steady-state cost on an unchanged 10k-file repo: ~30 ms of stat syscalls.
The model is downloaded once (~64 MB) on first use to ~/.cache/ast-bro/models/. It tries HuggingFace first, falls back to hf-mirror.com if blocked. TLS verification is disabled by default so corporate MITM proxies don't break setup; integrity is enforced via SHA-256 on every cached file. Set AST_OUTLINE_TLS_STRICT=1 to enforce strict TLS.
For more on what gets indexed (the five filter layers, .ast-bro-ignore syntax) see the "What gets walked" section above. For the security trade-offs around the TLS default, see the network-security wiki page on GitHub.
find-related quietly benefits from the dep graph too — when one is cached, results are reranked so files within depth 2 of the source (importer or importee) get a multiplicative boost. Disable with --no-dep-boost.
Dependency graph
ast-bro deps, reverse-deps, cycles, and graph build a file-level import graph for the project and answer different questions on it:
ast-bro deps src/auth.rs --depth 2 # what does auth.rs pull in?
ast-bro reverse-deps src/auth.rs # who imports auth.rs? (refactor blast radius)
ast-bro cycles # find import cycles via Tarjan SCC (exit 3 if any)
ast-bro graph . # full dependency graph (text)
ast-bro graph . --json # same, as JSON (ast-bro.graph.v1)
All four commands share one cache at .ast-bro/graph/index.bin (a unified UnifiedGraph { deps, calls: Option<CallGraph> } — same file used by callers / callees, see below). First call builds the dep half (~hundreds of ms for typical repos via the same ignore-respecting walk used by search); subsequent calls reuse it via per-file delta detection, with --rebuild to force a fresh build. Inside ast-bro mcp, every tools/call shares one in-memory Arc<UnifiedGraph> so the second invocation in a session is a memory read, not a disk read.
Resolution is per-language but shares one suffix-index resolver:
- Rust:
use crate::*/use super::*/mod foo;(with#[path]attribute support). - Python: relative imports (
from .x import y),__init__.pypackages, bareimport a.b. - TypeScript / JavaScript: relative paths with extension probing (
.ts → .tsx → .mts → .cts → .d.ts → .js → ... → .json),index.*fallback,tsconfig.jsonpathsaliases. - Java / Kotlin / Scala / C#: FQN suffix index built from each file's
package/namespacedeclaration. Inner classes resolve via strip-and-retry. - Go:
go.modmoduleprefix is stripped;import "mymod/pkg/foo"resolves topkg/foo/*.go(directory-as-package). Everygo.modin the repository counts, so a module in a subdirectory — or several modules side by side — resolves the same way. - Elixir: by module name, not path — directives and modules named without one (
Foo.Bar.baz()) resolve to the file whosedefmoduledefines them. Stdlib, Erlang and dependency modules are[external]. A module named without a directive is arefedge;cyclesleaves those out by default, since runtime cycles are normal in Elixir, and--include-refscounts them.
The four commands are also exposed as MCP tools for agents. For internals (suffix index, Tarjan SCC, per-file invalidation, find-related dep boost) see the deps wiki page on GitHub.
Call graph
ast-bro callers and ast-bro callees answer "who calls X" and "what does X call" with AST accuracy across 13 languages (every supported language but SQL and Markdown). They replace grep for refactor blast-radius assessment — no false positives on overloaded names, comments, or string literals.
ast-bro callers TakeDamage # function/method: in-edges
ast-bro callees TakeDamage # function/method: out-edges
ast-bro callers Player # type: implementors + constructions
ast-bro callees Player --depth 2 # type: ancestor walk (transitive)
ast-bro callers Player.TakeDamage --include-ambiguous --json
Both commands are kind-aware:
| Target kind | callers X |
callees X |
|---|---|---|
| function / method / constructor | call sites that invoke X |
call sites inside X's body |
| class / struct / trait / interface / enum / record | implementors + constructions (covers Foo(), new Foo(), Foo {}, Foo::new()) |
ancestor types and the methods they declare (transitive via --depth N) |
Symbol forms accepted by both: bare suffix (TakeDamage), dotted (Player.TakeDamage), file-scoped (src/Player.cs:TakeDamage), or flag form (--file src/Player.cs --symbol TakeDamage).
A name several definitions share is answered one section per definition, each under its own qualified name with its own count, and the header says so:
$ ast-bro callees parse
# 2 callee(s) for 'parse' across 2 definitions:
## 1 callee(s) of src/json.rs::parse:
src/json.rs:1 src/json.rs::j_helper (Exact)
## 1 callee(s) of src/toml.rs::parse:
src/toml.rs:1 src/toml.rs::t_helper (Exact)
--limit stays one budget across the sections. In --json, each row of such an answer names its definition, and definitions lists each matched symbol with its kind and total. An answer for a name one symbol declares carries neither field and reads as before.
Three-pass resolver. Bare names are disambiguated in three increasing-cost passes:
- Same-file — local definitions + per-file
import/use/usingbindings. - Global symbol table — single-match promotion across the project. Receiver-bearing calls (
obj.bar()) skip this pass to avoidbuilder.hidden()-style false positives on global homonyms. - Dep-graph disambiguation — for ambiguous matches, filter candidates by the caller's transitive forward-dep closure.
Every edge carries a Confidence tag — Exact (passes A/B), Inferred (pass C narrowed to one), or Ambiguous (multiple candidates survive). Ambiguous callers and unresolved/external callees are shown by default (tagged); --hide-ambiguous (callers) and --hide-external (callees) drop them when you want the cleaner bucket.
Cache. Same .ast-bro/graph/index.bin as the dep graph, lazily promoted — users who only run deps / cycles never pay the call-graph build cost. Per-file invalidation: edit one file, only that file gets re-extracted and re-resolved.
For internals (per-language node-kind tables, the call-shape pitfalls each adapter handles, the per-file patch path, cost numbers) see the calls wiki page on GitHub.
Reviewing changes
diff, review, log and blame read a change by declaration rather than by line, and --rev reads map, digest and show at any commit. Every one of them shells out to the repository's own git; nothing is checked out.
ast-bro diff # uncommitted work, untracked files included, vs HEAD
ast-bro diff --staged # the index vs HEAD
ast-bro diff main # what this branch changed since it left main (main...HEAD)
ast-bro diff a1b2c3d^! # one commit
ast-bro diff v1.2..v1.3 -- src/ # a range, limited to paths
ast-bro review main --depth 3 # the brief: call sites, constructions, tests
ast-bro log load_config -p # one declaration's history, with its own hunks
ast-bro blame src/config.rs # last real change per declaration
ast-bro show --rev v1.2 src/config.rs load_config
diff lists, per file, each declaration a change added (+), removed (-), modified (~), moved or renamed (>), with its lines on both sides and the parts that changed:
| Part | Meaning |
|---|---|
sig |
the signature as an API: parameters, return type, generics; both versions are printed in full |
vis |
visibility (pub, export, private, …) |
docs / attrs / bases |
the doc comment, the attributes or decorators, the implemented or extended types |
body |
the code, compared as a syntax tree with comments dropped |
value |
the initializer of a constant, variable or field, so a version bump is not a new signature |
format |
whitespace or comments only, proven on the syntax tree; counted per file in text, listed in JSON |
Rows go by section: code, tests (test files and in-file test modules), docs (Markdown), and other files, which no adapter reads and get one line each with their +N -M. Lines a change touched outside every declaration, such as imports, are listed rather than dropped. A..B and A...B read as git reads them, R^! is one commit against its first parent, and one ref R means R...HEAD.
review reads the same change against the call graph at the head of the range: each signature or visibility change with every call site the call graph finds and whether it sits in a declaration the change touched; declarations removed or renamed that call sites still use by the old name; types whose members came, went or changed type, with the code that builds (or implements) them; the project calls each function started or stopped making (not calls through a value or a lowercase module path, such as config::load(), which the diff still shows as a body change); and the tests that statically reach each changed function within --depth. Unresolved call sites are labelled as possible, never counted as callers, and a test walk the depth cut short says so. Every section is capped by --limit on its own, and each list of sites inside an entry is too, always with the true total. When the head is the clean checkout (nothing modified, nothing untracked) the working tree's graph cache answers; otherwise the head is written to a temporary tree and its graph is built there.
log reads each commit that touched the file as two versions matched declaration by declaration, so it follows the declaration itself — through renames, through a move to another parent or another file, overloads apart — and stops at the commit that added it; a merge that resolved a conflict by hand counts as a commit, where git log -L :name:file follows a line range into whatever code held those lines before. blame gives each declaration the newest commit that changed it in more than formatting, passing over reformat-only commits and those .git-blame-ignore-revs lists.
For internals (matching, the token streams behind body and format, the mirror behind --rev) see the review wiki page on GitHub.
Architecture & Development
See the wiki on GitHub for details on how ast-bro leverages ast-grep internally and how you can add new language adapters.
Getting started
git clone https://github.com/aeroxy/ast-bro.git
cd ast-bro
# With Cargo
cargo run -- digest src/
# With Nix flake
nix develop # Enter development shell
nix build # Build the project
nix flake check # Run all checks (tests, clippy, formatting)
Contributions welcome.
License
관련 프로젝트 살펴보기
불러오는 중…