New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details
Socket
Book a DemoSign in
Socket

@optave/codegraph

Package Overview
Dependencies
Maintainers
1
Versions
42
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@optave/codegraph

Local code graph CLI — parse codebases with tree-sitter, build dependency graphs, query them

Source
npmnpm
Version
1.1.0
Version published
Weekly downloads
818
-3.54%
Maintainers
1
Weekly downloads
 
Created
Source

codegraph

codegraph

Local code dependency graph CLI — parse, query, and visualize your codebase at file and function level.

npm version Apache-2.0 License CI Node >= 20 Local Only

Quick StartFeaturesCommandsLanguagesAI IntegrationCI/CDContributing

Zero network calls. Zero telemetry. Your code never leaves your machine.

Codegraph uses tree-sitter (via WASM — no native compilation required) to parse your codebase into an AST, extracts functions, classes, imports, and call sites, resolves dependencies, and stores everything in a local SQLite database. Query it instantly from the command line.

🚀 Quick Start

# Install
git clone https://github.com/optave/codegraph.git
cd codegraph
npm install
npm link

# Build a graph for any project
cd your-project
codegraph build        # → .codegraph/graph.db created

# Start exploring
codegraph map          # see most-connected files
codegraph query myFunc # find any function, see callers & callees
codegraph deps src/index.ts  # file-level import/export map

✨ Features

FeatureDescription
🔍Symbol searchFind any function, class, or method by name with callers/callees
📁File dependenciesSee what a file imports and what imports it
💥Impact analysisTrace every file affected by a change (transitive)
🧬Function-level tracingCall chains, caller trees, and function-level impact
📊Diff impactParse git diff, find overlapping functions, trace their callers
🗺️Module mapBird's-eye view of your most-connected files
🔄Cycle detectionFind circular dependencies at file or function level
📤ExportDOT (Graphviz), Mermaid, and JSON graph export
🧠Semantic searchEmbeddings-powered natural language code search
👀Watch modeIncrementally update the graph as files change
🤖MCP serverModel Context Protocol integration for AI assistants
🔒Fully localNo network calls, no data exfiltration, SQLite-backed

📦 Commands

Build & Watch

codegraph build [dir]          # Parse and build the dependency graph
codegraph build --no-incremental  # Force full rebuild
codegraph watch [dir]          # Watch for changes, update graph incrementally

Query & Explore

codegraph query <name>         # Find a symbol — shows callers and callees
codegraph deps <file>          # File imports/exports
codegraph map                  # Top 20 most-connected files
codegraph map -n 50            # Top 50

Impact Analysis

codegraph impact <file>        # Transitive reverse dependency trace
codegraph fn <name>            # Function-level: callers, callees, call chain
codegraph fn <name> --no-tests --depth 5
codegraph fn-impact <name>     # What functions break if this one changes
codegraph diff-impact          # Impact of unstaged git changes
codegraph diff-impact --staged # Impact of staged changes
codegraph diff-impact HEAD~3   # Impact vs a specific ref

Export & Visualization

codegraph export -f dot        # Graphviz DOT format
codegraph export -f mermaid    # Mermaid diagram
codegraph export -f json       # JSON graph
codegraph export --functions -o graph.dot  # Function-level, write to file
codegraph cycles               # Detect circular dependencies
codegraph cycles --functions   # Function-level cycles

Codegraph can build local embeddings for every function, method, and class, then search them by natural language. Everything runs locally using @huggingface/transformers — no API keys needed.

codegraph embed                # Build embeddings (default: minilm)
codegraph embed --model nomic  # Use a different model
codegraph search "handle authentication"
codegraph search "parse config" --min-score 0.4 -n 10
codegraph models               # List available models

Available Models

FlagModelDimensionsSizeLicenseNotes
minilm (default)all-MiniLM-L6-v2384~23 MBApache-2.0Fastest, good for quick iteration
jina-smalljina-embeddings-v2-small-en512~33 MBApache-2.0Better quality, still small
jina-basejina-embeddings-v2-base-en768~137 MBApache-2.0High quality, 8192 token context
nomicnomic-embed-text-v1768~137 MBApache-2.0Best quality, 8192 context

The model used during embed is stored in the database, so search auto-detects it — no need to pass --model when searching.

AI Integration

codegraph mcp                  # Start MCP server for AI assistants

Common Flags

FlagDescription
-d, --db <path>Custom path to graph.db
-T, --no-testsExclude .test., .spec., __test__ files
--depth <n>Transitive trace depth (default varies by command)
-j, --jsonOutput as JSON
-v, --verboseEnable debug output

🌐 Language Support

