leda

package
v0.7.2 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package leda provides dependency-graph context isolation for LLM tools. Given a codebase and a natural-language prompt, leda builds a directed dependency graph from source files, seeds entry points from the prompt, and traverses the graph to return only the files the LLM actually needs.

Index

Constants

This section is empty.

Variables

View Source
var DefaultExclude = []string{
	".git", "node_modules", "vendor", ".next",
	"__pycache__", ".tox", "dist", "build",
}

DefaultExclude contains directory names skipped by default during graph building.

Functions

This section is empty.

Types

type Context

type Context struct {
	Files      []string // absolute paths of isolated files
	Seeds      []string // which nodes were entry points
	TokenCount int      // estimated token count
	TraceGraph *Graph   // subgraph showing only the traversed portion
}

Context is the result of IsolateContext.

func (*Context) Contents

func (c *Context) Contents() (string, error)

Contents reads and concatenates all isolated files with filepath headers.

func (*Context) ContentsWithBudget

func (c *Context) ContentsWithBudget(maxTokens int) (string, error)

ContentsWithBudget is like Contents but stops at approximately maxTokens. A maxTokens of 0 means no limit.

func (*Context) FormatForLLM

func (c *Context) FormatForLLM(depth ContextDepth) (string, error)

FormatForLLM returns a structured prompt-ready string. At ContextWide depth it emits the full file contents (the default); at ContextNarrow depth it emits a per-file symbol summary instead.

func (*Context) NarrowSummary added in v0.5.0

func (c *Context) NarrowSummary(path string) NarrowSummary

NarrowSummary returns a per-file symbol summary for the given absolute path, drawn from the trace subgraph. Used by CLI formatters to render narrow-tier output without exposing internal graph state.

func (*Context) NarrowTokenEstimate added in v0.5.0

func (c *Context) NarrowTokenEstimate() int

NarrowTokenEstimate returns a rough token estimate for the narrow-tier emission of this context. Computed from the trace subgraph's symbol counts rather than file contents, it reflects what an agent actually pays for narrow output -- unlike TokenCount, which always reflects the wide-mode file-content estimate used for budget enforcement. Used by all three narrow output formats (files, json, llm); scaffolding differences between them are within rounding error and the body cost dominates.

type ContextDepth added in v0.5.0

type ContextDepth int

ContextDepth selects how much per-file detail formatted output should carry.

const (
	// ContextWide emits full file contents — the default, most expensive tier.
	ContextWide ContextDepth = iota
	// ContextNarrow emits a per-file symbol summary instead of file contents,
	// for narrow keyword-matchable questions where the agent only needs the
	// shape of each file, not its bodies.
	ContextNarrow
)

type DuplicateWarning added in v0.5.0

type DuplicateWarning struct {
	Path      string // relative path of the duplicate sub-tree
	MatchPath string // relative path of the original it matches
	FileCount int    // number of graph nodes inside the duplicate
}

DuplicateWarning identifies a directory sub-tree that appears to be a structural copy of another sub-tree in the graph.

type Edge

type Edge struct {
	From string
	To   string
}

Edge represents a directed dependency from one file to another.

type FanOutEntry

type FanOutEntry struct {
	File  string `json:"file"`
	Count int    `json:"count"`
}

FanOutEntry pairs a file with its edge count.

func TopNFromMap added in v0.6.0

func TopNFromMap(counts map[string]int, n int) []FanOutEntry

type Graph

type Graph struct {
	Duplicates []DuplicateWarning
	// contains filtered or unexported fields
}

Graph is a directed dependency graph of source files.

func BuildGraph

func BuildGraph(rootDir string, opts ...Option) (*Graph, error)

BuildGraph walks rootDir, parses all recognized source files, and returns a dependency graph.

func Load

func Load(r io.Reader) (*Graph, error)

Load deserializes a graph from a reader.

func LoadFromFile

func LoadFromFile(path string) (*Graph, error)

LoadFromFile is a convenience that loads a graph from a file.

func (*Graph) AddEdge

func (g *Graph) AddEdge(from, to string, kinds ...model.ImportKind)

AddEdge adds a directed edge from → to with the given import kind. Both nodes must exist.

func (*Graph) AddNode

func (g *Graph) AddNode(info NodeInfo)

AddNode adds a file node to the graph.

func (*Graph) EdgeKind added in v0.5.0

func (g *Graph) EdgeKind(from, to string) model.ImportKind

EdgeKind returns the import kind for an edge, defaulting to ImportDefault.

func (*Graph) Edges

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

Edges returns all directed edges.

func (*Graph) IsolateContext

func (g *Graph) IsolateContext(prompt string, opts ...QueryOption) *Context

IsolateContext returns the minimal set of files relevant to the prompt.

func (*Graph) NodeInfos

func (g *Graph) NodeInfos() []NodeInfo

NodeInfos returns metadata for all nodes.

func (*Graph) Nodes

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

Nodes returns all file paths in the graph, sorted.

func (*Graph) RootDir

func (g *Graph) RootDir() string

RootDir returns the root directory the graph was built from.

func (*Graph) Save

func (g *Graph) Save(w io.Writer) error

Save serializes the graph to a writer in gob format.

func (*Graph) SaveToFile

func (g *Graph) SaveToFile(path string) error

SaveToFile is a convenience that saves the graph to a file.

func (*Graph) Stats

func (g *Graph) Stats() GraphStats

Stats returns summary statistics about the graph.

func (*Graph) StatsByDirectory added in v0.5.0

func (g *Graph) StatsByDirectory() GraphStats

StatsByDirectory returns summary statistics with fan-in/fan-out rolled up by parent directory. Intra-directory edges are excluded so the counts reflect cross-package dependencies only. FanOutEntry.File carries the directory path in the returned stats.

type GraphStats

type GraphStats struct {
	NodeCount  int
	EdgeCount  int
	Components int
	TopFanOut  []FanOutEntry
	TopFanIn   []FanOutEntry
}

GraphStats summarizes a graph.

type NarrowSummary added in v0.5.0

type NarrowSummary struct {
	Functions  []string
	Types      []string
	Interfaces []string
	Constants  []string
	Variables  []string
}

NarrowSummary groups a file's symbols by kind for narrow-tier output.

func (NarrowSummary) Empty added in v0.5.0

func (s NarrowSummary) Empty() bool

Empty reports whether the summary has no symbols of any kind.

type NodeInfo

type NodeInfo struct {
	Path          string
	RelPath       string
	Extension     string
	Symbols       []model.Symbol
	Size          int64
	TokenEstimate int
}

NodeInfo holds metadata about a file node in the graph.

type Option

type Option func(*buildConfig)

Option configures graph building.

func WithExclude

func WithExclude(patterns ...string) Option

WithExclude adds glob patterns to exclude from graph building.

func WithExtensions

func WithExtensions(exts ...string) Option

WithExtensions limits parsing to these file extensions.

func WithGitIgnore

func WithGitIgnore(enabled bool) Option

WithGitIgnore controls whether .gitignore files are respected during graph building. Enabled by default.

func WithMaxDepth

func WithMaxDepth(depth int) Option

WithMaxDepth limits directory recursion depth.

func WithParsers

func WithParsers(registry *parser.Registry) Option

WithParsers overrides the default parser registry.

func WithResolver

func WithResolver(r resolve.Resolver) Option

WithResolver overrides the default import resolver.

type QueryOption

type QueryOption func(*queryConfig)

QueryOption configures context isolation.

func WithCallerDepth added in v0.5.0

func WithCallerDepth(depth int) QueryOption

WithCallerDepth sets how many levels of callers (ancestors) to include for each seed. Default is 1 (direct callers only).

func WithCustomSeeder

func WithCustomSeeder(fn func(prompt string, nodes []NodeInfo) []string) QueryOption

WithCustomSeeder provides a custom seed function.

func WithEdgeWeights added in v0.5.0

func WithEdgeWeights(weights map[model.ImportKind]float64) QueryOption

WithEdgeWeights sets weights for edge kinds during traversal. Weight must be in (0,1]; lower weight means the edge is a weaker connection (higher effective depth). Defaults: ImportDefault=1.0, ImportTypeOnly=0.6.

func WithMaxFiles

func WithMaxFiles(n int) QueryOption

WithMaxFiles caps the result set to n files.

func WithMaxTokens

func WithMaxTokens(n int) QueryOption

WithMaxTokens caps estimated tokens in the result.

func WithQueryExclude added in v0.4.2

func WithQueryExclude(patterns ...string) QueryOption

WithQueryExclude filters files matching the given patterns from query results.

func WithSeedStrategy

func WithSeedStrategy(s SeedStrategy) QueryOption

WithSeedStrategy sets the strategy for mapping prompt terms to graph nodes.

type SeedStrategy

type SeedStrategy int

SeedStrategy controls how prompt terms map to graph nodes.

const (
	// SeedFilename matches prompt words against file basenames.
	SeedFilename SeedStrategy = iota
	// SeedSymbol matches against top-level symbols (functions, methods, types,
	// consts, vars — including package-private ones for languages that capture
	// them, like Go).
	SeedSymbol
	// SeedPath matches against full relative paths.
	SeedPath
	// SeedCombined runs all strategies and merges results.
	SeedCombined
	// SeedCustom uses a user-provided seed function.
	SeedCustom
)

Jump to

Keyboard shortcuts

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