types

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: 12 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// File size limits
	DefaultMaxFileSize = 10 * 1024 * 1024 // 10MB per file - standard limit for indexing

	// Memory limits
	DefaultMaxMemoryMB = 100 // 100MB - typical memory limit for lightweight indexing

	// Performance limits
	DefaultMaxFileCount = 10000 // Maximum files to index in a single operation

	DefaultMaxTotalSizeMB = 500 // Maximum total size for indexed files (MB)

	// Binary detection optimization threshold
	BinaryPreCheckSizeThreshold = 100 * 1024 // 100KB - files above this size get pre-checked for binary content
	// Rationale: Reading first 512 bytes to detect binary files
	// is cheaper than loading the entire file into memory.
	// This prevents wasting memory on large binary files.
	BinaryPreCheckBytes = 512 // Number of bytes to read for binary magic number detection
)

Common system-wide constants

View Source
const (
	// RefQualityPrecise indicates explicit syntax declaration (e.g., "implements" keyword)
	RefQualityPrecise = "precise"

	// RefQualityAssigned indicates a concrete type was assigned to an interface-typed variable
	// e.g., var w Writer = &File{} - proves File implements Writer
	RefQualityAssigned = "assigned"

	// RefQualityReturned indicates a concrete type was returned from a function with interface return type
	// e.g., func New() Writer { return &File{} } - proves File implements Writer
	RefQualityReturned = "returned"

	// RefQualityCast indicates a type assertion to an interface was found
	// e.g., x.(Writer) - suggests the value implements Writer
	RefQualityCast = "cast"

	// RefQualityHeuristic indicates method signature matching only (no explicit usage evidence)
	// e.g., File has Write() method matching Writer interface - inferred relationship
	RefQualityHeuristic = "heuristic"
)

RefQuality represents the confidence level of a reference relationship. Higher quality values indicate more certain evidence of the relationship.

View Source
const (
	VariableFlagConst     = 1 << iota // bit 0: constant variable
	VariableFlagStatic                // bit 1: static member
	VariableFlagPointer               // bit 2: pointer type
	VariableFlagArray                 // bit 3: array/slice type
	VariableFlagChannel               // bit 4: channel type
	VariableFlagInterface             // bit 5: interface type
)

Bitfield constants for EnhancedSymbol metadata optimization Variable flag bit positions

View Source
const (
	FunctionFlagAsync     = 1 << iota // bit 0: async function
	FunctionFlagGenerator             // bit 1: generator function
	FunctionFlagMethod                // bit 2: method vs function
	FunctionFlagVariadic              // bit 3: variadic parameters
)

Function flag bit positions

View Source
const (
	// StringRefsPerBlock - optimized for cache efficiency
	// 20 bytes per StringRef, ~3 refs per 64-byte cache line
	// 4096 StringRefs = ~80KB per block
	StringRefsPerBlock = 4096
)

Variables

View Source
var EmptyStringRef = StringRef{}

EmptyStringRef represents an empty/invalid string reference

View Source
var EmptyZeroAllocStringRef = ZeroAllocStringRef{}

EmptyZeroAllocStringRef represents an empty/invalid zero-allocation string reference

View Source
var GlobalStringRefAllocator = &StringRefAllocator{
	blockPool: sync.Pool{
		New: func() interface{} {
			return &StringRefBlock{}
		},
	},
}

GlobalStringRefAllocator is the application-wide StringRef allocator

Functions

func ComputeHash

func ComputeHash(data []byte) uint64

ComputeHash is the public version of computeHash for use in zero-allocation code

func ComputeLineOffsets

func ComputeLineOffsets(content []byte) []int

ComputeLineOffsets computes byte offsets for the start of each line in the content. This enables O(1) line extraction instead of O(n) string splitting. LineOffsets[i] contains the byte offset where line i+1 starts. Example: for content "hello\nworld\n", returns [0, 6, 12]

func GetLineFromOffsets

func GetLineFromOffsets(content []byte, lineOffsets []int, lineNum int) []byte

GetLineFromOffsets extracts a single line using precomputed offsets. Returns the line content (without trailing newline) or empty slice if line is out of range.

func RefQualityRank

func RefQualityRank(quality string) int

RefQualityRank returns a numeric ranking for quality comparison (higher = more confident)

Types

type AccessLevel

type AccessLevel uint8

AccessLevel represents different access control levels

const (
	AccessUnknown AccessLevel = iota
	AccessPublic
	AccessPrivate
	AccessProtected
	AccessInternal
	AccessPackage
)

func (AccessLevel) String

func (al AccessLevel) String() string

String returns string representation of access level

type AccessPattern

type AccessPattern struct {
	// All detected accesses in order
	Accesses []FieldAccess

	// Overall pattern classification
	Pattern AccessPatternType

	// Per-target analysis
	TargetPatterns map[string]*TargetAccessPattern

	// Detected violations/concerns
	Violations []PatternViolation

	// Summary statistics
	TotalReads      int
	TotalWrites     int
	UniqueTargets   int
	ParameterWrites int
	ReceiverWrites  int
	GlobalWrites    int
	ClosureWrites   int
}

AccessPattern summarizes the read/write pattern for a function

func (*AccessPattern) HasViolations

func (ap *AccessPattern) HasViolations() bool

HasViolations returns true if any violations were detected

func (*AccessPattern) MaxSeverity

func (ap *AccessPattern) MaxSeverity() float64

MaxSeverity returns the maximum severity among all violations

type AccessPatternType

type AccessPatternType uint8

AccessPatternType classifies the overall read/write pattern of a function

const (
	// PatternPure - no writes at all (reads only or no accesses)
	PatternPure AccessPatternType = iota

	// PatternReadThenWrite - all reads occur before all writes (clean pattern)
	PatternReadThenWrite

	// PatternWriteOnly - only writes, no reads (initializer pattern)
	PatternWriteOnly

	// PatternWriteThenRead - writes before reads to same target (suspicious)
	PatternWriteThenRead

	// PatternInterleaved - mixed read/write ordering (complex/suspicious)
	PatternInterleaved

	// PatternUnknown - cannot determine pattern
	PatternUnknown
)

func (AccessPatternType) IsClean

func (p AccessPatternType) IsClean() bool

IsClean returns true if the pattern is considered clean/expected

func (AccessPatternType) String

func (p AccessPatternType) String() string

type AccessTarget

type AccessTarget uint8

AccessTarget represents what is being accessed

const (
	AccessTargetLocal     AccessTarget = iota // Local variable
	AccessTargetParameter                     // Function parameter
	AccessTargetReceiver                      // Method receiver (this/self)
	AccessTargetGlobal                        // Global/module-level variable
	AccessTargetClosure                       // Captured closure variable
	AccessTargetField                         // Object/struct field
	AccessTargetIndex                         // Array/slice/map index
	AccessTargetUnknown                       // Cannot determine
)

func (AccessTarget) String

func (t AccessTarget) String() string

type AccessType

type AccessType uint8

AccessType distinguishes reads from writes

const (
	AccessRead  AccessType = 1
	AccessWrite AccessType = 2
)

func (AccessType) String

func (a AccessType) String() string

type AllocatorStats

type AllocatorStats struct {
	TotalBlocks      int
	ActiveRefs       int64
	BlockSizeBytes   int
	TotalMemoryBytes int
	RefsPerBlock     int
}

Stats represents allocator statistics

type AnnotationType

type AnnotationType uint8

AnnotationType represents different types of annotations

const (
	AnnotationDecorator AnnotationType = iota // @decorator
	AnnotationAttribute                       // [Attribute]
	AnnotationPragma                          // #pragma
	AnnotationDirective                       // "use strict"
	AnnotationComment                         // // @annotation
	AnnotationGeneric                         // Generic language annotation
)

func (AnnotationType) String

func (at AnnotationType) String() string

String returns string representation of annotation type

type AwaitData

type AwaitData struct {
	Line        int      `json:"line"`
	AssignedVar string   `json:"assigned_var,omitempty"` // Variable receiving the result
	CallTarget  string   `json:"call_target,omitempty"`  // Function/method being awaited
	UsedVars    []string `json:"used_vars,omitempty"`    // Variables referenced in arguments
}

AwaitData tracks information about an await expression

type BlockBoundary

type BlockBoundary struct {
	Start int
	End   int
	Type  BlockType
	Name  string
	Depth int
}

type BlockType

type BlockType uint8
const (
	BlockTypeFunction BlockType = iota
	BlockTypeClass
	BlockTypeMethod
	BlockTypeInterface
	BlockTypeStruct
	BlockTypeVariable
	BlockTypeBlock
	// Additional block types
	BlockTypeEnum
	BlockTypeTrait
	BlockTypeImpl
	BlockTypeModule
	BlockTypeNamespace
	BlockTypeConstructor
	BlockTypeOther
)

func (BlockType) String

func (b BlockType) String() string

type BloomFilter

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

BloomFilter represents a bloom filter for Unicode characters

func NewBloomFilter

func NewBloomFilter() BloomFilter

NewBloomFilter creates a new bloom filter

func (*BloomFilter) Add

func (bf *BloomFilter) Add(r rune)

Add adds a rune to the bloom filter using multiple hash functions

func (*BloomFilter) Contains

func (bf *BloomFilter) Contains(r rune) bool

Contains checks if a rune might be in the bloom filter

type CallArgument

type CallArgument struct {
	Name      string `json:"name"`       // Argument name (if available)
	Type      string `json:"type"`       // Argument type (if available)
	Value     string `json:"value"`      // Argument value (if literal)
	IsLiteral bool   `json:"is_literal"` // Whether argument is a literal value
}

CallArgument represents an argument in a function call

type CallData

type CallData struct {
	Target    string `json:"target"` // Function/method name being called
	Line      int    `json:"line"`
	InLoop    bool   `json:"in_loop"`    // Whether this call is inside a loop
	LoopDepth int    `json:"loop_depth"` // Depth of containing loop (0 if not in loop)
	LoopLine  int    `json:"loop_line"`  // Line of containing loop
}

CallData tracks information about a function call for performance analysis

type CallType

type CallType uint8

CallType represents different types of function calls

const (
	CallDirect CallType = iota
	CallMethod
	CallCallback
	CallDynamic
	CallRecursive
	CallVirtual
	CallInterface
	CallAsync
	CallDeferred
)

func (CallType) String

func (ct CallType) String() string

String returns string representation of call type

type ComponentInfo

type ComponentInfo struct {
	Type        ComponentType `json:"type"`
	Name        string        `json:"name"`
	FilePath    string        `json:"file_path"`
	FileID      FileID        `json:"file_id"`
	Language    string        `json:"language"`
	Description string        `json:"description"`

	// Symbol information
	Symbols      []Symbol `json:"symbols"`
	Dependencies []string `json:"dependencies"` // Import paths, dependencies

	// Metadata for classification
	Patterns   []string               `json:"patterns"`   // Naming patterns that matched
	Confidence float64                `json:"confidence"` // Classification confidence (0-1)
	Evidence   []string               `json:"evidence"`   // Evidence for classification
	Metadata   map[string]interface{} `json:"metadata"`   // Additional component-specific data
}

ComponentInfo represents a detected code component with semantic information

type ComponentSearchOptions

type ComponentSearchOptions struct {
	Types         []ComponentType `json:"types"`          // Component types to find
	Language      string          `json:"language"`       // Specific language filter
	MinConfidence float64         `json:"min_confidence"` // Minimum classification confidence (default: 0.5)
	IncludeTests  bool            `json:"include_tests"`  // Include test components
	MaxResults    int             `json:"max_results"`    // Maximum results to return (default: 100)
}

ComponentSearchOptions defines options for finding components

type ComponentType

type ComponentType int

ComponentType represents different types of code components for semantic analysis

