### Install Leda CLI Source: https://github.com/jgabor/leda/blob/main/README.md Installs the Leda command-line tool using the Go package manager. ```bash go install github.com/jgabor/leda/cmd/leda@latest ``` -------------------------------- ### Leda Agent System Prompt Integration Source: https://github.com/jgabor/leda/blob/main/README.md Provides an example markdown snippet to include in an agent's system prompt to inform it about the availability and usage of Leda. ```markdown ```markdown # Leda Leda is a tool for analyzing code dependencies, optimizing LLM agent interactions by reducing token usage and session costs. It builds dependency graphs and allows querying for specific code contexts. ## Install ```bash go install github.com/jgabor/leda/cmd/leda@latest ``` ## CLI ``` leda [options] Commands: build Build and serialize a dependency graph query Query the graph with a natural language prompt stats Print graph statistics extract Extract structured metadata from a source file version Print the leda version ``` ### Build a graph ```bash 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 leda build --root ./myproject --exclude '.openchamber,.worktrees' # skip worktree-style sub-trees that .gitignore doesn't cover ``` `--exclude` accepts a comma-separated list of glob patterns matched against both the relative path and the basename of each entry. Use it for any directory that contains duplicate copies of the project (vendored worktrees, agent-experiment outputs, dataset mirrors) when those dirs aren't already covered by `.gitignore` or leda's built-in `DefaultExclude` (`.git`, `node_modules`, `vendor`, `.next`, `__pycache__`, `.tox`, `dist`, `build`). ### Query with a prompt ```bash 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 leda query --graph .leda --context narrow "where is TokenEstimate set?" # symbol summaries ``` The `--context` flag selects per-file detail. `narrow` emits a symbol summary per file (cheap, best for narrow keyword-matchable questions); `wide` (default) emits full file contents (best for tracing). `medium` (skeletons) is reserved for a future release. ### Graph statistics ```bash leda stats --graph .leda # per-file fan-in/out leda stats --graph .leda --group-by directory # package-level rollup leda stats --graph .leda --format json ``` File-level output is the default; the trailing hint line in text mode suggests `--group-by directory` when you want the answer aggregated by parent directory (package). Intra-directory edges are excluded from the directory-level rollup so the counts reflect cross-package dependencies only. All commands support `--format json` for agent-friendly output. ## Agent usage Leda is built for LLM agents working in a shell. Benchmarks show agents using leda reduce exploration tool calls by 57% (median) and session cost by 27% (median) across 8 runs on 3 repos. **ALWAYS run `leda query` first for structural codebase questions.** One call replaces 5-10 grep/read rounds: ```bash leda query --root . "how does the auth middleware validate tokens?" ``` `leda query` auto-builds the graph if `.leda` doesn't exist. For large codebases or repeated queries, run `leda build --root .` once to cache it. **Routing rules:** 1. **Structural questions** ("trace how X works", "what files handle Y"): `leda query --root . ''` 2. **Dependency/centrality** ("most-depended-on files", "hot paths"): `leda stats --graph .leda`, then `--group-by directory` for package view 3. **Exact identifier lookups** ("where is X defined?"): `leda query --root . --strategy symbol --context narrow ''` Fall back to native Read/Glob/Grep only when the exact file is already known or when leda returns nothing useful. `--format json` yields structured output suitable for piping into other shell tooling or parsing inside an agent loop. ## Wiring leda into your agent Agents only use leda if their system prompt tells them it exists. Add the following to your project's `CLAUDE.md` or `AGENTS.md`: ````markdown ``` -------------------------------- ### Build, Get Stats, and Read Targeted Files with Leda Source: https://github.com/jgabor/leda/blob/main/BENCHMARKS.md This sequence of commands is used to build the Leda project, gather statistics, and then read specific documentation files for analysis. It represents a leaner approach compared to reading full files. ```bash leda build leda stats AGENTS.md VISION.md dir listings ``` -------------------------------- ### leda graph pollution from non-standard worktree dirs Source: https://github.com/jgabor/leda/blob/main/TODO.md Demonstrates the usage of the `leda build --exclude PATTERN` flag and `leda.WithExclude(patterns ...string)` library option to prevent graph pollution from non-standard directories. The example shows how excluding a directory like `.foo` correctly reduces the number of nodes and edges. ```go leda.WithExclude(patterns ...string) ``` ```bash leda build --root /tmp/excltest --exclude .foo ``` -------------------------------- ### Extract Codebase Facts with Leda CLI Source: https://context7.com/jgabor/leda/llms.txt Use `leda extract` to get structured metadata from a codebase in JSON format. This includes language detection, naming conventions, error patterns, testing setup, and tooling configuration. Specify the root directory and desired format. ```bash leda extract --root ./myproject --format json ``` -------------------------------- ### Build the project Source: https://github.com/jgabor/leda/blob/main/AGENTS.md Compiles the Leda command-line tool from the source code. ```bash go build ./cmd/leda ``` -------------------------------- ### Build Leda graph Source: https://github.com/jgabor/leda/blob/main/BENCHMARKS.md Initialize a Leda graph for a specific project root. ```bash leda build --root /home/jgabor/git/depdevs ``` ```bash leda build --root . ``` -------------------------------- ### Leda CLI Commands Overview Source: https://github.com/jgabor/leda/blob/main/README.md Lists the available commands for the Leda CLI tool, including build, query, stats, extract, and version. ```bash leda [options] Commands: build Build and serialize a dependency graph query Query the graph with a natural language prompt stats Print graph statistics extract Extract structured metadata from a source file version Print the leda version ``` -------------------------------- ### Leda Extract Command Source: https://context7.com/jgabor/leda/llms.txt Extracts structured metadata from a codebase, including language detection, naming conventions, layering, error patterns, testing setup, and tooling configuration. Outputs results in JSON format. ```APIDOC ## leda extract ### Description Extracts structured metadata from a codebase. ### Method CLI Command ### Endpoint N/A (CLI tool) ### Parameters #### Query Parameters - **--root** (string) - Required - The root directory of the project. - **--format** (string) - Optional - Output format, defaults to 'json'. - **--lang** (string) - Optional - Filter extraction for a specific language (e.g., 'go'). ### Request Example ```bash leda extract --root ./myproject --format json ``` ### Response #### Success Response (200) - **language** (string) - The primary language detected. - **languages_detected** (object) - Counts of detected languages. - **extractor** (string) - The name of the extractor used. - **file_count** (integer) - Total number of files. - **token_estimate** (integer) - Estimated number of tokens. - **naming** (object) - Analysis of naming conventions. - **layering** (object) - Information about code structure and dependencies. - **errors** (object) - Analysis of error patterns. - **testing** (object) - Details about the testing setup. - **tooling** (object) - Information about the project's tooling. #### Response Example (JSON) ```json { "language": "go", "languages_detected": {"go": 24, "typescript": 4}, "extractor": "leda", "file_count": 28, "token_estimate": 45000, "naming": { "files": {"snake_case": 18, "short_lowercase": 6}, "directories": {"short_lowercase": 8}, "exported_symbols": {"PascalCase": 45, "camelCase": 12} }, "layering": { "modules": 6, "edges": 45, "fan_in": [{"file": "internal/leda", "count": 18}], "fan_out": [{"file": "cmd/leda/main.go", "count": 15}] }, "errors": { "patterns": {"fmt_errorf_w": 23, "errors_new": 5}, "dominant_style": "fmt_errorf_w" }, "testing": { "framework": "stdlib", "test_file_count": 8, "test_naming": "Test_", "placement": "same_package", "helpers": ["testdata/"] }, "tooling": { "build": ["go build", "Makefile"], "lint": ["golangci-lint"], "format": ["gofmt"], "ci": ["github-actions"], "dependency_manifest": "go.mod" } } ``` ``` -------------------------------- ### JSON Output for Leda Stats Source: https://context7.com/jgabor/leda/llms.txt Use the `--format json` flag with `leda stats` to get programmatic output. This includes counts for nodes, edges, components, and detailed top fan-out/fan-in information. ```bash leda stats --graph .leda --format json ``` -------------------------------- ### Leda Build and Stats Command Sequence Source: https://github.com/jgabor/leda/blob/main/BENCHMARKS.md This sequence demonstrates the use of `leda build` followed by `leda stats` to gather performance data. It's part of a longer path for orientation prompts. ```bash leda build leda stats ``` -------------------------------- ### Implement Custom Import Resolver Source: https://context7.com/jgabor/leda/llms.txt Create custom resolvers for non-standard module systems by implementing the resolve.Resolver interface. Use resolve.Multi to chain custom logic with the default resolver. ```go package main import ( "path/filepath" "github.com/jgabor/leda/internal/leda" "github.com/jgabor/leda/internal/resolve" ) // AliasResolver resolves path aliases like @/components -> src/components type AliasResolver struct { aliases map[string]string } func (r *AliasResolver) Resolve(importPath, fromFile, rootDir string) ([]string, error) { for alias, replacement := range r.aliases { if len(importPath) >= len(alias) && importPath[:len(alias)] == alias { resolved := replacement + importPath[len(alias):] fullPath := filepath.Join(rootDir, resolved) // Try with common extensions for _, ext := range []string{".ts", ".tsx", ".js", ".jsx"} { candidate := fullPath + ext return []string{candidate}, nil } } } return nil, nil } func main() { // Chain custom resolver with defaults aliasResolver := &AliasResolver{ aliases: map[string]string{ "@/": "src/", "~/": "lib/", }, } extensions := []string{".ts", ".tsx", ".js", ".jsx"} defaultResolver := resolve.DefaultResolver("./project", extensions) chainedResolver := resolve.Multi(aliasResolver, defaultResolver) g, _ := leda.BuildGraph("./project", leda.WithResolver(chainedResolver)) _ = g } ``` -------------------------------- ### Build Dependency Graphs with leda build Source: https://context7.com/jgabor/leda/llms.txt Commands to parse source files and generate a directed dependency graph. Use these to initialize or update the project's graph representation. ```bash leda build --root ./myproject --output .leda ``` ```bash leda build --root ./myproject --lang go,ts ``` ```bash leda build --root ./myproject --dry-run ``` ```bash leda build --root ./myproject --exclude '.openchamber,.worktrees' ``` ```bash leda build --root ./myproject --format json ``` ```bash leda build --root ./myproject --no-gitignore ``` -------------------------------- ### Query Dependency Graph with Prompt Source: https://github.com/jgabor/leda/blob/main/README.md Queries the dependency graph using a natural language prompt to find relevant files. Supports various output formats and query strategies. ```bash leda query --graph .leda "fix the auth middleware" ``` ```bash leda query --graph .leda --format llm --strategy symbol "database connection" ``` ```bash leda query --graph .leda --format json "auth" # structured JSON output ``` ```bash leda query --graph .leda --context narrow "where is TokenEstimate set?" # symbol summaries ``` -------------------------------- ### Build and Query Leda Graph with Narrow Context Source: https://github.com/jgabor/leda/blob/main/BENCHMARKS.md Use this command to build the Leda project and then query its graph with a narrow context for error handling analysis. The `--context narrow` flag optimizes the query by providing per-file symbol summaries. ```bash leda build leda query --graph .leda 'error handling, error definitions, error wrapping, error logging' --context narrow ``` -------------------------------- ### Run Isolation Quality Harness Source: https://github.com/jgabor/leda/blob/main/BENCHMARKS.md Execute the isolation quality evaluation harness. This command wraps the Go test suite for assessing seed and file recall, and exclusion rates against a golden dataset. ```bash .optimera/harness ``` -------------------------------- ### Run empirical agent-read reduction benchmark Source: https://github.com/jgabor/leda/blob/main/BENCHMARKS.md Executes the benchmark script against a target repository, defaulting to a local path if not specified. ```bash bash scripts/benchmark.sh # default target: ~/git/lira TARGET_REPO=/path/to/any/repo bash scripts/benchmark.sh # any target codebase ``` -------------------------------- ### Leda Agent Routing Rules Source: https://github.com/jgabor/leda/blob/main/README.md Illustrates how to route different types of code analysis questions to the appropriate Leda commands for agents. ```bash leda query --root . '' ``` ```bash leda stats --graph .leda ``` ```bash leda query --root . --strategy symbol --context narrow '' ``` -------------------------------- ### Build Dependency Graph Source: https://github.com/jgabor/leda/blob/main/README.md Builds and serializes a dependency graph for a given project root. Supports specifying languages, dry runs, output formats, and exclusions. ```bash leda build --root ./myproject --output .leda --lang go,ts ``` ```bash leda build --root ./myproject --dry-run # preview files without writing ``` ```bash leda build --root ./myproject --format json # machine-readable output ``` ```bash leda build --root ./myproject --exclude '.openchamber,.worktrees' # skip worktree-style sub-trees that .gitignore doesn't cover ``` -------------------------------- ### Extend benchmark suite with new target Source: https://github.com/jgabor/leda/blob/main/BENCHMARKS.md Adds a new repository to the benchmark suite by setting the TARGET_REPO environment variable. ```bash TARGET_REPO=/path/to/next/target bash scripts/benchmark.sh ``` -------------------------------- ### Go Library: BuildGraph Source: https://context7.com/jgabor/leda/llms.txt Builds a dependency graph from a specified root directory using the Leda Go library. Supports various configuration options for customization. ```APIDOC ## leda.BuildGraph (Go Library) ### Description Builds a dependency graph from a root directory. Returns a Graph that can be queried, saved, and loaded. ### Method Go Function Call ### Endpoint N/A (Go library function) ### Parameters #### Path Parameters - **root** (string) - Required - The root directory of the project to analyze. #### Query Parameters - **options** ([]leda.BuildOption) - Optional - A variadic list of options to configure graph building. - **leda.WithExtensions(extensions ...string)** - Limit analysis to files with specified extensions. - **leda.WithExclude(excludes ...string)** - Exclude specified files or directories. - **leda.WithMaxDepth(depth int)** - Limit the directory depth for analysis. - **leda.WithGitIgnore(enabled bool)** - Respect .gitignore files (default is true). - **leda.WithParsers(registry *parser.Registry)** - Use a custom parser registry. ### Request Example ```go // Basic graph building g, err := leda.BuildGraph("./myproject") if err != nil { log.Fatal(err) } // With options g, err = leda.BuildGraph("./myproject", leda.WithExtensions(".go", ".ts"), leda.WithExclude(".openchamber", "vendor"), leda.WithMaxDepth(5), leda.WithGitIgnore(false), leda.WithParsers(parser.DefaultRegistry()), ) if err != nil { log.Fatal(err) } ``` ### Response #### Success Response (200) - **g** (*leda.Graph) - The constructed dependency graph. - **Duplicates** ([]leda.Duplicate) - List of duplicated subtrees found. - **Stats()** (*leda.Stats) - Method to get graph statistics (NodeCount, EdgeCount, Components). - **SaveToFile(path string)** (error) - Method to save the graph to a file. #### Response Example (Go struct) ```go // Example of accessing graph data stats := g.Stats() fmt.Printf("Nodes: %d, Edges: %d, Components: %d\n", stats.NodeCount, stats.EdgeCount, stats.Components) for _, dup := range g.Duplicates { fmt.Printf("Warning: %s duplicates %s (%d files)\n", dup.Path, dup.MatchPath, dup.FileCount) } ``` ``` -------------------------------- ### Run Calibration Tests Source: https://github.com/jgabor/leda/blob/main/TODO.md Executes calibration tests with specific build tags. ```bash go test -tags calibration ./internal/leda/... ``` -------------------------------- ### Package-level Aggregation with Leda CLI Source: https://context7.com/jgabor/leda/llms.txt Run Leda stats with `--group-by directory` for package-level aggregation, excluding intra-directory edges. The output provides node, edge, and component counts, along with top fan-out and fan-in directories. ```bash leda stats --graph .leda --group-by directory ``` -------------------------------- ### Build Dependency Graph with Leda Go API Source: https://context7.com/jgabor/leda/llms.txt The `leda.BuildGraph` function constructs a dependency graph from a specified root directory. It returns a `Graph` object that can be queried, saved, and loaded. Basic usage requires only the root path. ```go package main import ( "fmt" "log" "github.com/jgabor/leda/internal/leda" "github.com/jgabor/leda/internal/parser" ) func main() { // Basic graph building g, err := leda.BuildGraph("./myproject") if err != nil { log.Fatal(err) } // With options g, err = leda.BuildGraph("./myproject", leda.WithExtensions(".go", ".ts"), // Limit to specific extensions leda.WithExclude(".openchamber", "vendor"), // Additional excludes leda.WithMaxDepth(5), // Limit directory depth leda.WithGitIgnore(false), // Disable .gitignore respect leda.WithParsers(parser.DefaultRegistry()), // Custom parser registry ) if err != nil { log.Fatal(err) } // Check for duplicated subtrees (common with worktrees) for _, dup := range g.Duplicates { fmt.Printf("Warning: %s duplicates %s (%d files)\n", dup.Path, dup.MatchPath, dup.FileCount) } // Get statistics stats := g.Stats() fmt.Printf("Nodes: %d, Edges: %d, Components: %d\n", stats.NodeCount, stats.EdgeCount, stats.Components) // Save for later use if err := g.SaveToFile(".leda"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Leda Stats with Group-by Directory and Head Source: https://github.com/jgabor/leda/blob/main/BENCHMARKS.md This command sequence shows how to use `leda stats` to group by directory and then pipe the output to `head -30` to display the top 30 entries. This is part of the hot-paths prompt flow. ```bash leda stats --group-by directory | head -30 ``` -------------------------------- ### Analyze Graph Statistics with leda stats Source: https://context7.com/jgabor/leda/llms.txt Command to output structural metrics of the dependency graph, including fan-in and fan-out rankings. ```bash leda stats --graph .leda ``` -------------------------------- ### Verify Log Patterns with Grep Source: https://github.com/jgabor/leda/blob/main/BENCHMARKS.md This command is used to verify specific logging patterns within the project files after a Leda build and query operation. ```bash grep -r "slog\.|log\." ``` -------------------------------- ### Implement Custom Parser Interface Source: https://context7.com/jgabor/leda/llms.txt Define a custom parser by implementing the parser.Parser interface to support new languages or override default behavior. Use parser.NewRegistry to register the parser before passing it to BuildGraph. ```go package main import ( "github.com/jgabor/leda/internal/leda" "github.com/jgabor/leda/internal/model" "github.com/jgabor/leda/internal/parser" ) // CustomParser implements parser.Parser for a custom language type CustomParser struct{} func (p *CustomParser) Language() string { return "custom" } func (p *CustomParser) Extensions() []string { return []string{".cust"} } func (p *CustomParser) ParseImports(filePath string) ([]model.Import, error) { // Parse and return imports return []model.Import{ {Path: "./relative/import", Kind: model.ImportDefault}, {Path: "./types", Kind: model.ImportTypeOnly}, }, nil } func (p *CustomParser) ParseSymbols(filePath string) ([]model.Symbol, error) { // Parse and return symbols return []model.Symbol{ {Name: "MyFunction", Kind: model.SymbolFunction}, {Name: "MyType", Kind: model.SymbolType}, {Name: "MyInterface", Kind: model.SymbolInterface}, {Name: "MY_CONST", Kind: model.SymbolConstant}, {Name: "myVar", Kind: model.SymbolVariable}, }, nil } func main() { // Create registry with custom parser reg := parser.NewRegistry(&CustomParser{}) // Or extend default registry defaultReg := parser.DefaultRegistry() // Note: Can't add to existing registry, create new one with all parsers // Use with BuildGraph g, _ := leda.BuildGraph("./project", leda.WithParsers(reg)) _ = g } ``` -------------------------------- ### Query Dependency Graphs with leda query Source: https://context7.com/jgabor/leda/llms.txt Commands to perform natural language queries against a built graph to identify relevant files for LLM context. Supports various output formats and constraints. ```bash leda query --graph .leda "how does the auth middleware validate tokens?" ``` ```bash leda query --root ./myproject "fix the database connection" ``` ```bash leda query --graph .leda --context narrow "where is TokenEstimate set?" ``` ```bash leda query --graph .leda --strategy symbol --context narrow "cmdQuery" ``` ```bash leda query --graph .leda --format llm "error handling patterns" ``` ```bash leda query --graph .leda --format json "auth" ``` ```bash leda query --graph .leda --max-files 5 --max-tokens 10000 "database" ``` ```bash leda query --graph .leda --edge-weight "type=0.8" "handlers" ``` ```bash leda query --graph .leda --exclude "*_test.go,testdata/*" "main logic" ``` ```bash leda query --graph .leda --caller-depth 3 "low-level utility" ``` -------------------------------- ### StateMachine Package Source: https://github.com/jgabor/leda/blob/main/benchmarks/reference-sets/lira-orientation.txt Go code for the state machine package, enabling the definition and management of stateful logic. ```go package statemachine import ( "context" "fmt" "sync" "time" ) // Machine represents a state machine. type Machine struct { currentState string stopCh chan struct{} wg sync.WaitGroup } // NewMachine creates a new Machine instance. func NewMachine() *Machine { return &Machine{ currentState: "initial", stopCh: make(chan struct{}), } } // Start begins the operation of the state machine. func (m *Machine) Start(ctx context.Context) error { fmt.Println("State machine starting...") m.wg.Add(1) go func() { defer m.wg.Done() for { select { case <-ctx.Done(): fmt.Println("State machine context cancelled, stopping...") return case <-m.stopCh: fmt.Println("State machine stop signal received, stopping...") return default: // Handle state transitions and logic here fmt.Printf("State machine in state: %s\n", m.currentState) time.Sleep(4 * time.Second) } } }() return nil } // Stop gracefully shuts down the state machine. func (m *Machine) Stop(ctx context.Context) { fmt.Println("State machine stopping...") close(m.stopCh) m.wg.Wait() fmt.Println("State machine stopped.") } // TransitionTo changes the state of the machine. func (m *Machine) TransitionTo(newState string) { fmt.Printf("Transitioning from %s to %s\n", m.currentState, newState) m.currentState = newState } ``` -------------------------------- ### Update Leda CLI for Discoverability Source: https://github.com/jgabor/leda/blob/main/TODO.md This update consolidates the Leda CLI surface and enhances guidance in AGENTS.md/README.md. It also sharpens the value proposition of `leda query -h` to improve user discoverability and reduce Read counts. ```bash leda query -h ``` -------------------------------- ### Run project tests Source: https://github.com/jgabor/leda/blob/main/AGENTS.md Executes all tests in the project with the race detector enabled. ```bash go test ./... -race ``` -------------------------------- ### Query Codebase Dependencies Source: https://github.com/jgabor/leda/blob/main/AGENTS.md Use `leda query` for structural codebase questions. It automatically builds the graph if `.leda` is missing. This command replaces multiple grep/read operations. ```bash leda query --root . "how does the auth middleware validate tokens?" ``` -------------------------------- ### Analyze Dependency Statistics Source: https://github.com/jgabor/leda/blob/main/AGENTS.md Run `leda stats` to understand dependency and centrality within your codebase. Use `--group-by directory` for a package-level view. This helps identify critical paths and highly depended-upon files. ```bash leda stats --graph .leda ``` ```bash leda stats --graph .leda --group-by directory ``` -------------------------------- ### Execute Leda CLI Commands Source: https://github.com/jgabor/leda/blob/main/README.md Common commands for querying the codebase and generating statistics. ```bash leda query --root . "how does X work?" ``` ```bash leda stats --graph .leda ``` ```bash leda query --root . --strategy symbol --context narrow 'X' ``` -------------------------------- ### Run Claude with Leda Awareness Source: https://github.com/jgabor/leda/blob/main/BENCHMARKS.md Invoke the Claude agent with Leda awareness enabled. This involves using the --append-system-prompt flag to provide guidance to the agent regarding the Leda CLI. ```bash claude -p --append-system-prompt "guidance block pointing at the in-container leda CLI" ``` -------------------------------- ### Build Dependency Graph Source: https://github.com/jgabor/leda/blob/main/AGENTS.md Execute `leda build` to cache the dependency graph for large codebases or repeated queries. This is an optimization step; `leda query` will auto-build if the graph is missing. ```bash leda build --root . ``` -------------------------------- ### IsolateContext - Query Code Graph Source: https://context7.com/jgabor/leda/llms.txt Use IsolateContext to find relevant files for a prompt. Load an existing graph and query it with basic or advanced options like limiting results, setting seed strategies, and excluding files. ```go package main import ( "fmt" "log" "github.com/jgabor/leda/internal/leda" "github.com/jgabor/leda/internal/model" ) func main() { // Load existing graph g, err := leda.LoadFromFile(".leda") if err != nil { log.Fatal(err) } // Basic query ctx := g.IsolateContext("how does auth middleware work?") fmt.Printf("Found %d files, ~%d tokens\n", len(ctx.Files), ctx.TokenCount) for _, f := range ctx.Files { fmt.Println(f) } // With query options ctx = g.IsolateContext("database connection", leda.WithMaxFiles(10), // Limit result count leda.WithMaxTokens(50000), // Limit total tokens leda.WithSeedStrategy(leda.SeedSymbol), // Match against symbols leda.WithCallerDepth(2), // Include 2 levels of callers leda.WithQueryExclude("*_test.go"), // Exclude test files leda.WithEdgeWeights(map[model.ImportKind]float64{ model.ImportTypeOnly: 0.8, // Type-only imports weaker }), ) // Access seed nodes that matched fmt.Printf("Seeded from: %v\n", ctx.Seeds) // Get file contents concatenated contents, err := ctx.Contents() if err != nil { log.Fatal(err) } fmt.Println(contents) // Format for LLM with full file contents (wide) llmOutput, err := ctx.FormatForLLM(leda.ContextWide) if err != nil { log.Fatal(err) } fmt.Println(llmOutput) // Format for LLM with symbol summaries only (narrow - 25x cheaper) llmNarrow, err := ctx.FormatForLLM(leda.ContextNarrow) if err != nil { log.Fatal(err) } fmt.Println(llmNarrow) // Get narrow token estimate fmt.Printf("Narrow tokens: %d\n", ctx.NarrowTokenEstimate()) // Get symbol summary for a specific file summary := ctx.NarrowSummary(ctx.Files[0]) fmt.Printf("Functions: %v\n", summary.Functions) fmt.Printf("Types: %v\n", summary.Types) } ```