cartograph

package module
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 21, 2026 License: MIT Imports: 16 Imported by: 0

README

Cartograph

Build a nervous system for your codebase. Cartograph indexes any repository into a knowledge graph — every function, call chain, dependency, and execution flow — then exposes it through smart tools so AI agents never miss code.

⚠️ Early Development — Cartograph is under active development. Expect frequent updates, breaking changes, and rough edges. APIs, CLI flags, and storage formats may change without notice. Not recommended for production workflows yet.

Even smaller models get full architectural context, making them compete with frontier models on code tasks.

TL;DR: Point it at a repo, get a complete map. Use the CLI to search, trace impact, and explore — or connect it to your AI editor via MCP so Cursor, Claude Code, and friends stop missing dependencies and shipping blind edits.


Install

brew install onixhdz/tap/cartograph
Shell script (Linux & macOS)
curl -sSfL https://onixhdz.github.io/cartograph/install.sh | sh

Install a specific version or to a custom directory:

curl -sSfL https://onixhdz.github.io/cartograph/install.sh | sh -s -- --version vX.Y.Z
curl -sSfL https://onixhdz.github.io/cartograph/install.sh | sh -s -- --install-dir ~/bin
Windows

Download the latest binary from GitHub Releases and add it to your PATH.

Verify
cartograph --version

Quick Start

# Install the Agent Skills
cartograph skills

# Index by GitHub shorthand — no full URL needed
cartograph analyze <path|url>

# Index a specific tag or branch (Go module style)
cartograph analyze hashicorp/nomad@v1.8.0

# Index with semantic embeddings (enables semantic search)
cartograph analyze <path|url> --embed async

# Inspect an umbrella folder and show recommended repo candidates first
cartograph analyze ~/repos

# Search for execution flows
cartograph query "authentication middleware"

# Search exact source text or regex patterns
cartograph search 'func .*Handler'
cartograph grep 'panic(' -F

# Inspect the indexed file tree
cartograph tree internal/service --depth 2

# See everything about a symbol — callers, callees, processes, relationships
cartograph context UserService

# What breaks if you change something?
cartograph impact validateUser

That's it. The graph and search indexes are built, persisted locally, and ready to query. Analyze prints a combined search-index summary, for example Search indexes: BM25 5481 documents, regex 4185 files.

Use cartograph search when you know the text shape: identifiers, string literals, errors, TODOs, config keys, route strings, or regex patterns. Use cartograph query when you need meaning: behavior, execution flows, ownership, impact, or architecture.

Embedded Go API

Go programs can embed Cartograph in-process through the root package:

import "github.com/onixhdz/cartograph"

Use this when building a long-running tool that needs Cartograph's local or remote analysis, query, Cypher, schema, and source-read operations without shelling out to the CLI or running a separate service. Client.Analyze accepts local paths, Git URLs, host-prefixed URLs, repository shorthand, inline refs, and registry aliases. See docs/embedded-api.md.

When a target contains multiple repo candidates, run plain cartograph analyze <folder> first. Analyze prints the candidate list and recommended follow-up commands.


AI Editor Integration (MCP)

{ "mcpServers": { "cartograph": { "command": "cartograph", "args": ["mcp"] } } }
Editor Config location
Claude Code .mcp.json
Cursor .cursor/mcp.json
OpenCode .opencode/mcp.json

Cartograph supports hybrid search — BM25 full-text merged with vector similarity via Reciprocal Rank Fusion. Embeddings are optional; when enabled, query uses both signals for better recall.

# Embed synchronously (blocks until complete)
cartograph analyze <path|url> --embed <sync|async>

# Check progress
cartograph status --watch
Providers
Provider Description Flag
llamacpp Built-in llama.cpp/GGUF inference (default, no external service) --embed-provider llamacpp
openai_compat Any OpenAI-compatible API (Ollama, vLLM, LiteLLM, etc) --embed-provider openai_compat
Models
cartograph models list                # Show aliases + cache status
cartograph models pull nomic-code     # Download ahead of time
cartograph models rm jina-code        # Remove from cache

Any GGUF model on Hugging Face works: --embed-model "org/model-GGUF". Models are cached at ~/.cache/cartograph/models/ and also read from the HF hub cache for zero-copy reuse.


Wiki Generation

Generate a documentation wiki from the knowledge graph. Cartograph gathers the data; your AI agent writes the prose.