LanguageExtensionsCoverage
JavaScript.js, .jsx, .mjs, .cjsFull — functions, classes, imports, call sites
TypeScript.ts, .tsxFull — interfaces, type aliases, .d.ts
Python.pyFunctions, classes, methods, imports, decorators
Terraform.tf, .hclResource, data, variable, module, output blocks

⚙️ How It Works

┌──────────┐    ┌───────────┐    ┌───────────┐    ┌──────────┐    ┌─────────┐
│  Source   │───▶│ tree-sitter│───▶│  Extract  │───▶│  Resolve │───▶│ SQLite  │
│  Files   │    │   Parse   │    │  Symbols  │    │  Imports │    │   DB    │
└──────────┘    └───────────┘    └───────────┘    └──────────┘    └─────────┘
                                                                       │
                                                                       ▼
                                                                 ┌─────────┐
                                                                 │  Query  │
                                                                 └─────────┘
  • Parse — tree-sitter (WASM) parses every source file into an AST
  • Extract — Functions, classes, methods, interfaces, imports, exports, and call sites are extracted
  • Resolve — Imports are resolved to actual files (handles ESM conventions, tsconfig.json path aliases, baseUrl)
  • Store — Everything goes into SQLite as nodes + edges with tree-sitter node boundaries
  • Query — All queries run locally against the SQLite DB — typically under 100ms

Call Resolution

Calls are resolved with priority and confidence scoring:

PrioritySourceConfidence
1Import-awareimport { foo } from './bar' → link to bar1.0
2Same-file — definitions in the current file1.0
3Same directory — definitions in sibling files0.7
4Same parent directory — definitions in sibling dirs0.5
5Global fallback — match by name across codebase0.3
6Method hierarchy — resolved through extends/implements

Dynamic patterns like fn.call(), fn.apply(), fn.bind(), and obj["method"]() are also detected on a best-effort basis.

📊 Performance

Benchmarked on a ~3,200-file TypeScript project:

MetricValue
Build time~30s
Nodes19,000+
Edges120,000+
Query time<100ms
DB size~5 MB

🤖 AI Agent Integration

MCP Server

Codegraph includes a built-in Model Context Protocol server, so AI assistants can query your dependency graph directly:

codegraph mcp

CLAUDE.md / Agent Instructions

Add this to your project's CLAUDE.md to help AI agents use codegraph:

## Code Navigation

This project has a codegraph database at `.codegraph/graph.db`.

- **Before modifying a function**: `codegraph fn <name> --no-tests`
- **Before modifying a file**: `codegraph deps <file>`
- **To assess PR impact**: `codegraph diff-impact --no-tests`
- **To find entry points**: `codegraph map`
- **To trace breakage**: `codegraph fn-impact <name> --no-tests`

Rebuild after major structural changes: `codegraph build`

🔁 CI / GitHub Actions

Codegraph ships with a ready-to-use GitHub Actions workflow that comments impact analysis on every pull request.

Copy .github/workflows/codegraph-impact.yml to your repo, and every PR will get a comment like:

3 functions changed12 callers affected across 7 files

🛠️ Configuration

Create a .codegraphrc.json in your project root to customize behavior:

{
  "include": ["src/**", "lib/**"],
  "exclude": ["**/*.test.js", "**/__mocks__/**"],
  "ignoreDirs": ["node_modules", ".git", "dist"],
  "extensions": [".js", ".ts", ".tsx", ".py"],
  "aliases": {
    "@/": "./src/",
    "@utils/": "./src/utils/"
  },
  "build": {
    "incremental": true
  }
}

📖 Programmatic API

Codegraph also exports a full API for use in your own tools:

import { buildGraph, queryNameData, findCycles, exportDOT } from 'codegraph';

// Build the graph
buildGraph('/path/to/project');

// Query programmatically
const results = queryNameData('myFunction', '/path/to/.codegraph/graph.db');

⚠️ Limitations

  • No full type inference — parses .d.ts interfaces but doesn't use TypeScript's type checker for overload resolution
  • Dynamic calls are best-effort — complex computed property access and eval patterns are not resolved
  • Python imports — resolves relative imports but doesn't follow sys.path or virtual environment packages

🤝 Contributing

Contributions are welcome! Here's how to get started:

git clone https://github.com/optave/codegraph.git
cd codegraph
npm install --legacy-peer-deps
npm test                # run tests with vitest
  • Fork the repo
  • Create your feature branch (git checkout -b feat/amazing-feature)
  • Commit your changes
  • Push to the branch
  • Open a Pull Request

📄 License

Apache-2.0

Built with tree-sitter and better-sqlite3. No data leaves your machine. Ever.

Keywords

codegraph

FAQs

Package last updated on 21 Feb 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts