graph

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 27 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	ConfExtracted = "EXTRACTED"
	ConfInferred  = "INFERRED"
)

Edge confidence tags. EXTRACTED edges come straight from syntax or a unique resolution; INFERRED edges rely on name matching and carry a score.

View Source
const (
	KindFile      = "file"
	KindFunc      = "func"
	KindMethod    = "method"
	KindType      = "type"
	KindClass     = "class"
	KindInterface = "interface"
	KindEnum      = "enum"
	KindTrait     = "trait"
)

Symbol node kinds.

View Source
const (
	EdgeCalls      = "calls"
	EdgeImports    = "imports"
	EdgeInherits   = "inherits"
	EdgeImplements = "implements"
)

Symbol edge kinds.

View Source
const (
	DefaultQueryBudget   = 2000
	DefaultExplainBudget = 1500
	DefaultImpactBudget  = 1500
)

Default hard token budgets per command.

View Source
const ConfExact = "EXACT"

ConfExact marks an edge confirmed by a compiler-grade index such as SCIP.

View Source
const DefaultPointerTokens = 120

DefaultPointerTokens caps a hook pointer; STACKLIT_HOOK_TOKENS overrides it.

View Source
const SchemaVersion = "1"

SchemaVersion is the version tag written into stacklit.graph.json.

Variables

This section is empty.

Functions

func ClampTokens added in v0.5.0

func ClampTokens(s string, budget int) string

ClampTokens is clampTokens for callers outside the package.

func DiscoverGoModules added in v0.5.0

func DiscoverGoModules(root string, files []string) map[string]string

DiscoverGoModules reads go.mod files next to the given Go sources.

func IsIdentifierQuery added in v0.5.0

func IsIdentifierQuery(q string) bool

IsIdentifierQuery reports whether q is a single code identifier (camelCase, snake_case, Type.Method, pkg::name, schema.table) rather than prose.

func LangOf added in v0.5.0

func LangOf(path string) string

LangOf returns the graph language for a path, or "" when unsupported.

func PatternIdent added in v0.5.0

func PatternIdent(p string) string

PatternIdent extracts the identifier a grep pattern is looking for, or "" when the pattern is prose, a real regex or too short to be worth a lookup.

func RenderHubs added in v0.5.0

func RenderHubs(hs []Hub, asJSON bool) string

RenderHubs prints hubs as text or JSON.

func StaleCheck added in v0.5.0

func StaleCheck(root string, g *SymGraph, fileTime time.Time) git.Staleness

StaleCheck compares a saved graph with the working tree. Only files the graph can index count as drift. fileTime (the graph file's mtime) is the fallback for graphs written before commits were recorded; zero skips it.

func StaleLine added in v0.5.0

func StaleLine(root string, g *SymGraph, fileTime time.Time) string

StaleLine is the one-line warning appended to query output, or "" when the graph is current, unstamped or STACKLIT_NO_STALE is set.

func Watch added in v0.5.0

func Watch(ctx context.Context, o WatchOptions) error

Watch builds the graph once, then rebuilds incrementally on source changes until ctx ends. Only changed files are re-parsed; linking is one linear pass.

Types

type BodyCache added in v0.5.0

type BodyCache map[string]map[string]string

BodyCache keeps computed body words per file, keyed by "line:name" within the file, so an incremental rebuild reads only the files that changed.

type BuildOptions

type BuildOptions struct {
	// MaxDepth is the maximum number of path segments a module name may have.
	// Deeper paths are collapsed to their ancestor. Defaults to 4 when 0.
	MaxDepth int
	// MaxModules caps how many modules are retained. 0 means no cap.
	MaxModules int
	// Root is the project directory. Optional; lets Rust workspace crate names
	// be read from Cargo.toml.
	Root string
	// SplitFiles splits a module holding more files than this into
	// subdirectory modules, as far down as needed. 0 disables splitting.
	SplitFiles int
}

BuildOptions configures the behaviour of Build.

type Community added in v0.5.0

type Community struct {
	ID    int      `json:"id"`
	Label string   `json:"label"`
	Files int      `json:"files"`
	Nodes int      `json:"nodes"`
	Top   []string `json:"top,omitempty"`
}

Community is a cluster of files found by label propagation.

type Def added in v0.5.0

type Def struct {
	Name    string
	Qual    string // Owner.Name for members, else Name
	Kind    string
	Line    int
	End     int    // last line of the definition body
	Doc     string // first sentence of the doc comment
	Sig     string
	Decl    bool     // prototype only; a definition elsewhere is preferred as a call target
	Vis     string   // public, private, protected, internal; empty when unknown
	Recv    string   // owning type for methods
	Methods []string // interface method names (Go structural matching)
}

Def is one symbol definition found in a file.

type Edge

type Edge struct {
	From  string
	To    string
	Count int // number of imports crossing this edge
}

Edge represents a dependency relationship between two modules.

type EdgeRef added in v0.5.0

type EdgeRef struct {
	From  string  `json:"from"`
	To    string  `json:"to"`
	Kind  string  `json:"kind"`
	Conf  string  `json:"conf"`
	Score float64 `json:"score"`
}

EdgeRef is the compact edge form used in command results.

type ExtractOptions added in v0.5.0

type ExtractOptions struct {
	// IncludeTests keeps test files in the graph; by default they are skipped.
	IncludeTests bool
	// MaxFileBytes skips files larger than this (default 1 MiB).
	MaxFileBytes int
	// MaxParseBytes is the largest file handed to tree-sitter. Larger files use
	// the line scanner where one exists, else contribute only their file node.
	// 0 reads STACKLIT_GRAPH_MAX_PARSE_BYTES, then the built-in default.
	MaxParseBytes int
	// ParseTimeout stops a single parse that runs away; such a file falls back like an oversize one.
	// 0 reads STACKLIT_GRAPH_PARSE_TIMEOUT_MS (default 3000).
	ParseTimeout time.Duration
	// MemoryBudget caps the estimated working set of concurrent tree-sitter
	// parses in bytes. 0 reads STACKLIT_PARSE_MEMORY_MB (default 512), negative disables the cap.
	MemoryBudget int64
}

ExtractOptions tunes extraction.

func OptionsFromEnv added in v0.5.0

func OptionsFromEnv() ExtractOptions

OptionsFromEnv returns extraction options read from the environment.

type FileGroup added in v0.5.0

type FileGroup struct {
	File    string    `json:"file"`
	Rank    int       `json:"rank,omitempty"`
	Score   float64   `json:"score,omitempty"`
	Symbols []SymLine `json:"symbols"`
}

FileGroup holds the shown symbols of one file.

type FileSyms added in v0.5.0

type FileSyms struct {
	Path    string
	Lang    string
	Pkg     string // Go package directory or Java package, for same-package lookup
	Defs    []Def
	Imports []Import
	Refs    []Ref
	// contains filtered or unexported fields
}

FileSyms is the extraction result for a single file.

func Extract added in v0.5.0

func Extract(root string, files []string, opts ExtractOptions) []*FileSyms

Extract reads and parses the given root-relative files in parallel. The result is sorted by path so the graph is deterministic.

func ExtractFile added in v0.5.0

func ExtractFile(path string, src []byte) *FileSyms

ExtractFile parses one file's content into symbols and references using the default size limits.

func ExtractPath added in v0.5.0

func ExtractPath(root, rel string, maxBytes int) *FileSyms

ExtractPath reads one root-relative file and extracts it; nil on any read problem.

type Graph

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

Graph holds the full dependency graph built from parsed files.

func Build

func Build(files []*parser.FileInfo, opts BuildOptions) *Graph

Build constructs a dependency Graph from a slice of parsed FileInfo.

func (*Graph) Edges

func (g *Graph) Edges() []Edge

Edges returns all edges sorted by (From, To).

func (*Graph) Entrypoints

func (g *Graph) Entrypoints() []string

Entrypoints returns file paths that were flagged as IsEntrypoint.

func (*Graph) Isolated

func (g *Graph) Isolated() []string

Isolated returns the names of modules that have no incoming and no outgoing dependency edges, sorted alphabetically.

func (*Graph) Module

func (g *Graph) Module(name string) *Module

Module returns a module by name, or nil if not found.

func (*Graph) Modules

func (g *Graph) Modules() []*Module

Modules returns all modules sorted by name.

func (*Graph) MostDepended

func (g *Graph) MostDepended() []string

MostDepended returns module names sorted by DependedBy count descending. Ties are broken alphabetically.

type HTMLGraph added in v0.5.0

type HTMLGraph struct {
	Files []string     `json:"files"`
	Kinds []string     `json:"kinds"`
	Comms []Community  `json:"comms"`
	Nodes []HTMLNode   `json:"nodes"`
	Edges [][5]float64 `json:"edges"`
	Total int          `json:"total"`
}

HTMLGraph is the symbol graph reduced for the interactive page. Edges are [from, to, kindIndex, score, inferred(0/1)] over indexes into Nodes.

type HTMLNode added in v0.5.0

type HTMLNode struct {
	Name string `json:"n"`
	Kind string `json:"k"`
	File int    `json:"f"`
	Line int    `json:"l"`
	End  int    `json:"e"`
	Comm int    `json:"c"`
	Sig  string `json:"s,omitempty"`
	Doc  string `json:"d,omitempty"`
}

HTMLNode is a symbol in the compact form embedded in stacklit.html.

type Hit added in v0.5.0

type Hit struct {
	Node  int
	Score float64
}

Hit is one ranked search result.

type Hop added in v0.5.0

type Hop struct {
	From    string  `json:"from"`
	To      string  `json:"to"`
	Kind    string  `json:"kind"`
	Forward bool    `json:"forward"`
	Conf    string  `json:"conf"`
	Score   float64 `json:"score"`
}

Hop is one step along a path; Forward is true when the edge points along the path.

type Hub added in v0.5.0

type Hub struct {
	Name      string  `json:"name"`
	Kind      string  `json:"kind"`
	Loc       string  `json:"loc"`
	In        int     `json:"in"`
	Out       int     `json:"out"`
	Rank      float64 `json:"rank"`
	Community string  `json:"community"`
}

Hub is a heavily connected symbol (a "god node").

type Import added in v0.5.0

type Import struct {
	Spec  string
	Alias string   // local name that qualifies uses, may be empty
	Names []string // directly imported names (JS named, Python from-import, Rust use)
}

Import is one import statement, kept as written; the resolver maps it to files.

type Module

type Module struct {
	Name      string
	FileCount int
	Files     []string // basenames of files in this module
	// FilesByRank lists the same basenames, most informative first (most
	// exports, then name). Callers that cap the listing keep a useful prefix.
	FilesByRank []string
	// ExportsByRank is Exports reordered so symbols from richer files come first.
	ExportsByRank   []string
	Exports         []string
	TypeDefs        map[string]string
	DependsOn       []string
	DependedBy      []string
	Languages       []string
	PrimaryLanguage string
	LineCount       int
	// contains filtered or unexported fields
}

Module represents a logical grouping of source files by directory.

type NodeRef added in v0.5.0

type NodeRef struct {
	Name      string `json:"name"`
	Kind      string `json:"kind"`
	Loc       string `json:"loc"`
	Community int    `json:"community"`
}

NodeRef is the compact node form used in command results.

type Order added in v0.5.0

type Order string

Order says how a view lists its files.

const (
	OrderRelevance Order = "relevance"
	OrderPath      Order = "path"
)

Query output orders. Relevance is the default: an agent reads top to bottom, so the best file must come first.

func DefaultOrder added in v0.5.0

func DefaultOrder() Order

DefaultOrder reads STACKLIT_QUERY_ORDER; anything unrecognised means relevance.

func ParseOrder added in v0.5.0

func ParseOrder(s string) (Order, error)

ParseOrder validates a --order value; empty means the environment default.

type PathResult added in v0.5.0

type PathResult struct {
	From    string  `json:"from"`
	To      string  `json:"to"`
	Found   bool    `json:"found"`
	Hops    []Hop   `json:"hops,omitempty"`
	Weakest float64 `json:"weakest,omitempty"`
	Note    string  `json:"note,omitempty"`
}

PathResult is the shortest path between two symbols.

func (*PathResult) Render added in v0.5.0

func (p *PathResult) Render(asJSON bool) string

Render prints the path as text or JSON.

type Ref added in v0.5.0

type Ref struct {
	From int
	Kind string // calls, inherits, implements
	Name string
	Qual string // receiver or namespace chain, "this" for own-type access
}

Ref is a use of a name inside a definition (From >= 0) or at file scope (From = -1).

type ResolveOptions added in v0.5.0

type ResolveOptions struct {
	// GoModules maps a Go module path to its root-relative directory.
	GoModules map[string]string
	// MaxCandidates caps how many same-name targets an ambiguous reference may fan out to.
	MaxCandidates int
}

ResolveOptions tunes cross-file resolution.

type Surprise added in v0.5.0

type Surprise struct {
	From     string  `json:"from"`
	To       string  `json:"to"`
	Kind     string  `json:"kind"`
	FromComm string  `json:"from_community"`
	ToComm   string  `json:"to_community"`
	Score    float64 `json:"score"`
	Conf     string  `json:"conf"`
}

Surprise is a cross-community link that is rare for its pair of communities.

type SymEdge added in v0.5.0

type SymEdge struct {
	From  int     `json:"f"`
	To    int     `json:"t"`
	Kind  string  `json:"k"`
	Conf  string  `json:"c"`
	Score float64 `json:"s"`
	Src   string  `json:"src,omitempty"` // adapter or index that produced the edge
}

SymEdge connects two nodes by index into SymGraph.Nodes.

type SymGraph added in v0.5.0

type SymGraph struct {
	Version     string      `json:"version"`
	Root        string      `json:"root,omitempty"`
	Nodes       []SymNode   `json:"nodes"`
	Edges       []SymEdge   `json:"edges"`
	Communities []Community `json:"communities,omitempty"`
	// Commit is the HEAD the graph was built at, so status and query can warn
	// when it has gone stale. No timestamp: the file stays reproducible.
	Commit string `json:"commit,omitempty"`
	// contains filtered or unexported fields
}

SymGraph is the symbol-level graph stored in stacklit.graph.json.

func BuildSymbols added in v0.5.0

func BuildSymbols(root string, files []string, eo ExtractOptions) *SymGraph

BuildSymbols extracts and resolves the given root-relative files into a graph.

func LinkSymbols added in v0.5.0

func LinkSymbols(root string, files []string, fs []*FileSyms, c BodyCache) *SymGraph

LinkSymbols resolves already extracted files into a graph. files is the full file list (for Go module discovery); fs must be sorted by path. Bodies come from c when it holds the file, so only changed files are re-read.

func Load added in v0.5.0

func Load(path string) (*SymGraph, error)

Load reads a graph file and indexes it.

func Resolve added in v0.5.0

func Resolve(files []*FileSyms, opts ResolveOptions) *SymGraph

Resolve turns per-file extraction results into a linked symbol graph. Every lookup goes through hash maps built once, so cost grows linearly with refs.

func (*SymGraph) AttachBodiesCached added in v0.5.0

func (g *SymGraph) AttachBodiesCached(root string, c BodyCache)

AttachBodiesCached is attachBodies that reuses and fills c. Callers drop a file's entry from c when the file changes. A nil c disables caching.

func (*SymGraph) ComputeCommunities added in v0.5.0

func (g *SymGraph) ComputeCommunities()

ComputeCommunities clusters files by deterministic weighted label propagation and stamps every node with its file's community. No randomness, no LLM.

func (*SymGraph) Explain added in v0.5.0

func (g *SymGraph) Explain(sym string, budget int, asJSON bool) (string, error)

Explain describes one symbol: where it is defined, its signature, callers and callees.

func (*SymGraph) Find added in v0.5.0

func (g *SymGraph) Find(q string) []int

Find resolves a user-supplied symbol or file reference to node indexes, best match first: exact ID, exact name, case-insensitive name, ID suffix, file path, substring.

func (*SymGraph) FitView added in v0.5.0

func (g *SymGraph) FitView(sp viewSpec, budget int, asJSON bool) string

FitView builds the largest prefix of ranked items whose rendering stays within budget tokens, then returns it. The result never exceeds budget: lowest-ranked items go first, and if even the head does not fit it is cut by bytes.

func (*SymGraph) HTMLData added in v0.5.0

func (g *SymGraph) HTMLData(maxNodes int) *HTMLGraph

HTMLData keeps the maxNodes most connected symbols so the page stays light.

func (*SymGraph) Hubs added in v0.5.0

func (g *SymGraph) Hubs(n int) []Hub

Hubs returns the top n symbols by total degree, ties by PageRank then path.

func (*SymGraph) Impact added in v0.5.0

func (g *SymGraph) Impact(target string, maxDepth, budget int, asJSON bool) (string, error)

Impact walks dependents of a symbol or file to estimate its blast radius. Reverse edges are followed to maxDepth; each node keeps its strongest path score.

func (*SymGraph) Index added in v0.5.0

func (g *SymGraph) Index()

Index builds adjacency lists and name lookups. It is safe to call twice.

func (*SymGraph) Label added in v0.5.0

func (g *SymGraph) Label(i int) string

Label is a short unambiguous display name for a node.

func (*SymGraph) Loc added in v0.5.0

func (g *SymGraph) Loc(i int) string

Loc is "file:line" for a node.

func (*SymGraph) PageRank added in v0.5.0

func (g *SymGraph) PageRank() []float64

PageRank scores nodes by how much weighted traffic reaches them along edges. Iteration order is fixed by node index, so results are identical between runs.

func (*SymGraph) Pointer added in v0.5.0

func (g *SymGraph) Pointer(ident string) string

Pointer answers "where is this identifier defined and who calls it" in one short line, or "" when the graph has no exact definition for it.

func (*SymGraph) Query added in v0.5.0

func (g *SymGraph) Query(q string, budget int, asJSON bool) string

Query returns a budgeted, file-grouped subgraph for a natural language question, in the order set by STACKLIT_QUERY_ORDER (relevance by default).

func (*SymGraph) QueryOrdered added in v0.5.0

func (g *SymGraph) QueryOrdered(q string, budget int, asJSON bool, order Order) string

QueryOrdered is Query with an explicit file order.

func (*SymGraph) RenderCommunities added in v0.5.0

func (g *SymGraph) RenderCommunities(asJSON bool) string

RenderCommunities prints the community list as text or JSON.

func (*SymGraph) Report added in v0.5.0

func (g *SymGraph) Report() string

Report renders a GRAPH_REPORT.md style overview. Output is deterministic.

func (*SymGraph) Save added in v0.5.0

func (g *SymGraph) Save(path string) error

Save writes the graph as compact JSON.

func (*SymGraph) Search added in v0.5.0

func (g *SymGraph) Search(q string, limit int) []Hit

Search ranks symbols for a question: BM25F over name, signature, doc, body and path, blended with PageRank, with identifier and quoted-phrase intents handled first. Order is deterministic.

func (*SymGraph) SearchFiles added in v0.5.0

func (g *SymGraph) SearchFiles(q string, limit int) []string

SearchFiles ranks files by their best symbols, for callers that want paths.

func (*SymGraph) ShortestPath added in v0.5.0

func (g *SymGraph) ShortestPath(a, b string) (*PathResult, error)

ShortestPath runs Dijkstra over both edge directions. Each hop costs 1 plus -ln(score), so a short path of confident edges beats a short path of guesses.

func (*SymGraph) Slice added in v0.5.0

func (g *SymGraph) Slice(root, sym string, budget int) (string, error)

Slice returns only the source lines of one symbol, with line numbers, so an agent never has to read the whole file. budget (tokens) is a hard cap.

func (*SymGraph) Stamp added in v0.5.0

func (g *SymGraph) Stamp(root string)

Stamp records the commit the graph was built at.

func (*SymGraph) Surprises added in v0.5.0

func (g *SymGraph) Surprises(n int) []Surprise

Surprises ranks cross-community symbol edges, favouring confident edges between community pairs that otherwise barely interact.

type SymLine added in v0.5.0

type SymLine struct {
	Name  string   `json:"name"`
	Kind  string   `json:"kind"`
	Start int      `json:"start"`
	End   int      `json:"end"`
	Sig   string   `json:"sig,omitempty"`
	Doc   string   `json:"doc,omitempty"`
	Tags  []string `json:"tags,omitempty"`
	Score float64  `json:"score,omitempty"`
}

SymLine is one symbol in a file-grouped view.

type SymNode added in v0.5.0

type SymNode struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	Kind string `json:"kind"`
	File string `json:"file"`
	Line int    `json:"line,omitempty"`
	End  int    `json:"end,omitempty"`
	Doc  string `json:"doc,omitempty"`
	Lang string `json:"lang,omitempty"`
	Sig  string `json:"sig,omitempty"`
	Vis  string `json:"vis,omitempty"`
	// Body holds a capped list of distinct body words used only for search.
	Body      string `json:"body,omitempty"`
	Community int    `json:"community"`
	Repo      string `json:"repo,omitempty"`   // set when graphs from several repos are merged
	Source    string `json:"source,omitempty"` // adapter or index that produced the node, empty for the built-in extractor
}