cartograph wiki generate    # collect context from the graph
# ... agent writes markdown pages via the wiki skill ...
cartograph wiki bundle      # package into a self-contained HTML viewer

The wiki skill is included in cartograph skills install.


Language Support

206 languages detected via tree-sitter. 13 Tier 1 languages get full extraction (symbols, imports, calls, heritage, types, assignments):

Go · TypeScript · JavaScript · Python · Java · Rust · C++ · C · Ruby · PHP · Kotlin · Swift · C#

56+ Tier 2 languages get inferred extraction via a grammar-agnostic AST engine — no hand-crafted queries needed.


How It Works

  1. Structure — Walk file tree, map folder/file relationships
  2. Parsing — Extract symbols via tree-sitter (hand-crafted + grammar-agnostic)
  3. Resolution — Resolve imports, calls, and inheritance across files
  4. Clustering — Group related symbols into communities (Leiden algorithm)
  5. Processes — Trace execution flows from entry points through call chains
  6. Search — Build BM25 indexes for graph query and regex indexes for raw source search

Everything is persisted locally — no external services needed.

cartograph query uses the knowledge graph plus search.bleve (BM25, and vectors when embeddings are complete). cartograph search and cartograph grep use search.regex plus stored source content for exact raw source matches.


Development

Prerequisites: Go 1.25+, Zig 0.14+ (for the native embedding library), and golangci-lint. Task is optional but recommended.

task test              # unit tests (short mode)
task test:integration  # all tests including network
task build:dev         # build for your host OS/arch
task lint              # golangci-lint

Or without Task:

go test -short ./...
go build ./...

Note: go build without Task skips the Zig-built embedding library — the llamacpp provider won't be available but everything else works.


Security & Privacy

Everything runs locally. No code leaves your machine. The index is stored in ~/.local/share/cartograph/ and can be deleted with cartograph clean.

When using --embed-provider openai_compat, only symbol names and descriptions are sent — no source code.


Acknowledgments

Cartograph was heavily inspired by GitNexus. Its approach to code knowledge graphs shaped many of the ideas here.


License

MIT

Documentation

Overview

Package cartograph provides the public embedded API for using Cartograph as an in-process Go library.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrDataDirInUse = errors.New("cartograph: data directory in use")

ErrDataDirInUse is returned when a background Cartograph service owns the configured data directory.

Functions

func DefaultDataDir

func DefaultDataDir() string

DefaultDataDir returns the default data directory for Cartograph.

It respects XDG_DATA_HOME when set, otherwise it falls back to ~/.local/share/cartograph.

Types

type AnalyzeOptions

type AnalyzeOptions struct {
	Force bool
	// Ref selects a remote branch or tag. Local targets reject this option.
	Ref string
	// CloneDepth controls remote shallow-clone depth. Values <= 0 use depth 1.
	CloneDepth int
	// AuthToken authenticates HTTPS clones of private repositories.
	AuthToken      string
	OnStep         func(step string, current, total int)
	OnFileProgress func(done, total int)
}

AnalyzeOptions controls local or remote repository analysis.

type AnalyzeResult

type AnalyzeResult struct {
	RepoName    string
	RepoHash    string
	IndexedPath string
	NodeCount   int
	EdgeCount   int
	Duration    time.Duration
	Skipped     bool
	Commit      string
}

AnalyzeResult summarizes a local or remote repository analysis run.

type CallTreeNode

type CallTreeNode struct {
	Symbol   SymbolMatch
	EdgeType string
	Children []CallTreeNode
	Pruned   int
}

CallTreeNode is a node in a transitive call tree returned by Context.

type CatFile

type CatFile struct {
	Path      string
	Content   string
	LineCount int
	Error     string
}

CatFile is a single file returned by Cat.

type CatOptions

type CatOptions struct {
	Lines string
}

CatOptions controls source reads.

type CatResult

type CatResult struct {
	Files []CatFile
}

CatResult contains file contents returned by Cat.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is an in-process Cartograph client.

A Client is safe for concurrent use. Repositories are loaded lazily on first access and remain cached until Close is called.

func Open

func Open(cfg Config) (*Client, error)

Open opens an embedded Cartograph client.

Example
package main

import (
	"context"

	"github.com/onixhdz/cartograph"
)

func main() {
	client, err := cartograph.Open(cartograph.Config{})
	if err != nil {
		return
	}
	defer client.Close()

	_, _ = client.List(context.Background())
}