const (
	ComponentTypeUnknown        ComponentType = iota
	ComponentTypeEntryPoint                   // main functions, init blocks, program entry points
	ComponentTypeAPIHandler                   // HTTP handlers, REST endpoints, GraphQL resolvers
	ComponentTypeViewController               // UI components, renderers, views, templates
	ComponentTypeController                   // State management, business logic controllers
	ComponentTypeDataModel                    // Structs, interfaces, schemas, data types
	ComponentTypeConfiguration                // Config files, settings, environment handling
	ComponentTypeTest                         // Test files, test functions, test utilities
	ComponentTypeUtility                      // Helper functions, utilities, shared code
	ComponentTypeService                      // Business logic services, application services
	ComponentTypeRepository                   // Data access layer, repositories, DAOs
	ComponentTypeMiddleware                   // Middleware, interceptors, filters
	ComponentTypeRouter                       // Routing configuration, URL mapping
	ComponentTypeValidator                    // Input validation, data validation
	ComponentTypeSerializer                   // JSON/XML serialization, data transformation
	ComponentTypeDatabase                     // Database migrations, models, queries
	ComponentTypeAuth                         // Authentication, authorization, security
	ComponentTypeLogging                      // Logging utilities, audit trails
	ComponentTypeMetrics                      // Monitoring, metrics, observability
	ComponentTypeWorker                       // Background workers, job processors
	ComponentTypeEvent                        // Event handling, messaging, pub/sub
)

func (ComponentType) String

func (ct ComponentType) String() string

String returns a string representation of the component type

type CompositeSymbolID

type CompositeSymbolID struct {
	FileID        FileID // 32-bit file identifier
	LocalSymbolID uint32 // 32-bit symbol identifier within the file
}

CompositeSymbolID is a composite identifier for symbols within the codebase It combines a FileID and LocalSymbolID to uniquely identify any symbol This will replace the current SymbolID (uint64) once migration is complete

func NewCompositeSymbolID

func NewCompositeSymbolID(fileID FileID, localID uint32) CompositeSymbolID

NewCompositeSymbolID creates a new CompositeSymbolID

func ParseCompactString

func ParseCompactString(compact string) (CompositeSymbolID, error)

ParseCompactString decodes a compact string back to a CompositeSymbolID. Uses the consolidated encoding package for base-63 decoding.

func (CompositeSymbolID) CompactString

func (s CompositeSymbolID) CompactString() string

CompactString returns the dense encoded representation for external APIs. Uses the consolidated encoding package for base-63 encoding.

func (CompositeSymbolID) Equals

func (s CompositeSymbolID) Equals(other CompositeSymbolID) bool

Equals checks if two CompositeSymbolIDs are equal

func (CompositeSymbolID) Hash

func (s CompositeSymbolID) Hash() uint64

Hash returns a hash value for the CompositeSymbolID

func (CompositeSymbolID) IsValid

func (s CompositeSymbolID) IsValid() bool

IsValid checks if the CompositeSymbolID is valid

func (CompositeSymbolID) MarshalJSON

func (s CompositeSymbolID) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for CompositeSymbolID Returns the compact encoded string for minimal JSON size

func (CompositeSymbolID) String

func (s CompositeSymbolID) String() string

String returns a human-readable string representation for debugging This is intentionally fast - use CompactString() for external APIs

func (*CompositeSymbolID) UnmarshalJSON

func (s *CompositeSymbolID) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler for CompositeSymbolID Handles both compact string format and legacy object format

func (CompositeSymbolID) ValidateRange

func (s CompositeSymbolID) ValidateRange() error

ValidateRange checks if the CompositeSymbolID components are within reasonable ranges

type ContextAttribute

type ContextAttribute struct {
	Type  ContextAttributeType `json:"type"`
	Value string               `json:"value"` // e.g., "use server", "@deprecated('Use foo instead')"
	Line  int                  `json:"line"`  // Line where attribute appears
}

ContextAttribute represents a context-altering attribute that affects code behavior

type ContextAttributeType

type ContextAttributeType uint8

ContextAttributeType represents different types of context-altering attributes

const (
	AttrTypeDirective    ContextAttributeType = iota // "use server", "use client", etc.
	AttrTypeUnsafe                                   // unsafe blocks or operations
	AttrTypeLock                                     // lock statements, mutex operations
	AttrTypeDecorator                                // @decorator annotations
	AttrTypePragma                                   // #pragma directives
	AttrTypeIterator                                 // function*/yield keywords
	AttrTypeAsync                                    // async/await
	AttrTypeVolatile                                 // volatile memory access
	AttrTypeDeprecated                               // @deprecated markers
	AttrTypeExperimental                             // @experimental markers
	AttrTypePure                                     // pure/const functions
	AttrTypeNoThrow                                  // nothrow/noexcept
	AttrTypeSideEffect                               // has side effects
	AttrTypeRecursive                                // recursive function
	AttrTypeExported                                 // exported/public
	AttrTypeInline                                   // inline directive
	AttrTypeVirtual                                  // virtual method
	AttrTypeAbstract                                 // abstract method
	AttrTypeStatic                                   // static method
	AttrTypeFinal                                    // final/sealed
	AttrTypeConst                                    // const method
	AttrTypeGenerator                                // generator function
	AttrTypeCoroutine                                // coroutine/async generator
)

func (ContextAttributeType) String

func (cat ContextAttributeType) String() string

type ContextManifest

type ContextManifest struct {
	// Task description - free-form text for agents
	Task string `json:"t,omitempty"`

	// Metadata
	Created     time.Time `json:"c,omitempty"` // Creation timestamp
	Version     string    `json:"v,omitempty"` // Manifest format version
	ProjectRoot string    `json:"p,omitempty"` // Project root path for relative file paths

	// Symbol references - the core data
	Refs []ContextRef `json:"r"`

	// Statistics for display
	Stats ManifestStats `json:"s,omitempty"`
}

ContextManifest is a compact, serializable representation of code context for efficient transfer between AI agent sessions. Stores symbol references, not source code - hydration happens on demand via LCI's index.

Design principle: LCI handles structure (compact JSON), agents handle semantics (free-form notes).

func (*ContextManifest) ComputeStats

func (m *ContextManifest) ComputeStats() ManifestStats

ComputeStats computes statistics for the manifest

func (*ContextManifest) MarshalJSON

func (m *ContextManifest) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling with version

func (*ContextManifest) Validate

func (m *ContextManifest) Validate() error

Validate checks if the manifest is valid

type ContextRef

type ContextRef struct {
	// Location (at least one required: F+S, F+L, or just F)
	F string     `json:"f"`           // File path (required)
	S string     `json:"s,omitempty"` // Symbol name (optional - can use line range instead)
	L *LineRange `json:"l,omitempty"` // Line range (optional - can use symbol instead)

	// Expansion directives - what related code to fetch on hydration
	// Examples: "callers", "callees:2", "implementations", "tests"
	X []string `json:"x,omitempty"`

	// Metadata for agent-to-agent communication (LCI passes through, doesn't interpret)
	Role string `json:"role,omitempty"` // Semantic hint: "modify", "contract", "pattern", "boundary"
	Note string `json:"n,omitempty"`    // Free-form architect annotation

	// Internal tracking (not serialized to file, used during hydration)
	ObjectID string `json:"-"` // LCI internal object ID (populated during save)
}

ContextRef is a compact reference to code with optional expansion directives. Stores location + metadata, not source code.

type CrossLanguageLink struct {
	Target      CompositeSymbolID `json:"target"`      // Symbol in other language
	LinkType    CrossLinkType     `json:"link_type"`   // Type of cross-language link
	Language    string            `json:"language"`    // Target language
	Bridge      string            `json:"bridge"`      // How languages are bridged (FFI, API, etc.)
	Confidence  float64           `json:"confidence"`  // Confidence in the link (0-1)
	Description string            `json:"description"` // Human-readable description
}

CrossLanguageLink represents a relationship between symbols in different languages

type CrossLinkType

type CrossLinkType uint8

CrossLinkType represents different types of cross-language links

const (
	CrossLinkFFI        CrossLinkType = iota // Foreign Function Interface
	CrossLinkAPI                             // REST API, GraphQL, etc.
	CrossLinkRPC                             // Remote Procedure Call
	CrossLinkMessage                         // Message passing
	CrossLinkSharedData                      // Shared data structures
	CrossLinkConfig                          // Configuration files
	CrossLinkBuild                           // Build system integration
)

func (CrossLinkType) String

func (clt CrossLinkType) String() string

String returns string representation of cross-link type

type Definition

type Definition struct {
	Name     string `json:"name"`
	Type     string `json:"type"`
	FilePath string `json:"file_path"`
	Line     int    `json:"line"`
	Column   int    `json:"column"`
}

Definition represents a symbol definition location

type DependencyStrength

type DependencyStrength uint8

DependencyStrength represents the strength of a dependency

const (
	DependencyWeak DependencyStrength = iota
	DependencyModerate
	DependencyStrong
	DependencyCritical
)

func (DependencyStrength) String

func (ds DependencyStrength) String() string

String returns string representation of dependency strength

type DependencyType

type DependencyType uint8

DependencyType represents different types of dependencies

const (
	DependencyUnknown DependencyType = iota
	DependencyImport
	DependencyInheritance
	DependencyComposition
	DependencyAggregation
	DependencyAssociation
	DependencyUsage
	DependencyConfiguration
	DependencyRuntime
)

func (DependencyType) String

func (dt DependencyType) String() string

String returns string representation of dependency type

type EnhancedCharacterMask

type EnhancedCharacterMask struct {
	ASCIIMask     [4]uint64   // Fast bitmask for ASCII (0-255)
	UnicodeFilter BloomFilter // Bloom filter for Unicode characters (>255)
	HasUnicode    bool        // Optimization flag
}

EnhancedCharacterMask combines ASCII bitmask with Unicode bloom filter

func ExtractCharMask

func ExtractCharMask(content []byte) EnhancedCharacterMask

ExtractCharMask creates an enhanced character mask supporting Unicode

func (EnhancedCharacterMask) HasAllChars

func (mask EnhancedCharacterMask) HasAllChars(pattern []byte) bool

HasAllChars checks if the mask contains all characters from the pattern

func (EnhancedCharacterMask) HasAllCharsIgnoreCase

func (mask EnhancedCharacterMask) HasAllCharsIgnoreCase(pattern []byte) bool

HasAllCharsIgnoreCase checks if the mask contains all characters from the pattern (case insensitive)

type EnhancedSymbol

type EnhancedSymbol struct {
	Symbol                   // Base symbol information
	ID           SymbolID    `json:"id"`
	IncomingRefs []Reference `json:"incoming_refs"`     // Symbols that reference this one
	OutgoingRefs []Reference `json:"outgoing_refs"`     // Symbols this one references
	ScopeChain   []ScopeInfo `json:"scope_chain"`       // Complete scope hierarchy
	RefStats     RefStats    `json:"ref_stats"`         // Aggregated reference statistics
	Metrics      interface{} `json:"metrics,omitempty"` // Code quality metrics (SymbolMetrics from analysis package)

	// Enhanced metadata for context analysis - MEMORY-CONSCIOUS VERSION
	// Use string fields but with clear documentation about memory implications
	TypeInfo    string   `json:"type_info,omitempty"`   // Type annotation (e.g., "string", "int", "*User")
	IsMutable   bool     `json:"is_mutable"`            // Whether the symbol is mutable (for variables)
	IsExported  bool     `json:"is_exported"`           // Whether the symbol is public/exported
	Annotations []string `json:"annotations,omitempty"` // Annotations like @lci:labels[tag], etc.
	DocComment  string   `json:"doc_comment,omitempty"` // Documentation comment
	Signature   string   `json:"signature,omitempty"`   // Function/method signature
	Complexity  int      `json:"complexity,omitempty"`  // Cyclomatic complexity for functions

	// Variable-specific metadata - COMPACT representation using bitfields
	VariableType  VariableType `json:"variable_type,omitempty"`  // Classification: global, local, parameter, field
	VariableFlags uint8        `json:"variable_flags,omitempty"` // Bitfield: bit0=const, bit1=static, bit2=pointer, bit3=array, bit4=channel, bit5=interface

	// Function-specific metadata - COMPACT representation
	ParameterCount uint8  `json:"parameter_count,omitempty"` // Number of parameters (0-255)
	FunctionFlags  uint8  `json:"function_flags,omitempty"`  // Bitfield: bit0=async, bit1=generator, bit2=method, bit3=variadic
	ReceiverType   string `json:"receiver_type,omitempty"`   // Method receiver type
}

EnhancedSymbol extends Symbol with relational information

func (*EnhancedSymbol) EntityID

