codegraph

package
v0.17.16 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultDBPath

func DefaultDBPath() (string, error)

DefaultDBPath returns the default database path resolved from git root.

Types

type ConfidenceLevel added in v0.16.25

type ConfidenceLevel string

ConfidenceLevel indicates how likely a dead code candidate is to be genuinely dead.

const (
	ConfidenceHigh   ConfidenceLevel = "high"   // Very likely dead: unexported, no registration patterns
	ConfidenceMedium ConfidenceLevel = "medium" // Possibly dead: name or path has minor false-positive hints
	ConfidenceLow    ConfidenceLevel = "low"    // Probably alive: in handler/registration files, name matches known patterns
)

type DeadCodeCandidate added in v0.16.25

type DeadCodeCandidate struct {
	Symbol      Symbol
	Confidence  ConfidenceLevel
	TestCallers int // number of callers found in test files (0 = no test callers)
}

DeadCodeCandidate is a symbol with zero inbound call edges, plus metadata about confidence and whether it has test-only callers.

type Edge

type Edge struct {
	SourceQualifiedName string // qualified name of the caller/owner
	TargetQualifiedName string // qualified name of the callee/target
	EdgeType            string // "calls", "defined_in", "imports"
	Line                int    // line where the edge originates
}

Edge represents a relationship between two symbols. SourceQualifiedName and TargetQualifiedName are the qualified names of the caller and callee respectively. They are resolved to node IDs during IndexFile. EdgeType values:

"calls"          - textual/unresolved call edge (same-package or unresolved cross-package)
"resolved_calls" - resolved cross-package call edge (target qualified via import map)
"defined_in"     - symbol defined in a file/package
"imports"        - module-level import relationship

type FileParser

type FileParser func(path string, content []byte) ([]Symbol, []Edge, error)

FileParser is a function that parses a source file at the given path and returns the symbols and edges to index. Implementations can call external parsers (e.g., from pkg/agent_tools) to extract this information.

type GraphStats

type GraphStats struct {
	NodeCount int
	EdgeCount int
	FileCount int
}

GraphStats provides summary statistics about the graph

type SQLiteStore

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

SQLiteStore implements Store using a SQLite database.

func NewStore

func NewStore(dbPath string) (*SQLiteStore, error)

NewStore opens a SQLite-backed code graph store at the given path. If dbPath is empty, the database is placed at `.sprout/codegraph.db` relative to the git root.

func (*SQLiteStore) BaseDir

func (s *SQLiteStore) BaseDir() string

BaseDir returns the git root directory used for resolving relative file paths.

func (*SQLiteStore) Close

func (s *SQLiteStore) Close() error

Close closes the underlying database.

func (*SQLiteStore) FindDeadCode

func (s *SQLiteStore) FindDeadCode(ctx context.Context, directory string) ([]Symbol, error)

FindDeadCode returns symbols with zero inbound call edges. Excludes known entry points: main(), init(), exported functions, and test functions. If directory is non-empty, restricts results to files under that directory prefix.

CAUTION: This is a heuristic lower-bound. Static call-graph extraction cannot trace through reflection, interface dispatch, cobra/click command registrations, or closures assigned to struct fields. Functions reported as "dead" may be reachable through these dynamic mechanisms. Treat results as candidates for manual review, not authoritative dead code.

func (*SQLiteStore) FindDeadCodeWithMeta added in v0.16.25

func (s *SQLiteStore) FindDeadCodeWithMeta(ctx context.Context, directory string) ([]DeadCodeCandidate, error)

FindDeadCodeWithMeta returns dead code candidates with confidence scoring and test-only caller detection. Test-only detection requires test files to be indexed in the graph; if they're not, TestCallers will always be 0.

Use HasTestCallers() to do a filesystem-based check for test references on candidates where TestCallers is 0 but the graph may not include tests.

func (*SQLiteStore) FindReferrerFiles

func (s *SQLiteStore) FindReferrerFiles(ctx context.Context, filePaths []string) ([]string, error)

FindReferrerFiles returns the set of file paths whose nodes have edges pointing to nodes in any of the given file paths. This identifies files whose outgoing edges may become stale when a callee file is re-indexed. Used by the incremental update path to compute the affected-file closure.

func (*SQLiteStore) GetStaleFiles

func (s *SQLiteStore) GetStaleFiles(ctx context.Context) ([]string, error)

GetStaleFiles returns file paths whose on-disk mtime is newer than the stored last_indexed timestamp. Deleted files are also reported as stale.

func (*SQLiteStore) IndexAll

func (s *SQLiteStore) IndexAll(ctx context.Context, parseFile FileParser) error

IndexAll performs a full walk of all source files in the repo and indexes them. Uses two-phase indexing: first inserts all symbols, then inserts all edges. This ensures cross-file call edges resolve correctly since all nodes exist in the database before edges are inserted.

func (*SQLiteStore) IndexChangedFiles

func (s *SQLiteStore) IndexChangedFiles(ctx context.Context, parseFile FileParser) error

IndexChangedFiles indexes only files whose on-disk mtime differs from last_indexed. Uses GetStaleFiles internally.

Uses a scoped two-phase approach mirroring IndexAll to preserve cross-file edges correctly: (1) compute the closure of affected files (stale files + files whose edges point into them) BEFORE any deletion, (2) re-index symbols for stale files, (3) re-parse and bulk-insert edges for the entire closure.