func (*Client) Analyze

func (c *Client) Analyze(ctx context.Context, target string, opts AnalyzeOptions) (result *AnalyzeResult, retErr error)

Analyze analyzes and indexes one local path, Git URL, host-prefixed URL, or owner/repository shorthand target.

Example
package main

import (
	"context"

	"github.com/onixhdz/cartograph"
)

func main() {
	ctx := context.Background()
	client, err := cartograph.Open(cartograph.Config{})
	if err != nil {
		return
	}
	defer client.Close()

	result, err := client.Analyze(ctx, ".", cartograph.AnalyzeOptions{})
	if err != nil {
		return
	}

	_, _ = client.Schema(ctx, result.RepoHash)
}

func (*Client) Cat

func (c *Client) Cat(ctx context.Context, repo string, files []string, opts CatOptions) (*CatResult, error)

Cat returns source contents for files in an indexed repository.

func (*Client) Close

func (c *Client) Close() error

Close releases resources held by the client.

func (*Client) Context

func (c *Client) Context(ctx context.Context, repo, symbol string, opts ContextOptions) (*ContextResult, error)

Context returns symbol context from an indexed repository.

func (*Client) Cypher

func (c *Client) Cypher(ctx context.Context, repo, cypher string, _ CypherOptions) (*CypherResult, error)

Cypher runs a read-only Cypher query against an indexed repository.

func (*Client) Impact

func (c *Client) Impact(ctx context.Context, repo, symbol string, opts ImpactOptions) (*ImpactResult, error)

Impact returns upstream or downstream impact for a symbol.

func (*Client) List

func (c *Client) List(ctx context.Context) (*ListResult, error)

List lists indexed repositories in the configured data directory.

func (*Client) Query

func (c *Client) Query(ctx context.Context, repo, text string, opts QueryOptions) (*QueryResult, error)

Query runs a graph-aware query against an indexed repository or plugin dataset.

func (*Client) RegisterPlugin

RegisterPlugin registers and ingests a plugin directly in this process.

func (*Client) Schema

func (c *Client) Schema(ctx context.Context, repo string) (*SchemaResult, error)

Schema returns graph schema summaries for an indexed repository.

func (*Client) Search

func (c *Client) Search(ctx context.Context, repo, pattern string, opts SearchOptions) (*SearchResult, error)

Search searches source text in an indexed repository.

func (*Client) Status

func (c *Client) Status(ctx context.Context, repo string) (*StatusResult, error)

Status returns index status for one repository.

func (*Client) Tree

func (c *Client) Tree(ctx context.Context, repo string, _ TreeOptions) (*TreeResult, error)

Tree returns indexed file paths for a repository.

type Config

type Config struct {
	// DataDir is the Cartograph data directory. If empty, DefaultDataDir is used.
	DataDir string
}

Config configures an embedded Cartograph client.

type ContextOptions

type ContextOptions struct {
	File                 string
	UID                  string
	Content              bool
	Depth                int
	IncludeTests         bool
	IncludeRelationships bool
	RelationshipLimit    int
}

ContextOptions controls symbol context behavior.

type ContextRelationship

type ContextRelationship struct {
	FromID string
	From   SymbolMatch
	ToID   string
	To     SymbolMatch
}

ContextRelationship is a graph edge returned by context relationship mode.

type ContextResult

type ContextResult struct {
	Symbol             SymbolMatch
	Callers            []SymbolMatch
	Callees            []SymbolMatch
	CallTree           *CallTreeNode
	Importers          []SymbolMatch
	Imports            []SymbolMatch
	Processes          []SymbolMatch
	Implementors       []SymbolMatch
	Extends            []SymbolMatch
	RelationshipGroups []RelationshipGroup
	RelationshipStats  *RelationshipStats
}

ContextResult contains a symbol's immediate and optional transitive graph context.

type CypherOptions

type CypherOptions struct{}

CypherOptions is reserved for future read-only Cypher options.

type CypherResult

type CypherResult struct {
	Columns []string
	Rows    []map[string]any
}

CypherResult contains read-only Cypher query rows.

type ImpactOptions

type ImpactOptions struct {
	File         string
	Direction    string
	Depth        int
	CrossRepo    bool
	IncludeTests bool
}

ImpactOptions controls impact traversal behavior.

type ImpactResult

