core

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Feb 7, 2026 License: MIT Imports: 36 Imported by: 0

Documentation

Overview

Testing infrastructure for FileContentStore - provides builder API for creating mock file systems in memory without disk I/O.

This enables fast, deterministic testing of indexing pipelines and dependent services.

Index

Constants

View Source
const (
	DefaultBatchSize     = 100  // Batch size for processing symbol updates
	DefaultChannelSize   = 1000 // Channel size for update queue
	DefaultMinStemLength = 3    // Minimum length for word stemming
)

Configuration constants for SemanticSearchIndex

View Source
const (
	// DefaultMaxNodes is the default maximum number of nodes in the Universal Symbol Graph
	DefaultMaxNodes = 100000 // 100k nodes should handle most large codebases
)

Variables

View Source
var (
	ErrSymbolNotFound  = &LookupError{Code: "SYMBOL_NOT_FOUND", Message: "symbol not found in index", Field: "object_id", Fatal: true}
	ErrSymbolNotInFile = &LookupError{Code: "SYMBOL_NOT_IN_FILE", Message: "symbol exists but not in specified file", Field: "object_id", Fatal: true}
	ErrRefTrackerNil   = &LookupError{Code: "REF_TRACKER_NIL", Message: "reference tracker not initialized - call graph unavailable", Field: "relationships", Fatal: false}
	ErrCallGraphEmpty  = &LookupError{Code: "CALL_GRAPH_EMPTY", Message: "call graph index is empty - relationships not indexed", Field: "relationships", Fatal: false}
	ErrNotAFunction    = &LookupError{Code: "NOT_A_FUNCTION", Message: "caller/callee queries only apply to functions and methods", Field: "caller_functions", Fatal: false}
	ErrSymbolIndexNil  = &LookupError{Code: "SYMBOL_INDEX_NIL", Message: "symbol index not initialized", Field: "basic_info", Fatal: true}
	ErrFileServiceNil  = &LookupError{Code: "FILE_SERVICE_NIL", Message: "file service not initialized", Field: "structure", Fatal: false}
)

Standard lookup error codes

View Source
var BuiltInTemplates = map[string]*ConfigTemplate{
	"web-application": {
		Name:        "Web Application",
		Description: "Configuration optimized for web application analysis with correct propagation semantics",
		Version:     "2.0",
		Config: &PropagationConfig{
			MaxIterations:        15,
			ConvergenceThreshold: 0.001,
			DefaultDecay:         0.8,
			LabelRules: []LabelPropagationRule{
				{
					Label:                "critical-bug",
					Direction:            "upstream",
					Mode:                 ModeReachability,
					MaxHops:              0,
					Priority:             3,
					Conditions:           []string{"critical"},
					IncludeTypeHierarchy: true,
				},
				{
					Label:                "security-vulnerability",
					Direction:            "upstream",
					Mode:                 ModeReachability,
					MaxHops:              0,
					Priority:             3,
					Conditions:           []string{"security"},
					IncludeTypeHierarchy: true,
				},
				{
					Label:                "authentication",
					Direction:            "upstream",
					Mode:                 ModeReachability,
					MaxHops:              0,
					Priority:             3,
					Conditions:           []string{"security"},
					IncludeTypeHierarchy: true,
				},
				{
					Label:                "database-calls",
					Direction:            "upstream",
					Mode:                 ModeAccumulation,
					MaxHops:              0,
					Priority:             2,
					IncludeTypeHierarchy: true,
				},
				{
					Label:                "api-calls",
					Direction:            "upstream",
					Mode:                 ModeAccumulation,
					MaxHops:              0,
					Priority:             2,
					IncludeTypeHierarchy: true,
				},
				{
					Label:                "api-endpoint",
					Direction:            "downstream",
					Mode:                 ModeReachability,
					MaxHops:              10,
					Priority:             2,
					Conditions:           []string{"public"},
					IncludeTypeHierarchy: true,
				},
				{
					Label:                "checkout-flow",
					Direction:            "upstream",
					Mode:                 ModeReachability,
					MaxHops:              0,
					Boost:                1.2,
					Priority:             3,
					Conditions:           []string{"payment", "critical"},
					IncludeTypeHierarchy: true,
				},
				{
					Label:                "ui-search-relevance",
					Direction:            "bidirectional",
					Mode:                 ModeDecay,
					Decay:                0.7,
					MaxHops:              6,
					MinStrength:          0.1,
					Priority:             1,
					IncludeTypeHierarchy: false,
				},
			},
			DependencyRules: []DependencyPropagationRule{
				{
					DependencyType: "database",
					Direction:      "upstream",
					Aggregation:    "sum",
					WeightFunction: "exponential",
					MaxDepth:       5,
					Threshold:      0.1,
				},
				{
					DependencyType: "external-api",
					Direction:      "upstream",
					Aggregation:    "unique",
					WeightFunction: "linear",
					MaxDepth:       4,
					Threshold:      0.15,
				},
				{
					DependencyType: "cache",
					Direction:      "upstream",
					Aggregation:    "max",
					WeightFunction: "exponential",
					MaxDepth:       3,
					Threshold:      0.2,
				},
			},
			CustomRules: []CustomPropagationRule{
				{
					Name:        "critical-path-boost",
					Description: "Boost propagation for critical business paths",
					Trigger:     "has_label(checkout) OR has_label(payment)",
					Action:      "multiply_strength(1.3)",
					Parameters:  map[string]interface{}{"boost_factor": 1.3},
					Priority:    1,
				},
			},
			AnalysisConfig: AnalysisConfig{
				DetectEntryPoints:   true,
				CalculateDepth:      true,
				FindCriticalPaths:   true,
				EntryPointLabels:    []string{"api-endpoint", "handler", "controller", "route"},
				CriticalLabels:      []string{"checkout", "payment", "authentication", "security"},
				HighImpactThreshold: 0.6,
			},
		},
	},

	"microservices": {
		Name:        "Microservices Architecture",
		Description: "Configuration for microservices-based systems with proper dependency tracking",
		Version:     "2.0",
		Config: &PropagationConfig{
			MaxIterations:        12,
			ConvergenceThreshold: 0.002,
			DefaultDecay:         0.75,
			LabelRules: []LabelPropagationRule{
				{
					Label:                "service-boundary",
					Direction:            "bidirectional",
					Mode:                 ModeReachability,
					MaxHops:              2,
					Priority:             3,
					IncludeTypeHierarchy: true,
				},
				{
					Label:                "cross-service-call",
					Direction:            "upstream",
					Mode:                 ModeAccumulation,
					MaxHops:              8,
					Priority:             2,
					IncludeTypeHierarchy: true,
				},
				{
					Label:                "distributed-transaction",
					Direction:            "upstream",
					Mode:                 ModeReachability,
					MaxHops:              0,
					Priority:             3,
					IncludeTypeHierarchy: true,
				},
				{
					Label:                "public-api",
					Direction:            "downstream",
					Mode:                 ModeReachability,
					MaxHops:              4,
					Priority:             2,
					IncludeTypeHierarchy: true,
				},
				{
					Label:                "service-importance",
					Direction:            "upstream",
					Mode:                 ModeMax,
					MaxHops:              0,
					Priority:             2,
					IncludeTypeHierarchy: true,
				},
			},
			DependencyRules: []DependencyPropagationRule{
				{
					DependencyType: "service",
					Direction:      "upstream",
					Aggregation:    "unique",
					WeightFunction: "linear",
					MaxDepth:       6,
					Threshold:      0.1,
				},
				{
					DependencyType: "database",
					Direction:      "upstream",
					Aggregation:    "sum",
					WeightFunction: "exponential",
					MaxDepth:       3,
					Threshold:      0.2,
				},
				{
					DependencyType: "message-queue",
					Direction:      "bidirectional",
					Aggregation:    "unique",
					WeightFunction: "linear",
					MaxDepth:       5,
					Threshold:      0.15,
				},
			},
			AnalysisConfig: AnalysisConfig{
				DetectEntryPoints:   true,
				CalculateDepth:      true,
				FindCriticalPaths:   true,
				EntryPointLabels:    []string{"api-gateway", "service-entry", "public-endpoint"},
				CriticalLabels:      []string{"cross-service", "data-consistency", "transaction"},
				HighImpactThreshold: 0.5,
			},
		},
	},

	"library-analysis": {
		Name:        "Library/SDK Analysis",
		Description: "Configuration for analyzing libraries and SDKs with API stability tracking",
		Version:     "2.0",
		Config: &PropagationConfig{
			MaxIterations:        8,
			ConvergenceThreshold: 0.005,
			DefaultDecay:         0.9,
			LabelRules: []LabelPropagationRule{
				{
					Label:                "public-api",
					Direction:            "downstream",
					Mode:                 ModeReachability,
					MaxHops:              10,
					Priority:             2,
					IncludeTypeHierarchy: true,
				},
				{
					Label:                "breaking-change",
					Direction:            "upstream",
					Mode:                 ModeReachability,
					MaxHops:              0,
					Priority:             3,
					IncludeTypeHierarchy: true,
				},
				{
					Label:                "deprecated",
					Direction:            "upstream",
					Mode:                 ModeReachability,
					MaxHops:              5,
					Priority:             3,
					IncludeTypeHierarchy: true,
				},
				{
					Label:                "internal-only",
					Direction:            "bidirectional",
					Mode:                 ModeReachability,
					MaxHops:              3,
					Priority:             1,
					IncludeTypeHierarchy: false,
				},
				{
					Label:                "complexity-score",
					Direction:            "upstream",
					Mode:                 ModeAccumulation,
					MaxHops:              0,
					Priority:             2,
					IncludeTypeHierarchy: true,
				},
			},
			DependencyRules: []DependencyPropagationRule{
				{
					DependencyType: "external-dependency",
					Direction:      "upstream",
					Aggregation:    "unique",
					WeightFunction: "linear",
					MaxDepth:       4,
					Threshold:      0.1,
				},
			},
			AnalysisConfig: AnalysisConfig{
				DetectEntryPoints:   true,
				CalculateDepth:      false,
				FindCriticalPaths:   false,
				EntryPointLabels:    []string{"public-api", "exported"},
				CriticalLabels:      []string{"breaking-change", "deprecated"},
				HighImpactThreshold: 0.8,
			},
		},
	},
}

BuiltInTemplates provides common configuration templates

Functions

func CoordinationInfoEnabled

func CoordinationInfoEnabled() bool

CoordinationInfoEnabled returns true if coordination info logging is enabled. Use this to guard expensive fmt.Sprintf calls before LogCoordinationInfo.

func CountLines

func CountLines(data []byte) int

CountLines counts the number of lines in content without allocation. This is a fast single-pass count that can be used to pre-allocate slices. Uses bytes.Count for optimal performance (SIMD on supported platforms).

func CountLinesMatching

func CountLinesMatching(data []byte, predicate func(line []byte) bool) int

CountLinesMatching counts lines that match a predicate.

func CountLinesWithCallback

func CountLinesWithCallback(data []byte, callback func(line []byte, lineNum int) bool) int

CountLinesWithCallback counts lines while calling a callback for each. This is useful when you need to both count and process in a single pass. The callback receives the line bytes and 1-based line number. Returning false from the callback stops iteration.

func DenseStats

func DenseStats() map[string]interface{}

DenseStats provides information about the dense object ID system

func ExpandAbbreviations

func ExpandAbbreviations(words []string, abbreviations map[string][]string) []string

ExpandAbbreviations expands known abbreviations in words

func FilterCallReferences

func FilterCallReferences(refs []types.Reference) []types.Reference

FilterCallReferences filters references to only include function calls

func FindLine

func FindLine(data []byte, predicate func(line []byte) bool) ([]byte, int, bool)

FindLine finds the first line matching a predicate. Returns the line bytes, line number (1-based), and ok=true if found.

func FindLineContaining

func FindLineContaining(data []byte, substr []byte) ([]byte, int, bool)

FindLineContaining finds the first line containing the given substring. Returns the line bytes, line number (1-based), and ok=true if found.

func ForEachLine

func ForEachLine(data []byte, callback func(line []byte, lineNum int) bool)

ForEachLine iterates over lines calling the callback for each. This is a convenience function for common iteration patterns. Returning false from the callback stops iteration.

func FormatUnifiedResults

func FormatUnifiedResults(result *UnifiedSearchResult) string

FormatUnifiedResults creates a human-readable format for combined results

func GeneratePhonetic

func GeneratePhonetic(name string) string

GeneratePhonetic generates a phonetic code for fuzzy matching Uses simplified Soundex algorithm for performance

func GetLineAtOffset

func GetLineAtOffset(offsets []uint32, byteOffset int) int

GetLineAtOffset returns the line number (1-based) for a given byte offset. Uses binary search on pre-computed offsets for O(log n) performance.

func GetLineBytesRange

func GetLineBytesRange(data []byte, start, end int) [][]byte

GetLineBytesRange returns lines as byte slices from start to end (inclusive, 1-based). Each returned slice is a view into the original data (zero-copy).

func GetLineOffsets

func GetLineOffsets(data []byte) []uint32

GetLineOffsets returns byte offsets for the start of each line. This is compatible with the existing computeLineOffsets but uses LineScanner.

func GetLineRange

func GetLineRange(data []byte, start, end int) []string

GetLineRange returns lines from start to end (inclusive, 1-based). Pre-allocates the result slice for efficiency.

func GetRetryDelay

func GetRetryDelay(err error, attempt int) time.Duration

GetRetryDelay calculates appropriate retry delay based on error type and context

func GetSystemLoad

func GetSystemLoad() int

GetSystemLoad gets current system load (0-100 scale)

func HashInt64FNV1a

func HashInt64FNV1a(h uint64, val int64) uint64

HashInt64FNV1a incorporates an int64 value into an existing FNV-1a hash. Returns the updated hash value.

func HashStringFNV1a

func HashStringFNV1a(s string) uint64

HashStringFNV1a computes the FNV-1a hash of a string without allocations. This is a reusable helper for computing string hashes inline.

func InitializePerformanceOptimizations

func InitializePerformanceOptimizations()

InitializePerformanceOptimizations initializes all performance optimizations

func IsCoordinationError

func IsCoordinationError(err error) bool

IsCoordinationError checks if an error is a coordination error

func IsExcludedFromAnalysisByAnnotation

func IsExcludedFromAnalysisByAnnotation(annotation *SemanticAnnotation, analysisType string) bool

IsExcludedFromAnalysisByAnnotation checks if an annotation excludes a specific analysis type. This is a standalone function for use when the annotation is already available.

func IsTemplateStringQuery

func IsTemplateStringQuery(pattern string) bool

IsTemplateStringQuery checks if a search pattern is likely a SQL or GraphQL query

func LogCoordinationError

func LogCoordinationError(err *CoordinationError)

LogCoordinationError logs a coordination error using the global error handler

func LogCoordinationInfo

func LogCoordinationInfo(message string, context ErrorContext)

LogCoordinationInfo logs a coordination info message using the global error handler

func LogCoordinationWarning

func LogCoordinationWarning(message string, context ErrorContext)

LogCoordinationWarning logs a coordination warning using the global error handler

func LogHealthCheck

func LogHealthCheck(indexType IndexType, health HealthStatus, availability float64, responseTime time.Duration, issues []string)

LogHealthCheck logs health checks using the global logger

func LogIndexOperation

func LogIndexOperation(indexType IndexType, operation string, startTime time.Time, duration time.Duration, success bool, details map[string]interface{})

LogIndexOperation logs index operations using the global logger

func LogIndexStateChange

func LogIndexStateChange(indexType IndexType, oldStatus, newStatus string, context map[string]interface{})

LogIndexStateChange logs index state changes using the global logger

func LogLockOperation

func LogLockOperation(indexType IndexType, lockType LockType, operation string, waitTime time.Duration, acquired bool, queueDepth int)

LogLockOperation logs lock operations using the global logger

func LogMetricsSnapshot

func LogMetricsSnapshot(indexType IndexType, metrics map[string]interface{})

LogMetricsSnapshot logs metrics snapshots using the global logger

func LogQueueOperation

func LogQueueOperation(operation string, queueDepth, maxDepth int, avgWaitTime time.Duration, details map[string]interface{})

LogQueueOperation logs queue operations using the global logger

func NewFNV1aHash

func NewFNV1aHash() uint64

NewFNV1aHash returns a new FNV-1a hash starting with the offset basis.

func SetCoordinationConfig

func SetCoordinationConfig(config *IndexCoordinationConfig)

SetCoordinationConfig updates the global coordination configuration

func SetGlobalErrorHandler

func SetGlobalErrorHandler(handler *ErrorHandler)

SetGlobalErrorHandler sets the global error handler

func SetGlobalIndexSystemLogger

func SetGlobalIndexSystemLogger(logger *IndexSystemLogger)

SetGlobalIndexSystemLogger sets the global index system logger

func SortByConfidence

func SortByConfidence(refs []ObjectReference)

Sort references by confidence (descending)

func SplitLinesBytesWithCapacity

func SplitLinesBytesWithCapacity(data []byte) [][]byte

SplitLinesBytesWithCapacity splits content into byte slices with pre-allocated capacity. Returns [][]byte where each slice is a view into the original data (zero-copy for bytes). Note: The returned byte slices share memory with the input data.

func SplitLinesWithCapacity

func SplitLinesWithCapacity(data []byte) []string

SplitLinesWithCapacity splits content into lines with pre-allocated capacity. This is an optimized replacement for strings.Split(s, "\n") that: 1. Counts lines first in a single pass 2. Pre-allocates the result slice 3. Populates without reallocation

Use this when you need a []string result but want to avoid reallocation.

func SplitSymbolName

func SplitSymbolName(name string) []string

SplitSymbolName splits a symbol name into constituent words Uses simplified algorithm optimized for indexing phase

func StemWords

func StemWords(words []string, minLength int) []string

StemWords applies Porter2 stemming to words

Types

type AIContext

type AIContext struct {
	NaturalLanguageSummary string            `json:"natural_language_summary"`
	SimilarObjects         []ObjectReference `json:"similar_objects"`
	RefactoringSuggestions []string          `json:"refactoring_suggestions"`
	CodeSmells             []CodeSmell       `json:"code_smells"`
	BestPractices          []string          `json:"best_practices"`
}

AIContext provides AI-enhanced understanding

type ASTContentFilter

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

ASTContentFilter provides AST-based content filtering for searches

func NewASTContentFilter

func NewASTContentFilter(astStore *ASTStore) *ASTContentFilter

NewASTContentFilter creates a new AST-based content filter

func (*ASTContentFilter) ExtractContentByType

func (acf *ASTContentFilter) ExtractContentByType(fileID types.FileID, content []byte, contentType ContentType) ([]ContentRange, error)

ExtractContentByType extracts specific content types from a file using its AST

func (*ASTContentFilter) ExtractGraphQLQueries

func (acf *ASTContentFilter) ExtractGraphQLQueries(fileID types.FileID, content []byte) ([]TemplateStringInfo, error)

ExtractGraphQLQueries finds GraphQL queries in template strings using AST

func (*ASTContentFilter) ExtractSQLQueries

func (acf *ASTContentFilter) ExtractSQLQueries(fileID types.FileID, content []byte) ([]TemplateStringInfo, error)

ExtractSQLQueries finds SQL queries in template strings using AST

type ASTStore

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

ASTStore maintains per-file AST trees for Tree-sitter queries Optimized for incremental updates - easy to add/remove/update individual files Content is accessed from FileContentStore to avoid duplication

LOCK-FREE DESIGN: During indexing, this store follows single-writer pattern where only the integrator modifies the maps while processors read content. We eliminate mutexes and use atomic snapshots for safe concurrent access.

func NewASTStore

func NewASTStore(fileContentStore *FileContentStore) *ASTStore

NewASTStore creates a new AST store with reference to FileContentStore

func (*ASTStore) Clear

func (as *ASTStore) Clear()

Clear removes all stored ASTs and associated data LOCK-FREE: Single-writer constraint - only called during shutdown/reset operations

func (*ASTStore) ExecuteQuery

func (as *ASTStore) ExecuteQuery(queryStr string, fileIDs []types.FileID, language string) ([]QueryResult, error)

ExecuteQuery runs a Tree-sitter query across all files or specific files LOCK-FREE: Maps are immutable after indexing, safe to read without synchronization

func (*ASTStore) GetAST

func (as *ASTStore) GetAST(fileID types.FileID) (*tree_sitter.Tree, []byte, string, string, bool)

GetAST retrieves the AST for a file (content accessed from FileContentStore) LOCK-FREE: Maps are immutable after indexing, safe to read without synchronization

func (*ASTStore) GetAllFiles

func (as *ASTStore) GetAllFiles() []types.FileID

GetAllFiles returns all file IDs that have ASTs stored LOCK-FREE: Maps are immutable after indexing, safe to read without synchronization

func (*ASTStore) GetFileCount

func (as *ASTStore) GetFileCount() int

GetFileCount returns the number of files with stored ASTs LOCK-FREE: Maps are immutable after indexing, safe to read without synchronization

func (*ASTStore) GetMemoryStats

func (as *ASTStore) GetMemoryStats() map[string]interface{}

GetMemoryStats returns memory usage statistics (content not duplicated) LOCK-FREE: Maps are immutable after indexing, safe to read without synchronization

func (*ASTStore) GetSupportedLanguages

func (as *ASTStore) GetSupportedLanguages() []string

GetSupportedLanguages returns the languages currently indexed LOCK-FREE: Maps are immutable after indexing, safe to read without synchronization

func (*ASTStore) RemoveFile

func (as *ASTStore) RemoveFile(fileID types.FileID)

RemoveFile removes all data for a file (for incremental updates) LOCK-FREE: Single-writer constraint during indexing - only integrator calls this

func (*ASTStore) Shutdown

func (as *ASTStore) Shutdown() error

Shutdown performs graceful shutdown with resource cleanup

func (*ASTStore) StoreAST

func (as *ASTStore) StoreAST(fileID types.FileID, ast *tree_sitter.Tree, path string, language string)

StoreAST stores an AST tree for a file (content comes from FileContentStore, no duplication) LOCK-FREE: Single-writer constraint during indexing - only integrator calls this

type AnalysisConfig

type AnalysisConfig struct {
	DetectEntryPoints   bool     `json:"detect_entry_points"`
	CalculateDepth      bool     `json:"calculate_depth"`
	FindCriticalPaths   bool     `json:"find_critical_paths"`
	EntryPointLabels    []string `json:"entry_point_labels"`    // Labels that indicate entry points
	CriticalLabels      []string `json:"critical_labels"`       // Labels that indicate critical functionality
	HighImpactThreshold float64  `json:"high_impact_threshold"` // Threshold for high-impact classification
}

AnalysisConfig controls high-level analysis features

type AnalysisContext

type AnalysisContext struct {
	Domain       string   `json:"domain"`       // ui, api, data, etc.
	Framework    string   `json:"framework"`    // detected framework (if any)
	Language     string   `json:"language"`     // programming language
	FileType     string   `json:"file_type"`    // source, test, config, etc.
	Complexity   string   `json:"complexity"`   // low, medium, high
	Dependencies []string `json:"dependencies"` // key dependencies detected
}

AnalysisContext provides contextual information for intent analysis

type AnnotatedSymbol

type AnnotatedSymbol struct {
	FileID     types.FileID        `json:"file_id"`
	SymbolID   types.SymbolID      `json:"symbol_id"`
	Symbol     types.Symbol        `json:"symbol"`
	Annotation *SemanticAnnotation `json:"annotation"`
	FilePath   string              `json:"file_path"`
}

AnnotatedSymbol represents a symbol with its semantic annotations

type AnnotationLocation

type AnnotationLocation struct {
	FileID    types.FileID   `json:"file_id"`
	SymbolID  types.SymbolID `json:"symbol_id"`
	StartLine int            `json:"start_line"`
	EndLine   int            `json:"end_line"`
	Context   string         `json:"context"`
}

AnnotationLocation specifies where an annotation was found

type AntiPattern

type AntiPattern struct {
	Name        string   `json:"name"`
	Description string   `json:"description"`
	Category    string   `json:"category"`    // performance, security, maintainability
	Patterns    []string `json:"patterns"`    // Regex patterns that indicate anti-pattern
	Contexts    []string `json:"contexts"`    // Where this anti-pattern applies
	Severity    string   `json:"severity"`    // critical, high, medium, low
	Remediation string   `json:"remediation"` // How to fix the anti-pattern
	Examples    []string `json:"examples"`    // Examples of the anti-pattern
}

AntiPattern defines problematic code patterns that violate best practices

type ArchitecturalPattern

type ArchitecturalPattern struct {
	Name        string
	Description string
	Scope       []string      // File patterns this applies to
	Rules       []PatternRule // Rules that must be satisfied
}

ArchitecturalPattern defines common architectural patterns

type ArchitectureOverview

type ArchitectureOverview struct {
	Components   []string               `json:"components"`
	Patterns     []string               `json:"patterns"`
	Dependencies []string               `json:"dependencies"`
	Structure    map[string]interface{} `json:"structure"`
	Complexity   string                 `json:"complexity"`
}

ArchitectureOverview provides high-level architectural context

type AssemblyResult

type AssemblyResult struct {
	Fragments []Fragment           // The fragments that could assemble the string
	Coverage  float64              // Percentage of target string covered
	Pattern   string               // Assembly pattern detected (concat, format, template)
	Score     float64              // Overall confidence score
	FileID    uint32               // File containing the assembly
	Location  types.SymbolLocation // Primary location of assembly
	Context   string               // Code snippet showing assembly
	GroupID   int                  // For grouping related results
}

AssemblyResult represents a potential string assembly match

type AssemblySearchEngine

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

AssemblySearchEngine performs reverse string assembly search

func NewAssemblySearchEngine

func NewAssemblySearchEngine(
	trigramIndex *TrigramIndex,
	symbolIndex *SymbolIndex,
	fileProvider FileProvider,
) *AssemblySearchEngine

NewAssemblySearchEngine creates a new assembly search engine

func (*AssemblySearchEngine) Search

Search performs assembly search for dynamically built strings

type AssemblySearchParams

type AssemblySearchParams struct {
	Pattern           string   // The target string to search for
	MinCoverage       float64  // Minimum coverage threshold (0.0-1.0)
	MinFragmentLength int      // Minimum fragment size in characters
	MaxResults        int      // Maximum number of results to return
	Languages         []string // Language filters (empty = all)
}