func (es *EnhancedSymbol) EntityID(rootPath string, filePath string) string

EntityID generates a unified entity ID for this enhanced symbol

func (*EnhancedSymbol) GetAnnotations

func (es *EnhancedSymbol) GetAnnotations() []string

func (*EnhancedSymbol) GetDocComment

func (es *EnhancedSymbol) GetDocComment() string

func (*EnhancedSymbol) GetReceiverType

func (es *EnhancedSymbol) GetReceiverType() string

func (*EnhancedSymbol) GetSignature

func (es *EnhancedSymbol) GetSignature() string

func (*EnhancedSymbol) GetTypeInfo

func (es *EnhancedSymbol) GetTypeInfo() string

Direct access methods for string fields (no content parameter needed)

func (*EnhancedSymbol) IsArray

func (es *EnhancedSymbol) IsArray() bool

func (*EnhancedSymbol) IsAsyncFunc

func (es *EnhancedSymbol) IsAsyncFunc() bool

Helper methods for function flag access

func (*EnhancedSymbol) IsChannel

func (es *EnhancedSymbol) IsChannel() bool

func (*EnhancedSymbol) IsConst

func (es *EnhancedSymbol) IsConst() bool

Helper methods for variable flag access

func (*EnhancedSymbol) IsGeneratorFunc

func (es *EnhancedSymbol) IsGeneratorFunc() bool

func (*EnhancedSymbol) IsInterface

func (es *EnhancedSymbol) IsInterface() bool

func (*EnhancedSymbol) IsMethodFunc

func (es *EnhancedSymbol) IsMethodFunc() bool

func (*EnhancedSymbol) IsPointer

func (es *EnhancedSymbol) IsPointer() bool

func (*EnhancedSymbol) IsStatic

func (es *EnhancedSymbol) IsStatic() bool

func (*EnhancedSymbol) IsVariadicFunc

func (es *EnhancedSymbol) IsVariadicFunc() bool

type EnhancedSymbolInfo

type EnhancedSymbolInfo struct {
	ID         CompositeSymbolID
	Name       string
	Kind       SymbolKind
	Location   SymbolLocation
	Scope      *SymbolScope
	IsExported bool
	IsExternal bool

	// Language-specific metadata
	Language       string
	Signature      string             // Function/method signature
	Type           string             // Variable/field type
	Value          string             // Constant value if applicable
	TypeParameters []TypeParameter    `json:"type_parameters,omitempty"` // Generic type parameters
	Attributes     []ContextAttribute `json:"attributes,omitempty"`      // Decorators, attributes, annotations

	// Relationships
	ParentSymbol    *CompositeSymbolID  // For methods, fields, etc.
	ImplementsIDs   []CompositeSymbolID // Interfaces this type implements
	ReferencedByIDs []CompositeSymbolID // Symbols that reference this one
	ReferencesIDs   []CompositeSymbolID // Symbols this one references
}

EnhancedSymbolInfo represents detailed information about a symbol

type EnhancedTrigram

type EnhancedTrigram struct {
	Type     TrigramType
	ByteHash uint32 // For byte-based trigrams (ASCII content)
	RuneStr  string // For rune-based trigrams (Unicode content)
	RuneHash uint64 // Hash of the rune string for indexing
}

EnhancedTrigram represents either a byte-based or rune-based trigram

func NewByteTrigram

func NewByteTrigram(b1, b2, b3 byte) EnhancedTrigram

NewByteTrigram creates a byte-based trigram

func NewRuneTrigram

func NewRuneTrigram(runes string) EnhancedTrigram

NewRuneTrigram creates a rune-based trigram

func (EnhancedTrigram) Hash

func (et EnhancedTrigram) Hash() uint64

Hash returns a consistent hash for the trigram regardless of type

func (EnhancedTrigram) String

func (et EnhancedTrigram) String() string

String returns a string representation of the trigram

type ErrorHandlingInfo

type ErrorHandlingInfo struct {
	// Can the function throw/panic?
	CanThrow bool

	// Does it return errors? (Go pattern)
	ReturnsError bool

	// Exception safety level
	ExceptionNeutral bool // No cleanup needed (no resources acquired)
	ExceptionSafe    bool // Cleanup guaranteed (defer, try-finally present)

	// Details
	DeferCount       int   // Number of defer statements
	TryFinallyCount  int   // Number of try-finally blocks
	ThrowCount       int   // Number of throw/panic sites
	ErrorReturnLines []int // Lines with error returns
}

ErrorHandlingInfo captures exception safety characteristics

type ExpansionDirective

type ExpansionDirective struct {
	Type  string // "callers", "callees", "implementations", etc.
	Depth int    // For "callers:2", depth is 2. Default is 1.
}

ExpansionDirective represents a parsed expansion directive

func ParseExpansionDirective

func ParseExpansionDirective(directive string) ExpansionDirective

ParseExpansionDirective parses a directive string like "callers:2" into structured form

type ExportInfo

type ExportInfo struct {
	LocalID      uint32 // Local symbol ID for this export
	ExportedName string // Name as exported
	LocalName    string // Local name (might be different)
	IsDefault    bool   // True for default export
	IsTypeOnly   bool   // True for TypeScript type-only exports
	IsReExport   bool   // True if re-exporting from another module
	SourcePath   string // Source module for re-exports
	Location     SymbolLocation
}

ExportInfo represents an export statement

type ExternalCallInfo

type ExternalCallInfo struct {
	FunctionName string
	Line         int
	Column       int
	IsMethod     bool
	ReceiverType string // For method calls
	Package      string // If determinable
	Reason       string // Why it's considered external
}

ExternalCallInfo details a call to an external/unknown function

type FieldAccess

type FieldAccess struct {
	// What is being accessed (canonical form: "param:user.Name", "global:counter")
	Target string

	// Classification of the target
	TargetType AccessTarget

	// Read or write
	Type AccessType

	// Location in source
	Line   int
	Column int

	// Order within function (0, 1, 2, ...) for sequence analysis
	SeqNum int

	// The base identifier (e.g., "user" in "user.Name")
	BaseIdentifier string

	// Field path (e.g., ["Name"] in "user.Name", ["addr", "city"] in "user.addr.city")
	FieldPath []string
}

FieldAccess tracks a single access to a variable/field

type FileID

type FileID uint32

type FileInfo

type FileInfo struct {
	ID   FileID
	Path string
	// Content is now managed by FileContentStore - access via ID
	LastModified    time.Time
	Checksum        uint64
	FastHash        uint64   // xxhash for quick equality checks (~0.5ns)
	ContentHash     [32]byte // Pre-computed SHA256 hash for cache optimization
	Blocks          []BlockBoundary
	EnhancedSymbols []*EnhancedSymbol // All symbols with relational data (pointers avoid copy overhead)
	Imports         []Import
	References      []Reference           // All references in this file
	ScopeHierarchy  []ScopeInfo           // Complete scope chain for file
	CharMask        EnhancedCharacterMask // Enhanced character mask with ASCII bitmask + Unicode bloom filter

	// Performance optimization: Precomputed line boundaries for O(1) line access
	// LineOffsets[i] contains the byte offset of the start of line i+1
	// Example: LineOffsets = [0, 10, 25] means line 1 starts at 0, line 2 at 10, line 3 at 25
	LineOffsets []int `json:"-"` // Computed during indexing

	// Performance optimization: Pre-computed line->symbol index for O(1) semantic filtering
	// LineToSymbols[line] contains indices into EnhancedSymbols for symbols on that line
	// Avoids O(symbols) scan per search match by moving to O(1) lookup
	LineToSymbols map[int][]int `json:"-"` // Computed during indexing

	// Performance analysis data collected during AST parsing
	// Used for detecting performance anti-patterns (sequential awaits, expensive calls in loops, etc.)
	PerfData []FunctionPerfData `json:"perf_data,omitempty"`

	// Deprecated: Remove after migration to FileContentStore
	Content []byte   `json:"-"` // Will be removed
	Lines   []string `json:"-"` // Will be removed
}

func (*FileInfo) EntityID

func (fi *FileInfo) EntityID(rootPath string) string

EntityID generates a stable, unique identifier for this file.

Format: file:<filename>:<relative_path> Examples:

file:main.go:cmd/lci/main.go
file:types.go:internal/types/types.go

This identifier is stable across runs and can be used for navigation, file lookups, and cross-references. Use with get_object_context tool for full file details including symbols, references, and content.

Returns empty string if validation fails - callers should check result before using in production code.

type FilePathIndex

type FilePathIndex struct {
	// Path segments indexed by depth for efficient glob matching
	// Example: "internal/tui/views/main.go" -> segments[0]["internal"], segments[1]["tui"], segments[2]["views"]
	PathSegments map[int]map[string][]FileID `json:"path_segments"` // depth -> segment -> FileIDs

	// Full paths for exact matching and fallback
	FullPaths map[FileID]string `json:"full_paths"` // FileID -> full path

	// File extensions for filtering
	Extensions map[string][]FileID `json:"extensions"` // extension (e.g., ".go") -> FileIDs

	// Directory hierarchy for efficient directory-based searches
	Directories map[string][]FileID `json:"directories"` // directory path -> FileIDs

	// Base filenames for pattern matching
	BaseNames map[string][]FileID `json:"base_names"` // filename without path -> FileIDs

	// File count for statistics
	TotalFiles int `json:"total_files"`
}

FilePathIndex supports efficient file path search with glob pattern matching

func NewFilePathIndex

func NewFilePathIndex() *FilePathIndex

NewFilePathIndex creates a new empty file path index

type FileSearchOptions

type FileSearchOptions struct {
	Pattern     string   `json:"pattern"`     // Glob pattern like "internal/tui/*view*.go"
	Type        string   `json:"type"`        // "glob", "regex", or "exact"
	Exclude     []string `json:"exclude"`     // Patterns to exclude
	MaxResults  int      `json:"max_results"` // Maximum results to return (default: 100)
	Extensions  []string `json:"extensions"`  // File extensions to include (e.g., [".go", ".ts"])
	Directories []string `json:"directories"` // Directory patterns to search in
}

FileSearchOptions defines options for file path searching

type FileSearchResult

type FileSearchResult struct {
	FileID      FileID `json:"file_id"`
	Path        string `json:"path"`
	Directory   string `json:"directory"`
	BaseName    string `json:"base_name"`
	Extension   string `json:"extension"`
	Language    string `json:"language"`     // Programming language based on extension
	MatchReason string `json:"match_reason"` // How the pattern matched
}

FileSearchResult represents a file found by path search

type FormatType

type FormatType string

FormatType represents the output format for hydrated context

const (
	FormatFull       FormatType = "full"       // Full source code
	FormatSignatures FormatType = "signatures" // Just function/method signatures
	FormatOutline    FormatType = "outline"    // Just symbol names and locations
)

func (FormatType) IsValid

func (f FormatType) IsValid() bool

IsValid checks if the format type is valid

type FunctionCall

type FunctionCall struct {
	Target      CompositeSymbolID `json:"target"`       // Function being called
	CallType    CallType          `json:"call_type"`    // Type of call
	Location    SymbolLocation    `json:"location"`     // Where call occurs
	Context     string            `json:"context"`      // Context of the call
	IsAsync     bool              `json:"is_async"`     // Whether call is asynchronous
	IsRecursive bool              `json:"is_recursive"` // Whether call is recursive
	Arguments   []CallArgument    `json:"arguments"`    // Arguments passed (if available)
}

FunctionCall extends the existing CallEdge with more context

type FunctionContext

type FunctionContext struct {
	Name        string `json:"name"`
	Qualified   string `json:"qualified"`
	StartLine   int    `json:"start_line"`
	EndLine     int    `json:"end_line"`
	Known       bool   `json:"known"`    // False if no enclosing function
	Inferred    bool   `json:"inferred"` // True if resolved heuristically, not from scope hierarchy
	Description string `json:"description,omitempty"`
}

FunctionContext represents the enclosing function for a match

type FunctionPerfData

type FunctionPerfData struct {
	Name      string      `json:"name"`
	StartLine int         `json:"start_line"`
	EndLine   int         `json:"end_line"`
	IsAsync   bool        `json:"is_async"`
	Language  string      `json:"language"`
	Loops     []LoopData  `json:"loops,omitempty"`
	Awaits    []AwaitData `json:"awaits,omitempty"`
	Calls     []CallData  `json:"calls,omitempty"`
}

