No single person can hold a large codebase in their head. A knowledge graph externalizes understanding into a queryable structure. Here's the 4-week playbook to build one.
Two years ago, a new engineer on my team asked me how our payment system worked. I started drawing on a whiteboard: "The API gateway calls the payment service, which talks to Stripe, and then events go to the billing service, which updates the ledger, and..." I was 10 minutes into the explanation and had filled two whiteboards. The engineer looked more confused, not less.
That's when I realized the problem. Our codebase had grown to a point where no single person could hold the full picture in their head. The architecture existed in fragments across dozens of engineers' mental models, outdated wiki pages, and tribal knowledge shared over lunch. We needed an externalized, queryable representation of how our system actually worked. We needed a knowledge graph.
A codebase knowledge graph is a structured representation of the entities in your codebase and the relationships between them. Think of it as the data model behind the whiteboard drawing, except it's generated from actual code rather than someone's memory.
Entities include:
Modules/packages: The organizational units of your code
Functions/classes: The building blocks
APIs/endpoints: The boundaries
Data models: The schemas and types
Dependencies: Both internal and external
Tests: And what they cover
Engineers: And what they own
Relationships include:
"Module A imports Module B"
"Function X calls Function Y"
"Endpoint /api/payments depends on Service Z"
"Engineer Jane is the primary contributor to Module A"
"Data model User is referenced by 47 functions across 12 modules"
# The Contrarian Take: Static Analysis Alone Won't Cut It
Most attempts at building codebase knowledge rely on static analysis: parsing import statements, building ASTs, and tracing type references. That's necessary but insufficient. Static analysis tells you what the code could do. It doesn't tell you what the code actually does in production.
I've seen dependency graphs that show Module A imports Module B, but the actual call path in production goes A -> C -> D -> B because of runtime configuration and dependency injection. The static graph is technically correct and practically useless.
A real knowledge graph combines three data sources:
Static analysis: What the code says (imports, types, function signatures)
Runtime data: What actually happens (call traces, API logs, database queries)
Human context: Why it's this way (ADRs, commit messages, ownership data)
Figure 1. One codebase, three layers. Static analysis says A imports B; tracing shows calls really go A → C → D → B; the human layer adds who owns what and why.
Start with what's easiest to extract: the import graph and call graph from static analysis.
typescript
// Using TypeScript compiler API to extract importsimport * as ts from "typescript";function extractImports(sourceFile: ts.SourceFile): string[] { const imports: string[] = []; ts.forEachChild(sourceFile, (node) => { if (ts.isImportDeclaration(node)) { const moduleSpecifier = node.moduleSpecifier; if (ts.isStringLiteral(moduleSpecifier)) { imports.push(moduleSpecifier.text); } } }); return imports;}// Build the import graph for your entire codebase// fileNames: every source file, e.g. from ts.parseJsonConfigFileContent(tsconfig)function buildImportGraph(fileNames: string[]): Map<string, string[]> { const program = ts.createProgram(fileNames, {}); const graph = new Map<string, string[]>(); for (const sourceFile of program.getSourceFiles()) { if (!sourceFile.isDeclarationFile) { graph.set(sourceFile.fileName, extractImports(sourceFile)); } } return graph;}
Static analysis misses runtime behavior. Add OpenTelemetry tracing to capture actual call paths:[2]
typescript
// Instrument key service boundaries to capture runtime relationshipsimport { trace, SpanStatusCode } from "@opentelemetry/api";const tracer = trace.getTracer("knowledge-graph-builder");export function instrumentedHandler(name: string, handler: Function) { return async (...args: unknown[]) => { const span = tracer.startSpan(name); try { const result = await handler(...args); span.setStatus({ code: SpanStatusCode.OK }); return result; } catch (error) { span.recordException(error as Error); span.setStatus({ code: SpanStatusCode.ERROR }); throw error; } finally { span.end(); } };}// Use distributed tracing data to build runtime call graph// Export traces to Jaeger/Zipkin, then query for service relationships
The runtime graph often reveals surprises. On one project, tracing showed that our "notification service" was actually the most-called service in the system because 14 other services sent events through it. The static analysis only showed 3 direct imports.
Change coupling is incredibly revealing. Files that frequently change together have an implicit relationship that static analysis can't see. If payment-processor.ts and email-templates.ts change together in 80% of commits, there's a hidden dependency your architecture diagram doesn't show.[3]
ADR references:
Link Architecture Decision Records to the modules they affect. This turns "why is this code like this?" from a Slack question into a graph query.[4]
For small-to-medium codebases, a JSON file with graph algorithms is sufficient:
typescript
// Simple graph queries without a graph databaseclass CodebaseGraph { private adjacency: Map<string, Set<string>> = new Map(); private nodeData: Map<string, CodebaseNode> = new Map(); addNode(node: CodebaseNode): void { this.nodeData.set(node.id, node); if (!this.adjacency.has(node.id)) { this.adjacency.set(node.id, new Set()); } } addEdge(source: string, target: string): void { this.adjacency.get(source)?.add(target); } // "What depends on this module?" dependents(nodeId: string): string[] { const results: string[] = []; for (const [source, targets] of this.adjacency) { if (targets.has(nodeId)) results.push(source); } return results; } // "What's the blast radius of changing this file?" blastRadius(nodeId: string, depth: number = 2): Set<string> { const visited = new Set<string>(); const queue: [string, number][] = [[nodeId, 0]]; while (queue.length > 0) { const [current, currentDepth] = queue.shift()!; if (currentDepth > depth || visited.has(current)) continue; visited.add(current); const dependentNodes = this.dependents(current); for (const dep of dependentNodes) { queue.push([dep, currentDepth + 1]); } } return visited; } // "Who should review changes to this module?" suggestReviewers(moduleId: string): string[] { // Query git ownership data for the module and its dependents const affectedModules = this.blastRadius(moduleId, 1); // Return engineers who own the affected modules return [...affectedModules] .map(id => this.nodeData.get(id)) .filter(node => node?.type === 'engineer') .map(node => node!.name); }}
For larger codebases (100K+ lines, 50+ engineers), consider a proper graph database like Neo4j:[5]
cypher
// Neo4j queries for codebase knowledge// Find the blast radius of changing a moduleMATCH path = (m:Module {name: "payments"})<-[:DEPENDS_ON*1..3]-(dependent)RETURN dependent.name, length(path) as distanceORDER BY distance;// Find knowledge silos: modules with only one contributorMATCH (e:Engineer)-[:CONTRIBUTES_TO]->(m:Module)WITH m, collect(e.name) as contributorsWHERE size(contributors) = 1RETURN m.name, contributors[0] as soleContributor;// Find hidden coupling: modules that always change togetherMATCH (m1:Module)-[c:CHANGES_WITH]->(m2:Module)WHERE c.frequency > 0.7 AND NOT (m1)-[:DEPENDS_ON]->(m2)RETURN m1.name, m2.name, c.frequency as couplingStrengthORDER BY couplingStrength DESC;
Before making a change, query the graph for blast radius:
"If I change the User model, what endpoints, services, and tests are affected?"
Figure 2. A blast-radius query walks the graph outward from the change: direct dependents first, then everything they touch.
On one team, this reduced production incidents from cross-cutting changes by 60% in the first quarter. Engineers could see the full impact before writing code, not after deploying it.
Instead of round-robin review assignment, query the graph for engineers who own the affected modules and their dependencies. PRs get reviewed by the people who actually understand the code.
New engineers get a personalized view of the codebase starting from their team's modules, expanding outward along dependency edges. Instead of "here's the entire codebase, good luck," they get "here are the 8 modules your team owns, here's how they connect to 5 other modules, and here's who to ask about each one."
// Fitness function: UI modules should never directly import database modulesfunction checkLayerViolations(graph: CodebaseGraph): string[] { const violations: string[] = []; const uiModules = graph.getNodesByTag("layer:ui"); const dbModules = graph.getNodesByTag("layer:database"); for (const ui of uiModules) { for (const db of dbModules) { if (graph.hasEdge(ui.id, db.id)) { violations.push(`Layer violation: ${ui.name} directly imports ${db.name}`); } } } return violations;}// Run this in CI. Fail the build on violations.
# The Stealable Framework: The 4-Week Graph Playbook
Here's the 4-week plan to build your first codebase knowledge graph:
Week 1 - Generate: Run madge or a custom AST parser to extract the static dependency graph. Export as JSON. Visualize it. Share with the team. Just seeing the graph often triggers "I didn't know those were connected" moments.
Week 2 - Enrich: Add git ownership data and change coupling analysis. Identify knowledge monopolies and hidden dependencies.
Week 3 - Query: Build the 5 most useful queries: blast radius, ownership lookup, dependency depth, change coupling, and circular dependency detection.
Week 4 - Integrate: Add the most impactful query to your development workflow. I recommend starting with blast radius analysis in CI: when a PR touches a file, automatically comment with the list of potentially affected modules.
The knowledge graph doesn't need to be perfect. A rough graph that covers 80% of your codebase is infinitely more useful than no graph at all. Start with static analysis, add runtime and human data over time, and let the graph grow as your understanding grows.
The codebase you're responsible for is a living system with thousands of interconnected parts. You wouldn't run a city without a map. Don't run a codebase without a knowledge graph.
MachGTM, which I build, has a sales-domain example of keeping evidence and corrections attached to connected knowledge. Its Brain correction guide follows an offering and customer proof into later research and writing, including the limits of generated entries and project-scoped results. For a codebase graph, ask the corresponding provenance question about an ownership or dependency claim and follow a correction into the next query that uses it.
Frequently asked questions
Is a dependency graph the same as a knowledge graph?
No. A dependency graph holds only what static analysis can see, such as imports. A knowledge graph adds runtime call paths from tracing and human context such as owners and architecture decisions. That extra context is what makes it useful for onboarding and impact analysis.
Do I need a graph database to start?
Not for small and medium codebases. A JSON file and a few graph algorithms answer the common questions. Consider a graph database such as Neo4j once the codebase passes roughly 100K lines or 50 engineers and the queries get deeper.
Where does the runtime data come from?
Distributed tracing. Instrument service boundaries with OpenTelemetry, then turn the recorded spans into caller-to-callee edges. That shows the paths requests really take in production, which often differ from what the imports suggest.
How long does a first useful version take?
The playbook here spreads it over four weeks: generate the static graph, enrich it with ownership and change coupling, write the key queries, then put one of them, such as blast radius, into the daily workflow. A rough graph covering most of the codebase is useful long before it is complete.
Five predictions for where code intelligence is heading by 2028, based on 6 years of building tools in this space. Includes what's real, what's overhyped, and a maturity model for planning.
Architecture fitness functions are automated tests for your system's structural properties. Here's how to implement the 5 most impactful ones and integrate them into your CI pipeline.
A 3-tier succession planning framework for engineering orgs, with a 90-day sprint for accelerating candidates from potential to ready. Based on succession plans built at 4 companies.
The CTO's real job in product development isn't attending every meeting or making every technical call. It's connecting feasibility, viability, and capacity while letting EMs handle the day-to-day.
Four years of data from a fully remote engineering team across 4 time zones. Specific metrics on productivity, retention, and onboarding with the frameworks that actually worked.
Small frictions cost more than big blockers. 47 micro-frictions consume 96 minutes per engineer per day. Here's the TAX Return framework for finding and eliminating the developer productivity tax.