SearchParams configures assembly search behavior

type BatchLoadResult

type BatchLoadResult struct {
	Loaded     []LoadResult
	Failed     []LoadResult
	Skipped    []string
	TotalFiles int
}

BatchLoadResult contains the results of batch loading

type BucketedTrigramData

type BucketedTrigramData struct {
	Trigrams map[uint32][]uint32 // trigramHash -> []offsets
}

BucketedTrigramData holds trigrams for a specific bucket from one file

type BucketedTrigramResult

type BucketedTrigramResult struct {
	FileID  types.FileID
	Buckets []BucketedTrigramData // One per bucket (sparse - only populated buckets have data)
}

BucketedTrigramResult is produced by processors with pre-sharded trigrams

type ChangeImpactInfo

type ChangeImpactInfo struct {
	BreakingChangeRisk  string   `json:"breaking_change_risk"` // "low", "medium", "high"
	DependentComponents []string `json:"dependent_components"`
	EstimatedImpact     int      `json:"estimated_impact"` // 1-10 scale
	RequiresTests       bool     `json:"requires_tests"`
}

type CodeExample

type CodeExample struct {
	FilePath    string `json:"file_path"`
	Function    string `json:"function,omitempty"`
	Purpose     string `json:"purpose"`
	Code        string `json:"code"`
	Explanation string `json:"explanation"`
	Relevance   string `json:"relevance"`
	LineRange   string `json:"line_range"`
}

CodeExample represents a contextually relevant code snippet

type CodeObjectContext

type CodeObjectContext struct {
	// Basic identification
	ObjectID      CodeObjectID         `json:"object_id"`
	Signature     string               `json:"signature"`
	Documentation string               `json:"documentation"`
	Location      types.SymbolLocation `json:"location"`

	// Direct relationships
	DirectRelationships DirectRelationships `json:"direct_relationships"`

	// Variable and data context
	VariableContext VariableContext `json:"variable_context"`

	// Semantic and dependency context
	SemanticContext SemanticContext `json:"semantic_context"`

	// Code structure context
	StructureContext StructureContext `json:"structure_context"`

	// Usage and impact analysis
	UsageAnalysis UsageAnalysis `json:"usage_analysis"`

	// AI-enhanced context
	AIContext AIContext `json:"ai_context"`

	// Metadata
	GeneratedAt    time.Time `json:"generated_at"`
	ContextVersion string    `json:"context_version"`

	// Diagnostics - reports any issues encountered during lookup
	Diagnostics *LookupDiagnostics `json:"diagnostics,omitempty"`
}

CodeObjectContext provides comprehensive context about a code object

type CodeObjectID

type CodeObjectID struct {
	FileID   types.FileID     `json:"file_id"`
	SymbolID string           `json:"symbol_id"` // Unique symbol identifier
	Name     string           `json:"name"`      // Human-readable name
	Type     types.SymbolType `json:"type"`      // Function, Class, Method, etc.
}

CodeObjectID uniquely identifies a code object (function, class, type, etc.)

func (CodeObjectID) IsValid

func (obj CodeObjectID) IsValid() bool

func (CodeObjectID) String

func (obj CodeObjectID) String() string

type CodeSmell

type CodeSmell struct {
	Type        string               `json:"type"` // "long-function", "god-class", etc."
	Description string               `json:"description"`
	Severity    string               `json:"severity"` // "low", "medium", "high", "critical"`
	Location    types.SymbolLocation `json:"location"`
}

type ColumnRange

type ColumnRange struct {
	Start int
	End   int
}

ColumnRange represents a column span

func (ColumnRange) Eq

func (cr ColumnRange) Eq(other ColumnRange) bool

Eq checks if two ColumnRanges are equal

type ComplexityMetrics

type ComplexityMetrics struct {
	CyclomaticComplexity int `json:"cyclomatic_complexity"`
	CognitiveComplexity  int `json:"cognitive_complexity"`
	LineCount            int `json:"line_count"`
	ParameterCount       int `json:"parameter_count"`
	NestingDepth         int `json:"nesting_depth"`
}

type ComponentDetector

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

ComponentDetector identifies semantic components in codebases using AST analysis and naming patterns

func NewComponentDetector

func NewComponentDetector() *ComponentDetector

NewComponentDetector creates a new component detector with shared cached rules

func (*ComponentDetector) DetectComponents

func (cd *ComponentDetector) DetectComponents(files map[types.FileID]string, symbols map[types.FileID][]types.Symbol, options types.ComponentSearchOptions) ([]types.ComponentInfo, error)

DetectComponents analyzes files and symbols to identify semantic components

type ConfigTemplate

type ConfigTemplate struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	Version     string                 `json:"version"`
	Config      *PropagationConfig     `json:"config"`
	Variables   map[string]interface{} `json:"variables,omitempty"`
	Extends     string                 `json:"extends,omitempty"`
}

ConfigTemplate represents a reusable configuration template

type ContentFilter

type ContentFilter struct {
	CommentsOnly    bool // Search only in comments
	CodeOnly        bool // Search only in code (exclude comments and strings)
	StringsOnly     bool // Search only in string literals
	TemplateStrings bool // Include template strings (sql“, gql“, etc.)
	ExcludeComments bool // Exclude comments from search (legacy, kept for compatibility)
}

ContentFilter defines what content types to include/exclude in search

type ContentRange

type ContentRange struct {
	Start   int
	End     int
	Content string
	Type    string // "comment", "string", "template", "code", etc.
	Tag     string // For tagged templates: sql, gql, etc.
}

ContentRange represents a range of content to search

type ContentSegment

type ContentSegment struct {
	Type    string // "comment", "code", "string", "template_string", "all"
	Content string
	Start   int
	End     int
	Tag     string // For template strings: sql, gql, etc.
}

ContentSegment represents a segment of content to search

func FilterContent

func FilterContent(content string, filter ContentFilter) []ContentSegment

FilterContent applies content filtering based on the filter settings

type ContentType

type ContentType int

ContentType represents the type of content to search

const (
	ContentAll ContentType = iota
	ContentCodeOnly
	ContentCommentsOnly
	ContentStringsOnly
	ContentTemplateStringsOnly
)

type ContentUpdate

type ContentUpdate struct {
	Type      UpdateType
	Path      string
	Content   []byte
	FileID    types.FileID
	BatchData []struct {
		Path    string
		Content []byte
	}
	Response chan UpdateResult
}

ContentUpdate represents a file content update request

type ContextAnalyzer

type ContextAnalyzer struct {
	Domain      string                 `json:"domain"` // ui, api, data, etc.
	Description string                 `json:"description"`
	Patterns    []string               `json:"patterns"`     // File/package patterns this applies to
	IntentRules []IntentRule           `json:"intent_rules"` // Domain-specific intent detection
	Metadata    map[string]interface{} `json:"metadata"`
}

ContextAnalyzer provides domain-specific analysis capabilities

type ContextKey

type ContextKey struct {
	Name    string
	FileID  types.FileID
	Context string
}

ContextKey is a zero-allocation key type for Name:FileID:Context lookups

type ContextLookupEngine

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

ContextLookupEngine provides the main interface for code object context lookup

func NewContextLookupEngine

func NewContextLookupEngine(
	symbolIndex *SymbolIndex,
	trigramIndex *TrigramIndex,
	fileService *FileService,
	graphPropagator *GraphPropagator,
	semanticAnnotator *SemanticAnnotator,
	componentDetector *ComponentDetector,
	refTracker *ReferenceTracker,
) *ContextLookupEngine

NewContextLookupEngine creates a new context lookup engine

func (*ContextLookupEngine) GetConfidenceThreshold

func (cle *ContextLookupEngine) GetConfidenceThreshold() float64

GetConfidenceThreshold returns the current confidence threshold

func (*ContextLookupEngine) GetContext

func (cle *ContextLookupEngine) GetContext(objectID CodeObjectID) (*CodeObjectContext, error)

GetContext returns comprehensive context for a code object Errors are reported in Diagnostics field; only fatal errors return error

func (*ContextLookupEngine) GetIncludeAIText

func (cle *ContextLookupEngine) GetIncludeAIText() bool

GetIncludeAIText returns whether AI text is included

func (*ContextLookupEngine) GetMaxContextDepth

func (cle *ContextLookupEngine) GetMaxContextDepth() int

GetMaxContextDepth returns the current max context depth

func (*ContextLookupEngine) SetConfidenceThreshold

func (cle *ContextLookupEngine) SetConfidenceThreshold(threshold float64)

SetConfidenceThreshold sets the minimum confidence threshold

func (*ContextLookupEngine) SetIncludeAIText

func (cle *ContextLookupEngine) SetIncludeAIText(include bool)

SetIncludeAIText sets whether to include AI-generated text

func (*ContextLookupEngine) SetMaxContextDepth

func (cle *ContextLookupEngine) SetMaxContextDepth(depth int)

SetMaxContextDepth sets the maximum depth for relationship analysis

type CoordinationError

type CoordinationError struct {
	Code      ErrorCode    `json:"code"`
	Message   string       `json:"message"`
	Details   string       `json:"details,omitempty"`
	Timestamp time.Time    `json:"timestamp"`
	Retryable bool         `json:"retryable"`
	Context   ErrorContext `json:"context,omitempty"`
}

CoordinationError represents an error that occurs during index coordination

func NewConcurrentLimitError

func NewConcurrentLimitError(current, limit int) *CoordinationError

NewConcurrentLimitError creates a concurrent limit error

func NewCoordinationError

func NewCoordinationError(code ErrorCode, message string) *CoordinationError

NewCoordinationError creates a new coordination error

func NewCoordinationErrorWithDetails

func NewCoordinationErrorWithDetails(code ErrorCode, message, details string) *CoordinationError

NewCoordinationErrorWithDetails creates a new coordination error with details

func NewDeadlockDetectedError

func NewDeadlockDetectedError(operation string, involvedIndexes []IndexType) *CoordinationError

NewDeadlockDetectedError creates a deadlock detected error

func NewIndexUnavailableError

func NewIndexUnavailableError(indexType IndexType, reason string) *CoordinationError

NewIndexUnavailableError creates an index unavailable error

func NewInvalidIndexTypeError

func NewInvalidIndexTypeError(indexType IndexType) *CoordinationError

NewInvalidIndexTypeError creates an invalid index type error

func NewLockTimeoutError

func NewLockTimeoutError(indexType IndexType, lockType LockType, waitTime time.Duration) *CoordinationError

NewLockTimeoutError creates a lock timeout error

func NewLockUnavailableError

func NewLockUnavailableError(indexType IndexType, reason string) *CoordinationError

NewLockUnavailableError creates a lock unavailable error

func NewSystemShutdownError

func NewSystemShutdownError(reason string) *CoordinationError

NewSystemShutdownError creates a system shutdown error

func (*CoordinationError) Error

func (ce *CoordinationError) Error() string

Error implements the error interface

func (*CoordinationError) IsRetryable

func (ce *CoordinationError) IsRetryable() bool

IsRetryable returns whether the error is potentially retryable

func (*CoordinationError) WithContext

func (ce *CoordinationError) WithContext(context ErrorContext) *CoordinationError

WithContext adds context to the coordination error

type CriticalPath

type CriticalPath struct {
	Path        []types.SymbolID       `json:"path"`
	Labels      []string               `json:"labels"`
	TotalImpact float64                `json:"total_impact"`
	Description string                 `json:"description"`
	Metadata    map[string]interface{} `json:"metadata"`
}

CriticalPath represents a high-impact propagation path

type CriticalityInfo

type CriticalityInfo struct {
	IsCritical         bool     `json:"is_critical"`
	CriticalityType    string   `json:"criticality_type"` // "security", "performance", "business-logic"
	ImpactScore        float64  `json:"impact_score"`
	AffectedComponents []string `json:"affected_components"`
}

type CustomPropagationRule

type CustomPropagationRule struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	Trigger     string                 `json:"trigger"` // Trigger condition
	Action      string                 `json:"action"`  // Action to take
	Parameters  map[string]interface{} `json:"parameters"`
	Priority    int                    `json:"priority"`
}

CustomPropagationRule allows custom propagation logic

type DefaultErrorLogger

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

DefaultErrorLogger provides a basic implementation of ErrorLogger using Go's standard log package

func NewDefaultErrorLogger

func NewDefaultErrorLogger() *DefaultErrorLogger

NewDefaultErrorLogger creates a new default error logger with standard output

func (*DefaultErrorLogger) LogError

func (del *DefaultErrorLogger) LogError(err *CoordinationError)

LogError logs a coordination error with detailed context

func (*DefaultErrorLogger) LogInfo

func (del *DefaultErrorLogger) LogInfo(message string, context ErrorContext)

LogInfo logs an info message with context

func (*DefaultErrorLogger) LogWarning

func (del *DefaultErrorLogger) LogWarning(message string, context ErrorContext)

LogWarning logs a warning message with context

type DefaultIndexCoordinator

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

DefaultIndexCoordinator implements the IndexCoordinator interface

func (*DefaultIndexCoordinator) AcquireIndexLock

func (c *DefaultIndexCoordinator) AcquireIndexLock(indexType IndexType, forWriting bool, timeout time.Duration) (LockRelease, error)

AcquireIndexLock acquires a lock for a specific index type

func (*DefaultIndexCoordinator) AcquireIndexLockCtx

func (c *DefaultIndexCoordinator) AcquireIndexLockCtx(ctx context.Context, indexType IndexType, forWriting bool) (LockRelease, error)

AcquireIndexLockCtx acquires a lock for a specific index type with context

func (*DefaultIndexCoordinator) AcquireMultipleLocks

func (c *DefaultIndexCoordinator) AcquireMultipleLocks(requirements SearchRequirements, forWriting bool, timeout time.Duration) (LockRelease, error)

AcquireMultipleLocks acquires locks for multiple index types based on search requirements

func (*DefaultIndexCoordinator) AcquireMultipleLocksCtx

func (c *DefaultIndexCoordinator) AcquireMultipleLocksCtx(ctx context.Context, requirements SearchRequirements, forWriting bool) (LockRelease, error)

AcquireMultipleLocksCtx acquires locks for multiple index types with context

func (*DefaultIndexCoordinator) Close

func (c *DefaultIndexCoordinator) Close() error

Close cleans up coordinator resources

func (*DefaultIndexCoordinator) GetAllIndexHealth

func (c *DefaultIndexCoordinator) GetAllIndexHealth() map[IndexType]IndexHealth

GetAllIndexHealth returns the health status of all indexes

func (*DefaultIndexCoordinator) GetAllIndexStatus

func (c *DefaultIndexCoordinator) GetAllIndexStatus() map[IndexType]IndexStatus

GetAllIndexStatus returns the status of all indexes

func (*DefaultIndexCoordinator) GetConfig

GetConfig returns the current configuration

func (*DefaultIndexCoordinator) GetIndexHealth

func (c *DefaultIndexCoordinator) GetIndexHealth(indexType IndexType) IndexHealth

GetIndexHealth returns the health status of a specific index

func (*DefaultIndexCoordinator) GetIndexStatus

func (c *DefaultIndexCoordinator) GetIndexStatus(indexType IndexType) IndexStatus

GetIndexStatus returns the current status of a specific index

func (*DefaultIndexCoordinator) SetConfig

func (c *DefaultIndexCoordinator) SetConfig(config *IndexCoordinationConfig)

SetConfig updates the coordinator configuration

func (*DefaultIndexCoordinator) WaitForIndex

func (c *DefaultIndexCoordinator) WaitForIndex(indexType IndexType, timeout time.Duration) error

WaitForIndex waits until a specific index is not indexing or timeout occurs

type DenseObjectID

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

DenseObjectID provides high-density symbol-based encoding for code objects Uses variable-length encoding with full character set for maximum density Target: 3-8 character IDs using A-Za-z0-9_ (62 symbols) for human readability

Note: This type uses the consolidated encoding package for base-63 operations.

func NewDenseObjectID

func NewDenseObjectID(fileID uint32, localSymbolID uint32, symbolType uint32) DenseObjectID

NewDenseObjectID creates a dense object ID from file ID and local symbol ID

func (DenseObjectID) ExtractFileID

func (doid DenseObjectID) ExtractFileID() types.FileID

ExtractFileID extracts the file ID from dense object ID

func (DenseObjectID) ExtractLocalSymbolID

func (doid DenseObjectID) ExtractLocalSymbolID() uint32

ExtractLocalSymbolID extracts the local symbol ID from dense object ID

func (DenseObjectID) ExtractSymbolType

func (doid DenseObjectID) ExtractSymbolType() uint8

ExtractSymbolType extracts the symbol type (not encoded in dense format)

func (DenseObjectID) IsValid

func (doid DenseObjectID) IsValid() bool

IsValid checks if the dense object ID is valid

func (DenseObjectID) String

func (doid DenseObjectID) String() string

String returns the dense encoded string

type Dependency

type Dependency struct {
	Type     string            `json:"type"`     // database, service, file, etc.
	Name     string            `json:"name"`     // specific resource name
	Mode     string            `json:"mode"`     // read, write, read-write
	Metadata map[string]string `json:"metadata"` // additional attributes
}

Dependency represents a dependency declaration

type DependencyDetail

type DependencyDetail struct {
	Name     string           `json:"name"`
	Source   types.SymbolID   `json:"source"`
	Path     []types.SymbolID `json:"path"`
	Mode     string           `json:"mode"`
	Weight   float64          `json:"weight"`
	Distance int              `json:"distance"`
}

DependencyDetail provides detailed information about a specific dependency instance

type DependencyPropagationRule

type DependencyPropagationRule struct {
	DependencyType string  `json:"dependency_type"` // Type of dependency to track
	Direction      string  `json:"direction"`       // upstream, downstream
	Aggregation    string  `json:"aggregation"`     // sum, max, unique, concat, weighted_sum
	WeightFunction string  `json:"weight_function"` // linear, exponential, log
	MaxDepth       int     `json:"max_depth"`       // Maximum aggregation depth
	Threshold      float64 `json:"threshold"`       // Minimum threshold for inclusion
}

DependencyPropagationRule defines how dependencies aggregate

type DetectedAntiPattern

type DetectedAntiPattern struct {
	Name        string                 `json:"name"`
	Category    string                 `json:"category"`
	Severity    string                 `json:"severity"`
	Confidence  float64                `json:"confidence"`
	Evidence    []string               `json:"evidence"`
	Location    IntentLocation         `json:"location"`
	Remediation string                 `json:"remediation"`
	Impact      string                 `json:"impact"`
	Metadata    map[string]interface{} `json:"metadata"`
}

DetectedAntiPattern represents an identified anti-pattern

type DetectedIntent

type DetectedIntent struct {
	Intent      string                 `json:"intent"`
	Category    string                 `json:"category"`
	Confidence  float64                `json:"confidence"`
	Evidence    []string               `json:"evidence"` // Code patterns that support this intent
	Location    IntentLocation         `json:"location"` // Where in the code this intent was found
	Description string                 `json:"description"`
	Metadata    map[string]interface{} `json:"metadata"`
}

DetectedIntent represents an identified code intent

type DirectRelationships

type DirectRelationships struct {
	// Incoming: things that use/reference this object
	IncomingReferences []ObjectReference `json:"incoming_references"`
	CallerFunctions    []ObjectReference `json:"caller_functions"`
	ParentClasses      []ObjectReference `json:"parent_classes"`
	ImplementingTypes  []ObjectReference `json:"implementing_types"`

	// Outgoing: things that this object uses/references
	OutgoingReferences []ObjectReference `json:"outgoing_references"`
	CalledFunctions    []ObjectReference `json:"called_functions"`
	UsedTypes          []ObjectReference `json:"used_types"`
	ImportedModules    []ModuleReference `json:"imported_modules"`

	// Hierarchy
	ParentObjects []ObjectReference `json:"parent_objects"` // Parent functions, classes, namespaces
	ChildObjects  []ObjectReference `json:"child_objects"`  // Member functions, nested types
}

DirectRelationships contains immediate relationships of the code object

type EntryPointRef

type EntryPointRef struct {
	EntryPointID CodeObjectID `json:"entry_point_id"`
	Type         string       `json:"type"` // "HTTP endpoint", "main function", etc.
	Path         string       `json:"path"` // URL path, command name, etc.
	Confidence   float64      `json:"confidence"`
}

type ErrorCode

type ErrorCode string

ErrorCode represents different types of coordination errors

const (
	// Lock timeout errors
	ErrCodeLockTimeout     ErrorCode = "LOCK_TIMEOUT"
	ErrCodeLockUnavailable ErrorCode = "LOCK_UNAVAILABLE"

	// Deadlock and contention errors
	ErrCodeDeadlockDetected  ErrorCode = "DEADLOCK_DETECTED"
	ErrCodeContentionTooHigh ErrorCode = "CONTENTION_TOO_HIGH"

	// Index state errors
	ErrCodeInvalidIndexType ErrorCode = "INVALID_INDEX_TYPE"
	ErrCodeIndexUnavailable ErrorCode = "INDEX_UNAVAILABLE"
	ErrCodeIndexCorrupted   ErrorCode = "INDEX_CORRUPTED"

	// Resource and limit errors
	ErrCodeConcurrentLimit   ErrorCode = "CONCURRENT_LIMIT"
	ErrCodeResourceExhausted ErrorCode = "RESOURCE_EXHAUSTED"
	ErrCodeMemoryLimit       ErrorCode = "MEMORY_LIMIT"

	// System errors
	ErrCodeSystemShutdown     ErrorCode = "SYSTEM_SHUTDOWN"
	ErrCodeConfigurationError ErrorCode = "CONFIGURATION_ERROR"
)

func GetErrorCode

func GetErrorCode(err error) ErrorCode

GetErrorCode extracts the error code from a coordination error

type ErrorContext

type ErrorContext struct {
	IndexType     IndexType     `json:"indexType,omitempty"`
	OperationType string        `json:"operationType,omitempty"`
	LockType      LockType      `json:"lockType,omitempty"`
	WaitTime      time.Duration `json:"waitTime,omitempty"`
	ConcurrentOps int           `json:"concurrentOps,omitempty"`
	QueueDepth    int           `json:"queueDepth,omitempty"`
}

ErrorContext provides additional context for coordination errors

type ErrorHandler

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

ErrorHandler provides centralized error handling for coordination operations

func GetGlobalErrorHandler

func GetGlobalErrorHandler() *ErrorHandler

GetGlobalErrorHandler returns the singleton global error handler

func NewErrorHandler

func NewErrorHandler(logger ErrorLogger) *ErrorHandler

NewErrorHandler creates a new error handler

func (*ErrorHandler) HandleError

func (eh *ErrorHandler) HandleError(err *CoordinationError)

HandleError processes a coordination error

func (*ErrorHandler) HandleInfo

func (eh *ErrorHandler) HandleInfo(message string, context ErrorContext)

HandleInfo processes an informational message

func (*ErrorHandler) HandleWarning

func (eh *ErrorHandler) HandleWarning(message string, context ErrorContext)

HandleWarning processes a warning condition

type ErrorLogger

type ErrorLogger interface {
	LogError(err *CoordinationError)
	LogWarning(message string, context ErrorContext)
	LogInfo(message string, context ErrorContext)
}

ErrorLogger interface for logging coordination errors

type ExportInfo

type ExportInfo struct {
	Name        string   `json:"name"`
	Type        string   `json:"type"`
	ExportStyle string   `json:"export_style"`
	UsedBy      []string `json:"used_by"`
}

type FastPathCache

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

FastPathCache provides zero-allocation caching for common operations

func NewFastPathCache

func NewFastPathCache(size int) *FastPathCache

NewFastPathCache creates a new fast path cache with specified size

type FastPathEntry

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

FastPathEntry represents a cached fast-path operation

type FastPathShard

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

FastPathShard represents a cache shard for reduced lock contention

type FastSearchContext

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

FastSearchContext provides pre-allocated context for fast search operations

type FileContent

type FileContent struct {
	FileID      types.FileID
	Content     []byte       // The actual file content
	LineOffsets []uint32     // Byte offsets for start of each line
	FastHash    uint64       // xxhash for quick equality checks (~0.5ns)
	ContentHash [32]byte     // Pre-computed SHA256 hash for cache optimization
	RefCount    atomic.Int32 // Reference counting for cleanup
}

FileContent holds the actual content and pre-computed line information

type FileContentSnapshot

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

FileContentSnapshot represents concurrent file content data using sync.Map for safe concurrent read/write access without copy-on-write overhead.

type FileContentStore

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

FileContentStore manages all file content centrally with concurrent read/write access. Uses sync.Map for O(1) concurrent operations without copy-on-write overhead.

ARCHITECTURE:

  • Concurrent reads via sync.Map (no locks, no copying)
  • Writes serialized through dedicated goroutine for consistency
  • O(1) per-file operations (no O(n) map copying)

PERFORMANCE:

  • Lock-free reads with atomic.Load (near-zero overhead)
  • Updates serialized through channel (maintains consistency)
  • Memory-efficient shallow copies for snapshots

func NewFileContentStore

func NewFileContentStore() *FileContentStore

NewFileContentStore creates a new lock-free file content store

func NewFileContentStoreWithLimit

func NewFileContentStoreWithLimit(maxMemoryBytes int64) *FileContentStore

NewFileContentStoreWithLimit creates a new lock-free file content store with memory limit

func (*FileContentStore) BatchLoadFiles

func (fcs *FileContentStore) BatchLoadFiles(files []struct {
	Path    string
	Content []byte
}) []types.FileID

BatchLoadFiles loads multiple files with a single update

func (*FileContentStore) Clear

func (fcs *FileContentStore) Clear()

Clear removes all files from the store

func (*FileContentStore) Close

func (fcs *FileContentStore) Close()

Close shuts down the update processor goroutine This is safe to call multiple times due to sync.Once

func (*FileContentStore) CreateStringRef

func (fcs *FileContentStore) CreateStringRef(fileID types.FileID, start, length uint32) types.StringRef

CreateStringRef creates a types.StringRef with computed hash

func (*FileContentStore) CreateSubstring

func (fcs *FileContentStore) CreateSubstring(parent types.StringRef, offset, length uint32) types.StringRef

CreateSubstring creates a types.StringRef for a substring within another types.StringRef

func (*FileContentStore) GetBytes

func (fcs *FileContentStore) GetBytes(ref types.StringRef) ([]byte, error)

GetBytes returns the byte slice for a types.StringRef (LOCK-FREE)

func (*FileContentStore) GetContent

func (fcs *FileContentStore) GetContent(fileID types.FileID) ([]byte, bool)

GetContent returns the full content for a file (LOCK-FREE)

func (*FileContentStore) GetContentHash

func (fcs *FileContentStore) GetContentHash(fileID types.FileID) [32]byte

GetContentHash returns the pre-computed SHA256 hash for a file (LOCK-FREE)

func (*FileContentStore) GetContextLines

func (fcs *FileContentStore) GetContextLines(fileID types.FileID, lineNum, before, after int) []types.StringRef

GetContextLines returns types.StringRefs for lines around a given line

func (*FileContentStore) GetFastHash

func (fcs *FileContentStore) GetFastHash(fileID types.FileID) uint64

GetFastHash returns the pre-computed xxhash for a file (LOCK-FREE)

func (*FileContentStore) GetFileCount

func (fcs *FileContentStore) GetFileCount() int

GetFileCount returns the number of files in the store (LOCK-FREE)

func (*FileContentStore) GetFileVersion

func (fcs *FileContentStore) GetFileVersion(fileID types.FileID) (uint64, bool)

GetFileVersion is deprecated and always returns 0, false The Version field has been removed from FileContent as it was not being used for optimistic locking as originally intended.

func (*FileContentStore) GetLine

func (fcs *FileContentStore) GetLine(fileID types.FileID, lineNum int) (types.StringRef, bool)

GetLine returns a types.StringRef for a specific line (LOCK-FREE)

func (*FileContentStore) GetLineCount

func (fcs *FileContentStore) GetLineCount(fileID types.FileID) int

GetLineCount returns the number of lines in a file (LOCK-FREE)

func (*FileContentStore) GetLineOffsets

func (fcs *FileContentStore) GetLineOffsets(fileID types.FileID) ([]uint32, bool)

GetLineOffsets returns the precomputed line offsets for a file (LOCK-FREE)

func (*FileContentStore) GetLines

func (fcs *FileContentStore) GetLines(fileID types.FileID, startLine, endLine int) []types.StringRef

GetLines returns types.StringRefs for a range of lines

func (*FileContentStore) GetMemoryUsage

func (fcs *FileContentStore) GetMemoryUsage() int64

GetMemoryUsage returns the current memory usage (LOCK-FREE)

func (*FileContentStore) GetString

func (fcs *FileContentStore) GetString(ref types.StringRef) (string, error)

GetString materializes a string from a types.StringRef (LOCK-FREE)

func (*FileContentStore) InvalidateFile

func (fcs *FileContentStore) InvalidateFile(path string)

InvalidateFile removes a file from the store

func (*FileContentStore) InvalidateFileByID

func (fcs *FileContentStore) InvalidateFileByID(fileID types.FileID)

InvalidateFileByID removes a file from the store by its FileID

func (*FileContentStore) LoadFile

func (fcs *FileContentStore) LoadFile(path string, content []byte) types.FileID

LoadFile loads a file's content into the store and returns its ID

func (*FileContentStore) SlowEqual

func (fcs *FileContentStore) SlowEqual(ref1, ref2 types.StringRef) (bool, error)

SlowEqual performs full content comparison when hashes match

type FileContentStoreBuilder

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

FileContentStoreBuilder provides a fluent API for building test file systems.

Example usage:

builder := NewFileContentStoreBuilder().
	WithFile("main.go", []byte("package main\n\nfunc main() {}")).
	WithFile("util.go", []byte("package util\n\nfunc Helper() {}"))

store := builder.Build()
fileIDs := builder.GetFileIDs()

func NewFileContentStoreBuilder

func NewFileContentStoreBuilder() *FileContentStoreBuilder

NewFileContentStoreBuilder creates a new builder for test file systems

func (*FileContentStoreBuilder) Build

Build creates a FileContentStore and loads all files into it. Returns the store with all files loaded. Use GetFileIDs() to get the FileID mappings.

func (*FileContentStoreBuilder) GetFileID

func (b *FileContentStoreBuilder) GetFileID(path string) types.FileID

GetFileID returns the FileID for a specific file by path. Must call Build() first. Returns 0 if file not found.

func (*FileContentStoreBuilder) GetFileIDs

func (b *FileContentStoreBuilder) GetFileIDs() []types.FileID

GetFileIDs returns the FileIDs for all files in the order they were added. Must call Build() first.

func (*FileContentStoreBuilder) GetMockFileSystem

func (b *FileContentStoreBuilder) GetMockFileSystem() *MockFileSystem

GetMockFileSystem returns the MockFileSystem representation

func (*FileContentStoreBuilder) GetStore

GetStore returns the built FileContentStore. Must call Build() first.

func (*FileContentStoreBuilder) WithFile

func (b *FileContentStoreBuilder) WithFile(path string, content string) *FileContentStoreBuilder

WithFile adds a file to the builder with string content

func (*FileContentStoreBuilder) WithFileBytes

func (b *FileContentStoreBuilder) WithFileBytes(path string, content []byte) *FileContentStoreBuilder

WithFileBytes adds a file to the builder with byte content

func (*FileContentStoreBuilder) WithLanguage

WithLanguage sets the language hint for the last added file

func (*FileContentStoreBuilder) WithModTime

func (b *FileContentStoreBuilder) WithModTime(modTime time.Time) *FileContentStoreBuilder

WithModTime sets the modification time for the last added file

func (*FileContentStoreBuilder) WithRootPath

WithRootPath sets the virtual root directory path

type FileImportData

type FileImportData struct {
	FileID   types.FileID
	Bindings []ImportBinding
}

FileImportData represents import data for a single file Used during parallel processing to collect imports without locking

type FileLoader

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

FileLoader provides high-level file loading operations using the FileService. It handles batch loading, filtering, and discovery of code files.

func NewFileLoader

func NewFileLoader(opts FileLoaderOptions) *FileLoader

NewFileLoader creates a new file loader

func (*FileLoader) AddExcludePattern

func (fl *FileLoader) AddExcludePattern(pattern string)

AddExcludePattern adds an exclude pattern

func (*FileLoader) AddSupportedExtension

func (fl *FileLoader) AddSupportedExtension(ext string)

AddSupportedExtension adds a file extension to the supported list

func (*FileLoader) Close

func (fl *FileLoader) Close()

Close releases resources held by the FileLoader

func (*FileLoader) DiscoverAndLoadFiles

func (fl *FileLoader) DiscoverAndLoadFiles(rootPath string) (*BatchLoadResult, error)

DiscoverAndLoadFiles discovers all code files in a directory tree and loads them

func (*FileLoader) DiscoverGoFiles

func (fl *FileLoader) DiscoverGoFiles(rootPath string) ([]string, error)

DiscoverGoFiles discovers all Go files in a directory tree

func (*FileLoader) DiscoverJSFiles

func (fl *FileLoader) DiscoverJSFiles(rootPath string) ([]string, error)

DiscoverJSFiles discovers all JavaScript/TypeScript files in a directory tree

func (*FileLoader) GetFileRegistry

func (fl *FileLoader) GetFileRegistry() map[string]types.FileID

GetFileRegistry returns a registry of all loaded files for use with resolvers

func (*FileLoader) GetLoadStats

func (fl *FileLoader) GetLoadStats() map[string]interface{}

GetLoadStats returns statistics about loaded files

func (*FileLoader) LoadFile

func (fl *FileLoader) LoadFile(path string) (types.FileID, error)

LoadFile loads a single file and returns its FileID

func (*FileLoader) LoadFiles

func (fl *FileLoader) LoadFiles(paths []string) *BatchLoadResult

LoadFiles loads multiple files concurrently

func (*FileLoader) LoadGoFiles

func (fl *FileLoader) LoadGoFiles(rootPath string) (*BatchLoadResult, error)

LoadGoFiles discovers and loads all Go files in a directory tree

func (*FileLoader) LoadJSFiles

func (fl *FileLoader) LoadJSFiles(rootPath string) (*BatchLoadResult, error)

LoadJSFiles discovers and loads all JavaScript/TypeScript files in a directory tree

func (*FileLoader) RemoveSupportedExtension

func (fl *FileLoader) RemoveSupportedExtension(ext string)

RemoveSupportedExtension removes a file extension from the supported list

func (*FileLoader) SetMaxConcurrentLoads

func (fl *FileLoader) SetMaxConcurrentLoads(max int)

SetMaxConcurrentLoads sets the maximum number of concurrent file loads

func (*FileLoader) UpdateFile

func (fl *FileLoader) UpdateFile(path string, content []byte) (types.FileID, error)

UpdateFile updates or loads a file with new content

type FileLoaderOptions

type FileLoaderOptions struct {
	FileService         *FileService
	SupportedExtensions []string
	ExcludePatterns     []string
	MaxConcurrentLoads  int
}

FileLoaderOptions configures the file loader

type FileLocation

type FileLocation struct {
	FileID types.FileID
	Offset uint32
}

type FileMetadata

type FileMetadata struct {
	Path    string
	Size    int64
	ModTime time.Time
	IsDir   bool
	Exists  bool
	FileID  types.FileID // Only set for loaded files
}

FileMetadata contains cached filesystem metadata

type FileProvider

type FileProvider interface {
	GetFileInfo(fileID types.FileID) *types.FileInfo
}

FileProvider interface for accessing file information

type FileSearchEngine

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

FileSearchEngine provides file path search capabilities using only indexes and content store

func NewFileSearchEngine

func NewFileSearchEngine() *FileSearchEngine

NewFileSearchEngine creates a new file search engine

func (*FileSearchEngine) Clear

func (fse *FileSearchEngine) Clear()

Clear resets the file search engine's path index

func (*FileSearchEngine) GetIndex

func (fse *FileSearchEngine) GetIndex() *types.FilePathIndex

GetIndex returns the underlying path index (for testing and debugging)

func (*FileSearchEngine) GetStats

func (fse *FileSearchEngine) GetStats() map[string]interface{}

GetStats returns statistics about the file path index

func (*FileSearchEngine) IndexFile

func (fse *FileSearchEngine) IndexFile(fileID types.FileID, filePath string)

IndexFile adds a file path to the search index

func (*FileSearchEngine) Reset

func (fse *FileSearchEngine) Reset()

Reset clears all indexed data

func (*FileSearchEngine) SearchFiles

func (fse *FileSearchEngine) SearchFiles(options types.FileSearchOptions) ([]types.FileSearchResult, error)

SearchFiles searches for files matching the given options using only the index

type FileService

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

FileService provides centralized file system operations and content management. It is the ONLY component that should directly interact with the filesystem. All other components should use this service for file operations.

func NewFileService

func NewFileService() *FileService

NewFileService creates a new centralized file service

func NewFileServiceWithOptions

func NewFileServiceWithOptions(opts FileServiceOptions) *FileService

NewFileServiceWithOptions creates a file service with custom configuration

func (*FileService) ClearCache

func (fs *FileService) ClearCache()

ClearCache clears all caches

func (*FileService) Close

func (fs *FileService) Close()

Close releases resources held by the FileService

func (*FileService) Exists

func (fs *FileService) Exists(path string) bool

Exists checks if a file or directory exists

func (*FileService) FindFilesWithExtensions

func (fs *FileService) FindFilesWithExtensions(dirPath string, extensions []string) ([]string, error)

FindFilesWithExtensions finds all files with given extensions in a directory

func (*FileService) GetAllLoadedFiles

func (fs *FileService) GetAllLoadedFiles() map[string]types.FileID

GetAllLoadedFiles returns a map of path -> FileID for all loaded files

func (*FileService) GetContentStore

func (fs *FileService) GetContentStore() *FileContentStore

GetContentStore returns the underlying content store for direct access when needed

func (*FileService) GetFileContent

func (fs *FileService) GetFileContent(fileID types.FileID) ([]byte, bool)

GetFileContent returns the content for a FileID

func (*FileService) GetFileIDForPath

func (fs *FileService) GetFileIDForPath(path string) types.FileID

GetFileIDForPath returns the FileID for a path, or 0 if not loaded

func (*FileService) GetFilePath

func (fs *FileService) GetFilePath(fileID types.FileID) (string, bool)

GetFilePath returns the file path for a FileID using O(1) reverse lookup

func (*FileService) GetFileSize

func (fs *FileService) GetFileSize(path string) (int64, error)

GetFileSize returns the size of a file in bytes

func (*FileService) GetModTime

func (fs *FileService) GetModTime(path string) (time.Time, error)

GetModTime returns the modification time of a file

func (*FileService) GetPathForFileID

func (fs *FileService) GetPathForFileID(fileID types.FileID) string

GetPathForFileID returns the path for a FileID, or empty string if not found

func (*FileService) InvalidateDirectory

func (fs *FileService) InvalidateDirectory(dirPath string)

InvalidateDirectory removes directory from caches

func (*FileService) InvalidateFile

func (fs *FileService) InvalidateFile(path string)

InvalidateFile removes file from caches

func (*FileService) IsDir

func (fs *FileService) IsDir(path string) bool

IsDir checks if a path is a directory

func (*FileService) IsFile

func (fs *FileService) IsFile(path string) bool

IsFile checks if a path is a regular file

func (*FileService) ListFiles

func (fs *FileService) ListFiles(dirPath string) ([]string, error)

ListFiles returns all files in a directory (non-recursive)

func (*FileService) ListGoFiles

func (fs *FileService) ListGoFiles(dirPath string) ([]string, error)

ListGoFiles returns all Go files in a directory

func (*FileService) ListJSFiles

func (fs *FileService) ListJSFiles(dirPath string) ([]string, error)

ListJSFiles returns all JavaScript/TypeScript files in a directory

func (*FileService) LoadFile

func (fs *FileService) LoadFile(path string) (types.FileID, error)

LoadFile loads a file's content and returns its FileID

func (*FileService) LoadFileFromMemory

func (fs *FileService) LoadFileFromMemory(path string, content []byte) types.FileID

LoadFileFromMemory loads file content from memory (for testing or streaming)

func (*FileService) MkdirAll

func (fs *FileService) MkdirAll(path string, perm fs.FileMode) error

MkdirAll creates all directories in the path

func (*FileService) ReadFile

func (fs *FileService) ReadFile(path string) ([]byte, error)

ReadFile reads the content of a file directly from disk

func (*FileService) SetExternalPathLookup

func (fs *FileService) SetExternalPathLookup(fn func(types.FileID) string)

SetExternalPathLookup sets an external function for file path lookup This allows integration with MasterIndex or other file path providers

func (*FileService) UpdateFileContent

func (fs *FileService) UpdateFileContent(path string, content []byte) (types.FileID, error)

UpdateFileContent updates existing file content or loads new file

func (*FileService) WriteFile

func (fs *FileService) WriteFile(path string, content []byte, perm fs.FileMode) error

WriteFile writes content to a file

type FileServiceOptions

type FileServiceOptions struct {
	ContentStore     *FileContentStore
	FileSystem       FileSystemInterface
	MaxFileSizeBytes int64
	IgnoreDotFiles   bool
	IgnorePatterns   []string
}

FileServiceOptions configures the file service

type FileStringPool

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

FileStringPool manages strings for a specific file with line information

func NewFileStringPool

func NewFileStringPool(pool *StringPool, content string) *FileStringPool

NewFileStringPool creates a new file-specific string pool

func (*FileStringPool) GetContextLines

func (fsp *FileStringPool) GetContextLines(lineNum, contextBefore, contextAfter int) []StringRange

GetContextLines returns StringRanges for lines around a given line with specified context

func (*FileStringPool) GetLine

func (fsp *FileStringPool) GetLine(lineNum int) (StringRange, bool)

GetLine returns the StringRange for a specific line (0-indexed)

func (*FileStringPool) GetLineCount

func (fsp *FileStringPool) GetLineCount() int

GetLineCount returns the total number of lines

func (*FileStringPool) GetLines

func (fsp *FileStringPool) GetLines(start, end int) []StringRange

GetLines returns StringRanges for a range of lines

type FileSymbolMap

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

FileSymbolMap stores all symbols in a file with spatial indexing

type FileSystemInterface

type FileSystemInterface interface {
	Stat(path string) (fs.FileInfo, error)
	ReadFile(path string) ([]byte, error)
	ReadDir(path string) ([]fs.DirEntry, error)
	Exists(path string) bool
	IsDir(path string) bool
	IsFile(path string) bool
}

FileSystemInterface abstracts filesystem operations for testing and flexibility

type Fragment

type Fragment struct {
	Text          string               // The fragment text
	FileID        uint32               // File containing fragment
	Location      types.SymbolLocation // Location in file
	InStringLit   bool                 // Is this found in a string literal?
	SymbolContext string               // Function/class containing fragment
	Confidence    float64              // Confidence this is part of assembly
}

Fragment represents a piece of the target string found in code

type FunctionTreeNode

type FunctionTreeNode struct {
	Name     string                 `json:"name"`
	Children []*FunctionTreeNode    `json:"children,omitempty"`
	Metadata map[string]interface{} `json:"metadata,omitempty"`
}

FunctionTreeNode represents a node in the function call tree This replaces the equivalent structure from CallGraph

type GraphPropagator

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

GraphPropagator implements multi-mode label and dependency propagation through the symbol call graph supporting reachability, accumulation, decay, and max modes

func NewGraphPropagator

func NewGraphPropagator(annotator *SemanticAnnotator, refTracker *ReferenceTracker, symbolIndex *SymbolIndex) *GraphPropagator

NewGraphPropagator creates a new graph propagation engine

func (*GraphPropagator) GetCriticalPaths

func (gp *GraphPropagator) GetCriticalPaths() []CriticalPath

GetCriticalPaths returns identified critical paths

func (*GraphPropagator) GetDependencyDepth

func (gp *GraphPropagator) GetDependencyDepth(symbolID types.SymbolID) int

GetDependencyDepth returns the maximum dependency depth for a symbol

func (*GraphPropagator) GetEntryPoints

func (gp *GraphPropagator) GetEntryPoints(label string) []*AnnotatedSymbol

GetEntryPoints returns identified entry points by label

func (*GraphPropagator) GetInterfaceCallImplementations

func (gp *GraphPropagator) GetInterfaceCallImplementations(interfaceSymbolID types.SymbolID) *InterfaceCallAttribution

GetInterfaceCallImplementations returns potential concrete implementations for an interface method call, using code analysis first and falling back to heuristics when explicit evidence is insufficient.

This method implements a tiered attribution strategy:

  1. Code Analysis: Use explicit implements references with quality ranking (assigned > returned > cast > heuristic)
  2. Heuristic Fallback: If no high-quality matches, use method signature matching
  3. Combined: Return all candidates with appropriate confidence scores

func (*GraphPropagator) GetPropagatedDependencies

func (gp *GraphPropagator) GetPropagatedDependencies(symbolID types.SymbolID) []PropagatedDependency

GetPropagatedDependencies returns all propagated dependencies for a symbol

func (*GraphPropagator) GetPropagatedLabels

func (gp *GraphPropagator) GetPropagatedLabels(symbolID types.SymbolID) []PropagatedLabel

GetPropagatedLabels returns all propagated labels for a symbol

func (*GraphPropagator) GetPropagationPath

func (gp *GraphPropagator) GetPropagationPath(targetID types.SymbolID, label string) []types.SymbolID

GetPropagationPath returns the propagation path showing how a label reached a target symbol Returns the sequence of symbol IDs from source to target, or nil if no path exists

func (*GraphPropagator) GetPropagationStats

func (gp *GraphPropagator) GetPropagationStats() map[string]interface{}

GetPropagationStats provides statistics about the propagation results

func (*GraphPropagator) GetSymbolsWithLabel

func (gp *GraphPropagator) GetSymbolsWithLabel(label string, minStrength float64) []*AnnotatedSymbol

GetSymbolsWithLabel returns all symbols that have a specific propagated label with at least the specified minimum strength

func (*GraphPropagator) PropagateAll

func (gp *GraphPropagator) PropagateAll() error

PropagateAll runs the complete propagation algorithm

func (*GraphPropagator) PropagateWithInterfaceAttribution

func (gp *GraphPropagator) PropagateWithInterfaceAttribution(
	rule LabelPropagationRule,
	sourceValue *PropagationValue,
	interfaceSymbolID types.SymbolID,
	newState map[PropagationKey]*PropagationValue,
) error

PropagateWithInterfaceAttribution propagates a label through an interface call to concrete implementations, adjusting strength based on attribution confidence. This allows labels to flow through interface boundaries with appropriate uncertainty.

func (*GraphPropagator) SetConfig

func (gp *GraphPropagator) SetConfig(config *PropagationConfig)

SetConfig updates the propagation configuration

type HealthMonitor

type HealthMonitor interface {
	// CheckHealth checks the health of a specific index
	CheckHealth(indexType IndexType) IndexHealth

	// StartMonitoring begins continuous health monitoring
	StartMonitoring(interval time.Duration) error

	// StopMonitoring stops continuous health monitoring
	StopMonitoring() error

	// GetHealthHistory returns historical health data
	GetHealthHistory(indexType IndexType, duration time.Duration) []IndexHealth

	// RegisterHealthCallback registers a callback for health changes
	RegisterHealthCallback(callback func(IndexHealth)) error

	// UnregisterHealthCallback removes a health change callback
	UnregisterHealthCallback(callbackID string) error
}

HealthMonitor interface for index health monitoring

type HealthStatus

type HealthStatus int

HealthStatus represents the health status of an index

const (
	// HealthStatusHealthy - Index is operating normally
	HealthStatusHealthy HealthStatus = iota
	// HealthStatusDegraded - Index is operational but with performance issues
	HealthStatusDegraded
	// HealthStatusUnhealthy - Index is not functioning properly
	HealthStatusUnhealthy
	// HealthStatusFailed - Index has failed and requires recovery
	HealthStatusFailed
	// HealthStatusUnknown - Health status could not be determined
	HealthStatusUnknown
)

func (HealthStatus) String

func (hs HealthStatus) String() string

String returns the string representation of HealthStatus

type ImplementationAttribution

type ImplementationAttribution struct {
	SymbolID   types.SymbolID `json:"symbol_id"`
	Confidence float64        `json:"confidence"` // 0.0-1.0, higher = more confident
	Quality    string         `json:"quality"`    // Quality from reference (assigned, returned, cast, heuristic)
	Evidence   string         `json:"evidence"`   // Description of why this implementation was chosen
}

ImplementationAttribution represents attribution to a specific implementation

type ImplementorWithQuality

type ImplementorWithQuality struct {
	SymbolID types.SymbolID
	Quality  string
	Rank     int // Higher rank = more confident (from types.RefQualityRank)
}

ImplementorWithQuality represents an implementor with its quality ranking

type ImportBinding

type ImportBinding struct {
	ImportedName string // Name as imported (might be aliased)
	OriginalName string // Original symbol name in source file
	SourceFile   string // File path being imported from (relative)
	LineNumber   int    // Line where import occurs
	IsWildcard   bool   // true for "import *" or "use .*"
}

ImportBinding represents a symbol import relationship

type ImportInfo

type ImportInfo struct {
	ModulePath  string `json:"module_path"`
	ImportName  string `json:"import_name"`
	ImportStyle string `json:"import_style"`
	IsUsed      bool   `json:"is_used"`
}

type ImportPattern

type ImportPattern struct {
	// Regex patterns to find import statements
	ImportRegexes []*regexp.Regexp

	// How to extract the imported symbol and source
	SymbolExtractor func(importLine string) []ImportBinding

	// How to determine if a symbol is exported
	ExportChecker func(symbol types.Symbol) bool
}

ImportPattern defines how to extract imports for a language

type ImportResolver

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

ImportResolver provides language-agnostic heuristics for symbol resolution Uses practical approximations rather than full language server accuracy

func NewImportResolver

func NewImportResolver() *ImportResolver

NewImportResolver creates a resolver with shared cached regex patterns

func (*ImportResolver) BuildImportGraph

func (ir *ImportResolver) BuildImportGraph(importData []*FileImportData)

BuildImportGraph builds the import graph from collected import data This should be called in a single-threaded phase after all files are processed

func (*ImportResolver) Clear

func (ir *ImportResolver) Clear()

Clear removes all import data

func (*ImportResolver) ExtractFileImports

func (ir *ImportResolver) ExtractFileImports(fileID types.FileID, filePath string, content []byte) *FileImportData

ExtractFileImports analyzes a file's imports and returns the import data This is lock-free and can be called safely from parallel goroutines

func (*ImportResolver) RemoveFile

func (ir *ImportResolver) RemoveFile(fileID types.FileID)

RemoveFile removes import data for a specific file

func (*ImportResolver) ResolveSymbolReference

func (ir *ImportResolver) ResolveSymbolReference(refFileID types.FileID, referencedName string, candidates []types.SymbolID, symbolLookup func(types.SymbolID) *types.EnhancedSymbol) types.SymbolID

ResolveSymbolReference attempts to resolve which specific symbol a reference points to

func (*ImportResolver) Shutdown

func (ir *ImportResolver) Shutdown() error

Shutdown performs graceful shutdown with resource cleanup

type IndexCoordinationConfig

type IndexCoordinationConfig struct {
	// Default timeout for lock acquisition
	DefaultLockTimeout time.Duration
	// Maximum number of concurrent operations per index
	MaxConcurrentOps int
	// Enable adaptive timeout based on system load
	AdaptiveTimeout bool
	// Lock metrics collection interval
	MetricsInterval time.Duration
	// Maximum queue depth for index operations
	MaxQueueDepth int
}

IndexCoordinationConfig represents configuration for index coordination

func DefaultIndexCoordinationConfig

func DefaultIndexCoordinationConfig() *IndexCoordinationConfig

DefaultIndexCoordinationConfig returns default configuration for index coordination

func GetCoordinationConfig

func GetCoordinationConfig() *IndexCoordinationConfig

GetCoordinationConfig returns the current global coordination configuration

type IndexCoordinator

type IndexCoordinator interface {
	// Lock acquisition for operations
	AcquireIndexLock(indexType IndexType, forWriting bool, timeout time.Duration) (LockRelease, error)
	AcquireIndexLockCtx(ctx context.Context, indexType IndexType, forWriting bool) (LockRelease, error)
	AcquireMultipleLocks(requirements SearchRequirements, forWriting bool, timeout time.Duration) (LockRelease, error)
	AcquireMultipleLocksCtx(ctx context.Context, requirements SearchRequirements, forWriting bool) (LockRelease, error)

	// Status and monitoring
	GetIndexStatus(indexType IndexType) IndexStatus
	GetAllIndexStatus() map[IndexType]IndexStatus
	WaitForIndex(indexType IndexType, timeout time.Duration) error
}

IndexCoordinator manages coordination between multiple index systems and search operations

func NewIndexCoordinator

func NewIndexCoordinator() IndexCoordinator

NewIndexCoordinator creates a new index coordinator

func NewIndexCoordinatorWithConfig

func NewIndexCoordinatorWithConfig(config *IndexCoordinationConfig) IndexCoordinator

NewIndexCoordinatorWithConfig creates a new index coordinator with custom configuration

type IndexHealth

type IndexHealth struct {
	IndexType     IndexType        `json:"indexType"`
	Status        HealthStatus     `json:"status"`
	LastChecked   time.Time        `json:"lastChecked"`
	ErrorMessage  string           `json:"errorMessage,omitempty"`
	QueueSize     int              `json:"queueSize"`
	OperationRate float64          `json:"operationRate"` // operations per second
	ErrorRate     float64          `json:"errorRate"`     // errors per second
	ResponseTime  time.Duration    `json:"responseTime"`
	LastUpdate    time.Time        `json:"lastUpdate"`
	UpdateCount   int64            `json:"updateCount"`
	ErrorCount    int              `json:"errorCount"`
	Availability  float64          `json:"availability"` // percentage
	IsAvailable   bool             `json:"isAvailable"`
	Performance   IndexPerformance `json:"performance"`
	LastError     error            `json:"-"` // not JSON serializable
	LastErrorTime time.Time        `json:"lastErrorTime"`
}

IndexHealth represents the health status of an index

type IndexLockInfo

type IndexLockInfo struct {
	IndexType         IndexType
	Priority          int
	ContentionRate    float64
	AverageWaitTime   time.Duration
	CurrentQueueDepth int
	IsIndexing        bool
	Dependencies      []IndexType
	Dependents        []IndexType
}

IndexLockInfo contains information about an index for lock ordering decisions

type IndexOpStatus

type IndexOpStatus int

IndexOpStatus represents the status of an index operation

const (
	// IndexOperationQueued - Operation is queued and waiting to start
	IndexOperationQueued IndexOpStatus = iota
	// IndexOperationRunning - Operation is currently running
	IndexOperationRunning
	// IndexOperationCompleted - Operation completed successfully
	IndexOperationCompleted
	// IndexOperationFailed - Operation failed
	IndexOperationFailed
	// IndexOperationCancelled - Operation was cancelled
	IndexOperationCancelled
	// IndexOperationTimeout - Operation timed out
	IndexOperationTimeout
)

func (IndexOpStatus) IsCompleted

func (ios IndexOpStatus) IsCompleted() bool

IsCompleted returns true if the operation is in a completed state

func (IndexOpStatus) String

func (ios IndexOpStatus) String() string

String returns the string representation of IndexOpStatus

type IndexOperation

type IndexOperation struct {
	ID                 string              `json:"id"`
	IndexType          IndexType           `json:"indexType"`
	OperationType      IndexUpdateType     `json:"operationType"`
	Status             IndexOpStatus       `json:"status"`
	Progress           float64             `json:"progress"`
	StartTime          time.Time           `json:"startTime"`
	EndTime            time.Time           `json:"endTime,omitempty"`
	Timeout            time.Duration       `json:"timeout"`
	Priority           int                 `json:"priority"`
	Context            *context.CancelFunc `json:"-"`
	CancelFunc         func()              `json:"-"`
	LastProgressUpdate time.Time           `json:"lastProgressUpdate"`
}

IndexOperation represents an active indexing operation

type IndexOperationResult

type IndexOperationResult struct {
	OperationID    string           `json:"operationID"`
	Success        bool             `json:"success"`
	OperationType  IndexUpdateType  `json:"operationType"`
	IndexType      IndexType        `json:"indexType"`
	Status         IndexOpStatus    `json:"status"`
	Progress       float64          `json:"progress"`
	Duration       time.Duration    `json:"duration"`
	FilesProcessed int              `json:"filesProcessed"`
	BytesProcessed int64            `json:"bytesProcessed"`
	Error          string           `json:"error,omitempty"`
	Metrics        OperationMetrics `json:"metrics"`
}

IndexOperationResult represents the result of an index operation

type IndexPerformance

type IndexPerformance struct {
	AverageResponseTime time.Duration `json:"averageResponseTime"`
	LockWaitTime        time.Duration `json:"lockWaitTime"`
	ContentionRate      float64       `json:"contentionRate"`
}

IndexPerformance represents performance metrics for an index

type IndexState

type IndexState struct {
	// Core index identification
	Type IndexType
	// contains filtered or unexported fields
}

IndexState represents the current state and coordination state of each index system

func NewIndexState

func NewIndexState(indexType IndexType) *IndexState

NewIndexState creates a new IndexState for the given index type

func (*IndexState) AcquireReadLock

func (is *IndexState) AcquireReadLock(ctx context.Context, timeout time.Duration) (LockRelease, error)

AcquireReadLock acquires a read lock for the index (shared access) Returns a release function and an error if the lock cannot be acquired

func (*IndexState) AcquireWriteLock

func (is *IndexState) AcquireWriteLock(ctx context.Context, timeout time.Duration) (LockRelease, error)

AcquireWriteLock acquires a write lock for the index (exclusive access) Returns a release function and an error if the lock cannot be acquired

func (*IndexState) AddBytesProcessed

func (is *IndexState) AddBytesProcessed(count int64)

AddBytesProcessed atomically adds to the number of bytes processed

func (*IndexState) AddFilesProcessed

func (is *IndexState) AddFilesProcessed(count int64)

AddFilesProcessed atomically adds to the number of files processed

func (*IndexState) ClearError

func (is *IndexState) ClearError()

ClearError clears any recorded error

func (*IndexState) CompleteOperation

func (is *IndexState) CompleteOperation()

CompleteOperation marks the current operation as complete

func (*IndexState) GetBytesProcessed

func (is *IndexState) GetBytesProcessed() int64

GetBytesProcessed returns the number of bytes processed in current operation

func (*IndexState) GetCurrentOperation

func (is *IndexState) GetCurrentOperation() int64

GetCurrentOperation returns the type of current operation

func (*IndexState) GetDetailedStatus

func (is *IndexState) GetDetailedStatus() IndexStatusSnapshot

GetDetailedStatus returns detailed status information (T033)

func (*IndexState) GetEstimatedTime

func (is *IndexState) GetEstimatedTime() time.Time

GetEstimatedTime returns the estimated completion time of the current operation

func (*IndexState) GetEstimatedTimeRemaining

func (is *IndexState) GetEstimatedTimeRemaining() time.Duration

GetEstimatedTimeRemaining calculates estimated time remaining for current operation

func (*IndexState) GetFilesProcessed

func (is *IndexState) GetFilesProcessed() int64

GetFilesProcessed returns the number of files processed in current operation

func (*IndexState) GetLastError

func (is *IndexState) GetLastError() (error, time.Time)

GetLastError returns the last error and when it occurred

func (*IndexState) GetLastUpdate

func (is *IndexState) GetLastUpdate() time.Time

GetLastUpdate returns the timestamp of the last update completion (atomic operation)

func (*IndexState) GetProgress

func (is *IndexState) GetProgress() float64

GetProgress returns the current progress percentage (0-100)

func (*IndexState) GetProgressStats

func (is *IndexState) GetProgressStats() struct {
	Progress               float64
	FilesPerSecond         float64
	BytesPerSecond         float64
	Elapsed                time.Duration
	EstimatedTimeRemaining time.Duration
	IsComplete             bool
}

GetProgressStats returns progress statistics (T033)

func (*IndexState) GetStartTime

func (is *IndexState) GetStartTime() time.Time

GetStartTime returns the start time of the current operation

func (*IndexState) GetStatus

func (is *IndexState) GetStatus() IndexStatus

GetStatus returns the current status of the index

func (*IndexState) GetStatusHistory

func (is *IndexState) GetStatusHistory(limit int) []IndexStatusSnapshot

GetStatusHistory returns recent status snapshots (T033)

func (*IndexState) GetTotalBytes

func (is *IndexState) GetTotalBytes() int64

GetTotalBytes returns the total number of bytes to process

func (*IndexState) GetTotalFiles

func (is *IndexState) GetTotalFiles() int64

GetTotalFiles returns the total number of files to process

func (*IndexState) GetUpdateCount

func (is *IndexState) GetUpdateCount() int64

GetUpdateCount returns the number of updates performed (atomic operation)

func (*IndexState) IncrementUpdateCount

func (is *IndexState) IncrementUpdateCount() int64

IncrementUpdateCount atomically increments the update count

func (*IndexState) IsIndexing

func (is *IndexState) IsIndexing() bool

IsIndexing returns whether the index is currently being updated (atomic operation)

func (*IndexState) Reset

func (is *IndexState) Reset()

Reset resets the index state to initial values

func (*IndexState) SetBytesProcessed

func (is *IndexState) SetBytesProcessed(count int64)

SetBytesProcessed atomically sets the number of bytes processed

func (*IndexState) SetCurrentOperation

func (is *IndexState) SetCurrentOperation(operationType int64)

SetCurrentOperation atomically sets the type of current operation

func (*IndexState) SetError

func (is *IndexState) SetError(err error)

SetError records an error for the index

func (*IndexState) SetEstimatedTime

func (is *IndexState) SetEstimatedTime(t time.Time)

SetEstimatedTime atomically sets the estimated completion time of the current operation

func (*IndexState) SetFilesProcessed

func (is *IndexState) SetFilesProcessed(count int64)

SetFilesProcessed atomically sets the number of files processed

func (*IndexState) SetIndexing

func (is *IndexState) SetIndexing(indexing bool)

SetIndexing atomically sets the indexing status

func (*IndexState) SetLastUpdate

func (is *IndexState) SetLastUpdate(t time.Time)

SetLastUpdate atomically sets the last update timestamp

func (*IndexState) SetProgress

func (is *IndexState) SetProgress(progress float64)

SetProgress atomically sets the progress percentage (0-100)

func (*IndexState) SetStartTime

func (is *IndexState) SetStartTime(t time.Time)

SetStartTime atomically sets the start time of the current operation

func (*IndexState) SetTotalBytes

func (is *IndexState) SetTotalBytes(count int64)

SetTotalBytes atomically sets the total number of bytes to process

func (*IndexState) SetTotalFiles

func (is *IndexState) SetTotalFiles(count int64)

SetTotalFiles atomically sets the total number of files to process

func (*IndexState) StartOperation

func (is *IndexState) StartOperation(operationType int64, totalFiles, totalBytes int64)

StartOperation starts tracking a new operation

func (*IndexState) UpdateOperation

func (is *IndexState) UpdateOperation(filesProcessed, bytesProcessed int64)

UpdateOperation updates the progress of the current operation

func (*IndexState) WaitForIndexUpdate

func (is *IndexState) WaitForIndexUpdate(ctx context.Context, timeout time.Duration) error

WaitForIndexUpdate waits until the index is not indexing or timeout occurs

type IndexStateRegistry

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

IndexStateRegistry manages a collection of index states

func NewIndexStateRegistry

func NewIndexStateRegistry() *IndexStateRegistry

NewIndexStateRegistry creates a new registry for managing index states

func (*IndexStateRegistry) GetAllDetailedStatus

func (r *IndexStateRegistry) GetAllDetailedStatus() map[IndexType]IndexStatusSnapshot

GetAllDetailedStatus returns detailed status for all indexes (T033)

func (*IndexStateRegistry) GetAllStatus

func (r *IndexStateRegistry) GetAllStatus() map[IndexType]IndexStatus

GetAllStatus returns the status of all indexes

func (*IndexStateRegistry) GetIndexState

func (r *IndexStateRegistry) GetIndexState(indexType IndexType) *IndexState

GetIndexState returns the state for a specific index type

func (*IndexStateRegistry) GetOverallProgress

func (r *IndexStateRegistry) GetOverallProgress() struct {
	OverallProgress        float64
	TotalFilesProcessed    int64
	TotalFiles             int64
	TotalBytesProcessed    int64
	TotalBytes             int64
	IndexesCompleted       int
	IndexesInProgress      int
	IndexesTotal           int
	EstimatedTimeRemaining time.Duration
	AverageFilesPerSecond  float64
	AverageBytesPerSecond  float64
}

GetOverallProgress calculates overall progress across all indexes (T033)

func (*IndexStateRegistry) GetProgressSummary

func (r *IndexStateRegistry) GetProgressSummary() map[IndexType]struct {
	Progress               float64
	FilesProcessed         int64
	TotalFiles             int64
	BytesProcessed         int64
	TotalBytes             int64
	IsIndexing             bool
	EstimatedTimeRemaining time.Duration
	IsComplete             bool
	ProgressStats          struct {
		Progress               float64
		FilesPerSecond         float64
		BytesPerSecond         float64
		Elapsed                time.Duration
		EstimatedTimeRemaining time.Duration
		IsComplete             bool
	}
}

GetProgressSummary returns a summary of progress across all indexes (T033)

func (*IndexStateRegistry) ResetAll

func (r *IndexStateRegistry) ResetAll()

ResetAll resets all index states to initial values

func (*IndexStateRegistry) StartOperationOnAll

func (r *IndexStateRegistry) StartOperationOnAll(operationType int64, filesPerIndex map[IndexType]int64, bytesPerIndex map[IndexType]int64)

StartOperationOnAll starts tracking operations on all indexes

type IndexStatus

type IndexStatus struct {
	Type        IndexType `json:"type"`
	IsIndexing  bool      `json:"isIndexing"`
	LastUpdate  time.Time `json:"lastUpdate"`
	UpdateCount int64     `json:"updateCount"`
	LockHolders int       `json:"lockHolders"`
	QueueDepth  int       `json:"queueDepth"`
}

IndexStatus represents the current status of an index

type IndexStatusSnapshot

type IndexStatusSnapshot struct {
	Timestamp              time.Time     `json:"timestamp"`
	IndexType              IndexType     `json:"indexType"`
	IsIndexing             bool          `json:"isIndexing"`
	Progress               float64       `json:"progress"`
	CurrentOperation       int64         `json:"currentOperation"`
	FilesProcessed         int64         `json:"filesProcessed"`
	TotalFiles             int64         `json:"totalFiles"`
	BytesProcessed         int64         `json:"bytesProcessed"`
	TotalBytes             int64         `json:"totalBytes"`
	LockHolders            int           `json:"lockHolders"`
	QueueDepth             int           `json:"queueDepth"`
	LastUpdate             time.Time     `json:"lastUpdate"`
	UpdateCount            int64         `json:"updateCount"`
	HasError               bool          `json:"hasError"`
	ErrorMessage           string        `json:"errorMessage,omitempty"`
	EstimatedTimeRemaining time.Duration `json:"estimatedTimeRemaining"`
}

IndexStatusSnapshot represents a snapshot of index status at a point in time (T033)

type IndexSystemLogger

type IndexSystemLogger struct {
	*DefaultErrorLogger
}

IndexSystemLogger provides specialized logging for index system operations

func GetGlobalIndexSystemLogger

func GetGlobalIndexSystemLogger() *IndexSystemLogger

GetGlobalIndexSystemLogger returns the singleton global index system logger

func NewIndexSystemLogger

func NewIndexSystemLogger() *IndexSystemLogger

NewIndexSystemLogger creates a new index system logger

func (*IndexSystemLogger) LogHealthCheck

func (isl *IndexSystemLogger) LogHealthCheck(indexType IndexType, health HealthStatus, availability float64, responseTime time.Duration, issues []string)

LogHealthCheck logs health check results

func (*IndexSystemLogger) LogIndexOperation

func (isl *IndexSystemLogger) LogIndexOperation(indexType IndexType, operation string, startTime time.Time, duration time.Duration, success bool, details map[string]interface{})

LogIndexOperation logs index operations with timing

func (*IndexSystemLogger) LogIndexStateChange

func (isl *IndexSystemLogger) LogIndexStateChange(indexType IndexType, oldStatus, newStatus string, context map[string]interface{})

LogIndexStateChange logs changes to index state

func (*IndexSystemLogger) LogLockOperation

func (isl *IndexSystemLogger) LogLockOperation(indexType IndexType, lockType LockType, operation string, waitTime time.Duration, acquired bool, queueDepth int)

LogLockOperation logs lock operations with contention details

func (*IndexSystemLogger) LogMetricsSnapshot

func (isl *IndexSystemLogger) LogMetricsSnapshot(indexType IndexType, metrics map[string]interface{})

LogMetricsSnapshot logs periodic metrics snapshots

func (*IndexSystemLogger) LogQueueOperation

func (isl *IndexSystemLogger) LogQueueOperation(operation string, queueDepth, maxDepth int, avgWaitTime time.Duration, details map[string]interface{})

LogQueueOperation logs queue operations

type IndexType

type IndexType int

IndexType represents different types of indexes that can be managed independently

const (
	// TrigramIndexType - Trigram pattern matching index
	TrigramIndexType IndexType = iota
	// SymbolIndexType - Symbol definitions and references index
	SymbolIndexType
	// ReferenceIndexType - Cross-reference tracking index
	ReferenceIndexType
	// CallGraphIndexType - Call hierarchy and relationship index
	CallGraphIndexType
	// PostingsIndexType - Word posting lists index
	PostingsIndexType
	// LocationIndexType - File location indexing
	LocationIndexType
	// ContentIndexType - Full content search index
	ContentIndexType
)

func GetAllIndexTypes

func GetAllIndexTypes() []IndexType

GetAllIndexTypes returns all available index types

func (IndexType) Int32

func (it IndexType) Int32() int32

Int32 returns the int32 representation of IndexType

func (IndexType) IsValid

func (it IndexType) IsValid() bool

IsValid checks if the IndexType is valid

func (IndexType) String

func (it IndexType) String() string

String returns the string representation of IndexType

type IndexUpdateOptions

type IndexUpdateOptions struct {
	// Force rebuild even if index appears up to date
	Force bool
	// Files to include in the update (empty means all files)
	Files []string
	// Priority of the update operation
	Priority int
	// Timeout for the update operation
	Timeout time.Duration
	// Whether to validate after update
	Validate bool
	// Callback function for progress updates
	ProgressCallback func(progress float64)
}

IndexUpdateOptions represents options for index update operations

func DefaultIndexUpdateOptions

func DefaultIndexUpdateOptions() IndexUpdateOptions

DefaultIndexUpdateOptions returns default options for index updates

type IndexUpdateType

type IndexUpdateType int

IndexUpdateType represents the type of index update operation

const (
	// IndexUpdateTypeIncremental - Incremental update with new/changed files
	IndexUpdateTypeIncremental IndexUpdateType = iota
	// IndexUpdateTypeFull - Full index rebuild
	IndexUpdateTypeFull
	// IndexUpdateTypeRecovery - Recovery from failed state
	IndexUpdateTypeRecovery
	// IndexUpdateTypeValidation - Index validation and consistency check
	IndexUpdateTypeValidation
)

func (IndexUpdateType) String

func (iut IndexUpdateType) String() string

String returns the string representation of IndexUpdateType

type IntegratedSearch

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

IntegratedSearch performs both regular and assembly search when appropriate

func NewIntegratedSearch

func NewIntegratedSearch(regular SearchEngine, assembly *AssemblySearchEngine) *IntegratedSearch

NewIntegratedSearch creates a search that combines regular and assembly search

func (*IntegratedSearch) Search

func (is *IntegratedSearch) Search(pattern string, options types.SearchOptions) (*UnifiedSearchResult, error)

Search performs integrated search with automatic assembly search detection

func (*IntegratedSearch) SearchWithFallback

func (is *IntegratedSearch) SearchWithFallback(pattern string, options types.SearchOptions) (*UnifiedSearchResult, error)

SearchWithFallback runs regular search first, then assembly if results are poor

type IntentAnalysisResult

type IntentAnalysisResult struct {
	FileID        types.FileID           `json:"file_id"`
	FilePath      string                 `json:"file_path"`
	PrimaryIntent string                 `json:"primary_intent"`
	IntentScore   float64                `json:"intent_score"`
	Intents       []DetectedIntent       `json:"intents"`
	AntiPatterns  []DetectedAntiPattern  `json:"anti_patterns"`
	Context       AnalysisContext        `json:"context"`
	Summary       IntentSummary          `json:"summary"`
	Metadata      map[string]interface{} `json:"metadata"`
}

IntentAnalysisResult contains the results of intent analysis

type IntentAnalyzer

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

IntentAnalyzer provides semantic understanding of code purpose and intent using pattern recognition and contextual analysis

func NewIntentAnalyzer

func NewIntentAnalyzer() *IntentAnalyzer

NewIntentAnalyzer creates a new intent analysis engine

func (*IntentAnalyzer) AnalyzeIntent

func (ia *IntentAnalyzer) AnalyzeIntent(options types.IntentAnalysisOptions, files map[types.FileID]string, symbols map[types.FileID][]types.Symbol, fileContent map[types.FileID]string) ([]*IntentAnalysisResult, error)

AnalyzeIntent performs intent analysis on the given files

type IntentLocation

type IntentLocation struct {
	StartLine int    `json:"start_line"`
	EndLine   int    `json:"end_line"`
	Function  string `json:"function"`
	Symbol    string `json:"symbol"`
	Context   string `json:"context"`
}

IntentLocation specifies where an intent or anti-pattern was detected

type IntentPattern

type IntentPattern struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	Category    string                 `json:"category"`   // ui, business-logic, data-access, etc.
	Patterns    []string               `json:"patterns"`   // Regex patterns to match
	Keywords    []string               `json:"keywords"`   // Intent-indicating keywords
	Contexts    []string               `json:"contexts"`   // File/package contexts where this applies
	Confidence  float64                `json:"confidence"` // Base confidence score (0.0-1.0)
	Examples    []string               `json:"examples"`   // Example code snippets
	Metadata    map[string]interface{} `json:"metadata"`
}

IntentPattern defines patterns for identifying code intent

type IntentRule

type IntentRule struct {
	Name        string   `json:"name"`
	Description string   `json:"description"`
	Trigger     string   `json:"trigger"`    // Pattern that triggers this rule
	Intent      string   `json:"intent"`     // The intent this rule identifies
	Confidence  float64  `json:"confidence"` // Confidence multiplier
	Context     []string `json:"context"`    // Additional context requirements
}

IntentRule defines domain-specific intent detection logic

type IntentSummary

type IntentSummary struct {
	TotalIntents     int      `json:"total_intents"`
	PrimaryCategory  string   `json:"primary_category"`
	ConfidenceScore  float64  `json:"confidence_score"`
	AntiPatternCount int      `json:"anti_pattern_count"`
	ComplexityScore  float64  `json:"complexity_score"`
	Recommendations  []string `json:"recommendations"`
}

IntentSummary provides high-level analysis summary

type InterfaceCallAttribution

type InterfaceCallAttribution struct {
	InterfaceSymbolID types.SymbolID              `json:"interface_symbol_id"`
	Implementations   []ImplementationAttribution `json:"implementations"`
	AttributionMethod string                      `json:"attribution_method"` // "code_analysis", "heuristic", "combined"
}

InterfaceCallAttribution represents an attribution of an interface call to specific concrete implementations with confidence levels.

type InterfaceInfo

type InterfaceInfo struct {
	InterfaceID        CodeObjectID `json:"interface_id"`
	Methods            []string     `json:"methods"`
	IsFullyImplemented bool         `json:"is_fully_implemented"`
}

type InterfaceWithQuality

type InterfaceWithQuality struct {
	SymbolID types.SymbolID
	Quality  string
	Rank     int // Higher rank = more confident (from types.RefQualityRank)
}

InterfaceWithQuality represents an implemented interface with its quality ranking

type LLMOptimizer

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

LLMOptimizer provides LLM-specific optimizations and context formatting for better AI agent integration and reduced token usage

func NewLLMOptimizer

func NewLLMOptimizer() *LLMOptimizer

NewLLMOptimizer creates a new LLM optimization engine

func (*LLMOptimizer) OptimizeForContext

func (opt *LLMOptimizer) OptimizeForContext(optimized *OptimizedSearchResult, maxTokens int) *OptimizedSearchResult

OptimizeForContext reduces content to fit within token limits

func (*LLMOptimizer) OptimizeForLLM

func (opt *LLMOptimizer) OptimizeForLLM(query string, results []SearchResult, intent *IntentAnalysisResult, patterns []PatternViolation) *OptimizedSearchResult

OptimizeForLLM takes raw search results and optimizes them for LLM consumption

type LabelPropagationRule

type LabelPropagationRule struct {
	Label                string          `json:"label"`                  // Label to propagate
	Direction            string          `json:"direction"`              // upstream, downstream, bidirectional
	Mode                 PropagationMode `json:"mode"`                   // Propagation mode (reachability, accumulation, decay, max)
	Decay                float64         `json:"decay"`                  // Strength reduction per hop (only used in ModeDecay)
	MaxHops              int             `json:"max_hops"`               // Maximum propagation distance (0 = unlimited)
	MinStrength          float64         `json:"min_strength"`           // Minimum strength to continue (only used in ModeDecay)
	Boost                float64         `json:"boost"`                  // Strength boost for certain conditions
	Conditions           []string        `json:"conditions"`             // Conditional propagation rules
	Priority             int             `json:"priority"`               // Rule priority (higher = more important)
	IncludeTypeHierarchy bool            `json:"include_type_hierarchy"` // Include implements/extends relationships in propagation
}

LabelPropagationRule defines how specific labels propagate

type LanguageRules

type LanguageRules struct {
	Language          string
	MainFunctionNames []string // e.g., ["main", "Main", "_main"]
	HandlerSuffixes   []string // e.g., ["Handler", "Controller", "Endpoint"]
	ViewSuffixes      []string // e.g., ["Component", "View", "Template"]
	ModelSuffixes     []string // e.g., ["Model", "Entity", "Schema"]
	TestPatterns      []string // e.g., ["test", "spec", "_test"]
	ConfigNames       []string // e.g., ["config", "settings", "env"]
}