FunctionPerfData holds performance analysis data for a single function Collected during AST parsing and stored in FileInfo for later analysis

type FunctionTree

type FunctionTree struct {
	RootFunction string      `json:"root_function"`
	Root         *TreeNode   `json:"root"`
	MaxDepth     int         `json:"max_depth"`
	TotalNodes   int         `json:"total_nodes"`
	Options      TreeOptions `json:"options"`
}

FunctionTree represents the complete call hierarchy of a function

func (*FunctionTree) String

func (tree *FunctionTree) String() string

String renders the tree as a formatted string with emoji annotations

type GlobalWriteInfo

type GlobalWriteInfo struct {
	GlobalName string
	Line       int
	Column     int
	FieldPath  []string
	IsPackage  bool // Package-level vs module-level
}

GlobalWriteInfo details a write to global state

type HotSpot

type HotSpot struct {
	File       string `json:"file"`
	MatchCount int    `json:"match_count"`
	FirstLine  int    `json:"first_line"`
	LastLine   int    `json:"last_line"`
}

HotSpot represents a file with high match density

type HydratedContext

type HydratedContext struct {
	// Task from manifest
	Task string `json:"task,omitempty"`

	// Hydrated references with source code
	Refs []HydratedRef `json:"refs"`

	// Hydration statistics
	Stats HydrationStats `json:"stats"`

	// Warnings (e.g., missing symbols, truncation)
	Warnings []string `json:"warnings,omitempty"`
}

HydratedContext is the expanded context with full source code and relationships. This is what agents receive after loading a manifest.

type HydratedRef

type HydratedRef struct {
	// Location
	File   string    `json:"file"`
	Symbol string    `json:"symbol,omitempty"`
	Lines  LineRange `json:"lines"`

	// Metadata from manifest (passed through from ContextRef)
	Role string `json:"role,omitempty"`
	Note string `json:"note,omitempty"`

	// Hydrated content
	Source string `json:"source"` // Actual source code

	// Symbol metadata (when available)
	SymbolType string `json:"symbol_type,omitempty"` // "function", "class", "method", etc.
	Signature  string `json:"signature,omitempty"`   // Function/method signature

	// Expanded relationships (based on directives in X)
	Expanded map[string][]HydratedRef `json:"expanded,omitempty"`

	// Context quality indicators
	IsExported  bool `json:"is_exported,omitempty"`
	IsGenerated bool `json:"is_generated,omitempty"` // Generated code (warn agent)

	// Purity analysis (for callees/dependencies)
	Purity     *PurityInfo `json:"purity,omitempty"`      // Purity info for this symbol
	IsExternal bool        `json:"is_external,omitempty"` // True if external dependency (not in codebase)
}

HydratedRef is a single reference with resolved source code and expanded relationships

type HydrationStats

type HydrationStats struct {
	RefsLoaded        int  `json:"refs_loaded"`         // Number of refs from manifest
	SymbolsHydrated   int  `json:"symbols_hydrated"`    // Total symbols (including expansions)
	TokensApprox      int  `json:"tokens_approx"`       // Approximate token count
	ExpansionsApplied int  `json:"expansions_applied"`  // Number of expansions executed
	Truncated         bool `json:"truncated,omitempty"` // Whether results were truncated
}

HydrationStats provides statistics about the hydration process

type Import

type Import struct {
	Path   string
	FileID FileID
	Line   int
}

type ImportInfo

type ImportInfo struct {
	LocalID       uint32   // Local symbol ID for this import
	ImportPath    string   // What is being imported
	Alias         string   // Import alias if any
	ImportedNames []string // Specific names imported (for named imports)
	IsDefault     bool     // True for default imports
	IsNamespace   bool     // True for namespace imports (import * as X)
	IsTypeOnly    bool     // True for TypeScript type-only imports
	Location      SymbolLocation
}

ImportInfo represents an import statement

type IntentAnalysisOptions

type IntentAnalysisOptions struct {
	Intent          string   `json:"intent"`           // Specific intent to search for (e.g., "size_management", "event_handling")
	Scope           string   `json:"scope"`            // File scope to analyze (glob patterns like "**/ui/**")
	Context         string   `json:"context"`          // Domain context ("ui", "api", "business-logic", "configuration")
	AntiPatterns    []string `json:"anti_patterns"`    // Specific anti-patterns to detect or "*" for all
	MinConfidence   float64  `json:"min_confidence"`   // Minimum confidence threshold (0.0-1.0, default: 0.5)
	IncludeEvidence bool     `json:"include_evidence"` // Include code evidence in results (default: true)
	MaxResults      int      `json:"max_results"`      // Maximum results to return (default: 50)
}

IntentAnalysisOptions configures intent analysis behavior for semantic code understanding

type KnownIOFunction

type KnownIOFunction struct {
	Package  string
	Function string
	Language string
	IOType   SideEffectCategory // SideEffectIO, SideEffectNetwork, etc.
}

KnownIOFunction represents a function known to perform I/O

type KnownPureFunction

type KnownPureFunction struct {
	Package  string // e.g., "strings", "math", "fmt"
	Function string // e.g., "ToLower", "Sqrt"
	Language string // e.g., "go", "javascript", "python"
}

KnownPureFunction represents a function known to be pure from external knowledge

type LineRange

type LineRange struct {
	Start int `json:"s"` // Start line (1-indexed)
	End   int `json:"e"` // End line (1-indexed, inclusive)
}

LineRange specifies a range of lines in a file (1-indexed, inclusive)

type LoadParams

type LoadParams struct {
	// Where to load from
	FromFile   string `json:"from_file,omitempty"`   // File path (relative to project root)
	FromString string `json:"from_string,omitempty"` // Inline JSON string

	// What to include
	Filter  []string `json:"filter,omitempty"`  // Only include these roles
	Exclude []string `json:"exclude,omitempty"` // Exclude these roles

	// Output control
	Format    string `json:"format,omitempty"`     // "full" (default), "signatures", "outline"
	MaxTokens int    `json:"max_tokens,omitempty"` // Approximate token limit (0 = no limit)
}

LoadParams are parameters for the context load operation

type LoopData

type LoopData struct {
	NodeType  string `json:"node_type"` // "for_statement", "while_statement", etc.
	StartLine int    `json:"start_line"`
	EndLine   int    `json:"end_line"`
	Depth     int    `json:"depth"` // Nesting depth (1 = top-level loop)
}

LoopData tracks information about a loop for performance analysis

type ManifestStats

type ManifestStats struct {
	RefCount      int            `json:"rc"`           // Number of refs
	TotalLines    int            `json:"tl,omitempty"` // Total lines referenced (approximate)
	FileCount     int            `json:"fc,omitempty"` // Unique files
	RoleBreakdown map[string]int `json:"rb,omitempty"` // Role → count
	SizeBytes     int            `json:"sb,omitempty"` // Manifest file size in bytes
}

ManifestStats provides statistics about the manifest

type ModuleResolution

type ModuleResolution struct {
	RequestPath  string // Original import/require path
	ResolvedPath string // Resolved file path
	FileID       FileID // Resolved file ID
	IsExternal   bool   // True if outside indexed folder
	IsBuiltin    bool   // True for language builtins
	Resolution   ResolutionType
	Error        string // Error message if resolution failed
}

ModuleResolution represents how a module/package is resolved

type MultiSearchStats

type MultiSearchStats struct {
	Patterns []string                `json:"patterns"`
	Results  map[string]*SearchStats `json:"results"`

	// Cross-pattern analysis
	CommonFiles       []string                  `json:"common_files"`  // Files matching all patterns
	CoOccurrence      map[string]map[string]int `json:"co_occurrence"` // Pattern pairs -> count
	TotalSearchTimeMs int64                     `json:"total_search_time_ms"`
}

MultiSearchStats represents statistics for multiple search patterns

type NodeAnnotation

type NodeAnnotation struct {
	Type        NodeType               `json:"type"`
	Emoji       string                 `json:"emoji"`
	Description string                 `json:"description"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"` // iterations, probability, timing, etc.
}

NodeAnnotation represents architectural patterns and characteristics

type NodeType

type NodeType uint8

NodeType represents different types of code nodes in function trees

const (
	NodeTypeFunction NodeType = iota
	NodeTypeLoop
	NodeTypeCondition
	NodeTypeSwitch
	NodeTypeAsync
	NodeTypeNetwork
	NodeTypeDatabase
	NodeTypeCPUIntensive
	NodeTypeFileIO
	NodeTypeExternal
	NodeTypeRecursive
)

func (NodeType) String

func (nt NodeType) String() string

type ParameterWriteInfo

type ParameterWriteInfo struct {
	ParameterName  string
	ParameterIndex int
	Line           int
	Column         int
	FieldPath      []string // Empty for direct write, populated for field access
	IsPointer      bool     // Write through pointer dereference
}

ParameterWriteInfo details a write to a function parameter

type PatternVerificationOptions

type PatternVerificationOptions struct {
	Pattern    string   `json:"pattern"`     // Pattern name (built-in) or custom rule
	Scope      string   `json:"scope"`       // File pattern scope for verification
	Severity   []string `json:"severity"`    // Filter by severity levels (error, warning, info)
	MaxResults int      `json:"max_results"` // Maximum violations to return
	ReportMode string   `json:"report_mode"` // 'violations' or 'summary' or 'detailed'
}

PatternVerificationOptions defines options for pattern verification

type PatternViolation

type PatternViolation struct {
	Type ViolationType

	// The target involved
	Target string

	// Location information
	Line      int // Primary line (usually the problematic access)
	ReadLine  int // Line of the read involved
	WriteLine int // Line of the write involved

	// Human-readable description
	Description string

	// Severity from 0.0 (informational) to 1.0 (definitely problematic)
	Severity float64
}

PatternViolation flags a specific concerning pattern

type PurityClassification

type PurityClassification struct {
	// Parameters mutated (vector of parameter indices)
	// e.g., [0, 2] means parameters 0 and 2 are mutated
	MutatedParameters []int

	// Object/receiver mutated
	MutatesReceiver bool

	// Globals mutated (list of global variable names)
	MutatedGlobals []string

	// Closures mutated (list of captured variable names)
	MutatedClosures []string

	// Dependent functions and their purity status
	// Maps function name to its purity (true = pure, false = impure)
	DependentFunctions map[string]bool

	// I/O operations performed
	PerformsIO bool

	// Network operations performed
	PerformsNetwork bool

	// Database operations performed
	PerformsDatabase bool

	// Exception/panic operations
	CanThrow bool
}

PurityClassification tracks WHAT affects purity (fine-grained analysis) This is a vector-based classification instead of a single level

type PurityConfidence

type PurityConfidence uint8

PurityConfidence represents confidence level in purity classification

const (
	// ConfidenceNone - cannot determine purity
	ConfidenceNone PurityConfidence = iota

	// ConfidenceLow - weak evidence, likely has side effects
	ConfidenceLow

	// ConfidenceMedium - some evidence but uncertainty remains
	ConfidenceMedium

	// ConfidenceHigh - strong evidence, analysis is reliable
	ConfidenceHigh

	// ConfidenceProven - proven pure/impure (e.g., user annotation, known stdlib)
	ConfidenceProven
)

func (PurityConfidence) String

func (c PurityConfidence) String() string

type PurityInfo

type PurityInfo struct {
	IsPure      bool     `json:"is_pure"`                // True if function has no side effects
	PurityLevel string   `json:"purity_level,omitempty"` // "Pure", "InternallyPure", "ObjectState", "ModuleGlobal", "ExternalDependency"
	Categories  []string `json:"categories,omitempty"`   // Side effect categories (e.g., "io", "param_write")
	PurityScore float64  `json:"purity_score,omitempty"` // 0.0-1.0
	Reasons     []string `json:"reasons,omitempty"`      // Why it's impure
}

PurityInfo contains purity analysis for a function

type PurityLevel

type PurityLevel int

PurityLevel represents the purity classification of a function Based on two-phase analysis: internal effects + transitive dependencies

