scoring

package
v1.9.0 Latest Latest
Warning

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

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

Documentation

Overview

Package scoring provides importance score calculation for observations.

Package scoring provides importance score calculation for observations.

Package scoring provides importance score calculation for observations.

Package scoring provides importance and relevance score calculation for observations.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Calculator

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

Calculator computes importance scores for observations.

func NewCalculator

func NewCalculator(config *models.ScoringConfig) *Calculator

NewCalculator creates a new scoring calculator. If config is nil, uses the default configuration.

func (*Calculator) BatchCalculate

func (c *Calculator) BatchCalculate(observations []*models.Observation, now time.Time) map[int64]float64

BatchCalculate computes scores for multiple observations. Returns a map of observation ID to calculated score.

func (*Calculator) Calculate

func (c *Calculator) Calculate(obs *models.Observation, now time.Time) float64

Calculate computes the importance score for an observation at the given time.

The scoring formula:

FinalScore = (BaseScore × TypeWeight × RecencyDecay) + FeedbackContrib + ConceptContrib + RetrievalContrib + UtilityContrib

Where:

  • BaseScore = 1.0
  • TypeWeight = observation type multiplier (e.g., bugfix=1.3, change=0.9)
  • RecencyDecay = 0.5^(age_days / half_life_days) - halves every 7 days by default
  • FeedbackContrib = user_feedback × feedback_weight
  • ConceptContrib = sum(concept_weights) × concept_weight_factor
  • RetrievalContrib = log2(retrieval_count + 1) × 0.1 × retrieval_weight

func (*Calculator) CalculateComponents

func (c *Calculator) CalculateComponents(obs *models.Observation, now time.Time) ScoreComponents

CalculateComponents returns the individual components of the importance score. Useful for debugging and explaining scores to users. This is the core calculation method - Calculate() delegates to this.

func (*Calculator) GetConfig

func (c *Calculator) GetConfig() *models.ScoringConfig

GetConfig returns the current scoring configuration.

func (*Calculator) RecalculateThreshold

func (c *Calculator) RecalculateThreshold() time.Duration

RecalculateThreshold returns the minimum duration before an observation should have its score recalculated. This prevents excessive recalculation while ensuring scores stay reasonably fresh.

func (*Calculator) UpdateConfig

func (c *Calculator) UpdateConfig(config *models.ScoringConfig)

UpdateConfig updates the calculator's scoring configuration. This allows runtime tuning of scoring parameters.

type EffectivenessResult added in v1.9.0

type EffectivenessResult struct {
	ObservationID int64   `json:"observation_id"`
	Injections    int     `json:"injections"`
	Successes     int     `json:"successes"`
	Effectiveness float64 `json:"effectiveness"`
	MinData       bool    `json:"min_data"` // true when injections >= 10
}

EffectivenessResult contains effectiveness data for an observation.

func ComputeEffectiveness added in v1.9.0

func ComputeEffectiveness(obsID int64, injections, successes int) EffectivenessResult

ComputeEffectiveness calculates effectiveness from stored counters. When injections is 0, effectiveness is 0 and MinData is false.

type ObservationStore

type ObservationStore interface {
	GetObservationsNeedingScoreUpdate(ctx context.Context, threshold time.Duration, limit int) ([]*models.Observation, error)
	UpdateImportanceScores(ctx context.Context, scores map[int64]float64) error
	GetConceptWeights(ctx context.Context) (map[string]float64, error)
}

ObservationStore defines the interface for observation storage operations needed by the recalculator.

type Recalculator

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

Recalculator periodically recalculates importance scores for observations.

func NewRecalculator

func NewRecalculator(store ObservationStore, calc *Calculator, log zerolog.Logger) *Recalculator

NewRecalculator creates a new background recalculator.

func (*Recalculator) GetStats

func (r *Recalculator) GetStats() Stats

GetStats returns current recalculator statistics.

func (*Recalculator) RecalculateNow

func (r *Recalculator) RecalculateNow(ctx context.Context) error

RecalculateNow triggers an immediate recalculation. This is useful for testing or when scores need to be updated urgently.

func (*Recalculator) RefreshConceptWeights

func (r *Recalculator) RefreshConceptWeights(ctx context.Context) error

RefreshConceptWeights reloads concept weights from the database. Call this after updating concept weights to apply changes.

func (*Recalculator) Start

func (r *Recalculator) Start(ctx context.Context)

Start begins the background recalculation loop. This should be called in a goroutine.

func (*Recalculator) Stop

func (r *Recalculator) Stop()

Stop stops the background recalculation loop.

type RelevanceCalculator

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

RelevanceCalculator computes relevance scores using the automem-inspired formula.

func NewRelevanceCalculator

func NewRelevanceCalculator(config *RelevanceConfig) *RelevanceCalculator

NewRelevanceCalculator creates a new relevance calculator.

func (*RelevanceCalculator) CalculateComponents

func (r *RelevanceCalculator) CalculateComponents(params RelevanceParams) RelevanceComponents

CalculateComponents returns the individual components of the relevance calculation.

func (*RelevanceCalculator) CalculateRelevance

func (r *RelevanceCalculator) CalculateRelevance(params RelevanceParams) float64

CalculateRelevance computes the relevance score for an observation.

Formula:

decayFactor   = exp(-baseDecayRate * ageDays)
accessFactor  = exp(-accessDecayRate * accessRecencyDays)
relFactor     = 1.0 + relationWeight * log1p(relCount)
relevance     = decayFactor * (0.3 + 0.3*accessFactor) * relFactor * (0.5 + importance) * (0.7 + 0.3*confidence)

func (*RelevanceCalculator) GetConfig

func (r *RelevanceCalculator) GetConfig() *RelevanceConfig

GetConfig returns the current relevance configuration.

type RelevanceComponents

type RelevanceComponents struct {
	DecayFactor      float64 `json:"decay_factor"`
	AccessFactor     float64 `json:"access_factor"`
	RelationFactor   float64 `json:"relation_factor"`
	ImportanceFactor float64 `json:"importance_factor"`
	ConfidenceFactor float64 `json:"confidence_factor"`
	FinalRelevance   float64 `json:"final_relevance"`
}

RelevanceComponents returns a breakdown of the relevance calculation.

type RelevanceConfig

type RelevanceConfig struct {
	// BaseDecayRate controls how fast relevance drops with age (default 0.1).
	BaseDecayRate float64 `json:"base_decay_rate"`
	// AccessDecayRate controls the access recency weight (default 0.05).
	AccessDecayRate float64 `json:"access_decay_rate"`
	// RelationWeight scales the relation count bonus (default 0.3).
	RelationWeight float64 `json:"relation_weight"`
	// MinRelevance is the floor value for relevance scores (default 0.001).
	MinRelevance float64 `json:"min_relevance"`
}

RelevanceConfig contains parameters for the relevance score formula.

func DefaultRelevanceConfig

func DefaultRelevanceConfig() *RelevanceConfig

DefaultRelevanceConfig returns the default relevance configuration.

type RelevanceParams

type RelevanceParams struct {
	// AgeDays is the number of days since the observation was created.
	AgeDays float64
	// AccessRecencyDays is days since last retrieval. If never accessed, use AgeDays.
	AccessRecencyDays float64
	// RelationCount is the total number of inbound + outbound relations.
	RelationCount int
	// ImportanceScore is the existing importance score (typically 0-2 range).
	ImportanceScore float64
	// AvgRelConfidence is the average confidence of this observation's relations (default 0.5).
	AvgRelConfidence float64
}

RelevanceParams contains input parameters for relevance calculation.

type ScoreComponents

type ScoreComponents struct {
	TypeWeight           float64 `json:"type_weight"`
	RecencyDecay         float64 `json:"recency_decay"`
	SourcePenalty        float64 `json:"source_penalty"`
	CoreScore            float64 `json:"core_score"`
	FeedbackContrib      float64 `json:"feedback_contrib"`
	ConceptContrib       float64 `json:"concept_contrib"`
	RetrievalContrib     float64 `json:"retrieval_contrib"`
	UtilityContrib       float64 `json:"utility_contrib"`
	EffectivenessContrib float64 `json:"effectiveness_contrib"`
	FinalScore           float64 `json:"final_score"`
	AgeDays              float64 `json:"age_days"`
}

ScoreComponents contains the breakdown of an importance score calculation.

type Stats

type Stats struct {
	Running     bool          `json:"running"`
	Interval    time.Duration `json:"interval"`
	BatchSize   int           `json:"batch_size"`
	HalfLife    float64       `json:"half_life_days"`
	MinScore    float64       `json:"min_score"`
	ConceptsLen int           `json:"concepts_count"`
}

Stats returns statistics about the recalculator.

Jump to

Keyboard shortcuts

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