Referrer files (those with edges into stale files) only have their OUTGOING edges deleted and re-resolved; their incoming edges are preserved. This prevents progressive edge loss in multi-level call chains (X→A→B where only B changes must not lose X→A).

func (*SQLiteStore) IndexFile

func (s *SQLiteStore) IndexFile(ctx context.Context, path string, symbols []Symbol, edges []Edge) error

IndexFile stores all symbols and edges for a given file. It replaces existing data for this file path (delete old nodes/edges, insert new).

func (*SQLiteStore) InsertAllEdges

func (s *SQLiteStore) InsertAllEdges(ctx context.Context, edges []Edge) error

InsertAllEdges inserts all call edges in a single transaction. All nodes must already exist in the database (call IndexFile or indexSymbolsOnly first). Deletes ALL existing edges first, then inserts the new set — this is correct for a full rebuild via IndexAll.

func (*SQLiteStore) InsertEdgesForFiles

func (s *SQLiteStore) InsertEdgesForFiles(ctx context.Context, stalePaths, referrerPaths []string, edges []Edge) error

InsertEdgesForFiles deletes and re-inserts edges for a scoped set of files. It is the scoped equivalent of InsertAllEdges used by the incremental update path: rather than wiping the entire edge table, it only touches edges from the affected files.

stalePaths: files whose symbols were just re-indexed (nodes deleted + recreated).

All edges touching these files (incoming AND outgoing) are deleted.

referrerPaths: files whose symbols are unchanged but whose outgoing edges

may reference changed/removed nodes in stale files. Only their OUTGOING
edges are deleted and re-resolved; incoming edges are preserved.

All nodes referenced by the edges must already exist in the database.

func (*SQLiteStore) QueryAllNodes

func (s *SQLiteStore) QueryAllNodes(ctx context.Context) ([]Symbol, error)

QueryAllNodes returns all nodes from the graph store.

func (*SQLiteStore) QueryCallees

func (s *SQLiteStore) QueryCallees(ctx context.Context, qualifiedName string) ([]Symbol, error)

QueryCallees returns symbols that are called by the given qualified name.

func (*SQLiteStore) QueryCallers

func (s *SQLiteStore) QueryCallers(ctx context.Context, qualifiedName string) ([]Symbol, error)

QueryCallers returns symbols that call the given qualified name.

func (*SQLiteStore) Stats

func (s *SQLiteStore) Stats() GraphStats

Stats returns summary statistics about the graph.

type Store

type Store interface {
	// IndexFile stores all symbols and edges for a given file.
	// It replaces existing data for this file path (delete old nodes/edges, insert new).
	IndexFile(ctx context.Context, path string, symbols []Symbol, edges []Edge) error

	// InsertAllEdges inserts all call edges in a single transaction.
	// All nodes must already exist in the database (call IndexFile or
	// indexSymbolsOnly first). Deletes ALL existing edges first, then
	// inserts the new set — this is correct for a full rebuild via IndexAll.
	InsertAllEdges(ctx context.Context, edges []Edge) error

	// InsertEdgesForFiles deletes and re-inserts edges for a scoped set of files.
	// stalePaths: files whose symbols were re-indexed (delete incoming + outgoing).
	// referrerPaths: files whose symbols are unchanged (delete outgoing only).
	// Used by the incremental update path.
	InsertEdgesForFiles(ctx context.Context, stalePaths, referrerPaths []string, edges []Edge) error

	// FindReferrerFiles returns file paths whose nodes have edges pointing
	// to nodes in the given files. Used to compute the affected-file closure
	// during incremental updates.
	FindReferrerFiles(ctx context.Context, filePaths []string) ([]string, error)

	// QueryCallers returns symbols that call the given qualified name.
	QueryCallers(ctx context.Context, qualifiedName string) ([]Symbol, error)

	// QueryCallees returns symbols that are called by the given qualified name.
	QueryCallees(ctx context.Context, qualifiedName string) ([]Symbol, error)

	// FindDeadCode returns symbols with zero inbound call edges.
	// Excludes known entry points: main(), init(), exported functions, and test functions.
	// If directory is non-empty, restricts results to files under that directory prefix.
	FindDeadCode(ctx context.Context, directory string) ([]Symbol, error)

	// GetStaleFiles returns file paths whose mtime differs from the last indexed time.
	GetStaleFiles(ctx context.Context) ([]string, error)

	// Stats returns summary statistics about the graph.
	Stats() GraphStats

	// QueryAllNodes returns all nodes from the graph store.
	QueryAllNodes(ctx context.Context) ([]Symbol, error)

	// Close closes the underlying database.
	Close() error

	// BaseDir returns the git root directory for resolving relative file paths.
	BaseDir() string
}

Store defines the persistent graph store interface

type Symbol

type Symbol struct {
	ID            int64  // database node ID (populated by queries)
	QualifiedName string // e.g. "pkg/codegraph.Store.IndexFile"
	DisplayName   string // e.g. "IndexFile"
	FilePath      string // relative path from git root
	Line          int    // line where symbol is declared
	Kind          string // "func", "type", "var", "const", "iface", "method"
	Language      string // "go", "typescript", "javascript", "python"
	FileMTime     string // file modification time as RFC3339 string
}

Symbol represents a code symbol (function, type, variable, etc.)

Jump to

Keyboard shortcuts

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