const (
	// PurityLevelPure - Level 1: True purity
	// No side effects, all dependencies are pure (referentially transparent)
	// Can only be achieved after Phase 2 resolves all dependencies
	PurityLevelPure PurityLevel = 1

	// PurityLevelInternallyPure - Level 2: Internally pure
	// No direct side effects in function body
	// But calls unknown/unresolved functions (before Phase 2)
	// OR calls functions that are Level 3+ (after Phase 2)
	PurityLevelInternallyPure PurityLevel = 2

	// PurityLevelObjectState - Level 3: Object-local mutations
	// Mutates receiver (methods) or parameters only
	// No global state or I/O
	// Examples: c.value++, array[i] = x
	PurityLevelObjectState PurityLevel = 3

	// PurityLevelModuleGlobal - Level 4: Module/global state
	// Mutates global variables or module-level state
	// No I/O or external dependencies
	// Examples: globalCounter++, cache[key] = value
	PurityLevelModuleGlobal PurityLevel = 4

	// PurityLevelExternalDependency - Level 5: External side effects
	// Performs I/O, network, database operations
	// Affects state outside the program
	// Examples: fmt.Println(), db.Execute(), http.Get()
	PurityLevelExternalDependency PurityLevel = 5
)

func ComputePurityLevel

func ComputePurityLevel(categories SideEffectCategory, hasUnresolvedCalls bool) PurityLevel

ComputePurityLevel determines the purity level based on side effect categories This is used in Phase 1 (internal analysis)

func (PurityLevel) String

func (p PurityLevel) String() string

String returns a human-readable representation of the purity level

type RefCount

type RefCount struct {
	IncomingCount int              `json:"incoming_count"`
	OutgoingCount int              `json:"outgoing_count"`
	IncomingFiles []FileID         `json:"incoming_files"`
	OutgoingFiles []FileID         `json:"outgoing_files"`
	ByType        map[string]int   `json:"by_type"`
	Strength      RefStrengthStats `json:"strength"`
}

RefCount tracks reference statistics

type RefStats

type RefStats struct {
	FolderLevel   RefCount `json:"folder_level"`
	FileLevel     RefCount `json:"file_level"`
	ClassLevel    RefCount `json:"class_level"`
	FunctionLevel RefCount `json:"function_level"`
	VariableLevel RefCount `json:"variable_level"`
	Total         RefCount `json:"total"`
}

RefStats provides reference statistics at multiple scope levels

type RefStrength

type RefStrength uint8

RefStrength represents the coupling strength of a reference

const (
	RefStrengthTight      RefStrength = iota // Direct dependency
	RefStrengthLoose                         // Indirect usage
	RefStrengthTransitive                    // Through other symbols
)

func (RefStrength) String

func (rs RefStrength) String() string

type RefStrengthStats

type RefStrengthStats struct {
	Tight      int `json:"tight"`
	Loose      int `json:"loose"`
	Transitive int `json:"transitive"`
}

RefStrengthStats provides breakdown by coupling strength

type Reference

type Reference struct {
	ID             uint64        `json:"id"`
	SourceSymbol   SymbolID      `json:"source_symbol"`
	TargetSymbol   SymbolID      `json:"target_symbol"`
	FileID         FileID        `json:"file_id"`
	Line           int           `json:"line"`
	Column         int           `json:"column"`
	Type           ReferenceType `json:"type"`
	ContextLines   []StringRef   `json:"-"`             // Line references for context (not serialized)
	ScopeContext   []ScopeInfo   `json:"scope_context"` // Scope breadcrumb at reference point
	Strength       RefStrength   `json:"strength"`
	ReferencedName string        `json:"referenced_name"`          // Actual symbol name being referenced (from Tree-sitter AST)
	Quality        string        `json:"quality,omitempty"`        // RefQuality* constants: precise, assigned, returned, cast, heuristic
	Resolved       *bool         `json:"resolved,omitempty"`       // For include/import resolution (nil if not applicable)
	Ambiguous      bool          `json:"ambiguous,omitempty"`      // Multiple possible targets
	Candidates     []string      `json:"candidates,omitempty"`     // Candidate file paths / symbols for ambiguous include
	FailureReason  string        `json:"failure_reason,omitempty"` // If Resolved=false

	// Deprecated
	Context []string `json:"context"` // Will be removed
}

Reference represents a relationship between symbols

func (*Reference) EntityID

func (r *Reference) EntityID(rootPath string, filePath string) string

EntityID generates a stable, unique identifier for this reference.

Format: reference:<type>_<symbol_name>:<filename>:<line>:<column> Examples:

reference:call_CalculateMetrics:test.go:123:45
reference:use_config:main.go:45:12

This identifier is stable across runs and can be used for navigation, reference lookups, and call graph analysis. Use with get_object_context tool for full reference details including source and target entities.

Returns empty string if validation fails - callers should check result before using in production code.

type ReferenceType

type ReferenceType uint8

ReferenceType represents the kind of reference relationship

const (
	RefTypeImport ReferenceType = iota
	RefTypeCall
	RefTypeInheritance
	RefTypeAssignment
	RefTypeDeclaration
	RefTypeParameter
	RefTypeReturn
	RefTypeTypeAnnotation
	RefTypeImplements
	RefTypeExtends
	RefTypeUsage
)

func (ReferenceType) String

func (rt ReferenceType) String() string

type RelatedSymbol

type RelatedSymbol struct {
	Symbol   EnhancedSymbol `json:"symbol"`
	Relation RelationType   `json:"relation"`
	Strength RefStrength    `json:"strength"`
	Distance int            `json:"distance"`            // Degrees of separation
	FileName string         `json:"file_name,omitempty"` // File name for display
}

RelatedSymbol represents a symbol related to the current one

type RelationType

type RelationType uint8

RelationType represents how symbols are related

const (
	RelationParent   RelationType = iota // Contains this symbol
	RelationChild                        // Contained by this symbol
	RelationSibling                      // Same scope level
	RelationCaller                       // Calls this symbol
	RelationCallee                       // Called by this symbol
	RelationImporter                     // Imports this symbol
	RelationImportee                     // Imported by this symbol
)

func (RelationType) String

func (rt RelationType) String() string

type RelationalContext

type RelationalContext struct {
	Symbol         EnhancedSymbol  `json:"symbol"`
	RefStats       RefStats        `json:"ref_stats"`
	Breadcrumbs    []ScopeInfo     `json:"breadcrumbs"`      // Scope chain outside search context
	RelatedSymbols []RelatedSymbol `json:"related_symbols"`  // Nearby related symbols
	Function       FunctionContext `json:"function_context"` // Enclosing function/method context
}

RelationalContext provides comprehensive relational information for search results

type RelationshipType

type RelationshipType uint8

RelationshipType represents different types of symbol relationships

const (
	// Structural relationships
	RelationExtends RelationshipType = iota
	RelationImplements
	RelationContains
	RelationContainedBy

	// Dependency relationships
	RelationDependsOn
	RelationDependedOnBy

	// Call relationships
	RelationCalls
	RelationCalledBy

	// Reference relationships
	RelationReferences
	RelationReferencedBy

	// Import relationships
	RelationImports
	RelationImportedBy

	// File co-location
	RelationFileCoLocated

	// Type relationships
	RelationTypeOf
	RelationHasType

	// Inheritance chain
	RelationParentType
	RelationChildType

	// Cross-language
	RelationCrossLanguage
)

func ParseRelationshipType

func ParseRelationshipType(s string) RelationshipType

ParseRelationshipType parses a string into a RelationshipType

func (RelationshipType) String

func (rt RelationshipType) String() string

String returns string representation of relationship type

type ResolutionType

type ResolutionType int

ResolutionType represents how a module was resolved

const (
	ResolutionUnknown   ResolutionType = iota
	ResolutionFile                     // Direct file resolution
	ResolutionDirectory                // Directory with index file
	ResolutionPackage                  // Package.json resolution
	ResolutionModule                   // Go module resolution
	ResolutionBuiltin                  // Language builtin
	ResolutionExternal                 // External dependency
	ResolutionNotFound                 // Could not resolve
	ResolutionInternal                 // Internal to project
	ResolutionError                    // Resolution failed
)

func (ResolutionType) String

func (rt ResolutionType) String() string

String returns a string representation of the resolution type

type SaveParams

type SaveParams struct {
	// What to save
	Refs []ContextRef `json:"refs,omitempty"` // References to save

	// Where to save
	ToFile   string `json:"to_file,omitempty"`   // File path (relative to project root)
	ToString bool   `json:"to_string,omitempty"` // Return as JSON string instead of writing

	// How to save
	Append bool   `json:"append,omitempty"` // Merge with existing manifest (default: false)
	Task   string `json:"task,omitempty"`   // Task description/directive
}

SaveParams are parameters for the context save operation

type SaveResponse

type SaveResponse struct {
	Saved     string        `json:"saved,omitempty"`    // File path if to_file was used
	Manifest  string        `json:"manifest,omitempty"` // JSON string if to_string was true
	Stats     ManifestStats `json:"stats"`
	RefCount  int           `json:"ref_count"`  // Number of refs saved
	FileCount int           `json:"file_count"` // Number of unique files
}

SaveResponse is the response from a save operation

type ScopeInfo

type ScopeInfo struct {
	Type       ScopeType          `json:"type"`
	Name       string             `json:"name"`
	FullPath   string             `json:"full_path"`
	StartLine  int                `json:"start_line"`
	EndLine    int                `json:"end_line"`
	Level      int                `json:"level"`
	Language   string             `json:"language"`
	Attributes []ContextAttribute `json:"attributes,omitempty"` // Context attributes for this scope
}

ScopeInfo represents contextual scope information

type ScopeType

type ScopeType uint8

ScopeType represents different levels of code organization

const (
	ScopeTypeFolder ScopeType = iota
	ScopeTypeFile
	ScopeTypePackage
	ScopeTypeNamespace
	ScopeTypeClass
	ScopeTypeInterface
	ScopeTypeFunction
	ScopeTypeMethod
	ScopeTypeVariable
	ScopeTypeBlock
	ScopeTypeStruct
)

func (ScopeType) String

func (st ScopeType) String() string

type SearchOptions

type SearchOptions struct {
	// Basic search options
	CaseInsensitive    bool
	MaxContextLines    int
	MergeFileResults   bool   // Merge multiple results from same file
	EnsureCompleteStmt bool   // Ensure complete statements with comments
	ExcludePattern     string // Regex pattern to exclude files
	IncludePattern     string // Regex pattern to include files (whitelist)

	// Result control
	MaxResults int // Optional cap for number of results to return (0 = no cap)

	// Regex support
	UseRegex bool // Enable regex pattern matching

	// Semantic search filters for AI agents
	SymbolTypes     []string // Filter by symbol types: "function", "variable", "class", "type", "constant"
	DeclarationOnly bool     // Only show symbol definitions, not usages
	UsageOnly       bool     // Only show symbol usages, not definitions
	ExportedOnly    bool     // Only show public/exported symbols
	ExcludeTests    bool     // Exclude test files and test functions
	ExcludeComments bool     // Exclude matches in comments (deprecated: use CodeOnly instead)
	MutableOnly     bool     // Only mutable variables (var, not const)
	GlobalOnly      bool     // Only global/package-level symbols

	// Content-specific filters (powered by AST)
	CommentsOnly    bool // Search only in comments
	CodeOnly        bool // Search only in code (excludes comments and strings)
	StringsOnly     bool // Search only in string literals
	TemplateStrings bool // Include template strings (sql“, gql“, etc.) when StringsOnly is true

	// Context extraction control
	FullFunction     bool // Show complete function body for matches inside functions
	MaxFunctionLines int  // Max lines for function context (0 = unlimited)
	ContextPadding   int  // Extra lines around match when not showing full function

	// Grep-like features (P0 - Critical for LLM use cases)
	InvertMatch     bool     // Inverted match (grep -v): show lines that DON'T match pattern
	Patterns        []string // Multiple patterns with OR logic (grep -e pattern1 -e pattern2)
	CountPerFile    bool     // Return match count per file (grep -c)
	FilesOnly       bool     // Return only filenames with matches (grep -l)
	WordBoundary    bool     // Match whole words only (grep -w)
	MaxCountPerFile int      // Max matches per file (grep -m), 0 = unlimited

	// Additional indexing-specific option
	Verbose bool // Show verbose output
	// Context search option
	IncludeObjectIDs bool // Include compact object IDs for context search (default: true)

	// AI-focused features for RepoBench evaluation
	ContextFilter string // Filter results by context pattern (e.g., "cache", "test")
}

