Help us shape the future of Go! Take the 2026 Go Developer Survey

search

package
v0.1.59 Latest Latest
Warning

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

Go to latest
Published: Aug 28, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package search provides zero-dependency code intelligence: symbol extraction (function/struct/class maps per file) and BM25 relevance search over file contents. Hand-rolled and dependency-free on purpose — these give the agent a structural map of the codebase without reading every file into context, and a relevance-ranked search that beats plain regex grep.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Cosine

func Cosine(a, b []float32) float64

Cosine returns the cosine similarity of two vectors (0 when either is empty), used to score how well a file matches the query semantically.

func FormatResults

func FormatResults(results []bm25Result, query string) string

FormatResults renders top search results with a snippet around the first query term match.

func FormatSymbolSummary

func FormatSymbolSummary(files []string) string

FormatSymbolSummary returns a compact symbol map string for a file list — the agent's "structure preview" of a file without reading its body.

func IsBinaryExt added in v0.1.1

func IsBinaryExt(ext string) bool

IsBinaryExt reports whether a file extension belongs to a binary or generated file.

func ReRank

func ReRank(ctx context.Context, root, query string, results []bm25Result, e *Embedder, limit int) []bm25Result

ReRank re-ranks BM25 results by embedding cosine similarity: the query and each candidate file are embedded (with a persistent per-file cache), and the top `limit` most similar files are returned. On any embedding failure (no endpoint, bad key, unsupported model) it returns the BM25 candidates untouched, truncated to limit — search_code never breaks because of it.

func ReRankDocs added in v0.1.1

func ReRankDocs(ctx context.Context, query string, results []bm25Result, e *Embedder, limit int) []bm25Result

ReRankDocs re-ranks in-memory BM25 results (e.g. project-memory facts) by embedding cosine similarity. Unlike ReRank — which persists a per-file embedding cache keyed by path — docs here are short texts embedded directly, so the candidate set must already be small (the caller limits it, typically top-8 from BM25). The query and each candidate are embedded in one batch; on ANY embedding failure it returns the BM25 order untouched — hybrid retrieval never breaks BM25-only operation.

Types

type BM25

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

BM25 indexes a set of documents and answers relevance queries.

func NewBM25

func NewBM25(docs []Document) *BM25

NewBM25 builds an index from documents.

func (*BM25) Search

func (b *BM25) Search(query string, n int) []bm25Result

Search ranks documents by BM25 relevance to the query, returning top n.

type BlastRadiusReport added in v0.1.32

type BlastRadiusReport struct {
	Target       string   `json:"target"`
	IsFile       bool     `json:"is_file"`
	Risk         string   `json:"risk"` // LOW, MEDIUM, HIGH, CRITICAL
	CallersCount int      `json:"callers_count"`
	Callers      []string `json:"callers,omitempty"`
	Importers    []string `json:"importers,omitempty"`
	Definitions  []string `json:"definitions,omitempty"`
}

BlastRadiusReport summarizes the ripple impact of changing a symbol or file.

func (*BlastRadiusReport) Format added in v0.1.32

func (r *BlastRadiusReport) Format() string

Format renders a clean, developer-friendly blast radius card.

type CallerLocation added in v0.1.16

type CallerLocation struct {
	File    string `json:"file"`
	Line    int    `json:"line"`
	Snippet string `json:"snippet"`
}

CallerLocation points to a call site in the workspace.

type ClusterGroup added in v0.1.16

type ClusterGroup struct {
	ID            int      `json:"cluster_id"`
	SuggestedFile string   `json:"suggested_file"`
	PrimaryTheme  string   `json:"primary_theme"`
	Symbols       []string `json:"symbols"`
	TotalLines    int      `json:"total_lines"`
	InternalCalls int      `json:"internal_calls"` // high = strong cohesion
	ExternalCalls int      `json:"external_calls"` // low = clean boundary
}

ClusterGroup represents a cohesive cluster of functions that belong together.

func ClusterFileSymbols added in v0.1.16

func ClusterFileSymbols(path string) ([]ClusterGroup, error)

ClusterFileSymbols performs modularity clustering on a monolithic file. It groups functions that call each other into self-contained modular candidates.

type DetailedSymbol added in v0.1.16

type DetailedSymbol struct {
	Name      string   `json:"name"`
	Kind      string   `json:"kind"` // "func", "method", "struct", "interface", "class", "type"
	StartLine int      `json:"start_line"`
	EndLine   int      `json:"end_line"`
	Lines     int      `json:"lines"`
	Receiver  string   `json:"receiver,omitempty"`
	Signature string   `json:"signature,omitempty"`
	Doc       string   `json:"doc,omitempty"`
	Calls     []string `json:"calls,omitempty"` // names of functions/methods called inside this symbol
}

DetailedSymbol represents a code symbol with exact start/end lines and call information.

func OutlineFile added in v0.1.16

func OutlineFile(path string) ([]DetailedSymbol, error)

OutlineFile extracts the structural symbol outline of a file without reading the full body into LLM context. Ideal for 1,000 to 20,000+ line files.

type Document

type Document struct {
	ID      string // file path
	Title   string // short name (basename)
	Body    string // full or partial content
	Snippet string // optional preview ("" = derive)
}

Document is a searchable item: a file with its content as the body.

func IndexDir

func IndexDir(dir string) ([]Document, error)

IndexDir builds a BM25 index over all text files under dir (skipping heavy dirs). Reading whole files into memory is bounded: skip files over 2MB.

type Embedder

type Embedder struct {
	BaseURL string
	APIKey  string
	Model   string
	// contains filtered or unexported fields
}

Embedder calls an OpenAI-compatible /embeddings endpoint — the same shape as OpenAI's text-embedding-3-small — so semantic re-ranking works with any compatible gateway the user configures. Nil-safe: when an Embedder is not wired, search_code stays BM25-only.

func NewEmbedder

func NewEmbedder(baseURL, apiKey, model string) *Embedder

NewEmbedder builds an embedder for an OpenAI-compatible base URL.

type GlobalIndex

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

GlobalIndex is a codebase-wide symbol + reference index built in the background to ensure instant (<50ms) startup time even on massive 50k+ file projects. All accessors are thread-safe and non-blocking.

func BuildGlobalIndex

func BuildGlobalIndex(root string) *GlobalIndex

BuildGlobalIndex spawns an asynchronous background worker pool to index the workspace without blocking the TUI startup, returning a live index immediately.

func (*GlobalIndex) AllSymbols

func (g *GlobalIndex) AllSymbols() map[string]map[string]bool

AllSymbols returns a map of file path -> set of defined symbols across the index.

func (*GlobalIndex) BlastRadius added in v0.1.32

func (g *GlobalIndex) BlastRadius(target string) *BlastRadiusReport

BlastRadius computes the blast radius of modifying a given symbol or file path.

func (*GlobalIndex) FileCount

func (g *GlobalIndex) FileCount() int

FileCount returns the number of indexed files (used by the tool's output header and /lsp-style status).

func (*GlobalIndex) Files

func (g *GlobalIndex) Files() []string

Files returns a copy of all indexed file paths.

func (*GlobalIndex) FormatLookup

func (g *GlobalIndex) FormatLookup(name string) string

FormatLookup renders a compact human-readable code_locate report.

func (*GlobalIndex) Importers

func (g *GlobalIndex) Importers(file string) []string

Importers returns the files whose import specifiers reference the given file (matched by the module name's last path segment, e.g. ConversationService.js is imported by files that `import ... from '.../ConversationService'`).

func (*GlobalIndex) IsReady added in v0.1.42

func (g *GlobalIndex) IsReady() bool

IsReady reports whether the initial background indexing pass has finished.

func (*GlobalIndex) Lookup

func (g *GlobalIndex) Lookup(name string) []IndexedSymbol

Lookup returns every indexed occurrence of a symbol name (definitions and declarations), sorted by file then line.

func (*GlobalIndex) Referencers

func (g *GlobalIndex) Referencers(name string) []string

Referencers returns the files that reference the symbol name (single quick pass over the indexed file list, capped), excluding its definition files.

func (*GlobalIndex) RefreshFile

func (g *GlobalIndex) RefreshFile(path string)

RefreshFile re-indexes a single changed file so the session-wide index stays current after edits — the index is no longer frozen at session start. Stale symbol entries for the file are dropped, then fresh symbols are indexed.

func (*GlobalIndex) ResolveSymbol

func (g *GlobalIndex) ResolveSymbol(name string) (string, bool)

ResolveSymbol returns the file that defines the given symbol using the instant symbol index, or "" when unknown.

func (*GlobalIndex) SymbolCount

func (g *GlobalIndex) SymbolCount() int

SymbolCount reports how many unique symbols the RAG index knows about.

func (*GlobalIndex) WaitReady added in v0.1.42

func (g *GlobalIndex) WaitReady(ctx context.Context)

WaitReady blocks until the initial background indexing pass completes or ctx is done.

type ImpactReport added in v0.1.16

type ImpactReport struct {
	Symbol      string           `json:"symbol"`
	File        string           `json:"file"`
	Kind        string           `json:"kind"`
	StartLine   int              `json:"start_line"`
	EndLine     int              `json:"end_line"`
	FanIn       int              `json:"fan_in"`       // count of callers
	FanOut      int              `json:"fan_out"`      // count of callees
	BlastRadius string           `json:"blast_radius"` // "LOW" | "MEDIUM" | "HIGH"
	Callers     []CallerLocation `json:"callers"`
	Callees     []string         `json:"callees"`
	Extraction  string           `json:"safe_extraction_order"`
}

ImpactReport details the blast radius of modifying a symbol.

func AnalyzeImpact added in v0.1.16

func AnalyzeImpact(rootPath, targetSymbol, targetFile string) (*ImpactReport, error)

AnalyzeImpact scans the workspace to compute the blast radius of a symbol.

type IndexedSymbol

type IndexedSymbol struct {
	Name string // symbol name
	Kind string // func / method / struct / class / interface / ...
	File string // absolute path
	Line int    // 1-based line
}

IndexedSymbol is one symbol occurrence: where a name is defined in the repo.

type ProjectContext

type ProjectContext struct {
	Root       string
	Tree       string // 2-level directory tree (names only)
	Docs       string // concatenated contents of AGENTS/CLAUDE/README (capped)
	EntryFiles []string
}

ProjectContext is a compact structural overview of the project plus any instruction docs, injected into the system prompt so the agent starts with orientation instead of blind grep/glob exploration.

func BuildProjectContext

func BuildProjectContext(root string) *ProjectContext

BuildProjectContext scans the working directory and produces the context. Shallow and fast: tree listing uses ReadDir one level at a time (no deep walk), docs are read with a size cap.

func (*ProjectContext) String

func (pc *ProjectContext) String() string

String renders the project context for injection into the system prompt. Kept compact: tree + entry files, docs only if present.

type SemanticCache

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

SemanticCache persists per-file embeddings under .brocode/index so repeated queries don't re-pay embedding cost for unchanged files.

func NewSemanticCache

func NewSemanticCache(root string) *SemanticCache

NewSemanticCache loads (or initializes) the cache file for root.

func (*SemanticCache) EmbedWithCache

func (c *SemanticCache) EmbedWithCache(ctx context.Context, e *Embedder, path string, maxBytes int) ([]float32, error)

EmbedWithCache returns the vector for path, embedding + caching on miss.

type SymbolItem

type SymbolItem struct {
	Name string // Symbol name (e.g. "EvaluateComplexity", "UserModel")
	Kind string // Kind (e.g. "func", "method", "struct", "class", "interface")
	Line int    // Line number in file
}

SymbolItem represents an extracted code symbol (function, struct, type, class, etc.).

func ExtractSymbols

func ExtractSymbols(path string) ([]SymbolItem, error)

ExtractSymbols parses a file and returns its structural symbols without reading the full file body into LLM context. Uses Go's native go/ast parser for Go files, and lightweight regex matching for other languages.

func SortedSymbols

func SortedSymbols(syms []SymbolItem) []SymbolItem

SortedSymbols returns symbols ordered by line.

type SymbolRAG

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

SymbolRAG provides instant (<1ms) local zero-dependency symbol resolution using an interned path table to minimize memory overhead across massive codebases.

func NewSymbolRAG

func NewSymbolRAG() *SymbolRAG

NewSymbolRAG creates a new local symbol RAG index.

func (*SymbolRAG) IndexSymbol

func (sr *SymbolRAG) IndexSymbol(symbol, filePath string)

IndexSymbol records a symbol mapping with interned path storage.

func (*SymbolRAG) RemoveFile

func (sr *SymbolRAG) RemoveFile(filePath string)

RemoveFile drops every symbol pointing at the given file.

func (*SymbolRAG) Resolve

func (sr *SymbolRAG) Resolve(symbol string) (string, bool)

Resolve looks up exact symbol matches.

Jump to

Keyboard shortcuts

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