codegraph

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jun 25, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const EmbeddingDimension = 128

EmbeddingDimension is the size of the hash-based embedding vector. 128 dimensions provides good separation for code symbols without requiring external ML models.

Variables

This section is empty.

Functions

func CosineSimilarity

func CosineSimilarity(a, b []float32) float32

CosineSimilarity computes cosine similarity between two vectors.

func CrossRepoImpact

func CrossRepoImpact(repos []string, symbol string, maxDepth int) (map[string]*ImpactResult, error)

CrossRepoImpact finds the impact of changing a symbol across multiple repos. If a symbol in hawk calls a symbol in eyrie, this traces that cross-repo dependency.

func CrossRepoQuery

func CrossRepoQuery(repos []string, query string, limit int) (map[string][]Node, error)

CrossRepoQuery queries across multiple codegraph databases. Useful for finding relationships between hawk, eyrie, tok, yaad, etc.

func GenerateEmbedding

func GenerateEmbedding(node Node) []float32

GenerateEmbedding creates a hash-based embedding for a code symbol. Uses feature hashing (the "hashing trick") to map code features to a fixed-size vector without requiring a trained model.

Features extracted: - Symbol name (split on camelCase/snake_case) - Qualified name parts - Docstring tokens - Signature tokens - File path components - Kind (function, class, etc.)

Types

type ASTEdge

type ASTEdge struct {
	Source string `json:"source"`
	Target string `json:"target"`
	Type   string `json:"type"` // "contains", "defines", "uses"
}

type ASTNode

type ASTNode struct {
	ID       string `json:"id"`
	Type     string `json:"type"` // "func", "type", "var", "const", "import"
	Name     string `json:"name"`
	File     string `json:"file"`
	StartPos int    `json:"start_pos"`
	EndPos   int    `json:"end_pos"`
}

type ASTView

type ASTView struct {
	Nodes []ASTNode `json:"nodes"`
	Edges []ASTEdge `json:"edges"`
}

ASTView represents the abstract syntax tree view.

type BetweennessResult

type BetweennessResult struct {
	Scores map[string]float64 `json:"scores"` // nodeID -> centrality score
	Top    []NodeCentrality   `json:"top"`    // top-N by centrality
}

BetweennessResult holds centrality scores for nodes.

type CFGEdge

type CFGEdge struct {
	Source string `json:"source"`
	Target string `json:"target"`
	Type   string `json:"type"` // "sequential", "branch_true", "branch_false", "loop_body", "loop_exit"
}

type CFGNode

type CFGNode struct {
	ID       string `json:"id"`
	Type     string `json:"type"` // "entry", "exit", "branch", "loop", "call", "return"
	Function string `json:"function"`
	File     string `json:"file"`
	Line     int    `json:"line"`
}

type CFGView

type CFGView struct {
	Nodes []CFGNode `json:"nodes"`
	Edges []CFGEdge `json:"edges"`
}

CFGView represents the control flow graph view.

type CallEdge

type CallEdge struct {
	Caller string `json:"caller"`
	Callee string `json:"callee"`
	File   string `json:"file"`
	Line   int    `json:"line"`
}

type CallNode

type CallNode struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	File     string `json:"file"`
	Line     int    `json:"line"`
	IsExport bool   `json:"is_export"`
}

type CallView

type CallView struct {
	Nodes []CallNode `json:"nodes"`
	Edges []CallEdge `json:"edges"`
}

CallView represents the call graph view.

type CodeGraph

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

CodeGraph is a tree-sitter based code knowledge graph. It parses source code into a graph of symbols and edges, stored in SQLite with FTS5 for fast search.

func Open

func Open(root string) (*CodeGraph, error)

Open opens or creates a CodeGraph database at the given path.

func (*CodeGraph) AnalyzeCoupling

func (cg *CodeGraph) AnalyzeCoupling(topN int) ([]CouplingMetric, error)

AnalyzeCoupling finds pairs of files that are tightly coupled (share many dependencies).

func (*CodeGraph) BetweennessCentrality

func (cg *CodeGraph) BetweennessCentrality(topN int) (*BetweennessResult, error)

BetweennessCentrality computes betweenness centrality for all nodes in the graph. Betweenness centrality measures how often a node lies on shortest paths between other nodes — high-centrality nodes are "bridges" connecting different parts of the codebase. Useful for finding coupling hotspots.

Algorithm: Brandes' algorithm (O(VE) for unweighted graphs).

