leda

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 7, 2026 License: MIT Imports: 13 Imported by: 0

README

leda

Leda is a linked-edge dependency analyzer that provides context isolation for LLM tools. Given a codebase and a natural-language prompt, it 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.

By deterministically tracing dependency paths rather than relying on vector similarity, leda avoids the irrelevant results common in typical RAG setups — delivering >70% reduction in token usage.

Install

go install github.com/jgabor/leda/cmd/leda@latest

Library usage

// Build a dependency graph from a project root.
g, err := leda.BuildGraph("./myproject",
    leda.WithExtensions("go", "ts"),
    leda.WithExclude("testdata"),
)

// Isolate the files relevant to a prompt.
ctx := g.IsolateContext("fix the auth middleware",
    leda.WithMaxFiles(20),
    leda.WithMaxTokens(8000),
    leda.WithSeedStrategy(leda.SeedSymbol),
)

// Get LLM-ready output.
output, err := ctx.FormatForLLM()

CLI

leda <command> [options]

Commands:
  build    Build and serialize a dependency graph
  query    Query the graph with a natural language prompt
  stats    Print graph statistics
  serve    Start MCP server (stdio)
Build a graph
leda build --root ./myproject --output .leda --lang go,ts
leda build --root ./myproject --dry-run              # preview files without writing
leda build --root ./myproject --format json           # machine-readable output
Query with a prompt
leda query --graph .leda "fix the auth middleware"
leda query --graph .leda --format llm --strategy symbol "database connection"
leda query --graph .leda --format json "auth"    # structured JSON output
Graph statistics
leda stats --graph .leda
leda stats --graph .leda --format json
MCP server
leda serve

Exposes leda_build_graph and leda_isolate_context as MCP tools over stdio.

All commands support --format json for agent-friendly output. The MCP server validates and canonicalizes all input paths.

Supported languages

All parsers use tree-sitter for accurate AST-based import and symbol extraction.

Language CLI alias Import resolution
Go go Go module + relative
TypeScript ts Relative
JavaScript js Relative
Python py Relative
Rust rs Relative
Java java Relative
C c Relative
C++ cpp Relative
Ruby rb Relative
PHP php Relative

New languages can be added by defining a langConfig in parser/languages.go with tree-sitter query patterns.

How it works

  1. Build: Walk the project tree, parse each file for symbols and imports, construct a directed graph where edges represent dependencies.
  2. Seed: Tokenize the prompt, split identifiers on camelCase/snake_case boundaries, and match against filenames, symbols, or paths to find entry-point nodes.
  3. Isolate: From seed nodes, traverse the graph (descendants for single seeds, shortest paths + descendants for multiple seeds) to collect the relevant subgraph.
  4. Budget: Optionally cap results by file count or estimated token count.

Acknowledgements

Leda is inspired by graph-oriented-generation.

License

MIT

Author

Jonathan Gabor (@jgabor)

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() (string, error)

FormatForLLM returns a structured prompt-ready string with file manifest + contents.

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
	Count int
}

FanOutEntry pairs a file with its edge count.

type Graph

type Graph struct {
	// 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)

AddEdge adds a directed edge from → to. Both nodes must exist.

func (*Graph) AddNode

func (g *Graph) AddNode(info NodeInfo)

AddNode adds a file node to the graph.

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.

type GraphStats

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

GraphStats summarizes a graph.

type NodeInfo

type NodeInfo struct {
	Path          string
	RelPath       string
	Extension     string
	Symbols       []string
	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 added in v0.2.0

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 WithCustomSeeder

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

WithCustomSeeder provides a custom seed function.

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 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 exported symbols.
	SeedSymbol
	// SeedPath matches against full relative paths.
	SeedPath
	// SeedCustom uses a user-provided seed function.
	SeedCustom
)

Directories

Path Synopsis
cmd
leda command
Command leda builds dependency graphs and isolates context for LLM tools.
Command leda builds dependency graphs and isolates context for LLM tools.
Package parser provides interfaces and implementations for extracting import dependencies and exported symbols from source files.
Package parser provides interfaces and implementations for extracting import dependencies and exported symbols from source files.
Package resolve turns raw import strings into absolute file paths.
Package resolve turns raw import strings into absolute file paths.

Jump to

Keyboard shortcuts

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