SymNode is a file or a symbol definition.

type View added in v0.5.0

type View struct {
	Title   string      `json:"title"`
	Head    []string    `json:"head,omitempty"`
	Files   []FileGroup `json:"files"`
	Total   int         `json:"total"`
	Shown   int         `json:"shown"`
	Omitted int         `json:"omitted,omitempty"`
	Notice  string      `json:"notice,omitempty"`
	// contains filtered or unexported fields
}

View is the compact, file-grouped result shared by query, explain and impact.

func (*View) JSON added in v0.5.0

func (v *View) JSON() string

JSON renders the view as indented JSON.

func (*View) Render added in v0.5.0

func (v *View) Render(asJSON bool) string

Render returns the view as text or JSON.

func (*View) Text added in v0.5.0

func (v *View) Text() string

Text renders the view as indented, file-grouped lines.

type WatchOptions added in v0.5.0

type WatchOptions struct {
	Root     string
	Out      string // graph file path, absolute or relative to Root
	Ignore   []string
	Debounce time.Duration
	// MaxWatches caps directory watches; above it Watch falls back to polling so
	// huge trees cannot exhaust inotify. 0 reads STACKLIT_WATCH_MAX (default 4096).
	MaxWatches   int
	PollInterval time.Duration // polling cadence, 0 reads STACKLIT_WATCH_POLL_MS (default 2000)
	ForcePoll    bool
	// Extract tunes parsing, including whether test files are tracked.
	Extract ExtractOptions
	Log     func(format string, args ...any)
}

WatchOptions configures Watch.

Jump to

Keyboard shortcuts

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