LanguageRules contains language-specific detection rules

type LineRef

type LineRef struct {
	FileID  types.FileID
	LineNum uint32 // 0-based line number
}

LineRef represents a reference to a specific line within a file

type LineScanner

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

LineScanner provides zero-allocation line iteration over byte content. It performs a single-pass scan, computing line offsets on-demand without allocating a slice of strings like strings.Split does.

Usage:

scanner := NewLineScanner(content)
for scanner.Scan() {
    line := scanner.Bytes() // Zero-copy access to current line
    lineNum := scanner.LineNumber() // 1-based line number
}

For counting lines before processing:

count := CountLines(content)
results := make([]Result, 0, count) // Pre-allocate with exact capacity

func NewLineScanner

func NewLineScanner(data []byte) *LineScanner

NewLineScanner creates a new line scanner for the given content. The scanner strips trailing \r\n or \n from each line.

func NewLineScannerKeepNewlines

func NewLineScannerKeepNewlines(data []byte) *LineScanner

NewLineScannerKeepNewlines creates a scanner that keeps newline characters.

func (*LineScanner) Bytes

func (ls *LineScanner) Bytes() []byte

Bytes returns the current line as a byte slice (zero-copy). The returned slice is valid until the next Scan call.

func (*LineScanner) EndOffset

func (ls *LineScanner) EndOffset() int

EndOffset returns the byte offset of the current line end (exclusive).

func (*LineScanner) Length

func (ls *LineScanner) Length() int

Length returns the length of the current line in bytes.

func (*LineScanner) LineNumber

func (ls *LineScanner) LineNumber() int

LineNumber returns the current line number (1-based).

func (*LineScanner) Offset

func (ls *LineScanner) Offset() int

Offset returns the byte offset of the current line start.

func (*LineScanner) Reset

func (ls *LineScanner) Reset()

Reset resets the scanner to the beginning.

func (*LineScanner) Scan

func (ls *LineScanner) Scan() bool

Scan advances to the next line. Returns false when done.

func (*LineScanner) Text

func (ls *LineScanner) Text() string

Text returns the current line as a string. Note: This allocates a new string. Use Bytes() for zero-allocation access.

type LineSymbolIndex

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

LineSymbolIndex provides fast symbol lookup within a specific line

type LoadResult

type LoadResult struct {
	Path   string
	FileID types.FileID
	Error  error
}

LoadResult contains the result of loading a file

type LocationKey

type LocationKey struct {
	FileID types.FileID
	Line   int
}

LocationKey is a zero-allocation key type for FileID:Line lookups Replaces fmt.Sprintf("%d:%d") in hot paths (50-100MB savings per query)

type LockOrderingStrategy

type LockOrderingStrategy int

LockOrderingStrategy defines different approaches to lock ordering

const (
	// StrategyNumeric - Simple numeric ordering (fallback)
	StrategyNumeric LockOrderingStrategy = iota
	// StrategyDependency - Order by dependencies (dependent indexes first)
	StrategyDependency
	// StrategyPriority - Order by priority and contention
	StrategyPriority
	// StrategyAdaptive - Adaptive ordering based on system conditions
	StrategyAdaptive
)

func (LockOrderingStrategy) String

func (los LockOrderingStrategy) String() string

String returns string representation of LockOrderingStrategy

type LockRelease

type LockRelease func()

LockRelease is a function type that releases acquired locks

type LockType

type LockType int

LockType represents the type of lock operation

const (
	// ReadLock - Shared lock for read operations
	ReadLock LockType = iota
	// WriteLock - Exclusive lock for write operations
	WriteLock
)

func (LockType) String

func (lt LockType) String() string

String returns the string representation of LockType

type LookupDiagnostics added in v0.4.0

type LookupDiagnostics struct {
	Errors   []LookupError `json:"errors,omitempty"`   // Non-fatal errors encountered
	Warnings []string      `json:"warnings,omitempty"` // Warnings about partial data
	// Index health indicators
	SymbolIndexReady   bool `json:"symbol_index_ready"`
	RefTrackerReady    bool `json:"ref_tracker_ready"`
	CallGraphPopulated bool `json:"call_graph_populated"`
	SideEffectsReady   bool `json:"side_effects_ready"`
	// Counts for verification
	RelationshipsFound int `json:"relationships_found"`
	SymbolsSearched    int `json:"symbols_searched"`
}

LookupDiagnostics tracks all issues encountered during context lookup

func (*LookupDiagnostics) AddError added in v0.4.0

func (d *LookupDiagnostics) AddError(err *LookupError)

AddError adds a lookup error to diagnostics

func (*LookupDiagnostics) AddWarning added in v0.4.0

func (d *LookupDiagnostics) AddWarning(msg string)

AddWarning adds a warning message

func (*LookupDiagnostics) HasFatalError added in v0.4.0

func (d *LookupDiagnostics) HasFatalError() bool

HasFatalError returns true if any fatal error occurred

type LookupError added in v0.4.0

type LookupError struct {
	Code    string // Machine-readable error code
	Message string // Human-readable description
	Field   string // Which field/section failed
	Fatal   bool   // If true, entire lookup should fail
}

LookupError represents a specific failure during context lookup

func (*LookupError) Error added in v0.4.0

func (e *LookupError) Error() string

type MemoryAnalysisHints

type MemoryAnalysisHints struct {
	// LoopWeight overrides the default loop iteration multiplier (0.0-100.0)
	// Use lower values for bounded/retry loops, higher for hot iteration loops
	LoopWeight float64 `json:"loop_weight,omitempty"`

	// LoopBounded marks the loop as having a known maximum iteration count
	// This significantly reduces the score for retry loops and similar patterns
	LoopBounded int `json:"loop_bounded,omitempty"`

	// CallFrequency indicates how often this code path is executed
	// Helps prioritize hot paths over CLI output or startup code
	CallFrequency string `json:"call_frequency,omitempty"`

	// PropagationWeight overrides the damping factor for score propagation (0.0-1.0)
	// Lower values reduce how much callee scores propagate to this function
	PropagationWeight float64 `json:"propagation_weight,omitempty"`

	// HasAnnotation tracks whether any memory hints were explicitly set
	HasAnnotation bool `json:"has_annotation,omitempty"`
}

MemoryAnalysisHints contains hints for memory pressure analysis

type MemoryPool

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

MemoryPool provides pre-allocated memory pools for common objects

type MockFile

type MockFile struct {
	// Path is the virtual file path (e.g., "src/main.go")
	Path string

	// Content is the file content as bytes
	Content []byte

	// Language is optional language hint for the parser
	// If empty, will be inferred from file extension
	Language string

	// ModTime is optional modification time for the file
	// If zero, uses current time
	ModTime time.Time
}

MockFile represents a single file in an in-memory file system for testing. Files are ordered - the array position determines processing order.

type MockFileSystem

type MockFileSystem struct {
	// Files is the ordered array of mock files
	Files []MockFile

	// RootPath is the virtual root directory (default: "/test")
	RootPath string
}

MockFileSystem represents an ordered collection of files for testing. The order of Files determines processing order in the indexer.

func NewMockFileSystem

func NewMockFileSystem(files map[string]string) *MockFileSystem

NewMockFileSystem creates a new mock file system from a map of files. The order is deterministic but based on map iteration, so prefer NewFileContentStoreBuilder for explicit ordering.

func (*MockFileSystem) LoadBatch

func (mfs *MockFileSystem) LoadBatch(store *FileContentStore) []types.FileID

LoadBatch loads multiple files into the store using the batch API for efficiency. Returns the FileIDs for all loaded files in order.

func (*MockFileSystem) LoadIntoStore

func (mfs *MockFileSystem) LoadIntoStore(store *FileContentStore) []types.FileID

LoadIntoStore loads the mock file system into an existing FileContentStore. Returns the FileIDs for all loaded files in order.

type ModuleReference

type ModuleReference struct {
	ModulePath  string   `json:"module_path"`
	ImportStyle string   `json:"import_style"` // "direct", "aliased", "wildcard"
	UsedItems   []string `json:"used_items"`
}

type ObjectLocationKey

type ObjectLocationKey struct {
	Name   string
	FileID types.FileID
}

ObjectLocationKey is a zero-allocation key type for Name:FileID lookups

type ObjectReference

type ObjectReference struct {
	ObjectID   CodeObjectID         `json:"object_id"`
	Location   types.SymbolLocation `json:"location"`
	Context    string               `json:"context"` // How it's referenced
	Confidence float64              `json:"confidence"`
}

func FilterHighConfidence

func FilterHighConfidence(refs []ObjectReference, threshold float64) []ObjectReference

Filter high-confidence references

func (ObjectReference) IsValid

func (ref ObjectReference) IsValid() bool

type OperationMetrics

type OperationMetrics struct {
	IndexTime      time.Duration `json:"indexTime"`
	ValidationTime time.Duration `json:"validationTime"`
	CleanupTime    time.Duration `json:"cleanupTime"`
	MemoryPeak     int64         `json:"memoryPeak"`
	GoroutineCount int           `json:"goroutineCount"`
}

OperationMetrics represents detailed metrics for an operation

type OperationPriority

type OperationPriority int

OperationPriority represents the priority level of an operation

const (
	// PriorityCritical - Critical operations (e.g., error recovery, user requests)
	PriorityCritical OperationPriority = iota
	// PriorityHigh - High priority operations (e.g., manual rebuilds)
	PriorityHigh
	// PriorityNormal - Normal priority operations (e.g., regular indexing)
	PriorityNormal
	// PriorityLow - Low priority operations (e.g., maintenance)
	PriorityLow
	// PriorityBackground - Background operations (e.g., statistics)
	PriorityBackground
)

func (OperationPriority) String

func (op OperationPriority) String() string

String returns string representation of OperationPriority

type OperationType

type OperationType int

OperationType represents the type of indexing operation

const (
	// OpUpdate - Incremental update operation
	OpUpdate OperationType = iota
	// OpRebuild - Full rebuild operation
	OpRebuild
	// OpIncremental - Incremental update with dependency tracking
	OpIncremental
)

func (OperationType) String

func (ot OperationType) String() string

String returns the string representation of OperationType

type OperationalMetrics

type OperationalMetrics struct {
	TotalSymbols     int64         `json:"total_symbols"`    // Total symbols added
	DroppedUpdates   int64         `json:"dropped_updates"`  // Updates dropped during shutdown
	BatchCount       int64         `json:"batch_count"`      // Number of batches processed
	LastBatchTime    time.Duration `json:"last_batch_time"`  // Time to process last batch
	AverageBatchTime time.Duration `json:"avg_batch_time"`   // Average batch processing time
	LastUpdateTime   time.Time     `json:"last_update_time"` // When last update was processed
}

OperationalMetrics tracks performance and operational statistics

type OptimizeContextOperations

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

OptimizeContextOperations provides context operation optimizations

func GetContextOptimizations

func GetContextOptimizations() *OptimizeContextOperations

GetContextOptimizations returns the context operation optimizer

func (*OptimizeContextOperations) FastCancel

func (oco *OptimizeContextOperations) FastCancel(ctx context.Context)

FastCancel provides fast cancellation handling

func (*OptimizeContextOperations) GetOptimizedContext

func (oco *OptimizeContextOperations) GetOptimizedContext(parent context.Context, timeout time.Duration) context.Context

GetOptimizedContext gets an optimized context from the pool

type OptimizeLockOperations

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

OptimizeLockOperations provides lock operation optimizations

func GetLockOptimizations

func GetLockOptimizations() *OptimizeLockOperations

GetLockOptimizations returns the lock operation optimizer

func (*OptimizeLockOperations) CalculateAdaptiveTimeout

func (olo *OptimizeLockOperations) CalculateAdaptiveTimeout(baseTimeout time.Duration, loadLevel int) time.Duration

CalculateAdaptiveTimeout calculates timeout based on current system load

func (*OptimizeLockOperations) ReleaseFastLock

func (olo *OptimizeLockOperations) ReleaseFastLock(indexType IndexType, forWriting bool)

ReleaseFastLock releases a fast-acquired lock

func (*OptimizeLockOperations) TryFastLock

func (olo *OptimizeLockOperations) TryFastLock(indexType IndexType, forWriting bool) bool

TryFastLock attempts a fast, non-blocking lock acquisition

type OptimizedSearchResult

type OptimizedSearchResult struct {
	Summary         string               `json:"summary"`
	KeyFindings     []string             `json:"key_findings"`
	CodeExamples    []CodeExample        `json:"code_examples"`
	Architecture    ArchitectureOverview `json:"architecture"`
	Recommendations []string             `json:"recommendations"`
	TokenEstimate   int                  `json:"token_estimate"`
	SourceFiles     []string             `json:"source_files"`
}

OptimizedSearchResult represents search results optimized for LLM consumption

type PatternRule

type PatternRule struct {
	Name           string   `json:"name"`
	Description    string   `json:"description"`
	Pattern        string   `json:"pattern"`          // Regex pattern to match functions/symbols
	MustContain    []string `json:"must_contain"`     // Required patterns that must be present
	MustNotContain []string `json:"must_not_contain"` // Anti-patterns that must be absent
	FileScope      string   `json:"file_scope"`       // File pattern scope for this rule
	Severity       string   `json:"severity"`         // error, warning, info
}

PatternRule defines a specific verification rule

type PatternVerifier

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

PatternVerifier validates architectural patterns and compliance rules

func NewPatternVerifier

func NewPatternVerifier() *PatternVerifier

NewPatternVerifier creates a new pattern verification engine

func (*PatternVerifier) GetAvailablePatterns

func (pv *PatternVerifier) GetAvailablePatterns() []string

GetAvailablePatterns returns list of built-in architectural patterns

func (*PatternVerifier) GetPatternDetails

func (pv *PatternVerifier) GetPatternDetails(patternName string) (*ArchitecturalPattern, error)

GetPatternDetails returns details about a specific pattern

func (*PatternVerifier) VerifyArchitecturalPattern

func (pv *PatternVerifier) VerifyArchitecturalPattern(patternName string, files map[types.FileID]string, symbols map[types.FileID][]types.Symbol, fileContent map[types.FileID]string) (*VerificationResult, error)

VerifyArchitecturalPattern runs verification for a built-in architectural pattern

func (*PatternVerifier) VerifyPattern

func (pv *PatternVerifier) VerifyPattern(rule VerificationRule, files map[types.FileID]string, symbols map[types.FileID][]types.Symbol, fileContent map[types.FileID]string) (*VerificationResult, error)

VerifyPattern runs pattern verification with the given rule

type PatternViolation

type PatternViolation struct {
	File       string                 `json:"file"`
	FileID     types.FileID           `json:"file_id"`
	Rule       string                 `json:"rule"`
	Severity   string                 `json:"severity"`
	Line       int                    `json:"line"`
	Symbol     string                 `json:"symbol"`
	Issue      string                 `json:"issue"`
	Context    string                 `json:"context"`
	Suggestion string                 `json:"suggestion"`
	Evidence   []string               `json:"evidence"`
	Metadata   map[string]interface{} `json:"metadata"`
}

PatternViolation represents a single violation found

type PerformanceOptimizations

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

PerformanceOptimizations contains high-performance optimization utilities

func GetPerformanceOptimizations

func GetPerformanceOptimizations() *PerformanceOptimizations

GetPerformanceOptimizations returns the singleton performance optimizations instance

func (*PerformanceOptimizations) FastPathCheck

func (po *PerformanceOptimizations) FastPathCheck(pattern string, options interface{}) (isFast bool, indexTypes []IndexType)

FastPathCheck performs a zero-allocation fast path check for common search patterns

func (*PerformanceOptimizations) GetPerformanceMetrics

func (po *PerformanceOptimizations) GetPerformanceMetrics() map[string]interface{}

GetPerformanceMetrics returns current performance metrics

func (*PerformanceOptimizations) GetResultSliceFromPool

func (po *PerformanceOptimizations) GetResultSliceFromPool() []SearchResult

GetResultSliceFromPool gets a pre-allocated result slice

func (*PerformanceOptimizations) GetSearchContextFromPool

func (po *PerformanceOptimizations) GetSearchContextFromPool() *FastSearchContext

GetSearchContextFromPool gets a pre-allocated search context

func (*PerformanceOptimizations) GetStringFromPool

func (po *PerformanceOptimizations) GetStringFromPool() []byte

GetStringFromPool gets a string buffer from the pool (zero-allocation)

func (*PerformanceOptimizations) OptimizeIndexTypeSlice

func (po *PerformanceOptimizations) OptimizeIndexTypeSlice(indexTypes []IndexType) []IndexType

OptimizeIndexTypeSlice optimizes index type slice operations

func (*PerformanceOptimizations) OptimizeMemoryUsage

func (po *PerformanceOptimizations) OptimizeMemoryUsage()

OptimizeMemoryUsage optimizes memory usage by cleaning up pools

func (*PerformanceOptimizations) OptimizeStringOperations

func (po *PerformanceOptimizations) OptimizeStringOperations(s string) string

OptimizeStringOperations provides zero-allocation string operations

func (*PerformanceOptimizations) ReturnResultSliceToPool

func (po *PerformanceOptimizations) ReturnResultSliceToPool(slice []SearchResult)

ReturnResultSliceToPool returns a result slice to the pool

func (*PerformanceOptimizations) ReturnSearchContextToPool

func (po *PerformanceOptimizations) ReturnSearchContextToPool(ctx *FastSearchContext)

ReturnSearchContextToPool returns a search context to the pool

func (*PerformanceOptimizations) ReturnStringToPool

func (po *PerformanceOptimizations) ReturnStringToPool(buf []byte)

ReturnStringToPool returns a string buffer to the pool

type PerformanceProfiler

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

PerformanceProfiler provides lightweight performance profiling

func GetPerformanceProfiler

func GetPerformanceProfiler() *PerformanceProfiler

GetPerformanceProfiler returns the performance profiler

func (*PerformanceProfiler) Enable

func (pp *PerformanceProfiler) Enable(enabled bool)

Enable enables or disables profiling

func (*PerformanceProfiler) GetProfileResults

func (pp *PerformanceProfiler) GetProfileResults() map[string]interface{}

GetProfileResults returns profiling results

func (*PerformanceProfiler) ProfileOperation

func (pp *PerformanceProfiler) ProfileOperation(name string, fn func() error) error

ProfileOperation profiles an operation execution time

type Position

type Position struct {
	Line   int
	Column int
}

Position represents a line/column coordinate

type PositionedSymbol

type PositionedSymbol struct {
	Symbol   types.Symbol
	SymbolID types.SymbolID // Store ID for O(1) lookup
	StartPos Position
	EndPos   Position
}

PositionedSymbol represents a symbol with its exact position

type PostingsIndex

type PostingsIndex struct {

	// Flag to indicate bulk indexing mode (lock-free when true)
	BulkIndexing int32
	// contains filtered or unexported fields
}

PostingsIndex stores token -> (fileID -> firstOffset). Offsets are byte positions in original file content. For memory efficiency we only store the first offset per (token,file). Note: This index is ASCII-focused and best-effort; non-ASCII tokens are ignored.

func NewPostingsIndex

func NewPostingsIndex() *PostingsIndex

func (*PostingsIndex) Find

func (pi *PostingsIndex) Find(token string, caseInsensitive bool) (files []types.FileID, firstOffsets map[types.FileID]int)

Find returns candidate files and first offsets for a token. If caseInsensitive is true, the token is lowercased before lookup.

func (*PostingsIndex) IndexFile

func (pi *PostingsIndex) IndexFile(fileID types.FileID, content []byte)

IndexFile tokenizes ASCII word tokens (a-z,A-Z,0-9,_) and records the first occurrence offset per token for this file. Skips tokens shorter than 3.

func (*PostingsIndex) RemoveFile

func (pi *PostingsIndex) RemoveFile(fileID types.FileID)

RemoveFile removes all postings for a given fileID.

type PropagatedDependency

type PropagatedDependency struct {
	Type     string                 `json:"type"`
	Count    int                    `json:"count"`
	Sources  []types.SymbolID       `json:"sources"`
	Depth    int                    `json:"depth"`
	Weight   float64                `json:"weight"`
	Details  []DependencyDetail     `json:"details"`
	Metadata map[string]interface{} `json:"metadata"`
}

PropagatedDependency represents an aggregated dependency

type PropagatedLabel

type PropagatedLabel struct {
	Label      string                 `json:"label"`
	Strength   float64                `json:"strength"`
	Source     types.SymbolID         `json:"source"`
	Path       []types.SymbolID       `json:"path"`
	Hops       int                    `json:"hops"`
	Metadata   map[string]interface{} `json:"metadata"`
	Confidence float64                `json:"confidence"`
}

PropagatedLabel represents a label that has been propagated to a symbol

type PropagationConfig

type PropagationConfig struct {
	// Global settings
	MaxIterations        int     `json:"max_iterations"`        // Maximum propagation iterations
	ConvergenceThreshold float64 `json:"convergence_threshold"` // Convergence threshold
	DefaultDecay         float64 `json:"default_decay"`         // Default decay rate (only used in ModeDecay)

	// Label propagation rules
	LabelRules []LabelPropagationRule `json:"label_rules"`

	// Dependency propagation rules
	DependencyRules []DependencyPropagationRule `json:"dependency_rules"`

	// Custom propagation functions
	CustomRules []CustomPropagationRule `json:"custom_rules"`

	// Analysis configuration
	AnalysisConfig AnalysisConfig `json:"analysis_config"`
}

PropagationConfig defines rules for how attributes propagate through the graph

type PropagationConfigManager

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

PropagationConfigManager handles loading, validation, and management of propagation configurations

func NewPropagationConfigManager

func NewPropagationConfigManager(configDir string) *PropagationConfigManager

NewPropagationConfigManager creates a new configuration manager

func NewPropagationConfigManagerWithFileService

func NewPropagationConfigManagerWithFileService(configDir string, fileService *FileService) *PropagationConfigManager

NewPropagationConfigManagerWithFileService creates a new configuration manager with a specific FileService

func (*PropagationConfigManager) GetAvailableTemplates

func (pcm *PropagationConfigManager) GetAvailableTemplates() []string

GetAvailableTemplates returns a list of available configuration templates

func (*PropagationConfigManager) GetTemplateInfo

func (pcm *PropagationConfigManager) GetTemplateInfo(templateName string) (*ConfigTemplate, error)

GetTemplateInfo returns information about a specific template

func (*PropagationConfigManager) LoadConfig

func (pcm *PropagationConfigManager) LoadConfig(name string) (*PropagationConfig, error)

LoadConfig loads a configuration from file

func (*PropagationConfigManager) LoadConfigFromTemplate

func (pcm *PropagationConfigManager) LoadConfigFromTemplate(templateName string, variables map[string]interface{}) (*PropagationConfig, error)

LoadConfigFromTemplate loads and customizes a configuration template

func (*PropagationConfigManager) MergeConfigs

func (pcm *PropagationConfigManager) MergeConfigs(configs ...*PropagationConfig) *PropagationConfig

MergeConfigs merges multiple configurations with priority handling

func (*PropagationConfigManager) SaveConfig

func (pcm *PropagationConfigManager) SaveConfig(name string, config *PropagationConfig, format string) error

SaveConfig saves a configuration to file

func (*PropagationConfigManager) ValidateConfig

func (pcm *PropagationConfigManager) ValidateConfig(config *PropagationConfig) error

ValidateConfig validates a configuration for consistency and correctness

type PropagationInfo

type PropagationInfo struct {
	Label     string       `json:"label"`     // "critical-bug", "performance-cost", etc.
	Source    CodeObjectID `json:"source"`    // Where it originates
	Strength  float64      `json:"strength"`  // Propagation strength
	Direction string       `json:"direction"` // "upstream", "downstream", "bidirectional"
}

type PropagationKey

type PropagationKey struct {
	SymbolID  types.SymbolID `json:"symbol_id"`
	Attribute string         `json:"attribute"` // Label name or dependency type
	Type      string         `json:"type"`      // "label" or "dependency"
}

PropagationKey uniquely identifies a propagation value

type PropagationMode

type PropagationMode string

PropagationMode defines how properties propagate through the call graph

const (
	// ModeReachability: Binary reachability - all reachable symbols get full strength (1.0)
	// Use for: Bug propagation, security vulnerabilities, dependency existence
	// Semantics: If function A calls function B with @lci:critical, A is also critical (not 0.7× critical)
	ModeReachability PropagationMode = "reachability"

	// ModeAccumulation: Strength accumulates upward through call graph
	// Use for: Performance costs, database call counts, resource usage
	// Semantics: If A calls B (1 DB call) and C (2 DB calls), A has 3 DB calls total
	ModeAccumulation PropagationMode = "accumulation"

	// ModeDecay: Strength decays per hop (PageRank-style)
	// Use for: UI relevance ranking, attention priority for search results
	// Semantics: Direct callers 100% relevant, 2-hop 80% relevant, 5-hop 33% relevant
	// WARNING: This is primarily a UI heuristic, not a semantic property of code
	ModeDecay PropagationMode = "decay"

	// ModeMax: Take maximum strength along any path
	// Use for: Risk assessment, criticality levels, priority propagation
	// Semantics: If A calls B (priority=3) and C (priority=5), A gets priority=5
	ModeMax PropagationMode = "max"
)

type PropagationRule

type PropagationRule struct {
	Attribute   string  `json:"attribute"`           // which attribute to propagate
	Direction   string  `json:"direction"`           // upstream, downstream, bidirectional
	Decay       float64 `json:"decay"`               // strength reduction per hop (0.0-1.0)
	MaxHops     int     `json:"max_hops"`            // maximum propagation distance
	Aggregation string  `json:"aggregation"`         // sum, max, unique, concat
	Condition   string  `json:"condition,omitempty"` // conditional propagation
}

PropagationRule defines how annotations should propagate through the graph

type PropagationValue

type PropagationValue struct {
	Strength    float64                `json:"strength"`     // Current propagation strength
	Source      types.SymbolID         `json:"source"`       // Original source symbol
	Hops        int                    `json:"hops"`         // Number of hops from source
	Path        []types.SymbolID       `json:"path"`         // Propagation path
	Metadata    map[string]interface{} `json:"metadata"`     // Additional metadata
	LastUpdated int                    `json:"last_updated"` // Iteration when last updated
}

