Documentation
¶
Overview ¶
Package reason provides tools for reasoning about code changes.
This package implements the "think before act" principle by providing analysis tools that help understand the impact of proposed changes:
- Breaking change detection (will callers break?)
- Change simulation (what needs to be updated?)
- Type compatibility checking (can this type be used here?)
- Test coverage analysis (what tests cover this?)
- Side effect detection (what external effects does this have?)
- Refactoring suggestions (how can this code be improved?)
All tools in this package are READ-ONLY and do not modify code. They analyze the existing codebase and proposed changes to provide actionable insights before changes are made.
Index ¶
- Variables
- func CalibrateConfidence(base float64, adjustments ...ConfidenceAdjustment) float64
- func SummarySideEffects(analysis *SideEffectAnalysis) map[SideEffectType][]SideEffect
- type BreakingAnalysis
- type BreakingChange
- type BreakingChangeAnalyzer
- func (a *BreakingChangeAnalyzer) AnalyzeBreaking(ctx context.Context, targetID string, proposedSig string) (*BreakingAnalysis, error)
- func (a *BreakingChangeAnalyzer) AnalyzeBreakingBatch(ctx context.Context, changes map[string]string) (map[string]*BreakingAnalysis, error)
- func (a *BreakingChangeAnalyzer) SetCRS(recorder CRSRecorder)
- type BreakingChangeType
- type CRSRecorder
- type CallerUpdate
- type ChangeSimulation
- type ChangeSimulator
- func (s *ChangeSimulator) SetCRS(recorder CRSRecorder)
- func (s *ChangeSimulator) SimulateChange(ctx context.Context, targetID string, newSignature string) (*ChangeSimulation, error)
- func (s *ChangeSimulator) SimulateMultipleChanges(ctx context.Context, changes map[string]string) (map[string]*ChangeSimulation, error)
- type ChangeValidation
- type ChangeValidator
- type CodeMetrics
- type ConfidenceAdjustment
- type ConfidenceCalibration
- type ConfidenceLevel
- type CoverageReport
- type FunctionPattern
- type ImportReference
- type InterfaceSatisfaction
- type MethodMatch
- type NopCRSRecorder
- type ParameterInfo
- type ParsedSignature
- type RefactorSuggester
- func (r *RefactorSuggester) CalculateMetricsOnly(ctx context.Context, targetID string) (*CodeMetrics, error)
- func (r *RefactorSuggester) GetHealthDistribution(ctx context.Context) (map[string]int, error)
- func (r *RefactorSuggester) GetUnhealthyFunctions(ctx context.Context, threshold int) ([]RefactorSuggestions, error)
- func (r *RefactorSuggester) SetCRS(recorder CRSRecorder)
- func (r *RefactorSuggester) SuggestRefactor(ctx context.Context, targetID string) (*RefactorSuggestions, error)
- func (r *RefactorSuggester) SuggestRefactorBatch(ctx context.Context, targetIDs []string) (map[string]*RefactorSuggestions, error)
- type RefactorSuggestions
- type RefactorType
- type RiskLevel
- type Severity
- type SideEffect
- type SideEffectAnalysis
- type SideEffectAnalyzer
- func (a *SideEffectAnalyzer) FindSideEffects(ctx context.Context, targetID string) (*SideEffectAnalysis, error)
- func (a *SideEffectAnalyzer) FindSideEffectsBatch(ctx context.Context, targetIDs []string) (map[string]*SideEffectAnalysis, error)
- func (a *SideEffectAnalyzer) GetPureFunctions(ctx context.Context) ([]string, error)
- type SideEffectPatterns
- type SideEffectType
- type SignatureParser
- type Suggestion
- type TestCoverage
- type TestCoverageFinder
- func (f *TestCoverageFinder) FindTestCoverage(ctx context.Context, targetID string) (*TestCoverage, error)
- func (f *TestCoverageFinder) FindTestsForFile(ctx context.Context, filePath string) ([]TestInfo, error)
- func (f *TestCoverageFinder) FindUncoveredSymbols(ctx context.Context, kinds []ast.SymbolKind) ([]string, error)
- func (f *TestCoverageFinder) GenerateCoverageReport(ctx context.Context) (*CoverageReport, error)
- func (f *TestCoverageFinder) SetCRS(recorder CRSRecorder)
- type TestInfo
- type TypeCompatibility
- type TypeCompatibilityChecker
- type TypeInfo
- type TypeMismatch
- type TypeParamInfo
- type TypeReference
- type ValidationError
- type ValidationWarning
Constants ¶
This section is empty.
Variables ¶
var ( // AdjustmentInTestFile lowers confidence for symbols in test files. // Test files often have unusual patterns that don't represent production code. AdjustmentInTestFile = ConfidenceAdjustment{ Reason: "in test file", Multiplier: 0.5, } // AdjustmentHasNosecComment lowers confidence when nosec/nolint comment nearby. // The developer has explicitly acknowledged the pattern. AdjustmentHasNosecComment = ConfidenceAdjustment{ Reason: "nosec/nolint comment nearby", Multiplier: 0.2, } // AdjustmentHighComplexity increases confidence for high-complexity code. // Complex code is more likely to have issues. AdjustmentHighComplexity = ConfidenceAdjustment{ Reason: "high cyclomatic complexity", Multiplier: 1.3, } // AdjustmentLowComplexity decreases confidence for simple code. // Simple code is less likely to have issues. AdjustmentLowComplexity = ConfidenceAdjustment{ Reason: "low cyclomatic complexity", Multiplier: 0.7, } // AdjustmentManyCallers increases confidence when many callers exist. // More callers means higher impact if there's an issue. AdjustmentManyCallers = ConfidenceAdjustment{ Reason: "many callers (>10)", Multiplier: 1.2, } // AdjustmentFewCallers decreases confidence when few callers exist. // Fewer callers means lower impact. AdjustmentFewCallers = ConfidenceAdjustment{ Reason: "few callers (<3)", Multiplier: 0.8, } // AdjustmentExportedSymbol increases confidence for exported symbols. // Exported symbols have wider impact potential. AdjustmentExportedSymbol = ConfidenceAdjustment{ Reason: "exported symbol", Multiplier: 1.1, } // AdjustmentUnexportedSymbol decreases confidence for unexported symbols. // Unexported symbols have limited scope. AdjustmentUnexportedSymbol = ConfidenceAdjustment{ Reason: "unexported symbol", Multiplier: 0.9, } // AdjustmentInterfaceMethod increases confidence for interface methods. // Interface methods have contract implications. AdjustmentInterfaceMethod = ConfidenceAdjustment{ Reason: "interface method", Multiplier: 1.3, } // AdjustmentStaticAnalysisOnly reminds that this is static analysis. // Runtime behavior may differ. AdjustmentStaticAnalysisOnly = ConfidenceAdjustment{ Reason: "static analysis only", Multiplier: 0.95, } )
Common confidence adjustments for reuse across analyzers.
var ( // ErrInvalidInput is returned when input parameters are invalid. ErrInvalidInput = errors.New("invalid input") // ErrSymbolNotFound is returned when a target symbol cannot be found. ErrSymbolNotFound = errors.New("symbol not found") // ErrContextCanceled is returned when the context is canceled. ErrContextCanceled = errors.New("context canceled") // ErrGraphNotReady is returned when the graph is not frozen. ErrGraphNotReady = errors.New("graph not ready: must be frozen") // ErrUnsupportedLanguage is returned when the language is not supported. ErrUnsupportedLanguage = errors.New("unsupported language") // ErrParseFailure is returned when signature parsing fails. ErrParseFailure = errors.New("failed to parse signature") // ErrTypeNotFound is returned when a type cannot be found. ErrTypeNotFound = errors.New("type not found") )
Common errors for the reason package.
var GoSideEffectPatterns = &SideEffectPatterns{ Language: "go", FileIO: []FunctionPattern{ { Package: "os", Functions: []string{"Open", "OpenFile", "Create", "Remove", "RemoveAll", "Mkdir", "MkdirAll", "ReadFile", "WriteFile", "Rename", "Chmod", "Chown", "Truncate"}, EffectType: SideEffectTypeFileIO, Reversible: false, Idempotent: false, Description: "File system operations", }, { Package: "io", Functions: []string{"Copy", "CopyN", "ReadAll", "WriteString"}, EffectType: SideEffectTypeFileIO, Reversible: false, Idempotent: false, Description: "I/O copy operations", }, { Package: "io/ioutil", Functions: []string{"ReadFile", "WriteFile", "ReadAll", "ReadDir", "TempDir", "TempFile"}, EffectType: SideEffectTypeFileIO, Reversible: false, Idempotent: false, Description: "Legacy I/O utilities (deprecated but still used)", }, { Package: "bufio", Functions: []string{"Write", "WriteString", "WriteByte", "WriteRune", "Flush"}, EffectType: SideEffectTypeFileIO, Reversible: false, Idempotent: false, Description: "Buffered I/O write operations", }, }, Network: []FunctionPattern{ { Package: "net/http", Functions: []string{"Get", "Post", "PostForm", "Head", "Do", "NewRequest"}, EffectType: SideEffectTypeNetwork, Reversible: false, Idempotent: false, Description: "HTTP client requests", }, { Package: "net", Functions: []string{"Dial", "DialTCP", "DialUDP", "DialIP", "DialUnix", "Listen", "ListenTCP", "ListenUDP", "ListenUnix"}, EffectType: SideEffectTypeNetwork, Reversible: true, Idempotent: false, Description: "Network connections and listeners", }, { Package: "net/rpc", Functions: []string{"Dial", "DialHTTP", "Call"}, EffectType: SideEffectTypeNetwork, Reversible: false, Idempotent: false, Description: "RPC client operations", }, }, Database: []FunctionPattern{ { Package: "database/sql", Functions: []string{"Query", "QueryRow", "QueryContext", "QueryRowContext", "Exec", "ExecContext", "Prepare", "PrepareContext", "Begin", "BeginTx"}, EffectType: SideEffectTypeDatabase, Reversible: false, Idempotent: false, Description: "SQL database operations", }, { Package: "gorm.io/gorm", Functions: []string{"Create", "Save", "Delete", "Update", "Updates", "Exec", "Raw"}, EffectType: SideEffectTypeDatabase, Reversible: false, Idempotent: false, Description: "GORM ORM operations", }, }, Logging: []FunctionPattern{ { Package: "log", Functions: []string{"Print", "Printf", "Println", "Fatal", "Fatalf", "Fatalln", "Panic", "Panicf", "Panicln", "Output"}, EffectType: SideEffectTypeLogging, Reversible: false, Idempotent: true, Description: "Standard logging", }, { Package: "log/slog", Functions: []string{"Info", "InfoContext", "Warn", "WarnContext", "Error", "ErrorContext", "Debug", "DebugContext", "Log", "LogAttrs"}, EffectType: SideEffectTypeLogging, Reversible: false, Idempotent: true, Description: "Structured logging", }, { Package: "fmt", Functions: []string{"Print", "Printf", "Println", "Fprint", "Fprintf", "Fprintln"}, EffectType: SideEffectTypeLogging, Reversible: false, Idempotent: true, Description: "Formatted output (when writing to stdout/stderr)", }, }, GlobalState: []FunctionPattern{ { Package: "sync", Functions: []string{"Lock", "Unlock", "RLock", "RUnlock", "Wait", "Signal", "Broadcast", "Store", "Swap", "CompareAndSwap"}, EffectType: SideEffectTypeGlobalState, Reversible: true, Idempotent: false, Description: "Synchronization primitives", }, { Package: "sync/atomic", Functions: []string{"AddInt32", "AddInt64", "AddUint32", "AddUint64", "StoreInt32", "StoreInt64", "StorePointer", "SwapInt32", "SwapInt64", "CompareAndSwapInt32", "CompareAndSwapInt64"}, EffectType: SideEffectTypeGlobalState, Reversible: false, Idempotent: false, Description: "Atomic operations on shared memory", }, }, Process: []FunctionPattern{ { Package: "os/exec", Functions: []string{"Command", "CommandContext", "Run", "Start", "Output", "CombinedOutput"}, EffectType: SideEffectTypeProcess, Reversible: false, Idempotent: false, Description: "External command execution", }, { Package: "os", Functions: []string{"Exit", "Getpid", "Kill"}, EffectType: SideEffectTypeProcess, Reversible: false, Idempotent: false, Description: "Process control", }, { Package: "syscall", Functions: []string{"Exec", "ForkExec", "Kill", "Syscall"}, EffectType: SideEffectTypeProcess, Reversible: false, Idempotent: false, Description: "Low-level system calls", }, }, Environment: []FunctionPattern{ { Package: "os", Functions: []string{"Setenv", "Unsetenv", "Clearenv", "Chdir"}, EffectType: SideEffectTypeEnvironment, Reversible: true, Idempotent: false, Description: "Environment and working directory modifications", }, }, }
GoSideEffectPatterns defines side effect patterns for Go.
var PythonSideEffectPatterns = &SideEffectPatterns{ Language: "python", FileIO: []FunctionPattern{ { Module: "builtins", Functions: []string{"open", "print"}, EffectType: SideEffectTypeFileIO, Reversible: false, Idempotent: false, Description: "Built-in file operations", }, { Module: "os", Functions: []string{"remove", "unlink", "mkdir", "makedirs", "rmdir", "removedirs", "rename", "replace", "chmod", "chown", "truncate"}, EffectType: SideEffectTypeFileIO, Reversible: false, Idempotent: false, Description: "OS-level file operations", }, { Module: "shutil", Functions: []string{"copy", "copy2", "copytree", "move", "rmtree", "make_archive"}, EffectType: SideEffectTypeFileIO, Reversible: false, Idempotent: false, Description: "High-level file operations", }, { Module: "pathlib", Functions: []string{"write_text", "write_bytes", "unlink", "rmdir", "mkdir", "touch", "rename", "replace"}, EffectType: SideEffectTypeFileIO, Reversible: false, Idempotent: false, Description: "Path object file operations", }, }, Network: []FunctionPattern{ { Module: "requests", Functions: []string{"get", "post", "put", "delete", "patch", "head", "options", "request"}, EffectType: SideEffectTypeNetwork, Reversible: false, Idempotent: false, Description: "HTTP client requests", }, { Module: "urllib.request", Functions: []string{"urlopen", "urlretrieve"}, EffectType: SideEffectTypeNetwork, Reversible: false, Idempotent: false, Description: "URL operations", }, { Module: "httpx", Functions: []string{"get", "post", "put", "delete", "patch", "head", "options", "request"}, EffectType: SideEffectTypeNetwork, Reversible: false, Idempotent: false, Description: "Async HTTP client requests", }, { Module: "aiohttp", Functions: []string{"request", "get", "post", "put", "delete", "patch"}, EffectType: SideEffectTypeNetwork, Reversible: false, Idempotent: false, Description: "Async HTTP operations", }, { Module: "socket", Functions: []string{"connect", "bind", "listen", "accept", "send", "sendall", "recv"}, EffectType: SideEffectTypeNetwork, Reversible: true, Idempotent: false, Description: "Low-level socket operations", }, }, Database: []FunctionPattern{ { Module: "sqlite3", Functions: []string{"execute", "executemany", "executescript", "commit", "rollback"}, EffectType: SideEffectTypeDatabase, Reversible: false, Idempotent: false, Description: "SQLite database operations", }, { Module: "sqlalchemy", Functions: []string{"execute", "commit", "rollback", "flush", "add", "delete", "merge"}, EffectType: SideEffectTypeDatabase, Reversible: false, Idempotent: false, Description: "SQLAlchemy ORM operations", }, { Module: "psycopg2", Functions: []string{"execute", "executemany", "commit", "rollback"}, EffectType: SideEffectTypeDatabase, Reversible: false, Idempotent: false, Description: "PostgreSQL operations", }, { Module: "pymongo", Functions: []string{"insert_one", "insert_many", "update_one", "update_many", "delete_one", "delete_many", "replace_one"}, EffectType: SideEffectTypeDatabase, Reversible: false, Idempotent: false, Description: "MongoDB operations", }, { Module: "redis", Functions: []string{"set", "get", "delete", "hset", "hget", "lpush", "rpush", "publish"}, EffectType: SideEffectTypeDatabase, Reversible: false, Idempotent: false, Description: "Redis operations", }, }, Logging: []FunctionPattern{ { Module: "logging", Functions: []string{"info", "warning", "error", "critical", "debug", "exception", "log"}, EffectType: SideEffectTypeLogging, Reversible: false, Idempotent: true, Description: "Python logging", }, }, Process: []FunctionPattern{ { Module: "subprocess", Functions: []string{"run", "call", "check_call", "check_output", "Popen"}, EffectType: SideEffectTypeProcess, Reversible: false, Idempotent: false, Description: "Subprocess execution", }, { Module: "os", Functions: []string{"system", "popen", "execl", "execle", "execlp", "execv", "execve", "execvp", "spawnl", "spawnle", "kill", "_exit"}, EffectType: SideEffectTypeProcess, Reversible: false, Idempotent: false, Description: "OS-level process operations", }, { Module: "sys", Functions: []string{"exit"}, EffectType: SideEffectTypeProcess, Reversible: false, Idempotent: false, Description: "System exit", }, }, Environment: []FunctionPattern{ { Module: "os", Functions: []string{"putenv", "unsetenv", "chdir"}, EffectType: SideEffectTypeEnvironment, Reversible: true, Idempotent: false, Description: "Environment modifications", }, }, }
PythonSideEffectPatterns defines side effect patterns for Python.
var TypeScriptSideEffectPatterns = &SideEffectPatterns{ Language: "typescript", FileIO: []FunctionPattern{ { Module: "fs", Functions: []string{"readFile", "readFileSync", "writeFile", "writeFileSync", "appendFile", "appendFileSync", "unlink", "unlinkSync", "mkdir", "mkdirSync", "rmdir", "rmdirSync", "rename", "renameSync", "copyFile", "copyFileSync", "truncate", "truncateSync"}, EffectType: SideEffectTypeFileIO, Reversible: false, Idempotent: false, Description: "Node.js file system operations", }, { Module: "fs/promises", Functions: []string{"readFile", "writeFile", "appendFile", "unlink", "mkdir", "rmdir", "rename", "copyFile", "truncate", "rm"}, EffectType: SideEffectTypeFileIO, Reversible: false, Idempotent: false, Description: "Promise-based file system operations", }, }, Network: []FunctionPattern{ { Module: "", Functions: []string{"fetch"}, EffectType: SideEffectTypeNetwork, Reversible: false, Idempotent: false, Description: "Fetch API (global)", }, { Module: "axios", Functions: []string{"get", "post", "put", "delete", "patch", "head", "options", "request"}, EffectType: SideEffectTypeNetwork, Reversible: false, Idempotent: false, Description: "Axios HTTP client", }, { Module: "http", Functions: []string{"request", "get"}, EffectType: SideEffectTypeNetwork, Reversible: false, Idempotent: false, Description: "Node.js HTTP module", }, { Module: "https", Functions: []string{"request", "get"}, EffectType: SideEffectTypeNetwork, Reversible: false, Idempotent: false, Description: "Node.js HTTPS module", }, { Module: "node-fetch", Functions: []string{"default"}, EffectType: SideEffectTypeNetwork, Reversible: false, Idempotent: false, Description: "Node fetch polyfill", }, }, Database: []FunctionPattern{ { Module: "prisma", Functions: []string{"create", "createMany", "update", "updateMany", "upsert", "delete", "deleteMany"}, EffectType: SideEffectTypeDatabase, Reversible: false, Idempotent: false, Description: "Prisma ORM operations", }, { Module: "mongoose", Functions: []string{"save", "remove", "updateOne", "updateMany", "deleteOne", "deleteMany", "insertMany", "create"}, EffectType: SideEffectTypeDatabase, Reversible: false, Idempotent: false, Description: "Mongoose MongoDB operations", }, { Module: "typeorm", Functions: []string{"save", "remove", "insert", "update", "delete", "query"}, EffectType: SideEffectTypeDatabase, Reversible: false, Idempotent: false, Description: "TypeORM operations", }, { Module: "pg", Functions: []string{"query"}, EffectType: SideEffectTypeDatabase, Reversible: false, Idempotent: false, Description: "PostgreSQL client operations", }, { Module: "mysql2", Functions: []string{"query", "execute"}, EffectType: SideEffectTypeDatabase, Reversible: false, Idempotent: false, Description: "MySQL client operations", }, }, Logging: []FunctionPattern{ { Module: "console", Functions: []string{"log", "info", "warn", "error", "debug", "trace"}, EffectType: SideEffectTypeLogging, Reversible: false, Idempotent: true, Description: "Console logging", }, { Module: "winston", Functions: []string{"info", "warn", "error", "debug", "verbose", "silly", "log"}, EffectType: SideEffectTypeLogging, Reversible: false, Idempotent: true, Description: "Winston logger", }, { Module: "pino", Functions: []string{"info", "warn", "error", "debug", "trace", "fatal"}, EffectType: SideEffectTypeLogging, Reversible: false, Idempotent: true, Description: "Pino logger", }, }, Process: []FunctionPattern{ { Module: "child_process", Functions: []string{"exec", "execSync", "execFile", "execFileSync", "spawn", "spawnSync", "fork"}, EffectType: SideEffectTypeProcess, Reversible: false, Idempotent: false, Description: "Child process execution", }, { Module: "process", Functions: []string{"exit", "kill", "abort"}, EffectType: SideEffectTypeProcess, Reversible: false, Idempotent: false, Description: "Process control", }, }, Environment: []FunctionPattern{ { Module: "process", Functions: []string{"chdir"}, EffectType: SideEffectTypeEnvironment, Reversible: true, Idempotent: false, Description: "Working directory change", }, }, }
TypeScriptSideEffectPatterns defines side effect patterns for TypeScript/JavaScript.
Functions ¶
func CalibrateConfidence ¶
func CalibrateConfidence(base float64, adjustments ...ConfidenceAdjustment) float64
CalibrateConfidence computes a calibrated confidence score.
Description:
Takes a base confidence score and applies a series of adjustments. Each adjustment multiplies the current score. The result is clamped to the range [0.0, 1.0].
Inputs:
base - The starting confidence score (0.0-1.0). adjustments - Zero or more adjustments to apply.
Outputs:
float64 - The calibrated confidence score (0.0-1.0).
Example:
confidence := CalibrateConfidence(0.8,
AdjustmentExportedSymbol,
AdjustmentManyCallers,
)
Thread Safety:
This function is safe for concurrent use.
func SummarySideEffects ¶
func SummarySideEffects(analysis *SideEffectAnalysis) map[SideEffectType][]SideEffect
SummarySideEffects returns a summary of side effects grouped by type.
Description:
Groups the side effects in an analysis by their type for easier understanding and reporting.
Inputs:
analysis - The side effect analysis to summarize.
Outputs:
map[SideEffectType][]SideEffect - Side effects grouped by type.
Types ¶
type BreakingAnalysis ¶
type BreakingAnalysis struct {
// TargetID is the symbol being analyzed.
TargetID string `json:"target_id"`
// IsBreaking indicates if any breaking changes were detected.
IsBreaking bool `json:"is_breaking"`
// BreakingChanges lists all detected breaking changes.
BreakingChanges []BreakingChange `json:"breaking_changes"`
// SafeChanges lists changes that are safe (non-breaking).
SafeChanges []string `json:"safe_changes"`
// CallersAffected is the count of affected callers.
CallersAffected int `json:"callers_affected"`
// Confidence is how confident we are in the analysis (0.0-1.0).
Confidence float64 `json:"confidence"`
// Limitations lists what we couldn't check.
Limitations []string `json:"limitations"`
}
BreakingAnalysis is the result of breaking change analysis.
type BreakingChange ¶
type BreakingChange struct {
// Type categorizes the breaking change.
Type BreakingChangeType `json:"type"`
// Description explains what changed.
Description string `json:"description"`
// Affected lists the IDs of affected callers/users.
Affected []string `json:"affected"`
// Severity indicates how serious the break is.
Severity Severity `json:"severity"`
// AutoFixable indicates if an automatic fix can be generated.
AutoFixable bool `json:"auto_fixable"`
// SuggestedFix is the suggested fix if auto-fixable.
SuggestedFix string `json:"suggested_fix,omitempty"`
}
BreakingChange describes a single breaking change detected.
func CompareSignatures ¶
func CompareSignatures(current, proposed *ParsedSignature) []BreakingChange
CompareSignatures compares two signatures and returns breaking changes.
Description:
Compares a current signature against a proposed signature and identifies any breaking changes that would affect callers.
Inputs:
current - The current signature. proposed - The proposed new signature.
Outputs:
[]BreakingChange - List of breaking changes detected.
Thread Safety:
This function is safe for concurrent use.
type BreakingChangeAnalyzer ¶
type BreakingChangeAnalyzer struct {
// contains filtered or unexported fields
}
BreakingChangeAnalyzer analyzes proposed changes for breaking impact.
Description:
BreakingChangeAnalyzer helps the agent understand the impact of proposed changes before making them. It identifies callers that would break and provides confidence-calibrated assessments.
Thread Safety:
BreakingChangeAnalyzer is safe for concurrent use. It performs read-only operations on the graph and index.
func NewBreakingChangeAnalyzer ¶
func NewBreakingChangeAnalyzer(g *graph.Graph, idx *index.SymbolIndex) *BreakingChangeAnalyzer
NewBreakingChangeAnalyzer creates a new BreakingChangeAnalyzer.
Description:
Creates an analyzer that can detect breaking changes in proposed signature modifications.
Inputs:
g - The code graph. Must be frozen. idx - The symbol index.
Outputs:
*BreakingChangeAnalyzer - The configured analyzer.
Example:
analyzer := NewBreakingChangeAnalyzer(graph, index) analysis, err := analyzer.AnalyzeBreaking(ctx, "pkg.Handler", "func(ctx, req) error")
func (*BreakingChangeAnalyzer) AnalyzeBreaking ¶
func (a *BreakingChangeAnalyzer) AnalyzeBreaking( ctx context.Context, targetID string, proposedSig string, ) (*BreakingAnalysis, error)
AnalyzeBreaking analyzes whether a proposed signature change would break callers.
Description:
Compares the current signature of the target symbol against a proposed new signature. Identifies all breaking changes and the callers that would be affected.
Inputs:
ctx - Context for cancellation. targetID - The symbol ID to analyze. proposedSig - The proposed new signature.
Outputs:
*BreakingAnalysis - Analysis results including affected callers. error - Non-nil if the analysis fails.
Example:
analysis, err := analyzer.AnalyzeBreaking(ctx,
"handlers/user.go:10:HandleUser",
"func(ctx context.Context, req *UserRequest, opts Options) (*Response, error)",
)
if analysis.IsBreaking {
fmt.Printf("%d callers would break\n", analysis.CallersAffected)
}
Limitations:
- Only detects structural breaking changes (signatures, types)
- Does not detect behavioral breaking changes
- Requires the graph to be frozen
- May not detect all edge cases
func (*BreakingChangeAnalyzer) AnalyzeBreakingBatch ¶
func (a *BreakingChangeAnalyzer) AnalyzeBreakingBatch( ctx context.Context, changes map[string]string, ) (map[string]*BreakingAnalysis, error)
AnalyzeBreakingBatch analyzes multiple symbols for breaking changes.
Description:
Analyzes multiple target symbols against proposed signatures in a batch. More efficient than individual calls when analyzing related changes.
Inputs:
ctx - Context for cancellation. changes - Map of targetID to proposed signature.
Outputs:
map[string]*BreakingAnalysis - Analysis results keyed by targetID. error - Non-nil if the analysis fails.
func (*BreakingChangeAnalyzer) SetCRS ¶
func (a *BreakingChangeAnalyzer) SetCRS(recorder CRSRecorder)
SetCRS configures CRS recording for this analyzer.
type BreakingChangeType ¶
type BreakingChangeType string
BreakingChangeType categorizes the type of breaking change.
const ( // BreakingChangeSignature indicates a signature change (params, returns). BreakingChangeSignature BreakingChangeType = "signature" // BreakingChangeReturn indicates a return type change. BreakingChangeReturn BreakingChangeType = "return" // BreakingChangeBehavior indicates a behavior change inferred from usage. BreakingChangeBehavior BreakingChangeType = "behavior" // BreakingChangeVisibility indicates a visibility change (exported -> unexported). BreakingChangeVisibility BreakingChangeType = "visibility" // BreakingChangeType indicates a type change (e.g., struct field type). BreakingChangeTypeChange BreakingChangeType = "type" // BreakingChangeRemoval indicates a symbol was removed. BreakingChangeRemoval BreakingChangeType = "removal" )
type CRSRecorder ¶
type CRSRecorder interface {
// RecordToolStep records a tool execution step in the CRS.
RecordToolStep(ctx context.Context, toolName string, resultCount int, duration time.Duration, err error)
}
CRSRecorder abstracts CRS step recording for reason tool implementations.
Description ¶
CRSRecorder provides a simplified interface for reason analysis tools to record their executions in the CRS. This interface mirrors patterns.CRSRecorder — Go duck typing means any implementation satisfying one automatically satisfies the other.
Thread Safety ¶
Implementations must be safe for concurrent use.
type CallerUpdate ¶
type CallerUpdate struct {
// CallerID is the symbol ID of the caller.
CallerID string `json:"caller_id"`
// CallerName is the name of the calling function.
CallerName string `json:"caller_name"`
// CurrentCall is the current call expression (if extractable).
CurrentCall string `json:"current_call,omitempty"`
// NeededCall is what the call should be changed to.
NeededCall string `json:"needed_call,omitempty"`
// FilePath is the file containing the caller.
FilePath string `json:"file_path"`
// Line is the line number of the call.
Line int `json:"line"`
// UpdateType describes the type of update needed.
UpdateType string `json:"update_type"`
}
CallerUpdate describes a caller that needs to be updated.
type ChangeSimulation ¶
type ChangeSimulation struct {
// TargetID is the symbol being changed.
TargetID string `json:"target_id"`
// Valid indicates if the change appears valid.
Valid bool `json:"valid"`
// CallersToUpdate lists callers that need to be updated.
CallersToUpdate []CallerUpdate `json:"callers_to_update"`
// ImportsNeeded lists imports that would need to be added.
ImportsNeeded []string `json:"imports_needed"`
// TypeMismatches lists type incompatibilities introduced.
TypeMismatches []TypeMismatch `json:"type_mismatches"`
// TestsAffected lists test symbols that would be affected.
TestsAffected []string `json:"tests_affected"`
// Confidence is how confident we are in the simulation (0.0-1.0).
Confidence float64 `json:"confidence"`
// Limitations lists what we couldn't simulate.
Limitations []string `json:"limitations"`
}
ChangeSimulation is the result of simulating a change.
type ChangeSimulator ¶
type ChangeSimulator struct {
// contains filtered or unexported fields
}
ChangeSimulator simulates the impact of proposed code changes.
Description:
ChangeSimulator previews what would happen if a change were made, identifying callers that need updates, imports needed, type mismatches, and affected tests.
Thread Safety:
ChangeSimulator is safe for concurrent use.
func NewChangeSimulator ¶
func NewChangeSimulator(g *graph.Graph, idx *index.SymbolIndex) *ChangeSimulator
NewChangeSimulator creates a new ChangeSimulator.
Description:
Creates a simulator that can preview the impact of proposed changes using the code graph and symbol index.
Inputs:
g - The code graph. Must be frozen. idx - The symbol index.
Outputs:
*ChangeSimulator - The configured simulator.
func (*ChangeSimulator) SetCRS ¶
func (s *ChangeSimulator) SetCRS(recorder CRSRecorder)
SetCRS configures CRS recording for this simulator.
func (*ChangeSimulator) SimulateChange ¶
func (s *ChangeSimulator) SimulateChange( ctx context.Context, targetID string, newSignature string, ) (*ChangeSimulation, error)
SimulateChange simulates what would happen if a symbol were changed.
Description:
Simulates the impact of changing a symbol's signature or implementation. Identifies all callers that would need updates, any type mismatches that would be introduced, and tests that would be affected.
Inputs:
ctx - Context for cancellation. targetID - The symbol ID to change. newSignature - The proposed new signature.
Outputs:
*ChangeSimulation - Simulation results. error - Non-nil if the simulation fails.
Example:
sim, err := simulator.SimulateChange(ctx,
"pkg/handlers.Handle",
"func(ctx context.Context, req *Request, opts Options) error",
)
if len(sim.CallersToUpdate) > 0 {
fmt.Printf("%d callers need updates\n", len(sim.CallersToUpdate))
}
Limitations:
- Cannot simulate runtime behavior changes
- Type checking is structural, not semantic
- May not detect all indirect impacts
func (*ChangeSimulator) SimulateMultipleChanges ¶
func (s *ChangeSimulator) SimulateMultipleChanges( ctx context.Context, changes map[string]string, ) (map[string]*ChangeSimulation, error)
SimulateMultipleChanges simulates multiple related changes.
Description:
Simulates a batch of related changes, useful when making coordinated updates across multiple symbols.
Inputs:
ctx - Context for cancellation. changes - Map of targetID to new signature.
Outputs:
map[string]*ChangeSimulation - Simulation results keyed by targetID. error - Non-nil if the simulation fails.
type ChangeValidation ¶
type ChangeValidation struct {
// SyntaxValid indicates if the syntax is correct.
SyntaxValid bool `json:"syntax_valid"`
// TypesValid indicates if all type references exist.
TypesValid bool `json:"types_valid"`
// ImportsValid indicates if all imports can resolve.
ImportsValid bool `json:"imports_valid"`
// Errors lists all validation errors found.
Errors []ValidationError `json:"errors,omitempty"`
// Warnings lists non-fatal issues found.
Warnings []ValidationWarning `json:"warnings,omitempty"`
// Scope describes the validation scope.
// Always "syntactic" for this validator.
Scope string `json:"scope"`
// Confidence is how confident we are (0.0-1.0).
Confidence float64 `json:"confidence"`
}
ChangeValidation is the result of validating a change.
type ChangeValidator ¶
type ChangeValidator struct {
// contains filtered or unexported fields
}
ChangeValidator validates proposed code changes.
Description:
ChangeValidator performs syntactic validation of proposed code changes. It checks for syntax errors, type reference existence, and import resolution. IMPORTANT: This is syntactic validation only. It cannot perform full semantic type checking - that requires the compiler or LSP.
Thread Safety:
ChangeValidator is safe for concurrent use.
func NewChangeValidator ¶
func NewChangeValidator(idx *index.SymbolIndex) *ChangeValidator
NewChangeValidator creates a new ChangeValidator.
Description:
Creates a validator that can check proposed code for syntactic validity.
Inputs:
idx - The symbol index (for type reference checking).
Outputs:
*ChangeValidator - The configured validator.
func (*ChangeValidator) SetCRS ¶
func (v *ChangeValidator) SetCRS(recorder CRSRecorder)
SetCRS configures CRS recording for this validator.
func (*ChangeValidator) ValidateChange ¶
func (v *ChangeValidator) ValidateChange( ctx context.Context, filePath string, newContent string, ) (*ChangeValidation, error)
ValidateChange validates proposed code content.
Description:
Validates the proposed code for a file. Performs: - Syntax checking (will it parse?) - Type reference checking (do referenced types exist?) - Import resolution (do imported packages exist?) IMPORTANT LIMITATION: This performs syntactic validation only. It cannot verify: - Type safety (is this assignment valid?) - Interface satisfaction (does this implement the interface?) - Semantic correctness (will this compile?) For full type checking, use the compiler or LSP.
Inputs:
ctx - Context for cancellation. filePath - Path to the file being changed. newContent - Proposed new content for the file.
Outputs:
*ChangeValidation - Validation results. error - Non-nil if validation itself fails.
Example:
validation, err := validator.ValidateChange(ctx,
"handlers/user.go",
"package handlers\n\nfunc Handle() error { return nil }",
)
if !validation.SyntaxValid {
for _, e := range validation.Errors {
fmt.Printf("Line %d: %s\n", e.Line, e.Message)
}
}
type CodeMetrics ¶
type CodeMetrics struct {
// LineCount is the number of lines in the function body.
LineCount int `json:"line_count"`
// CyclomaticComplexity measures decision points (branches, loops).
CyclomaticComplexity int `json:"cyclomatic_complexity"`
// ParameterCount is the number of parameters.
ParameterCount int `json:"parameter_count"`
// ReturnCount is the number of return values.
ReturnCount int `json:"return_count"`
// NestingDepth is the maximum nesting level.
NestingDepth int `json:"nesting_depth"`
// CognitiveComplexity measures how hard the code is to understand.
CognitiveComplexity int `json:"cognitive_complexity"`
// CallerCount is the number of functions that call this one.
CallerCount int `json:"caller_count"`
// CalleeCount is the number of functions this one calls.
CalleeCount int `json:"callee_count"`
// IsExported indicates if the function is exported/public.
IsExported bool `json:"is_exported"`
}
CodeMetrics contains measured characteristics of code.
type ConfidenceAdjustment ¶
type ConfidenceAdjustment struct {
// Reason explains why the adjustment is applied.
Reason string `json:"reason"`
// Multiplier is the factor to multiply confidence by.
// Values < 1.0 decrease confidence, > 1.0 increase confidence.
Multiplier float64 `json:"multiplier"`
}
ConfidenceAdjustment represents a factor that adjusts confidence scores.
type ConfidenceCalibration ¶
type ConfidenceCalibration struct {
// BaseScore is the starting confidence.
BaseScore float64 `json:"base_score"`
// Adjustments lists all adjustments applied.
Adjustments []ConfidenceAdjustment `json:"adjustments"`
// FinalScore is the calibrated result.
FinalScore float64 `json:"final_score"`
}
ConfidenceCalibration tracks the full calculation for transparency.
func NewConfidenceCalibration ¶
func NewConfidenceCalibration(base float64) *ConfidenceCalibration
NewConfidenceCalibration creates a new calibration tracker.
Description:
Creates a ConfidenceCalibration that tracks all adjustments applied to a base score, useful for explaining how a confidence score was calculated.
Inputs:
base - The starting confidence score (0.0-1.0).
Outputs:
*ConfidenceCalibration - A new calibration tracker.
Example:
cal := NewConfidenceCalibration(0.8)
cal.Apply(AdjustmentExportedSymbol)
cal.Apply(AdjustmentManyCallers)
fmt.Printf("Final: %.2f\n", cal.FinalScore)
func (*ConfidenceCalibration) Apply ¶
func (c *ConfidenceCalibration) Apply(adj ConfidenceAdjustment) *ConfidenceCalibration
Apply adds an adjustment to the calibration.
Description:
Applies the given adjustment to the current score and records it in the adjustments list for transparency.
Inputs:
adj - The adjustment to apply.
Outputs:
*ConfidenceCalibration - Returns self for chaining.
func (*ConfidenceCalibration) ApplyIf ¶
func (c *ConfidenceCalibration) ApplyIf(condition bool, adj ConfidenceAdjustment) *ConfidenceCalibration
ApplyIf conditionally applies an adjustment.
Description:
Applies the adjustment only if the condition is true. Useful for conditional adjustments based on analysis results.
Inputs:
condition - Whether to apply the adjustment. adj - The adjustment to apply if condition is true.
Outputs:
*ConfidenceCalibration - Returns self for chaining.
type ConfidenceLevel ¶
type ConfidenceLevel string
ConfidenceLevel categorizes confidence into human-readable levels.
const ( // ConfidenceLevelVeryHigh indicates very high confidence (>= 0.9). ConfidenceLevelVeryHigh ConfidenceLevel = "very_high" // ConfidenceLevelHigh indicates high confidence (>= 0.7). ConfidenceLevelHigh ConfidenceLevel = "high" // ConfidenceLevelMedium indicates medium confidence (>= 0.5). ConfidenceLevelMedium ConfidenceLevel = "medium" // ConfidenceLevelLow indicates low confidence (>= 0.3). ConfidenceLevelLow ConfidenceLevel = "low" // ConfidenceLevelVeryLow indicates very low confidence (< 0.3). ConfidenceLevelVeryLow ConfidenceLevel = "very_low" )
func GetConfidenceLevel ¶
func GetConfidenceLevel(confidence float64) ConfidenceLevel
GetConfidenceLevel converts a numeric confidence to a level.
Description:
Maps a confidence score (0.0-1.0) to a human-readable level.
Inputs:
confidence - The confidence score (0.0-1.0).
Outputs:
ConfidenceLevel - The corresponding level.
type CoverageReport ¶
type CoverageReport struct {
// TotalSymbols is the total number of symbols analyzed.
TotalSymbols int `json:"total_symbols"`
// CoveredSymbols is the number of symbols with test coverage.
CoveredSymbols int `json:"covered_symbols"`
// UncoveredSymbols lists symbols without coverage.
UncoveredSymbols []string `json:"uncovered_symbols"`
// CoveragePercent is the percentage of covered symbols.
CoveragePercent float64 `json:"coverage_percent"`
// TestCount is the total number of test functions.
TestCount int `json:"test_count"`
// Confidence is how confident we are in the report (0.0-1.0).
Confidence float64 `json:"confidence"`
}
CoverageReport is a summary of test coverage for a codebase.
type FunctionPattern ¶
type FunctionPattern struct {
// Package is the Go package path (e.g., "os", "net/http").
Package string `json:"package,omitempty"`
// Module is the Python/TypeScript module name (e.g., "os", "fs").
Module string `json:"module,omitempty"`
// Functions lists function names that have side effects.
Functions []string `json:"functions"`
// EffectType categorizes the side effect.
EffectType SideEffectType `json:"effect_type"`
// Reversible indicates if the effect can be undone.
Reversible bool `json:"reversible"`
// Idempotent indicates if repeating the call is safe.
Idempotent bool `json:"idempotent"`
// Description explains what the side effect does.
Description string `json:"description"`
}
FunctionPattern defines a pattern for detecting side effects.
type ImportReference ¶
ImportReference represents an import found in code.
type InterfaceSatisfaction ¶
type InterfaceSatisfaction struct {
// TypeName is the type being checked.
TypeName string `json:"type_name"`
// InterfaceName is the interface being checked against.
InterfaceName string `json:"interface_name"`
// Satisfied indicates if the type satisfies the interface.
Satisfied bool `json:"satisfied"`
// MissingMethods lists methods the type doesn't implement.
MissingMethods []string `json:"missing_methods,omitempty"`
// MatchedMethods lists methods that match.
MatchedMethods []MethodMatch `json:"matched_methods,omitempty"`
// Reason explains the result.
Reason string `json:"reason"`
// Confidence is how confident we are (0.0-1.0).
Confidence float64 `json:"confidence"`
}
InterfaceSatisfaction represents the result of interface satisfaction check.
type MethodMatch ¶
type MethodMatch struct {
// InterfaceMethod is the method name from the interface.
InterfaceMethod string `json:"interface_method"`
// TypeMethod is the matching method from the type.
TypeMethod string `json:"type_method"`
// SignatureMatch indicates if signatures match exactly.
SignatureMatch bool `json:"signature_match"`
}
MethodMatch represents a matched method between type and interface.
type NopCRSRecorder ¶
type NopCRSRecorder struct{}
NopCRSRecorder is a no-op implementation for tests and standalone usage.
Thread Safety ¶
This type is safe for concurrent use (stateless).
func (*NopCRSRecorder) RecordToolStep ¶
func (n *NopCRSRecorder) RecordToolStep(_ context.Context, _ string, _ int, _ time.Duration, _ error)
RecordToolStep is a no-op.
type ParameterInfo ¶
type ParameterInfo struct {
// Name is the parameter name. May be empty for unnamed parameters.
Name string `json:"name"`
// Type is the parameter type information.
Type TypeInfo `json:"type"`
// Optional indicates if the parameter has a default value (Python/TS).
Optional bool `json:"optional,omitempty"`
// Default is the default value expression if optional.
Default string `json:"default,omitempty"`
}
ParameterInfo represents a function parameter.
type ParsedSignature ¶
type ParsedSignature struct {
// Name is the function/method name.
Name string `json:"name"`
// Receiver is the receiver type for methods. Nil for functions.
Receiver *TypeInfo `json:"receiver,omitempty"`
// Parameters lists all parameters in order.
Parameters []ParameterInfo `json:"parameters"`
// Returns lists all return types in order.
Returns []TypeInfo `json:"returns"`
// TypeParams lists generic type parameters if any.
TypeParams []TypeParamInfo `json:"type_params,omitempty"`
// Variadic indicates if the last parameter is variadic.
Variadic bool `json:"variadic,omitempty"`
// Language is the source language.
Language string `json:"language"`
}
ParsedSignature represents a parsed function/method signature.
type RefactorSuggester ¶
type RefactorSuggester struct {
// contains filtered or unexported fields
}
RefactorSuggester provides refactoring suggestions for code.
Description:
RefactorSuggester analyzes code and suggests improvements such as extracting functions, reducing complexity, and improving naming. All suggestions are confidence-calibrated and include risk assessment.
Thread Safety:
RefactorSuggester is safe for concurrent use.
func NewRefactorSuggester ¶
func NewRefactorSuggester(g *graph.Graph, idx *index.SymbolIndex) *RefactorSuggester
NewRefactorSuggester creates a new RefactorSuggester.
Description:
Creates a suggester that can analyze code and provide refactoring recommendations using the code graph and symbol index.
Inputs:
g - The code graph. Must be frozen. idx - The symbol index.
Outputs:
*RefactorSuggester - The configured suggester.
func (*RefactorSuggester) CalculateMetricsOnly ¶
func (r *RefactorSuggester) CalculateMetricsOnly( ctx context.Context, targetID string, ) (*CodeMetrics, error)
CalculateMetricsOnly calculates metrics without generating suggestions.
Description:
Calculates code metrics for a symbol without the overhead of generating suggestions. Useful for dashboards and reporting.
Inputs:
ctx - Context for cancellation. targetID - The symbol ID to analyze.
Outputs:
*CodeMetrics - The calculated metrics. error - Non-nil if the analysis fails.
func (*RefactorSuggester) GetHealthDistribution ¶
GetHealthDistribution returns a distribution of function health scores.
Description:
Analyzes all functions and groups them by health score ranges. Useful for understanding overall codebase health.
Inputs:
ctx - Context for cancellation.
Outputs:
map[string]int - Count of functions in each health range. error - Non-nil if the analysis fails.
func (*RefactorSuggester) GetUnhealthyFunctions ¶
func (r *RefactorSuggester) GetUnhealthyFunctions( ctx context.Context, threshold int, ) ([]RefactorSuggestions, error)
GetUnhealthyFunctions returns functions with health below threshold.
Description:
Scans all functions and returns those with a health score below the specified threshold. Useful for finding code that needs attention.
Inputs:
ctx - Context for cancellation. threshold - Minimum health score (0-100).
Outputs:
[]RefactorSuggestions - Analysis for unhealthy functions. error - Non-nil if the analysis fails.
func (*RefactorSuggester) SetCRS ¶
func (r *RefactorSuggester) SetCRS(recorder CRSRecorder)
SetCRS configures CRS recording for this suggester.
func (*RefactorSuggester) SuggestRefactor ¶
func (r *RefactorSuggester) SuggestRefactor( ctx context.Context, targetID string, ) (*RefactorSuggestions, error)
SuggestRefactor analyzes a function and suggests refactorings.
Description:
Analyzes the target function and provides calibrated refactoring suggestions based on code metrics and patterns.
Inputs:
ctx - Context for cancellation. targetID - The symbol ID to analyze.
Outputs:
*RefactorSuggestions - Suggestions with confidence and risk assessment. error - Non-nil if the analysis fails.
Example:
suggestions, err := suggester.SuggestRefactor(ctx, "pkg/handlers.ProcessData")
for _, s := range suggestions.Suggestions {
if s.Confidence > 0.7 {
fmt.Printf("%s: %s\n", s.Type, s.Description)
}
}
Limitations:
- Cannot analyze runtime behavior
- Metrics are approximations without full AST parsing
- May not detect all code smells
func (*RefactorSuggester) SuggestRefactorBatch ¶
func (r *RefactorSuggester) SuggestRefactorBatch( ctx context.Context, targetIDs []string, ) (map[string]*RefactorSuggestions, error)
SuggestRefactorBatch analyzes multiple functions for refactoring.
Description:
Analyzes multiple functions and provides refactoring suggestions for each one. More efficient than individual calls.
Inputs:
ctx - Context for cancellation. targetIDs - The symbol IDs to analyze.
Outputs:
map[string]*RefactorSuggestions - Suggestions keyed by targetID. error - Non-nil if the analysis fails completely.
type RefactorSuggestions ¶
type RefactorSuggestions struct {
// TargetID is the symbol being analyzed.
TargetID string `json:"target_id"`
// TargetName is the name of the symbol.
TargetName string `json:"target_name"`
// Suggestions lists all refactoring suggestions.
Suggestions []Suggestion `json:"suggestions"`
// Metrics contains the measured code characteristics.
Metrics CodeMetrics `json:"metrics"`
// OverallHealth is a score from 0-100 indicating code health.
OverallHealth int `json:"overall_health"`
// Limitations lists what we couldn't analyze.
Limitations []string `json:"limitations"`
}
RefactorSuggestions is the result of refactoring analysis.
type RefactorType ¶
type RefactorType string
RefactorType categorizes the type of refactoring suggestion.
const ( // RefactorTypeExtractFunction suggests extracting code into a new function. RefactorTypeExtractFunction RefactorType = "extract_function" // RefactorTypeExtractInterface suggests extracting an interface. RefactorTypeExtractInterface RefactorType = "extract_interface" // RefactorTypeRename suggests renaming for clarity. RefactorTypeRename RefactorType = "rename" // RefactorTypeSimplify suggests simplifying complex logic. RefactorTypeSimplify RefactorType = "simplify" // RefactorTypeSplitFunction suggests splitting a large function. RefactorTypeSplitFunction RefactorType = "split_function" // RefactorTypeReduceParameters suggests reducing parameter count. RefactorTypeReduceParameters RefactorType = "reduce_parameters" // RefactorTypeRemoveDeadCode suggests removing unused code. RefactorTypeRemoveDeadCode RefactorType = "remove_dead_code" // RefactorTypeReduceNesting suggests reducing nesting depth. RefactorTypeReduceNesting RefactorType = "reduce_nesting" )
type RiskLevel ¶
type RiskLevel string
RiskLevel categorizes the risk of a refactoring.
const ( // RiskLevelLow indicates minimal risk of breaking changes. RiskLevelLow RiskLevel = "low" // RiskLevelMedium indicates moderate risk requiring testing. RiskLevelMedium RiskLevel = "medium" // RiskLevelHigh indicates significant risk requiring careful review. RiskLevelHigh RiskLevel = "high" )
type Severity ¶
type Severity string
Severity represents the severity level of a change or issue.
const ( // SeverityCritical indicates a critical issue that will cause failures. SeverityCritical Severity = "CRITICAL" // SeverityHigh indicates a high-priority issue likely to cause problems. SeverityHigh Severity = "HIGH" // SeverityMedium indicates a medium-priority issue that may cause problems. SeverityMedium Severity = "MEDIUM" // SeverityLow indicates a low-priority issue or minor inconvenience. SeverityLow Severity = "LOW" )
type SideEffect ¶
type SideEffect struct {
// Type categorizes the side effect (file_io, network, database, etc.).
Type SideEffectType `json:"type"`
// Operation describes the specific operation (e.g., "Write", "Query").
Operation string `json:"operation"`
// Location describes where the side effect occurs.
Location string `json:"location"`
// Description explains what the side effect does.
Description string `json:"description"`
// Reversible indicates if the effect can be undone.
Reversible bool `json:"reversible"`
// Idempotent indicates if repeating the call is safe.
Idempotent bool `json:"idempotent"`
// Transitive indicates if this effect comes from a called function.
Transitive bool `json:"transitive"`
// SourceFunctionID is the function that directly has the side effect.
// For transitive effects, this is the callee that has the effect.
SourceFunctionID string `json:"source_function_id,omitempty"`
// CallChain shows the path from target to the side effect source.
CallChain []string `json:"call_chain,omitempty"`
}
SideEffect describes a single side effect detected in a function.
type SideEffectAnalysis ¶
type SideEffectAnalysis struct {
// TargetID is the symbol being analyzed.
TargetID string `json:"target_id"`
// IsPure indicates if the function has no side effects.
IsPure bool `json:"is_pure"`
// SideEffects lists all detected side effects.
SideEffects []SideEffect `json:"side_effects"`
// DirectEffects is the count of direct side effects.
DirectEffects int `json:"direct_effects"`
// TransitiveEffects is the count of transitive side effects.
TransitiveEffects int `json:"transitive_effects"`
// Confidence is how confident we are in the analysis (0.0-1.0).
Confidence float64 `json:"confidence"`
// Limitations lists what we couldn't analyze.
Limitations []string `json:"limitations"`
}
SideEffectAnalysis is the result of side effect analysis.
type SideEffectAnalyzer ¶
type SideEffectAnalyzer struct {
// contains filtered or unexported fields
}
SideEffectAnalyzer detects side effects in functions.
Description:
SideEffectAnalyzer helps understand what external effects a function has, including file I/O, network calls, database operations, and global state mutations. This is crucial for understanding the impact of changes.
Thread Safety:
SideEffectAnalyzer is safe for concurrent use.
func NewSideEffectAnalyzer ¶
func NewSideEffectAnalyzer(g *graph.Graph, idx *index.SymbolIndex) *SideEffectAnalyzer
NewSideEffectAnalyzer creates a new SideEffectAnalyzer.
Description:
Creates an analyzer that can detect side effects in functions using the code graph and symbol index.
Inputs:
g - The code graph. Must be frozen. idx - The symbol index.
Outputs:
*SideEffectAnalyzer - The configured analyzer.
func (*SideEffectAnalyzer) FindSideEffects ¶
func (a *SideEffectAnalyzer) FindSideEffects( ctx context.Context, targetID string, ) (*SideEffectAnalysis, error)
FindSideEffects analyzes a function for side effects.
Description:
Detects side effects in the target function including file I/O, network calls, database operations, and global state mutations. Also tracks transitive side effects through called functions.
Inputs:
ctx - Context for cancellation. targetID - The symbol ID to analyze.
Outputs:
*SideEffectAnalysis - Analysis results. error - Non-nil if the analysis fails.
Example:
analysis, err := analyzer.FindSideEffects(ctx, "pkg/handlers.SaveUser")
if !analysis.IsPure {
fmt.Printf("Found %d side effects\n", len(analysis.SideEffects))
}
Limitations:
- Static analysis only, cannot detect runtime-determined side effects
- May not detect effects through reflection or interfaces
- Transitive tracking limited to prevent performance issues
func (*SideEffectAnalyzer) FindSideEffectsBatch ¶
func (a *SideEffectAnalyzer) FindSideEffectsBatch( ctx context.Context, targetIDs []string, ) (map[string]*SideEffectAnalysis, error)
FindSideEffectsBatch analyzes multiple functions for side effects.
Description:
Analyzes multiple functions for side effects in a batch. More efficient than individual calls when analyzing related functions.
Inputs:
ctx - Context for cancellation. targetIDs - The symbol IDs to analyze.
Outputs:
map[string]*SideEffectAnalysis - Analysis results keyed by targetID. error - Non-nil if the analysis fails completely.
func (*SideEffectAnalyzer) GetPureFunctions ¶
func (a *SideEffectAnalyzer) GetPureFunctions( ctx context.Context, ) ([]string, error)
GetPureFunctions returns all functions that appear to be pure.
Description:
Analyzes all functions in the index and returns those with no detected side effects. Useful for identifying functions safe to optimize or cache.
Inputs:
ctx - Context for cancellation.
Outputs:
[]string - IDs of functions that appear to be pure. error - Non-nil if the analysis fails.
Limitations:
- May include false positives (functions with undetectable side effects)
- May exclude false negatives (pure functions with unrecognized patterns)
type SideEffectPatterns ¶
type SideEffectPatterns struct {
// Language is the programming language these patterns apply to.
Language string `json:"language"`
// FileIO patterns for file system operations.
FileIO []FunctionPattern `json:"file_io"`
// Network patterns for network operations.
Network []FunctionPattern `json:"network"`
// Database patterns for database operations.
Database []FunctionPattern `json:"database"`
// Logging patterns for logging operations.
Logging []FunctionPattern `json:"logging"`
// GlobalState patterns for global state mutations.
GlobalState []FunctionPattern `json:"global_state"`
// Process patterns for process/system operations.
Process []FunctionPattern `json:"process"`
// Environment patterns for environment variable operations.
Environment []FunctionPattern `json:"environment"`
}
SideEffectPatterns defines language-specific side effect detection patterns.
func GetPatternsForLanguage ¶
func GetPatternsForLanguage(language string) *SideEffectPatterns
GetPatternsForLanguage returns side effect patterns for the given language.
Description:
Returns the predefined side effect patterns for the specified language. Returns nil if the language is not supported.
Inputs:
language - The programming language (go, python, typescript, javascript).
Outputs:
*SideEffectPatterns - The patterns for the language, or nil if unsupported.
func (*SideEffectPatterns) GetAllPatterns ¶
func (p *SideEffectPatterns) GetAllPatterns() []FunctionPattern
GetAllPatterns returns all side effect patterns flattened into a slice.
func (*SideEffectPatterns) GetPatternsByType ¶
func (p *SideEffectPatterns) GetPatternsByType(effectType SideEffectType) []FunctionPattern
GetPatternsByType returns patterns for a specific side effect type.
type SideEffectType ¶
type SideEffectType string
SideEffectType categorizes the type of side effect.
const ( // SideEffectTypeFileIO indicates file system operations. SideEffectTypeFileIO SideEffectType = "file_io" // SideEffectTypeNetwork indicates network operations. SideEffectTypeNetwork SideEffectType = "network" // SideEffectTypeDatabase indicates database operations. SideEffectTypeDatabase SideEffectType = "database" // SideEffectTypeLogging indicates logging operations. SideEffectTypeLogging SideEffectType = "logging" // SideEffectTypeGlobalState indicates global state mutations. SideEffectTypeGlobalState SideEffectType = "global_state" // SideEffectTypeProcess indicates process/system operations. SideEffectTypeProcess SideEffectType = "process" // SideEffectTypeEnvironment indicates environment variable operations. SideEffectTypeEnvironment SideEffectType = "environment" )
type SignatureParser ¶
type SignatureParser struct {
// contains filtered or unexported fields
}
SignatureParser parses function signatures using tree-sitter.
Description:
SignatureParser provides accurate, language-aware parsing of function and method signatures. It uses tree-sitter for robust parsing rather than error-prone regex patterns.
Thread Safety:
SignatureParser is safe for concurrent use. Each ParseSignature call creates its own parser instance internally.
func NewSignatureParser ¶
func NewSignatureParser() *SignatureParser
NewSignatureParser creates a new SignatureParser.
Description:
Creates a parser that can handle Go, Python, and TypeScript signatures. Languages are lazily initialized on first use.
Outputs:
*SignatureParser - A new signature parser.
func (*SignatureParser) ParseSignature ¶
func (p *SignatureParser) ParseSignature(sig string, lang string) (*ParsedSignature, error)
ParseSignature parses a function signature string.
Description:
Parses the given signature string using tree-sitter for the specified language. Returns structured information about the signature including parameters, return types, and type parameters.
Inputs:
sig - The signature string to parse.
lang - The language ("go", "python", "typescript").
Outputs:
*ParsedSignature - The parsed signature structure. error - Non-nil if parsing fails or language is unsupported.
Example:
parser := NewSignatureParser()
sig, err := parser.ParseSignature(
"func(ctx context.Context, id string) (*User, error)",
"go",
)
Limitations:
- Requires valid syntax for the target language
- May not handle all edge cases for complex signatures
- Does not resolve type aliases or imports
type Suggestion ¶
type Suggestion struct {
// Type categorizes the refactoring.
Type RefactorType `json:"type"`
// Description explains what should be done.
Description string `json:"description"`
// Rationale explains why this refactoring is suggested.
Rationale string `json:"rationale"`
// CodeBefore shows the current code pattern (snippet or description).
CodeBefore string `json:"code_before,omitempty"`
// CodeAfter shows the suggested code pattern (snippet or description).
CodeAfter string `json:"code_after,omitempty"`
// Confidence is how confident we are in this suggestion (0.0-1.0).
Confidence float64 `json:"confidence"`
// Basis explains what evidence supports this suggestion.
Basis string `json:"basis"`
// Risk indicates what could go wrong.
Risk string `json:"risk"`
// RiskLevel categorizes the risk.
RiskLevel RiskLevel `json:"risk_level"`
// Priority indicates suggested order of applying (1 = highest).
Priority int `json:"priority"`
// AffectedSymbols lists symbols that would be affected.
AffectedSymbols []string `json:"affected_symbols,omitempty"`
}
Suggestion represents a single refactoring suggestion.
type TestCoverage ¶
type TestCoverage struct {
// TargetID is the symbol being analyzed.
TargetID string `json:"target_id"`
// IsCovered indicates if any test exercises this symbol.
IsCovered bool `json:"is_covered"`
// DirectTests lists tests that directly call this symbol.
DirectTests []TestInfo `json:"direct_tests"`
// IndirectTests lists tests that call this symbol transitively.
IndirectTests []TestInfo `json:"indirect_tests"`
// CoverageDepth is the minimum call depth from any test.
CoverageDepth int `json:"coverage_depth"`
// Confidence is how confident we are in the analysis (0.0-1.0).
Confidence float64 `json:"confidence"`
// Limitations lists what we couldn't analyze.
Limitations []string `json:"limitations"`
}
TestCoverage is the result of coverage analysis for a symbol.
type TestCoverageFinder ¶
type TestCoverageFinder struct {
// contains filtered or unexported fields
}
TestCoverageFinder analyzes which symbols are covered by tests.
Description:
TestCoverageFinder uses the code graph to determine which symbols are exercised by test functions. It provides structural coverage information based on call relationships.
Thread Safety:
TestCoverageFinder is safe for concurrent use.
func NewTestCoverageFinder ¶
func NewTestCoverageFinder(g *graph.Graph, idx *index.SymbolIndex) *TestCoverageFinder
NewTestCoverageFinder creates a new TestCoverageFinder.
Description:
Creates a finder that can analyze test coverage using the code graph.
Inputs:
g - The code graph. Must be frozen. idx - The symbol index.
Outputs:
*TestCoverageFinder - The configured finder.
func (*TestCoverageFinder) FindTestCoverage ¶
func (f *TestCoverageFinder) FindTestCoverage( ctx context.Context, targetID string, ) (*TestCoverage, error)
FindTestCoverage finds tests that cover a symbol.
Description:
Analyzes the code graph to find all tests that exercise a given symbol, either directly or transitively through call chains.
Inputs:
ctx - Context for cancellation. targetID - The symbol ID to analyze.
Outputs:
*TestCoverage - Coverage results. error - Non-nil if the analysis fails.
Example:
coverage, err := finder.FindTestCoverage(ctx, "pkg/handlers.Handle")
if !coverage.IsCovered {
fmt.Println("Symbol is not covered by any tests")
}
Limitations:
- Only detects structural coverage (calls), not path coverage
- Does not account for conditional execution
- Cannot detect table-driven test coverage
func (*TestCoverageFinder) FindTestsForFile ¶
func (f *TestCoverageFinder) FindTestsForFile( ctx context.Context, filePath string, ) ([]TestInfo, error)
FindTestsForFile finds all tests that cover symbols in a file.
Description:
Identifies all test functions that exercise any symbol defined in the given file.
Inputs:
ctx - Context for cancellation. filePath - Path to the file to analyze.
Outputs:
[]TestInfo - Tests that cover symbols in the file. error - Non-nil if the analysis fails.
func (*TestCoverageFinder) FindUncoveredSymbols ¶
func (f *TestCoverageFinder) FindUncoveredSymbols( ctx context.Context, kinds []ast.SymbolKind, ) ([]string, error)
FindUncoveredSymbols finds symbols that have no test coverage.
Description:
Scans all symbols in the index and identifies those that are not reached by any test function.
Inputs:
ctx - Context for cancellation. kinds - Symbol kinds to check. If empty, checks functions and methods.
Outputs:
[]string - IDs of uncovered symbols. error - Non-nil if the analysis fails.
func (*TestCoverageFinder) GenerateCoverageReport ¶
func (f *TestCoverageFinder) GenerateCoverageReport( ctx context.Context, ) (*CoverageReport, error)
GenerateCoverageReport generates a coverage report for the codebase.
Description:
Analyzes all functions and methods in the codebase and generates a summary report of test coverage.
Inputs:
ctx - Context for cancellation.
Outputs:
*CoverageReport - The coverage report. error - Non-nil if the analysis fails.
func (*TestCoverageFinder) SetCRS ¶
func (f *TestCoverageFinder) SetCRS(recorder CRSRecorder)
SetCRS configures CRS recording for this finder.
type TestInfo ¶
type TestInfo struct {
// TestID is the test function symbol ID.
TestID string `json:"test_id"`
// TestName is the name of the test function.
TestName string `json:"test_name"`
// FilePath is the test file path.
FilePath string `json:"file_path"`
// CallDepth is how many calls away from the target.
CallDepth int `json:"call_depth"`
// CallPath is the chain of calls from test to target.
CallPath []string `json:"call_path,omitempty"`
}
TestInfo describes a test that covers a symbol.
type TypeCompatibility ¶
type TypeCompatibility struct {
// SourceType is the type we have.
SourceType string `json:"source_type"`
// TargetType is the type we need.
TargetType string `json:"target_type"`
// Compatible indicates if the types are compatible.
Compatible bool `json:"compatible"`
// Reason explains why types are or aren't compatible.
Reason string `json:"reason"`
// Conversions lists possible conversions if not directly compatible.
Conversions []string `json:"conversions,omitempty"`
// Confidence is how confident we are (0.0-1.0).
Confidence float64 `json:"confidence"`
}
TypeCompatibility is the result of type compatibility checking.
type TypeCompatibilityChecker ¶
type TypeCompatibilityChecker struct {
// contains filtered or unexported fields
}
TypeCompatibilityChecker checks if types are compatible.
Description:
TypeCompatibilityChecker analyzes whether one type can be used where another is expected. This includes interface satisfaction, structural compatibility, and possible conversions.
Thread Safety:
TypeCompatibilityChecker is safe for concurrent use.
func NewTypeCompatibilityChecker ¶
func NewTypeCompatibilityChecker(g *graph.Graph, idx *index.SymbolIndex) *TypeCompatibilityChecker
NewTypeCompatibilityChecker creates a new TypeCompatibilityChecker.
Description:
Creates a checker that can analyze type compatibility using the code graph and symbol index.
Inputs:
g - The code graph. Must be frozen. idx - The symbol index.
Outputs:
*TypeCompatibilityChecker - The configured checker.
func (*TypeCompatibilityChecker) CheckCompatibility ¶
func (c *TypeCompatibilityChecker) CheckCompatibility( ctx context.Context, sourceType string, targetType string, ) (*TypeCompatibility, error)
CheckCompatibility checks if sourceType can be used where targetType is expected.
Description:
Analyzes whether a source type is compatible with a target type. Checks for direct assignment compatibility, interface satisfaction, and suggests conversions when applicable.
Inputs:
ctx - Context for cancellation. sourceType - The type you have (type name or full path). targetType - The type you need (type name or full path).
Outputs:
*TypeCompatibility - Compatibility analysis result. error - Non-nil if the analysis fails.
Example:
result, err := checker.CheckCompatibility(ctx, "*MyStruct", "io.Reader")
if result.Compatible {
fmt.Println("Types are compatible")
} else {
fmt.Printf("Incompatible: %s\n", result.Reason)
}
Limitations:
- Performs structural analysis only, not full semantic type checking
- May not detect all interface implementations
- Requires types to be present in the index
func (*TypeCompatibilityChecker) CheckInterfaceSatisfaction ¶
func (c *TypeCompatibilityChecker) CheckInterfaceSatisfaction( ctx context.Context, typeName string, interfaceName string, ) (*InterfaceSatisfaction, error)
CheckInterfaceSatisfaction checks if a type satisfies an interface.
Description:
Determines whether a concrete type implements all methods required by an interface. Uses the code graph to find method definitions.
Inputs:
ctx - Context for cancellation. typeName - The concrete type to check. interfaceName - The interface to check against.
Outputs:
*InterfaceSatisfaction - Detailed satisfaction analysis. error - Non-nil if the analysis fails.
type TypeInfo ¶
type TypeInfo struct {
// Name is the type name (e.g., "string", "*User", "[]byte").
Name string `json:"name"`
// Package is the package path for qualified types.
// Empty for builtin types.
Package string `json:"package,omitempty"`
// IsPointer indicates if this is a pointer type.
IsPointer bool `json:"is_pointer,omitempty"`
// IsSlice indicates if this is a slice type.
IsSlice bool `json:"is_slice,omitempty"`
// IsMap indicates if this is a map type.
IsMap bool `json:"is_map,omitempty"`
// IsChannel indicates if this is a channel type.
IsChannel bool `json:"is_channel,omitempty"`
// IsVariadic indicates if this is a variadic parameter (...T).
IsVariadic bool `json:"is_variadic,omitempty"`
// ElementType is the element type for slices, arrays, maps, channels.
ElementType *TypeInfo `json:"element_type,omitempty"`
// KeyType is the key type for maps.
KeyType *TypeInfo `json:"key_type,omitempty"`
// TypeParams lists generic type parameters if any.
TypeParams []string `json:"type_params,omitempty"`
}
TypeInfo represents type information extracted from signatures.
type TypeMismatch ¶
type TypeMismatch struct {
// Location describes where the mismatch occurs.
Location string `json:"location"`
// Expected is the type that was expected.
Expected string `json:"expected"`
// Got is the type that was found.
Got string `json:"got"`
// Suggestion is how to fix the mismatch.
Suggestion string `json:"suggestion,omitempty"`
}
TypeMismatch describes a type incompatibility.
type TypeParamInfo ¶
type TypeParamInfo struct {
// Name is the type parameter name (e.g., "T", "K").
Name string `json:"name"`
// Constraint is the type constraint (e.g., "any", "comparable").
Constraint string `json:"constraint,omitempty"`
}
TypeParamInfo represents a generic type parameter.
type TypeReference ¶
TypeReference represents a type reference found in code.
type ValidationError ¶
type ValidationError struct {
// Type categorizes the error.
Type string `json:"type"` // syntax, type_ref, import
// Message describes the error.
Message string `json:"message"`
// Line is the line number (1-indexed).
Line int `json:"line"`
// Column is the column number (0-indexed).
Column int `json:"column"`
// Severity is the error severity.
Severity string `json:"severity"` // error, warning
}
ValidationError describes a validation error.
type ValidationWarning ¶
type ValidationWarning struct {
// Type categorizes the warning.
Type string `json:"type"`
// Message describes the warning.
Message string `json:"message"`
// Line is the line number (1-indexed).
Line int `json:"line"`
}
ValidationWarning describes a non-fatal issue.