type ImpactResult struct {
	Target   SymbolMatch
	Affected []SymbolMatch
	Depth    int
}

ImpactResult contains affected symbols for a target.

type ListResult

type ListResult struct {
	Repos []RepoInfo
}

ListResult lists indexed repositories.

type NodeLabelSummary

type NodeLabelSummary struct {
	Label string
	Count int
}

NodeLabelSummary describes a node label and its count.

type PluginDatasetStatus

type PluginDatasetStatus struct {
	PluginName     string
	PluginVersion  string
	ConnectionName string
	Repo           string
	RepoHash       string
	NodeCount      int
	EdgeCount      int
	ResourceCount  int
	Duration       time.Duration
}

PluginDatasetStatus summarizes a registered plugin dataset.

type PluginDisplayField

type PluginDisplayField struct {
	Label string
	Value string
}

PluginDisplayField is one displayed plugin result field.

type PluginQueryMatch

type PluginQueryMatch struct {
	EntityLabel string
	NodeID      string
	Score       float64
	Fields      []PluginDisplayField
}

PluginQueryMatch represents one plugin dataset query match.

type ProcessMatch

type ProcessMatch struct {
	Name           string
	HeuristicLabel string
	StepCount      int
	CallerCount    int
	Importance     float64
	Relevance      float64
}

ProcessMatch represents a matched process in query results.

type QueryOptions

type QueryOptions struct {
	Plugin       bool
	Limit        int
	Content      bool
	CrossRepo    bool
	IncludeTests bool
}

QueryOptions controls Query behavior.

type QueryResult

type QueryResult struct {
	Processes      []ProcessMatch
	ProcessSymbols []SymbolMatch
	Definitions    []SymbolMatch
	UsageExamples  []SymbolMatch
	TestFlows      []ProcessMatch
	PluginResults  []PluginQueryMatch
}

QueryResult contains graph-aware query matches.

type RegisterPluginOptions

type RegisterPluginOptions struct {
	ConnectionName string
	Config         map[string]string
	ResourceTypes  []string
	Concurrency    int
	Timeout        time.Duration
	MaxNodes       int
	MaxEdges       int
}

RegisterPluginOptions configures in-process plugin registration.

type RelTypeSummary

type RelTypeSummary struct {
	Type  string
	Count int
}

RelTypeSummary describes a relationship type and its count.

type RelationshipGroup

type RelationshipGroup struct {
	Type          string
	Relationships []ContextRelationship
}

RelationshipGroup contains context relationships grouped by graph relationship type.

type RelationshipPatternSummary

type RelationshipPatternSummary struct {
	From  string
	Type  string
	To    string
	Count int
}

RelationshipPatternSummary describes an observed edge pattern.

type RelationshipStats

type RelationshipStats struct {
	Depth                 int
	ReturnedNodes         int
	ReturnedRelationships int
	Limit                 int
	Truncated             bool
}

RelationshipStats describes a bounded graph neighborhood returned with Context.

type RepoArtifact

type RepoArtifact struct {
	Name  string
	Bytes int64
}

RepoArtifact describes one on-disk index artifact.

type RepoInfo

type RepoInfo struct {
	Name      string
	Hash      string
	Type      string
	IndexedAt string
	NodeCount int
	EdgeCount int
	BuiltWith string
	Embedding string
}

RepoInfo describes one indexed repository.

type SchemaResult

type SchemaResult struct {
	NodeLabels           []NodeLabelSummary
	RelTypes             []RelTypeSummary
	RelationshipPatterns []RelationshipPatternSummary
	Properties           []string
	TotalNodes           int
	TotalEdges           int
}

SchemaResult summarizes the graph schema for writing Cypher queries.

type SearchMatch

type SearchMatch struct {
	FilePath string
	Line     int
	Column   int
	LineText string
	Before   []string
	After    []string
	Symbol   *SymbolMatch
}

SearchMatch is one source search match plus bounded context.

type SearchOptions

type SearchOptions struct {
	FixedStrings bool
	IgnoreCase   bool
	Limit        int
	ContextLines int
	Files        string
	ExcludeTests bool
}

SearchOptions controls source search behavior.

type SearchResult

type SearchResult struct {
	Repo         string
	Pattern      string
	FixedStrings bool
	IndexStatus  string
	Message      string
	DurationMS   int64
	MatchCount   int
	FileCount    int
	Truncated    bool
	Matches      []SearchMatch
}