func (*CodeGraph) BuildContext

func (cg *CodeGraph) BuildContext(query string, maxNodes int) (string, error)

BuildContext builds relevant context for a natural language query.

func (*CodeGraph) Close

func (cg *CodeGraph) Close() error

Close closes the database connection.

func (*CodeGraph) CommunityDetection

func (cg *CodeGraph) CommunityDetection() (*CommunityDetectionResult, error)

CommunityDetection finds communities (module boundaries) using the Louvain algorithm. Communities are groups of nodes that are more densely connected to each other than to the rest of the graph. This automatically discovers module boundaries.

Algorithm: Louvain method (greedy modularity optimization).

func (*CodeGraph) ConnectedComponents

func (cg *CodeGraph) ConnectedComponents() ([][]string, error)

ConnectedComponents finds isolated subsystems in the code graph. Each component is a set of nodes where every node is reachable from every other.

func (*CodeGraph) DiffGraph

func (cg *CodeGraph) DiffGraph(beforeNodes map[string]bool, beforeEdges map[string]bool) *GraphDiff

GraphDiff computes the structural difference between the current graph and a snapshot. Useful for detecting what changed after a sync.

func (*CodeGraph) Explore

func (cg *CodeGraph) Explore(query string, maxFiles int) (*ExploreResult, error)

Explore returns source code for several related symbols grouped by file.

func (*CodeGraph) Files

func (cg *CodeGraph) Files(dirFilter string) ([]FileEntry, error)

Files returns the list of all indexed files.

func (*CodeGraph) FindDeadCode

func (cg *CodeGraph) FindDeadCode() ([]DeadCodeEntry, error)

FindDeadCode uses the call graph to find symbols that are never called/referenced. More accurate than standalone dead code detection because it uses the full resolved call graph from codegraph.

func (*CodeGraph) GetCallees

func (cg *CodeGraph) GetCallees(nodeID string, maxDepth int) ([]Node, error)

GetCallees returns nodes that the given node calls.

func (*CodeGraph) GetCallers

func (cg *CodeGraph) GetCallers(nodeID string, maxDepth int) ([]Node, error)

GetCallers returns nodes that call the given node.

func (*CodeGraph) GetImpactRadius

func (cg *CodeGraph) GetImpactRadius(nodeID string, maxDepth int) ([]Node, error)

GetImpactRadius returns all nodes affected by changing the given node.

func (*CodeGraph) GetNode

func (cg *CodeGraph) GetNode(id string) (Node, error)

GetNode returns a single node by ID.

func (*CodeGraph) HybridSearch

func (cg *CodeGraph) HybridSearch(query string, limit int) ([]Node, error)

HybridSearch combines FTS5 keyword search with embedding-based semantic search. Uses Reciprocal Rank Fusion (RRF) to merge results from both methods.

func (*CodeGraph) ImpactAnalysis

func (cg *CodeGraph) ImpactAnalysis(nodeID string, maxDepth int) (*ImpactResult, error)

ImpactAnalysis computes the blast radius of changing a symbol. Uses the full call graph to find all directly and transitively affected nodes.

func (*CodeGraph) IndexDir

func (cg *CodeGraph) IndexDir(dir string) error

IndexDir indexes all supported source files in a directory.

func (*CodeGraph) IndexFile

func (cg *CodeGraph) IndexFile(filePath string) error

IndexFile parses a file and stores its symbols in the graph.

func (*CodeGraph) PageRank

func (cg *CodeGraph) PageRank(iterations int, damping float64) (map[string]float64, error)

PageRank computes PageRank on the code graph's call/reference edges. This is more accurate than repomap's PageRank because it uses the precise call graph from tree-sitter parsing rather than string matching.

func (*CodeGraph) ResolveRefs

func (cg *CodeGraph) ResolveRefs() error

ResolveRefs resolves unresolved references to build call graph edges.

func (*CodeGraph) Search

func (cg *CodeGraph) Search(query string, limit int) ([]Node, error)

Search finds symbols by name using FTS5.

func (*CodeGraph) SemanticSearch

func (cg *CodeGraph) SemanticSearch(query string, limit int) ([]Node, error)

SemanticSearch performs embedding-based semantic search. It generates embeddings for all nodes and finds the most similar to the query embedding.

func (*CodeGraph) SnapshotGraph

func (cg *CodeGraph) SnapshotGraph() (nodes map[string]bool, edges map[string]bool, err error)

