---
name: multi-agent-graph
description: "Build and query this repo's code graph: a deterministic, LLM-free map of symbols, imports and references used to narrow Phase 1's Explore scope and to keep the knowledge base current. Read-only on code, costs no API tokens. Use when a task needs to know where something lives or what depends on it before reading files."
user-invocable: true
argument-hint: '[build | refresh | ask "<question>" | affected "<symbol>" | path <from> <to> | callers <fn> | callees <fn> | export <format> | links <a,b> | report | diff <older> | status]'
metadata:
  language: en
---

# multi-agent-graph - code graph build and query

**Input**: $ARGUMENTS

A code graph is a map of what this repo declares and what refers to what, built by
regex over comment-stripped source and hand-written per-language readers. It
exists so Phase 1 can narrow its Explore fan-out and Phase 5 can refresh
`~/.claude/knowledge/<project>/` without an LLM pass. It answers "where does this
live", "what depends on this" and "who calls this". The main file
(`code-graph.json`) holds files, modules, type-level symbols and their
`defines`, `imports`, `references` and `inherits` edges. Beside it sit sidecars:
`code-graph.calls.json` (function nodes and `calls` edges, built by default),
and, only when asked, `code-graph.docs.json` (documentation sections and
rationale comments) and `code-graph.infra.json` (Dockerfiles, Compose,
Kubernetes, Helm, Terraform, CI workflows, `.env` files, application config,
dependency manifests; names only). Readers join the sidecars that are present
and say so when one is absent, stale or truncated. Every `calls` edge says how
it was derived and how sure it is: `high` means a binding was resolved, `medium`
an inference, `low` only a name and argument count, which is a lead, not a fact.
Types are not inferred beyond a constructor call, an annotation or a return
type, so a receiver reached through a collection element or a function value is
unknown. ADR-0010 has the design.

No worktree, no branch, no commit, no pipeline chaining.

## Sub-commands

| Input                               | Runs                                                                                        | Notes                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| ----------------------------------- | ------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `build`                             | `graph-build.mjs --root <repo> --stack <stack> [--no-calls] [--docs] [--infra]`             | Writes `~/.claude/knowledge/<project>/code-graph.json` and the calls sidecar; `--docs` and `--infra` add those sidecars (a `code-graph.config.json` beside the graph sets them per repo, a flag wins). A sidecar a run did not build is deleted                                                                                                                                                                                                                                                                                                                                                      |
| `refresh`                           | same as `build`                                                                             | A full rebuild takes seconds, so there is no separate incremental path                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `ask "<question>"`                  | `graph-query.mjs "<question>" --budget N`                                                   | Token-budgeted traversal; default budget 2000                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `affected "<symbol>"`               | `graph-affected.mjs "<symbol>" --depth N`                                                   | Reverse traversal: the blast radius of a change                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `path <from> <to>`                  | `graph-query.mjs --path <from> <to>`                                                        | Shortest path between two symbols or files (id or name), with the confidence of each hop and, last, the weakest one; of two routes of equal length the stronger is reported. An ambiguous name is refused with candidate ids, an unknown one gets its nearest names (exit 3); external modules are never walked through                                                                                                                                                                                                                                                                              |
| `callers "<fn>"` / `callees "<fn>"` | `graph-query.mjs --callers <fn> [--depth N] [--min-confidence C]`                           | The functions that call fn, or that fn calls, to depth N (default 3, at most 15), each with `via`, its confidence and the weakest confidence on the chain. Edges below medium confidence are left out unless `--min-confidence low` asks for them (then labelled leads); `path`, `affected`, `report` and `export` apply the same default. `fn` is an id, a name or `Owner.name`; an ambiguous one exits 3 with candidates                                                                                                                                                                           |
| `export <format>`                   | `graph-export.mjs --format dot\|graphml\|csv\|mermaid [--level symbol\|file\|module]`       | The graph for other tools; `mermaid` defaults to the module-level architecture diagram. A view over `--max-nodes` (300) is raised a level until it fits                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `links <a,b,...>`                   | `graph-links.mjs build --projects <a,b,...>`, then `graph-links.mjs affected --project <b>` | Which files of one repository import another (package, module or Kotlin type names), for a run across a main repo and its libraries. Graphs stay separate (ADR-0018)                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `report`                            | `graph-report.mjs`                                                                          | Writes `GRAPH_REPORT.md` beside the graph: hubs, the most-called functions with their span, functions nothing calls (candidates with known blind spots: function values, registries, default parameters, framework entry points), configuration read and set, import cycles, clusters with cohesion, surprising connections (edges between two clusters, rarest cluster pair first, top 10), questions worth asking, modules, external dependencies, unconnected files, and symbols no other file references (candidates only - the extractor is regex, not a parser, so nothing gates on that list) |
| `diff <older-graph>`                | `graph-report.mjs --diff <older-graph>`                                                     | Files, symbols and edges added or removed since an older build, and the import-cycle count before and after                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `status`                            | `graph-report.mjs --status`                                                                 | One line: stack, scale, build time and whether `baseCommit` still matches HEAD. Never read the graph file yourself - it is 22MB on a large repo                                                                                                                                                                                                                                                                                                                                                                                                                                                      |

With no argument, run `status`, then offer `build` when no graph exists and
`refresh` when `baseCommit` differs from the current HEAD.