PropagationValue stores the propagated value and metadata

type ProximityScore

type ProximityScore struct {
	SameLine     bool
	SameFunction bool
	SameFile     bool
	CallDistance int // Number of function calls between fragments
	Score        float64
}

ProximityScore represents how close fragments are in code

type PurityReport

type PurityReport struct {
	SymbolID             types.SymbolID
	FunctionName         string
	IsPure               bool
	LocalCategories      types.SideEffectCategory
	TransitiveCategories types.SideEffectCategory
	Confidence           types.PurityConfidence
	PurityScore          float64
	Reasons              []string
}

PurityReport is a human-readable report of a function's purity

type QueryMatch

type QueryMatch struct {
	CaptureNames []string          `json:"capture_names"` // Names of captured nodes (@function.name, @call.target, etc.)
	Captures     []QueryNode       `json:"captures"`      // The captured nodes
	StartByte    uint              `json:"start_byte"`
	EndByte      uint              `json:"end_byte"`
	StartPoint   tree_sitter.Point `json:"start_point"`
	EndPoint     tree_sitter.Point `json:"end_point"`
	Text         string            `json:"text"` // The matched text
}

QueryMatch represents a single match from a Tree-sitter query

type QueryNode

type QueryNode struct {
	Name       string            `json:"name"` // Capture name (@function.name, @call.target, etc.)
	Type       string            `json:"type"` // Node type (identifier, function_declaration, etc.)
	Text       string            `json:"text"` // Node text content
	StartByte  uint              `json:"start_byte"`
	EndByte    uint              `json:"end_byte"`
	StartPoint tree_sitter.Point `json:"start_point"`
	EndPoint   tree_sitter.Point `json:"end_point"`
}

QueryNode represents a captured node in a Tree-sitter query

type QueryResult

type QueryResult struct {
	FileID   types.FileID `json:"file_id"`
	FilePath string       `json:"file_path"`
	Language string       `json:"language"`
	Matches  []QueryMatch `json:"matches"`
}

QueryResult represents the result of a Tree-sitter query

type QueueStatus

type QueueStatus struct {
	IndexType       IndexType     `json:"indexType"`
	PendingOps      int           `json:"pendingOps"`
	RunningOps      int           `json:"runningOps"`
	CompletedOps    int64         `json:"completedOps"`
	FailedOps       int64         `json:"failedOps"`
	AverageWait     time.Duration `json:"averageWait"`
	AverageRuntime  time.Duration `json:"averageRuntime"`
	QueueDepth      int           `json:"queueDepth"`
	ActiveOps       int           `json:"activeOps"`
	MaxQueueDepth   int           `json:"maxQueueDepth"`
	AverageWaitTime time.Duration `json:"averageWaitTime"`
}

QueueStatus represents the status of operation queues

type RealFileSystem

type RealFileSystem struct{}

RealFileSystem implements FileSystemInterface using the actual filesystem

func (*RealFileSystem) Exists

func (rfs *RealFileSystem) Exists(path string) bool

func (*RealFileSystem) IsDir

func (rfs *RealFileSystem) IsDir(path string) bool

func (*RealFileSystem) IsFile

func (rfs *RealFileSystem) IsFile(path string) bool

func (*RealFileSystem) ReadDir

func (rfs *RealFileSystem) ReadDir(path string) ([]fs.DirEntry, error)

func (*RealFileSystem) ReadFile

func (rfs *RealFileSystem) ReadFile(path string) ([]byte, error)

func (*RealFileSystem) Stat

func (rfs *RealFileSystem) Stat(path string) (fs.FileInfo, error)

type ReferenceSpatialIndex

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

ReferenceSpatialIndex provides O(log n) spatial lookup of symbols by line/column Used specifically by ReferenceTracker for fast same-file reference resolution

func NewReferenceSpatialIndex

func NewReferenceSpatialIndex(capacity int) *ReferenceSpatialIndex

NewReferenceSpatialIndex creates a new spatial index for a file's symbols

func (*ReferenceSpatialIndex) AddSymbol

func (rsi *ReferenceSpatialIndex) AddSymbol(symbolID types.SymbolID, symbolName string, startLine, endLine, startCol, endCol int)

AddSymbol adds a symbol to the spatial index

func (*ReferenceSpatialIndex) Clear

func (rsi *ReferenceSpatialIndex) Clear()

Clear removes all symbols from the index

func (*ReferenceSpatialIndex) Count

func (rsi *ReferenceSpatialIndex) Count() int

Count returns the number of symbols in the index

func (*ReferenceSpatialIndex) FindAtLocation

func (rsi *ReferenceSpatialIndex) FindAtLocation(line, col int) types.SymbolID

FindAtLocation finds the symbol at a specific line/column location Returns 0 if no symbol found at that location Time complexity: O(log n + k) where k is the number of overlapping symbols (typically 1-3)

func (*ReferenceSpatialIndex) FindByName

func (rsi *ReferenceSpatialIndex) FindByName(name string) types.SymbolID

FindByName finds a symbol by name in this file Returns 0 if no symbol with that name exists in this file Time complexity: O(1)

type ReferenceSpatialLocation

type ReferenceSpatialLocation struct {
	StartLine int
	EndLine   int
	StartCol  int
	EndCol    int
	SymbolID  types.SymbolID
}

ReferenceSpatialLocation represents a symbol's location in a file for spatial indexing

type ReferenceStats

type ReferenceStats struct {
	TotalReferences int `json:"total_references"`
	TotalSymbols    int `json:"total_symbols"`
	FilesWithRefs   int `json:"files_with_references"`
	SymbolRefs      int `json:"symbol_references"` // Total incoming + outgoing ref count
}

ReferenceStats contains pre-computed reference tracking statistics

type ReferenceTracker

type ReferenceTracker struct {
	BulkIndexing int32
	// contains filtered or unexported fields
}

ReferenceTracker manages bidirectional symbol references and scope relationships

func NewReferenceTracker

func NewReferenceTracker(symbolLocationIndex *SymbolLocationIndex) *ReferenceTracker

NewReferenceTracker creates a new reference tracking system symbolLocationIndex can be nil for tests

func NewReferenceTrackerForTest

func NewReferenceTrackerForTest() *ReferenceTracker

NewReferenceTrackerForTest creates a ReferenceTracker for testing with a new SymbolLocationIndex

func (*ReferenceTracker) AddHeuristicReference

func (rt *ReferenceTracker) AddHeuristicReference(ref types.Reference)

AddHeuristicReference adds a reference without requiring known source/target symbols.

func (*ReferenceTracker) AddTestReference

func (rt *ReferenceTracker) AddTestReference(ref types.Reference)

AddTestReference adds a reference directly for testing purposes This bypasses normal symbol resolution and directly populates the reference maps

func (*ReferenceTracker) BuildFunctionTree

func (rt *ReferenceTracker) BuildFunctionTree(symbolID types.SymbolID, maxDepth int) *FunctionTreeNode

BuildFunctionTree builds a tree of function calls from RefTracker

func (*ReferenceTracker) BuildFunctionTreeByName

func (rt *ReferenceTracker) BuildFunctionTreeByName(functionName string, maxDepth int) *FunctionTreeNode

BuildFunctionTreeByName builds a tree of function calls from a function name

func (*ReferenceTracker) Clear

func (rt *ReferenceTracker) Clear()

Clear resets all data in the reference tracker

func (*ReferenceTracker) FindSymbolByFileAndName

func (rt *ReferenceTracker) FindSymbolByFileAndName(fileID types.FileID, name string) *types.EnhancedSymbol

FindSymbolByFileAndName finds a symbol by file ID and name. This is more precise than FindSymbolByName for disambiguation.

func (*ReferenceTracker) FindSymbolByName

func (rt *ReferenceTracker) FindSymbolByName(name string) *types.EnhancedSymbol

FindSymbolByName finds a symbol by its name (first match). This is a convenience method for expansion directives.

func (*ReferenceTracker) FindSymbolsByName

func (rt *ReferenceTracker) FindSymbolsByName(name string) []*types.EnhancedSymbol

FindSymbolsByName finds all symbols with a given name Results are automatically filtered to exclude symbols from deleted files

func (*ReferenceTracker) GetAllReferences

func (rt *ReferenceTracker) GetAllReferences() []types.Reference

GetAllReferences returns a snapshot of all references (testing/diagnostics).

func (*ReferenceTracker) GetBaseTypes

func (rt *ReferenceTracker) GetBaseTypes(typeID types.SymbolID) []types.SymbolID

GetBaseTypes returns types this type extends (inheritance chain). For a given type symbol ID, this returns all base types that this type has RefTypeExtends references pointing to.

func (*ReferenceTracker) GetCallStats

func (rt *ReferenceTracker) GetCallStats() map[string]interface{}

GetCallStats returns statistics about function calls (replaces CallGraph.GetStats)

func (*ReferenceTracker) GetCalleeNames

func (rt *ReferenceTracker) GetCalleeNames(symbolID types.SymbolID) []string

GetCalleeNames gets the names of functions called by a symbol

func (*ReferenceTracker) GetCalleeSymbols

func (rt *ReferenceTracker) GetCalleeSymbols(symbolID types.SymbolID) []types.SymbolID

GetCalleeSymbols gets the symbol IDs of functions called by this symbol

func (*ReferenceTracker) GetCallerNames

func (rt *ReferenceTracker) GetCallerNames(symbolID types.SymbolID) []string

GetCallerNames gets the names of functions that call this symbol

func (*ReferenceTracker) GetCallerSymbols

func (rt *ReferenceTracker) GetCallerSymbols(symbolID types.SymbolID) []types.SymbolID

GetCallerSymbols gets the symbol IDs of functions that call this symbol

func (*ReferenceTracker) GetDerivedTypes

func (rt *ReferenceTracker) GetDerivedTypes(baseID types.SymbolID) []types.SymbolID

GetDerivedTypes returns types that extend this type. For a given base type symbol ID, this returns all symbols that have RefTypeExtends references pointing to this type.

func (*ReferenceTracker) GetEnhancedSymbol

func (rt *ReferenceTracker) GetEnhancedSymbol(symbolID types.SymbolID) *types.EnhancedSymbol

GetEnhancedSymbol returns an enhanced symbol by ID Returns nil if the symbol is from a deleted file OPTIMIZED: Uses SymbolStore.Get for O(1) array access instead of map lookup

func (*ReferenceTracker) GetFileEnhancedSymbols

func (rt *ReferenceTracker) GetFileEnhancedSymbols(fileID types.FileID) []*types.EnhancedSymbol

GetFileEnhancedSymbols returns all enhanced symbols for a file Returns cached slice if available (zero-copy), otherwise builds and caches Returns nil if the file has been deleted

func (*ReferenceTracker) GetFileLineToSymbols

func (rt *ReferenceTracker) GetFileLineToSymbols(fileID types.FileID) map[int][]int

GetFileLineToSymbols returns pre-computed line->symbol indices for semantic filtering Returns nil if not available (caller should build on-demand as fallback)

func (*ReferenceTracker) GetFilePerfData

func (rt *ReferenceTracker) GetFilePerfData(fileID types.FileID) []types.FunctionPerfData

GetFilePerfData returns performance analysis data for a file

func (*ReferenceTracker) GetFileReferences

func (rt *ReferenceTracker) GetFileReferences(fileID types.FileID) []types.Reference

GetFileReferences returns all references where either source or target is in the given file

func (*ReferenceTracker) GetImplementedInterfaces

func (rt *ReferenceTracker) GetImplementedInterfaces(typeID types.SymbolID) []types.SymbolID

GetImplementedInterfaces returns all interfaces a type implements. For a given type symbol ID, this returns all interface symbols that this type has RefTypeImplements references pointing to.

func (*ReferenceTracker) GetImplementedInterfacesWithQuality

func (rt *ReferenceTracker) GetImplementedInterfacesWithQuality(typeID types.SymbolID) []InterfaceWithQuality

GetImplementedInterfacesWithQuality returns interfaces sorted by quality (highest first) This allows the expansion engine to prefer interfaces with stronger evidence

func (*ReferenceTracker) GetImplementors

func (rt *ReferenceTracker) GetImplementors(interfaceID types.SymbolID) []types.SymbolID

GetImplementors returns all types that implement an interface. For a given interface symbol ID, this returns all symbols that have RefTypeImplements references pointing to this interface.

func (*ReferenceTracker) GetImplementorsWithQuality

func (rt *ReferenceTracker) GetImplementorsWithQuality(interfaceID types.SymbolID) []ImplementorWithQuality

GetImplementorsWithQuality returns implementors sorted by quality (highest first) This allows the expansion engine to prefer implementations with stronger evidence (assigned, returned, cast) over heuristic matches (method name matching)

func (*ReferenceTracker) GetReferenceStats

func (rt *ReferenceTracker) GetReferenceStats() ReferenceStats

GetReferenceStats returns pre-computed reference statistics

func (*ReferenceTracker) GetRelationshipStats added in v0.4.0

func (rt *ReferenceTracker) GetRelationshipStats() map[string]int

GetRelationshipStats returns detailed stats about call graph population Used for diagnostics when relationship queries return empty

func (*ReferenceTracker) GetSymbolAtLine

func (rt *ReferenceTracker) GetSymbolAtLine(fileID types.FileID, line int) *types.EnhancedSymbol

GetSymbolAtLine finds the symbol that contains the given line in a file This is optimized for search result enhancement

func (*ReferenceTracker) GetSymbolReferences

func (rt *ReferenceTracker) GetSymbolReferences(symbolID types.SymbolID, direction string) []types.Reference

GetSymbolReferences returns all references for a symbol (incoming and outgoing)

func (*ReferenceTracker) GetTypeRelationships

func (rt *ReferenceTracker) GetTypeRelationships(symbolID types.SymbolID) *TypeRelationships

GetTypeRelationships returns all type relationships for a symbol. This includes both implements and extends relationships in both directions.

func (*ReferenceTracker) HasRelationships added in v0.4.0

func (rt *ReferenceTracker) HasRelationships() bool

HasRelationships returns true if the reference tracker has any call graph data This is used to detect if the index is in "lightweight" mode without relationships

func (*ReferenceTracker) ProcessAllReferences

func (rt *ReferenceTracker) ProcessAllReferences()

ProcessAllReferences processes all stored references after all symbols have been indexed

func (*ReferenceTracker) ProcessFile

func (rt *ReferenceTracker) ProcessFile(fileID types.FileID, path string, symbols []types.Symbol, references []types.Reference, scopes []types.ScopeInfo) []types.EnhancedSymbol

ProcessFile processes a file's enhanced symbols, references, scopes, and imports This is now split into two phases: AddSymbols and ProcessReferences

func (*ReferenceTracker) ProcessFileImports

func (rt *ReferenceTracker) ProcessFileImports(fileID types.FileID, filePath string, content []byte)

ProcessFileImports processes a file's imports for better symbol resolution This collects import data lock-free during parallel indexing

func (*ReferenceTracker) ProcessFileWithEnhanced

func (rt *ReferenceTracker) ProcessFileWithEnhanced(fileID types.FileID, path string, symbols []types.Symbol, parserEnhanced []types.EnhancedSymbol, references []types.Reference, scopes []types.ScopeInfo) []types.EnhancedSymbol

ProcessFileWithEnhanced processes a file's symbols with optional pre-computed enhanced symbols from the parser (which include complexity data). If parserEnhanced is provided, complexity values will be copied from matching symbols.

func (*ReferenceTracker) ProcessFileWithScopeChains

func (rt *ReferenceTracker) ProcessFileWithScopeChains(fileID types.FileID, path string, symbols []types.Symbol, parserEnhanced []types.EnhancedSymbol, references []types.Reference, scopes []types.ScopeInfo, scopeChains [][]types.ScopeInfo) []types.EnhancedSymbol

ProcessFileWithScopeChains processes a file's symbols with optional pre-built scope chains. When scopeChains is provided (from map phase), it uses them directly instead of rebuilding. This moves O(n × s) scope chain building from single-threaded reduce to parallel map phase.

func (*ReferenceTracker) RemoveFile

func (rt *ReferenceTracker) RemoveFile(fileID types.FileID)

RemoveFile removes all symbols and references for a specific file

func (*ReferenceTracker) SetDeletedFileTracker

func (rt *ReferenceTracker) SetDeletedFileTracker(tracker interface {
	IsDeleted(types.FileID) bool
	GetDeletedSet() interface {
		Contains(types.FileID) bool
		Len() int
	}
})

SetDeletedFileTracker sets the deleted file tracker for filtering stale symbols This must be called after construction to avoid circular dependencies

func (*ReferenceTracker) Shutdown

func (rt *ReferenceTracker) Shutdown() error

Shutdown performs graceful shutdown with resource cleanup

func (*ReferenceTracker) StoreLineToSymbols

func (rt *ReferenceTracker) StoreLineToSymbols(fileID types.FileID, lineToSymbols map[int][]int)

StoreLineToSymbols stores pre-computed line->symbol indices for a file This eliminates 1.1GB allocation in search by moving computation to indexing

func (*ReferenceTracker) StorePerfData

func (rt *ReferenceTracker) StorePerfData(fileID types.FileID, perfData []types.FunctionPerfData)

StorePerfData stores performance analysis data for a file

type RelationshipTree

type RelationshipTree struct {
	RootSymbol *types.UniversalSymbolNode `json:"root_symbol"`
	Root       *RelationshipTreeNode      `json:"root"`
	MaxDepth   int                        `json:"max_depth"`
	Relations  []types.RelationshipType   `json:"relations"`
}

RelationshipTree represents a tree of symbol relationships

type RelationshipTreeNode

type RelationshipTreeNode struct {
	Symbol   *types.UniversalSymbolNode                         `json:"symbol"`
	Depth    int                                                `json:"depth"`
	Children map[types.RelationshipType][]*RelationshipTreeNode `json:"children"`
}

RelationshipTreeNode represents a node in a relationship tree

type RequirementsBuilder

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

RequirementsBuilder provides a fluent interface for building SearchRequirements

func NewRequirementsBuilder

func NewRequirementsBuilder() *RequirementsBuilder

NewRequirementsBuilder creates a new RequirementsBuilder

func (*RequirementsBuilder) Build

Build returns the constructed SearchRequirements

func (*RequirementsBuilder) WithAll

WithAll adds all index requirements

func (*RequirementsBuilder) WithCallGraph

func (rb *RequirementsBuilder) WithCallGraph() *RequirementsBuilder

WithCallGraph adds call graph requirement

func (*RequirementsBuilder) WithContent

func (rb *RequirementsBuilder) WithContent() *RequirementsBuilder

WithContent adds content requirement

func (*RequirementsBuilder) WithIndexType

func (rb *RequirementsBuilder) WithIndexType(indexType IndexType) *RequirementsBuilder

WithIndexType adds requirement for a specific index type

func (*RequirementsBuilder) WithLocations

func (rb *RequirementsBuilder) WithLocations() *RequirementsBuilder

WithLocations adds location requirement

func (*RequirementsBuilder) WithPostings

func (rb *RequirementsBuilder) WithPostings() *RequirementsBuilder

WithPostings adds postings requirement

func (*RequirementsBuilder) WithReferences

func (rb *RequirementsBuilder) WithReferences() *RequirementsBuilder

WithReferences adds reference requirement

func (*RequirementsBuilder) WithSymbols

func (rb *RequirementsBuilder) WithSymbols() *RequirementsBuilder

WithSymbols adds symbol requirement

func (*RequirementsBuilder) WithTrigrams

func (rb *RequirementsBuilder) WithTrigrams() *RequirementsBuilder

WithTrigrams adds trigram requirement

type SearchCacheEntry

type SearchCacheEntry struct {
	Results   []types.FileID
	Timestamp time.Time
}

SearchCacheEntry holds a cached search result with metadata

type SearchEngine

type SearchEngine interface {
	Search(pattern string, options types.SearchOptions) ([]searchtypes.Result, error)
}

SearchEngine interface for regular search

type SearchLocation

type SearchLocation struct {
	FileID types.FileID
	Line   int
	Column int
	Offset int
}

SearchLocation represents a pre-computed search match location

type SearchOperation

type SearchOperation struct {
	ID            string             `json:"id"`
	Requirements  SearchRequirements `json:"requirements"`
	AcquiredLocks []IndexType        `json:"acquiredLocks"`
	StartTime     time.Time          `json:"startTime"`
	Timeout       time.Duration      `json:"timeout"`
}

SearchOperation represents an active search operation

type SearchRequirements

type SearchRequirements struct {
	NeedsTrigrams   bool `json:"needsTrigrams"`
	NeedsSymbols    bool `json:"needsSymbols"`
	NeedsReferences bool `json:"needsReferences"`
	NeedsCallGraph  bool `json:"needsCallGraph"`
	NeedsPostings   bool `json:"needsPostings"`
	NeedsLocations  bool `json:"needsLocations"`
	NeedsContent    bool `json:"needsContent"`
}

SearchRequirements defines which index types are required for a specific search operation

func AnalyzePattern

func AnalyzePattern(pattern string) SearchRequirements

AnalyzePattern determines search requirements based on a search pattern

func AnalyzeSearchOptions

func AnalyzeSearchOptions(options interface{}) SearchRequirements

AnalyzeSearchOptions determines search requirements based on search options This would be implemented based on the actual search options structure For now, it returns comprehensive requirements

func NewComprehensiveRequirements

func NewComprehensiveRequirements() SearchRequirements

NewComprehensiveRequirements creates SearchRequirements that needs all indexes

func NewSearchRequirements

func NewSearchRequirements() SearchRequirements

NewSearchRequirements creates a new SearchRequirements with all values set to false

func NewSymbolOnlyRequirements

func NewSymbolOnlyRequirements() SearchRequirements

NewSymbolOnlyRequirements creates SearchRequirements that only needs symbol index

func NewTrigramOnlyRequirements

func NewTrigramOnlyRequirements() SearchRequirements

NewTrigramOnlyRequirements creates SearchRequirements that only needs trigram index

func (SearchRequirements) GetComplexity

func (sr SearchRequirements) GetComplexity() int

GetComplexity returns a score representing the complexity of the search requirements Higher values indicate more complex searches that require more indexes

func (SearchRequirements) GetRequiredIndexTypes

func (sr SearchRequirements) GetRequiredIndexTypes() []IndexType

GetRequiredIndexTypes returns a slice of all required index types

func (SearchRequirements) HasAnyRequirements

func (sr SearchRequirements) HasAnyRequirements() bool

HasAnyRequirements returns true if at least one requirement is set to true

func (SearchRequirements) Intersection

Intersection returns a new SearchRequirements that includes only requirements present in both

func (SearchRequirements) IsSubset

func (sr SearchRequirements) IsSubset(other SearchRequirements) bool

IsSubset returns true if this SearchRequirements is a subset of the other requirements

func (SearchRequirements) Merge

Merge combines two SearchRequirements, returning a new requirements that includes all requirements from both

func (SearchRequirements) RequiresIndex

func (sr SearchRequirements) RequiresIndex(indexType IndexType) bool

RequiresIndex returns true if the specified index type is required

func (SearchRequirements) String

func (sr SearchRequirements) String() string

String returns a human-readable string representation of the requirements

func (SearchRequirements) Validate

func (sr SearchRequirements) Validate() error

Validate validates the search requirements and returns an error if invalid

type SearchResult

type SearchResult struct {
	File          string  `json:"file"`
	Line          int     `json:"line"`
	Column        int     `json:"column"`
	Score         float64 `json:"score"`
	Match         string  `json:"match"`
	Context       string  `json:"context"`
	SymbolName    string  `json:"symbol_name,omitempty"`
	SymbolType    string  `json:"symbol_type,omitempty"`
	IsDeclaration bool    `json:"is_declaration,omitempty"`
}

SearchResult represents a search result for LLM optimization

type SearchResults

type SearchResults struct {
	LineNumbers []int
	Lines       []types.ZeroAllocStringRef
	Context     map[int][]types.ZeroAllocStringRef
}

SearchResults represents zero-allocation search results

type SemanticAnnotation

type SemanticAnnotation struct {
	// Core metadata
	Labels   []string          `json:"labels"`   // @lci:labels[api,public,critical]
	Category string            `json:"category"` // @lci:category[endpoint]
	Tags     map[string]string `json:"tags"`     // @lci:tag[team=backend,owner=alice]

	// Exclusion directives - exclude from specific analyses
	// @lci:exclude[memory] - exclude from memory pressure analysis
	// @lci:exclude[memory,complexity] - exclude from multiple analyses
	// @lci:exclude[all] - exclude from all optional analyses
	Excludes []string `json:"excludes,omitempty"`

	// Dependency information
	Dependencies []Dependency `json:"dependencies"` // @lci:deps[db:read,service:auth]
	Provides     []string     `json:"provides"`     // @lci:provides[user-auth,session]

	// Metrics and attributes
	Metrics    map[string]interface{} `json:"metrics"`    // @lci:metrics[complexity=high,perf=slow]
	Attributes map[string]interface{} `json:"attributes"` // @lci:attr[timeout=30s,retries=3]

	// Memory analysis control annotations
	// @lci:loop-weight[0.1] - Override loop iteration multiplier (0.0-100.0, default varies by loop type)
	// @lci:loop-bounded[3] - Mark loop as bounded with max iterations (reduces false positives for retry loops)
	// @lci:call-frequency[once-per-request] - Hint about how often this code runs
	//   Values: hot-path, once-per-file, once-per-request, once-per-session, startup-only, cli-output
	// @lci:propagation-weight[0.5] - Override propagation damping factor for this function (0.0-1.0)
	MemoryHints *MemoryAnalysisHints `json:"memory_hints,omitempty"`

	// Propagation configuration
	PropagationRules []PropagationRule `json:"propagation_rules,omitempty"`

	// Source location
	SourceLocation AnnotationLocation `json:"source_location"`

	// Extraction metadata
	RawText     string   `json:"raw_text"`
	ParsedLines []string `json:"parsed_lines"`
	Confidence  float64  `json:"confidence"`
}

SemanticAnnotation contains structured metadata extracted from comments

type SemanticAnnotator

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

SemanticAnnotator extracts and manages semantic annotations from code comments Supports structured comment-based metadata for enhanced code understanding

func NewSemanticAnnotator

