## Code Graph (Phase 1 Step 2.6 + Phase 5 Step 3)

<!-- toc -->
- [Phase 1 Step 2.6  -  query before dispatching Explore](#phase-1-step-26---query-before-dispatching-explore)
- [Impact of a change, not of a name](#impact-of-a-change-not-of-a-name)
- [Who implements this](#who-implements-this)
- [How two symbols connect](#how-two-symbols-connect)
- [Who calls this](#who-calls-this)
- [Configuration, documentation and rationale](#configuration-documentation-and-rationale)
- [Confirming with a language server](#confirming-with-a-language-server)
- [Phase 5 Step 3  -  refresh after the branch changed code](#phase-5-step-3---refresh-after-the-branch-changed-code)
- [What the report answers that a file-level view cannot](#what-the-report-answers-that-a-file-level-view-cannot)
- [The graph is drawable, and one place already asks for it](#the-graph-is-drawable-and-one-place-already-asks-for-it)
- [The same graph through the toolkit](#the-same-graph-through-the-toolkit)
<!-- /toc -->

A deterministic, LLM-free map of what a repo declares and what refers to what,
written to `~/.claude/knowledge/<project>/code-graph.json`. Gated by
`prefs.global.codeGraph.enabled` (default `true`); with it off, no graph is
built or refreshed (a graph file already on disk is still read). Design, trade and measurements:
`docs/adr/0010-own-code-graph.md`.

### Phase 1 Step 2.6  -  query before dispatching Explore

Runs only when a rule file exists for `detectedStack`. A stack with no rule file
is reported as unsupported, never guessed at.

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

node $HOME/.claude/scripts/graph-report.mjs --graph "$GRAPH_PATH" --status
node $HOME/.claude/scripts/graph-build.mjs --root "$PROJECT_ROOT" --stack "$STACK" \
  --max-nodes "${prefs_codeGraph_maxNodes:-200000}" --json
node $HOME/.claude/scripts/validate-code-graph.mjs "$GRAPH_PATH"
node $HOME/.claude/scripts/graph-query.mjs "$TASK_TITLE $TASK_DESCRIPTION" \
  --graph "$GRAPH_PATH" --budget "${prefs_codeGraph_queryBudget:-2000}" --json
node $HOME/.claude/scripts/graph-affected.mjs "<symbol the task names>" \
  --graph "$GRAPH_PATH" --depth 2 --json
```

`GRAPH_PATH` is derived once and passed to every call. The query, affected and
report scripts default it from the CWD's basename, and a run happens in a
worktree whose basename need not equal the repo's, so a defaulted path can point
at a graph that was never built. Pass it.

Build when there is no graph at all, and when `baseCommit` no longer matches
HEAD. The missing case is the one that matters in practice: `architecture.md`
and its siblings are written in Phase 5, which is the phase a run is least
likely to reach, so a repo can have a long history of tasks and an empty
knowledge directory. The graph must not inherit that. `--status` exits 1 on a
missing file, and that exit means build, not skip.

A build is not usable until
`validate-code-graph.mjs` exits 0: a graph whose edges point at missing nodes
truncates traversals silently, so a non-zero exit means skip the injection and
run Explore as if no graph existed.

`graph-query` output becomes the Explore agents' starting file set;
`graph-affected` output feeds `analysis.touchedAreas[]`.

Use it to narrow an open-ended search, not to replace a grep for a name the task
already spells out. Measured on a 4,300-file Swift app at a fixed 30k retrieval
budget, it roughly doubled coverage at under half the cost on domain-word
questions and lost narrowly to `grep -lw` on exact type names.

### Impact of a change, not of a name

`graph-affected --diff <base>` (or `<base>..<head>`, or `--diff-file <path>`)
seeds the reverse walk from the change itself. Each hunk maps onto the
innermost declaration it touches, through spans derived from indentation
(`endLine`, schema 1.1.0; attribute and decorator lines above a declaration,
multi-line ones included, belong to it); enclosing declarations are seeded too, because
references point at types and a method alone has no dependents. The walk
continues through what each dependent file declares, so the answer is the full
blast radius to `--depth`, and the defining file is never reported as its own
dependent. The JSON names `changedSymbols`, `notIndexed` (changed files the
graph does not contain), `fileLevel` (files from a pre-1.1.0 graph, seeded
whole) and `freshness`.

`freshness` is how far the graph is behind the tree: files edited since the
build (by size and mtime against the manifest, uncommitted work included),
files removed, and whether HEAD moved. `stale: true` means the answer describes
the tree as it was; say so, or rebuild first. A full build takes seconds.
Spans are line numbers in the tree the graph was built from, so a stale graph
reads the diff on its old side (`side: "old"`): a graph built on the base
checkout maps a branch's diff correctly, and a deleted file still reaches its
dependents.

### Who implements this

`inherits` edges (schema 1.2.0) run from a subtype to each supertype the graph
defines once: a superclass, the protocols or interfaces it adopts (Swift and
Kotlin `:` lists, Python bases, TypeScript `extends` / `implements`), and a
conformance a Swift `extension` adds. `graph-affected "<Protocol>" --kind
inherits --depth 1` lists its conformers; without `--kind` the walk follows
them with every other dependency. Production code never gains an edge to a
type a test file declares, so a fake named after a framework type cannot turn
into a hub.

### How two symbols connect

`graph-query.mjs --path <from> <to>` answers with the shortest chain of edges
between two symbols or files, given by id or by name. An ambiguous name is
refused with its candidate ids and an unknown one gets its nearest names (exit
3), so the answer is never a guess. A module node (an import the repository
does not declare) can end a path but is never walked through, since it joins
every file that imports it. On Android, a capitalised `fun` (in practice a
Compose UI function) is a symbol of kind `composable`, so screens and
components take part like types.

### Who calls this

`calls` edges run from the function that contains a call to the function,
method or type it reaches, in Swift, Kotlin, TypeScript and JavaScript, Python,
Go, Rust, Java, C#, C and C++. They live in a sidecar, `<graph>.calls.json`,
built by default and joined in memory by `graph-query`, `graph-affected`,
`graph-report`, `graph-export` and `graph-hint`; the main graph file does not
change. When the sidecar is absent, stale, built against another graph or
truncated, the answer carries a note saying so (`notes` in `--json`, a line in
text output), and a caller list is then a lower bound, not a complete one.

Everything that is consumed without a person choosing it reads edges of medium
confidence and better by default: `--callers`, `--callees`, `--path`,
`graph-affected`, the report's most-called table and `graph-export`. Low edges
appear only with `--min-confidence low` (query, path, export) and are labelled
as leads.

Each edge carries `via` (typed-receiver, implicit-self, constructor,
interface-member, dispatch, import, same-file, same-directory, unique-name,
name-arity...) and a `confidence`:

- `high`: a binding was resolved: same file, an import into a repo file, a
  member of the enclosing type, a member of the receiver's declared type, or
  package-wide visibility in Go, Java, Kotlin, C# and Swift.
- `medium`: inference: a chain of return types, a dispatch to implementers, a
  weak receiver match, a name unique in the repo in a language without per-name
  imports.
- `low`: name and argument count only, or an import followed that did not reach
  the definition. A bare same-directory match in JavaScript, TypeScript and
  Python is at most `low`.

A name imported from outside the repo (`node:test`, a package) produces no
edge. A guess is never `certain`.

```bash
node $HOME/.claude/scripts/graph-query.mjs --callers "Cache.store" --graph "$GRAPH_PATH" --depth 3
node $HOME/.claude/scripts/graph-query.mjs --callees "Service.notify" --graph "$GRAPH_PATH" --min-confidence medium
node $HOME/.claude/scripts/graph-affected.mjs "Cache.store" --graph "$GRAPH_PATH"
```

`affected` follows `calls` only into a function or method that is itself a seed,
then through each caller, and reports files. It follows edges of high and medium
confidence and never a `low` one; every row carries its confidence and `via`,
and a dependent reached only through medium edges is marked so it can be
confirmed before it is reported. For a type it follows imports,
references and inheritance as before. Methods a type declares are nodes with
`symbolKind: "method"` and an `owner`. Call edges never feed degree, so hubs
and the free-text ranking stay as they were.

What a bare name may denote (ADR 0010 has the reasoning): a type nested in
another type only from inside that type or an extension of it, or written
qualified; a platform name (`URL`, `Date`, `Timeline`, `print`, `Map`, ...) only
when the repository declaration is in lexical scope; in Swift, a declaration in
another build target only when the caller's target can see it (its own target, a
module it imports, or, in a test target, the app target it is named after;
otherwise `low`). JavaScript and TypeScript arity ranks candidates and never
rejects one; a function declared inside another is visible to the closures in
it; `import { x } from m; export { x }`, `export { x } from m` and
`export * from m` are followed to the definition.

Measuring it. Three dev-only scripts, run from a checkout, with pinned seeds
(7 this repository, 278 a Next.js site, 11 a Swift app):

- `eval-call-sample.mjs --graph G --root R --confidence high --n 40 --seed 7`
  prints edges to read by hand: the caller's lines that name the callee and the
  callee's declaration.
- `eval-call-recall.mjs bare|member --graph G --root R [--n 40] [--seed 7]`
  counts the calls a reader can see that are edges. `bare` is JavaScript and
  TypeScript over the whole population (this repository 99.7%, the site 99.9%);
  `member` samples functions in any language and over-counts, because a call on
  a library object that shares a repository name counts as a miss.
- `eval-call-scope.mjs --graph G --root R` counts the `high` edges the Swift
  scope rules rule out (a nested type reached from outside its outer type, a
  platform-named symbol reached from another file). Both counts must be zero.

Edges by confidence on those trees: this repository 13,249 high / 66 medium /
453 low; the site 3,915 / 1 / 0; the Swift app 3,629 / 1,371 / 165. A sample of
40 with no error bounds the error rate at about 7% with 95% confidence, 8 with no
error at about 38%. A `low` edge is an unresolved binding: often right in
script-style code that shares globals, a lead anywhere else. Trust `high`,
confirm `medium`, ask for `low` explicitly.

Swift member-call recall is a named limit (15 of 23 member calls to repository
names have an edge with seed 11 on the Swift app; the rest include library name
clashes). The resolver's own misses have three causes: a local bound by a cast
inside a longer expression (`guard let c = x as? Cell` is read), a local bound to
a shared instance whose static is initialised by a closure, a factory or a
computed property (a typed or constructor-initialised static is read), and a
static extension method on a platform type called through the type.

Python, Go, Rust, Java, C#, C++ and Kotlin precision is fixture-verified only:
`eval-call-edges.mjs` checks nine hand-written cases (147 expected edges, pooled
recall 98.0%, precision at medium and above 100.0%); no real tree of those
languages was sampled.

"Functions nothing calls" in `graph-report` is a list of candidates, not dead
code: a function reached through a function value, a registry, reflection, a
framework entry point or a self-recursive call has no `calls` edge, and the
section says so.

### Configuration, documentation and rationale

Two more sidecars are opt-in (`graph-build --infra`, `--docs`, or
`code-graph.config.json` beside the graph with `{"infra": true, "docs": true}`;
a flag beats the file):

- `<graph>.infra.json`: `infra` nodes (a Dockerfile stage, Compose service,
  Kubernetes resource, Helm chart, Terraform block, CI workflow or job), `env`
  (a variable name) and `config` (a Helm value, a BuildConfig field, an
  application config key), joined by `sets`, `uses`, `builds`, `runs` and
  `reads` edges. A source file that reads `process.env.X`, `os.getenv("X")` and
  the like gets a `reads` edge to the `env:X` node that a Compose file,
  manifest, workflow or `.env` file also points at, so `--path <file> env:X`
  reaches the place the variable is set. `graph-report` lists variables read and
  set nowhere in the repo, and the reverse. Dependency manifests (package.json,
  Cargo.toml, go.mod, requirements, pyproject, Podfile, Package.swift,
  pom.xml, build.gradle, csproj) become dependency module nodes. Only names are
  stored, never values.
- `<graph>.docs.json`: documentation sections (`doc`) mention the files and
  symbols they name in backticks, a decision record's first heading is
  `symbolKind: "adr"`, and a code comment starting NOTE, WHY, HACK or citing an
  ADR is a `rationale` node that `explains` the declaration around it.

Each sidecar has its own schema and version, caps on nodes and edges (calls
250,000 / 1,000,000; docs 20,000 / 80,000; infra 30,000 / 120,000) with a
`truncated` marker, and a manifest of the files it read, so a documentation or
configuration file changed after the build makes the layer stale. Readers say
when a layer is off, absent or stale instead of answering as if it were empty.
Free-text `ask` leaves all of these out; `ask --include doc,infra` brings them
in. Files are read only when they are regular files inside the repo root;
symlinks are not followed.

### Confirming with a language server

The graph joins by name, so a direct dependent can be a file that only uses
the same word, and a dependent behind an ambiguous name is missing; a `low`
call edge is the same kind of lead. Where the
toolkit's `code_references` (≥ v3.22.2) has an index (Swift through sourcekit-lsp, Kotlin
through kotlin-lsp), check the answer before a decision rests on it: call
`code_references` with `file` and `symbol` for each changed type (at most five).
With the Write tool, save the `graph-affected --json` answer as
`$RUN_DIR/affected.json` and the `code_references` results as a JSON array in
`$RUN_DIR/references.json` (`$RUN_DIR` is the run's log directory, where
`agent-state.json` lives), then merge:

```bash
node $HOME/.claude/scripts/graph-confirm.mjs --affected "$RUN_DIR/affected.json" \
  --references "$RUN_DIR/references.json" --root "$PROJECT_ROOT"
```

Each direct dependent comes back `confirmed`, `name-only` (a ready semantic
index did not find it: treat it as a probable false positive) or `unchecked`
(a deeper ring, or no usable index); `lspOnly` names files the server found
that the graph missed. An answer with `indexReady: false` or `semantic: false`
confirms and demotes nothing.

Phase 3 Step 1.75 passes the graph to `diff-risk-score.mjs --graph`, which adds
`dependents_reached`: the distinct non-test files two rings out, capped so a
hub cannot outweigh a security path. No graph, no signal, nothing fails.

### Phase 5 Step 3  -  refresh after the branch changed code

Runs when `prefs.global.codeGraph.enabled` and `prefs.global.codeGraph.autoRefresh`
are both true.

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

node $HOME/.claude/scripts/graph-build.mjs --root "$PROJECT_ROOT" --stack "$STACK" \
  --max-nodes "${prefs_codeGraph_maxNodes:-200000}" --json
node $HOME/.claude/scripts/validate-code-graph.mjs "$GRAPH_PATH"
node $HOME/.claude/scripts/graph-report.mjs --graph "$GRAPH_PATH"
```

The report adds three whole-graph views (`_graph-analysis.mjs`): import cycles
(files that import each other, directly or around a loop), clusters of files
more connected to each other than to the rest (label propagation over imports
and references, with cohesion = the share of a cluster's edges that stay
inside), and a short list of questions worth asking before a change, drawn
from the hubs, the cycles and the strongest links between clusters. All three
are deterministic, so a changed report means changed code. `graph-report.mjs
--diff <older graph>` lists what changed between two builds.

A run across several repositories (dev-context extras, submodules) joins their
graphs with `graph-links.mjs build --projects <a,b,...>`: an import of a name
one repository does not declare is matched against what the others export,
and `graph-links.mjs affected --project <b>` lists the files elsewhere that
import b. The graphs are not merged (ADR-0018).

The rebuild costs no API tokens, so it runs every task rather than on a staleness
heuristic. A non-zero validator exit keeps the previous graph and logs
`knowledge.graph_invalid`; it never fails the run - a stale graph is a degraded
Phase 1, not a broken deliverable.

### What the report answers that a file-level view cannot

`GRAPH_REPORT.md` ends with **Symbols nothing else references**: symbols no other
file in the repo names. The older "unconnected files" section only ever found
files with NO edge at all, so a file imported for one symbol while three of its
other exports were dead looked healthy.

It is candidates, never verdicts, and it gates nothing. The extractor is regex
over comment-stripped source, not a parser (ADR-0010), so dynamic dispatch,
reflection, string-keyed lookup and a public API consumed outside this repo are
indistinguishable from dead code here. Four classes are therefore excluded and
COUNTED rather than listed, because they could not carry a reference edge however
heavily they are used: a kind outside the stack's `referenceKinds`, a name
declared in more than one place (the builder drops ambiguous tokens), a nested
declaration, and anything declared in a test file. Symbols referenced ONLY from
tests are listed separately - that is not dead code, it is code whose only
consumer is its own test, which is worth knowing before a plan calls it
load-bearing.

### The graph is drawable, and one place already asks for it

The PR body's Impact Analysis, part 3, asks which symbols and files a change
reaches. That is `graph-affected.mjs`'s question, and until now the answer was
re-typed as prose by a model while the measurement sat on disk unread.

```bash
node $HOME/.claude/scripts/graph-mermaid.mjs "<symbol[,symbol]>" [--depth N] [--max-nodes N]
```

It emits a fenced `flowchart` and nothing else - no renderer, no plugin, no
dependency, because mermaid is text and GitHub renders it natively in pull
requests, issues and markdown files. Traversal is not reimplemented: `findByName`
and `affected` are imported from `graph-affected.mjs`, so the diagram and the
text report cannot disagree about what is affected.

Three properties that are enforced rather than promised
(`smoke-graph-mermaid.sh`):

- Every drawn node and edge resolves back into `code-graph.json`, with the edge
  kind it claims. A diagram is read as fact and checked less than prose, so an
  invented edge is the expensive failure.
- Over `--max-nodes` the leftover count is printed inside the diagram, not
  dropped. A small picture of a large blast radius reads as reassurance.
- The graph's `baseCommit` is printed beside it. A graph built before the change
  draws an older tree, and nothing else in the PR would reveal that.

Exit 1 with a reason on stderr means no graph or no such symbol. The caller
records the gap and writes the prose alone; it never hand-draws a replacement.

Jira is not a target: its renderer turns the fence into a literal
`{code:mermaid}` block. Confluence renders it through the `ac:name="mermaid"`
macro when the space carries the plugin (`channels/confluence.md`).

### The same graph through the toolkit

The toolkit reads the same `~/.claude/knowledge/<project>/code-graph.json` over
MCP, so an agent without a shell (a read-only reviewer, a Copilot or Codex
session) gets the graph too. `project` is the directory name under
`~/.claude/knowledge/`; `mcp__multi-agent__graph_projects` lists them.

| Need                              | Tool                                                                                                                                   | Script equivalent                                |
| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ |
| Starting file set for a question  | `mcp__multi-agent__graph_query` (`project`, `query`, optional `budget` or `tier`)                                                      | `graph-query.mjs` (`--tier`)                     |
| One node and its edges            | `mcp__multi-agent__graph_node` (`project`, `id` or `name`)                                                                             | none                                             |
| Dependents or dependencies        | `mcp__multi-agent__graph_neighbors` (`project`, `id`, optional `direction`, `kinds`, `depth`, `limit`)                                 | `graph-affected.mjs`                             |
| How two nodes connect             | `mcp__multi-agent__graph_path` (`project`, `from`, `to`, optional `kinds`, `maxDepth`, `directed`)                                     | `graph-query.mjs --path`                         |
| Is the graph sane and current     | `mcp__multi-agent__graph_stats` (`project`): counts by kind, age in days, base commit, whether the stats header agrees with the arrays | `graph-report.mjs --status`                      |
| Hubs a change will ripple through | `mcp__multi-agent__graph_hubs` (`project`, optional `kinds`, `nodeKind`, `limit`)                                                      | the report's hubs section                        |
| Clusters and cross-cluster links  | `mcp__multi-agent__graph_cluster` (`project`, optional `node`, `limit`, `surprising`)                                                  | the report's clusters and surprising connections |

Phase 1 Step 2.6 still runs the scripts, because it also builds and validates.
The tools are for reading a graph that already passed `validate-code-graph.mjs`:
before a plan touches a file, `graph_cluster` with `node` set to it and
`surprising: true` names the cross-cluster edges worth a second look, and
`graph_hubs` says whether the file is one of the few everything depends on.
A `graph_stats` age or base commit that disagrees with HEAD means refresh first.

`tier` (`--tier` on the script) answers at a fixed size instead of a token
budget, and the toolkit and the script share the sizes and the fitter
(`lib/tiered-budget.mjs`, vendored into the toolkit): `quick` is the top
matches in about 1.5k characters, `panorama` adds the hubs and clusters around
them and their direct neighbours in about 6k, `deep` gives full node detail,
neighbours two hops out and the shortest paths between matches in about 12k.
Whole rows are dropped to fit and the answer says how many. Without a tier both
answer exactly as before. `learnings-ledger.mjs brief|profile --tier` and the
toolkit's `learnings_search` take the same three tiers.
