Documentation
¶
Overview ¶
Package code defines domain entities, ports, and analytics for static code graphs, symbol indexes, and architectural insights.
Package code provides AST extraction, code graph management, and file watching capabilities.
Index ¶
- Constants
- func BuildTestRunCommands(testFiles []string, testFuncs []ImpactedTestFunction) []string
- func GenerateRepoMap(graph *CodeGraph, maxTokens int) string
- func IsTestFilePath(path string) bool
- type AnalyticsReport
- type CodeBlastRadius
- type CodeGraph
- type CommunityCohesion
- type FileWatcher
- func (w *FileWatcher) ScanDiff() (changed []string, deleted []string)
- func (w *FileWatcher) ScanOnce() []string
- func (w *FileWatcher) Watch(ctx context.Context, onFileChanged func(path string)) error
- func (w *FileWatcher) WatchWithEvents(ctx context.Context, onFileChanged func(path string), ...) error
- type GodNode
- type ImpactedTestFunction
- type ImportCycle
- type Parameter
- type Relation
- type Service
- type Store
- type Symbol
- type SymbolFilter
- type SymbolSearchQuery
- type SymbolSearchResult
- type TestImpactResult
- type WatcherConfig
Constants ¶
const ( ConfidenceExtracted = 1.0 // Stated directly in AST (e.g. import, direct call) ConfidenceInferred = 0.8 // Deduced (e.g. 2-pass member call resolution) ConfidenceAmbiguous = 0.5 // Plausible but uncertain )
Confidence levels for code relationships, matching Graphify standards.
const ( RelationCalls = "calls" RelationImports = "imports" RelationImplements = "implements" RelationDefines = "defines" RelationUses = "uses" RelationContains = "contains" RelationExtends = "extends" RelationInstantiates = "instantiates" RelationUsesType = "uses_type" RelationReferences = "references" RelationExports = "exports" )
Standard relation types.
const ( KindFunc = "func" KindMethod = "method" KindStruct = "struct" KindInterface = "interface" KindClass = "class" KindModule = "module" KindPackage = "package" KindType = "type" KindTable = "table" KindEnum = "enum" KindVariable = "variable" KindConstant = "constant" )
Standard symbol kinds.
const ( VisibilityPublic = "public" VisibilityPrivate = "private" VisibilityProtected = "protected" VisibilityInternal = "internal" )
Standard visibility levels.
Variables ¶
This section is empty.
Functions ¶
func BuildTestRunCommands ¶ added in v2.3.8
func BuildTestRunCommands(testFiles []string, testFuncs []ImpactedTestFunction) []string
BuildTestRunCommands generates actionable, minimal test commands per language.
func GenerateRepoMap ¶ added in v2.3.8
GenerateRepoMap creates a compact, token-budgeted structural map of the repository using high-centrality AST symbols, tailored for LLM system prompts (inspired by Aider).
func IsTestFilePath ¶ added in v2.3.8
IsTestFilePath checks if a file path is a known test file convention across languages.
Types ¶
type AnalyticsReport ¶
type AnalyticsReport struct {
Project string `json:"project"`
TotalSymbols int `json:"total_symbols"`
TotalRelations int `json:"total_relations"`
TotalFiles int `json:"total_files"`
GodNodes []GodNode `json:"god_nodes"`
ImportCycles []ImportCycle `json:"import_cycles"`
Communities []CommunityCohesion `json:"communities"`
AverageCohesion float64 `json:"average_cohesion"`
GeneratedAt time.Time `json:"generated_at"`
}
AnalyticsReport provides architectural diagnostic metrics.
func ComputeAnalytics ¶
func ComputeAnalytics(graph *CodeGraph) *AnalyticsReport
ComputeAnalytics runs structural graph diagnostics on a project's CodeGraph.
type CodeBlastRadius ¶ added in v2.3.5
type CodeBlastRadius struct {
Target string `json:"target"`
TargetKind string `json:"target_kind"` // "symbol", "file", "git_diff"
RootNode string `json:"root_node,omitempty"`
ChangedFiles []string `json:"changed_files,omitempty"`
DirectCallers []string `json:"direct_callers"`
ImpactedFiles []string `json:"impacted_files"`
TotalImpacted []string `json:"total_impacted"`
BlastRadiusPct float64 `json:"blast_radius_pct"`
AffectedCycles []ImportCycle `json:"affected_cycles,omitempty"`
}
CodeBlastRadius represents the impacted symbols, callers, and files when a code entity changes.
func CalculateCodeBlastRadius ¶ added in v2.3.5
func CalculateCodeBlastRadius(graph *CodeGraph, target string, maxHops int) *CodeBlastRadius
CalculateCodeBlastRadius computes callers and impacted files when a symbol or file is modified.
func CalculateDiffBlastRadius ¶ added in v2.3.5
func CalculateDiffBlastRadius(graph *CodeGraph, modifiedFiles []string, maxHops int) *CodeBlastRadius
CalculateDiffBlastRadius computes the aggregate impact of a list of changed files.
type CodeGraph ¶
type CodeGraph struct {
Project string `json:"project"`
Symbols []Symbol `json:"symbols"`
Relations []Relation `json:"relations"`
}
CodeGraph encapsulates the complete structural graph for a project or component.
type CommunityCohesion ¶
type CommunityCohesion struct {
CommunityID int `json:"community_id"`
Label string `json:"label"`
Members []string `json:"members"`
InternalEdges int `json:"internal_edges"`
PossibleEdges int `json:"possible_edges"`
CohesionScore float64 `json:"cohesion_score"` // 2*E / (N*(N-1))
}
CommunityCohesion measures the internal coupling density of a module or cluster.
type FileWatcher ¶
type FileWatcher struct {
// contains filtered or unexported fields
}
FileWatcher monitors code files and triggers incremental AST indexing upon changes.
func NewFileWatcher ¶
func NewFileWatcher(cfg WatcherConfig) *FileWatcher
NewFileWatcher creates a new Zero-CGO background file watcher.
func (*FileWatcher) ScanDiff ¶ added in v2.3.10
func (w *FileWatcher) ScanDiff() (changed []string, deleted []string)
ScanDiff performs a single scan of the directory tree, returning modified/added files and deleted files.
func (*FileWatcher) ScanOnce ¶
func (w *FileWatcher) ScanOnce() []string
ScanOnce performs a single scan of the directory tree, returning modified or added files.
func (*FileWatcher) Watch ¶
func (w *FileWatcher) Watch(ctx context.Context, onFileChanged func(path string)) error
Watch runs the polling loop until the context is canceled, calling onFileChanged on updates.
func (*FileWatcher) WatchWithEvents ¶ added in v2.3.10
func (w *FileWatcher) WatchWithEvents(ctx context.Context, onFileChanged func(path string), onFileDeleted func(path string)) error
WatchWithEvents runs the polling loop until the context is canceled, calling onFileChanged on updates and onFileDeleted when monitored files are removed.
type GodNode ¶
type GodNode struct {
ID string `json:"id"`
Name string `json:"name"`
Kind string `json:"kind"`
FilePath string `json:"file_path"`
Degree int `json:"degree"`
InDegree int `json:"in_degree"`
OutDegree int `json:"out_degree"`
Score float64 `json:"score"`
}
GodNode identifies high-centrality architectural hubs.
type ImpactedTestFunction ¶ added in v2.3.8
type ImpactedTestFunction struct {
ID string `json:"id"`
Name string `json:"name"`
FilePath string `json:"file_path"`
LineNumber int `json:"line_number"`
Hops int `json:"hops"` // 1 = direct caller, 2+ = transitive
Direct bool `json:"direct"` // true if directly calling target
}
ImpactedTestFunction represents a test function identified in the code graph.
type ImportCycle ¶
type ImportCycle struct {
ID string `json:"id"`
Files []string `json:"files"`
CyclePath []string `json:"cycle_path"`
}
ImportCycle represents a circular dependency loop between files or modules.
type Relation ¶
type Relation struct {
ID int64 `json:"id,omitempty"`
Project string `json:"project"`
SourceID string `json:"source_id"` // Caller / Importer symbol ID
TargetID string `json:"target_id"` // Callee / Imported symbol ID
Relation string `json:"relation"` // "calls", "imports", "implements", "defines", "uses", "contains", "extends", "instantiates", "uses_type", "references", "exports"
Confidence float64 `json:"confidence"` // 1.0 = EXTRACTED, 0.85 = INFERRED, 0.5 = AMBIGUOUS
Reasoning string `json:"reasoning,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
Relation represents a directed architectural edge between two code symbols.
type Service ¶
type Service interface {
IngestPath(ctx context.Context, rootPath string, project string, maxFiles int) (*AnalyticsReport, error)
GetGraph(ctx context.Context, project string) (*CodeGraph, error)
ListSymbols(ctx context.Context, filter SymbolFilter) ([]Symbol, error)
Analyze(ctx context.Context, project string) (*AnalyticsReport, error)
}
Service coordinates code AST ingestion, querying, and analytics.
type Store ¶
type Store interface {
SaveSymbols(ctx context.Context, symbols []Symbol) error
GetSymbolByID(ctx context.Context, id string) (*Symbol, error)
ListSymbols(ctx context.Context, filter SymbolFilter) ([]Symbol, error)
CountSymbols(ctx context.Context, filter SymbolFilter) (int, error)
DeleteSymbolsByProject(ctx context.Context, project string) error
DeleteSymbolsByFile(ctx context.Context, project, filePath string) error
SaveRelations(ctx context.Context, relations []Relation) error
GetGraph(ctx context.Context, project string) (*CodeGraph, error)
ListRelationsBySymbol(ctx context.Context, symbolID string) ([]Relation, error)
DeleteRelationsByProject(ctx context.Context, project string) error
DeleteRelationsByFile(ctx context.Context, project, filePath string) error
}
Store defines storage operations for code symbols and relations.
type Symbol ¶
type Symbol struct {
ID string `json:"id"` // Deterministic unique ID (e.g. "func:domain.NewService")
Project string `json:"project"` // Project namespace
FilePath string `json:"file_path"` // Relative file path (e.g. "internal/domain/service.go")
LineNumber int `json:"line_number"` // 1-based start line
EndLine int `json:"end_line,omitempty"` // 1-based end line
StartColumn int `json:"start_col,omitempty"` // Start column offset
EndColumn int `json:"end_col,omitempty"` // End column offset
Kind string `json:"kind"` // "func", "method", "struct", "class", "interface", "table", "module", "enum"
Name string `json:"name"` // Symbol identifier (e.g. "CalculateBlastRadius")
PackageName string `json:"package_name"` // Package or namespace (e.g. "domain")
ParentID string `json:"parent_id,omitempty"` // Hierarchical parent ID (e.g. class ID for methods, struct ID for fields)
Visibility string `json:"visibility,omitempty"` // "public", "private", "protected", "internal"
Signature string `json:"signature,omitempty"` // Full declaration signature
DocSummary string `json:"doc_summary,omitempty"` // GoDoc / JSDoc / Docstring description
Parameters []Parameter `json:"parameters,omitempty"` // Ordered list of typed parameters
ReturnType string `json:"return_type,omitempty"` // Explicit return type
Complexity int `json:"complexity,omitempty"` // Cyclomatic complexity score (branches + 1)
Metadata map[string]any `json:"metadata,omitempty"` // Language-specific extras (async, static, decorators, fields)
FileHash string `json:"file_hash,omitempty"` // SHA-256 of file for incremental scanning
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
Symbol represents an extracted code entity with rich semantic metadata.
type SymbolFilter ¶
type SymbolFilter struct {
Project string
FilePath string
Kind string
PackageName string
Query string
Limit int
Offset int
}
SymbolFilter specifies criteria for querying symbols.
type SymbolSearchQuery ¶ added in v2.3.8
type SymbolSearchQuery struct {
Query string `json:"query"`
IsRegex bool `json:"is_regex"`
Kind string `json:"kind,omitempty"`
FilePath string `json:"file_path,omitempty"`
Limit int `json:"limit,omitempty"`
}
SymbolSearchQuery specifies parameters for searching code symbols.
type SymbolSearchResult ¶ added in v2.3.8
type SymbolSearchResult struct {
Symbol Symbol `json:"symbol"`
Score float64 `json:"score"`
MatchField string `json:"match_field"` // "name_exact", "name_prefix", "name_contains", "signature", "doc"
}
SymbolSearchResult represents a matched symbol with relevance score.
func SearchSymbols ¶ added in v2.3.8
func SearchSymbols(graph *CodeGraph, query SymbolSearchQuery) []SymbolSearchResult
SearchSymbols queries symbols in the given CodeGraph by substring or regular expression.
type TestImpactResult ¶ added in v2.3.8
type TestImpactResult struct {
Target string `json:"target"`
TargetKind string `json:"target_kind"` // "symbol", "file", "git_diff"
ImpactedTestFiles []string `json:"impacted_test_files"`
ImpactedTestFuncs []ImpactedTestFunction `json:"impacted_test_functions"`
RecommendedCommands []string `json:"recommended_commands"`
}
TestImpactResult summarizes test impact analysis.
func FindImpactedTests ¶ added in v2.3.8
func FindImpactedTests(graph *CodeGraph, target string, maxHops int) *TestImpactResult
FindImpactedTests traverses the reverse dependency graph to identify all test suites and functions that exercise the target symbol, file, or git diff.
type WatcherConfig ¶
type WatcherConfig struct {
Directory string
Project string
PollInterval time.Duration
DebounceDuration time.Duration
Extensions []string
IgnoreDirs []string
}
WatcherConfig configures the background file watcher.
func DefaultWatcherConfig ¶
func DefaultWatcherConfig(dir, project string) WatcherConfig
DefaultWatcherConfig returns standard file watcher settings for Cortex.