explore

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 11, 2026 License: AGPL-3.0 Imports: 23 Imported by: 0

Documentation

Overview

Package explore provides high-level exploration tools for code analysis.

These tools compose lower-level graph queries to answer complex questions about codebases, such as finding entry points, tracing data flow, and building minimal context for understanding functions.

Thread Safety:

All tools in this package are designed for concurrent use. They perform
read-only operations on the graph and index.

Index

Constants

View Source
const (
	// DefaultCacheSize is the default maximum number of entries per cache type.
	DefaultCacheSize = 100

	// DefaultCacheTTL is the default time-to-live for cache entries.
	DefaultCacheTTL = 5 * time.Minute
)

Default cache configuration.

View Source
const (
	// DefaultNumHashes is the default number of MinHash signatures.
	DefaultNumHashes = 128

	// DefaultShingleSize is the default size of shingles for MinHash.
	DefaultShingleSize = 3
)

Default configuration for fingerprinting.

View Source
const (
	// DefaultTokenBudget is the default maximum token budget.
	DefaultTokenBudget = 4000

	// DefaultMaxCallees is the default maximum number of key callees to include.
	DefaultMaxCallees = 5

	// DefaultMaxTypes is the default maximum number of types to include.
	DefaultMaxTypes = 10

	// DefaultMaxInterfaces is the default maximum number of interfaces to include.
	DefaultMaxInterfaces = 3
)

Default configuration for minimal context.

View Source
const (
	// DefaultSimilarityLimit is the default number of similar results to return.
	DefaultSimilarityLimit = 10

	// DefaultLSHBands is the default number of LSH bands.
	DefaultLSHBands = 16

	// DefaultLSHBandSize is the default size of each LSH band.
	DefaultLSHBandSize = 8

	// MinSimilarityThreshold is the minimum similarity score to include in results.
	MinSimilarityThreshold = 0.3
)

Default configuration for similarity search.

View Source
const DefaultEmbeddingTimeout = 30 * time.Second

DefaultEmbeddingTimeout is the default timeout for embedding requests.

View Source
const (
	// DefaultEntryPointLimit is the default maximum number of entry points to return.
	DefaultEntryPointLimit = 100
)

Default configuration for entry point finding.

Variables

View Source
var (
	// ErrSymbolNotFound indicates the requested symbol was not found.
	ErrSymbolNotFound = errors.New("symbol not found")

	// ErrFileNotFound indicates the requested file was not found.
	ErrFileNotFound = errors.New("file not found")

	// ErrPackageNotFound indicates the requested package was not found.
	ErrPackageNotFound = errors.New("package not found")

	// ErrInvalidInput indicates invalid input was provided.
	ErrInvalidInput = errors.New("invalid input")

	// ErrTraversalLimitReached indicates traversal exceeded configured limits.
	ErrTraversalLimitReached = errors.New("traversal limit reached")

	// ErrTokenBudgetExceeded indicates the token budget was exceeded.
	ErrTokenBudgetExceeded = errors.New("token budget exceeded")

	// ErrGraphNotReady indicates the graph is not ready for queries.
	ErrGraphNotReady = errors.New("graph not ready")

	// ErrContextCanceled indicates the operation was canceled.
	ErrContextCanceled = errors.New("context canceled")

	// ErrUnsupportedLanguage indicates the language is not supported.
	ErrUnsupportedLanguage = errors.New("unsupported language")

	// ErrNoEntryPoints indicates no entry points were found.
	ErrNoEntryPoints = errors.New("no entry points found")

	// ErrCacheMiss indicates the requested data is not in cache.
	ErrCacheMiss = errors.New("cache miss")
)

Sentinel errors for the explore package.

Functions

func ComputeSimilarity

func ComputeSimilarity(a, b *ASTFingerprint) (float64, []string)

ComputeSimilarity computes the similarity between two fingerprints.

Description:

Computes overall similarity using both MinHash (if available) and
direct feature comparison. Returns a score from 0.0 to 1.0.

Inputs:

a, b - The fingerprints to compare.

Outputs:

float64 - Similarity score (0.0 to 1.0).
[]string - List of matched traits explaining similarity.

func CosineSimilarity

func CosineSimilarity(a, b []float32) float64

CosineSimilarity computes the cosine similarity between two vectors.

Description

Computes the cosine of the angle between two vectors, which is a common similarity metric for embeddings. Returns a value between -1 (opposite) and 1 (identical).

Inputs

  • a, b: The vectors to compare. Must have the same length.

Outputs

  • float64: The cosine similarity score.

Performance

O(n) where n is the vector dimension. Typical: < 1μs for 768-dim vectors.

func EstimateTokens

func EstimateTokens(code string) int

EstimateTokens estimates the token count for a piece of code.

Description:

Provides a rough estimate of OpenAI/Anthropic token count based on
character count. Actual token count varies by model and content.

Inputs:

code - The code string to estimate.

Outputs:

int - Estimated token count.

func EstimateTokensForSymbol

func EstimateTokensForSymbol(sym *ast.Symbol) int

EstimateTokensForSymbol estimates tokens for a symbol.

func JaccardSimilarity

func JaccardSimilarity(a, b []uint64) float64

JaccardSimilarity computes the estimated Jaccard similarity from MinHash signatures.

Description:

Estimates the Jaccard similarity (intersection/union) of two sets from
their MinHash signatures. Accuracy improves with more hash functions.

Inputs:

a, b - MinHash signatures (must be same length).

Outputs:

float64 - Estimated Jaccard similarity (0.0 to 1.0).

Example:

sim := JaccardSimilarity(sig1, sig2)
if sim > 0.8 {
    fmt.Println("Very similar!")
}

func MinHashSignature

func MinHashSignature(set []string, numHashes int) []uint64

MinHashSignature computes the MinHash signature for a set of strings.

Description:

Computes a locality-sensitive hash that can be used for efficient
similarity estimation. Similar sets will have similar MinHash signatures.

Inputs:

set - The set of strings to hash.
numHashes - The number of hash functions to use.

Outputs:

[]uint64 - The MinHash signature (length = numHashes).

Example:

sig := MinHashSignature([]string{"a", "b", "c"}, 128)

func SimilarityThreshold

func SimilarityThreshold(numBands, bandSize int) float64

SimilarityThreshold estimates the similarity threshold for given LSH parameters.

Description:

Returns the approximate similarity threshold where items have ~50%
probability of being candidates using the given LSH parameters.

Inputs:

numBands - Number of hash bands.
bandSize - Size of each band.

Outputs:

float64 - Approximate similarity threshold.

Types

type APISymbol

type APISymbol struct {
	// Name is the symbol name.
	Name string `json:"name"`

	// Signature is the symbol signature.
	Signature string `json:"signature"`

	// DocString is the documentation comment.
	DocString string `json:"doc_string,omitempty"`
}

APISymbol represents a public API symbol.

type ASTFingerprint

type ASTFingerprint struct {
	// SymbolID is the unique symbol identifier.
	SymbolID string `json:"symbol_id"`

	// NodeTypes is the sequence of AST node types.
	NodeTypes []string `json:"node_types"`

	// ControlFlow is the abstracted control flow pattern.
	ControlFlow string `json:"control_flow"`

	// CallPattern lists called function signatures (abstracted).
	CallPattern []string `json:"call_pattern"`

	// ParamCount is the number of parameters.
	ParamCount int `json:"param_count"`

	// ReturnCount is the number of return values.
	ReturnCount int `json:"return_count"`

	// Complexity is the cyclomatic complexity.
	Complexity int `json:"complexity"`

	// MinHash is the locality-sensitive hash for O(1) similarity lookup.
	MinHash []uint64 `json:"min_hash,omitempty"`
}

ASTFingerprint enables O(n log n) structural similarity via LSH.

func ComputeFingerprintFromSignature

func ComputeFingerprintFromSignature(signature string, kind ast.SymbolKind, language string) *ASTFingerprint

ComputeFingerprintFromSignature creates a fingerprint from just a signature.

Description:

Creates a fingerprint without needing a full symbol, useful for
comparing against signatures extracted from code.

Inputs:

signature - The function signature string.
kind - The symbol kind (function, method, etc.).
language - The programming language.

Outputs:

*ASTFingerprint - The computed fingerprint.

type CacheConfig

type CacheConfig struct {
	// MaxSize is the maximum number of entries per cache type.
	MaxSize int

	// TTL is the time-to-live for cache entries.
	TTL time.Duration
}

CacheConfig configures the exploration cache.

func DefaultCacheConfig

func DefaultCacheConfig() CacheConfig

DefaultCacheConfig returns sensible defaults.

type CacheStats

type CacheStats struct {
	EntryPointCount  int
	FileSummaryCount int
	PackageAPICount  int
	Hits             int64
	Misses           int64
	HitRate          float64
	MaxSize          int
	TTLSeconds       int64
}

CacheStats returns cache statistics.

type CachedEntryPointFinder

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

CachedEntryPointFinder wraps EntryPointFinder with caching.

func NewCachedEntryPointFinder

func NewCachedEntryPointFinder(finder *EntryPointFinder, cache *ExplorationCache) *CachedEntryPointFinder

NewCachedEntryPointFinder creates a cached entry point finder.

func (*CachedEntryPointFinder) FindEntryPoints

FindEntryPoints finds entry points with caching.

type CachedFileSummarizer

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

CachedFileSummarizer wraps FileSummarizer with caching.

func NewCachedFileSummarizer

func NewCachedFileSummarizer(summarizer *FileSummarizer, cache *ExplorationCache) *CachedFileSummarizer

NewCachedFileSummarizer creates a cached file summarizer.

func (*CachedFileSummarizer) SummarizeFile

func (s *CachedFileSummarizer) SummarizeFile(ctx context.Context, filePath string) (*FileSummary, error)

SummarizeFile summarizes a file with caching.

type CachedPackageAPISummarizer

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

CachedPackageAPISummarizer wraps PackageAPISummarizer with caching.

func NewCachedPackageAPISummarizer

func NewCachedPackageAPISummarizer(summarizer *PackageAPISummarizer, cache *ExplorationCache) *CachedPackageAPISummarizer

NewCachedPackageAPISummarizer creates a cached package API summarizer.

func (*CachedPackageAPISummarizer) FindPackageAPI

func (s *CachedPackageAPISummarizer) FindPackageAPI(ctx context.Context, packagePath string) (*PackageAPI, error)

FindPackageAPI finds the package API with caching.

type CodeBlock

type CodeBlock struct {
	// ID is the symbol ID.
	ID string `json:"id"`

	// Name is the symbol name.
	Name string `json:"name"`

	// Kind is the symbol kind (function, struct, interface, etc.).
	Kind string `json:"kind"`

	// FilePath is the relative path to the file.
	FilePath string `json:"file_path"`

	// StartLine is the 1-indexed starting line.
	StartLine int `json:"start_line"`

	// EndLine is the 1-indexed ending line.
	EndLine int `json:"end_line"`

	// Signature is the symbol signature.
	Signature string `json:"signature,omitempty"`

	// Code is the actual code content.
	Code string `json:"code,omitempty"`

	// TokenEstimate is an estimated token count for the code.
	TokenEstimate int `json:"token_estimate,omitempty"`
}

CodeBlock represents a code snippet with context.

type ConfigFinder

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

ConfigFinder finds configuration usage in code.

Thread Safety:

ConfigFinder is safe for concurrent use. It performs read-only
operations on the graph and index.

func NewConfigFinder

func NewConfigFinder(g *graph.Graph, idx *index.SymbolIndex) *ConfigFinder

NewConfigFinder creates a new ConfigFinder.

Description:

Creates a finder that can identify configuration access points
in code, tracking where configuration values are read.

Inputs:

g - The code graph. Must be frozen.
idx - The symbol index.

Outputs:

*ConfigFinder - The configured finder.

Example:

finder := NewConfigFinder(graph, index)
usage, err := finder.FindConfigUsage(ctx, "DATABASE_URL")

func (*ConfigFinder) DiscoverConfigs

func (f *ConfigFinder) DiscoverConfigs(ctx context.Context) (*ConfigUsage, error)

DiscoverConfigs finds all configuration access points in the codebase.

Description:

Scans the entire codebase and returns all configuration access points,
including environment variables, config file reads, and flag definitions.
This is useful for discovery queries where the user doesn't know what
configs exist.

Inputs:

ctx - Context for cancellation.

Outputs:

*ConfigUsage - All discovered configuration access points.
error - Non-nil if the operation was canceled.

Performance:

Target latency: < 2s for typical codebases.

Thread Safety:

This method is safe for concurrent use.

func (*ConfigFinder) FindAllConfigAccess

func (f *ConfigFinder) FindAllConfigAccess(ctx context.Context, filePath string) ([]ConfigUse, error)

FindAllConfigAccess finds all configuration access points in a file.

Description:

Scans all symbols in a file and identifies configuration access points.

Inputs:

ctx - Context for cancellation.
filePath - The relative path to the file.

Outputs:

[]ConfigUse - All configuration access points in the file.
error - Non-nil if the file is not found or operation was canceled.

Thread Safety:

This method is safe for concurrent use.

func (*ConfigFinder) FindConfigByFramework

func (f *ConfigFinder) FindConfigByFramework(ctx context.Context, framework string) ([]ConfigUse, error)

FindConfigByFramework finds configuration access for a specific framework.

Description:

Finds all configuration access points that use a specific framework
(e.g., "viper", "envconfig", "dotenv").

Inputs:

ctx - Context for cancellation.
framework - The framework name to search for.

Outputs:

[]ConfigUse - All configuration access points for the framework.
error - Non-nil if the operation was canceled.

Thread Safety:

This method is safe for concurrent use.

func (*ConfigFinder) FindConfigUsage

func (f *ConfigFinder) FindConfigUsage(ctx context.Context, configKey string) (*ConfigUsage, error)

FindConfigUsage finds all places where a configuration key is used.

Description:

Searches the codebase for usages of the specified configuration key.
Supports patterns with wildcards (e.g., "DATABASE_*" matches
DATABASE_URL, DATABASE_HOST, etc.).

Inputs:

ctx - Context for cancellation.
configKey - The configuration key or pattern to search for.

Outputs:

*ConfigUsage - All usages of the configuration key.
error - Non-nil if the operation was canceled.

Performance:

Target latency: < 500ms for typical codebases.

Thread Safety:

This method is safe for concurrent use.

func (*ConfigFinder) FindEnvironmentVariables

func (f *ConfigFinder) FindEnvironmentVariables(ctx context.Context) ([]ConfigUse, error)

FindEnvironmentVariables finds all environment variable accesses.

Description:

Specifically finds accesses to environment variables through
os.Getenv, os.environ, process.env, etc.

Inputs:

ctx - Context for cancellation.

Outputs:

[]ConfigUse - All environment variable access points.
error - Non-nil if the operation was canceled.

Thread Safety:

This method is safe for concurrent use.

func (*ConfigFinder) GetPatterns

func (f *ConfigFinder) GetPatterns(language string) []ConfigPattern

GetPatterns returns config patterns for a language.

func (*ConfigFinder) RegisterPatterns

func (f *ConfigFinder) RegisterPatterns(language string, patterns []ConfigPattern)

RegisterPatterns adds config patterns for a language.

func (*ConfigFinder) TraceConfigUsage

func (f *ConfigFinder) TraceConfigUsage(ctx context.Context, symbolID string, opts ...ExploreOption) (*DataFlow, error)

TraceConfigUsage traces where a config value flows after being read.

Description:

Starting from a config access point, traces where the value flows
through the codebase using call graph analysis.

Inputs:

ctx - Context for cancellation.
symbolID - The symbol ID of the config accessor.
opts - Optional configuration (MaxNodes, MaxHops).

Outputs:

*DataFlow - The flow of the config value through the code.
error - Non-nil if the symbol is not found or operation was canceled.

Thread Safety:

This method is safe for concurrent use.

type ConfigPattern

type ConfigPattern struct {
	// FunctionName is a pattern for the function/method name.
	FunctionName string

	// Receiver is a pattern for the receiver type (for methods).
	Receiver string

	// Package is a pattern for the package containing the function.
	Package string

	// Framework identifies the configuration framework.
	Framework string

	// Description explains what this pattern matches.
	Description string
	// contains filtered or unexported fields
}

ConfigPattern defines a pattern for identifying configuration access.

func DefaultGoConfigPatterns

func DefaultGoConfigPatterns() []ConfigPattern

DefaultGoConfigPatterns returns default configuration patterns for Go.

func DefaultPythonConfigPatterns

func DefaultPythonConfigPatterns() []ConfigPattern

DefaultPythonConfigPatterns returns default configuration patterns for Python.

func DefaultTypeScriptConfigPatterns

func DefaultTypeScriptConfigPatterns() []ConfigPattern

DefaultTypeScriptConfigPatterns returns default configuration patterns for TypeScript/JavaScript.

type ConfigUsage

type ConfigUsage struct {
	// ConfigKey is the configuration key or pattern.
	ConfigKey string `json:"config_key"`

	// UsedIn contains all usage locations.
	UsedIn []ConfigUse `json:"used_in"`

	// DefaultVal is the default value if found.
	DefaultVal string `json:"default_value,omitempty"`
}

ConfigUsage represents usage of a configuration key.

type ConfigUse

type ConfigUse struct {
	// Function is the function name where config is used.
	Function string `json:"function"`

	// FilePath is the relative path to the file.
	FilePath string `json:"file_path"`

	// Line is the 1-indexed line number.
	Line int `json:"line"`

	// Context describes how the config is used.
	Context string `json:"context"`
}

ConfigUse represents a usage of a configuration value.

type DataFlow

type DataFlow struct {
	// Sources contains where data enters the system.
	Sources []DataPoint `json:"sources"`

	// Transforms contains where data is modified.
	Transforms []DataPoint `json:"transforms"`

	// Sinks contains where data exits the system.
	Sinks []DataPoint `json:"sinks"`

	// Path contains the ordered function calls in the flow.
	Path []string `json:"path"`

	// Precision indicates analysis precision ("function" or "variable").
	Precision string `json:"precision"`

	// Limitations documents what we couldn't track.
	Limitations []string `json:"limitations,omitempty"`
}

DataFlow represents the flow of data through the codebase.

type DataFlowTracer

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

DataFlowTracer traces data flow through function calls.

Thread Safety:

DataFlowTracer is safe for concurrent use. It performs read-only
operations on the graph and index.

func NewDataFlowTracer

func NewDataFlowTracer(g *graph.Graph, idx *index.SymbolIndex) *DataFlowTracer

NewDataFlowTracer creates a new DataFlowTracer.

Description:

Creates a tracer that can follow data flow through function calls,
identifying sources (where data enters), transforms (where data
is processed), and sinks (where data exits).

Inputs:

g - The code graph. Must be frozen.
idx - The symbol index.

Outputs:

*DataFlowTracer - The configured tracer.

Example:

tracer := NewDataFlowTracer(graph, index)
flow, err := tracer.TraceDataFlow(ctx, "handlers.HandleRequest", opts...)

func NewDataFlowTracerWithRegistries

func NewDataFlowTracerWithRegistries(
	g *graph.Graph,
	idx *index.SymbolIndex,
	sources *SourceRegistry,
	sinks *SinkRegistry,
) *DataFlowTracer

NewDataFlowTracerWithRegistries creates a DataFlowTracer with custom registries.

Description:

Creates a tracer with custom source and sink registries. Useful for
specialized analysis or when sharing registries with trust flow analysis.

Inputs:

g - The code graph. Must be frozen.
idx - The symbol index.
sources - Custom source registry.
sinks - Custom sink registry.

Outputs:

*DataFlowTracer - The configured tracer.

func (*DataFlowTracer) FindDangerousSinksInFile

func (t *DataFlowTracer) FindDangerousSinksInFile(ctx context.Context, filePath string) ([]DataPoint, error)

FindDangerousSinksInFile finds all dangerous sinks in a file.

Description:

Scans all symbols in a file and identifies which ones are dangerous
sinks (command execution, SQL injection, etc.). Useful for security
auditing.

Inputs:

ctx - Context for cancellation.
filePath - The relative path to the file.

Outputs:

[]DataPoint - All dangerous sinks found in the file.
error - Non-nil if the file is not found or operation was canceled.

Thread Safety:

This method is safe for concurrent use.

func (*DataFlowTracer) FindSinksInFile

func (t *DataFlowTracer) FindSinksInFile(ctx context.Context, filePath string) ([]DataPoint, error)

FindSinksInFile finds all data sinks in a file.

Description:

Scans all symbols in a file and identifies which ones are data sinks.

Inputs:

ctx - Context for cancellation.
filePath - The relative path to the file.

Outputs:

[]DataPoint - All data sinks found in the file.
error - Non-nil if the file is not found or operation was canceled.

Thread Safety:

This method is safe for concurrent use.

func (*DataFlowTracer) FindSourcesInFile

func (t *DataFlowTracer) FindSourcesInFile(ctx context.Context, filePath string) ([]DataPoint, error)

FindSourcesInFile finds all data sources in a file.

Description:

Scans all symbols in a file and identifies which ones are data sources.

Inputs:

ctx - Context for cancellation.
filePath - The relative path to the file.

Outputs:

[]DataPoint - All data sources found in the file.
error - Non-nil if the file is not found or operation was canceled.

Thread Safety:

This method is safe for concurrent use.

func (*DataFlowTracer) TraceDataFlow

func (t *DataFlowTracer) TraceDataFlow(ctx context.Context, symbolID string, opts ...ExploreOption) (*DataFlow, error)

TraceDataFlow traces data flow starting from a symbol.

Description:

Performs BFS traversal from the starting symbol, following CALLS edges
to identify where data flows. Classifies each visited symbol as a
source, transform, or sink based on pattern matching.

Inputs:

ctx - Context for cancellation.
symbolID - The symbol ID to start tracing from.
opts - Optional configuration (MaxNodes, MaxHops).

Outputs:

*DataFlow - The traced data flow with sources, transforms, and sinks.
error - Non-nil if the symbol is not found or operation was canceled.

Errors:

ErrSymbolNotFound - Symbol not found in the graph.
ErrContextCanceled - Context was canceled.
ErrGraphNotReady - Graph is not frozen.
ErrTraversalLimitReached - Max nodes limit was reached.

Performance:

Target latency: < 500ms for typical call graphs.
Max nodes: 1000 (configurable via options).

Limitations:

  • Function-level precision only (not variable-level)
  • Cannot track data through interface calls reliably
  • May miss flows through reflection or dynamic dispatch

Thread Safety:

This method is safe for concurrent use.

func (*DataFlowTracer) TraceDataFlowReverse

func (t *DataFlowTracer) TraceDataFlowReverse(ctx context.Context, symbolID string, opts ...ExploreOption) (*DataFlow, error)

TraceDataFlowReverse traces data flow backwards from a sink.

Description:

Performs reverse BFS traversal from the starting symbol, following
incoming CALLS edges to find where data came from. Useful for
understanding the provenance of data at a particular point.

Inputs:

ctx - Context for cancellation.
symbolID - The symbol ID to start tracing from (typically a sink).
opts - Optional configuration (MaxNodes, MaxHops).

Outputs:

*DataFlow - The traced data flow with sources, transforms, and sinks.
error - Non-nil if the symbol is not found or operation was canceled.

Thread Safety:

This method is safe for concurrent use.

func (*DataFlowTracer) TraceToDangerousSinks

func (t *DataFlowTracer) TraceToDangerousSinks(ctx context.Context, symbolID string, opts ...ExploreOption) (*DataFlow, error)

TraceToDangerousSinks traces from a source to find paths to dangerous sinks.

Description:

Performs BFS from the starting symbol, looking for paths that end at
dangerous sinks. This is useful for identifying potential security
vulnerabilities.

Inputs:

ctx - Context for cancellation.
symbolID - The symbol ID to start tracing from (typically a source).
opts - Optional configuration (MaxNodes, MaxHops).

Outputs:

*DataFlow - The traced data flow, with only dangerous sinks included.
error - Non-nil if the symbol is not found or operation was canceled.

Thread Safety:

This method is safe for concurrent use.

type DataPoint

type DataPoint struct {
	// ID is the symbol ID.
	ID string `json:"id"`

	// Type indicates what kind of data point (param, return, field, variable).
	Type string `json:"type"`

	// Name is the symbol name.
	Name string `json:"name"`

	// Location is the file:line reference.
	Location string `json:"location"`

	// Category is the source/sink category (http_input, env_var, etc.).
	Category string `json:"category"`

	// Confidence indicates how certain we are about this classification (0.0-1.0).
	Confidence float64 `json:"confidence"`
}

DataPoint represents a point in the data flow.

type EmbeddingClient

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

EmbeddingClient wraps calls to the embeddings service.

Description

EmbeddingClient provides a Go interface to the Python embeddings service, which runs transformer models (like BGE, Qwen) to generate vector embeddings for text. These embeddings enable semantic similarity search.

Thread Safety

EmbeddingClient is safe for concurrent use.

func NewEmbeddingClient

func NewEmbeddingClient(baseURL string) *EmbeddingClient

NewEmbeddingClient creates a new embedding client.

Description

Creates a client configured to connect to the embeddings service. The service should be running and accessible at the given URL.

Inputs

Example

client := explore.NewEmbeddingClient("http://localhost:8000")
vector, err := client.Embed(ctx, "func ProcessData(ctx context.Context) error")

func (*EmbeddingClient) BaseURL

func (c *EmbeddingClient) BaseURL() string

BaseURL returns the configured base URL.

func (*EmbeddingClient) BatchEmbed

func (c *EmbeddingClient) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error)

BatchEmbed computes embeddings for multiple texts efficiently.

Description

Batches multiple texts into a single request for efficiency. The service processes them together, reducing overhead.

Inputs

  • ctx: Context for cancellation and timeout.
  • texts: The texts to embed.

Outputs

  • [][]float32: The embedding vectors, one per input text.
  • error: Non-nil if embedding fails.

Performance

Batching is more efficient than individual Embed calls when embedding multiple texts. Target: < 50ms per text in batch.

func (*EmbeddingClient) Embed

func (c *EmbeddingClient) Embed(ctx context.Context, text string) ([]float32, error)

Embed computes a vector embedding for the given text.

Description

Calls the embeddings service to convert text into a dense vector representation suitable for semantic similarity search.

Inputs

  • ctx: Context for cancellation and timeout.
  • text: The text to embed (e.g., function signature, docstring).

Outputs

  • []float32: The embedding vector.
  • error: Non-nil if embedding fails.

Example

vector, err := client.Embed(ctx, "func ProcessData(ctx context.Context, data []byte) error")
if err != nil {
    // Handle error - may fall back to structural similarity
}

Limitations

  • Text may be truncated if exceeding model's max input tokens (512 for BGE).
  • Network latency depends on embedding service location.

func (*EmbeddingClient) Health

func (c *EmbeddingClient) Health(ctx context.Context) error

Health checks if the embeddings service is available.

Description

Performs a health check against the embeddings service to verify it is running and the model is loaded.

Inputs

  • ctx: Context for cancellation and timeout.

Outputs

  • error: Non-nil if service is unavailable.

Example

if err := client.Health(ctx); err != nil {
    log.Warn("Embeddings service unavailable, falling back to structural similarity")
}

func (*EmbeddingClient) WithTimeout

func (c *EmbeddingClient) WithTimeout(timeout time.Duration) *EmbeddingClient

WithTimeout sets a custom timeout for embedding requests.

type EntryPoint

type EntryPoint struct {
	// ID is the unique symbol ID.
	ID string `json:"id"`

	// Name is the symbol name.
	Name string `json:"name"`

	// Type categorizes the entry point (main, handler, command, test, lambda, grpc).
	Type EntryPointType `json:"type"`

	// Framework identifies the framework if detected (gin, echo, cobra, fastapi, etc.).
	Framework string `json:"framework,omitempty"`

	// FilePath is the relative path to the file containing this entry point.
	FilePath string `json:"file_path"`

	// Line is the 1-indexed line number where the entry point is defined.
	Line int `json:"line"`

	// Signature is the function/method signature.
	Signature string `json:"signature"`

	// DocComment contains any documentation comment.
	DocComment string `json:"doc_comment,omitempty"`

	// Package is the package/module containing this entry point.
	Package string `json:"package,omitempty"`
}

EntryPoint represents a code entry point discovered in the codebase.

type EntryPointFinder

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

EntryPointFinder discovers entry points in a codebase.

Thread Safety:

EntryPointFinder is safe for concurrent use. It performs read-only
operations on the graph and index.

func NewEntryPointFinder

func NewEntryPointFinder(g *graph.Graph, idx *index.SymbolIndex) *EntryPointFinder

NewEntryPointFinder creates a new EntryPointFinder.

Description:

Creates a finder that can discover entry points using the provided
graph and symbol index. Uses the default pattern registry.

Inputs:

g - The code graph. Must be frozen.
idx - The symbol index.

Outputs:

*EntryPointFinder - The configured finder.

Example:

finder := NewEntryPointFinder(graph, index)
result, err := finder.FindEntryPoints(ctx, EntryPointAll, nil)

func (*EntryPointFinder) DetectFrameworks

func (f *EntryPointFinder) DetectFrameworks(ctx context.Context) (map[string]int, error)

DetectFrameworks identifies frameworks used in the codebase.

Description:

Analyzes entry points to determine which frameworks are in use.

Inputs:

ctx - Context for cancellation.

Outputs:

map[string]int - Framework name to count of entry points.
error - Non-nil if the operation was canceled or failed.

func (*EntryPointFinder) FindByFramework

func (f *EntryPointFinder) FindByFramework(ctx context.Context, framework string) ([]EntryPoint, error)

FindByFramework finds entry points for a specific framework.

Description:

Finds all entry points associated with a framework (e.g., "gin", "fastapi").

Inputs:

ctx - Context for cancellation.
framework - Framework name to filter by.

Outputs:

[]EntryPoint - Entry points for the framework.
error - Non-nil if the operation was canceled or failed.

func (*EntryPointFinder) FindByPackage

func (f *EntryPointFinder) FindByPackage(ctx context.Context, packagePath string) ([]EntryPoint, error)

FindByPackage finds entry points in a specific package.

Description:

Finds all entry points within a package/module.

Inputs:

ctx - Context for cancellation.
packagePath - Package path to filter by.

Outputs:

[]EntryPoint - Entry points in the package.
error - Non-nil if the operation was canceled or failed.

func (*EntryPointFinder) FindEntryPoints

func (f *EntryPointFinder) FindEntryPoints(ctx context.Context, opts EntryPointOptions) (*EntryPointResult, error)

FindEntryPoints discovers entry points in the codebase.

Description:

Scans all symbols in the index and matches them against registered
entry point patterns. Returns entry points sorted by file path and line.

Inputs:

ctx - Context for cancellation.
opts - Options for filtering and limiting results.

Outputs:

*EntryPointResult - Discovered entry points.
error - Non-nil if the operation was canceled or failed.

Errors:

ErrContextCanceled - Context was canceled.
ErrGraphNotReady - Graph is not frozen.

Performance:

O(n) where n is the number of symbols. Target latency: < 100ms.

Thread Safety:

This method is safe for concurrent use.

func (*EntryPointFinder) FindHandlers

func (f *EntryPointFinder) FindHandlers(ctx context.Context) ([]EntryPoint, error)

FindHandlers finds all HTTP/REST handlers.

Description:

Convenience method for finding HTTP handlers across frameworks.

Inputs:

ctx - Context for cancellation.

Outputs:

[]EntryPoint - Handler entry points found.
error - Non-nil if the operation was canceled or failed.

func (*EntryPointFinder) FindMainEntryPoints

func (f *EntryPointFinder) FindMainEntryPoints(ctx context.Context) ([]EntryPoint, error)

FindMainEntryPoints finds all main/script entry points.

Description:

Convenience method for finding main() functions and __main__ blocks.

Inputs:

ctx - Context for cancellation.

Outputs:

[]EntryPoint - Main entry points found.
error - Non-nil if the operation was canceled or failed.

func (*EntryPointFinder) FindTests

func (f *EntryPointFinder) FindTests(ctx context.Context) ([]EntryPoint, error)

FindTests finds all test entry points.

Description:

Convenience method for finding test functions.

Inputs:

ctx - Context for cancellation.

Outputs:

[]EntryPoint - Test entry points found.
error - Non-nil if the operation was canceled or failed.

func (*EntryPointFinder) WithRegistry

func (f *EntryPointFinder) WithRegistry(registry *EntryPointRegistry) *EntryPointFinder

WithRegistry returns a new finder with a custom pattern registry.

type EntryPointOptions

type EntryPointOptions struct {
	// Type filters results to a specific entry point type.
	// Use EntryPointAll for all types.
	Type EntryPointType

	// Package filters results to a specific package.
	Package string

	// Language filters results to a specific language.
	Language string

	// Limit is the maximum number of results to return.
	Limit int

	// IncludeTests includes test entry points in results.
	IncludeTests bool
}

EntryPointOptions configures entry point finding.

func DefaultEntryPointOptions

func DefaultEntryPointOptions() EntryPointOptions

DefaultEntryPointOptions returns sensible defaults.

type EntryPointPatterns

type EntryPointPatterns struct {
	// Language identifies which language these patterns apply to.
	Language string

	// Main patterns for main entry points (main(), __main__).
	Main []PatternMatcher

	// Handler patterns for HTTP/REST handlers.
	Handler []PatternMatcher

	// Command patterns for CLI commands.
	Command []PatternMatcher

	// Test patterns for test functions.
	Test []PatternMatcher

	// Lambda patterns for serverless handlers.
	Lambda []PatternMatcher

	// GRPC patterns for gRPC service implementations.
	GRPC []PatternMatcher
}

EntryPointPatterns defines detection patterns per language.

func DefaultGoPatterns

func DefaultGoPatterns() *EntryPointPatterns

DefaultGoPatterns returns default entry point patterns for Go.

func DefaultJavaScriptPatterns

func DefaultJavaScriptPatterns() *EntryPointPatterns

DefaultJavaScriptPatterns returns default entry point patterns for JavaScript.

func DefaultPythonPatterns

func DefaultPythonPatterns() *EntryPointPatterns

DefaultPythonPatterns returns default entry point patterns for Python.

func DefaultTypeScriptPatterns

func DefaultTypeScriptPatterns() *EntryPointPatterns

DefaultTypeScriptPatterns returns default entry point patterns for TypeScript.

type EntryPointRegistry

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

EntryPointRegistry holds patterns for all supported languages.

func NewEntryPointRegistry

func NewEntryPointRegistry() *EntryPointRegistry

NewEntryPointRegistry creates a new registry with default patterns.

func (*EntryPointRegistry) GetPatterns

func (r *EntryPointRegistry) GetPatterns(language string) (*EntryPointPatterns, bool)

GetPatterns returns patterns for a language.

func (*EntryPointRegistry) Languages

func (r *EntryPointRegistry) Languages() []string

Languages returns all registered languages.

func (*EntryPointRegistry) RegisterPatterns

func (r *EntryPointRegistry) RegisterPatterns(language string, patterns *EntryPointPatterns)

RegisterPatterns adds or replaces patterns for a language.

type EntryPointResult

type EntryPointResult struct {
	// EntryPoints contains all discovered entry points.
	EntryPoints []EntryPoint `json:"entry_points"`

	// Truncated indicates if results were truncated due to limits.
	Truncated bool `json:"truncated,omitempty"`

	// TotalFound is the total count before truncation.
	TotalFound int `json:"total_found"`
}

EntryPointResult contains the result of an entry point search.

type EntryPointType

type EntryPointType string

EntryPointType categorizes different kinds of entry points.

const (
	// EntryPointMain represents main() or __main__ entry points.
	EntryPointMain EntryPointType = "main"

	// EntryPointHandler represents HTTP/REST handlers.
	EntryPointHandler EntryPointType = "handler"

	// EntryPointCommand represents CLI commands.
	EntryPointCommand EntryPointType = "command"

	// EntryPointTest represents test functions.
	EntryPointTest EntryPointType = "test"

	// EntryPointLambda represents serverless function handlers.
	EntryPointLambda EntryPointType = "lambda"

	// EntryPointGRPC represents gRPC service implementations.
	EntryPointGRPC EntryPointType = "grpc"

	// EntryPointAll is a special value for finding all entry point types.
	EntryPointAll EntryPointType = "all"
)

type ErrorFlow

type ErrorFlow struct {
	// Origins contains where errors are created.
	Origins []ErrorPoint `json:"origins"`

	// Handlers contains where errors are caught/handled.
	Handlers []ErrorPoint `json:"handlers"`

	// Escapes contains unhandled error paths.
	Escapes []ErrorPoint `json:"escapes"`
}

ErrorFlow represents error propagation through the codebase.

type ErrorFlowTracer

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

ErrorFlowTracer traces error propagation through function calls.

Thread Safety:

ErrorFlowTracer is safe for concurrent use. It performs read-only
operations on the graph and index.

func NewErrorFlowTracer

func NewErrorFlowTracer(g *graph.Graph, idx *index.SymbolIndex) *ErrorFlowTracer

NewErrorFlowTracer creates a new ErrorFlowTracer.

Description:

Creates a tracer that can follow error propagation through function
calls, identifying error origins, handlers, and escape points.

Inputs:

g - The code graph. Must be frozen.
idx - The symbol index.

Outputs:

*ErrorFlowTracer - The configured tracer.

Example:

tracer := NewErrorFlowTracer(graph, index)
flow, err := tracer.TraceErrorFlow(ctx, "handlers.HandleRequest", opts...)

func (*ErrorFlowTracer) FindErrorHandlers

func (t *ErrorFlowTracer) FindErrorHandlers(ctx context.Context, filePath string) ([]ErrorPoint, error)

FindErrorHandlers finds all error handling points in a file.

Description:

Scans all symbols in a file and identifies which ones handle errors.

Inputs:

ctx - Context for cancellation.
filePath - The relative path to the file.

Outputs:

[]ErrorPoint - All error handlers found in the file.
error - Non-nil if the file is not found or operation was canceled.

Thread Safety:

This method is safe for concurrent use.

func (*ErrorFlowTracer) FindErrorOrigins

func (t *ErrorFlowTracer) FindErrorOrigins(ctx context.Context, filePath string) ([]ErrorPoint, error)

FindErrorOrigins finds all error creation points in a file.

Description:

Scans all symbols in a file and identifies which ones create errors.

Inputs:

ctx - Context for cancellation.
filePath - The relative path to the file.

Outputs:

[]ErrorPoint - All error origins found in the file.
error - Non-nil if the file is not found or operation was canceled.

Thread Safety:

This method is safe for concurrent use.

func (*ErrorFlowTracer) FindUnhandledErrors

func (t *ErrorFlowTracer) FindUnhandledErrors(ctx context.Context, symbolID string, opts ...ExploreOption) ([]ErrorPoint, error)

FindUnhandledErrors finds functions that return errors but might not handle them.

Description:

Analyzes the call graph to find functions that receive errors from
callees but might not handle them (potential escape points).

Inputs:

ctx - Context for cancellation.
symbolID - The symbol ID to start analyzing from.
opts - Optional configuration (MaxNodes, MaxHops).

Outputs:

[]ErrorPoint - Functions that might have unhandled errors.
error - Non-nil if the symbol is not found or operation was canceled.

Thread Safety:

This method is safe for concurrent use.

func (*ErrorFlowTracer) GetErrorFlowSummary

func (t *ErrorFlowTracer) GetErrorFlowSummary(ctx context.Context, filePath string) (*ErrorFlow, error)

GetErrorFlowSummary provides a summary of error handling in a file.

Description:

Provides a quick overview of error handling patterns in a file,
including counts of origins, handlers, and potential escapes.

Inputs:

ctx - Context for cancellation.
filePath - The relative path to the file.

Outputs:

*ErrorFlow - Summary of error handling in the file.
error - Non-nil if the file is not found or operation was canceled.

Thread Safety:

This method is safe for concurrent use.

func (*ErrorFlowTracer) TraceErrorFlow

func (t *ErrorFlowTracer) TraceErrorFlow(ctx context.Context, symbolID string, opts ...ExploreOption) (*ErrorFlow, error)

TraceErrorFlow traces error propagation from a function.

Description:

Performs BFS traversal from the starting symbol, analyzing each
function's error handling behavior to identify:
- Origins: Where errors are created (errors.New, fmt.Errorf)
- Handlers: Where errors are caught/handled (if err != nil with handling)
- Escapes: Where errors propagate up without handling

Inputs:

ctx - Context for cancellation.
symbolID - The symbol ID to start tracing from.
opts - Optional configuration (MaxNodes, MaxHops).

Outputs:

*ErrorFlow - The traced error flow with origins, handlers, and escapes.
error - Non-nil if the symbol is not found or operation was canceled.

Errors:

ErrSymbolNotFound - Symbol not found in the graph.
ErrContextCanceled - Context was canceled.
ErrGraphNotReady - Graph is not frozen.

Performance:

Target latency: < 500ms for typical call graphs.

Limitations:

  • Cannot track errors through interface calls reliably
  • May miss custom error types that don't follow naming conventions
  • Does not analyze error wrapping chains in detail

Thread Safety:

This method is safe for concurrent use.

type ErrorPoint

type ErrorPoint struct {
	// Function is the function name.
	Function string `json:"function"`

	// FilePath is the relative path to the file.
	FilePath string `json:"file_path"`

	// Line is the 1-indexed line number.
	Line int `json:"line"`

	// Type indicates the error handling type (origin, handler, propagate, escape).
	Type string `json:"type"`

	// Code is the error handling code snippet.
	Code string `json:"code,omitempty"`
}

ErrorPoint represents a point in the error flow.

type ExplorationCache

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

ExplorationCache provides caching for expensive exploration operations.

Thread Safety:

ExplorationCache is safe for concurrent use.

func NewExplorationCache

func NewExplorationCache(config CacheConfig) *ExplorationCache

NewExplorationCache creates a new exploration cache with the given config.

Example:

cache := NewExplorationCache(DefaultCacheConfig())

func (*ExplorationCache) Clear

func (c *ExplorationCache) Clear()

Clear removes all cached entries.

func (*ExplorationCache) GetEntryPoints

func (c *ExplorationCache) GetEntryPoints(opts EntryPointOptions) *EntryPointResult

GetEntryPoints retrieves cached entry point results.

Returns nil if not cached or expired.

func (*ExplorationCache) GetFileSummary

func (c *ExplorationCache) GetFileSummary(filePath string) *FileSummary

GetFileSummary retrieves a cached file summary.

Returns nil if not cached or expired.

func (*ExplorationCache) GetPackageAPI

func (c *ExplorationCache) GetPackageAPI(packagePath string) *PackageAPI

GetPackageAPI retrieves a cached package API.

Returns nil if not cached or expired.

func (*ExplorationCache) InvalidateFile

func (c *ExplorationCache) InvalidateFile(filePath string)

InvalidateFile invalidates all cache entries related to a file.

func (*ExplorationCache) InvalidatePackage

func (c *ExplorationCache) InvalidatePackage(packagePath string)

InvalidatePackage invalidates all cache entries related to a package.

func (*ExplorationCache) SetEntryPoints

func (c *ExplorationCache) SetEntryPoints(opts EntryPointOptions, result *EntryPointResult)

SetEntryPoints caches entry point results.

func (*ExplorationCache) SetFileSummary

func (c *ExplorationCache) SetFileSummary(filePath string, summary *FileSummary)

SetFileSummary caches a file summary.

func (*ExplorationCache) SetPackageAPI

func (c *ExplorationCache) SetPackageAPI(packagePath string, api *PackageAPI)

SetPackageAPI caches a package API.

func (*ExplorationCache) Stats

func (c *ExplorationCache) Stats() CacheStats

Stats returns current cache statistics.

type ExploreOption

type ExploreOption func(*ExploreOptions)

ExploreOption is a functional option for configuring exploration.

func WithIncludeCode

func WithIncludeCode(include bool) ExploreOption

WithIncludeCode sets whether to include source code.

func WithMaxHops

func WithMaxHops(h int) ExploreOption

WithMaxHops sets the maximum traversal depth.

func WithMaxNodes

func WithMaxNodes(n int) ExploreOption

WithMaxNodes sets the maximum nodes to visit.

func WithTokenBudget

func WithTokenBudget(t int) ExploreOption

WithTokenBudget sets the token budget for context building.

func WithUseCache

func WithUseCache(use bool) ExploreOption

WithUseCache sets whether to use caching.

type ExploreOptions

type ExploreOptions struct {
	// MaxNodes is the maximum nodes to visit during traversal.
	MaxNodes int

	// MaxHops is the maximum depth for data flow tracing.
	MaxHops int

	// TokenBudget is the maximum token budget for context building.
	TokenBudget int

	// IncludeCode indicates whether to include source code in results.
	IncludeCode bool

	// UseCache indicates whether to use the exploration cache.
	UseCache bool
}

ExploreOptions configures exploration tool behavior.

func DefaultExploreOptions

func DefaultExploreOptions() ExploreOptions

DefaultExploreOptions returns sensible defaults.

type FileSummarizer

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

FileSummarizer provides structured summaries of source files.

Thread Safety:

FileSummarizer is safe for concurrent use. It performs read-only
operations on the graph and index.

func NewFileSummarizer

func NewFileSummarizer(g *graph.Graph, idx *index.SymbolIndex) *FileSummarizer

NewFileSummarizer creates a new FileSummarizer.

Description:

Creates a summarizer that can produce structured summaries of files
using the provided graph and symbol index.

Inputs:

g - The code graph. Must be frozen.
idx - The symbol index.

Outputs:

*FileSummarizer - The configured summarizer.

Example:

summarizer := NewFileSummarizer(graph, index)
summary, err := summarizer.SummarizeFile(ctx, "handlers/user.go")

func (*FileSummarizer) SummarizeFile

func (s *FileSummarizer) SummarizeFile(ctx context.Context, filePath string) (*FileSummary, error)

SummarizeFile produces a structured summary of a file.

Description:

Extracts types, functions, imports, and metadata from a file
to provide a quick overview without reading the entire file.

Inputs:

ctx - Context for cancellation.
filePath - Relative path to the file.

Outputs:

*FileSummary - Structured summary of the file.
error - Non-nil if the file is not found or operation was canceled.

Errors:

ErrFileNotFound - File not found in the index.
ErrContextCanceled - Context was canceled.

Performance:

Target latency: < 50ms.

Thread Safety:

This method is safe for concurrent use.

func (*FileSummarizer) SummarizePackage

func (s *FileSummarizer) SummarizePackage(ctx context.Context, packagePath string) ([]*FileSummary, error)

SummarizePackage produces summaries for all files in a package.

Description:

Produces summaries for all files belonging to a package/module.

Inputs:

ctx - Context for cancellation.
packagePath - Package path to summarize.

Outputs:

[]*FileSummary - Summaries of all files in the package.
error - Non-nil if the operation was canceled.

Thread Safety:

This method is safe for concurrent use.

type FileSummary

type FileSummary struct {
	// FilePath is the relative path to the file.
	FilePath string `json:"file_path"`

	// Package is the package/module name.
	Package string `json:"package"`

	// Imports lists import paths.
	Imports []string `json:"imports"`

	// Types contains type summaries.
	Types []TypeBrief `json:"types"`

	// Functions contains function summaries.
	Functions []FuncBrief `json:"functions"`

	// LineCount is the total number of lines.
	LineCount int `json:"line_count"`

	// Purpose is an inferred description of the file's purpose.
	Purpose string `json:"purpose,omitempty"`
}

FileSummary provides a structured summary of a file.

type FingerprintBuilder

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

FingerprintBuilder builds AST fingerprints from symbols.

Description:

Extracts structural features from code symbols to enable similarity
comparison. Features include control flow patterns, call patterns,
and signature characteristics.

Thread Safety:

This type is safe for concurrent use. All methods perform read-only
operations on the graph.

func NewFingerprintBuilder

func NewFingerprintBuilder(g *graph.Graph) *FingerprintBuilder

NewFingerprintBuilder creates a new FingerprintBuilder.

Description:

Creates a builder that can compute fingerprints for symbols.
The graph is used to extract call patterns.

Inputs:

g - The code graph. May be nil for standalone fingerprinting.

Example:

builder := NewFingerprintBuilder(graph)
fp := builder.ComputeFingerprint(symbol)

func (*FingerprintBuilder) ComputeFingerprint

func (b *FingerprintBuilder) ComputeFingerprint(sym *ast.Symbol, opts ...FingerprintOption) *ASTFingerprint

ComputeFingerprint extracts structural features from a symbol.

Description:

Analyzes the symbol's signature and relationships to extract features
that can be used for similarity comparison. Features are language-agnostic
where possible.

Inputs:

sym - The symbol to fingerprint. Must not be nil.
opts - Optional configuration.

Outputs:

*ASTFingerprint - The computed fingerprint, never nil.

Example:

fp := builder.ComputeFingerprint(funcSymbol)
fmt.Printf("Complexity: %d, Params: %d\n", fp.Complexity, fp.ParamCount)

type FingerprintIndex

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

FingerprintIndex provides efficient similarity lookups using LSH.

Description:

Uses Locality-Sensitive Hashing (LSH) to enable O(n log n) approximate
nearest neighbor queries instead of O(n) brute force.

Thread Safety:

NOT safe for concurrent modification. Safe for concurrent queries
after Build() is called.

func NewFingerprintIndex

func NewFingerprintIndex(numBands, bandSize int) *FingerprintIndex

NewFingerprintIndex creates a new LSH index.

Description:

Creates an index that can store fingerprints and efficiently find
similar ones using LSH. Configure bands and band size based on
desired similarity threshold.

Inputs:

numBands - Number of hash bands for LSH (more = more candidates, lower threshold)
bandSize - Size of each band (signature length / numBands)

Example:

// For ~0.5 similarity threshold with 128 hashes
index := NewFingerprintIndex(32, 4)

func (*FingerprintIndex) Add

func (idx *FingerprintIndex) Add(fp *ASTFingerprint)

Add adds a fingerprint to the index.

func (*FingerprintIndex) FindSimilar

func (idx *FingerprintIndex) FindSimilar(query *ASTFingerprint, limit int) []string

FindSimilar finds candidate similar fingerprints using LSH.

Description:

Returns candidate symbol IDs that are likely similar based on LSH.
Should be followed by exact similarity computation for final ranking.

Inputs:

query - The fingerprint to find similar ones for.
limit - Maximum number of candidates to return.

Outputs:

[]string - Symbol IDs of candidate similar fingerprints.

func (*FingerprintIndex) Get

func (idx *FingerprintIndex) Get(symbolID string) (*ASTFingerprint, bool)

Get retrieves a fingerprint by symbol ID.

func (*FingerprintIndex) Size

func (idx *FingerprintIndex) Size() int

Size returns the number of fingerprints in the index.

type FingerprintOption

type FingerprintOption func(*FingerprintOptions)

FingerprintOption is a functional option for fingerprint configuration.

func WithNumHashes

func WithNumHashes(n int) FingerprintOption

WithNumHashes sets the number of MinHash signatures.

func WithShingleSize

func WithShingleSize(s int) FingerprintOption

WithShingleSize sets the shingle size.

type FingerprintOptions

type FingerprintOptions struct {
	// NumHashes is the number of MinHash signatures to compute.
	NumHashes int

	// ShingleSize is the size of k-shingles for set representation.
	ShingleSize int

	// IncludeCallPattern determines whether to include call patterns.
	IncludeCallPattern bool
}

FingerprintOptions configures fingerprint computation.

func DefaultFingerprintOptions

func DefaultFingerprintOptions() FingerprintOptions

DefaultFingerprintOptions returns sensible defaults.

type FuncBrief

type FuncBrief struct {
	// Name is the function name.
	Name string `json:"name"`

	// Signature is the function signature.
	Signature string `json:"signature"`

	// Exported indicates if the function is exported.
	Exported bool `json:"exported"`
}

FuncBrief provides a brief summary of a function.

type FunctionCriteria

type FunctionCriteria struct {
	// MinParams is the minimum parameter count (-1 to ignore).
	MinParams int

	// MaxParams is the maximum parameter count (-1 to ignore).
	MaxParams int

	// MinReturns is the minimum return count (-1 to ignore).
	MinReturns int

	// MaxReturns is the maximum return count (-1 to ignore).
	MaxReturns int

	// MinComplexity is the minimum complexity (-1 to ignore).
	MinComplexity int

	// MaxComplexity is the maximum complexity (-1 to ignore).
	MaxComplexity int

	// HasErrorReturn requires the function to return an error.
	HasErrorReturn *bool

	// HasContextParam requires the function to take a context parameter.
	HasContextParam *bool

	// Limit is the maximum number of results (0 for unlimited).
	Limit int
}

FunctionCriteria specifies criteria for function search.

type HybridWeights

type HybridWeights struct {
	Structural float64 // Weight for structural similarity (default 0.6)
	Semantic   float64 // Weight for semantic similarity (default 0.4)
}

HybridWeights configures the balance between structural and semantic.

func DefaultHybridWeights

func DefaultHybridWeights() HybridWeights

DefaultHybridWeights returns the default hybrid weighting.

type MinimalContext

type MinimalContext struct {
	// Target is the function being analyzed.
	Target CodeBlock `json:"target"`

	// Types contains required type definitions.
	Types []CodeBlock `json:"types"`

	// Interfaces contains implemented interfaces.
	Interfaces []CodeBlock `json:"interfaces"`

	// KeyCallees contains must-understand dependencies.
	KeyCallees []CodeBlock `json:"key_callees"`

	// TotalTokens is the total estimated token count.
	TotalTokens int `json:"total_tokens"`
}

MinimalContext contains the minimum code needed to understand a function.

type MinimalContextBuilder

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

MinimalContextBuilder builds minimal context for understanding a function.

Description:

Extracts the minimum amount of code needed to understand a target function,
including required types, implemented interfaces, and key dependencies.
All results respect the configured token budget.

Thread Safety:

This type is safe for concurrent use. All methods perform read-only
operations on the graph and index.

func NewMinimalContextBuilder

func NewMinimalContextBuilder(g *graph.Graph, idx *index.SymbolIndex) *MinimalContextBuilder

NewMinimalContextBuilder creates a new MinimalContextBuilder.

Description:

Creates a builder that can extract minimal context for functions.
The graph must be frozen before use.

Inputs:

g - The code graph. Must not be nil and must be frozen.
idx - The symbol index. Must not be nil.

Example:

builder := NewMinimalContextBuilder(graph, index)
ctx, err := builder.BuildMinimalContext(ctx, "pkg.FunctionName", WithTokenBudget(4000))

func (*MinimalContextBuilder) BuildMinimalContext

func (b *MinimalContextBuilder) BuildMinimalContext(ctx context.Context, symbolID string, opts ...ExploreOption) (*MinimalContext, error)

BuildMinimalContext extracts the minimum context needed to understand a function.

Description:

Collects the target function, required types (parameters and returns),
implemented interfaces, and key callees (sorted by call frequency).
Results are trimmed to fit within the token budget, prioritizing the
target function and essential types over callees.

Inputs:

ctx - Context for cancellation. Must not be nil.
symbolID - ID of the target function/method.
opts - Optional configuration (TokenBudget, IncludeCode).

Outputs:

*MinimalContext - The extracted context, never nil on success.
error - Non-nil on validation failure or if symbol not found.

Errors:

ErrInvalidInput - Context is nil or empty symbolID
ErrSymbolNotFound - Symbol not found in index
ErrGraphNotReady - Graph is not frozen
ErrContextCanceled - Context was canceled

Limitations:

  • Token estimates are approximate (based on character count)
  • Does not include transitive dependencies
  • Code content requires source access (may be empty)

Example:

result, err := builder.BuildMinimalContext(ctx, "pkg/handlers.HandleRequest")
if err != nil {
    return err
}
fmt.Printf("Total tokens: %d\n", result.TotalTokens)

func (*MinimalContextBuilder) GetContextForFunction deprecated

func (b *MinimalContextBuilder) GetContextForFunction(ctx context.Context, symbolID string, opts ...ExploreOption) (*MinimalContext, error)

GetContextForFunction is an alias for BuildMinimalContext.

Deprecated: Use BuildMinimalContext instead.

type PackageAPI

type PackageAPI struct {
	// Package is the package/module path.
	Package string `json:"package"`

	// Types contains exported types.
	Types []APISymbol `json:"types"`

	// Functions contains exported functions.
	Functions []APISymbol `json:"functions"`

	// Constants contains exported constants.
	Constants []APISymbol `json:"constants"`

	// Variables contains exported variables.
	Variables []APISymbol `json:"variables"`
}

PackageAPI represents the public API of a package.

type PackageAPISummarizer

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

PackageAPISummarizer provides public API summaries for packages.

func NewPackageAPISummarizer

func NewPackageAPISummarizer(g *graph.Graph, idx *index.SymbolIndex) *PackageAPISummarizer

NewPackageAPISummarizer creates a new PackageAPISummarizer.

func (*PackageAPISummarizer) FindPackageAPI

func (s *PackageAPISummarizer) FindPackageAPI(ctx context.Context, packagePath string) (*PackageAPI, error)

FindPackageAPI extracts the public API of a package.

Description:

Returns all exported types, functions, constants, and variables
in a package.

Inputs:

ctx - Context for cancellation.
packagePath - Package path to analyze.

Outputs:

*PackageAPI - The public API of the package.
error - Non-nil if the package is not found or operation was canceled.

Performance:

Target latency: < 50ms.

Thread Safety:

This method is safe for concurrent use.

type PatternMatcher

type PatternMatcher struct {
	// Name is a glob/regex pattern for the symbol name (e.g., "main", "Test*").
	Name string

	// Package is a glob/regex pattern for the package name.
	Package string

	// Signature is a pattern for the function signature.
	Signature string

	// Interface is the interface name that the type must implement.
	Interface string

	// Implements is similar to Interface but for service implementations.
	Implements string

	// Decorator is a decorator/annotation name (Python/TypeScript).
	Decorator string

	// BaseClass is a base class name (Python).
	BaseClass string

	// Type is a type pattern for struct fields or variables.
	Type string

	// Export indicates an exported symbol requirement.
	Export string

	// Framework identifies the framework if this pattern matches.
	Framework string
	// contains filtered or unexported fields
}

PatternMatcher defines criteria for matching entry points.

func (*PatternMatcher) Match

func (pm *PatternMatcher) Match(sym *ast.Symbol) bool

Match checks if a symbol matches the pattern.

Thread Safety: This method is safe for concurrent use.

type SemanticSimilarityEngine

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

SemanticSimilarityEngine extends SimilarityEngine with embedding support.

Description

SemanticSimilarityEngine wraps the structural SimilarityEngine and adds optional semantic similarity via embeddings. It supports three modes: structural (default), semantic, and hybrid.

Thread Safety

This type is safe for concurrent queries after Build() is called.

func NewSemanticSimilarityEngine

func NewSemanticSimilarityEngine(
	g *graph.Graph,
	idx *index.SymbolIndex,
	embedClient *EmbeddingClient,
) *SemanticSimilarityEngine

NewSemanticSimilarityEngine creates a new engine with optional embedding support.

Description

Creates an engine that supports structural, semantic, and hybrid similarity. If embedClient is nil, only structural similarity is available.

Inputs

  • g: Code graph. Must be frozen before Build().
  • idx: Symbol index.
  • embedClient: Optional embedding client. May be nil.

Example

// Without embeddings (structural only)
engine := NewSemanticSimilarityEngine(graph, index, nil)

// With embeddings (all methods available)
client := NewEmbeddingClient("http://localhost:8000")
engine := NewSemanticSimilarityEngine(graph, index, client)

func (*SemanticSimilarityEngine) Build

Build pre-computes fingerprints and optionally embeddings.

Description

Builds the structural fingerprint index. If embedding client is available and the service is healthy, also pre-computes embeddings for all functions. Embedding computation failures are non-fatal - the engine falls back to structural similarity.

Inputs

  • ctx: Context for cancellation.

Outputs

  • error: Non-nil only for structural build failures.

func (*SemanticSimilarityEngine) FindSimilarCode

func (e *SemanticSimilarityEngine) FindSimilarCode(
	ctx context.Context,
	symbolID string,
	method SimilarityMethod,
	opts ...ExploreOption,
) (*SimilarCode, error)

FindSimilarCode finds code similar to a target function.

Description

Finds similar code using the specified method. Falls back to structural if semantic is requested but unavailable.

Inputs

  • ctx: Context for cancellation.
  • symbolID: ID of the target function.
  • method: Similarity method (structural, semantic, hybrid).
  • opts: Optional configuration.

Outputs

  • *SimilarCode: Results including similarity scores and explanations.
  • error: Non-nil on validation failure or if symbol not found.

Example

// Structural similarity
result, err := engine.FindSimilarCode(ctx, "pkg.Function", SimilarityStructural)

// Semantic similarity (if available)
result, err := engine.FindSimilarCode(ctx, "pkg.Function", SimilaritySemantic)

// Hybrid (best of both)
result, err := engine.FindSimilarCode(ctx, "pkg.Function", SimilarityHybrid)

func (*SemanticSimilarityEngine) GetEmbedding

func (e *SemanticSimilarityEngine) GetEmbedding(symbolID string) ([]float32, bool)

GetEmbedding returns the pre-computed embedding for a symbol.

func (*SemanticSimilarityEngine) IsBuilt

func (e *SemanticSimilarityEngine) IsBuilt() bool

IsBuilt returns true if the engine is ready for queries.

func (*SemanticSimilarityEngine) IsEmbeddingEnabled

func (e *SemanticSimilarityEngine) IsEmbeddingEnabled() bool

IsEmbeddingEnabled returns true if semantic similarity is available.

func (*SemanticSimilarityEngine) Stats

Stats returns statistics about the engine.

func (*SemanticSimilarityEngine) WithDefaultMethod

WithDefaultMethod sets the default similarity method.

func (*SemanticSimilarityEngine) WithHybridWeights

WithHybridWeights sets custom hybrid weights.

type SemanticSimilarityStats

type SemanticSimilarityStats struct {
	StructuralStats  SimilarityEngineStats `json:"structural_stats"`
	EmbeddingCount   int                   `json:"embedding_count"`
	EmbeddingEnabled bool                  `json:"embedding_enabled"`
	EmbeddingBuilt   bool                  `json:"embedding_built"`
	DefaultMethod    string                `json:"default_method"`
}

SemanticSimilarityStats contains statistics about the engine.

type SimilarCode

type SimilarCode struct {
	// Query is the target symbol that was searched for.
	Query string `json:"query"`

	// Results contains similar code matches.
	Results []SimilarResult `json:"results"`

	// Method indicates the similarity method used ("structural" or "semantic").
	Method string `json:"method"`
}

SimilarCode contains the result of a similarity search.

type SimilarResult

type SimilarResult struct {
	// ID is the symbol ID.
	ID string `json:"id"`

	// Similarity is the similarity score (0.0-1.0).
	Similarity float64 `json:"similarity"`

	// FilePath is the relative path to the file.
	FilePath string `json:"file_path"`

	// Code is the code content.
	Code string `json:"code,omitempty"`

	// Why explains the similarity.
	Why string `json:"why,omitempty"`

	// MatchedTraits lists what aspects are similar.
	MatchedTraits []string `json:"matched_traits,omitempty"`
}

SimilarResult represents a single similar code match.

type SimilarityEngine

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

SimilarityEngine finds similar code using fingerprint-based comparison.

Description:

Uses AST fingerprinting with MinHash LSH to efficiently find structurally
similar code. Pre-computes fingerprints during initialization for O(n log n)
similarity queries.

Thread Safety:

This type is safe for concurrent queries after Build() is called.
Build() itself is NOT safe for concurrent use.

func NewSimilarityEngine

func NewSimilarityEngine(g *graph.Graph, idx *index.SymbolIndex) *SimilarityEngine

NewSimilarityEngine creates a new SimilarityEngine.

Description:

Creates an engine that can find similar code. Call Build() to
pre-compute fingerprints before querying.

Inputs:

g - The code graph. Must be frozen.
idx - The symbol index.

Example:

engine := NewSimilarityEngine(graph, index)
if err := engine.Build(ctx); err != nil {
    return err
}
similar, err := engine.FindSimilarCode(ctx, "pkg.Function", 5)

func (*SimilarityEngine) Build

func (e *SimilarityEngine) Build(ctx context.Context) error

Build pre-computes fingerprints for all function symbols.

Description:

Iterates through all function and method symbols in the index,
computes their fingerprints, and indexes them for efficient similarity
queries. This is a one-time operation that should be called before
any FindSimilarCode queries.

Inputs:

ctx - Context for cancellation.

Outputs:

error - Non-nil if context is cancelled or graph is not ready.

Performance:

O(n) where n is the number of functions/methods.
Typical: ~1ms per 100 functions.

func (*SimilarityEngine) FindFunctionsLike

func (e *SimilarityEngine) FindFunctionsLike(ctx context.Context, criteria FunctionCriteria) ([]SimilarResult, error)

FindFunctionsLike finds functions that match specific characteristics.

Description:

Searches for functions matching specified criteria like parameter count,
return types, or naming patterns. More flexible than signature-based search.

Inputs:

ctx - Context for cancellation.
criteria - Search criteria.

Outputs:

[]SimilarResult - Matching functions.
error - Non-nil on validation failure.

func (*SimilarityEngine) FindSimilarBySignature

func (e *SimilarityEngine) FindSimilarBySignature(ctx context.Context, signature string, kind ast.SymbolKind, limit int) (*SimilarCode, error)

FindSimilarBySignature finds code similar to a given signature.

Description:

Allows searching for similar code without having a specific symbol ID,
useful for finding implementations that match a desired signature pattern.

Inputs:

ctx - Context for cancellation.
signature - The function signature to search for (e.g., "func(ctx context.Context) error").
kind - The symbol kind (function or method).
limit - Maximum number of results.

Outputs:

*SimilarCode - Results matching the signature pattern.
error - Non-nil on validation failure.

func (*SimilarityEngine) FindSimilarCode

func (e *SimilarityEngine) FindSimilarCode(ctx context.Context, symbolID string, opts ...ExploreOption) (*SimilarCode, error)

FindSimilarCode finds code similar to a target function.

Description:

Uses LSH to find candidate similar functions, then computes exact
similarity scores and returns the top matches with explanations.

Inputs:

ctx - Context for cancellation. Must not be nil.
symbolID - ID of the target function to find similar code for.
opts - Optional configuration (limit via WithMaxNodes).

Outputs:

*SimilarCode - Results including matched traits explaining similarity.
error - Non-nil on validation failure or if symbol not found.

Errors:

ErrInvalidInput - Context is nil or empty symbolID
ErrSymbolNotFound - Symbol not found in index
ErrGraphNotReady - Engine not built

Example:

result, err := engine.FindSimilarCode(ctx, "pkg/handlers.HandleRequest")
for _, match := range result.Results {
    fmt.Printf("%s: %.2f similar (%v)\n", match.ID, match.Similarity, match.MatchedTraits)
}

func (*SimilarityEngine) GetFingerprint

func (e *SimilarityEngine) GetFingerprint(symbolID string) (*ASTFingerprint, bool)

GetFingerprint returns the fingerprint for a symbol.

Description:

Returns the pre-computed fingerprint for a symbol, or computes
it on demand if not in the index.

Inputs:

symbolID - The symbol ID.

Outputs:

*ASTFingerprint - The fingerprint, nil if symbol not found.
bool - True if fingerprint was found or computed.

func (*SimilarityEngine) IsBuilt

func (e *SimilarityEngine) IsBuilt() bool

IsBuilt returns true if the engine has been built.

func (*SimilarityEngine) Stats

Stats returns statistics about the similarity engine.

type SimilarityEngineStats

type SimilarityEngineStats struct {
	TotalFingerprints int  `json:"total_fingerprints"`
	IndexSize         int  `json:"index_size"`
	Built             bool `json:"built"`
}

SimilarityEngineStats contains statistics about the engine.

type SimilarityMethod

type SimilarityMethod string

SimilarityMethod specifies the similarity algorithm to use.

const (
	// SimilarityStructural uses AST fingerprinting with MinHash LSH.
	// Fast, works offline, focuses on code structure.
	SimilarityStructural SimilarityMethod = "structural"

	// SimilaritySemantic uses embeddings for semantic similarity.
	// Finds functionally similar code even with different structure.
	// Requires embeddings service.
	SimilaritySemantic SimilarityMethod = "semantic"

	// SimilarityHybrid combines structural and semantic methods.
	// Weights: 0.6 structural + 0.4 semantic by default.
	SimilarityHybrid SimilarityMethod = "hybrid"
)

type SinkCategory

type SinkCategory string

SinkCategory categorizes data output sinks.

const (
	// SinkResponse represents HTTP response writes.
	SinkResponse SinkCategory = "response"

	// SinkDatabase represents database writes.
	SinkDatabase SinkCategory = "database"

	// SinkFile represents file writes.
	SinkFile SinkCategory = "file"

	// SinkLog represents logging calls.
	SinkLog SinkCategory = "log"

	// SinkNetwork represents network calls.
	SinkNetwork SinkCategory = "network"

	// SinkCommand represents command execution (dangerous sink).
	SinkCommand SinkCategory = "command"

	// SinkSQL represents SQL query execution (dangerous sink).
	SinkSQL SinkCategory = "sql"

	// SinkUnknown represents unclassified sinks.
	SinkUnknown SinkCategory = "unknown"
)

type SinkPattern

type SinkPattern struct {
	// Category is the sink category (response, database, file, log, etc.).
	Category SinkCategory

	// FunctionName is a pattern for the function/method name.
	FunctionName string

	// Receiver is a pattern for the receiver type (for methods).
	Receiver string

	// Package is a pattern for the package containing the function.
	Package string

	// Signature is a pattern for the function signature.
	Signature string

	// Description explains what this sink represents.
	Description string

	// IsDangerous indicates if this sink could be a security risk with untrusted data.
	IsDangerous bool

	// Confidence is the base confidence level for matches (0.0-1.0).
	Confidence float64
	// contains filtered or unexported fields
}

SinkPattern defines a pattern for identifying data sinks.

func DefaultGoSinkPatterns

func DefaultGoSinkPatterns() []SinkPattern

DefaultGoSinkPatterns returns default data sink patterns for Go.

func DefaultPythonSinkPatterns

func DefaultPythonSinkPatterns() []SinkPattern

DefaultPythonSinkPatterns returns default data sink patterns for Python.

func DefaultTypeScriptSinkPatterns

func DefaultTypeScriptSinkPatterns() []SinkPattern

DefaultTypeScriptSinkPatterns returns default data sink patterns for TypeScript/JavaScript.

func (*SinkPattern) Match

func (p *SinkPattern) Match(sym *ast.Symbol) bool

Match checks if a symbol matches this sink pattern.

type SinkRegistry

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

SinkRegistry holds patterns for identifying data sinks.

Thread Safety:

SinkRegistry is safe for concurrent read access after initialization.
Do not modify patterns after construction.

func NewSinkRegistry

func NewSinkRegistry() *SinkRegistry

NewSinkRegistry creates a new SinkRegistry with default patterns.

func (*SinkRegistry) GetDangerousSinks

func (r *SinkRegistry) GetDangerousSinks(language string) []SinkPattern

GetDangerousSinks returns all sink patterns that are marked as dangerous.

func (*SinkRegistry) GetPatterns

func (r *SinkRegistry) GetPatterns(language string) []SinkPattern

GetPatterns returns sink patterns for a language.

func (*SinkRegistry) Languages

func (r *SinkRegistry) Languages() []string

Languages returns all registered languages.

func (*SinkRegistry) MatchSink

func (r *SinkRegistry) MatchSink(sym *ast.Symbol) (*SinkPattern, bool)

MatchSink checks if a symbol matches any sink pattern.

func (*SinkRegistry) RegisterPatterns

func (r *SinkRegistry) RegisterPatterns(language string, patterns []SinkPattern)

RegisterPatterns adds patterns for a language.

type SourceCategory

type SourceCategory string

SourceCategory categorizes data input sources.

const (
	// SourceHTTP represents HTTP request data (body, query, headers, form).
	SourceHTTP SourceCategory = "http_input"

	// SourceEnv represents environment variable reads.
	SourceEnv SourceCategory = "env_var"

	// SourceFile represents file reads.
	SourceFile SourceCategory = "file_read"

	// SourceCLI represents command line arguments.
	SourceCLI SourceCategory = "cli_arg"

	// SourceDB represents database query results.
	SourceDB SourceCategory = "db_result"

	// SourceWebSocket represents WebSocket message data.
	SourceWebSocket SourceCategory = "websocket"

	// SourceUnknown represents unclassified sources.
	SourceUnknown SourceCategory = "unknown"
)

type SourcePattern

type SourcePattern struct {
	// Category is the source category (http_input, env_var, file_read, etc.).
	Category SourceCategory

	// FunctionName is a pattern for the function/method name.
	FunctionName string

	// Receiver is a pattern for the receiver type (for methods).
	Receiver string

	// Package is a pattern for the package containing the function.
	Package string

	// Signature is a pattern for the function signature.
	Signature string

	// Description explains what this source represents.
	Description string

	// Confidence is the base confidence level for matches (0.0-1.0).
	Confidence float64
	// contains filtered or unexported fields
}

SourcePattern defines a pattern for identifying data sources.

func DefaultGoSourcePatterns

func DefaultGoSourcePatterns() []SourcePattern

DefaultGoSourcePatterns returns default data source patterns for Go.

func DefaultPythonSourcePatterns

func DefaultPythonSourcePatterns() []SourcePattern

DefaultPythonSourcePatterns returns default data source patterns for Python.

func DefaultTypeScriptSourcePatterns

func DefaultTypeScriptSourcePatterns() []SourcePattern

DefaultTypeScriptSourcePatterns returns default data source patterns for TypeScript/JavaScript.

func (*SourcePattern) Match

func (p *SourcePattern) Match(sym *ast.Symbol) bool

Match checks if a symbol matches this source pattern.

type SourceRegistry

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

SourceRegistry holds patterns for identifying data sources.

Thread Safety:

SourceRegistry is safe for concurrent read access after initialization.
Do not modify patterns after construction.

func NewSourceRegistry

func NewSourceRegistry() *SourceRegistry

NewSourceRegistry creates a new SourceRegistry with default patterns.

func (*SourceRegistry) GetPatterns

func (r *SourceRegistry) GetPatterns(language string) []SourcePattern

GetPatterns returns source patterns for a language.

func (*SourceRegistry) Languages

func (r *SourceRegistry) Languages() []string

Languages returns all registered languages.

func (*SourceRegistry) MatchSource

func (r *SourceRegistry) MatchSource(sym *ast.Symbol) (*SourcePattern, bool)

MatchSource checks if a symbol matches any source pattern.

func (*SourceRegistry) RegisterPatterns

func (r *SourceRegistry) RegisterPatterns(language string, patterns []SourcePattern)

RegisterPatterns adds patterns for a language.

type TypeBrief

type TypeBrief struct {
	// Name is the type name.
	Name string `json:"name"`

	// Kind is the type kind (struct, interface, alias).
	Kind string `json:"kind"`

	// Fields is the number of fields (for structs).
	Fields int `json:"fields"`

	// Methods lists method names.
	Methods []string `json:"methods"`
}

TypeBrief provides a brief summary of a type.

Jump to

Keyboard shortcuts

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