diff --git a/README.md b/README.md index c5913e34..5339b91a 100644 --- a/README.md +++ b/README.md @@ -1,270 +1,164 @@ -# codegraph +# Codegraph -Codegraph is a small multi-language code analysis library and CLI for understanding repos quickly. It builds dependency graphs, symbol indexes, go-to-definition results, find-references results, semantic chunks, architecture drift reports, and PR review and impact artifacts across source languages plus graph-first document, stylesheet, and template formats. +**Give your coding agent a map of the repository, not a pile of search results.** -It is built for agent and human workflows that need repo structure fast without standing up a full editor or LSP stack. +Codegraph is a local CLI **and TypeScript library** that turns a source tree into a resolved model of files, symbols, references, and dependencies. Agents and humans can ask where an implementation lives, how components connect, what a change can break, and which tests are likely relevant - then get bounded source evidence and copyable next steps. + +Without structural context, an agent spends early turns listing directories, guessing search terms, opening candidate files, and reconstructing relationships in its prompt. Codegraph performs that deterministic discovery once so more of the context window can go toward understanding and changing the code. + +```bash +codegraph explore "how does auth reach the database?" --root . --pretty +codegraph review --base HEAD --head WORKTREE --summary +``` + +Use Codegraph alongside text search and compilers: text search finds exact strings, compilers prove language behavior, and Codegraph supplies the cross-file repository map between them. ## Table of contents +- [What you can do](#what-you-can-do) +- [Try it](#try-it) +- [A useful first five minutes](#a-useful-first-five-minutes) +- [What the output looks like](#what-the-output-looks-like) - [Why Codegraph](#why-codegraph) -- [Features](#features) -- [Quick start](#quick-start) -- [CLI examples](#cli-examples) -- [Key output examples](#key-output-examples) +- [Why not just grep or an LSP?](#why-not-just-grep-or-an-lsp) - [Agent setup](#agent-setup) +- [Language support](#language-support) - [Using as a library](#using-as-a-library) -- [Common workflows](#common-workflows) -- [Supported languages](#supported-languages) +- [How it works](#how-it-works) +- [Limits and tradeoffs](#limits-and-tradeoffs) - [Documentation](#documentation) -- [Installation options](#installation-options) -- [FAQ](#faq) -- [Contributing and releases](#contributing-and-releases) +- [Contributing](#contributing) -## Why Codegraph +## What you can do -Use Codegraph when you need fast structural answers about a repo without relying on a full editor session or language-server setup. - -- Triage an unfamiliar codebase with one pass that highlights hotspots, unresolved imports, cycles, and next commands to run. -- Review diffs with changed symbols, graph deltas, likely regression tests, and risk signals that agents or humans can consume directly. -- Export graph data as JSON, Mermaid, DOT, or SQLite, then inspect it from scripts, Markdown renderers, Graphviz, or SQL tools. -- Keep one workflow across source languages, monorepos, and graph-first document and template formats instead of stitching together separate tools. - -For unfamiliar repos with a concrete question, start with `explore "how does auth reach db?" --root . --pretty`; use `orient --root . --budget small --pretty` when you need a map before asking a question. -For daily change work, start with `review --base HEAD --head WORKTREE --summary`; use `impact --base HEAD --head WORKTREE --pretty` as the broader blast-radius map when needed. -Search is code-first by default in hybrid mode, and explore, search, explain, and review packets include analysis labels so reduced-mode or mixed-semantics runs stay visible. -Detailed command contracts and JSON shapes live in [docs/cli.md](./docs/cli.md). - -## Features - -- Multi-language dependency graphs, including imports, re-exports, `require()`, dynamic imports, workspace resolution, document links, stylesheet imports, and SFC script dependencies. -- Per-file symbol indexes with locals, exports, docstrings, line spans, and lightweight complexity metadata. -- Cross-file go-to-definition and find-references support across the shared source-language pipeline. -- Deterministic agent exploration, orientation, packet retrieval, search, bounded explanations, portable artifact bundles, and MCP tools across files, symbols, chunks, SQL objects, graph neighborhoods, and review ranges with stable follow-up targets. -- Project lifecycle commands initialize, inspect, refresh, and remove `.codegraph/manifest.json` metadata while reusing the existing disk cache. -- Semantic chunking for code and text files, including Vue and Svelte single-file component block splitting. -- Duplicate and near-duplicate detection over indexed symbols, semantic chunks, text chunks, token fingerprints, and AST shape hashes when parser context is available. -- AST grep, public API summaries, unresolved import reports, hotspot analysis, cycle detection, and shortest dependency paths. -- PR impact analysis and review bundles that map diffs to changed symbols, impacted code, likely tests, graph deltas, and conservative provider-backed call-arity hints after signature changes. -- SQL language support for `.sql` files, including statement chunks, object symbols, SQL-to-SQL graph edges, SQL navigation, and statement facts. -- SQLite export plus read-only SQL access for downstream tools and agent workflows. -- Native Tree-sitter parsing by default when a matching prebuilt is available, with reduced graph-only and regex recovery when native is unavailable. - -Sample graph output can be generated with `npm run graph:mermaid`, `npm run graph:dot`, or `npm run graph:json`. - -This repo keeps test fixtures out of default Codegraph scans with `codegraph.config.json`: - -```json -{ - "discovery": { - "ignoreGlobs": ["tests/samples/**", "tests/languages/samples/**"] - } -} -``` +| Question | Start here | What comes back | +| --------------------------------------- | ----------------------------------------------------------------------- | --------------------------------------------------------------------------------- | +| "Where should I start in this repo?" | `codegraph orient --root . --budget small --pretty` | Central modules, a bounded tree, and copyable follow-ups | +| "How does this feature work?" | `codegraph explore "" --root . --pretty` | Ranked anchors, source packets, dependency paths, blast radius, and likely tests | +| "What could this change break?" | `codegraph review --base HEAD --head WORKTREE --summary` | Changed symbols, risk signals, candidate tests, duplicate leads, and review tasks | +| "What depends on this file?" | `codegraph rdeps src/file.ts --json` | Reverse dependencies from the resolved project graph | +| "Where is this symbol defined or used?" | `codegraph goto ` and `codegraph refs ...` | Semantic definitions and references across supported languages | +| "Is the architecture drifting?" | `codegraph drift ./src --base origin/main --head HEAD --pretty` | New cycles, hotspot changes, unresolved imports, API changes, and graph deltas | +| "Where is code duplicated?" | `codegraph duplicates ./src --min-confidence medium` | Ranked exact and near-duplicate groups with locations and confidence | +| "Can another tool consume the graph?" | `codegraph graph --root . ./src --compact-json --output codegraph.json` | JSON, Mermaid, DOT, or SQLite output | -Use this pattern in other repos when large fixture, generated, or vendored trees should not participate in search, unresolved-import checks, graphing, indexing, inspect, impact, or review runs. Config globs are project-root-relative. CLI `--include-glob` and `--ignore-glob` stay relative to each active scan root. +Human-readable output uses `--pretty` or `--summary`. JSON, MCP tools, and library APIs preserve stable fields, ranges, handles, reasons, confidence, and omission counts for automation. -## Quick start +## Try it -Requirements: Node.js 24.10+. +**Requirement:** Node.js 24.10 or newer. -For contributors and first-time evaluation, start from a local source checkout: +### From a source checkout + +This is the least ambiguous way to evaluate the current repository: ```bash git clone https://github.com/lzehrung/codegraph.git cd codegraph npm install npm run build +node ./dist/cli.js doctor +node ./dist/cli.js orient --root . --budget small --pretty ``` -`npm run build` always rebuilds `dist/`. If Cargo is available, it also requires the local native workspace build to succeed; if Cargo is unavailable, it still completes with the JavaScript build output and a warning. +Continue with `node ./dist/cli.js ` from the checkout. To use the bare `codegraph` examples below unchanged, run `npm install -g .` after the build. -Then start with the default workflow. For code reviews, the lowest-friction loop is `review --summary` first, `impact --pretty` only when you need blast radius, then `search` or `explain` on a file or symbol named in the summary; use review JSON when a follow-up needs stable handles. +### From GitHub Packages -```bash -# compact reviewer handoff for current edits -node ./dist/cli.js review --base HEAD --head WORKTREE --summary +If access to the `@lzehrung` GitHub Packages registry is configured: -# broader blast-radius map when the review packet needs expansion -node ./dist/cli.js impact --base HEAD --head WORKTREE --pretty - -# one-call answer for a concrete repo question -node ./dist/cli.js explore "how does auth reach db?" --root . --pretty - -# bounded repo orientation with next-step suggestions -node ./dist/cli.js orient --root . --budget small --pretty +```bash +npm config set "@lzehrung:registry" "https://npm.pkg.github.com" +npm install -g @lzehrung/codegraph +codegraph doctor +``` -# find and explain a concrete anchor -node ./dist/cli.js search "build review report" --json -node ./dist/cli.js explain src/cli.ts +Published installs resolve the optional native runtime automatically when a compatible artifact exists. See [Installation](./docs/installation.md) for registry setup, release tarballs, local global installs, and native runtime modes. -# optional lifecycle manifest and cache warmup -node ./dist/cli.js init --root . -node ./dist/cli.js status --root . --json +## A useful first five minutes -# optional runtime and artifact health check -node ./dist/cli.js doctor +Do not begin by generating every possible report. Start with the question you actually have. -# optional broader architecture summary -node ./dist/cli.js inspect ./src --limit 20 +### Understand an unfamiliar repo -# build a graph for product code -node ./dist/cli.js graph --root . ./src --compact-json --output codegraph.json - -# inspect public API surface -node ./dist/cli.js apisurface +```bash +# Ask one concrete architecture question +codegraph explore "how does the CLI reach review analysis?" --root . --pretty -# find duplicate and near-duplicate code -node ./dist/cli.js duplicates ./src --min-confidence medium --limit 20 +# If you do not know the question yet, get a bounded map +codegraph orient --root . --budget small --pretty -# compare architecture drift between refs -node ./dist/cli.js drift ./src --base origin/main --head HEAD --compact-json -node ./dist/cli.js drift ./src --base origin/main --head HEAD --pretty --graph-edges summary --public-api removals +# Follow an anchor returned by either command +codegraph explain src/review.ts +codegraph deps src/review.ts --json +codegraph refs --file src/review.ts --line 215 --col 23 --pretty ``` -If you install the published CLI instead of using a source checkout, replace `node ./dist/cli.js` with `codegraph`. - -Small orientation packets skip deeper health analysis and record that omission; use `--budget medium` or `--budget large` when health counts matter. - -## CLI examples - -Choose output by consumer: - -- Use `--pretty` or `--summary` when a person or model needs a compact triage view. -- Use `--json` or library APIs when a script, tool wrapper, or follow-up command needs stable fields. - -Use these as starting points, then see [docs/cli.md](./docs/cli.md) for all flags, defaults, and output contracts. +### Review local changes ```bash -# fastest code-review handoff for current edits +# Compact reviewer handoff for staged and unstaged tracked changes codegraph review --base HEAD --head WORKTREE --summary -codegraph impact --base HEAD --head WORKTREE --pretty -# repo question, orientation, and bounded follow-up -codegraph explore "how does auth reach db?" --root . --pretty -codegraph orient --root . --budget small --pretty -codegraph search "build review report" --json -codegraph explain src/review.ts +# Broader blast-radius map when the summary needs expansion +codegraph impact --base HEAD --head WORKTREE --pretty +``` -# project lifecycle marker and cache warmup -codegraph init --root . -codegraph status --root . --json -codegraph sync --root . +Use `--head STAGED` to compare `HEAD` with the index, or use refs such as `--base origin/main --head HEAD` for a branch review. -# semantic navigation -codegraph goto -codegraph refs --file src/index.ts --line 12 --col 17 --pretty +### Inspect repository health -# architecture and review +```bash +codegraph inspect ./src --limit 20 +codegraph cycles --sort priority +codegraph unresolved +codegraph apisurface +codegraph duplicates ./src --min-confidence medium --limit 20 codegraph drift ./src --base origin/main --head HEAD --pretty --graph-edges summary --public-api removals -codegraph drift ./src --base origin/main --head HEAD --compact-json -codegraph impact --base origin/main --head HEAD --pretty -codegraph review --base origin/main --head HEAD --summary - -# duplicate and graph exploration -codegraph duplicates ./src --json --min-confidence medium --limit 20 -codegraph graph --root . ./src --compact-json --output codegraph.json ``` -See [docs/cli.md](./docs/cli.md) for full flags, JSON shapes, drift policy gates, duplicate scopes, and review output details. +### Export the model -## Key output examples - -These excerpts show the shape of the outputs agents and humans usually consume. Use `--pretty` or `--summary` for triage, and switch to JSON when a follow-up command needs stable handles, paths, ranges, reasons, or counts. +```bash +codegraph graph --root . ./src --compact-json --output codegraph.json +codegraph graph --root . ./src --mermaid --output graph.mmd +codegraph graph --root . ./src --dot --output graph.dot +codegraph graph --root . ./src --sqlite codegraph.sqlite +``` -### Orientation +## What the output looks like -`orient --root . --budget small --pretty` gives first-turn focus targets plus copyable follow-ups: +Because ranking and counts change with the working tree, this abbreviated `explore` excerpt shows the stable response structure rather than snapshot-specific totals: ```text -Summary -- 567 file(s) in scope. -- 5 graph-central module(s) ranked for first follow-up. -- Health analysis skipped for small budget. - -Start here -- src/index.ts: graph-central module: fan-in 96, fan-out 40, score 232 - - codegraph packet get src/index.ts --pretty - - codegraph explain src/index.ts - -Recommended next -- codegraph hotspots . --limit 20 -- codegraph impact --base HEAD --head WORKTREE --pretty -- codegraph review --base HEAD --head WORKTREE --summary -- codegraph search --json -``` +Anchors +- buildReviewReport [symbol] src/review.ts +- src/cli/help.ts:1 [chunk] src/cli/help.ts +- ReviewPreset [symbol] src/review.ts -### Search - -`search "graph json" --json` returns ranked, explainable anchors. Follow-up commands reuse the returned handle, file, or symbol path: - -```json -{ - "schemaVersion": 1, - "query": "build review report", - "mode": "hybrid", - "analysis": { - "label": "native semantic" - }, - "resultCount": 1, - "totalCandidates": 42, - "results": [ - { - "handle": "symbol:src%2Freview.ts:buildReviewReport:214:1", - "kind": "symbol", - "label": "buildReviewReport", - "file": "src/review.ts", - "score": 248, - "provenance": { - "surface": "code", - "capability": "semantic", - "analysisMode": "semantic", - "backend": "native", - "confidence": "high" - }, - "rankReasons": ["exact phrase match in symbol name", "symbol token match: build, review, report"], - "followUps": [ - "codegraph explain \"symbol:src%2Freview.ts:buildReviewReport:214:1\"", - "codegraph refs --file src/review.ts --line 214 --col 1 --pretty" - ] - } - ] -} -``` +Relevant source +- buildReviewReport is defined in src/review.ts. +- References, dependencies, and dependents are summarized here. -### Impact +Blast radius +- src/review.ts: src/index.ts, src/cli/review.ts, src/mcp/server.ts, ... -`impact --base HEAD --head WORKTREE --pretty` answers what changed and what else can break. Pretty output keeps severity and reason labels visible: +Candidate tests +- tests/agent-explain.test.ts +- tests/agent-explore.test.ts +- tests/agent-packet.test.ts -```text -Impact Analysis Report -====================== -Changed files: 1 -Changed symbols: 1 -Impacted items: 2 - -utils.ts: defaultExport (reason: direct reference, severity: 100.0%) -main.ts: defaultExport (reason: transitive dependency, severity: 72.0%) -``` +Follow-ups +- codegraph file src/review.ts --pretty +- codegraph refs --file src/review.ts --line 215 --col 23 --pretty -Use `--compact-json` when tooling needs normalized arrays, graph edges, diagnostics, and `schemaVersion`: - -```json -{ - "schemaVersion": 1, - "format": "compact", - "files": ["utils.ts", "main.ts", "dynamic-import.ts", "helpers.ts", "tsconfig.json"], - "changedFiles": [{ "file": 0, "kind": "modified", "hunks": [{ "start": 28, "end": 38 }] }], - "changedSymbols": [{ "file": 0, "name": "defaultExport", "kind": "function", "exported": true }], - "impacted": [ - { "file": 0, "symbols": ["defaultExport"], "reasons": ["directRef"], "severity": 1 }, - { "file": 1, "symbols": ["defaultExport"], "reasons": ["importAlias", "transitive"], "severity": 0.72 } - ] -} +Limits +- anchors, packets, paths, blast radius, reverse dependencies, and candidate tests ``` -### Review +Real output includes counts, copyable follow-ups, explicit limits, and omission counts. It does not pretend omitted context was analyzed. -`review --base HEAD --head WORKTREE --summary` is the compact reviewer handoff. It combines changed files, changed symbols, candidate tests, risk signals, review tasks, duplicate leads, and call-compatibility hints when a supported signature change has resolvable callsites: +A worktree review is optimized for a different job: ```text Review Summary @@ -275,272 +169,152 @@ Symbols changed: 22 Candidate tests: 1 (high: 1, medium: 0, low: 0) Risk: high (80) Signals: exported-symbols-changed, many-symbols-changed - -Changed files: -- src/invoices-a.ts: updated (label, output, rounded, subtotal, summarizeInvoices) -- src/invoices-b.ts: updated (label, output, rounded, subtotal, summarizeInvoices) -- src/orders-a.ts: updated (label, output, rounded, subtotal, summarizeOrders) -- src/orders-b.ts: updated (label, output, rounded, subtotal, summarizeOrders) -- src/pricing.ts: updated (calculateTotal, discounted) - -Candidate tests: -High-confidence tests: -- tests/pricing.test.ts: importsChanged - -Review tasks: -- review-summary: medium - Review changed symbols (baseline-review) -- api-compat: high - Verify API compatibility (exported-symbols-changed) -- high-change-volume: high - Assess change scope (large-change-set) -- duplicate-sibling-check:d9a0ad66c9cb5610: high - Check related duplicate implementation (duplicate-sibling) -- duplicate-sibling-check:a9188e0046912ef6: high - Check related duplicate implementation (duplicate-sibling) - -Call compatibility: -- calculateTotal: src/checkout.ts:3 passes 2 arguments; new signature requires 3. -- calculateTotal: tests/pricing.test.ts:2 passes 2 arguments; new signature requires 3. - -Duplicate leads: -- src/invoices-a.ts:1-10 matches src/invoices-b.ts:1-10 (exact, score 100). -- src/orders-a.ts:1-10 matches src/orders-b.ts:1-10 (exact, score 100). -- src/invoices-a.ts:1-10 matches src/orders-a.ts:1-10 (renamed, score 100). -- omitted: 1 by budget, 24 hidden evidence items ``` -### Dependency graph +Structured output carries the underlying changed files, symbols, graph edges, reasons, diagnostics, snippets, and candidate-test confidence instead of requiring a caller to parse this display text. -For a small dependency slice, Mermaid output can be pasted directly into Markdown renderers that support Mermaid: +## Why Codegraph -```mermaid -flowchart LR -f0["utils.ts"] -f1["main.ts"] -s0["utils.ts:defaultExport"] -f1 --> f0 -f0 --> s0 -``` +### Spend context on the problem, not repository discovery -For full-repo exploration, generate a portable graph artifact for scripts or downstream tools: +One bounded `explore` response can combine ranked anchors, relevant source, dependency paths, blast radius, candidate tests, and next commands. The agent gets an evidence-backed starting point without first dumping the tree or repeatedly guessing which files to open. -```bash -codegraph graph --root . ./src --compact-json --output codegraph.json -codegraph graph --root . ./src --mermaid --output graph.mmd -codegraph graph --root . ./src --dot --output graph.dot -``` +### Ground the next action + +Results carry source paths, symbol ranges, stable handles, rank reasons, graph relationships, confidence, and omission counts. An agent can inspect why something ranked, jump to the definition or references, and continue from an exact target instead of treating a fuzzy match as an answer. + +### Reuse one map from discovery through review + +Search, navigation, dependency analysis, impact, and review share the same graph and semantic index. The target found during discovery can flow directly into `explain`, `refs`, `deps`, impact analysis, and candidate-test selection. + +### Work across the repository an agent actually has + +Source code, SQL, workspace packages, documentation links, stylesheets, templates, and single-file components can participate in one repository model. Capability claims remain language-specific, so graph support is not presented as full compiler or language-server parity. + +### Keep the evidence local and reusable + +Codegraph runs locally through a CLI, library, or MCP server. People can read pretty output; agents and programs can keep structured JSON, stable handles, warm sessions, SQLite data, or graph exports without parsing display text. + +## Why not just grep or an LSP? + +Codegraph complements both. + +- Use text search for exact strings, logs, config keys, and prose. +- Use a compiler or language server when you need compiler-grade type analysis, overload resolution, dynamic dispatch, or editor refactors. +- Use Codegraph when the question crosses files, languages, dependency edges, a git diff, or an agent context boundary. + +The useful distinction is evidence shape, not a claim that one tool replaces every other tool. ## Agent setup -Using a local agent client? The top-level installer configures Codegraph-owned MCP entries, bundled skill payloads, and marker files for supported clients, while preserving existing user config: +The installer can configure Codegraph-owned MCP entries, bundled skills, and marker files while preserving unrelated client configuration: ```bash codegraph install --target codex,claude --dry-run codegraph install --target codex,claude --yes codegraph install --print-config codex -codegraph uninstall --target codex --yes ``` -Supported installer targets are `codex`, `claude`, `cursor`, `gemini`, `opencode`, and `agents`. Writes require `--yes`; `--dry-run` previews files, and `uninstall` removes only Codegraph-owned marker blocks, marker files, exact bundled skill payloads, or exact installer-owned MCP entries. +Supported `--target` ids are `codex`, `claude`, `cursor`, `gemini`, `opencode`, and `agents` (universal agent skills). Writes require `--yes`; `--dry-run` previews every change, and uninstall removes only Codegraph-owned content. -Using a skill-aware agent only? Install the bundled skill directly so repo navigation, semantic references, dependency tracing, and PR impact questions route to Codegraph automatically: +For a skill without MCP configuration: ```bash -# Codex CLI: ${CODEX_HOME:-~/.codex}/skills/codegraph codegraph skill install --agent codex - -# Claude Code: ~/.claude/skills/codegraph codegraph skill install --agent claude +codegraph skill install --agent cursor +``` -# Universal agent skills: ~/.agents/skills/codegraph -codegraph skill install --agent agents +See [Agent workflows](./docs/agent-workflows.md) for exploration strategy, warm sessions, streaming, review loops, and tool wrappers. See [MCP](./docs/mcp.md) for server and client configuration. -# Cursor CLI: ~/.cursor/skills/codegraph -codegraph skill install --agent cursor +## Language support -# Gemini CLI: ~/.gemini/skills/codegraph -codegraph skill install --agent gemini +**Shared source-language indexing and navigation:** JavaScript, TypeScript, Python, PHP, Go, Java, C#, Ruby, Rust, Kotlin, Swift, Zig, C, and C++. -# OpenCode: ~/.config/opencode/skills/codegraph -codegraph skill install --agent opencode -``` +**SQL:** statement chunking, object symbols, common DDL/DML and CTE facts, SQL-to-SQL edges, and object-level navigation. Codegraph does not claim column-definition resolution. + +**Graph-first formats:** HTML, Astro, Handlebars, Markdown, MDX, reStructuredText, AsciiDoc, CSS, SCSS, and Less have narrower graph or chunking support. + +**Single-file components:** Vue and Svelte script blocks participate in dependency graphs and chunking; semantic navigation is narrower. -For a custom skill location, use `codegraph skill install --target /skills/codegraph`; the target must end with `skills/codegraph`, and the installer creates the directory as needed. Cursor CLI supports native skills directories too, so `.cursor/skills/codegraph` works alongside the universal `~/.agents/skills/codegraph` location. To inspect the packaged skill paths and target health, run `codegraph skill doctor`. +See [Language parity](./docs/language-parity.md) for the capability matrix and [Scenario catalog](./docs/scenario-catalog.md) for the fixtures behind those claims. ## Using as a library -Use the TypeScript API when another program needs deterministic explore responses, file packs, review packets, or model prompts. CLI `--pretty` and `--summary` output is also useful for model-readable triage, but library callers should keep structured fields until the final UI or prompt boundary. For repeated calls, prefer one warm `createCodeReviewSession()` or one agent/MCP session over rebuilding ad hoc indexes. +Use the TypeScript API when another program needs structured results or a warm, reusable session: ```ts -import { - buildProjectIndex, - buildReviewReport, - analyzeArchitectureDrift, - analyzeImpactFromDiff, - analyzeImpactStreaming, - tool_impactJSON, -} from "@lzehrung/codegraph"; +import { buildProjectIndex, analyzeImpactFromDiff } from "@lzehrung/codegraph"; + const root = process.cwd(); const index = await buildProjectIndex(root, { native: "auto" }); -const review = await buildReviewReport(root, { - gitBase: "origin/main", - gitHead: "HEAD", - reviewDepth: "standard", -}); - -const drift = await analyzeArchitectureDrift(root, { - provider: "git", - base: "origin/main", - head: "HEAD", - failOn: ["new-cycle", "public-api-removal"], - format: "compact", - graphEdges: "summary", - publicApi: "removals", -}); - const impact = await analyzeImpactFromDiff(root, index, { provider: "git", - base: "origin/main", - head: "HEAD", + base: "HEAD", + head: "WORKTREE", detectBreakingChanges: true, }); -for await (const chunk of analyzeImpactStreaming(root, index, { - provider: "git", - base: "origin/main", - head: "HEAD", -})) { - if (chunk.type === "complete") { - console.log(chunk.report.changedSymbols, chunk.report.impacted); - } -} - -const wrapped = await tool_impactJSON(root, { provider: "git", base: "HEAD", head: "WORKTREE" }, { index }); +console.log(impact.changedSymbols, impact.impacted); ``` -Good downstream packs preserve structured fields such as symbol handles, ranges, diff snippets, callsites, graph edges, candidate-test confidence, impact reasons, diagnostics, and `schemaVersion`/`format`. Streaming callers that only need incremental chunks can set `streamSummary: "light"` to skip terminal suggestions, export summaries, re-export chains, ranked top impacts, graph metadata, cycles, clusters, and surface-area work. Use [docs/library-api.md](./docs/library-api.md) for the full API reference and [docs/agent-workflows.md](./docs/agent-workflows.md) for session and streaming recipes. +Keep structured fields until the final UI or prompt boundary. Repeated callers should prefer one warm `createCodeReviewSession()` or agent/MCP session; see the [Library API reference](./docs/library-api.md) for exports, session lifecycle, streaming, graph APIs, and review reports. -Impact and review JSON may include `callCompatibility` on changed symbols when a provider-backed callable signature changes and resolved callsites have high-confidence argument counts. Treat these as review leads, not compiler-grade type checking; unsupported or ambiguous callsites are omitted from pretty output. Impact changed-file entries also preserve git copy or rename `oldFile` and `similarityIndex` metadata when available. +The public surface also includes `buildReviewReport`, `analyzeImpactStreaming`, and `tool_impactJSON` for specialized review and integration workflows. Batch output can retain ranked top impacts and full report metadata; streaming callers can choose a lighter terminal summary after consuming incremental chunks. -The supported package import surface includes the compatibility root export, `@lzehrung/codegraph`, plus documented subpath facades such as `@lzehrung/codegraph/agent`, `@lzehrung/codegraph/indexer`, and `@lzehrung/codegraph/impact`. The public API boundary and compatibility-export guidance live in [docs/library-api.md](./docs/library-api.md#public-api-boundary). +The root export includes compatibility APIs; documented subpath facades provide narrower imports. See the [public API boundary](./docs/library-api.md#public-api-boundary) before choosing an import path. -## Common workflows +## How it works -- Repo triage: run `codegraph inspect ./src --limit 20`, then follow with `codegraph hotspots ./src --limit 20` or `codegraph unresolved` to focus the next pass. -- Duplicate cleanup: run `codegraph duplicates ./src --min-confidence medium` for the default pretty triage view, or add `--json` when a downstream tool needs grouped duplicate data. -- Symbol navigation: use `codegraph goto ` and `codegraph refs --file --line --col --pretty` when a question is about definitions or semantic usages rather than matching strings. -- PR review: run `codegraph review --base origin/main --head HEAD --summary` for a compact reviewer handoff with actionable candidate tests, add `codegraph impact --base origin/main --head HEAD --pretty` when you need a ranked blast-radius map, or redirect plain `review` output when a downstream tool needs the full JSON bundle. -- Worktree review: run `codegraph review --base HEAD --head WORKTREE --summary` for current staged and unstaged tracked-file changes, then add `codegraph impact --base HEAD --head WORKTREE --pretty` only when the handoff needs wider blast-radius context. Use `--head STAGED` to compare `HEAD` against the current index. -- Graph exploration: run `codegraph graph --root . ./src --compact-json --output codegraph.json` for scripts, `--mermaid` for Markdown renderers, or `--dot` for Graphviz. Bare `codegraph graph` writes `codegraph.json`; add `--stdout` when piping. -- Public API inspection: run `codegraph apisurface` to summarize exported symbols before refactors, reviews, or release checks. +Codegraph follows a single analysis pipeline: -## Supported languages +1. Discover supported files under the selected project and include roots. +2. Parse source languages with Tree-sitter and extract imports, exports, definitions, bindings, and scopes. +3. Resolve module specifiers to project files or explicit external nodes. +4. Build forward and reverse dependency indexes plus a semantic symbol index. +5. Reuse those indexes for navigation, exploration, impact, review, and exports. -### Source languages +The native addon accelerates the normal Tree-sitter path; it is not a separate analysis model. Compatible disk caches and long-lived sessions avoid repeating unchanged work. [How it works](./docs/how-it-works.md) covers discovery, resolution, caching, recovery, and performance choices in detail. -JavaScript, TypeScript, Python, PHP, Go, Java, C#, Ruby, Rust, Kotlin, Swift, Zig, C, and C++ all participate in the shared source-language indexing and navigation pipeline. +## Limits and tradeoffs -### Graph-first formats +The honest boundaries matter: -HTML, Astro, Handlebars, Markdown, MDX, reStructuredText, AsciiDoc, CSS, SCSS, and Less participate in graph or chunking workflows with narrower capability claims than the full source-language pipeline. CSS-family graphing covers stylesheet imports; SCSS also resolves Sass partials, including extensionless and explicit `.scss` specifiers. +- Codegraph is not a compiler or type checker. Reflection, generated code, macros, overload behavior, and dynamic dispatch can be missed. +- Precise navigation depends on successful parsing and language queries. Without a compatible native runtime, Codegraph falls back to reduced graph-only and regex recovery rather than claiming equivalent semantics. +- Call-compatibility findings are conservative review leads, not compiler diagnostics. +- Duplicate matches and candidate tests are ranked leads that still require human or agent judgment. +- `--fast-graph` is an explicit speed/accuracy tradeoff for plain JavaScript and TypeScript import extraction. +- The checked benchmark fixtures demonstrate bounded evidence retrieval, not universal speed, cost, or quality advantages. See [Benchmark methodology](./docs/benchmarks/README.md). -### SQL - -SQL files participate in normal repository indexing. Codegraph discovers every `.sql` file by default, chunks SQL statements, extracts table/view/index/routine symbols, records common DDL/DML and CTE read/write facts, adds SQL-to-SQL object edges, and supports go-to-definition and find-references within SQL files. SQL navigation resolves schema-qualified names plus object-level `alias.column` and `schema.table.column` references to table/view definitions, but it does not claim column-definition resolution. SQL-to-SQL edges are precise for exact object-name matches, heuristic for unambiguous qualified-to-basename fallback matches, and skipped for ambiguous basename guesses. SQL indexing, graphing, and navigation work in native-only installs without the optional JS fallback package. SQL is still intentionally scoped to SQL semantics: Codegraph does not infer a current schema from migrations, fixtures, dumps, or seeds, and it does not globally link arbitrary application-code strings to SQL objects. - -### Single-file components - -Vue and Svelte script blocks are parsed with the JS and TS pipeline for dependency graphs and chunking, including external `