SearchOptions defines options for searching code

type SearchStats

type SearchStats struct {
	Pattern          string `json:"pattern"`
	TotalMatches     int    `json:"total_matches"`
	FilesWithMatches int    `json:"files_with_matches"`

	// Distribution across codebase
	FileDistribution map[string]int `json:"file_distribution"` // filepath -> match count
	DirDistribution  map[string]int `json:"dir_distribution"`  // directory -> match count

	// Symbol context
	SymbolTypes     map[string]int `json:"symbol_types"` // "function", "variable", etc -> count
	DefinitionCount int            `json:"definition_count"`
	UsageCount      int            `json:"usage_count"`
	CommentMatches  int            `json:"comment_matches"`

	// Code quality indicators
	TestFileMatches int `json:"test_file_matches"`
	ExportedSymbols int `json:"exported_symbols"`

	// Performance hints
	HotSpots     []HotSpot `json:"hot_spots"` // Files with most matches
	SearchTimeMs int64     `json:"search_time_ms"`
}

SearchStats represents statistical information about search results

type SideEffectCategory

type SideEffectCategory uint32

SideEffectCategory represents categories of side effects as a bitfield. Multiple categories can be combined with bitwise OR.

const (
	// SideEffectNone indicates no detected side effects (pure function candidate)
	SideEffectNone SideEffectCategory = 0

	// Write effects - mutations to state
	SideEffectParamWrite    SideEffectCategory = 1 << iota // Writes to function parameters
	SideEffectReceiverWrite                                // Writes to receiver/this/self
	SideEffectGlobalWrite                                  // Writes to global/module-level state
	SideEffectClosureWrite                                 // Writes to captured closure variables
	SideEffectFieldWrite                                   // Writes to object fields (general)

	// I/O effects
	SideEffectIO       // Any I/O operation (file, network, console)
	SideEffectDatabase // Database operations
	SideEffectNetwork  // Network operations specifically

	// Control flow effects
	SideEffectThrow   // Can throw/panic/raise
	SideEffectChannel // Channel send/receive (Go)
	SideEffectAsync   // Async operations that may have deferred effects

	// Uncertainty markers (conservative flags)
	SideEffectExternalCall  // Calls external/unknown function
	SideEffectDynamicCall   // Dynamic dispatch (interface, function pointer)
	SideEffectReflection    // Uses reflection
	SideEffectUncertain     // Analysis couldn't determine (assume side effects)
	SideEffectIndirectWrite // Writes through pointer/reference that may alias
)

func (SideEffectCategory) HasIOEffects

func (s SideEffectCategory) HasIOEffects() bool

HasIOEffects returns true if any I/O-related side effects are present

func (SideEffectCategory) HasUncertainty

func (s SideEffectCategory) HasUncertainty() bool

HasUncertainty returns true if any uncertainty markers are present

func (SideEffectCategory) HasWriteEffects

func (s SideEffectCategory) HasWriteEffects() bool

HasWriteEffects returns true if any write-related side effects are present

func (SideEffectCategory) IsPure

func (s SideEffectCategory) IsPure() bool

IsPure returns true only if no side effects AND no uncertainty

func (SideEffectCategory) String

func (s SideEffectCategory) String() string

String returns a human-readable representation of the side effect categories

type SideEffectInfo

type SideEffectInfo struct {
	// Function identification
	FunctionName string
	FilePath     string
	StartLine    int
	EndLine      int

	// Bitfield of detected side effect categories
	Categories SideEffectCategory

	// Confidence in the analysis
	Confidence PurityConfidence

	// Purity level (two-phase analysis result)
	PurityLevel PurityLevel

	// Purity classification: track WHAT affects purity
	PurityClassification PurityClassification

	// Access pattern analysis
	AccessPattern *AccessPattern

	// Specific details about detected effects
	ParameterWrites []ParameterWriteInfo
	GlobalWrites    []GlobalWriteInfo
	ExternalCalls   []ExternalCallInfo
	ThrowSites      []ThrowSiteInfo

	// Unresolved function calls (for Phase 2 propagation)
	UnresolvedCalls []UnresolvedCallInfo

	// Error handling analysis
	ErrorHandling *ErrorHandlingInfo

	// Transitive effects (from callees) - populated by propagation
	TransitiveCategories SideEffectCategory
	TransitiveConfidence PurityConfidence

	// Combined assessment
	IsPure           bool    // True ONLY if locally pure AND all callees pure
	PurityScore      float64 // 1.0 = definitely pure, 0.0 = definitely impure
	PurityConfidence float64 // Confidence in the purity score (0.0-1.0)

	// Reasons for impurity (for debugging/reporting)
	ImpurityReasons []string
}

SideEffectInfo captures complete side-effect analysis for a function

func NewSideEffectInfo

func NewSideEffectInfo() *SideEffectInfo

NewSideEffectInfo creates a new SideEffectInfo with default values

func (*SideEffectInfo) AddCategory

func (si *SideEffectInfo) AddCategory(cat SideEffectCategory)

AddCategory adds a side effect category

func (*SideEffectInfo) AddImpurityReason

func (si *SideEffectInfo) AddImpurityReason(reason string)

AddImpurityReason adds a reason why the function is not pure

func (*SideEffectInfo) ComputePurityScore

func (si *SideEffectInfo) ComputePurityScore()

ComputePurityScore calculates the purity score and level based on categories and confidence. This uses a CONSERVATIVE approach: any uncertainty results in low purity score. This is called after Phase 1 (internal analysis) and after Phase 2 (propagation).

type StringRef

type StringRef struct {
	FileID FileID // Which file this string comes from
	Offset uint32 // Byte offset in the file
	Length uint32 // Number of bytes
	Hash   uint64 // Precomputed hash of the string content
}

StringRef is a lightweight, immutable reference to a substring within a file

func NewStringRef

func NewStringRef(fileID FileID, content []byte, start, length int) StringRef

NewStringRef creates a new StringRef from the given content

func NewStringRefWithLine

func NewStringRefWithLine(fileID FileID, content []byte, start, length, lineNum int) StringRef

NewStringRefWithLine creates a new StringRef with line number information

func (StringRef) Contains

func (ref StringRef) Contains(offset uint32) bool

Contains checks if the given byte offset falls within this reference

func (StringRef) Equal

func (ref StringRef) Equal(other StringRef) bool

Equal performs fast equality check using hash first

func (StringRef) ExtendTo

func (ref StringRef) ExtendTo(other StringRef) StringRef

ExtendTo creates a reference that spans from this ref to another

func (StringRef) IsEmpty

func (ref StringRef) IsEmpty() bool

IsEmpty returns true if this is an empty/invalid reference

func (StringRef) IsSameLocation

func (ref StringRef) IsSameLocation(other StringRef) bool

IsSameLocation checks if two refs point to exactly the same location

func (StringRef) Overlaps

func (ref StringRef) Overlaps(other StringRef) bool

Overlaps checks if two references overlap (must be in same file)

func (StringRef) QuickCompare

func (ref StringRef) QuickCompare(other StringRef) int

QuickCompare provides fast comparison for sorting

func (StringRef) String

func (ref StringRef) String(content []byte) string

String returns the actual string content (allocates) Use sparingly - prefer zero-copy operations

func (StringRef) Substring

func (ref StringRef) Substring(offset, length uint32) StringRef

Substring creates a sub-reference without accessing memory

func (StringRef) TrimPrefix

func (ref StringRef) TrimPrefix(n uint32) StringRef

TrimPrefix removes n bytes from the start

func (StringRef) TrimSuffix

func (ref StringRef) TrimSuffix(n uint32) StringRef

TrimSuffix removes n bytes from the end

type StringRefAllocator

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

StringRefAllocator provides efficient block-based allocation for StringRefs

func (*StringRefAllocator) Allocate

func (a *StringRefAllocator) Allocate() *StringRef

Allocate returns a pointer to a new StringRef

func (*StringRefAllocator) AllocateBatch

func (a *StringRefAllocator) AllocateBatch(n int) []*StringRef

AllocateBatch allocates multiple StringRefs and returns them individually

func (*StringRefAllocator) AllocateSlice

func (a *StringRefAllocator) AllocateSlice(n int) []StringRef

AllocateSlice pre-allocates a slice of StringRefs from the block allocator

func (*StringRefAllocator) NewStringRef

func (a *StringRefAllocator) NewStringRef(fileID FileID, start, length uint32, hash uint64) *StringRef

NewStringRef allocates and initializes a new StringRef

func (*StringRefAllocator) NewStringRefSlice

func (a *StringRefAllocator) NewStringRefSlice(fileID FileID, offsets []uint32) []StringRef

NewStringRefSlice allocates and initializes a slice of StringRefs

func (*StringRefAllocator) Reset

func (a *StringRefAllocator) Reset()

Reset returns all blocks to the free list for reuse

func (*StringRefAllocator) ReturnToPool

func (a *StringRefAllocator) ReturnToPool()

ReturnToPool returns blocks to the sync.Pool to be GC'd if needed

func (*StringRefAllocator) Stats

Stats returns current allocator statistics

type StringRefBlock

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

StringRefBlock is a block of pre-allocated StringRefs

type Symbol

type Symbol struct {
	Name           string
	Type           SymbolType
	FileID         FileID
	Line           int
	Column         int
	EndLine        int
	EndColumn      int
	Attributes     []ContextAttribute // Context-altering attributes
	TypeParameters []TypeParameter    `json:"type_parameters,omitempty"` // Generic type parameters
	Visibility     SymbolVisibility   `json:"visibility,omitempty"`      // Visibility/export status
}

func (*Symbol) EntityID

func (s *Symbol) EntityID(rootPath string, filePath string) string

EntityID generates a stable, unique identifier for this symbol.

Format: symbol:<type>_<name>:<filename>:<line>:<column> Examples:

symbol:func_main:main.go:71:0           -> Function main
symbol:var_config:main.go:25:5          -> Variable config
symbol:struct_MyStruct:types.go:16:27   -> Struct MyStruct

This identifier is stable across runs and can be used for navigation, cross-references, and drill-down operations. Use with get_object_context tool for full symbol details including calls, references, and metrics.

Returns empty string if validation fails - callers should check result before using in production code.

type SymbolAnnotation

type SymbolAnnotation struct {
	Type       AnnotationType `json:"type"`       // Type of annotation
	Value      string         `json:"value"`      // Annotation value
	Parameters []string       `json:"parameters"` // Annotation parameters
	Location   SymbolLocation `json:"location"`   // Where annotation appears
}

SymbolAnnotation represents language-specific annotations

type SymbolDependency

type SymbolDependency struct {
	Target        CompositeSymbolID  `json:"target"`         // What this symbol depends on
	Type          DependencyType     `json:"type"`           // Type of dependency
	Strength      DependencyStrength `json:"strength"`       // How strong the dependency is
	Context       string             `json:"context"`        // Context where dependency occurs
	ImportPath    string             `json:"import_path"`    // Import path if applicable
	IsOptional    bool               `json:"is_optional"`    // Whether dependency is optional
	IsConditional bool               `json:"is_conditional"` // Whether dependency is conditional
}

SymbolDependency represents a dependency relationship with additional context

type SymbolID

type SymbolID uint64

type SymbolIdentity

type SymbolIdentity struct {
	ID        CompositeSymbolID `json:"id"`        // Unique composite ID
	Name      string            `json:"name"`      // Symbol name
	FullName  string            `json:"full_name"` // Fully qualified name
	Kind      SymbolKind        `json:"kind"`      // Type of symbol (function, class, etc.)
	Language  string            `json:"language"`  // Programming language
	Location  SymbolLocation    `json:"location"`  // Where the symbol is defined
	Signature string            `json:"signature"` // Function/method signature
	Type      string            `json:"type"`      // Variable/field type
	Value     string            `json:"value"`     // Constant value if applicable
}

SymbolIdentity contains core identification information for a symbol