SnapshotGraph returns the current graph state for diffing.

func (*CodeGraph) Stats

func (cg *CodeGraph) Stats() (map[string]interface{}, error)

Stats returns graph statistics.

func (*CodeGraph) Status

func (cg *CodeGraph) Status() (*StatusResult, error)

Status returns detailed index health and statistics.

func (*CodeGraph) Sync

func (cg *CodeGraph) Sync() (*SyncResult, error)

Sync performs an incremental sync — only re-indexes files whose content hash has changed since the last index. Removes files that no longer exist.

func (*CodeGraph) Trace

func (cg *CodeGraph) Trace(fromName, toName string) ([]Node, error)

Trace finds the shortest call path between two symbols. Returns the chain of nodes from 'from' to 'to', or nil if no path exists.

type CodePattern

type CodePattern struct {
	PatternID   string   `json:"pattern_id"`
	Name        string   `json:"name"`
	Description string   `json:"description"`
	Example     string   `json:"example"`     // code example
	WhenToUse   string   `json:"when_to_use"` // when to apply this pattern
	Files       []string `json:"files"`       // files where pattern was found
	Frequency   int      `json:"frequency"`   // how often seen
	Tags        []string `json:"tags"`
}

CodePattern stores a learned code pattern.

func ExtractPatternsFromCode

func ExtractPatternsFromCode(nodes []Node) []CodePattern

ExtractPatternsFromCode analyzes code to extract recurring patterns.

type CodeVectorStore

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

CodeVectorStore extends VectorStore with code-specific functionality.

func NewCodeVectorStore

func NewCodeVectorStore() *CodeVectorStore

NewCodeVectorStore creates a vector store for code symbols.

func (*CodeVectorStore) HybridSearch

func (cvs *CodeVectorStore) HybridSearch(ctx context.Context, query string, limit int, keywordResults []Node) ([]Node, error)

HybridSearch combines vector search with keyword search.

func (*CodeVectorStore) IndexNode

func (cvs *CodeVectorStore) IndexNode(ctx context.Context, node Node) error

IndexNode adds a code symbol to the vector store.

func (*CodeVectorStore) SearchCode

func (cvs *CodeVectorStore) SearchCode(ctx context.Context, query string, limit int) ([]Node, error)

SearchCode finds code symbols similar to the query.

func (*CodeVectorStore) Stats

func (cvs *CodeVectorStore) Stats() map[string]interface{}

Stats returns vector store statistics.

type Collection

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

Collection represents a vector collection (simplified for non-CGO builds).

type Community

type Community struct {
	ID    int      `json:"id"`
	Nodes []string `json:"nodes"`
	Score float64  `json:"modularity_score"`
}

Community holds a cluster of nodes detected by community detection.

type CommunityDetectionResult

type CommunityDetectionResult struct {
	Communities []Community `json:"communities"`
	Modularity  float64     `json:"modularity"`
}

CommunityDetectionResult holds the result of community detection.

type CouplingMetric

type CouplingMetric struct {
	FileA      string  `json:"file_a"`
	FileB      string  `json:"file_b"`
	SharedDeps int     `json:"shared_deps"` // number of shared dependencies
	Coupling   float64 `json:"coupling"`    // 0-1 coupling score
}

CouplingMetric represents coupling between two modules/files.

type CrossRepoCall

type CrossRepoCall struct {
	FromRepo string `json:"from_repo"`
	ToRepo   string `json:"to_repo"`
	Symbol   string `json:"symbol"`
	File     string `json:"file"`
	Line     int    `json:"line"`
	Target   Node   `json:"target"`
}

CrossRepoCall represents a function call that crosses repo boundaries.

func FindCrossRepoCalls

func FindCrossRepoCalls(repos []string) ([]CrossRepoCall, error)

FindCrossRepoCalls finds function calls that cross repo boundaries. For example, hawk calling eyrie functions.

type DFGEdge

type DFGEdge struct {
	Source string `json:"source"`
	Target string `json:"target"`
	Type   string `json:"type"` // "defines", "uses", "flows_to", "depends_on"
}

type DFGNode

type DFGNode struct {
	ID       string `json:"id"`
	Type     string `json:"type"` // "definition", "use", "parameter", "return"
	Name     string `json:"name"`
	Variable string `json:"variable"`
	File     string `json:"file"`
	Line     int    `json:"line"`
}

type DFGView

type DFGView struct {
	Nodes []DFGNode `json:"nodes"`
	Edges []DFGEdge `json:"edges"`
}

