history

package
v1.0.8 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package history provides persistent storage for analysis results over time. This enables blast radius trends, hotspot evolution, and coupling drift tracking.

History is stored in a separate SQLite database (.contextception/history.sqlite) to keep it independent from the index, which gets rebuilt frequently.

Index

Constants

View Source
const CurrentScoreVersion = 1

CurrentScoreVersion is the current risk score formula version. Bump this when the scoring formula changes to invalidate old percentiles.

View Source
const HistoryFile = "history.sqlite"

HistoryFile is the filename of the history database.

Variables

This section is empty.

Functions

func FormatAccuracySummary added in v1.0.7

func FormatAccuracySummary(metrics *AccuracyMetrics, lowestRated []RatedAnalysis) string

FormatAccuracySummary produces the human-readable accuracy dashboard text.

func FormatGainSummary added in v1.0.7

func FormatGainSummary(summary *UsageSummary, topFiles []TopFile, daily []UsagePeriod) string

FormatGainSummary produces the human-readable gain dashboard text.

func HistoryPath

func HistoryPath(repoRoot string) string

HistoryPath returns the path to the history database for a repo.

Types

type AccuracyExport added in v1.0.7

type AccuracyExport struct {
	Metrics     *AccuracyMetrics `json:"metrics"`
	LowestRated []RatedAnalysis  `json:"lowest_rated,omitempty"`
}

AccuracyExport represents the full accuracy export for JSON output.

type AccuracyMetrics added in v1.0.7

type AccuracyMetrics struct {
	TotalRatings         int     `json:"total_ratings"`
	AvgUsefulness        float64 `json:"avg_usefulness"`
	MustReadPrecision    float64 `json:"must_read_precision"`
	MustReadRecall       float64 `json:"must_read_recall"`
	LikelyModifyAccuracy float64 `json:"likely_modify_accuracy"`
}

AccuracyMetrics contains precision/recall metrics computed from feedback.

type BlastDistribution

type BlastDistribution struct {
	Level   string  `json:"level"`
	Count   int     `json:"count"`
	Percent float64 `json:"percent"`
}

BlastDistribution shows what percentage of runs had each blast level.

type BlastRadiusTrend

type BlastRadiusTrend struct {
	Date   string `json:"date"`
	Level  string `json:"level"`
	Files  int    `json:"files"`
	Branch string `json:"branch,omitempty"`
}

BlastRadiusTrend returns blast radius levels over time.

type FeedbackEntry added in v1.0.7

type FeedbackEntry struct {
	FilePath         string   `json:"file_path"`
	Usefulness       int      `json:"usefulness"`
	UsefulFiles      []string `json:"useful_files,omitempty"`
	UnnecessaryFiles []string `json:"unnecessary_files,omitempty"`
	MissingFiles     []string `json:"missing_files,omitempty"`
	ModifiedFiles    []string `json:"modified_files,omitempty"`
	Notes            string   `json:"notes,omitempty"`
}

FeedbackEntry represents a single feedback record from the LLM.

type FileRiskHistory

type FileRiskHistory struct {
	Date       string `json:"date"`
	BlastLevel string `json:"blast_level"`
	Status     string `json:"status"`
}

FileRiskHistory shows how a file's blast radius has changed over time.

type GainExport added in v1.0.7

type GainExport struct {
	Summary  *UsageSummary `json:"summary"`
	TopFiles []TopFile     `json:"top_files"`
	Daily    []UsagePeriod `json:"daily,omitempty"`
	Weekly   []UsagePeriod `json:"weekly,omitempty"`
	Monthly  []UsagePeriod `json:"monthly,omitempty"`
}

GainExport represents the full analytics export for JSON/CSV output.

type HotspotFrequency

type HotspotFrequency struct {
	File     string `json:"file"`
	Count    int    `json:"count"`
	LastSeen string `json:"last_seen"`
}

HotspotFrequency represents how often a file appears as a hotspot.

type RatedAnalysis added in v1.0.7

type RatedAnalysis struct {
	FilePath   string `json:"file_path"`
	Usefulness int    `json:"usefulness"`
	Notes      string `json:"notes,omitempty"`
	CreatedAt  string `json:"created_at"`
}

RatedAnalysis represents a feedback entry with its rating for display.

type RiskScoreEntry added in v1.0.7

type RiskScoreEntry struct {
	FilePath  string
	RiskScore int
	RefRange  string
}

RiskScoreEntry holds data for a single risk score record.

type Store

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

Store manages the historical analysis database.

func Open

func Open(repoRoot string) (*Store, error)

Open opens or creates the history database.

func (*Store) Close

func (s *Store) Close() error

Close closes the database.

func (*Store) ComputePercentile added in v1.0.7

func (s *Store) ComputePercentile(score int) (int, error)

ComputePercentile returns the percentile ranking for a given score. Returns 0 if fewer than minRecordsForPercentile records exist with the current score version.

func (*Store) FeedbackCount added in v1.0.7

func (s *Store) FeedbackCount() (int, error)

FeedbackCount returns the total number of feedback entries.

func (*Store) FilesWithUsage added in v1.0.7

func (s *Store) FilesWithUsage(since time.Time) (map[string]bool, error)

FilesWithUsage returns the set of files that have context analysis entries since the given time. Only includes analyze/get_context entries, not analyze_change (which lists changed files, not files whose dependency context was individually analyzed). This satisfies the session.UsageLogQuerier interface.

func (*Store) GetAccuracyMetrics added in v1.0.7

func (s *Store) GetAccuracyMetrics(since time.Time) (*AccuracyMetrics, error)

GetAccuracyMetrics computes precision/recall from feedback data.

func (*Store) GetBlastDistribution

func (s *Store) GetBlastDistribution(since time.Time) ([]BlastDistribution, error)

GetBlastDistribution returns the distribution of blast radius levels.

func (*Store) GetBlastRadiusTrend

func (s *Store) GetBlastRadiusTrend(limit int, branch string) ([]BlastRadiusTrend, error)

GetBlastRadiusTrend returns the last N analysis runs' blast radius.

func (*Store) GetFileRiskHistory

func (s *Store) GetFileRiskHistory(filePath string, limit int) ([]FileRiskHistory, error)

GetFileRiskHistory returns the risk history for a specific file.

func (*Store) GetHotspotEvolution

func (s *Store) GetHotspotEvolution(limit int, since time.Time) ([]HotspotFrequency, error)

GetHotspotEvolution returns files that appear most frequently as hotspots.

func (*Store) GetLowestRated added in v1.0.7

func (s *Store) GetLowestRated(since time.Time, limit int) ([]RatedAnalysis, error)

GetLowestRated returns the lowest-rated analyses.

func (*Store) GetTopFiles added in v1.0.7

func (s *Store) GetTopFiles(since time.Time, limit int) ([]TopFile, error)

GetTopFiles returns the most frequently analyzed files.

func (*Store) GetUsageByPeriod added in v1.0.7

func (s *Store) GetUsageByPeriod(period string, since time.Time, limit int) ([]UsagePeriod, error)

GetUsageByPeriod returns usage statistics grouped by the given period. period must be "day", "week", or "month".

func (*Store) GetUsageSummary added in v1.0.7

func (s *Store) GetUsageSummary(since time.Time) (*UsageSummary, error)

GetUsageSummary returns aggregate usage statistics since the given time.

func (*Store) RecordFeedback added in v1.0.7

func (s *Store) RecordFeedback(entry *FeedbackEntry) (int64, error)

RecordFeedback stores an LLM feedback entry, linking to the most recent usage_log for the file.

func (*Store) RecordRun

func (s *Store) RecordRun(report *model.ChangeReport, commitSHA, branch string) (int64, error)

RecordRun stores a change report in the history database.

func (*Store) RecordUsage added in v1.0.7

func (s *Store) RecordUsage(entry *UsageEntry) (int64, error)

RecordUsage stores a usage log entry.

func (*Store) RunCount

func (s *Store) RunCount() (int, error)

RunCount returns the total number of recorded runs.

func (*Store) StoreRiskScore added in v1.0.7

func (s *Store) StoreRiskScore(filePath string, riskScore int, refRange string) error

StoreRiskScore records a per-file risk score in the history database.

func (*Store) StoreRiskScores added in v1.0.7

func (s *Store) StoreRiskScores(scores []RiskScoreEntry) error

StoreRiskScores records multiple per-file risk scores in a single transaction.

func (*Store) UsageCount added in v1.0.7

func (s *Store) UsageCount() (int, error)

UsageCount returns the total number of usage log entries.

type TopFile added in v1.0.7

type TopFile struct {
	File     string `json:"file"`
	Count    int    `json:"count"`
	LastSeen string `json:"last_seen"`
}

TopFile represents a frequently analyzed file.

type UsageEntry added in v1.0.7

type UsageEntry struct {
	Source            string   // "mcp", "cli", "hook"
	Tool              string   // "get_context", "analyze", "analyze_change"
	FilesAnalyzed     []string // file paths analyzed
	MustReadCount     int
	LikelyModifyCount int
	TestCount         int
	BlastLevel        string
	Confidence        float64
	HasConfidence     bool // true for analyze/get_context, false for analyze_change
	ResponseTokens    int
	DurationMs        int64
	Mode              string
	TokenBudget       int
}

UsageEntry represents a single usage tracking record.

func UsageEntryFromAnalysis added in v1.0.7

func UsageEntryFromAnalysis(source, tool string, files []string, output *model.AnalysisOutput, durationMs int64, mode string, tokenBudget int) *UsageEntry

UsageEntryFromAnalysis creates a UsageEntry from an analysis output.

func UsageEntryFromChangeReport added in v1.0.7

func UsageEntryFromChangeReport(source string, files []string, report *model.ChangeReport, durationMs int64, mode string, tokenBudget int) *UsageEntry

UsageEntryFromChangeReport creates a UsageEntry from a change report.

type UsagePeriod added in v1.0.7

type UsagePeriod struct {
	Period        string  `json:"period"`
	Analyses      int     `json:"analyses"`
	Files         int     `json:"files"`
	AvgConfidence float64 `json:"avg_confidence"`
	AvgDurationMs float64 `json:"avg_duration_ms"`
}

UsagePeriod represents usage data for a time period.

type UsageSummary added in v1.0.7

type UsageSummary struct {
	ContextAnalyses  int            `json:"context_analyses"` // analyze + get_context
	ChangeAnalyses   int            `json:"change_analyses"`  // analyze_change
	TotalAnalyses    int            `json:"total_analyses"`   // all tools combined
	FilesAnalyzed    int            `json:"files_analyzed"`   // unique files from context analyses
	AvgConfidence    float64        `json:"avg_confidence"`   // from context analyses only (NULLs excluded)
	AvgDurationMs    float64        `json:"avg_duration_ms"`
	BlastLevelCounts map[string]int `json:"blast_level_counts"`
}

UsageSummary contains aggregate usage statistics.

Jump to

Keyboard shortcuts

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