# 10. Our own code graph, not a forked one

**Status:** Accepted · 2026-08-28

> **Phase numbers below are the eight-phase ones.** [ADR-0014](./0014-six-phase-consolidation.md) renumbered the contract in v19.0.0 (`phase-1-analysis.md` is now `phase-1-plan.md` and Phase 7 Report is now Phase 5). The decision this ADR records is unchanged; only the labels moved, and they are left as written because an ADR records what was decided.

## Context

Two parts of the pipeline were paying for the same missing capability.

Phase 1 dispatches parallel Explore agents that re-scan the repository with
grep and read on every task, and `phase-1-analysis.md` makes the "very
thorough" tier the default for feature, refactor and component work. Phase 7
writes `~/.claude/knowledge/<project>/architecture.md` with an LLM, from the
narrow window of whatever task happened to run, and the file is treated as
stale after 90 days.

Both want the same thing: a cheap, current answer to "where does this live"
and "what depends on this".

A public code-graph tool solved this and, unlike most projects in the space,
published numbers for it. Its benchmark measures a fixed coding agent on ERPNext (~1M lines) over a graded question
set: key-fact coverage rises from 70.8% on a grep-and-read baseline to 82.0%
with a graph tool, at ~140K tokens per query, n=6. The baseline it beats is
our Phase 1.

The obvious move was to adopt it. Two things ruled that out. Its extraction
is built on tree-sitter, which is a native npm runtime dependency and
therefore forbidden by ADR-0004. And depending on an external repository for
a capability this central puts the pipeline's core behaviour outside our
control.

## Decision

Build the capability inside the pipeline as our own implementation; no code
is taken from another project.

Its properties: extraction is deterministic and LLM-free; the artifact is a
single `graph.json` of typed nodes and edges; hub ("god-node") ranking is the
highest-signal line of the report; queries are token-budgeted traversals
rather than neighbourhood dumps; reverse traversal answers impact; and the
measurement methodology is a graded question set against a grep-and-read
baseline with the same cost accounting on both arms.

Not adopted: tree-sitter (ADR-0004), LLM-named communities (the pipeline
already has model routing for that), an MCP server (we ship our own toolkit),
and its multi-platform installers and hooks.

The engine is `pipeline/scripts/_code-graph.mjs`, with per-stack rules in
`pipeline/scripts/code-graph-rules/<stack>.json` (ios, android, node, python,
go, rust, java, csharp, cpp), a call-edge resolver under
`pipeline/scripts/call-graph/`, an infrastructure and documentation extractor
under `pipeline/scripts/infra/`, entry points (`graph-build`, `graph-query`,
`graph-affected`, `graph-report`, `graph-export`, `validate-code-graph`), a
schema at `pipeline/schemas/code-graph.schema.json`, and the
`/multi-agent:graph` command. It sits behind
`prefs.global.codeGraph.enabled`, off when this was decided and on by default
since ADR 0017's change-impact work made Phase 3 depend on it.

## Layers: a main graph and sidecars

The main graph file (`code-graph.json`, schema 1.2.x) holds files, modules and
type-level symbols with `defines`, `imports`, `references` and `inherits` edges
only. Everything a newer capability adds sits in a sidecar file next to it:

| Sidecar | File                 | Built      | Holds                                                                                                  |
| ------- | -------------------- | ---------- | ------------------------------------------------------------------------------------------------------ |
| calls   | `<graph>.calls.json` | by default | function and method nodes, `calls` edges                                                               |
| docs    | `<graph>.docs.json`  | opt-in     | documentation sections, rationale comments                                                             |
| infra   | `<graph>.infra.json` | opt-in     | Dockerfile, Compose, Kubernetes, Helm, Terraform, CI, `.env`, application config, dependency manifests |

`--no-calls`, `--docs` and `--infra` on `graph-build` choose the layers for one
run; `code-graph.config.json` beside the graph (`{"calls": false, "docs": true,
"infra": true}`) chooses them per repo and a flag beats it. A sidecar a run did
not build is deleted, so none outlives the graph it was made against.

Each sidecar has its own schema (`code-graph-calls`, `-docs`, `-infra`) and
version. It records the graph it was built against (`parent`: generatedAt,
baseCommit, stack, node and edge counts), carries node and edge caps (calls
250,000 / 1,000,000; docs 20,000 / 80,000; infra 30,000 / 120,000), and a
`truncated` marker when a cap dropped something: edges go weakest-first, then
nodes no kept edge needs. The docs and infra sidecars also list the files they
read in a manifest, so a documentation or configuration file edited or added
after the build makes the layer stale.

Why a separate file: the published toolkit and every older reader validate the
main graph against schema 1.2.x and know its kinds. Folding calls, documentation
and configuration into it would double the file and break those readers.
With sidecars the main file is within 1 KB of the size it had before this
work (24.21 MB on the reference Swift app), HEAD's validator accepts it, and the
toolkit keeps working unchanged. New abilities are additive.

Readers (`graph-query`, `graph-report`, `graph-export`, `graph-affected`,
`graph-hint`) join the sidecars in memory when they are present and say plainly,
in a `notes` list or a stderr line, when one is absent, stale (the graph or the
manifest inputs moved), built against another graph (not joined), invalid, or
truncated. Joined nodes carry a `layer` and a degree of 0: hub and degree
metrics stay structural, so a call edge never ranks a function above a type.

## Call edges without a language server

Definitions and imports are regex over comment-stripped source. Calls need more
than a regex, and a tree-sitter binding is still forbidden, so `call-graph/`
holds a hand-written tokeniser, a bracket matcher and one declaration reader per
language (Swift, Kotlin, TypeScript and JavaScript, Python, Go, Rust, Java, C#,
C and C++), chosen by file extension. It finds the declarations of a file (types,
functions, fields, parameters, imports), reads each function body as call
chains (`root.member.method(args)`), and resolves the chains across files:

- the receiver's type from a declaration, a parameter, a field, `self`, a
  constructor call, or the return type of the previous call in the chain
- the method on that type, on its supertypes, and on the extensions, impl blocks
  and receiver methods that add to it
- a call through a protocol or interface, or to a method a subclass overrides,
  also reaches each implementer's method (Go interfaces are satisfied
  structurally)
- a bare call to a method of the enclosing type, a function in the same file, an
  imported module, or a constructor
- overloads by argument count and labels; what stays ambiguous is reported as
  ambiguous. JavaScript and TypeScript calls may pass any number of arguments,
  so arity ranks candidates there and never rejects one

Every local, parameter and nested function is bound in its scope, so a name that
shadows an outer function resolves to the local one and produces no edge. A
function declared inside another is hoisted to the whole enclosing body and is
visible to the closures in it; a name the enclosing function binds as a plain
variable stays that variable inside the nested function. A module-level
variable that holds a function is the callee of a bare call in its own file.

What a bare name may denote:

- A type nested inside another type is reached by its bare name only from code
  lexically inside the outer type or an extension of it (and, in Java and C#,
  from a subclass). From anywhere else it needs the qualified spelling
  (`Outer.Inner(...)`). In type position, where a bare spelling can be a
  shortened qualified one, a nested type is reachable at medium.
- A name every platform already owns (`URL`, `Date`, `Timeline`, `Text`,
  `print`, `Map`, `fetch`, `List`, ...; a short list per language in
  `call-graph/platform.mjs`) is the platform's. It binds to a repository
  declaration only when that declaration is in lexical scope: the same file, an
  enclosing type, or a module an import names.
- In Swift a declaration in another build target is seen only when the caller's
  target can see it. A target is the `Sources/<Target>` or `Tests/<Target>`
  directory of a package, or the first directory of an Xcode project; a caller
  sees its own target, a module it imports, and, in a test target, the app target
  it is named after. A unique match in a target the caller cannot see is `low`.
- A name bound by an import that leads outside the repository is external (no
  edge), whatever repository function shares it. Only a language whose imports
  name modules a path can reach (`moduleSuffixes`) can call an import external;
  elsewhere an unresolved import degrades the edge to low.
- `import { x } from m; export { x }`, `export { x } from m` and
  `export * from m` are followed to the file that defines `x`.

Each `calls` edge records how it was derived (`via`) and a confidence defined
by what the resolver proved:

- `high`: a binding was resolved. The callee is in the same file, in a repo file
  the caller imports by that name (through re-exports too), a member of the
  enclosing type, a member of the receiver's declared type, or visible
  package-wide in a language whose scope is the package (Go, Java, Kotlin, C#)
  or in the caller's own Swift target.
- `medium`: inference. The type came through a chain of return types, a weak
  receiver match, a dispatch to implementers, a type found by its bare name in
  another package or in a Swift target reached by import, or a name unique in the
  repo in a language without per-name imports.
- `low`: an unresolved binding: only the name and argument count identify the
  callee, or an import was followed that did not reach the definition, or the
  caller's target cannot see the declaration. A bare call that matches only a
  same-directory file in JavaScript, TypeScript or Python is at most `low`: a
  directory is not a scope in those languages. In script-style code, where
  files share globals, such an edge is often right; anywhere else it is a lead.

A guess is never `certain`; the calls schema and validator reject it. A receiver
of a library type produces no edge, except for a method an extension in the
repository adds to that type: that edge is at most `medium`, and `high` only when
the call uses a parameter or shape only the extension declares. An unknown
receiver falls back to a method name that is unique in the repository, at low confidence and never for a
name common in standard libraries or on web and DOM objects.

Everything that is consumed without a person choosing it reads edges of medium
confidence and better by default: `--callers`, `--callees`, `--path`, the
report's most-called table and `graph-export`. `graph-affected` never follows a
`low` edge, prints each row's confidence and `via`, and marks a dependent
reached only through medium edges. Low edges appear only on request
(`--min-confidence low`) and are labelled as leads.

A call is attributed to the function that contains it, which becomes a node of
its own (`symbolKind` method or function, with an `owner`); a call outside any
function belongs to the file. A function is a node only in the calls sidecar.
Its id is its qualified name; an overload adds its parameter labels
(`Song.init(title:id:)`) and a true duplicate a numeral, so an id does not
change when lines above it move.

What it costs in precision and recall, stated so a reader does not assume more:

- No type inference beyond a constructor call, an annotation or a return type.
  A receiver reached through a collection element, a closure's return value, a
  generic container, a function value, a registry lookup or reflection is
  unknown, and a call through such a value has no edge.
- Overloads that differ only by parameter type cannot be told apart; they are
  reported as ambiguous with low confidence.
- Macros and code generation are invisible. In C and C++ each `#if` / `#else`
  branch is read with its own bracket state.
- A trailing closure without parentheses (`foo { }`) is not a call.
- Parameter lists are scanned for calls (a default value such as
  `copy = (a, b) => copyDir(a, b)`) in TypeScript and JavaScript only; the other
  languages read function bodies. Nested functions are resolved in TypeScript and
  JavaScript only. A self-recursive call has no edge.
- A dynamic import with a computed path binds nothing, and the calls on its
  destructured names resolve at low confidence.
- Swift target boundaries come from directories and `import` lines, not from the
  project file, so a project whose directories do not follow its targets sees
  more `low` and `medium` edges than the truth.
- The lexer follows nested block comments (Swift, Kotlin, Rust), raw strings
  (Swift `#"..."#`, Rust `r#"..."#`, C++ `R"x(...)x"`), and calls inside string
  interpolation (Swift, Kotlin, JavaScript).
- A file over 1.5 MB, a binary one, one with a line over 4,000 characters, one
  with more than 400,000 tokens, nesting deeper than 400, brackets that do not
  balance, or that takes more than 2.5 s to analyse is not call-analysed; its
  definitions are still in the graph and the count is in
  `stats.callFilesSkipped`, the files and reasons in `coverage`. A build whose
  call analysis passes four minutes in total stops analysing and records
  `total-time-budget`; resolving the calls has its own two-minute budget, and the
  files it did not reach are listed as `resolve-time-budget`.

## Configuration, documentation and rationale as nodes

With `--infra`, Dockerfiles, Compose files, Kubernetes manifests, Helm charts,
Kustomize, Terraform and Terragrunt, GitHub Actions and GitLab CI, `.env` files,
Gradle build configuration, application configuration files and dependency
manifests are read into `infra`, `env`, `config` and `module` nodes with `sets`,
`uses`, `builds`, `runs` and `reads` edges. Code that reads a variable or key by
a literal name (`process.env.X`, `os.getenv("X")`, `System.getenv`,
`@Value("${a.b}")`, `BuildConfig.X`, ...) gets a `reads` edge to the same `env:`
or `config:` node the infrastructure sets or defines. Only names are stored,
never values.

With `--docs`, documentation sections and decision records become `doc` nodes
with `mentions` edges to the files and symbols they name in backticks, and a
code comment that opens with NOTE, WHY, HACK or cites an ADR becomes a
`rationale` node with an `explains` edge to the declaration around it.

Both extractors read only regular files inside the repository root (symlinks
are not followed, nothing is read through one), bound every file by size, line
length, nesting and node count, run every pattern in linear time, and stop
collecting after 30 s, listing what they skipped in `coverage.skipped`. The YAML
reader keeps maps without a prototype, so a key named `__proto__`,
`constructor` or `prototype` is data.

## What we deliberately gave up

Definition extraction is regex over comment-stripped source, and the call
resolver is a set of lightweight readers, not parsers. Two further limits
follow from the same choice and are documented in the command rather than
hidden:

- A reference resolves only when a name maps to exactly one declaration. A
  type declared in two files is dropped rather than fanned out to both, so
  `affected` under-reports on duplicated names.
- Only type-like symbols are reference targets. An early build let functions
  be targets and the hub list filled with `with`, `localized`, `size` and
  `name`: a bare lowercase name matched across files is almost never a call to
  that exact declaration. The same measurement was repeated per stack rather
  than assumed: on this repo, including JavaScript functions put `ok` at degree
  52 and `f` at 38.
- A nested declaration is a node but never a reference target. Sealed
  hierarchies name their cases after the concept they model - `Icon`, `Color`,
  `Success` - and each is declared exactly once, so the ambiguity rule does not
  catch them. Before this rule, every Kotlin file that merely mentioned the
  framework's `Color` gained an edge to one app's nested case: 4,072 false
  edges out of 74,969.

## Measurement

Call-edge quality is measured three ways, and they are kept apart.

Fixtures: `eval-call-edges.mjs` runs nine hand-checked cases, one per language,
under `pipeline/eval/call-edges/` (small sources, a list of every call to
something the sources define, a floor per case). A call to a library is not
listed, so an edge for it counts against precision. Pooled over 147 expected
edges: recall 98.0%, precision at medium and above 100.0%. The cases include
calls the resolver cannot follow, so recall is not 100%.

Samples to read by hand. Precision on real code is checked, not computed:
`eval-call-sample.mjs` prints a reproducible sample of edges, each with the
caller's lines that name the callee and the callee's declaration. The seeds are
fixed: 7 for this repository, 278 for a Next.js site, 11 for a Swift app.

```
node pipeline/scripts/graph-build.mjs --root <repo> --stack <node|ios> --out <dir>/code-graph.json
node pipeline/scripts/eval-call-sample.mjs --graph <dir>/code-graph.json --root <repo> \
     --confidence high --n 40 --seed 7
node pipeline/scripts/eval-call-sample.mjs --graph <dir>/code-graph.json --root <repo> \
     --confidence low --n 8 --seed 7
```

Edge counts by confidence, from the same build on the three trees:

| Tree                                    | high   | medium | low |
| --------------------------------------- | ------ | ------ | --- |
| this repository (875 files, JavaScript) | 13,249 | 66     | 453 |
| site (410 files, TypeScript)            | 3,915  | 1      | 0   |
| Swift app (499 files)                   | 3,629  | 1,371  | 165 |

A sample of 40 with no error bounds the error rate of the population at about
7% with 95% confidence, and 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.

Scope rules, counted mechanically on a Swift graph: `eval-call-scope.mjs` counts
`high` constructor edges to a nested type from a caller outside its outer type
that does not spell the name qualified, and `high` edges to a top-level
repository symbol with a platform name reached from another file. Both must be
zero; it exits 1 otherwise.

```
node pipeline/scripts/eval-call-scope.mjs --graph <dir>/code-graph.json --root <swift-repo>
```

Recall of bare calls on JavaScript and TypeScript, whole populations: for every
function, each bare call to a function its own source binds (defined in the same
file or imported from a repository file) should be an edge.

```
node pipeline/scripts/eval-call-recall.mjs bare --graph <dir>/code-graph.json --root <repo>
```

This repository: 7,940 of 7,966 (99.7%); the site: 2,243 of 2,245 (99.9%). What
remains missed: a self-recursive call (an edge to oneself is not emitted), a
callback parameter that shares a repository function's name (the script counts
it, the resolver is right not to), a name that is rebound inside a nested
function, and a call through a computed dynamic import. Calls through a function
value, a registry or reflection are not counted by that script and are not edges
either.

Member-call recall is a named limit for Swift. `eval-call-recall.mjs member`
takes a seeded sample of functions and counts each `.name(` call whose name is a
function of the repository; it over-counts, since a call on a library object
that shares a name counts as a miss. With seed 11 on the Swift app, 15 of 23
such calls have an edge. The misses that are the resolver's, and not name
clashes with a library, have three causes:

- a local bound by a cast: `guard let c = x as? Cell` is read (medium); a cast
  inside a longer expression is not;
- a local bound to a shared instance: `let m = Mgr.shared` is read when the
  static is declared with a type or a constructor call; one initialised by a
  closure, a factory function or a computed property, and an instance property
  initialised that way, are not;
- a static extension method on a platform type, called through the type.

```
node pipeline/scripts/eval-call-recall.mjs member --graph <dir>/code-graph.json --root <repo> \
     --n 40 --seed 11
```

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%) and no real tree of those
languages was sampled.

The question set is the guard for ranking: a change to the graph must not lower
its coverage there. On the reference Swift app (4,428 files, 30,394 nodes, main
graph 24.21 MB, HEAD's validator accepts it) the grep-and-read arm scores 67.0%
at 25,347 tokens per question and the code graph 78.06% at 19,494, the coverage
the main graph reaches alone. A build takes 4.4 to 5.2 s with the calls sidecar
(21.9 MB) against 2.7 to 3.0 s without it.

Gated on a large private Swift app: 4,290 sources, 29,212 nodes, 54,626 edges,
built in 3.2s, validator clean. Build time is dominated by reading the tree, so
a repo whose files are not in the page cache costs more: the first build of the
4,229-file Kotlin app took 18.2s and every later one 2.4-3.4s. Ten graded questions, both arms capped at a
30,000-token retrieval budget, ground truth derived by grep and path match so
that the impact family is stacked against the graph on purpose.

| Arm         | Coverage | Tokens/question |
| ----------- | -------- | --------------- |
| grep + read | 66.0%    | 24,555          |
| code graph  | 80.4%    | 18,465          |

The aggregate passes the gate, but the split is the useful part. On questions
naming an exact type, `grep -lw` is the oracle: it scored 100% and the graph
was marginally worse and marginally more expensive. On questions phrased in
domain words, the graph scored 63.3% against 32.0% at 10,937 tokens against
24,983. The value is in narrowing an open-ended search, not in replacing a
grep for a name you already know.

The harness, the ten graded questions and the raw per-question result live
beside the graph they measured, under `~/.claude/knowledge/<project>/gate/`.
They stay there rather than in this repo because they name the private
codebase's files and symbols, and a number nobody can re-derive is an assertion
rather than a measurement: `node run-gate.mjs` reproduces the table above.

That measurement covers the context each strategy assembles, not the quality
of an answer written from it. The published numbers measure the latter. The two
are not directly comparable and this ADR does not claim they are.

## Consequences

Positive:

- No new runtime dependency; ADR-0004 holds.
- Graph construction costs no API tokens, so Phase 7 can refresh it every run
  instead of ageing an LLM-written file for 90 days.
- Staleness becomes a commit comparison rather than a date heuristic.
- Every stack after the first is one rules file. Bringing up Kotlin, Python
  and JavaScript needed two engine changes, and both were engine defects that
  iOS had been getting away with rather than stack requirements: nesting was
  measured from the pattern's match column, so `public final class Foo` read as
  nested, and the import pass read a fully stripped body, which blanks a
  JavaScript module specifier because it is a string literal. iOS was re-gated
  after both and scored identically.

Negative:

- Accuracy is bounded by regex extraction and will stay below what a parser
  would give.
- Each supported stack carries a hand-written rules file that has to keep up
  with its language.
- The symbol layer is thin on stacks whose exported unit is a function. On
  Node the useful graph is the import graph between files, and the command
  says so rather than implying a richness the stack does not have.
- A 4,400-file repo produces a main graph of about 24 MB (unchanged by this
  work) and a calls sidecar of about 22 MB. Both are read whole on every query;
  that is fine at this scale and is not proven at ten times it.
- A build with the calls sidecar costs about 60% more than without it (4.4 to
  5.2 s against 2.7 to 3.0 s on a large Swift app).
- `low` call edges are leads, not facts; the sidecar keeps them because a
  reader can filter on `--min-confidence`, and says so in every report.