DFGView represents the data flow graph view.

type DeadCodeEntry

type DeadCodeEntry struct {
	Node       Node    `json:"node"`
	Confidence float64 `json:"confidence"`
	Reason     string  `json:"reason"`
}

DeadCodeEntry represents a potentially dead code symbol.

type Edge

type Edge struct {
	ID       int    `json:"id"`
	Source   string `json:"source"`
	Target   string `json:"target"`
	Kind     string `json:"kind"`
	Line     int    `json:"line"`
	Metadata string `json:"metadata"`
}

Edge represents a relationship between two nodes.

type ExploreResult

type ExploreResult struct {
	Files       map[string][]Node `json:"files"`
	SourceLines map[string]string `json:"source_lines"` // file:line -> source snippet
}

ExploreResult holds source code for multiple symbols grouped by file.

type FileEntry

type FileEntry struct {
	Path      string `json:"path"`
	Language  string `json:"language"`
	Size      int    `json:"size"`
	NodeCount int    `json:"node_count"`
	IndexedAt int    `json:"indexed_at"`
}

FileEntry represents a tracked file in the index.

type GraphDiff

type GraphDiff struct {
	AddedNodes   []string `json:"added_nodes"`
	RemovedNodes []string `json:"removed_nodes"`
	AddedEdges   int      `json:"added_edges"`
	RemovedEdges int      `json:"removed_edges"`
	Affected     []string `json:"affected_files"` // files whose symbols changed
}

GraphDiff represents structural changes between two graph states.

type ImpactResult

type ImpactResult struct {
	Root     string         `json:"root"`
	Impacted map[string]int `json:"impacted"` // nodeID -> depth
	Nodes    []Node         `json:"nodes"`
	MaxDepth int            `json:"max_depth"`
}

ImpactResult holds the result of impact analysis.

type IssueMemory

type IssueMemory struct {
	IssueID      string    `json:"issue_id"`
	Title        string    `json:"title"`
	Description  string    `json:"description"`
	RootCause    string    `json:"root_cause"`
	FixPattern   string    `json:"fix_pattern"` // pattern that fixed it
	FilesChanged []string  `json:"files_changed"`
	SymbolsUsed  []string  `json:"symbols_used"` // symbols involved in the fix
	Approach     string    `json:"approach"`     // approach taken
	Success      bool      `json:"success"`
	Duration     string    `json:"duration"`
	CreatedAt    time.Time `json:"created_at"`
	Tags         []string  `json:"tags"` // "bug", "feature", "refactor", "security"
}

IssueMemory stores what was learned from a resolved issue.

type LanguageExtractor

type LanguageExtractor struct {
	FunctionTypes  []string
	ClassTypes     []string
	MethodTypes    []string
	InterfaceTypes []string
	StructTypes    []string
	EnumTypes      []string
	TypeAliasTypes []string
	ImportTypes    []string
	CallTypes      []string
	VariableTypes  []string

	NameField   string
	BodyField   string
	ParamsField string

	GetSignature  func(node *sitter.Node, source []byte) string
	GetVisibility func(node *sitter.Node, source []byte) string
	IsExported    func(node *sitter.Node, source []byte) bool
	ExtractImport func(node *sitter.Node, source []byte) (fromPath string, names []string)
}

LanguageExtractor defines how to extract symbols from a language's AST.

type MemoryStore

type MemoryStore interface {
	Save(key string, value []byte) error
	Load(key string) ([]byte, error)
	List(prefix string) ([]string, error)
	Delete(key string) error
}

MemoryStore is the interface for persistent storage.

type MultiViewGraph

type MultiViewGraph struct {
	AST  *ASTView  `json:"ast"`
	DFG  *DFGView  `json:"dfg"`
	CFG  *CFGView  `json:"cfg"`
	Call *CallView `json:"call"`
}

MultiViewGraph represents code from multiple perspectives: AST (syntax), DFG (data flow), CFG (control flow), and Call Graph. Research shows multi-view representation improves all downstream tasks.

func BuildMultiViewGraph

func BuildMultiViewGraph(filePath string, source []byte) (*MultiViewGraph, error)

BuildMultiViewGraph constructs a multi-view graph from Go source code.

type Node

