Capture LLVM bitcode from any build and query it through rllvm-query's MCP server.


Extract whole-program LLVM bitcode from any build.
Point your build system at rllvm's compiler wrappers, build normally, then pull the bitcode for the whole program back out of the finished binary, and ask it source-level questions across C, C++ and Rust.
rllvm keeps the CC/CXX → build → extract workflow of wllvm and gllvm: rllvm-cc and rllvm-cxx stand in for wllvm/gclang, rllvm-get-bc for extract-bc/get-bc.
| 🌟 rllvm | wllvm / gllvm | |
|---|---|---|
| 🦀 Languages | C, C++, Objective-C, Rust | C, C++, Fortran |
| 🔍 Analysis | Source-level queries, MCP server | ❌ |
| 🤖 Agents | Claude Code plugin | ❌ |
| 📋 No wrapper build | Import compile_commands.json | ❌ |
| 🎯 Targets | Native, cross, WebAssembly, eBPF | Native; cross with a target objcopy |
| 🔗 LTO | Three modes, dispatched on object content | -flto unlikely to survive extraction |
| ♻️ Rebuilds | Cache validated against inputs | No bitcode cache |
| 📦 Moving a build tree | Paths relative to a root | Absolute bitcode paths |
| ⚙️ Setup | Detected from llvm-config | Environment variables |
brew install h1994st/tap/rllvm llvm # macOS or Linux with Homebrew
# Or: cargo install rllvm
# LLVM on Ubuntu/Debian: sudo apt install llvm llvm-dev clang libclang-dev
rllvm-cc hello.c -o hello
rllvm-get-bc hello # writes hello.bc
rllvm-info hello.bc # target, function, block, instruction counts
On first run, tool paths are detected from llvm-config and written to ~/.rllvm/config.toml.

<img alt="rllvm's pipeline: the wrappers capture bitcode beside each object, the linker carries the recorded paths into the binary, rllvm-get-bc extracts them, and rllvm-query answers questions over the result" src="docs/assets/architecture-light.svg">
The wrappers run the real compiler and also emit bitcode. Each object gets a section recording its bitcode path; the linker concatenates those sections, so the binary lists every module that went into it. Extraction reads the paths back and merges the modules.
Capture covers only what you build through the wrappers. A prebuilt native library contributes no bitcode, so build every dependency you need in the whole-program view.

/plugin marketplace add h1994st/rllvm
/plugin install rllvm@rllvm
| Part | What it does |
|---|---|
setup skill | Installs rllvm and rllvm-query with your approval, picks a compatible LLVM, configures, and troubleshoots |
capture skill | Chooses how to capture your build and what to extract |
query skill | Picks the query that answers your question and reports what the answer does not cover |
complete-callgraph skill | Resolves unresolved indirect calls into a labeled overlay, never reported as proven |
/overlay-view | A read-only pane of the overlay's candidates and edges |
| MCP server | rllvm-query mcp, configured automatically |
Builds run as ordinary shell commands you approve, never inside the server. See the plugin example.
CC=rllvm-cc CXX=rllvm-cxx ./configure && make # Autotools, Make
CC=rllvm-cc CXX=rllvm-cxx cmake -S . -B build && cmake --build build
RUSTC_WRAPPER=rllvm-rustc cargo build # Rust and its C/C++
rllvm-compdb generate build/ --output-dir analysis/all # compile_commands.json
rllvm-cc wraps clang and rllvm-cxx wraps clang++, Objective-C included. rllvm-compdb compiles an existing compilation database without rebuilding, so its modules describe the source tree rather than a real link.
| Build | Notes | Example |
|---|---|---|
| CMake, Objective-C | Toolchain file cmake/rllvm-toolchain.cmake sets all four compilers | cmake, objc |
| Rust | Per-crate capture; your LLVM must read what rustc -vV emits | rust, ffi |
| LLD | -fuse-ld=lld | lld |
| LTO | RLLVM_LTO_MODE: marker (default), save-temps or skip | lto |
| Cross | --target=<triple> reaches the compile and the link | cross-compile |
| WebAssembly, eBPF | --target=wasm32-unknown-unknown, --target=bpf -g | wasm, ebpf |
| Compilation database | Direct clang/clang++ entries; select with --source or --entry | compdb |
Every compiler flag reaches the real compiler. Wrapper options are long-only and prefixed --rllvm-, such as --rllvm-verbose=3 to log subcommands; see the wrapper options example. RLLVM_CACHE=1 skips the extra bitcode compilation on a rebuild once the preprocessed inputs, dependencies, compiler, command, directory and environment match; keep it off when inputs preprocessing cannot see, such as profiles, change. Universal (multiple -arch) builds are unsupported.
rllvm-get-bc app # one whole-program app.bc
rllvm-get-bc -b libfoo.a # a bitcode archive, libfoo.bca
rllvm-info app --json > catalog.json # which modules, and where they came from
rllvm-get-bc app --module MODULE_ID --output-dir analysis/selected
rllvm-get-bc accepts executables, objects and archives. A catalog records the modules found and their provenance; queries read it, and --module, --source and --configuration select from it. To move a build tree, build with RLLVM_BITCODE_ROOT and extract with --bitcode-root.
See the merge strategies, catalogs and relocatable examples, and the catalog format.
rllvm-query links LLVM statically, so it ships separately:
brew install h1994st/tap/rllvm-query # brings its own llvm
# Or: cargo install rllvm-query
# If llvm-config is not on PATH: LLVM_SYS_231_PREFIX="$(brew --prefix llvm)"
On Ubuntu/Debian, install libpolly-N-dev alongside llvm-N-dev and libclang-N-dev.
rllvm-query --catalog catalog.json defs parse_frame # where it is defined
rllvm-query --catalog catalog.json at parser.c 4 # what is at a source line
rllvm-query --catalog catalog.json callers parse_frame # who calls it
rllvm-query --catalog catalog.json callees main # what it calls
rllvm-query --catalog catalog.json uses parse_frame # where its address is taken
rllvm-query --catalog catalog.json reach main parse_frame # a path between two functions
rllvm-query --catalog catalog.json slice main parse_frame # every function on such a path
rllvm-query --catalog catalog.json closure parse_frame in # everything that reaches it
rllvm-query --catalog catalog.json externals # unbound symbols
rllvm-query --catalog catalog.json ffi-exports # Rust functions C can call
rllvm-query --catalog catalog.json indirect-targets parser.c:8 # targets of an indirect call
rllvm-query --catalog catalog.json resolution-candidates # unresolved indirect calls
rllvm-query --catalog catalog.json guards --at clamp.c:14 --operand 2 # what bounds a value
Every answer also says what it could not see: modules that failed to parse, indirect call sites, ambiguous bindings, and source that changed since it was compiled. Add --json for the machine-readable envelope or --full for those blocks as text. Name a symbol by its mangled name, its demangled reading, or a bare identifier that searches. A file:line names its file as the debug info recorded it, or by any path to the same file, symlinks included. Pipe several queries in, one per line, to load the catalog once. Extracted facts are cached; RLLVM_QUERY_CACHE=0 turns that off, and rllvm-query cache clear empties it.
See the queries, name resolution and staleness examples.
<img alt="An unresolved indirect call in dispatch, its candidate targets, an agent's overlay edge to handler labeled agent with high confidence, a refuted edge that is never walked, and an annotate verdict on memcpy's length; reach with --include-overlay returns the path marked not proven" src="docs/assets/callgraph-light.svg">
An agent that resolves an indirect call records it with rllvm-query overlay record in an overlay file beside the catalog (or --overlay PATH); the catalog itself never changes. Overlay edges are hypotheses: reach, closure and slice walk them only with --include-overlay (and --min-confidence), label each step agent, and never call such a path proven. slice --emit-module OUT.bc writes a slice as one small module for checking an edge. An overlay can also hold annotate verdicts on whether a value is feasible, which reach and slice surface with --annotations. See the call-graph overlay example.

guards lists the comparisons, clamps, masks and moduli that constrain a call's argument (--at FILE:LINE --operand N), its result (--return) or a -g local (--function F --local NAME), with each guard's bound and source line; --from F keeps only callers on a path from F. A local reused for several values is refused with the lines that use it; a name several variables share, such as a shadowed local, is refused with the line each is declared at, though a variable of an inlined callee does not count; --at FILE:LINE beside --local traces the value it holds at that use. A use at a line is a read of the value the local holds there, possibly through another variable that holds the same value inside the local's scope. An overlay annotate anchor carries no use-site, so a reused local cannot be annotated. Each guard gives affine, anchored = scale * guarded + offset, when its relation to the value is a constant one. Its scale and offset are decimal strings, since they may exceed 64 bits. verified means its bound soundly carries to the value; otherwise it is a lead whose caveat says why: the relation is not affine, the guard bounds a value computed from it, no branch edge shows a comparison held at the use, the bound wraps, or it cannot be mapped. A comparison is verified only through its branch's edge into the use, one every path to the use crosses (a loop's backedge into the block it enters is fine), and gives the predicate that holds on that edge, which may negate the source condition: past if (x > 16) return; it is ule 16. A verified comparison's predicate holds at the use; one with no deciding edge keeps its predicate as written. A --return anchor, or a --local without --at, sits before the comparisons that test the value, so they are leads there: for their bound, anchor at the later use, --at that use for a local or an argument anchor on the call that consumes a returned value. A clamp computed from the value bounds its own result, so when it is made of a comparison (a branch or select clamp, not an intrinsic umin), that comparison is listed too. For a clamp, mask, modulo or saturation, verified does not say it runs on every path, relation does: an unconditional bound is verified and dominates or defines, while one on_path is conditional. The numeric cap is bound: a verified guard without one is capped by a runtime value, the guard's operand, which is a sound relation but not a numeric limit; to reach a number, anchor on that operand and trace it. A load is followed to the nearest store before it in its block, which overwrites any earlier one, with nothing between that writes memory. A call, another store or any other operation between (an atomicrmw, a cmpxchg, a volatile load), or stores only in other blocks, make each guard reached through it a lead, and the trace is reported lost there. It is evidence, never a verdict: an empty list does not mean unbounded. See the value guards example.
rllvm-query mcp serves the same queries as tools over stdio:
{ "mcpServers": { "rllvm": { "command": "rllvm-query", "args": ["mcp"] } } }
A client loads a catalog with load_catalog or a binary with inventory, and keeps several loaded at once. See the MCP example; the Claude Code plugin configures this for you.
The TOML file lives at $RLLVM_CONFIG or ~/.rllvm/config.toml. rllvm-init --dry-run previews detection; --llvm-prefix chooses a toolchain and -o selects the file to write.
| Key | Required | Description |
|---|---|---|
llvm_config_filepath | Yes | Absolute path to llvm-config |
clang_filepath | Yes | Absolute path to clang |
clangxx_filepath | Yes | Absolute path to clang++ |
llvm_ar_filepath | Yes | Absolute path to llvm-ar |
llvm_link_filepath | Yes | Absolute path to llvm-link |
llvm_objcopy_filepath | No | Absolute path to llvm-objcopy; preferred for embedding, with an internal fallback |
llvm_bindir | No | Directory of the LLVM tools without a key of their own (llvm-nm, llvm-dis, llvm-extract, opt; default: llvm-config --bindir) |
rustc_filepath | No | Compiler for direct Rust invocation; RLLVM_REAL_RUSTC overrides; defaults to rustc on PATH |
bitcode_store_path | No | Directory for bitcode files (must be absolute; created if missing) |
bitcode_root | No | Record embedded paths relative to this root (default: absolute) |
llvm_link_flags | No | Extra flags for llvm-link |
lto_ldflags | No | Extra flags for link-time optimization |
bitcode_generation_flags | No | Extra flags for bitcode generation (e.g. -flto) |
lto_mode | No | How -flto builds record bitcode: marker (default), save-temps, skip; RLLVM_LTO_MODE overrides |
is_configure_only | No | Skip extra C/C++ bitcode work (default: false) |
cache_enabled | No | Reuse C/C++ bitcode across rebuilds; overridden by RLLVM_CACHE (default: false) |
cache_dir | No | Cache directory; also holds rllvm-query's query-facts/ (default: ~/.rllvm/cache) |
query_cache | No | Reuse rllvm-query's extracted per-module facts; overridden by RLLVM_QUERY_CACHE (default: true) |
query_cache_warn_mb | No | Facts cache size, in MB, past which rllvm-query warns (default: 1024) |
log_level | No | 0=error (default), 1=warn, 2=info, 3=debug, 4+=trace; RLLVM_LOG_LEVEL overrides |
Clean build-only time relative to native compilation, on an Apple M4 with LLVM 23.1.2:
| Workload | Cache disabled | Primed C/C++ cache |
|---|---|---|
| nghttp2 C (CMake) | 1.86× | 1.65× |
| nghttp2 C++ (CMake) | 1.88× | 1.28× |
| Quiche (Cargo) | 1.28× | 1.23× |
C/C++ capture adds a bitcode compilation per source; Rust emits bitcode in the same rustc invocation.
See the baseline for conditions and the benchmark guide for reproduction.
wllvm and gllvm built the wrapper-and-extract approach this tool follows.
rules_rllvm is a separate Bazel-native project and does not use these binaries.
hooks/register.tsx 465 lines1// A read-only view of rllvm-query's call-graph overlay. It draws only from
2// the results of the server's own tool calls, so records the agent has not
3// saved yet show as they are made; it never reads the overlay file, never
4// writes anything, and offers nothing to press.
5
6import { atom, read, update } from 'claude-code'
7import type { Register, StateDollar } from 'claude-code'
8
9import type {
10 OverlayConfidence,
11 OverlayEdge,
12 OverlayEdgeKey,
13 OverlayField,
14 OverlayFunction,
15 OverlayGroup,
16 OverlaySite,
17 OverlaySiteAt,
18 OverlaySlot,
19 OverlayVerdict,
20 OverlayView,
21} from '../types'
22
23const PANE = 'rllvm-overlay'
24const TITLE = 'Call-graph overlay'
25const COMMAND = 'overlay-view'
26const EMPTY = 'Run resolution_candidates to see unresolved fields.'
27const GROUP_LIMIT = 50
28
29const CANDIDATES_TOOL = 'resolution_candidates'
30const SAVE_TOOL = 'save_overlay'
31const SUMMARY_TOOLS = ['record_edges', 'list_overlay', 'load_overlay']
32const OVERLAY_TOOLS = [CANDIDATES_TOOL, SAVE_TOOL, ...SUMMARY_TOOLS]
33
34const CONFIDENCES: readonly OverlayConfidence[] = ['low', 'medium', 'high']
35const VERDICT_MARKS: Readonly<Record<OverlayVerdict, string>> = {
36 confirmed: '✓',
37 refuted: '✗',
38 inconclusive: '?',
39}
40
41const groups = atom({ plugin: 'rllvm', key: 'groups' } as const, [])
42const droppedGroups = atom({ plugin: 'rllvm', key: 'dropped_groups' } as const, 0)
43const overlay = atom({ plugin: 'rllvm', key: 'overlay' } as const, null)
44
45type Json = Record<string, unknown>
46
47const isObject = (value: unknown): value is Json =>
48 typeof value === 'object' && value !== null && !Array.isArray(value)
49
50/**
51 * The rllvm-query tool a call went to, or undefined for any other tool. The
52 * server is named by whoever configured it (`plugin_rllvm_rllvm-query` from
53 * the rllvm plugin, anything by hand), so only the `mcp__` prefix and the
54 * `__<tool>` suffix are fixed.
55 */
56const overlayTool = (name: string): string | undefined =>
57 OVERLAY_TOOLS.find(tool => {
58 const suffix = `__${tool}`
59 return name.startsWith('mcp__') && name.endsWith(suffix) && name.length > 5 + suffix.length
60 })
61
62/** The JSON text an MCP result carries, whichever shape the engine handed it in. */
63const resultText = (ran: { text?: string; result?: unknown }): string | undefined => {
64 if (typeof ran.text === 'string') return ran.text
65 const result = ran.result
66 if (typeof result === 'string') return result
67 const blocks = Array.isArray(result) ? result : isObject(result) ? result.content : undefined
68 const first: unknown = Array.isArray(blocks) ? blocks[0] : undefined
69 return isObject(first) && typeof first.text === 'string' ? first.text : undefined
70}
71
72// Readers of the server's payloads. Each answers undefined for a value that
73// is not the shape the server sends, and a payload with any such value is
74// ignored whole, so the view never shows half of an answer.
75
76const allOf = <T,>(values: unknown, parse: (value: unknown) => T | undefined): T[] | undefined => {
77 if (!Array.isArray(values)) return undefined
78 const parsed = values.map(parse)
79 return parsed.every(value => value !== undefined) ? (parsed as T[]) : undefined
80}
81
82const parseFunction = (value: unknown): OverlayFunction | undefined =>
83 isObject(value) && typeof value.module_id === 'string' && typeof value.symbol === 'string'
84 ? { module_id: value.module_id, symbol: value.symbol }
85 : undefined
86
87const parseField = (value: unknown): OverlayField | undefined =>
88 isObject(value) && typeof value.record === 'string' && typeof value.offset === 'number'
89 ? { record: value.record, offset: value.offset }
90 : undefined
91
92const parseSlot = (value: unknown): OverlaySlot | undefined => {
93 if (!isObject(value)) return undefined
94 if (value.kind === 'global' && typeof value.name === 'string') {
95 const module_id = value.module_id ?? null
96 return module_id === null || typeof module_id === 'string'
97 ? { kind: 'global', name: value.name, module_id }
98 : undefined
99 }
100 const fn = parseFunction(value.function)
101 if (!fn) return undefined
102 if (value.kind === 'param' && typeof value.index === 'number')
103 return { kind: 'param', function: fn, index: value.index }
104 return value.kind === 'returned' ? { kind: 'returned', function: fn } : undefined
105}
106
107const parseSite = (value: unknown): OverlaySite | undefined => {
108 if (!isObject(value)) return undefined
109 const fn = parseFunction(value.function)
110 const { block_index, instruction_index } = value
111 return fn && typeof block_index === 'number' && typeof instruction_index === 'number'
112 ? { function: fn, block_index, instruction_index }
113 : undefined
114}
115
116const parseLocation = (value: unknown): string | null =>
117 isObject(value) && typeof value.file === 'string' && typeof value.line === 'number'
118 ? `${value.file}:${value.line}`
119 : null
120
121const parseSiteAt = (value: unknown): OverlaySiteAt | undefined => {
122 const site = isObject(value) ? parseSite(value.site) : undefined
123 return site && isObject(value) ? { site, location: parseLocation(value.location) } : undefined
124}
125
126const parseGroup = (value: unknown): OverlayGroup | undefined => {
127 if (!isObject(value) || typeof value.signature !== 'string') return undefined
128 const field = value.field === undefined || value.field === null ? null : parseField(value.field)
129 const slot = value.slot === undefined || value.slot === null ? null : parseSlot(value.slot)
130 const sites = allOf(value.sites, parseSiteAt)
131 const candidates = allOf(value.candidates, one =>
132 isObject(one) ? parseFunction(one.function) : undefined,
133 )
134 if (field === undefined || slot === undefined || !sites || !candidates) return undefined
135 return {
136 field,
137 slot,
138 field_name: typeof value.field_name === 'string' ? value.field_name : null,
139 signature: value.signature,
140 sites,
141 candidates,
142 single_candidate: value.single_candidate === true,
143 }
144}
145
146const parseKey = (value: unknown): OverlayEdgeKey | undefined => {
147 if (!isObject(value)) return undefined
148 const to = parseFunction(value.to)
149 if (!to) return undefined
150 if ('via_field' in value) {
151 const via_field = parseField(value.via_field)
152 return via_field && { via_field, to }
153 }
154 if ('via_slot' in value) {
155 const via_slot = parseSlot(value.via_slot)
156 return via_slot && { via_slot, to }
157 }
158 const site = parseSite(value.site)
159 return site && { site, to }
160}
161
162const parseEdge = (value: unknown): OverlayEdge | undefined => {
163 if (!isObject(value)) return undefined
164 const key = parseKey(value.key)
165 const confidence = CONFIDENCES.find(one => one === value.confidence)
166 const verdict = isObject(value.verification) ? value.verification.verdict : null
167 const isVerdict =
168 verdict === null || (typeof verdict === 'string' && Object.hasOwn(VERDICT_MARKS, verdict))
169 if (!key || !confidence || !isVerdict || typeof value.sites !== 'number') return undefined
170 return { key, confidence, verdict: verdict as OverlayVerdict | null, sites: value.sites }
171}
172
173const parseSummary = (value: unknown): OverlayView | undefined => {
174 if (!isObject(value) || !isObject(value.coverage)) return undefined
175 const { unresolved_sites, covered_sites } = value.coverage
176 const edges = allOf(value.edges, parseEdge)
177 const path =
178 value.path === undefined || typeof value.path === 'string' ? (value.path ?? null) : undefined
179 if (
180 !edges ||
181 path === undefined ||
182 typeof value.pending !== 'number' ||
183 typeof unresolved_sites !== 'number' ||
184 typeof covered_sites !== 'number'
185 ) {
186 return undefined
187 }
188 return { path, pending: value.pending, edges, unresolved_sites, covered_sites }
189}
190
191/** Keeps what a tool's answer says about the overlay; ignores anything else. */
192const remember = async ($: StateDollar, tool: string, payload: unknown) => {
193 if (tool === CANDIDATES_TOOL) {
194 const parsed = isObject(payload) ? allOf(payload.results, parseGroup) : undefined
195 if (!parsed) return
196 // The server lists field and slot groups first, the ones an edge can
197 // cover most sites through, so the first are kept and the rest only
198 // counted.
199 await update($, groups, () => parsed.slice(0, GROUP_LIMIT))
200 await update($, droppedGroups, () => Math.max(0, parsed.length - GROUP_LIMIT))
201 } else if (tool === SAVE_TOOL) {
202 if (!isObject(payload) || typeof payload.saved !== 'number' || typeof payload.path !== 'string')
203 return
204 const { saved, path } = payload
205 await update(
206 $,
207 overlay,
208 view => view && { ...view, path, pending: Math.max(0, view.pending - saved) },
209 )
210 } else {
211 const parsed = parseSummary(payload)
212 if (parsed) await update($, overlay, () => parsed)
213 }
214}
215
216// Labels.
217
218const fieldLabel = (field: OverlayField) => `${field.record}@${field.offset}`
219
220const slotLabel = (slot: OverlaySlot) =>
221 slot.kind === 'global'
222 ? `global ${slot.name}`
223 : slot.kind === 'param'
224 ? `param ${slot.index} of ${slot.function.symbol}`
225 : `*${slot.function.symbol}()`
226
227/** Identifies a slot exactly, where its label may repeat across modules. */
228const slotId = (slot: OverlaySlot) =>
229 slot.kind === 'global'
230 ? `global:${slot.module_id ?? ''}:${slot.name}`
231 : slot.kind === 'param'
232 ? `param:${slot.function.module_id}:${slot.function.symbol}:${slot.index}`
233 : `returned:${slot.function.module_id}:${slot.function.symbol}`
234
235/** The field or slot a group dispatches through: its id and label, or null for neither. */
236const groupPattern = (group: OverlayGroup) =>
237 group.field
238 ? { id: fieldLabel(group.field), label: fieldLabel(group.field) }
239 : group.slot
240 ? { id: slotId(group.slot), label: slotLabel(group.slot) }
241 : null
242
243/** The field or slot an edge covers, or null for a site edge. */
244const edgePattern = (key: OverlayEdgeKey) =>
245 'via_field' in key
246 ? { id: fieldLabel(key.via_field), label: fieldLabel(key.via_field) }
247 : 'via_slot' in key
248 ? { id: slotId(key.via_slot), label: slotLabel(key.via_slot) }
249 : null
250
251const siteId = (site: OverlaySite) =>
252 `${site.function.module_id}:${site.function.symbol}:${site.block_index}:${site.instruction_index}`
253
254const sameFunction = (a: OverlayFunction, b: OverlayFunction) =>
255 a.module_id === b.module_id && a.symbol === b.symbol
256
257const plural = (count: number, noun: string) => `${count} ${noun}${count === 1 ? '' : 's'}`
258
259const edgeMark = (edge: OverlayEdge) =>
260 `${edge.confidence} ${edge.verdict ? VERDICT_MARKS[edge.verdict] : 'unverified'}`
261
262/** A function's symbol, with its module when another listed function shares the symbol. */
263const functionLabel = (fn: OverlayFunction, among: readonly OverlayFunction[]) =>
264 among.some(other => other.symbol === fn.symbol && other.module_id !== fn.module_id)
265 ? `${fn.symbol} (${fn.module_id.slice(0, 8)})`
266 : fn.symbol
267
268type Line = { key: string; text: string; detail?: string; isDim?: boolean; isBold?: boolean }
269
270/** One group's lines: its header, then each candidate, marked when an edge claims it. */
271const groupLines = (group: OverlayGroup, edges: readonly OverlayEdge[]): Line[] => {
272 // A group with no field is named by its first site, where the call is.
273 const first = group.sites[0]
274 const where = first ? [first.site.function.symbol, first.location ?? ''].join(' ').trim() : ''
275 const pattern = groupPattern(group)
276 const id = pattern ? pattern.id : `site-${first ? siteId(first.site) : group.signature}`
277 const head = pattern
278 ? `${pattern.label}${group.field_name ? ` (${group.field_name})` : ''}`
279 : `${where || 'sites'} (${group.signature})`
280 const details = [plural(group.sites.length, 'site')]
281 if (pattern) details.push(group.signature)
282 if (group.single_candidate) details.push('single candidate')
283 const sites = new Set(group.sites.map(one => siteId(one.site)))
284 const claims = edges.filter(edge => {
285 const covers = edgePattern(edge.key)
286 if (covers) return pattern !== null && covers.id === pattern.id
287 return pattern === null && 'site' in edge.key && sites.has(siteId(edge.key.site))
288 })
289 // An edge to a function the candidates do not list still belongs here.
290 const targets = [
291 ...group.candidates,
292 ...claims
293 .map(edge => edge.key.to)
294 .filter(to => !group.candidates.some(one => sameFunction(one, to))),
295 ]
296 return [
297 { key: `group-${id}`, text: head, detail: ` · ${details.join(' · ')}`, isBold: true },
298 ...targets.map(target => {
299 const label = functionLabel(target, targets)
300 const edge = claims.find(one => sameFunction(one.key.to, target))
301 return edge
302 ? {
303 key: `candidate-${id}-${label}`,
304 text: `→ ${label} ${edgeMark(edge)}`,
305 isDim: edge.verdict === 'refuted',
306 }
307 : { key: `candidate-${id}-${label}`, text: ` ${label}` }
308 }),
309 ]
310}
311
312/** Field and slot edges whose pattern no group lists, one block per pattern. */
313const orphanPatternBlocks = (
314 patternEdges: readonly OverlayEdge[],
315 known: ReadonlySet<string>,
316): Line[][] => {
317 const byPattern = new Map<string, { label: string; edges: OverlayEdge[] }>()
318 for (const edge of patternEdges) {
319 const pattern = edgePattern(edge.key)
320 if (!pattern || known.has(pattern.id)) continue
321 const entry = byPattern.get(pattern.id) ?? { label: pattern.label, edges: [] }
322 byPattern.set(pattern.id, { ...entry, edges: [...entry.edges, edge] })
323 }
324 return [...byPattern].map(([id, { label, edges }]) => [
325 { key: `group-${id}`, text: label, isBold: true },
326 ...edges.map(edge => {
327 const name = functionLabel(
328 edge.key.to,
329 edges.map(one => one.key.to),
330 )
331 return {
332 key: `candidate-${id}-${name}`,
333 text: `→ ${name} ${edgeMark(edge)}`,
334 isDim: edge.verdict === 'refuted',
335 }
336 }),
337 ])
338}
339
340/** Edges recorded for one call site, with the site's source line when a group named it. */
341const siteBlock = (
342 edges: readonly OverlayEdge[],
343 at: ReadonlyMap<string, string | null>,
344): Line[] => {
345 const lines = edges.flatMap(edge => {
346 if (!('site' in edge.key)) return []
347 const { site, to } = edge.key
348 const where = at.get(siteId(site)) ?? `b${site.block_index}:i${site.instruction_index}`
349 const text = `${site.function.symbol} ${where} → ${functionLabel(to, [])} ${edgeMark(edge)}`
350 return [{ text, isDim: edge.verdict === 'refuted' }]
351 })
352 return lines.length
353 ? [
354 { key: 'sites', text: 'sites', isBold: true },
355 ...lines.map((line, index) => ({ key: `site-${index}`, ...line })),
356 ]
357 : []
358}
359
360const coverageLine = (view: OverlayView | null): Line =>
361 view
362 ? {
363 key: 'coverage',
364 text: [
365 `covered ${view.covered_sites} of ${view.unresolved_sites} unresolved sites`,
366 plural(view.edges.length, 'edge'),
367 `${view.pending} unsaved`,
368 ].join(' · '),
369 }
370 : { key: 'coverage', text: 'no overlay loaded yet', isDim: true }
371
372/**
373 * Everything the pane shows, cut to `rows` lines with a count of the blocks
374 * left out, `dropped` groups never kept among them.
375 */
376const paneLines = (
377 list: readonly OverlayGroup[],
378 dropped: number,
379 view: OverlayView | null,
380 rows: number,
381): Line[] => {
382 const edges = view?.edges ?? []
383 const head = [coverageLine(view)]
384 if (view?.path) head.push({ key: 'path', text: view.path, isDim: true })
385 if (list.length === 0) head.push({ key: 'empty', text: EMPTY, isDim: true })
386
387 const known = new Set(list.flatMap(group => groupPattern(group)?.id ?? []))
388 const at = new Map(
389 list.flatMap(group => group.sites.map(one => [siteId(one.site), one.location] as const)),
390 )
391 const blocks = [
392 ...list.map(group => groupLines(group, edges)),
393 ...orphanPatternBlocks(edges, known),
394 siteBlock(edges, at),
395 ].filter(block => block.length > 0)
396
397 const more = (count: number): Line => ({ key: 'more', text: `…${count} more`, isDim: true })
398 const shown = [...head]
399 for (const [index, block] of blocks.entries()) {
400 const isLast = index === blocks.length - 1 && dropped === 0
401 if (shown.length + block.length + (isLast ? 0 : 1) > rows) {
402 shown.push(more(blocks.length - index + dropped))
403 return shown
404 }
405 shown.push(...block)
406 }
407 if (dropped > 0) shown.push(more(dropped))
408 return shown
409}
410
411export const register: Register = on => {
412 on('session.start', async ($, e, next) => {
413 await $.command.register({
414 name: COMMAND,
415 description: "Show rllvm-query's call-graph overlay in a pane",
416 })
417 return next(e)
418 })
419
420 on('command.run', { command: COMMAND }, async $ => {
421 await $.ui.open({ id: PANE, title: TITLE })
422 return { text: 'Call-graph overlay pane opened.' }
423 })
424
425 on('tool.call', async ($, e, next) => {
426 const tool = overlayTool(String(e.tool))
427 if (!tool) return next(e)
428 const ran = await next(e)
429 if (ran.deny !== undefined || ran.isError === true) return ran
430 const text = resultText(ran)
431 if (text === undefined) return ran
432 let payload: unknown
433 try {
434 payload = JSON.parse(text)
435 } catch {
436 return ran
437 }
438 await remember($, tool, payload)
439 return ran
440 })
441
442 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
443 const { Box, Text } = $.ui.resolve(e)
444 const rows = e.props.scroll?.bodyRows ?? e.viewport?.rows ?? Number.POSITIVE_INFINITY
445 const lines = paneLines(
446 await read($, groups),
447 await read($, droppedGroups),
448 await read($, overlay),
449 Math.max(rows, 1),
450 )
451 return (
452 <Box flexDirection="column">
453 {lines.map(line => (
454 <Box key={line.key}>
455 <Text dimColor={line.isDim === true} bold={line.isBold === true} wrap="truncate-end">
456 {line.text}
457 {line.detail ? <Text dimColor>{line.detail}</Text> : null}
458 </Text>
459 </Box>
460 ))}
461 </Box>
462 )
463 })
464}
465types/index.d.ts 78 lines1// What the overlay view keeps in `$.state`: the last answers of
2// rllvm-query's MCP tools, reduced to what the pane draws. Nothing here is
3// read from disk; unsaved records show because they arrive in tool results.
4
5/** A function as rllvm-query names it: the module it is defined in, and its symbol. */
6export type OverlayFunction = { module_id: string; symbol: string }
7
8/** A struct field by record name and byte offset (`ops@8`). */
9export type OverlayField = { record: string; offset: number }
10
11/**
12 * Where a callback is kept on its way to a call: a global, a function's
13 * parameter, or the location an accessor returns the address of.
14 */
15export type OverlaySlot =
16 | { kind: 'global'; name: string; module_id: string | null }
17 | { kind: 'param'; function: OverlayFunction; index: number }
18 | { kind: 'returned'; function: OverlayFunction }
19
20/** One unresolved indirect call site. */
21export type OverlaySite = {
22 function: OverlayFunction
23 block_index: number
24 instruction_index: number
25}
26
27/** A site and where it is in the source, when the build recorded that. */
28export type OverlaySiteAt = { site: OverlaySite; location: string | null }
29
30/** One `resolution_candidates` group: a field, a slot (or a set of sites) and the functions it may call. */
31export type OverlayGroup = {
32 field: OverlayField | null
33 slot: OverlaySlot | null
34 field_name: string | null
35 signature: string
36 sites: OverlaySiteAt[]
37 candidates: OverlayFunction[]
38 single_candidate: boolean
39}
40
41/** An overlay edge's identity: a field, a slot or a single site, and the function it calls. */
42export type OverlayEdgeKey =
43 | { via_field: OverlayField; to: OverlayFunction }
44 | { via_slot: OverlaySlot; to: OverlayFunction }
45 | { site: OverlaySite; to: OverlayFunction }
46
47export type OverlayConfidence = 'low' | 'medium' | 'high'
48
49export type OverlayVerdict = 'confirmed' | 'refuted' | 'inconclusive'
50
51/** One agent-recorded edge and what has been checked about it. */
52export type OverlayEdge = {
53 key: OverlayEdgeKey
54 confidence: OverlayConfidence
55 verdict: OverlayVerdict | null
56 sites: number
57}
58
59/** The overlay as the last summary reported it. */
60export type OverlayView = {
61 path: string | null
62 pending: number
63 edges: OverlayEdge[]
64 unresolved_sites: number
65 covered_sites: number
66}
67
68declare module 'claude-code' {
69 interface PluginState {
70 rllvm: {
71 groups: OverlayGroup[]
72 /** Groups the last `resolution_candidates` listed beyond those kept. */
73 dropped_groups: number
74 overlay: OverlayView | null
75 }
76 }
77}
78