type SymbolKind

type SymbolKind int

SymbolKind represents the kind of symbol

const (
	SymbolKindUnknown SymbolKind = iota
	SymbolKindPackage
	SymbolKindImport
	SymbolKindType
	SymbolKindInterface
	SymbolKindStruct
	SymbolKindClass
	SymbolKindFunction
	SymbolKindMethod
	SymbolKindConstructor
	SymbolKindVariable
	SymbolKindConstant
	SymbolKindField
	SymbolKindProperty
	SymbolKindParameter
	SymbolKindLabel
	SymbolKindModule
	SymbolKindNamespace
	SymbolKindEnum
	SymbolKindEnumMember
	SymbolKindTrait
	SymbolKindEvent
	SymbolKindDelegate
	SymbolKindRecord
	SymbolKindAttribute
)

func (SymbolKind) String

func (sk SymbolKind) String() string

String returns a string representation of the symbol kind

type SymbolLocation

type SymbolLocation struct {
	FileID FileID
	Line   int
	Column int
	Offset int // Byte offset in file
}

SymbolLocation represents a location in the codebase

type SymbolMetadata

type SymbolMetadata struct {
	// Documentation and comments
	Documentation []string `json:"documentation"` // Doc comments
	Comments      []string `json:"comments"`      // Inline comments

	// Attributes and annotations
	Attributes  []ContextAttribute `json:"attributes"`  // Context attributes (async, deprecated, etc.)
	Annotations []SymbolAnnotation `json:"annotations"` // Language-specific annotations

	// Quality metrics
	ComplexityScore int `json:"complexity_score"` // Cyclomatic/cognitive complexity
	CouplingScore   int `json:"coupling_score"`   // How tightly coupled this symbol is
	CohesionScore   int `json:"cohesion_score"`   // How cohesive this symbol is

	// AI navigation hints
	EditRiskScore int      `json:"edit_risk_score"` // Risk of editing this symbol (0-10)
	StabilityTags []string `json:"stability_tags"`  // CORE, PUBLIC_API, RECURSIVE, etc.
	SafetyNotes   []string `json:"safety_notes"`    // Human-readable safety warnings
}

SymbolMetadata contains additional contextual information

type SymbolReference

type SymbolReference struct {
	Symbol     CompositeSymbolID // The symbol being referenced
	Location   SymbolLocation    // Where the reference occurs
	IsExternal bool              // True if the symbol is external to the indexed folder
	ImportPath string            // Import path if applicable (e.g., "fmt", "react")
}

SymbolReference represents a reference to a symbol from another location

type SymbolRelationships

type SymbolRelationships struct {
	// Structural relationships
	Extends     []CompositeSymbolID `json:"extends"`      // Types this symbol extends
	Implements  []CompositeSymbolID `json:"implements"`   // Interfaces this symbol implements
	Contains    []CompositeSymbolID `json:"contains"`     // Symbols contained within this symbol
	ContainedBy *CompositeSymbolID  `json:"contained_by"` // Parent symbol containing this one

	// Dependency relationships
	Dependencies []SymbolDependency  `json:"dependencies"` // Symbols this depends on
	Dependents   []CompositeSymbolID `json:"dependents"`   // Symbols that depend on this

	// Call relationships (from existing CallGraph)
	CallsTo  []FunctionCall `json:"calls_to"`  // Functions this calls
	CalledBy []FunctionCall `json:"called_by"` // Functions that call this

	// File co-location relationships
	FileCoLocated []CompositeSymbolID `json:"file_co_located"` // Other symbols in same file

	// Cross-language relationships
	CrossLanguage []CrossLanguageLink `json:"cross_language"` // Links to symbols in other languages
}

SymbolRelationships contains all relationship types for a symbol

type SymbolScope

type SymbolScope struct {
	Type     SymbolScopeType
	Name     string // Name of the scope (e.g., function name, class name)
	Parent   *SymbolScope
	StartPos int // Start position in file
	EndPos   int // End position in file
}

SymbolScope represents the scope hierarchy of a symbol

type SymbolScopeType

type SymbolScopeType int

SymbolScopeType represents different types of scopes for symbols This is distinct from the existing ScopeType used elsewhere

const (
	ScopeGlobal SymbolScopeType = iota
	ScopeModule
	ScopePackage
	ScopeClass
	ScopeFunction
	ScopeMethod
	ScopeBlock
	ScopeNamespace
	ScopeInterface
)

func (SymbolScopeType) String

func (st SymbolScopeType) String() string

String returns a string representation of the scope type

type SymbolTable

type SymbolTable struct {
	FileID   FileID
	Language string
	Symbols  map[uint32]*EnhancedSymbolInfo // LocalSymbolID -> Symbol
	Imports  []ImportInfo
	Exports  []ExportInfo

	// Scope tree
	RootScope *SymbolScope

	// Quick lookups
	SymbolsByName map[string][]uint32 // Name -> LocalSymbolIDs
	NextLocalID   uint32              // Next available LocalSymbolID
}

SymbolTable represents a collection of symbols for a file

type SymbolType

type SymbolType uint8
const (
	SymbolTypeFunction SymbolType = iota
	SymbolTypeClass
	SymbolTypeMethod
	SymbolTypeVariable
	SymbolTypeConstant
	SymbolTypeInterface
	SymbolTypeType
	// Phase 4: New symbol types
	SymbolTypeStruct
	SymbolTypeModule
	SymbolTypeNamespace
	// Phase 5A: C# specific symbol types
	SymbolTypeProperty
	SymbolTypeEvent
	SymbolTypeDelegate
	SymbolTypeEnum
	SymbolTypeRecord
	SymbolTypeOperator
	SymbolTypeIndexer
	// Phase 5B: Kotlin specific symbol types
	SymbolTypeObject
	SymbolTypeCompanion
	SymbolTypeExtension
	SymbolTypeAnnotation
	// Additional symbol types
	SymbolTypeField
	SymbolTypeEnumMember
	// Rust specific symbol types
	SymbolTypeTrait
	SymbolTypeImpl
	// Constructor
	SymbolTypeConstructor
)

func (SymbolType) String

func (st SymbolType) String() string

type SymbolUsage

type SymbolUsage struct {
	ReferenceCount    int `json:"reference_count"`    // Total references to this symbol
	ImportCount       int `json:"import_count"`       // Times imported
	InheritanceCount  int `json:"inheritance_count"`  // Times extended/implemented
	CallCount         int `json:"call_count"`         // Times called (functions only)
	ModificationCount int `json:"modification_count"` // Times modified (variables only)

	// Reference patterns
	ReferencingFiles []FileID       `json:"referencing_files"` // Files that reference this
	HotSpots         []UsageHotSpot `json:"hot_spots"`         // High-usage locations

	// Temporal usage patterns
	FirstSeen      time.Time `json:"first_seen"`      // When first discovered
	LastModified   time.Time `json:"last_modified"`   // Last modification time
	LastReferenced time.Time `json:"last_referenced"` // Last time referenced
}

SymbolUsage represents usage statistics and patterns

type SymbolVisibility

type SymbolVisibility struct {
	Access      AccessLevel `json:"access"`       // public, private, protected, internal
	Scope       SymbolScope `json:"scope"`        // Scope hierarchy information
	IsExported  bool        `json:"is_exported"`  // Whether symbol is exported/public
	IsExternal  bool        `json:"is_external"`  // Whether symbol is external to project
	IsBuiltin   bool        `json:"is_builtin"`   // Whether symbol is language builtin
	IsGenerated bool        `json:"is_generated"` // Whether symbol is generated code
}

SymbolVisibility represents access control and scope information

type TargetAccessPattern

type TargetAccessPattern struct {
	// The target being accessed
	Target string

	// Classification of the target
	TargetType AccessTarget

	// Pattern for this specific target
	Pattern AccessPatternType

	// Access counts
	ReadCount  int
	WriteCount int

	// Sequence string: "RRW" = read, read, write; "WRR" = write, read, read
	Sequence string

	// Lines of first read and first write (for violation reporting)
	FirstReadLine  int
	FirstWriteLine int

	// Line of first read after a write (for WriteThenRead detection)
	FirstReadAfterWriteLine int
}

TargetAccessPattern tracks access pattern to a single variable/field

type ThrowSiteInfo

type ThrowSiteInfo struct {
	Type   string // "panic", "throw", "raise", etc.
	Line   int
	Column int
}

ThrowSiteInfo details a throw/panic/raise site

type TreeNode

type TreeNode struct {
	Name        string           `json:"name"`
	FilePath    string           `json:"file_path"`
	Line        int              `json:"line"`
	Depth       int              `json:"depth"`
	NodeType    NodeType         `json:"node_type"`
	Annotations []NodeAnnotation `json:"annotations"`
	Children    []*TreeNode      `json:"children"`
	Parent      *TreeNode        `json:"-"` // Exclude from JSON to avoid circular references

	// Edit safety and stability indicators for coding agents
	EditRiskScore   int      `json:"edit_risk_score"`  // 0-10 risk of breaking when editing this function
	StabilityTags   []string `json:"stability_tags"`   // CORE, PUBLIC_API, RECURSIVE, SIDE_EFFECTS, FRAGILE
	DependencyCount int      `json:"dependency_count"` // Number of functions this depends on
	DependentCount  int      `json:"dependent_count"`  // Number of functions that depend on this
	ImpactRadius    int      `json:"impact_radius"`    // How many files could be affected by changes
	SafetyNotes     []string `json:"safety_notes"`     // Human-readable safety warnings
}

TreeNode represents a node in the function call hierarchy

type TreeOptions

type TreeOptions struct {
	MaxDepth       int    `json:"max_depth"`
	ShowLines      bool   `json:"show_lines"`
	Compact        bool   `json:"compact"`
	ExcludePattern string `json:"exclude_pattern"`
	AgentMode      bool   `json:"agent_mode"`
}

TreeOptions configures tree generation behavior

type TrigramType

type TrigramType uint8

TrigramType indicates whether a trigram is byte-based or rune-based

const (
	ByteTrigram TrigramType = iota
	RuneTrigram
)

type TypeParameter

type TypeParameter struct {
	Name       string `json:"name"`       // e.g., "T", "K", "V"
	Constraint string `json:"constraint"` // e.g., "any", "comparable", "io.Reader"
}

TypeParameter represents a generic type parameter (e.g., T in func Foo[T any]())

type UniversalSymbolNode

type UniversalSymbolNode struct {
	// Identity - Core identification information
	Identity SymbolIdentity `json:"identity"`

	// Relationships - All types of relationships this symbol has
	Relationships SymbolRelationships `json:"relationships"`

	// Visibility - Access control and scope information
	Visibility SymbolVisibility `json:"visibility"`

	// Usage - Usage statistics and metrics
	Usage SymbolUsage `json:"usage"`

	// Metadata - Additional contextual information
	Metadata SymbolMetadata `json:"metadata"`
}

UniversalSymbolNode represents a node in the Universal Symbol Graph This is the core node that extends beyond just function calls to include all symbol relationships

func (*UniversalSymbolNode) GetComplexityIndicator

func (usn *UniversalSymbolNode) GetComplexityIndicator() string

GetComplexityIndicator returns a simple complexity indicator based on relationships and metadata

func (*UniversalSymbolNode) GetNavigationSuggestions

func (usn *UniversalSymbolNode) GetNavigationSuggestions() []string

GetNavigationSuggestions returns suggested next actions for AI navigation

func (*UniversalSymbolNode) GetRelationshipCount

func (usn *UniversalSymbolNode) GetRelationshipCount() int

GetRelationshipCount returns the total number of relationships for this symbol

func (*UniversalSymbolNode) IsEditSafe

func (usn *UniversalSymbolNode) IsEditSafe() bool

IsEditSafe returns whether this symbol is safe for AI agents to edit

func (*UniversalSymbolNode) String

func (usn *UniversalSymbolNode) String() string

String returns a string representation of the UniversalSymbolNode

type UnresolvedCallInfo

type UnresolvedCallInfo struct {
	FunctionName string
	Qualifier    string // Package/module or receiver type
	IsMethod     bool
	Line         int
	Column       int
}

UnresolvedCallInfo tracks a function call that needs Phase 2 resolution

type UsageHotSpot

type UsageHotSpot struct {
	FileID     FileID  `json:"file_id"`     // File with high usage
	StartLine  int     `json:"start_line"`  // Start of hot spot region
	EndLine    int     `json:"end_line"`    // End of hot spot region
	UsageCount int     `json:"usage_count"` // Number of usages in region
	UsageType  string  `json:"usage_type"`  // Type of usage (calls, references, etc.)
	Intensity  float64 `json:"intensity"`   // Usage intensity score
}

UsageHotSpot represents a location with high symbol usage

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

ValidationError represents a validation error

func (*ValidationError) Error

func (e *ValidationError) Error() string

type VariableType

type VariableType uint8

VariableType represents different classifications of variables

const (
	VariableTypeGlobal    VariableType = iota // Package/global scope
	VariableTypeLocal                         // Function local scope
	VariableTypeParameter                     // Function parameter
	VariableTypeField                         // Class/struct field
	VariableTypeMember                        // Class member (method/property)
	VariableTypeConstant                      // Constant value
)

func (VariableType) String

func (vt VariableType) String() string

type ViolationType

type ViolationType uint8

ViolationType categorizes concerning access patterns

const (
	// ViolationWriteBeforeRead - write to target before reading from it
	ViolationWriteBeforeRead ViolationType = iota

	// ViolationReadAfterWrite - read from aggregate after write to part of it
	ViolationReadAfterWrite

	// ViolationInterleavedAccess - R-W-R or W-R-W pattern on same target
	ViolationInterleavedAccess

	// ViolationSelfInterference - function result depends on its own mutation
	ViolationSelfInterference

	// ViolationMutateParameter - writes to a function parameter
	ViolationMutateParameter

	// ViolationMutateReceiver - writes to method receiver
	ViolationMutateReceiver
)

func (ViolationType) String

func (v ViolationType) String() string

type ZeroAllocStringRef

type ZeroAllocStringRef struct {
	Data   []byte // Direct reference to the byte data (no allocation)
	FileID FileID // For safety and LRU tracking
	Offset uint32 // Offset within the data slice
	Length uint32 // Length of the string reference
	Hash   uint64 // Precomputed hash for fast equality
}

ZeroAllocStringRef is a zero-allocation string reference that operates on []byte data This eliminates the need for string conversion in most operations

func FromBytes

func FromBytes(data []byte) ZeroAllocStringRef

FromBytes creates a ZeroAllocStringRef from a byte slice

func FromString

func FromString(s string) ZeroAllocStringRef

FromString creates a ZeroAllocStringRef from a string Note: This allocates because we need to convert string to []byte Use sparingly - only when converting from external string sources

func FromStringRef

func FromStringRef(ref StringRef, data []byte) ZeroAllocStringRef

FromStringRef converts a regular StringRef to ZeroAllocStringRef This requires access to the FileContentStore to get the underlying data

func (ZeroAllocStringRef) Bytes

func (ref ZeroAllocStringRef) Bytes() []byte

Bytes returns the underlying byte slice without any allocation

func (ZeroAllocStringRef) Compare

func (ref ZeroAllocStringRef) Compare(other ZeroAllocStringRef) int

Compare performs lexical comparison with another ZeroAllocStringRef (zero allocation)

func (ZeroAllocStringRef) CompareString

func (ref ZeroAllocStringRef) CompareString(s string) int

CompareString performs lexical comparison with a string (zero allocation)

func (ZeroAllocStringRef) Contains

func (ref ZeroAllocStringRef) Contains(pattern string) bool

Contains checks if the reference contains the given pattern (zero allocation)

func (ZeroAllocStringRef) ContainsAny

func (ref ZeroAllocStringRef) ContainsAny(substrings ...string) bool

ContainsAny checks if the reference contains any of the given substrings (zero allocation)

func (ZeroAllocStringRef) ContainsBytes

func (ref ZeroAllocStringRef) ContainsBytes(pattern []byte) bool

ContainsBytes checks if the reference contains the given byte pattern (zero allocation)

func (ZeroAllocStringRef) ContainsFold

func (ref ZeroAllocStringRef) ContainsFold(pattern string) bool

ContainsFold performs case-insensitive contains check (zero allocation)

func (ZeroAllocStringRef) Count

func (ref ZeroAllocStringRef) Count(substring string) int

Count counts non-overlapping occurrences of the substring (zero allocation)

func (ZeroAllocStringRef) Equal

func (ref ZeroAllocStringRef) Equal(other ZeroAllocStringRef) bool

Equal performs zero-allocation equality check with another ZeroAllocStringRef

func (ZeroAllocStringRef) EqualFold

func (ref ZeroAllocStringRef) EqualFold(s string) bool

EqualFold performs case-insensitive equality check (zero allocation)

func (ZeroAllocStringRef) EqualString

func (ref ZeroAllocStringRef) EqualString(s string) bool

EqualString performs zero-allocation equality check with a string

func (ZeroAllocStringRef) Fields

func (ref ZeroAllocStringRef) Fields() []ZeroAllocStringRef

Fields splits the reference by whitespace (zero allocation)

func (ZeroAllocStringRef) GreaterThan

func (ref ZeroAllocStringRef) GreaterThan(other ZeroAllocStringRef) bool

GreaterThan checks if this reference is lexicographically greater than another

func (ZeroAllocStringRef) HasAnyPrefix

func (ref ZeroAllocStringRef) HasAnyPrefix(prefixes ...string) bool

HasAnyPrefix checks if the reference starts with any of the given prefixes (zero allocation)

func (ZeroAllocStringRef) HasAnySuffix

func (ref ZeroAllocStringRef) HasAnySuffix(suffixes ...string) bool

HasAnySuffix checks if the reference ends with any of the given suffixes (zero allocation)

func (ZeroAllocStringRef) HasPrefix

func (ref ZeroAllocStringRef) HasPrefix(prefix string) bool

HasPrefix checks if the reference starts with the given prefix (zero allocation)

func (ZeroAllocStringRef) HasPrefixFold

func (ref ZeroAllocStringRef) HasPrefixFold(prefix string) bool

HasPrefixFold performs case-insensitive prefix check (zero allocation)

func (ZeroAllocStringRef) HasSuffix

func (ref ZeroAllocStringRef) HasSuffix(suffix string) bool

HasSuffix checks if the reference ends with the given suffix (zero allocation)

func (ZeroAllocStringRef) HasSuffixFold

func (ref ZeroAllocStringRef) HasSuffixFold(suffix string) bool

HasSuffixFold performs case-insensitive suffix check (zero allocation)

func (ZeroAllocStringRef) Index

func (ref ZeroAllocStringRef) Index(substring string) int

Index finds the index of the first occurrence of the substring (zero allocation)

func (ZeroAllocStringRef) IsEmpty

func (ref ZeroAllocStringRef) IsEmpty() bool

IsEmpty returns true if this is an empty/invalid reference

func (ZeroAllocStringRef) IsEmptyString

func (ref ZeroAllocStringRef) IsEmptyString() bool

IsEmptyString checks if the reference represents an empty string (zero allocation)

func (ZeroAllocStringRef) IsValid

func (ref ZeroAllocStringRef) IsValid() bool

IsValid checks if the reference has valid data (zero allocation)

func (ZeroAllocStringRef) Join

Join concatenates this reference with another using a separator (zero allocation until final string conversion)

func (ZeroAllocStringRef) LastIndex

func (ref ZeroAllocStringRef) LastIndex(substring string) int

LastIndex finds the index of the last occurrence of the substring (zero allocation)

func (ZeroAllocStringRef) Len

func (ref ZeroAllocStringRef) Len() int

Len returns the length of the reference (zero allocation)

func (ZeroAllocStringRef) LessThan

func (ref ZeroAllocStringRef) LessThan(other ZeroAllocStringRef) bool

LessThan checks if this reference is lexicographically less than another

func (ZeroAllocStringRef) MarshalJSON

func (ref ZeroAllocStringRef) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for efficient JSON serialization

func (ZeroAllocStringRef) Slice

func (ref ZeroAllocStringRef) Slice(start, length uint32) ZeroAllocStringRef

Slice returns a substring from start with given length (zero allocation)

func (ZeroAllocStringRef) Split

func (ref ZeroAllocStringRef) Split(separator string) []ZeroAllocStringRef

Split splits the reference by the given separator (zero allocation for result elements)

func (ZeroAllocStringRef) SplitN

func (ref ZeroAllocStringRef) SplitN(separator string, n int) []ZeroAllocStringRef

SplitN splits the reference by the given separator, up to n parts (zero allocation)

func (ZeroAllocStringRef) String

func (ref ZeroAllocStringRef) String() string

String converts to string - ONLY use this when absolutely necessary (API output, logging) This is the ONLY allocation method in the entire interface

func (ZeroAllocStringRef) Substring

func (ref ZeroAllocStringRef) Substring(start, end int) ZeroAllocStringRef

Substring returns a substring from start to end (zero allocation)

func (ZeroAllocStringRef) ToLower

func (ref ZeroAllocStringRef) ToLower() ZeroAllocStringRef

ToLower creates a new ZeroAllocStringRef with all Unicode letters converted to lowercase Note: This DOES allocate a new []byte because Unicode case conversion requires it

func (ZeroAllocStringRef) ToStringRef

func (ref ZeroAllocStringRef) ToStringRef() StringRef

ToStringRef converts a ZeroAllocStringRef back to regular StringRef

func (ZeroAllocStringRef) ToUpper

func (ref ZeroAllocStringRef) ToUpper() ZeroAllocStringRef

ToUpper creates a new ZeroAllocStringRef with all Unicode letters converted to uppercase Note: This DOES allocate a new []byte because Unicode case conversion requires it

func (ZeroAllocStringRef) Trim

func (ref ZeroAllocStringRef) Trim(cutset string) ZeroAllocStringRef

Trim returns a new ZeroAllocStringRef with the given cutset removed from both ends

func (ZeroAllocStringRef) TrimLeft

func (ref ZeroAllocStringRef) TrimLeft(cutset string) ZeroAllocStringRef

TrimLeft returns a new ZeroAllocStringRef with leading cutset removed

func (ZeroAllocStringRef) TrimRight

func (ref ZeroAllocStringRef) TrimRight(cutset string) ZeroAllocStringRef

TrimRight returns a new ZeroAllocStringRef with trailing cutset removed

func (ZeroAllocStringRef) TrimSpace

func (ref ZeroAllocStringRef) TrimSpace() ZeroAllocStringRef

TrimSpace returns a new ZeroAllocStringRef with leading/trailing whitespace removed

type ZeroAllocStringRefSlice

type ZeroAllocStringRefSlice []ZeroAllocStringRef

ZeroAllocStringRefSlice provides helper methods for slices of ZeroAllocStringRef

func (ZeroAllocStringRefSlice) Filter

func (zass ZeroAllocStringRefSlice) Filter(patterns ...string) ZeroAllocStringRefSlice

Filter returns references that contain any of the given patterns (zero allocation)

func (ZeroAllocStringRefSlice) FilterByPrefix

func (zass ZeroAllocStringRefSlice) FilterByPrefix(prefixes ...string) ZeroAllocStringRefSlice

FilterByPrefix returns references that start with any of the given prefixes (zero allocation)

func (ZeroAllocStringRefSlice) FilterBySuffix

func (zass ZeroAllocStringRefSlice) FilterBySuffix(suffixes ...string) ZeroAllocStringRefSlice

FilterBySuffix returns references that end with any of the given suffixes (zero allocation)

func (ZeroAllocStringRefSlice) Join

func (zass ZeroAllocStringRefSlice) Join(separator string) ZeroAllocStringRef

Join concatenates references with a separator (zero allocation until final string conversion)

func (ZeroAllocStringRefSlice) Sort

func (zass ZeroAllocStringRefSlice) Sort()

Sort sorts the references lexicographically (zero allocation)

func (ZeroAllocStringRefSlice) Strings

func (zass ZeroAllocStringRefSlice) Strings() []string

Strings converts all references to strings (allocates - use sparingly)

func (ZeroAllocStringRefSlice) Unique

Unique removes duplicate references (zero allocation, preserves order)

Jump to

Keyboard shortcuts

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