type Node struct {
	ID            string `json:"id"`
	Kind          string `json:"kind"`
	Name          string `json:"name"`
	QualifiedName string `json:"qualified_name"`
	FilePath      string `json:"file_path"`
	Language      string `json:"language"`
	StartLine     int    `json:"start_line"`
	EndLine       int    `json:"end_line"`
	Signature     string `json:"signature"`
	Docstring     string `json:"docstring"`
	Visibility    string `json:"visibility"`
	IsExported    bool   `json:"is_exported"`
}

Node represents a code symbol (function, class, method, etc.).

type NodeCentrality

type NodeCentrality struct {
	NodeID   string  `json:"node_id"`
	Name     string  `json:"name"`
	FilePath string  `json:"file_path"`
	Score    float64 `json:"score"`
	Kind     string  `json:"kind"`
}

type RepoMemory

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

RepoMemory integrates codegraph with yaad (persistent memory) to learn from past issues, fixes, and code patterns. This implements the research finding that repository memory improves localization by 13%.

func NewRepoMemory

func NewRepoMemory(store MemoryStore) *RepoMemory

NewRepoMemory creates a new repository memory system.

func (*RepoMemory) BuildContextFromMemory

func (rm *RepoMemory) BuildContextFromMemory(query string) string

BuildContextFromMemory builds context from past issues and patterns.

func (*RepoMemory) FindRelevantPatterns

func (rm *RepoMemory) FindRelevantPatterns(context string, limit int) ([]CodePattern, error)

FindRelevantPatterns finds patterns relevant to the given context.

func (*RepoMemory) FindSimilarIssues

func (rm *RepoMemory) FindSimilarIssues(description string, limit int) ([]IssueMemory, error)

FindSimilarIssues finds past issues similar to the given description.

func (*RepoMemory) SaveIssue

func (rm *RepoMemory) SaveIssue(mem IssueMemory) error

SaveIssue records what was learned from resolving an issue.

func (*RepoMemory) SavePattern

func (rm *RepoMemory) SavePattern(pattern CodePattern) error

SavePattern records a learned code pattern.

type SearchResult

type SearchResult struct {
	ID       string
	Score    float32
	Metadata map[string]string
}

SearchResult represents a search result.

type StatusResult

type StatusResult struct {
	ProjectRoot string         `json:"project_root"`
	DBPath      string         `json:"db_path"`
	DBSizeBytes int64          `json:"db_size_bytes"`
	Files       int            `json:"files"`
	Nodes       int            `json:"nodes"`
	Edges       int            `json:"edges"`
	Unresolved  int            `json:"unresolved_refs"`
	NodesByKind map[string]int `json:"nodes_by_kind"`
	FilesByLang map[string]int `json:"files_by_lang"`
	JournalMode string         `json:"journal_mode"`
	UpToDate    bool           `json:"up_to_date"`
}

StatusResult holds detailed index health information.

type SyncResult

type SyncResult struct {
	FilesChecked  int `json:"files_checked"`
	FilesAdded    int `json:"files_added"`
	FilesModified int `json:"files_modified"`
	FilesRemoved  int `json:"files_removed"`
	NodesUpdated  int `json:"nodes_updated"`
	DurationMs    int `json:"duration_ms"`
}

SyncResult holds the result of an incremental sync.

type UnresolvedRef

type UnresolvedRef struct {
	FromNodeID    string
	ReferenceName string
	ReferenceKind string
	Line          int
	FilePath      string
	Language      string
}

type Vector

type Vector struct {
	ID        string
	Embedding []float32
	Metadata  map[string]string
}

Vector represents a stored vector.

type VectorStore

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

VectorStore provides zero-dependency vector search using chromem-go. This is a pure Go implementation that requires no external services. Based on research: chromem-go provides ChromaDB-compatible vector search with zero CGO dependencies, making it ideal for cross-platform builds.

func NewVectorStore

func NewVectorStore(dim int) *VectorStore

NewVectorStore creates a new vector store.

func (*VectorStore) Add

func (vs *VectorStore) Add(ctx context.Context, id string, embedding []float32, metadata map[string]string) error

Add inserts a vector into the store.

func (*VectorStore) Count

func (vs *VectorStore) Count(ctx context.Context) int

Count returns the number of vectors in the store.

func (*VectorStore) Delete

func (vs *VectorStore) Delete(ctx context.Context, id string) error

Delete removes a vector from the store.

func (*VectorStore) Search

func (vs *VectorStore) Search(ctx context.Context, query []float32, k int) ([]SearchResult, error)

Search finds the k nearest neighbors to the query vector.

Jump to

Keyboard shortcuts

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