SearchResult contains source search matches.

type StatusResult

type StatusResult struct {
	Name              string
	Hash              string
	Path              string
	URL               string
	Type              string
	Indexed           bool
	IndexedAt         string
	NodeCount         int
	EdgeCount         int
	Commit            string
	Branch            string
	Languages         []string
	Duration          string
	BuiltWith         string
	EmbeddingStatus   string
	EmbeddingProgress int
	EmbeddingTotal    int
	EmbeddingModel    string
	EmbeddingProvider string
	EmbeddingDims     int
	EmbeddingError    string
	Artifacts         []RepoArtifact
}

StatusResult describes one repository's index status.

type SymbolMatch

type SymbolMatch struct {
	Name        string
	FilePath    string
	StartLine   int
	EndLine     int
	Label       string
	ProcessName string
	Content     string
	Score       float64
	Repo        string
	Signature   string
}

SymbolMatch represents a matched symbol in query, context, and impact results.

type TreeOptions

type TreeOptions struct{}

TreeOptions configures Tree. There are currently no options.

type TreeResult

type TreeResult struct {
	Repo  string
	Files []string
}

TreeResult contains indexed repository file paths.

Directories

Path Synopsis
cmd
cartograph command
examples
embedded command
internal
embedding
Package embedding provides text embedding vectors for semantic search.
Package embedding provides text embedding vectors for semantic search.
embedding/local
Package local provides embedding via native CGO-linked inference.
Package local provides embedding via native CGO-linked inference.
graph
Package graph defines the node labels, relationship types, and property structs used throughout the Cartograph knowledge graph.
Package graph defines the node labels, relationship types, and property structs used throughout the Cartograph knowledge graph.
ingestion
Package ingestion implements the Cartograph ingestion pipeline: filesystem walking, structure building, import/call/heritage resolution, community detection, and process detection.
Package ingestion implements the Cartograph ingestion pipeline: filesystem walking, structure building, import/call/heritage resolution, community detection, and process detection.
mcp
Package mcp implements an MCP (Model Context Protocol) server for Cartograph.
Package mcp implements an MCP (Model Context Protocol) server for Cartograph.
query
Package query implements the query/context/cypher/impact tool backends that operate on an in-memory lpg.Graph.
Package query implements the query/context/cypher/impact tool backends that operate on an in-memory lpg.Graph.
remote
Package remote provides Git remote operations: URL parsing, cloning (in-memory and on-disk), and billy filesystem walkers/readers that integrate with the ingestion pipeline.
Package remote provides Git remote operations: URL parsing, cloning (in-memory and on-disk), and billy filesystem walkers/readers that integrate with the ingestion pipeline.
search
Package search implements full-text search (BM25 via Bleve) and hybrid search (RRF merging) for the Cartograph knowledge graph.
Package search implements full-text search (BM25 via Bleve) and hybrid search (RRF merging) for the Cartograph knowledge graph.
service
Package service defines the HTTP/JSON API types for the CLI ↔ service IPC.
Package service defines the HTTP/JSON API types for the CLI ↔ service IPC.
storage
Package storage defines the GraphStore persistence interface and repository metadata management.
Package storage defines the GraphStore persistence interface and repository metadata management.
storage/bbolt
Package bbolt implements the storage.GraphStore interface using bbolt (an embedded key-value store) with msgpack serialization.
Package bbolt implements the storage.GraphStore interface using bbolt (an embedded key-value store) with msgpack serialization.
sysutil
Package sysutil provides platform-specific system utilities: available memory, process detachment, signal handling, and PID management for resource-aware tuning and daemon lifecycle control.
Package sysutil provides platform-specific system utilities: available memory, process detachment, signal handling, and PID management for resource-aware tuning and daemon lifecycle control.
testutil
Package testutil provides shared test fixtures and helpers for Cartograph unit tests.
Package testutil provides shared test fixtures and helpers for Cartograph unit tests.
wiki
Package wiki implements context generation and HTML bundling for agent-driven wiki generation.
Package wiki implements context generation and HTML bundling for agent-driven wiki generation.
Package plugin is the SDK for implementing in-process Cartograph plugins.
Package plugin is the SDK for implementing in-process Cartograph plugins.
plugintest
Package plugintest provides test utilities for Cartograph plugin authors.
Package plugintest provides test utilities for Cartograph plugin authors.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL