analyzer

package
v0.7.6 Latest Latest
Warning

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

Go to latest
Published: Mar 7, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const SpecBaselineFileName = ".fault-spec-baseline.json"

SpecBaselineFileName is the default filename for the spec baseline.

Variables

View Source
var CompliancePacks = map[string]CompliancePack{
	"owasp-top-10-2021": {
		ID:          "owasp-top-10-2021",
		Name:        "OWASP Top 10 (2021)",
		Description: "The OWASP Top 10 is a standard awareness document for web application security, representing the most critical security risks.",
		CWEIDs: []string{
			"CWE-79",
			"CWE-89",
			"CWE-22",
			"CWE-78",
			"CWE-94",
			"CWE-611",
			"CWE-502",
			"CWE-918",
			"CWE-601",
			"CWE-798",
			"CWE-327",
			"CWE-295",
			"CWE-330",
			"CWE-862",
			"CWE-863",
		},
	},
	"cwe-top-25-2023": {
		ID:          "cwe-top-25-2023",
		Name:        "CWE Top 25 (2023)",
		Description: "The CWE Top 25 Most Dangerous Software Weaknesses is a list of the most common and impactful software vulnerabilities.",
		CWEIDs: []string{
			"CWE-79",
			"CWE-89",
			"CWE-22",
			"CWE-78",
			"CWE-787",
			"CWE-416",
			"CWE-476",
			"CWE-20",
			"CWE-125",
			"CWE-190",
			"CWE-502",
			"CWE-798",
			"CWE-862",
			"CWE-863",
			"CWE-306",
			"CWE-434",
			"CWE-611",
			"CWE-918",
			"CWE-77",
			"CWE-362",
			"CWE-269",
			"CWE-94",
			"CWE-119",
			"CWE-276",
			"CWE-732",
		},
	},
}

CompliancePacks maps pack IDs to their definitions.

View Source
var IssueIDToCWE = map[string]string{

	"security-sql-injection":         "CWE-89",
	"security-xss":                   "CWE-79",
	"security-path-traversal":        "CWE-22",
	"security-hardcoded-credentials": "CWE-798",
	"security-weak-crypto":           "CWE-327",
	"security-command-injection":     "CWE-78",
	"security-code-injection":        "CWE-94",
	"security-xxe":                   "CWE-611",
	"security-deserialization":       "CWE-502",
	"security-ssrf":                  "CWE-918",
	"security-open-redirect":         "CWE-601",
	"security-weak-random":           "CWE-330",
	"security-insecure-tls":          "CWE-295",
	"security-sensitive-log":         "CWE-532",
	"security-eval":                  "CWE-95",
	"security-prototype-pollution":   "CWE-1321",
	"security-regex-dos":             "CWE-1333",
	"security-unsafe-reflection":     "CWE-470",

	"concurrency-race":              "CWE-362",
	"concurrency-deadlock":          "CWE-833",
	"resource-leak":                 "CWE-404",
	"resource-unclosed":             "CWE-404",
	"error-handling-unchecked":      "CWE-252",
	"error-handling-swallowed":      "CWE-390",
	"import-nonexistent":            "CWE-829",
	"complexity-high":               "CWE-1121",
	"hallucination-nonexistent-api": "CWE-476",
}

IssueIDToCWE maps a Fault issue ID to its CWE ID, if known. This duplicates the mapping from reporter/sarif.go for use by the analyzer package.

Functions

func AugmentSpecContent added in v0.7.5

func AugmentSpecContent(specContent string, baseline *SpecBaseline) string

AugmentSpecContent appends an "Already Implemented" section to the spec content listing items from the baseline. Returns spec unchanged if baseline is nil or empty.

func FilterSpecUnexpected added in v0.7.5

func FilterSpecUnexpected(unexpected []string, baseline *SpecBaseline) []string

FilterSpecUnexpected removes unexpected items that match accepted entries in the baseline. Uses bidirectional strings.Contains fuzzy matching (same as matchesBaseline).

func MatchBaselineToRequirements added in v0.7.6

func MatchBaselineToRequirements(baseline *SpecBaseline, reqIDs []string, reqDescs []string) map[string]bool

MatchBaselineToRequirements fuzzy-matches baseline Implemented strings against requirement descriptions. Returns a set of matched requirement IDs.

func MergeAcceptedUnexpected added in v0.7.5

func MergeAcceptedUnexpected(baseline *SpecBaseline, newItems []string) int

MergeAcceptedUnexpected adds new items to the baseline's AcceptedUnexpected list, deduplicating by case-insensitive exact match. Returns the number of new items added.

func MergeImplemented added in v0.7.5

func MergeImplemented(baseline *SpecBaseline, newItems []string) int

MergeImplemented adds new items to the baseline's Implemented list, deduplicating by case-insensitive exact match. Returns the number of new items added.

func ParseSuppressionComments

func ParseSuppressionComments(line string) []string

ParseSuppressionComments parses a line for fault:ignore directives. Returns the list of suppressed categories, or ["*"] for suppress-all. Returns nil if no suppression directive is found.

func SaveBaseline

func SaveBaseline(path string, result *AnalysisResult) error

SaveBaseline saves the current issues as a baseline file.

func SaveSpecBaseline added in v0.7.5

func SaveSpecBaseline(path string, baseline *SpecBaseline) error

SaveSpecBaseline writes the spec baseline to a JSON file.

Types

type AnalysisContext

type AnalysisContext struct {
	RepoPath    string
	Diff        *git.Diff
	ParsedFiles map[string]*parser.ParsedFile
	Config      *config.Config
	Index       *index.Index // Full repo index (may be nil if index build fails)
}

AnalysisContext provides data to analyzers.

type AnalysisResult

type AnalysisResult struct {
	RepoPath     string        `json:"repo_path"`
	Branch       string        `json:"branch"`
	CommitRange  string        `json:"commit_range"`
	Timestamp    time.Time     `json:"timestamp"`
	Duration     time.Duration `json:"duration"`
	FilesChanged int           `json:"files_changed"`
	Issues       []Issue       `json:"issues"`
	Confidence   *Confidence   `json:"confidence,omitempty"`
	Summary      string        `json:"summary,omitempty"`
}

AnalysisResult holds the complete output of a fault check run.

func (*AnalysisResult) ErrorCount

func (r *AnalysisResult) ErrorCount() int

ErrorCount returns the number of error-severity issues.

func (*AnalysisResult) InfoCount

func (r *AnalysisResult) InfoCount() int

InfoCount returns the number of info-severity issues.

func (*AnalysisResult) ShouldBlock

func (r *AnalysisResult) ShouldBlock(blockOn string) bool

ShouldBlock determines if the result should cause a non-zero exit code.

func (*AnalysisResult) WarningCount

func (r *AnalysisResult) WarningCount() int

WarningCount returns the number of warning-severity issues.

type Analyzer

type Analyzer interface {
	// Name returns the unique name of this analyzer.
	Name() string
	// Analyze runs the analyzer on the given context and returns issues.
	Analyze(ctx *AnalysisContext) ([]Issue, error)
}

Analyzer is the interface all analyzers must implement.

type AntiPatternAnalyzer

type AntiPatternAnalyzer struct{}

AntiPatternAnalyzer detects common anti-patterns in added code.

func NewAntiPatternAnalyzer

func NewAntiPatternAnalyzer() *AntiPatternAnalyzer

NewAntiPatternAnalyzer creates a new anti-pattern analyzer.

func (*AntiPatternAnalyzer) Analyze

func (a *AntiPatternAnalyzer) Analyze(ctx *AnalysisContext) ([]Issue, error)

Analyze scans diff content for anti-patterns in added lines.

func (*AntiPatternAnalyzer) Name

func (a *AntiPatternAnalyzer) Name() string

Name returns the analyzer name.

type Baseline

type Baseline struct {
	Version int             `json:"version"`
	Issues  []BaselineEntry `json:"issues"`
}

Baseline holds a set of known issues to suppress.

func LoadBaseline

func LoadBaseline(path string) (*Baseline, error)

LoadBaseline loads a baseline from a JSON file.

type BaselineEntry

type BaselineEntry struct {
	ID       string `json:"id"`
	Category string `json:"category"`
	File     string `json:"file"`
	Message  string `json:"message"`
}

BaselineEntry represents a single suppressed issue.

type ComplexityAnalyzer

type ComplexityAnalyzer struct{}

ComplexityAnalyzer detects overly complex code that AI agents tend to generate: long functions, too many parameters, deep nesting, high cyclomatic complexity, and excessive return statements.

func NewComplexityAnalyzer

func NewComplexityAnalyzer() *ComplexityAnalyzer

NewComplexityAnalyzer creates a new complexity analyzer.

func (*ComplexityAnalyzer) Analyze

func (a *ComplexityAnalyzer) Analyze(ctx *AnalysisContext) ([]Issue, error)

Analyze runs all complexity checks on changed files.

func (*ComplexityAnalyzer) Name

func (a *ComplexityAnalyzer) Name() string

Name returns the analyzer name.

type CompliancePack added in v0.7.0

type CompliancePack struct {
	ID          string // e.g., "owasp-top-10-2021"
	Name        string // e.g., "OWASP Top 10 (2021)"
	Description string
	CWEIDs      []string // e.g., ["CWE-79", "CWE-89", ...]
}

CompliancePack defines a set of CWE IDs that map to a compliance standard.

type ComplianceResult added in v0.7.0

type ComplianceResult struct {
	PackID       string                `json:"pack_id"`
	PackName     string                `json:"pack_name"`
	TotalCWEs    int                   `json:"total_cwes"`
	ViolatedCWEs int                   `json:"violated_cwes"`
	Violations   []ComplianceViolation `json:"violations"`
	Compliant    bool                  `json:"compliant"`
}

ComplianceResult summarizes compliance check findings.

func CheckCompliance added in v0.7.0

func CheckCompliance(packID string, issues []Issue) (*ComplianceResult, error)

CheckCompliance runs compliance checking against analysis results.

type ComplianceViolation added in v0.7.0

type ComplianceViolation struct {
	CWEID   string `json:"cwe_id"`
	IssueID string `json:"issue_id"`
	Count   int    `json:"count"`
}

ComplianceViolation records a specific CWE violated by issues.

type ConcurrencyAnalyzer

type ConcurrencyAnalyzer struct{}

ConcurrencyAnalyzer detects concurrency safety issues in added code.

func NewConcurrencyAnalyzer

func NewConcurrencyAnalyzer() *ConcurrencyAnalyzer

NewConcurrencyAnalyzer creates a new concurrency analyzer.

func (*ConcurrencyAnalyzer) Analyze

func (a *ConcurrencyAnalyzer) Analyze(ctx *AnalysisContext) ([]Issue, error)

Analyze scans diff content for concurrency anti-patterns in added lines.

func (*ConcurrencyAnalyzer) Name

func (a *ConcurrencyAnalyzer) Name() string

Name returns the analyzer name.

type Confidence

type Confidence struct {
	Score   float64            `json:"score"`
	Factors []string           `json:"factors,omitempty"`
	PerFile map[string]float64 `json:"per_file,omitempty"`
}

Confidence represents how confident the analysis is.

type ConsistencyAnalyzer

type ConsistencyAnalyzer struct{}

ConsistencyAnalyzer checks for cross-file consistency issues such as changed function signatures without updated callers, changed type definitions, and interface/implementation gaps.

func NewConsistencyAnalyzer

func NewConsistencyAnalyzer() *ConsistencyAnalyzer

NewConsistencyAnalyzer creates a new cross-file consistency analyzer.

func (*ConsistencyAnalyzer) Analyze

func (a *ConsistencyAnalyzer) Analyze(ctx *AnalysisContext) ([]Issue, error)

Analyze runs cross-file consistency checks on the analysis context.

func (*ConsistencyAnalyzer) Name

func (a *ConsistencyAnalyzer) Name() string

Name returns the analyzer name.

type CustomRuleAnalyzer added in v0.7.0

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

CustomRuleAnalyzer checks files against user-defined regex patterns.

func NewCustomRuleAnalyzer added in v0.7.0

func NewCustomRuleAnalyzer(rules []CustomRuleConfig) *CustomRuleAnalyzer

NewCustomRuleAnalyzer creates a new custom rule analyzer.

func (*CustomRuleAnalyzer) Analyze added in v0.7.0

func (a *CustomRuleAnalyzer) Analyze(ctx *AnalysisContext) ([]Issue, error)

Analyze checks parsed files against custom rules.

func (*CustomRuleAnalyzer) Name added in v0.7.0

func (a *CustomRuleAnalyzer) Name() string

Name returns the analyzer name.

type CustomRuleConfig added in v0.7.0

type CustomRuleConfig struct {
	ID       string
	Pattern  string // regex
	Files    string // glob
	Severity string // error, warning, info
	Message  string
}

CustomRuleConfig defines a single custom rule from config.

type DeadCodeAnalyzer

type DeadCodeAnalyzer struct{}

DeadCodeAnalyzer detects exported symbols that are never imported anywhere in the codebase, leveraging the full repo Index.

func NewDeadCodeAnalyzer

func NewDeadCodeAnalyzer() *DeadCodeAnalyzer

NewDeadCodeAnalyzer creates a new dead code analyzer.

func (*DeadCodeAnalyzer) Analyze

func (a *DeadCodeAnalyzer) Analyze(ctx *AnalysisContext) ([]Issue, error)

Analyze scans exported symbols in changed files and reports any that have no importers anywhere in the index.

func (*DeadCodeAnalyzer) Name

func (a *DeadCodeAnalyzer) Name() string

Name returns the analyzer name.

type DepGraphAnalyzer

type DepGraphAnalyzer struct{}

DepGraphAnalyzer detects circular dependencies and unused manifest dependencies.

func NewDepGraphAnalyzer

func NewDepGraphAnalyzer() *DepGraphAnalyzer

NewDepGraphAnalyzer creates a new dependency graph analyzer.

func (*DepGraphAnalyzer) Analyze

func (a *DepGraphAnalyzer) Analyze(ctx *AnalysisContext) ([]Issue, error)

Analyze builds a dependency graph from the index and checks for circular dependencies and unused manifest dependencies.

func (*DepGraphAnalyzer) Name

func (a *DepGraphAnalyzer) Name() string

Name returns the analyzer name.

type DocDriftAnalyzer

type DocDriftAnalyzer struct{}

DocDriftAnalyzer detects stale comments and documentation that no longer match the function signatures they describe. This is one of the most common AI agent tells: modifying function signatures while leaving the docstring unchanged.

func NewDocDriftAnalyzer

func NewDocDriftAnalyzer() *DocDriftAnalyzer

NewDocDriftAnalyzer creates a new doc drift analyzer.

func (*DocDriftAnalyzer) Analyze

func (a *DocDriftAnalyzer) Analyze(ctx *AnalysisContext) ([]Issue, error)

Analyze runs doc drift detection on the analysis context.

func (*DocDriftAnalyzer) Name

func (a *DocDriftAnalyzer) Name() string

Name returns the analyzer name.

type ErrorHandlingAnalyzer

type ErrorHandlingAnalyzer struct{}

ErrorHandlingAnalyzer detects poor error handling patterns in added code.

func NewErrorHandlingAnalyzer

func NewErrorHandlingAnalyzer() *ErrorHandlingAnalyzer

NewErrorHandlingAnalyzer creates a new error handling analyzer.

func (*ErrorHandlingAnalyzer) Analyze

func (a *ErrorHandlingAnalyzer) Analyze(ctx *AnalysisContext) ([]Issue, error)

Analyze scans diff content for error handling anti-patterns in added lines.

func (*ErrorHandlingAnalyzer) Name

func (a *ErrorHandlingAnalyzer) Name() string

Name returns the analyzer name.

type HallucinationAnalyzer

type HallucinationAnalyzer struct{}

HallucinationAnalyzer detects AI hallucinations: phantom imports, stub implementations, and references to nonexistent files.

func NewHallucinationAnalyzer

func NewHallucinationAnalyzer() *HallucinationAnalyzer

NewHallucinationAnalyzer creates a new hallucination analyzer.

func (*HallucinationAnalyzer) Analyze

func (h *HallucinationAnalyzer) Analyze(ctx *AnalysisContext) ([]Issue, error)

Analyze scans the diff for phantom imports, stub functions, and missing file references.

func (*HallucinationAnalyzer) Name

func (h *HallucinationAnalyzer) Name() string

Name returns the analyzer name.

type ImportAnalyzer

type ImportAnalyzer struct{}

ImportAnalyzer checks for broken imports, removed exports still imported, and missing external dependencies across changed files.

func NewImportAnalyzer

func NewImportAnalyzer() *ImportAnalyzer

NewImportAnalyzer creates a new import/export analyzer.

func (*ImportAnalyzer) Analyze

func (a *ImportAnalyzer) Analyze(ctx *AnalysisContext) ([]Issue, error)

Analyze runs import/export validation on the analysis context.

func (*ImportAnalyzer) Name

func (a *ImportAnalyzer) Name() string

Name returns the analyzer name.

type Issue

type Issue struct {
	ID           string   `json:"id"`
	FixID        string   `json:"fix_id,omitempty"` // stable category ID for auto-fix matching
	Severity     Severity `json:"severity"`
	Category     string   `json:"category"`
	File         string   `json:"file"`
	Line         int      `json:"line,omitempty"`
	EndLine      int      `json:"end_line,omitempty"`
	Message      string   `json:"message"`
	Suggestion   string   `json:"suggestion,omitempty"`
	RelatedFiles []string `json:"related_files,omitempty"`
}

Issue represents a single problem found by an analyzer.

func FilterBaseline

func FilterBaseline(issues []Issue, baseline *Baseline) []Issue

FilterBaseline removes issues that match baseline entries, returning only new issues. Matching is by category + file + fuzzy message match (baseline IDs are treated as best-effort, because many issue IDs embed line numbers which shift as code changes).

func FilterSuppressed

func FilterSuppressed(issues []Issue, fileLines map[string][]string) []Issue

FilterSuppressed removes issues that are suppressed by inline comments. For each issue at line N, it checks if line N-1 or line N contains a fault:ignore directive matching the issue's category.

type MigrationAnalyzer

type MigrationAnalyzer struct{}

MigrationAnalyzer detects dangerous database migration operations in diff hunks.

func NewMigrationAnalyzer

func NewMigrationAnalyzer() *MigrationAnalyzer

NewMigrationAnalyzer creates a new migration safety analyzer.

func (*MigrationAnalyzer) Analyze

func (a *MigrationAnalyzer) Analyze(ctx *AnalysisContext) ([]Issue, error)

Analyze scans changed migration files for destructive or risky operations.

func (*MigrationAnalyzer) Name

func (a *MigrationAnalyzer) Name() string

Name returns the analyzer name.

type ReferenceAnalyzer

type ReferenceAnalyzer struct{}

ReferenceAnalyzer checks for broken references caused by deleted or renamed files and removed symbols.

func NewReferenceAnalyzer

func NewReferenceAnalyzer() *ReferenceAnalyzer

NewReferenceAnalyzer creates a new broken reference analyzer.

func (*ReferenceAnalyzer) Analyze

func (a *ReferenceAnalyzer) Analyze(ctx *AnalysisContext) ([]Issue, error)

Analyze runs broken reference checks on the analysis context.

func (*ReferenceAnalyzer) Name

func (a *ReferenceAnalyzer) Name() string

Name returns the analyzer name.

type ResourceAnalyzer

type ResourceAnalyzer struct{}

ResourceAnalyzer detects resource leaks in added code.

func NewResourceAnalyzer

func NewResourceAnalyzer() *ResourceAnalyzer

NewResourceAnalyzer creates a new resource leak analyzer.

func (*ResourceAnalyzer) Analyze

func (a *ResourceAnalyzer) Analyze(ctx *AnalysisContext) ([]Issue, error)

Analyze scans diff content for resource leak patterns in added lines.

func (*ResourceAnalyzer) Name

func (a *ResourceAnalyzer) Name() string

Name returns the analyzer name.

type Runner

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

Runner orchestrates running all enabled analyzers.

func NewRunner

func NewRunner(cfg *config.Config, analyzers []Analyzer) *Runner

NewRunner creates a runner with the given analyzers and config.

func (*Runner) Run

func (r *Runner) Run(repoPath string, diff *git.Diff, parsedFiles map[string]*parser.ParsedFile, idx *index.Index) *AnalysisResult

Run executes all enabled analyzers and returns the combined result.

type SecurityAnalyzer

type SecurityAnalyzer struct{}

SecurityAnalyzer detects OWASP-style vulnerabilities in added code.

func NewSecurityAnalyzer

func NewSecurityAnalyzer() *SecurityAnalyzer

NewSecurityAnalyzer creates a new security analyzer.

func (*SecurityAnalyzer) Analyze

func (a *SecurityAnalyzer) Analyze(ctx *AnalysisContext) ([]Issue, error)

Analyze scans diff content for security vulnerabilities in added lines.

func (*SecurityAnalyzer) Name

func (a *SecurityAnalyzer) Name() string

Name returns the analyzer name.

type Severity

type Severity string

Severity represents the severity level of an issue.

const (
	SeverityError   Severity = "error"
	SeverityWarning Severity = "warning"
	SeverityInfo    Severity = "info"
)

type SpecAnalyzer

type SpecAnalyzer struct{}

SpecAnalyzer validates code against a .fault-spec.yaml specification file. It checks for orphaned anchors, unanchored requirements, modified anchored code, and target mismatches.

func NewSpecAnalyzer

func NewSpecAnalyzer() *SpecAnalyzer

NewSpecAnalyzer creates a new spec validation analyzer.

func (*SpecAnalyzer) Analyze

func (a *SpecAnalyzer) Analyze(ctx *AnalysisContext) ([]Issue, error)

Analyze runs spec validation on the given context.

func (*SpecAnalyzer) Name

func (a *SpecAnalyzer) Name() string

Name returns the analyzer name.

type SpecBaseline added in v0.7.5

type SpecBaseline struct {
	Version            int       `json:"version"`
	SpecFile           string    `json:"spec_file"`
	Implemented        []string  `json:"implemented"`
	AcceptedUnexpected []string  `json:"accepted_unexpected"`
	UpdatedAt          time.Time `json:"updated_at"`
}

SpecBaseline tracks which spec requirements have already been implemented.

func LoadSpecBaseline added in v0.7.5

func LoadSpecBaseline(path string) (*SpecBaseline, error)

LoadSpecBaseline loads a spec baseline from a JSON file. Returns nil, nil if the file does not exist.

type TestImpactAnalyzer

type TestImpactAnalyzer struct{}

TestImpactAnalyzer checks whether changed source files have corresponding test coverage.

func NewTestImpactAnalyzer

func NewTestImpactAnalyzer() *TestImpactAnalyzer

NewTestImpactAnalyzer creates a new test impact analyzer.

func (*TestImpactAnalyzer) Analyze

func (a *TestImpactAnalyzer) Analyze(ctx *AnalysisContext) ([]Issue, error)

Analyze checks that source file changes have corresponding test file changes.

func (*TestImpactAnalyzer) Name

func (a *TestImpactAnalyzer) Name() string

Name returns the analyzer name.

Jump to

Keyboard shortcuts

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