The toolkit serves the same graph read-only (`project` = the directory under
`~/.claude/knowledge/`): `multi-agent:graph_stats` for shape and age,
`multi-agent:graph_hubs` for the most connected nodes and
`multi-agent:graph_cluster` (optional `node`, `surprising: true`) for
clusters and cross-cluster edges, beside `multi-agent:graph_query`,
`multi-agent:graph_node`, `multi-agent:graph_neighbors`,
`multi-agent:graph_path` and `multi-agent:graph_projects`. Use
them where no shell is available. Mapping: `features/code-graph.md` "The same
graph through the toolkit".

## Steps

1. **Resolve the repo.** `PROJECT_ROOT` is the current repo root unless the user
   named another. Derive the graph path once and pass it to every call below:

   ```bash
   GRAPH_PATH="$HOME/.claude/knowledge/$(basename "$PROJECT_ROOT")/code-graph.json"
   ```

   The query, affected and report scripts default that path from the CWD's
   basename, which is not the same thing when the shell sits in a worktree or a
   sub-package, so a defaulted path can point at a graph that was never built.

2. **Resolve the stack.** Read `state.detectedStack` when a run is in flight;
   otherwise detect from project markers the way Phase 1 Step 2 does. Only stacks
   with a file in `$HOME/.claude/scripts/code-graph-rules/` can be built. A stack with
   no rule file is reported as unsupported, never guessed at.

3. **Run the sub-command.** Every script is read-only on the repo and writes only
   under `~/.claude/knowledge/`:

   ```bash
   node $HOME/.claude/scripts/graph-build.mjs --root "$PROJECT_ROOT" --stack "$STACK" --out "$GRAPH_PATH"
   node $HOME/.claude/scripts/graph-query.mjs "<question>" --graph "$GRAPH_PATH" --budget 2000
   node $HOME/.claude/scripts/graph-affected.mjs "<symbol>" --graph "$GRAPH_PATH" --depth 2
   node $HOME/.claude/scripts/graph-report.mjs --graph "$GRAPH_PATH"
   node $HOME/.claude/scripts/graph-report.mjs --graph "$GRAPH_PATH" --status
   ```

4. **Validate after a build.** A graph that parses but whose edges point at
   missing nodes yields silently truncated traversals, so the build is not
   reported as successful until the validator agrees:

   ```bash
   node $HOME/.claude/scripts/validate-code-graph.mjs "$GRAPH_PATH"
   ```

   A non-zero exit fails CLOSED: report the validator's `errors[]` verbatim and
   do not record the graph as usable.

5. **Report.** One line for a build (`files / nodes / edges / elapsed`), the
   traversal output as-is for `ask` and `affected`, the report path for `report`.

## What the output is for

`ask` returns ranked nodes plus their neighbourhood within a token budget. Feed
it to an Explore agent as the starting file set rather than pasting it into a
final answer: it is a search result, not an explanation.

`affected` returns dependents, which is what `analysis.touchedAreas[]` wants.

## Limits worth stating when reporting

- References resolve only when a name maps to exactly one declaration. A type
  declared in two files is ambiguous and is deliberately dropped, so `affected`
  under-reports for duplicated names rather than fanning out to every candidate.
- Only type-like symbols are `references` targets. Functions and methods are
  reached through `calls` edges instead, which are resolved by receiver type and
  scope, not by a bare name; a `low` one is a name and argument-count match.
  Free-text `ask` does not rank or walk functions, calls, documentation or
  configuration unless `--include` names the kinds; `path`, `callers`,
  `callees` and `affected` on a function do. Call edges never count toward
  degree, so hubs stay structural.
- A bare name reaches a type nested in another type only from inside that type
  (or an extension of it) or written qualified, and a platform name (`URL`,
  `Date`, `print`, `Map`) binds to a repository declaration only when it is in
  lexical scope. In Swift a declaration in a target the caller cannot see is
  `low`. `affected` follows edges of high and medium confidence only and marks a
  dependent reached through medium edges: list those as unconfirmed.
- A call list is a lower bound: a call through a function value, a registry,
  reflection, a default parameter value or a JSX attribute has no edge. The
  precision audited on real code is for JavaScript and TypeScript; other
  languages are fixture-verified only (`features/code-graph.md`).
- A source file the call analysis refused (over 1.5 MB, binary, a line over
  4,000 characters, over 400,000 tokens, brackets that do not balance) keeps its
  definitions and loses its calls; `stats.callFilesSkipped` counts them and
  `coverage` lists them. A source file added since the build is named in
  `freshness.addedFiles`.
- Comments and string literals are stripped before extraction, so a name that
  appears only in prose or in a string produces no edge.
- A nested declaration is a node but never a reference target. A Kotlin sealed
  case or a Python inner class named `Icon` or `Color` is declared exactly once,
  so the ambiguity rule above does not catch it, and every file that merely
  mentions the framework type of that name would otherwise gain an edge to it.
- On stacks whose exported unit is a function (Node most of all) the symbol
  layer is thin by design and the import graph between files carries the value.
  Ask `affected "<file>.mjs"` there, not `affected "<functionName>"`.
- `affected` at `--depth 1` returns direct symbol references only. An import
  whose module name matches a declaring file's basename reaches the symbol
  through that file, so its importers appear at depth 2. Keep the default
  depth of 2 unless direct references are what you actually want.
