Code Dependency Graph for Confident AI-Assisted Developers
Part of the Code Knowledge Graphs guide. Start with Knowledge Graph for Code Explained: A Practical Guide
A helper changes from returning Tier | null to returning Tier, its consumers still compile, and you have a tidy diff, but callers used null to decide whether a user needed provisioning.
That's the question I want a code dependency graph to help me investigate, before I accept an AI refactor, while the old behavior is still available to compare, with the affected callers in front of me.
What the graph needs to represent
A code dependency graph connects code entities through named relationships. Files can import files. Functions can call functions. The useful level depends on the change.
For an import rule, start with a file graph, follow the edges across module boundaries, inspect the reverse dependencies, and check how the tool resolves your project paths. For a function's return value, you'll also need its callers and their source.
I care about the distinction because an edge from billing.ts to tiers.ts doesn't say which export billing uses. A caller edge gets you closer to the decision inside that file.
Consider this illustrative chain:
checkout.ts imports billing.ts
billing.ts imports tiers.ts
createInvoice() calls getUserTier()
Here, checkout depends transitively on the tiers module, through billing, but that alone doesn't establish that checkout calls getUserTier, or explain what an invoice does with a missing tier.
For workspace packages, the separate monorepo dependency graph guide goes further into package boundaries.
Build an import graph first
Use one of these starting points in a checkout of your repository. The directory names are examples: replace src or mypackage with the code you want to inspect.
TypeScript: dependency-cruiser
The dependency-cruiser README documents installation and configuration. npm and npx commands below assume you're at the repository root.
npm install --save-dev dependency-cruiser
npx dependency-cruiser --init
npx dependency-cruiser src --include-only '^src' --ts-config tsconfig.json --output-type json > dependencies.json
npm adds the development dependency. dependency-cruiser's --init asks a few questions (--init oneshot takes the defaults) and writes .dependency-cruiser.cjs in ESM projects (.dependency-cruiser.js otherwise), which later runs pick up automatically. The third command reads src, resolves paths through tsconfig.json, and writes JSON: a modules array, each entry with its resolved dependencies, plus a summary of rule violations. Review the generated configuration before treating it as your architecture policy.
Before trusting the JSON, run npx dependency-cruiser --info and check that typescript and .ts are ticked. dependency-cruiser can parse TypeScript with the compiler installed in your project, and release 18.7.0 supports typescript from 2.0 up to, but not including, 7.0. Without a supported parser, this directory-based recipe can skip TypeScript files, write JSON with an empty modules list, and still exit 0. If --init ran before a supported compiler was installed, its configuration leaves .ts out of the resolver's extensions, and after you install one the third command lists your files with no dependencies between them, still with exit 0, so delete that configuration and run --init again (it won't overwrite an existing one).
dependency-cruiser can write DOT instead of JSON if you want a diagram, with the documented --output-type dot option, but rendering that output to SVG needs Graphviz's dot command, a separate prerequisite. The CLI reference covers both formats.
dependency-cruiser leaves out imports that TypeScript compilation removes, such as import type, unless tsPreCompilationDeps is on, and the configuration --init writes for a project with a tsconfig.json normally sets tsPreCompilationDeps: true, so check for that line before inspecting type changes, or pass --ts-pre-compilation-deps when you run without that configuration.
Keep the scope visible. The ^src filter deliberately narrows this example; expand it when the consumers you care about live elsewhere. The filter also drops imports dependency-cruiser couldn't resolve, since an unresolved path doesn't match ^src, so list those with npx dependency-cruiser src --output-type err, which reports each one as not-to-unresolvable.
Cycles: Madge
The Madge README describes module dependency analysis and circular dependency detection. This example examines TypeScript files in src.
npm -g install madge
madge --extensions ts,tsx --ts-config tsconfig.json --circular --warning src
npm installs the CLI globally here, --circular requests cycles, --warning lists skipped files, and the extensions and TypeScript options tell it what files and configuration to use. Those options are listed in Madge's CLI source.
Check the warnings. Madge documents that skipped or unresolved files can leave dependencies out of the result.
Python: pydeps
The pydeps documentation gives this installation command and the options used below:
pip install pydeps
pydeps mypackage --show-deps --no-output --max-bacon 0
This prints dependency data without rendering an image, removes the default distance limit, and analyzes the mypackage folder in the current directory (pydeps 3.0.8 and later, which need Python 3.10 or newer, also accept an installed package's name), so replace mypackage with yours. The tool derives imports from Python bytecode; its docs warn that missing modules are excluded by default.
An empty result needs checking. Pick an import you know exists and confirm that the tool found it before you use the output to plan a removal.
Follow a return-type change into its callers
Back to getUserTier. These are illustrative signatures for a hypothetical contract change.
// Before
export function getUserTier(id: string): Tier | null
// Proposed
export function getUserTier(id: string): Tier
Changing the annotation alone doesn't change runtime behavior. TypeScript explicitly erases type annotations.
Suppose the implementation changes too, returning a free tier for an unprovisioned user where it once returned null, while a caller still uses a null branch to start provisioning, and that branch now stops running for that user. The caller can still compile.
The graph helps find that caller. Reading the branch tells you why it matters.
For this proposed edit, I'd write down the changed behavior, inspect each direct caller's handling of the result, follow the relevant callers toward entry points, and add a case for the previously missing user. The blast radius of a change guide covers that traversal in more detail.
Across services, record the contract and consumer version separately. A repository import graph is insufficient evidence for deciding whether another deployed service needs a migration.
Read module context in the coding session
I build Pharaoh, a hosted MCP service for TypeScript, JavaScript, Python, C and C++ repositories. It exposes repository structure to your coding agent, including exported signatures, module dependencies, endpoints, and callers from other modules.
This captured get_module_context excerpt shows external callers of features/auth in the public Pharaoh-so/cal.diy repository at revision 54343aa6.
## External Callers
### app-store/zapier
- packages/app-store/zapier/lib/validateAccountOrApiKey.ts: validateAccountOrApiKey() → isAuthorized()
### trpc/server
- packages/trpc/server/routers/viewer/auth/changePassword.handler.ts: changePasswordHandler() → verifyPassword()
- packages/trpc/server/routers/viewer/ooo/outOfOfficeEntriesList.handler.ts: outOfOfficeEntriesList() → checkAdminOrOwner()
The full result lists callers from 19 modules; these lines come from two of them.
That gives the agent concrete files to open. For example, checkAdminOrOwner has a caller in an out-of-office handler, outside the auth module, where a module-local search could end too early, so the review has somewhere specific to continue.
For a compact impact summary, this captured excerpt from the same repository and revision shows production callers, using get_blast_radius on checkAdminOrOwner, at depth three.
### api/v2
- apps/api/v2/src/modules/atoms/controllers/atoms.conferencing-apps.controller.ts: AtomsConferencingAppsController.listUserInstalledConferencingApps (3 hops)
- apps/api/v2/src/modules/atoms/controllers/atoms.event-types.controller.ts: AtomsEventTypesController.getAtomEventTypeApp (2 hops)
- apps/api/v2/src/modules/atoms/services/conferencing-atom.service.ts: ConferencingAtomsService.getUserConferencingApps (2 hops)
- apps/api/v2/src/modules/atoms/services/event-types-atom.service.ts: EventTypesAtomService.getEventTypesAppIntegration
These are affected relationships to investigate. They don't establish that a caller will break.
Start with get_module_context, use search_functions if you need to locate an implementation, then ask get_blast_radius about the specific target, and open the affected source files. Blast radius follows production callers for three hops by default, up to five, and excludes test-file callers.
Pharaoh maps the default branch, refreshes a live repository after each push there, and lets you ask for a refresh before the next push with pharaoh_account, but the graph doesn't describe your uncommitted edits or feature branch. Compare the returned relationships with the checkout you're changing.
The tool overview explains the available queries.
For your repository, connect Pharaoh.
Check the changed code and the graph's limits
Rerun the local analysis after the edit. dependency-cruiser reads the files in your working checkout, and --affected main keeps the modules changed since main plus every module that can reach them (--reaches '<regex>' does the same for a module you name), so check the new imports and the modules that reach them, and run the relevant tests. Keep unresolved dependencies in the review notes.
For a small refactor, use this review sequence:
- Name the changed export, file, or function.
- Confirm the graph contains the expected direct dependency or caller.
- Inspect reverse dependencies and follow them toward an application entry point.
- Read each affected call site for assumptions about arguments, return values, errors, or side effects.
- Record unresolved edges and run tests for the changed path before merging.
If the graph and the source disagree, treat that as an investigation item rather than evidence that the code is unused. Check the parser, path configuration, generated files, and the checkout or branch being analyzed.
For cleanup, distinguish dead code from uncertain usage. Pharaoh marks a function Dead when every signal agrees, meaning no entry point reaches it, no other file names it, and no production file imports its file.
An unreached function with another naming or import signal is Possibly unused. Inspect those references before deleting it.
There's also a separate status for exports whose only caller is a test.
A passing unit test and a production call path answer different questions.
I would start with one shared helper and a caller I already know, check that the graph finds the connection, follow it to the source, and use that small review to decide what else needs testing before merging the refactor.
Article Record
ReferencesPrimary sources used for this article
- Semantic Code Graph – an information model to facilitate software comprehension
- Installation
- Dependency cruiser
- dependency-cruiser/doc/cli.md at main · sverweij/dependency-cruiser
- pydeps¶
- Tree-sitter
- Code Impact Beyond Disciplinary Boundaries
- JohT/code-graph-analysis-pipeline
- juspay/codetraverse
- compass-soul/codegraph
- andreirx/repo-graph
- Code Knowledge Graph for LLM Agents: What It Is and Why You Need One · Andrey Kumanyaev
Update HistoryMeaningful revisions to this article
- Added a practical example showing how to check changed code and understand the graph’s limits.