func NewSemanticAnnotator() *SemanticAnnotator

NewSemanticAnnotator creates a new semantic annotation system with shared cached patterns

func (*SemanticAnnotator) ExtractAnnotations

func (sa *SemanticAnnotator) ExtractAnnotations(fileID types.FileID, filePath string, content string, symbols []types.Symbol) error

ExtractAnnotations processes file content to extract semantic annotations

func (*SemanticAnnotator) GetAnnotation

func (sa *SemanticAnnotator) GetAnnotation(fileID types.FileID, symbolID types.SymbolID) *SemanticAnnotation

GetAnnotation retrieves annotation for a specific symbol

func (*SemanticAnnotator) GetAnnotationStats

func (sa *SemanticAnnotator) GetAnnotationStats() map[string]interface{}

GetAnnotationStats provides statistics about extracted annotations

func (*SemanticAnnotator) GetDependencyGraph

func (sa *SemanticAnnotator) GetDependencyGraph() map[types.SymbolID][]Dependency

GetDependencyGraph builds a dependency graph from annotations

func (*SemanticAnnotator) GetExcludedSymbols

func (sa *SemanticAnnotator) GetExcludedSymbols(analysisType string) []*AnnotatedSymbol

GetExcludedSymbols returns all symbols excluded from a specific analysis type

func (*SemanticAnnotator) GetMemoryHints

func (sa *SemanticAnnotator) GetMemoryHints(fileID types.FileID, symbolID types.SymbolID) *MemoryAnalysisHints

GetMemoryHints retrieves memory analysis hints for a specific symbol Returns nil if no memory hints are defined for the symbol

func (*SemanticAnnotator) GetSymbolsByCategory

func (sa *SemanticAnnotator) GetSymbolsByCategory(category string) []*AnnotatedSymbol

GetSymbolsByCategory finds all symbols in a specific category

func (*SemanticAnnotator) GetSymbolsByLabel

func (sa *SemanticAnnotator) GetSymbolsByLabel(label string) []*AnnotatedSymbol

GetSymbolsByLabel finds all symbols with a specific label

func (*SemanticAnnotator) IsExcludedFromAnalysis

func (sa *SemanticAnnotator) IsExcludedFromAnalysis(fileID types.FileID, symbolID types.SymbolID, analysisType string) bool

IsExcludedFromAnalysis checks if a symbol should be excluded from a specific analysis type. Supported analysis types: "memory", "complexity", "duplicates", "all" Returns true if the symbol has @lci:exclude[analysisType] or @lci:exclude[all]

type SemanticContext

type SemanticContext struct {
	EntryPointDependencies []EntryPointRef   `json:"entry_point_dependencies"`
	ServiceDependencies    []ServiceRef      `json:"service_dependencies"`
	PropagationLabels      []PropagationInfo `json:"propagation_labels"`
	CriticalityAnalysis    CriticalityInfo   `json:"criticality_analysis"`
	Purpose                string            `json:"purpose"` // "API handler", "utility function", etc.
	Confidence             float64           `json:"confidence"`
}

SemanticContext provides semantic meaning and dependencies

type SemanticIndexStats

type SemanticIndexStats struct {
	TotalSymbols      int
	UniqueWords       int
	UniqueStems       int
	UniquePhonetics   int
	AbbreviationCount int
	MemoryEstimate    int64 // Estimated bytes
}

SemanticIndexStats contains statistics about the semantic index

type SemanticIndexUpdate

type SemanticIndexUpdate struct {
	SymbolID   types.SymbolID
	SymbolName string
	Words      []string
	Stems      []string
	Phonetic   string
	Expansions []string
}

SemanticIndexUpdate represents a batch update to the semantic index

type SemanticSearchIndex

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

SemanticSearchIndex provides pre-computed semantic search optimizations Built during indexing phase to eliminate search-time computation overhead

Memory overhead: ~240 bytes per symbol for 10K symbols (~2.4MB total) Performance gain: 40-60% reduction in search time by eliminating:

  • Name splitting (28% of CPU)
  • Stemming computation (10% of CPU)
  • Abbreviation expansion
  • Phonetic code generation

Thread-safety: Lock-free reads with atomic state management

func NewSemanticSearchIndex

func NewSemanticSearchIndex() *SemanticSearchIndex

NewSemanticSearchIndex creates a new semantic search index

func (*SemanticSearchIndex) AddSymbolData

func (ssi *SemanticSearchIndex) AddSymbolData(
	symbolID types.SymbolID,
	symbolName string,
	words []string,
	stems []string,
	phonetic string,
	expansions []string,
)

AddSymbolData adds semantic data for a symbol (used during reduce phase) This is the atomic operation that builds the final semantic index

func (*SemanticSearchIndex) AddSymbolDataBatch

func (ssi *SemanticSearchIndex) AddSymbolDataBatch(updates []*SemanticIndexUpdate)

AddSymbolDataBatch adds multiple symbols in a single atomic update This is much more efficient than AddSymbolData for bulk loads Reduces map copies from O(n*m) to O(m) where n=symbols, m=map count

func (*SemanticSearchIndex) Close

func (ssi *SemanticSearchIndex) Close()

Close shuts down the semantic index No-op for the simplified implementation since there are no background goroutines

func (*SemanticSearchIndex) GetOperationalMetrics

func (ssi *SemanticSearchIndex) GetOperationalMetrics() OperationalMetrics

GetOperationalMetrics returns operational statistics

func (*SemanticSearchIndex) GetStats

func (ssi *SemanticSearchIndex) GetStats() SemanticIndexStats

GetStats returns statistics about the semantic index

func (*SemanticSearchIndex) GetSymbolName

func (ssi *SemanticSearchIndex) GetSymbolName(symbolID types.SymbolID) string

GetSymbolName returns the symbol name for a given symbolID (lock-free)

func (*SemanticSearchIndex) GetSymbolNames

func (ssi *SemanticSearchIndex) GetSymbolNames(symbolIDs []types.SymbolID) []string

GetSymbolNames returns symbol names for multiple symbolIDs (lock-free)

func (*SemanticSearchIndex) GetSymbolWords

func (ssi *SemanticSearchIndex) GetSymbolWords(symbolID types.SymbolID) []string

GetSymbolWords returns pre-split words for a symbol (lock-free)

func (*SemanticSearchIndex) GetSymbolsByAbbreviation

func (ssi *SemanticSearchIndex) GetSymbolsByAbbreviation(abbrev string) []types.SymbolID

GetSymbolsByAbbreviation returns symbols with abbreviation expansion (lock-free)

func (*SemanticSearchIndex) GetSymbolsByPhonetic

func (ssi *SemanticSearchIndex) GetSymbolsByPhonetic(code string) []types.SymbolID

GetSymbolsByPhonetic returns symbols with similar phonetic code (lock-free)

func (*SemanticSearchIndex) GetSymbolsByStem

func (ssi *SemanticSearchIndex) GetSymbolsByStem(stem string) []types.SymbolID

GetSymbolsByStem returns symbols with a specific stem (lock-free)

func (*SemanticSearchIndex) GetSymbolsByWord

func (ssi *SemanticSearchIndex) GetSymbolsByWord(word string) []types.SymbolID

GetSymbolsByWord returns symbols containing a specific word (lock-free)

type ServiceRef

type ServiceRef struct {
	ServiceName    string  `json:"service_name"`
	OperationType  string  `json:"operation_type"`  // "database", "http", "message_queue"
	DependencyType string  `json:"dependency_type"` // "direct", "indirect", "transitive"
	Confidence     float64 `json:"confidence"`
}

type ShardedTrigramStorage

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

ShardedTrigramStorage manages trigram data across multiple buckets Each bucket can be updated independently without blocking other buckets

func NewShardedTrigramStorage

func NewShardedTrigramStorage(bucketCount uint16) *ShardedTrigramStorage

NewShardedTrigramStorage creates a new sharded storage with the specified number of buckets

func (*ShardedTrigramStorage) Clear

func (s *ShardedTrigramStorage) Clear()

Clear removes all trigrams from all buckets

func (*ShardedTrigramStorage) GetBucket

func (s *ShardedTrigramStorage) GetBucket(trigramHash uint32) *TrigramBucket

GetBucket returns the bucket for a given trigram hash NOTE: This is for search/read operations only. For writes, use MergeBucketDataForWorker

func (*ShardedTrigramStorage) GetBucketByID

func (s *ShardedTrigramStorage) GetBucketByID(bucketID int) *TrigramBucket

GetBucketByID returns the bucket for a given bucket ID NOTE: This is for search/read operations only. For writes, use MergeBucketDataForWorker This method is kept for compatibility but should not be used for writes

func (*ShardedTrigramStorage) GetBucketCount

func (s *ShardedTrigramStorage) GetBucketCount() int

GetBucketCount returns the total number of buckets

func (*ShardedTrigramStorage) MergeBucketDataForWorker

func (s *ShardedTrigramStorage) MergeBucketDataForWorker(
	result *BucketedTrigramResult,
	bucketStart, bucketEnd int,
	allocator *alloc.SlabAllocator[FileLocation],
)

MergeBucketDataForWorker merges trigrams for a specific bucket range This is thread-safe and should be used by merger workers instead of accessing buckets directly

func (*ShardedTrigramStorage) MergeBucketedTrigrams

func (s *ShardedTrigramStorage) MergeBucketedTrigrams(
	result *BucketedTrigramResult,
	allocator *alloc.SlabAllocator[FileLocation],
)

MergeBucketedTrigrams merges pre-bucketed trigrams into storage Each bucket is processed independently, allowing parallel merging

func (*ShardedTrigramStorage) RemoveFile

func (s *ShardedTrigramStorage) RemoveFile(fileID types.FileID)

RemoveFile removes all occurrences of a file from all buckets

func (*ShardedTrigramStorage) SearchTrigram

func (s *ShardedTrigramStorage) SearchTrigram(trigramHash uint32) []FileLocation

SearchTrigram searches for a trigram across all buckets

type SideEffectPropagationConfig

type SideEffectPropagationConfig struct {
	// MaxIterations limits propagation iterations (for cycle detection)
	MaxIterations int

	// PropagateIO - if true, I/O effects propagate to callers
	PropagateIO bool

	// PropagateThrows - if true, throw/panic effects propagate to callers
	PropagateThrows bool

	// PropagateGlobalWrites - if true, global write effects propagate to callers
	PropagateGlobalWrites bool

	// ConfidenceDecay - how much confidence decays per hop (e.g., 0.9 = 10% decay)
	ConfidenceDecay float64

	// MinConfidence - minimum confidence to continue propagation
	MinConfidence float64
}

SideEffectPropagationConfig controls propagation behavior

func DefaultSideEffectPropagationConfig

func DefaultSideEffectPropagationConfig() *SideEffectPropagationConfig

DefaultSideEffectPropagationConfig returns sensible defaults

type SideEffectPropagator

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

SideEffectPropagator propagates side effect information through the call graph. This allows transitive purity analysis - a function that calls an impure function is itself impure, even if its local analysis shows no side effects.

func NewSideEffectPropagator

func NewSideEffectPropagator(refTracker *ReferenceTracker, symbolIndex *SymbolIndex, config *SideEffectPropagationConfig) *SideEffectPropagator

NewSideEffectPropagator creates a new propagator

func (*SideEffectPropagator) AddLocalSideEffect

func (sep *SideEffectPropagator) AddLocalSideEffect(symbolID types.SymbolID, info *types.SideEffectInfo)

AddLocalSideEffect registers locally-detected side effect info for a symbol

func (*SideEffectPropagator) GetAllSideEffects

func (sep *SideEffectPropagator) GetAllSideEffects() map[types.SymbolID]*types.SideEffectInfo

GetAllSideEffects returns all side effect info

func (*SideEffectPropagator) GetFunctionsByPurity

func (sep *SideEffectPropagator) GetFunctionsByPurity() map[types.PurityConfidence][]types.SymbolID

GetFunctionsByPurity returns functions grouped by their purity confidence

func (*SideEffectPropagator) GetImpureFunctions

func (sep *SideEffectPropagator) GetImpureFunctions() []types.SymbolID

GetImpureFunctions returns all functions with detected side effects

func (*SideEffectPropagator) GetIterationCount

func (sep *SideEffectPropagator) GetIterationCount() int

GetIterationCount returns the number of propagation iterations performed

func (*SideEffectPropagator) GetPureFunctions

func (sep *SideEffectPropagator) GetPureFunctions() []types.SymbolID

GetPureFunctions returns all functions detected as pure

func (*SideEffectPropagator) GetPurityReport

func (sep *SideEffectPropagator) GetPurityReport(symbolID types.SymbolID) *PurityReport

GetPurityReport generates a human-readable purity report for a symbol

func (*SideEffectPropagator) GetSideEffectInfo

func (sep *SideEffectPropagator) GetSideEffectInfo(symbolID types.SymbolID) *types.SideEffectInfo

GetSideEffectInfo returns the side effect info for a symbol (including propagated effects)

func (*SideEffectPropagator) Propagate

func (sep *SideEffectPropagator) Propagate() error

Propagate performs transitive side effect propagation through the call graph. Side effects flow upstream: if A calls B and B has side effects, A inherits them.

func (*SideEffectPropagator) PropagateSideEffectsFromResults

func (sep *SideEffectPropagator) PropagateSideEffectsFromResults(
	fileID types.FileID,
	results map[string]*types.SideEffectInfo,
)

PropagateSideEffectsFromResults takes results from the unified extractor and registers them for propagation using the reference tracker to find symbol IDs.

type StringPool

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

StringPool provides centralized string storage with efficient range-based access

func NewStringPool

func NewStringPool() *StringPool

NewStringPool creates a new string pool

func (*StringPool) CreateSubrange

func (sp *StringPool) CreateSubrange(parent StringRange, start, length uint32) StringRange

CreateSubrange creates a new StringRange that is a subset of an existing range

func (*StringPool) GetRangeString

func (sp *StringPool) GetRangeString(r StringRange) (string, bool)

GetRangeString retrieves the substring specified by a StringRange

func (*StringPool) GetString

func (sp *StringPool) GetString(id uint32) (string, bool)

GetString retrieves the full string for a given pool ID

func (*StringPool) Intern

func (sp *StringPool) Intern(s string) uint32

Intern adds a string to the pool and returns its ID If the string already exists, returns the existing ID

func (*StringPool) InternRange

func (sp *StringPool) InternRange(s string) StringRange

InternRange adds a string to the pool and returns a StringRange for the full string

type StringRange

type StringRange struct {
	PoolID uint32 // ID of the string pool entry
	Start  uint32 // Start offset in the pooled string
	Length uint32 // Length of the substring
}

StringRange represents a range within a pooled string

type StructureContext

type StructureContext struct {
	FilePath                string            `json:"file_path"`
	Module                  string            `json:"module"`
	Package                 string            `json:"package"`
	Imports                 []ImportInfo      `json:"imports"`
	Exports                 []ExportInfo      `json:"exports"`
	InterfaceImplementation []InterfaceInfo   `json:"interface_implementations"`
	InheritanceChain        []ObjectReference `json:"inheritance_chain"`
	CompositionPattern      string            `json:"composition_pattern"`
}

StructureContext provides structural information about the code object

type SymbolIndex

type SymbolIndex struct {

	// Flag to indicate bulk indexing mode (lock-free when true)
	BulkIndexing int32
	// contains filtered or unexported fields
}

func NewSymbolIndex

func NewSymbolIndex() *SymbolIndex

func (*SymbolIndex) ClearAll

func (si *SymbolIndex) ClearAll()

ClearAll removes all symbols and resets statistics Call with lock held

func (*SymbolIndex) Count

func (si *SymbolIndex) Count() int

Count returns the total number of symbols (definitions + references)

func (*SymbolIndex) DefinitionCount

func (si *SymbolIndex) DefinitionCount() int

DefinitionCount returns the number of symbol definitions

func (*SymbolIndex) FinalizeStats

func (si *SymbolIndex) FinalizeStats()

FinalizeStats performs final optimization of statistics Should be called once after all files have been indexed Builds TopSymbols from the frequency map (expensive operation, done once)

func (*SymbolIndex) FindDefinitions

func (si *SymbolIndex) FindDefinitions(symbolName string) []searchtypes.Result

func (*SymbolIndex) FindReferences

func (si *SymbolIndex) FindReferences(symbolName string) []searchtypes.Result

func (*SymbolIndex) GetAllDefinitions

func (si *SymbolIndex) GetAllDefinitions() map[string][]types.Symbol

GetAllDefinitions returns all symbol definitions Used for semantic search which scores all symbols

func (*SymbolIndex) GetAllFileIDs

func (si *SymbolIndex) GetAllFileIDs() []types.FileID

GetAllFileIDs returns all FileIDs that have symbols indexed

func (*SymbolIndex) GetAllMetrics

func (si *SymbolIndex) GetAllMetrics() map[types.FileID]map[string]interface{}

GetAllMetrics returns all stored metrics for debugging

func (*SymbolIndex) GetAllSymbolNames

func (si *SymbolIndex) GetAllSymbolNames() []string

GetAllSymbolNames returns all unique symbol names from definitions This is efficient since the symbol index is small (deduped) compared to content

func (*SymbolIndex) GetEntryPoints

func (si *SymbolIndex) GetEntryPoints() []types.Symbol

GetEntryPoints returns all entry point symbols (main, init, exported) Results are automatically filtered to exclude symbols from deleted files

func (*SymbolIndex) GetFileMetrics

func (si *SymbolIndex) GetFileMetrics(fileID types.FileID) map[string]interface{}

GetFileMetrics retrieves all metrics for a file

func (*SymbolIndex) GetFilePath

func (si *SymbolIndex) GetFilePath(fileID types.FileID) (string, bool)

GetFilePath returns the file path for a FileID

func (*SymbolIndex) GetStats

func (si *SymbolIndex) GetStats() SymbolIndexStats

GetStats returns pre-computed symbol statistics Embedded slices (EntryPoints, ExportedSymbols, TopSymbols) are filtered to exclude deleted files

func (*SymbolIndex) GetSymbolMetrics

func (si *SymbolIndex) GetSymbolMetrics(fileID types.FileID, symbolName string) interface{}

GetSymbolMetrics retrieves metrics for a symbol

func (*SymbolIndex) GetTopSymbols

func (si *SymbolIndex) GetTopSymbols(limit int) []SymbolWithScore

GetTopSymbols returns most referenced symbols Results are automatically filtered to exclude symbols from deleted files

func (*SymbolIndex) GetTypeDistribution

func (si *SymbolIndex) GetTypeDistribution() map[types.SymbolType]int

GetTypeDistribution returns histogram of symbol types

func (*SymbolIndex) IndexSymbols

func (si *SymbolIndex) IndexSymbols(fileID types.FileID, symbols []types.Symbol)

func (*SymbolIndex) RemoveFileMetrics

func (si *SymbolIndex) RemoveFileMetrics(fileID types.FileID)

RemoveFileMetrics removes all metrics for a file

func (*SymbolIndex) RemoveFileSymbols

func (si *SymbolIndex) RemoveFileSymbols(fileID types.FileID)

RemoveFileSymbols removes all symbols for a specific file

func (*SymbolIndex) RemoveSymbols

func (si *SymbolIndex) RemoveSymbols(fileID types.FileID, symbols []types.Symbol)

func (*SymbolIndex) SetDeletedFileTracker

func (si *SymbolIndex) SetDeletedFileTracker(tracker deletedFileTrackerInterface)

SetDeletedFileTracker sets the deleted file tracker for filtering stale symbols This must be called after construction to avoid circular dependencies

func (*SymbolIndex) StoreSymbolMetrics

func (si *SymbolIndex) StoreSymbolMetrics(fileID types.FileID, symbolName string, metrics interface{})

StoreSymbolMetrics stores metrics for a symbol

func (*SymbolIndex) UpdateStatsIncremental

func (si *SymbolIndex) UpdateStatsIncremental(fileID types.FileID, symbols []types.Symbol)

UpdateStatsIncremental updates statistics incrementally without full recomputation This is much faster than updateStatsLocked and should be called for each file during indexing Call with lock held

func (*SymbolIndex) UpdateSymbols

func (si *SymbolIndex) UpdateSymbols(fileID types.FileID, oldSymbols, newSymbols []types.Symbol)

type SymbolIndexStats

type SymbolIndexStats struct {
	TotalSymbols   int `json:"total_symbols"`
	TotalFunctions int `json:"total_functions"`
	TotalMethods   int `json:"total_methods"`
	TotalTypes     int `json:"total_types"`
	TotalVariables int `json:"total_variables"`
	FileCount      int `json:"file_count"`

	// Top-N sorted results
	TopSymbols      []SymbolWithScore `json:"top_symbols,omitempty"`
	ExportedSymbols []types.Symbol    `json:"exported_symbols,omitempty"`
	EntryPoints     []types.Symbol    `json:"entry_points,omitempty"`

	// Distribution data
	TypeDistribution map[types.SymbolType]int `json:"type_distribution"`
}

SymbolIndexStats contains pre-computed, queryable statistics

type SymbolLocationIndex

type SymbolLocationIndex struct {

	// Flag to indicate bulk indexing mode (lock-free when true)
	BulkIndexing int32
	// contains filtered or unexported fields
}

SymbolLocationIndex provides instant symbol lookup by file position Uses a 2-level spatial index: file → line → column → symbol for O(1) lookup

func NewSymbolLocationIndex

func NewSymbolLocationIndex() *SymbolLocationIndex

NewSymbolLocationIndex creates a new symbol location index

func (*SymbolLocationIndex) Clear

func (sli *SymbolLocationIndex) Clear()

Clear removes all indexed symbols

func (*SymbolLocationIndex) FindSymbolAtPosition

func (sli *SymbolLocationIndex) FindSymbolAtPosition(fileID types.FileID, line, column int) *types.Symbol

FindSymbolAtPosition finds the symbol at a specific line/column in a file Returns the most specific symbol (smallest range) that contains the position

func (*SymbolLocationIndex) FindSymbolIDAtPosition

func (sli *SymbolLocationIndex) FindSymbolIDAtPosition(fileID types.FileID, line, column int) types.SymbolID

FindSymbolIDAtPosition finds the symbol ID at a specific line/column in a file Returns the most specific symbol ID (smallest range) that contains the position Uses spatial indexing for O(1) average case lookup

func (*SymbolLocationIndex) GetFileSymbols

func (sli *SymbolLocationIndex) GetFileSymbols(fileID types.FileID) []types.Symbol

GetFileSymbols returns all symbols in a file

func (*SymbolLocationIndex) GetStats

func (sli *SymbolLocationIndex) GetStats() map[string]interface{}

GetStats returns statistics about the symbol location index

func (*SymbolLocationIndex) IndexFileSymbols

func (sli *SymbolLocationIndex) IndexFileSymbols(fileID types.FileID, symbols []types.Symbol, enhancedSymbols []*types.EnhancedSymbol)

IndexFileSymbols indexes all symbols in a file for instant position-based lookup enhancedSymbols can be nil for basic symbols (will generate temporary IDs)

func (*SymbolLocationIndex) RemoveFile

func (sli *SymbolLocationIndex) RemoveFile(fileID types.FileID)

RemoveFile removes all symbols for a specific file

func (*SymbolLocationIndex) Shutdown

func (sli *SymbolLocationIndex) Shutdown() error

Shutdown performs graceful shutdown with resource cleanup

type SymbolRange

type SymbolRange struct {
	Symbol   types.Symbol
	SymbolID types.SymbolID // Store ID for O(1) lookup
	StartPos Position
	EndPos   Position
}

SymbolRange represents the full range a symbol covers

type SymbolRule

type SymbolRule struct {
	SymbolKind      types.SymbolKind
	NamePattern     *regexp.Regexp
	TypePattern     *regexp.Regexp // For type annotations, return types, etc.
	RequiredImports []string       // Required import patterns
	Confidence      float64        // Rule confidence multiplier
}

SymbolRule defines rules for classifying components based on symbols

type SymbolStore

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

SymbolStore is a high-performance symbol storage implementation that uses parallel arrays instead of maps for better cache locality and performance.

Instead of: map[SymbolID]*EnhancedSymbol We use: []*EnhancedSymbol (data) + map[SymbolID]int (index)

This provides: - O(1) array access (faster than map lookup) - Better CPU cache locality - Reduced memory overhead (no map bucket overhead) - ~30-50% performance improvement in symbol lookups

NOTE: SymbolStore assumes the caller holds appropriate locks. It is designed to be used within ReferenceTracker, which provides the necessary synchronization via its own mutex.

func NewSymbolStore

func NewSymbolStore(expectedSize int) *SymbolStore

NewSymbolStore creates a new SymbolStore with pre-allocated capacity

func (*SymbolStore) Capacity

func (ss *SymbolStore) Capacity() int

Capacity returns the current capacity of the data array

NOTE: Assumes caller holds appropriate lock (e.g., ReferenceTracker.mu)

func (*SymbolStore) Clear

func (ss *SymbolStore) Clear()

Clear removes all symbols from the store

NOTE: Assumes caller holds appropriate lock (e.g., ReferenceTracker.mu)

func (*SymbolStore) Delete

func (ss *SymbolStore) Delete(id types.SymbolID) bool

Delete removes a symbol by ID Returns true if symbol was deleted, false if not found

NOTE: Assumes caller holds appropriate lock (e.g., ReferenceTracker.mu)

func (*SymbolStore) Get

Get retrieves a symbol by ID in O(1) time Returns nil if not found

NOTE: Assumes caller holds appropriate lock (e.g., ReferenceTracker.mu)

func (*SymbolStore) GetAll

func (ss *SymbolStore) GetAll() []*types.EnhancedSymbol

GetAll returns all symbols as a slice This is a copy, not a reference to internal data

NOTE: Assumes caller holds appropriate lock (e.g., ReferenceTracker.mu)

func (*SymbolStore) GetByID

func (ss *SymbolStore) GetByID(id types.SymbolID) *types.EnhancedSymbol

GetByID retrieves a symbol by ID (alias for Get for convenience)

func (*SymbolStore) GetIDs

func (ss *SymbolStore) GetIDs() []types.SymbolID

GetIDs returns all symbol IDs

NOTE: Assumes caller holds appropriate lock (e.g., ReferenceTracker.mu)

func (*SymbolStore) Range

func (ss *SymbolStore) Range(fn func(id types.SymbolID, symbol *types.EnhancedSymbol) bool)

Range calls fn for each symbol in the store If fn returns false, iteration stops The symbols are visited in array order (insertion order)

NOTE: Assumes caller holds appropriate lock (e.g., ReferenceTracker.mu)

func (*SymbolStore) Set

func (ss *SymbolStore) Set(id types.SymbolID, symbol *types.EnhancedSymbol)

Set adds or updates a symbol If ID exists, updates the symbol If new ID, appends to array and adds to index

NOTE: Assumes caller holds appropriate lock (e.g., ReferenceTracker.mu)

func (*SymbolStore) Size

func (ss *SymbolStore) Size() int

Size returns the number of symbols in the store

NOTE: Assumes caller holds appropriate lock (e.g., ReferenceTracker.mu)

type SymbolWithScore

type SymbolWithScore struct {
	Symbol types.Symbol `json:"symbol"`
	Score  int          `json:"score"` // Reference count
}

type TaggedTemplateExtractor

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

TaggedTemplateExtractor extracts SQL, GraphQL, and other tagged template literals

func NewTaggedTemplateExtractor

func NewTaggedTemplateExtractor() *TaggedTemplateExtractor

NewTaggedTemplateExtractor creates an extractor for common template literals

func (*TaggedTemplateExtractor) ExtractTemplateStrings

func (tte *TaggedTemplateExtractor) ExtractTemplateStrings(content string) []TemplateString

ExtractTemplateStrings finds tagged template literals in JavaScript/TypeScript code

type TemplateString

type TemplateString struct {
	Tag        string // sql, gql, etc.
	Content    string // The actual SQL/GraphQL query
	Function   string // Optional: function it's passed to
	StartPos   int
	EndPos     int
	LineNumber int
}

TemplateString represents an extracted template literal

type TemplateStringInfo

type TemplateStringInfo struct {
	Tag      string // The tag (sql, gql, etc.) for tagged templates
	Content  string // The actual content
	FileID   types.FileID
	StartPos int
	EndPos   int
	Line     int
}

TemplateStringInfo contains information about a template literal

type TestCoverageInfo

type TestCoverageInfo struct {
	HasTests      bool     `json:"has_tests"`
	TestFilePaths []string `json:"test_file_paths"`
}

TestCoverageInfo provides test file discovery (not coverage measurement) Note: Actual coverage percentage requires specialized tools like 'go test -cover'

type TrigramBucket

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

TrigramBucket holds trigrams for a specific bucket with its own lock This enables lock-free parallel merging across different buckets

func (*TrigramBucket) GetMutex

func (b *TrigramBucket) GetMutex() *sync.Mutex

GetMutex returns the bucket's mutex for locking

func (*TrigramBucket) GetTrigrams

func (b *TrigramBucket) GetTrigrams() map[uint32]*TrigramEntry

GetTrigrams returns the bucket's trigram map

type TrigramEntry

type TrigramEntry struct {
	Locations []FileLocation
}

type TrigramIndex

type TrigramIndex struct {

	// Flag to indicate bulk indexing mode (lock-free when true)
	BulkIndexing int32
	// contains filtered or unexported fields
}

func NewTrigramIndex

func NewTrigramIndex() *TrigramIndex

func (*TrigramIndex) Clear

func (ti *TrigramIndex) Clear()

func (*TrigramIndex) CreateBucketedResult

func (ti *TrigramIndex) CreateBucketedResult(fileID types.FileID) *BucketedTrigramResult

CreateBucketedResult creates a properly sized result structure Processors call this to get the right size array for bucketing

func (*TrigramIndex) FileCount

func (ti *TrigramIndex) FileCount() int

FileCount returns the number of unique files in the index Note: During search operations, updates are already blocked by GoroutineIndex

func (*TrigramIndex) FindCandidates

func (ti *TrigramIndex) FindCandidates(pattern string) []types.FileID

func (*TrigramIndex) FindCandidatesWithOptions

func (ti *TrigramIndex) FindCandidatesWithOptions(pattern string, caseInsensitive bool) []types.FileID

func (*TrigramIndex) FindMatchLocations

func (ti *TrigramIndex) FindMatchLocations(pattern string, caseInsensitive bool, fileProvider func(types.FileID) *types.FileInfo) []SearchLocation

FindMatchLocations returns exact match locations for a pattern using trigram index

func (*TrigramIndex) ForceCleanup

func (ti *TrigramIndex) ForceCleanup()

ForceCleanup immediately performs cleanup of invalidated files

func (*TrigramIndex) GetAllocator

func (ti *TrigramIndex) GetAllocator() *alloc.SlabAllocator[FileLocation]

GetAllocator returns the slab allocator for use by merger pipeline

func (*TrigramIndex) GetAllocatorStats

func (ti *TrigramIndex) GetAllocatorStats() alloc.AllocatorStats

GetAllocatorStats returns statistics from the slab allocator for monitoring

func (*TrigramIndex) GetBucketCount

func (ti *TrigramIndex) GetBucketCount() int

GetBucketCount returns the total number of buckets

func (*TrigramIndex) GetBucketForTrigram

func (ti *TrigramIndex) GetBucketForTrigram(trigramHash uint32) uint16

GetBucketForTrigram returns the bucket ID for a trigram hash This ensures consistent bucketing across all components

func (*TrigramIndex) GetInvalidationCount

func (ti *TrigramIndex) GetInvalidationCount() int

GetInvalidationCount returns the current number of invalidated files

func (*TrigramIndex) IndexFile

func (ti *TrigramIndex) IndexFile(fileID types.FileID, content []byte)

func (*TrigramIndex) IndexFileWithBucketedTrigrams

func (ti *TrigramIndex) IndexFileWithBucketedTrigrams(result *BucketedTrigramResult)

IndexFileWithBucketedTrigrams indexes a file using pre-bucketed trigrams This is the new channel-friendly API that avoids lock contention

func (*TrigramIndex) IndexFileWithTrigrams

func (ti *TrigramIndex) IndexFileWithTrigrams(fileID types.FileID, trigrams map[uint32][]uint32)

IndexFileWithTrigrams indexes a file using pre-computed simple trigrams from the processor This is more efficient than IndexFile because trigrams are computed in parallel processors Thread-safe: Uses mutex to protect all map operations OPTIMIZED: Pre-calculates total trigram count to minimize GrowSlice operations

func (*TrigramIndex) RemoveFile

func (ti *TrigramIndex) RemoveFile(fileID types.FileID, content []byte)

func (*TrigramIndex) SetBulkIndexing

func (ti *TrigramIndex) SetBulkIndexing(enabled bool)

SetBulkIndexing sets the bulk indexing mode

func (*TrigramIndex) SetCleanupThreshold

func (ti *TrigramIndex) SetCleanupThreshold(threshold int)

SetCleanupThreshold sets the threshold for triggering background cleanup

func (*TrigramIndex) UpdateFile

func (ti *TrigramIndex) UpdateFile(fileID types.FileID, oldContent, newContent []byte)

type TypeRelationships

type TypeRelationships struct {
	Implements    []types.SymbolID // Interfaces this type implements
	ImplementedBy []types.SymbolID // Types that implement this interface
	Extends       []types.SymbolID // Base types this type extends
	ExtendedBy    []types.SymbolID // Types that extend this type
}

TypeRelationships holds all type relationship information for a symbol

func (*TypeRelationships) HasTypeRelationships

func (tr *TypeRelationships) HasTypeRelationships() bool

HasTypeRelationships returns true if the symbol has any type relationships

type UnifiedSearchResult

type UnifiedSearchResult struct {
	RegularResults    []searchtypes.Result
	AssemblyResults   []AssemblyResult
	TotalTime         time.Duration
	AssemblyTriggered bool
}

UnifiedSearchResult combines regular and assembly search results

type UniversalGraphStats

type UniversalGraphStats struct {
	TotalNodes        int            `json:"total_nodes"`
	NodesByKind       map[string]int `json:"nodes_by_kind"`
	NodesByLanguage   map[string]int `json:"nodes_by_language"`
	RelationshipCount map[string]int `json:"relationship_count"`
	LastUpdated       time.Time      `json:"last_updated"`
	MemoryUsage       int64          `json:"memory_usage_bytes"`
	QueryCount        int64          `json:"query_count"`
	AvgQueryTime      time.Duration  `json:"avg_query_time"`
}

UniversalGraphStats tracks statistics about the Universal Symbol Graph

type UniversalSymbolGraph

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

UniversalSymbolGraph represents the Universal Symbol Graph that extends beyond function calls to include all symbol relationships across languages

func NewUniversalSymbolGraph

func NewUniversalSymbolGraph() *UniversalSymbolGraph

NewUniversalSymbolGraph creates a new Universal Symbol Graph

func NewUniversalSymbolGraphWithConfig

func NewUniversalSymbolGraphWithConfig(maxNodes int) *UniversalSymbolGraph

NewUniversalSymbolGraphWithConfig creates a new Universal Symbol Graph with custom configuration

func (*UniversalSymbolGraph) AddSymbol

func (usg *UniversalSymbolGraph) AddSymbol(node *types.UniversalSymbolNode) error

AddSymbol adds a symbol to the Universal Symbol Graph

func (*UniversalSymbolGraph) BuildRelationshipTree

func (usg *UniversalSymbolGraph) BuildRelationshipTree(rootID types.CompositeSymbolID, relationTypes []types.RelationshipType, maxDepth int) (*RelationshipTree, error)

BuildRelationshipTree builds a tree of relationships starting from a symbol

func (*UniversalSymbolGraph) Clear

func (usg *UniversalSymbolGraph) Clear()

Clear clears all symbols and indexes

func (*UniversalSymbolGraph) GetAllSymbols

func (usg *UniversalSymbolGraph) GetAllSymbols() []*types.UniversalSymbolNode

GetAllSymbols returns all symbols in the Universal Symbol Graph

func (*UniversalSymbolGraph) GetFileCoLocatedSymbols

func (usg *UniversalSymbolGraph) GetFileCoLocatedSymbols(id types.CompositeSymbolID) ([]*types.UniversalSymbolNode, error)

GetFileCoLocatedSymbols returns symbols that are co-located in the same file

func (*UniversalSymbolGraph) GetRelatedSymbols

func (usg *UniversalSymbolGraph) GetRelatedSymbols(id types.CompositeSymbolID, relationType types.RelationshipType) ([]*types.UniversalSymbolNode, error)

GetRelatedSymbols finds symbols related to the given symbol by relationship type

func (*UniversalSymbolGraph) GetReverseRelatedSymbols

func (usg *UniversalSymbolGraph) GetReverseRelatedSymbols(id types.CompositeSymbolID, relationType types.RelationshipType) ([]*types.UniversalSymbolNode, error)

GetReverseRelatedSymbols finds symbols that have the given relationship TO the specified symbol

func (*UniversalSymbolGraph) GetStats

func (usg *UniversalSymbolGraph) GetStats() UniversalGraphStats

GetStats returns statistics about the Universal Symbol Graph

func (*UniversalSymbolGraph) GetSymbol

GetSymbol retrieves a symbol by its CompositeSymbolID

func (*UniversalSymbolGraph) GetSymbolsByFile

func (usg *UniversalSymbolGraph) GetSymbolsByFile(fileID types.FileID) []*types.UniversalSymbolNode

GetSymbolsByFile returns all symbols in a specific file

func (*UniversalSymbolGraph) GetSymbolsByLanguage

func (usg *UniversalSymbolGraph) GetSymbolsByLanguage(language string) []*types.UniversalSymbolNode

GetSymbolsByLanguage returns all symbols for a specific language

func (*UniversalSymbolGraph) GetSymbolsByName

func (usg *UniversalSymbolGraph) GetSymbolsByName(name string) []*types.UniversalSymbolNode

GetSymbolsByName finds symbols by name

func (*UniversalSymbolGraph) GetUsageHotSpots

func (usg *UniversalSymbolGraph) GetUsageHotSpots(limit int) []*types.UniversalSymbolNode

GetUsageHotSpots returns symbols with high usage patterns

func (*UniversalSymbolGraph) RemoveSymbol

func (usg *UniversalSymbolGraph) RemoveSymbol(id types.CompositeSymbolID) error

RemoveSymbol removes a symbol from the Universal Symbol Graph

func (*UniversalSymbolGraph) UpdateUsage

func (usg *UniversalSymbolGraph) UpdateUsage(id types.CompositeSymbolID, usageType string, location types.SymbolLocation) error

UpdateUsage updates usage statistics for a symbol

type UpdateResult

type UpdateResult struct {
	FileID  types.FileID
	FileIDs []types.FileID // For batch operations
	Success bool
	Error   error
}

UpdateResult represents the result of an update operation

type UpdateType

type UpdateType int

UpdateType represents the type of update operation

const (
	UpdateTypeLoad UpdateType = iota
	UpdateTypeBatch
	UpdateTypeInvalidate
	UpdateTypeInvalidateByID
	UpdateTypeClear
)

type UsageAnalysis

type UsageAnalysis struct {
	CallFrequency     int64             `json:"call_frequency"` // If available
	FanIn             int               `json:"fan_in"`         // Number of callers
	FanOut            int               `json:"fan_out"`        // Number of calls
	ComplexityMetrics ComplexityMetrics `json:"complexity_metrics"`
	ChangeImpact      ChangeImpactInfo  `json:"change_impact"`
	TestCoverage      TestCoverageInfo  `json:"test_coverage"`
}

UsageAnalysis provides metrics and impact analysis

type VariableContext

type VariableContext struct {
	GlobalVariables []VariableInfo `json:"global_variables"`
	UsedGlobals     []VariableInfo `json:"used_globals"`    // Actually used by this object
	ClassVariables  []VariableInfo `json:"class_variables"` // For classes
	LocalVariables  []VariableInfo `json:"local_variables"` // Important locals
	Parameters      []VariableInfo `json:"parameters"`      // Function parameters
	ReturnValues    []VariableInfo `json:"return_values"`   // Return type info
}

VariableContext contains information about variables accessible to the object

type VariableInfo

type VariableInfo struct {
	Name      string               `json:"name"`
	Type      string               `json:"type"`
	Location  types.SymbolLocation `json:"location"`
	IsUsed    bool                 `json:"is_used"`
	UseCount  int                  `json:"use_count"`
	Scope     string               `json:"scope"` // "global", "class", "local"
	IsMutable bool                 `json:"is_mutable"`
}

type VerificationResult

type VerificationResult struct {
	RuleName     string                 `json:"rule_name"`
	Scope        string                 `json:"scope"`
	TotalFiles   int                    `json:"total_files"`
	CheckedFiles int                    `json:"checked_files"`
	Violations   []PatternViolation     `json:"violations"`
	Summary      VerificationSummary    `json:"summary"`
	Metadata     map[string]interface{} `json:"metadata"`
}

VerificationResult contains the results of pattern verification

type VerificationRule

type VerificationRule struct {
	Name        string        `json:"name"`
	Description string        `json:"description"`
	Scope       string        `json:"scope"`  // File pattern scope
	Checks      []PatternRule `json:"checks"` // List of checks to perform
	Enabled     bool          `json:"enabled"`
}

VerificationRule is a custom user-defined rule

type VerificationSummary

type VerificationSummary struct {
	TotalViolations int      `json:"total_violations"`
	ErrorCount      int      `json:"error_count"`
	WarningCount    int      `json:"warning_count"`
	InfoCount       int      `json:"info_count"`
	ComplianceScore float64  `json:"compliance_score"`
	RulesSatisfied  []string `json:"rules_satisfied"`
	RulesViolated   []string `json:"rules_violated"`
	FilesAnalyzed   []string `json:"files_analyzed"`
}

VerificationSummary provides aggregated results

type ZeroAllocFileContentStore

type ZeroAllocFileContentStore struct {
	*FileContentStore // Embed existing functionality
}

ZeroAllocFileContentStore extends FileContentStore with zero-allocation string operations This provides all the helper methods needed for zero-allocation string processing

func NewZeroAllocFileContentStore

func NewZeroAllocFileContentStore() *ZeroAllocFileContentStore

NewZeroAllocFileContentStore creates a new zero-allocation file content store

func NewZeroAllocFileContentStoreFromStore

func NewZeroAllocFileContentStoreFromStore(store *FileContentStore) *ZeroAllocFileContentStore

NewZeroAllocFileContentStoreFromStore creates a zero-allocation file content store from an existing store

func NewZeroAllocFileContentStoreWithLimit

func NewZeroAllocFileContentStoreWithLimit(maxMemoryBytes int64) *ZeroAllocFileContentStore

NewZeroAllocFileContentStoreWithLimit creates a new zero-allocation file content store with memory limit

func (*ZeroAllocFileContentStore) ContextToJSON

func (zafcs *ZeroAllocFileContentStore) ContextToJSON(fileID types.FileID, lineNum, before, after int) ([]byte, error)

ContextToJSON converts context lines to JSON without intermediate string allocation

func (*ZeroAllocFileContentStore) CountRunes

func (zafcs *ZeroAllocFileContentStore) CountRunes(ref types.ZeroAllocStringRef) int

CountRunes counts Unicode runes in the reference without allocation

func (*ZeroAllocFileContentStore) ExtractBraceContent

func (zafcs *ZeroAllocFileContentStore) ExtractBraceContent(lineRef types.ZeroAllocStringRef) types.ZeroAllocStringRef

ExtractBraceContent extracts content between braces without allocation

func (*ZeroAllocFileContentStore) ExtractFunctionName

func (zafcs *ZeroAllocFileContentStore) ExtractFunctionName(lineRef types.ZeroAllocStringRef) types.ZeroAllocStringRef

ExtractFunctionName attempts to extract a function name from a line without allocation

func (*ZeroAllocFileContentStore) ExtractImportPath

ExtractImportPath attempts to extract an import path from a line without allocation

func (*ZeroAllocFileContentStore) ExtractParenContent

func (zafcs *ZeroAllocFileContentStore) ExtractParenContent(lineRef types.ZeroAllocStringRef) types.ZeroAllocStringRef

ExtractParenContent extracts content between parentheses without allocation

func (*ZeroAllocFileContentStore) ExtractRunes

func (zafcs *ZeroAllocFileContentStore) ExtractRunes(ref types.ZeroAllocStringRef, startRune, endRune int) types.ZeroAllocStringRef

ExtractRunes extracts Unicode runes within a range without allocation

func (*ZeroAllocFileContentStore) ExtractVariableName

func (zafcs *ZeroAllocFileContentStore) ExtractVariableName(lineRef types.ZeroAllocStringRef) types.ZeroAllocStringRef

ExtractVariableName attempts to extract a variable name from a line without allocation

func (*ZeroAllocFileContentStore) FilterCommentLines

func (zafcs *ZeroAllocFileContentStore) FilterCommentLines(lines []types.ZeroAllocStringRef, commentPrefixes ...string) []types.ZeroAllocStringRef

FilterCommentLines removes comment lines without allocation

func (*ZeroAllocFileContentStore) FilterEmptyLines

func (zafcs *ZeroAllocFileContentStore) FilterEmptyLines(lines []types.ZeroAllocStringRef) []types.ZeroAllocStringRef

FilterEmptyLines removes empty lines without allocation

func (*ZeroAllocFileContentStore) FindAllLinesWithPattern

func (zafcs *ZeroAllocFileContentStore) FindAllLinesWithPattern(fileID types.FileID, pattern string) []int

FindAllLinesWithPattern finds all lines containing a pattern without allocation

func (*ZeroAllocFileContentStore) FindAllLinesWithPrefix

func (zafcs *ZeroAllocFileContentStore) FindAllLinesWithPrefix(fileID types.FileID, prefix string) []int

FindAllLinesWithPrefix finds all lines starting with a prefix without allocation

func (*ZeroAllocFileContentStore) FindAllLinesWithSuffix

func (zafcs *ZeroAllocFileContentStore) FindAllLinesWithSuffix(fileID types.FileID, suffix string) []int

FindAllLinesWithSuffix finds all lines ending with a suffix without allocation

func (*ZeroAllocFileContentStore) FindClassDefinitions

func (zafcs *ZeroAllocFileContentStore) FindClassDefinitions(fileID types.FileID) []int

FindClassDefinitions finds all class definition lines without allocation

func (*ZeroAllocFileContentStore) FindFunctionDefinitions

func (zafcs *ZeroAllocFileContentStore) FindFunctionDefinitions(fileID types.FileID) []int

FindFunctionDefinitions finds all function definition lines without allocation

func (*ZeroAllocFileContentStore) FindImportStatements

func (zafcs *ZeroAllocFileContentStore) FindImportStatements(fileID types.FileID) []int

FindImportStatements finds all import statement lines without allocation

func (*ZeroAllocFileContentStore) FindVariableDeclarations

func (zafcs *ZeroAllocFileContentStore) FindVariableDeclarations(fileID types.FileID) []int

FindVariableDeclarations finds all variable declaration lines without allocation

func (*ZeroAllocFileContentStore) FindWithContext

func (zafcs *ZeroAllocFileContentStore) FindWithContext(fileID types.FileID, pattern string, contextLines int) SearchResults

FindWithContext finds all matches and provides context without allocation

func (*ZeroAllocFileContentStore) GetZeroAllocContextLines

func (zafcs *ZeroAllocFileContentStore) GetZeroAllocContextLines(fileID types.FileID, lineNum, before, after int) []types.ZeroAllocStringRef

GetZeroAllocContextLines returns ZeroAllocStringRefs for context lines without allocation

func (*ZeroAllocFileContentStore) GetZeroAllocLine

func (zafcs *ZeroAllocFileContentStore) GetZeroAllocLine(fileID types.FileID, lineNum int) types.ZeroAllocStringRef

GetZeroAllocLine returns a ZeroAllocStringRef for a specific line without allocation

func (*ZeroAllocFileContentStore) GetZeroAllocLines

func (zafcs *ZeroAllocFileContentStore) GetZeroAllocLines(fileID types.FileID, startLine, count int) []types.ZeroAllocStringRef

GetZeroAllocLines returns ZeroAllocStringRefs for a range of lines without allocation Parameters: startLine (0-indexed), count (number of lines to return)

func (*ZeroAllocFileContentStore) GetZeroAllocStringRef

func (zafcs *ZeroAllocFileContentStore) GetZeroAllocStringRef(ref types.StringRef) types.ZeroAllocStringRef

GetZeroAllocStringRef returns a ZeroAllocStringRef without any allocation

func (*ZeroAllocFileContentStore) HasCodeContent

func (zafcs *ZeroAllocFileContentStore) HasCodeContent(lineRef types.ZeroAllocStringRef) bool

HasCodeContent checks if a line contains actual code (not just comments/whitespace) without allocation

func (*ZeroAllocFileContentStore) IsCommentLine

func (zafcs *ZeroAllocFileContentStore) IsCommentLine(lineRef types.ZeroAllocStringRef) bool

IsCommentLine checks if a line is a comment without allocation

func (*ZeroAllocFileContentStore) IsEmptyLine

func (zafcs *ZeroAllocFileContentStore) IsEmptyLine(lineRef types.ZeroAllocStringRef) bool

IsEmptyLine checks if a line is empty or contains only whitespace without allocation

func (*ZeroAllocFileContentStore) LinesToJSON

func (zafcs *ZeroAllocFileContentStore) LinesToJSON(lines []types.ZeroAllocStringRef) ([]byte, error)

LinesToJSON converts lines to JSON without intermediate string allocation

func (*ZeroAllocFileContentStore) ProcessLinesInBulk

func (zafcs *ZeroAllocFileContentStore) ProcessLinesInBulk(fileID types.FileID, startLine, endLine int, processor func(types.ZeroAllocStringRef) bool) []int

ProcessLinesInBulk processes multiple lines with a function without allocation

func (*ZeroAllocFileContentStore) RemoveCommonPrefix

func (zafcs *ZeroAllocFileContentStore) RemoveCommonPrefix(lines []types.ZeroAllocStringRef) []types.ZeroAllocStringRef

RemoveCommonPrefix removes common prefix from multiple lines without allocation

func (*ZeroAllocFileContentStore) SearchInLine

func (zafcs *ZeroAllocFileContentStore) SearchInLine(fileID types.FileID, lineNum int, pattern string) bool

SearchInLine searches for a pattern in a specific line without allocation

func (*ZeroAllocFileContentStore) SearchInLines

func (zafcs *ZeroAllocFileContentStore) SearchInLines(fileID types.FileID, startLine, endLine int, pattern string) []int

SearchInLines searches for a pattern in multiple lines without allocation

func (*ZeroAllocFileContentStore) SearchLinesWithAnyPrefix

func (zafcs *ZeroAllocFileContentStore) SearchLinesWithAnyPrefix(fileID types.FileID, startLine, endLine int, prefixes ...string) []int

SearchLinesWithAnyPrefix finds lines that start with any of the given prefixes without allocation

func (*ZeroAllocFileContentStore) SearchLinesWithAnySuffix

func (zafcs *ZeroAllocFileContentStore) SearchLinesWithAnySuffix(fileID types.FileID, startLine, endLine int, suffixes ...string) []int

SearchLinesWithAnySuffix finds lines that end with any of the given suffixes without allocation

func (*ZeroAllocFileContentStore) TrimWhitespaceLines

func (zafcs *ZeroAllocFileContentStore) TrimWhitespaceLines(lines []types.ZeroAllocStringRef) []types.ZeroAllocStringRef

TrimWhitespaceLines removes leading/trailing whitespace from lines without allocation

type ZeroAllocations

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

ZeroAllocations represents a collection of zero-allocation optimizations

func GetZeroAllocations

func GetZeroAllocations() *ZeroAllocations

GetZeroAllocations returns the zero-allocation optimizer

func (*ZeroAllocations) AllocateBuffer

func (za *ZeroAllocations) AllocateBuffer(size int) []byte

AllocateBuffer gets a buffer from the pool (tracks allocations saved)

func (*ZeroAllocations) GetOptimizationMetrics

func (za *ZeroAllocations) GetOptimizationMetrics() map[string]interface{}

GetOptimizationMetrics returns zero-allocation metrics

func (*ZeroAllocations) ReturnBuffer

func (za *ZeroAllocations) ReturnBuffer(buf []byte)

ReturnBuffer returns a buffer to the pool

Jump to

Keyboard shortcuts

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