context

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 31, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

Documentation

Overview

Package context defines domain entities for the Proactive Context Engine. The engine automatically injects relevant memory facts into every tool response, ensuring the LLM always has context without explicitly requesting it.

Index

Constants

View Source
const (
	DefaultTokenBudget     = 300  // tokens reserved for context injection
	DefaultMaxFacts        = 10   // max facts per context frame
	DefaultRecencyWeight   = 0.25 // weight for time-based recency scoring
	DefaultFrequencyWeight = 0.15 // weight for access frequency scoring
	DefaultLevelWeight     = 0.30 // weight for hierarchy level scoring (L0 > L3)
	DefaultKeywordWeight   = 0.30 // weight for keyword match scoring
	DefaultDecayHalfLife   = 72.0 // hours until unused fact score halves
)

Default configuration values.

Variables

This section is empty.

Functions

func DefaultSkipTools

func DefaultSkipTools() []string

DefaultSkipTools returns the default list of tools excluded from context injection. These are tools that already return facts directly or system tools where context is noise.

func EstimateTokenCount

func EstimateTokenCount(text string) int

EstimateTokenCount returns an approximate token count for the given text. Uses the heuristic of ~4 characters per token, with a minimum of 1.

func ExtractKeywords

func ExtractKeywords(text string) []string

ExtractKeywords extracts meaningful keywords from text, filtering stop words and short tokens. Splits camelCase and snake_case identifiers. Returns deduplicated lowercase keywords.

Types

type ContextFrame

type ContextFrame struct {
	ToolName    string        `json:"tool_name"`
	TokenBudget int           `json:"token_budget"`
	Facts       []*ScoredFact `json:"facts"`
	TokensUsed  int           `json:"tokens_used"`
	CreatedAt   time.Time     `json:"created_at"`
}

ContextFrame holds the selected facts for injection into a single tool response.

func NewContextFrame

func NewContextFrame(toolName string, tokenBudget int) *ContextFrame

NewContextFrame creates an empty context frame for the given tool.

func (*ContextFrame) AddFact

func (cf *ContextFrame) AddFact(sf *ScoredFact) bool

AddFact attempts to add a scored fact to the frame within the token budget. Returns true if the fact was added, false if it would exceed the budget.

func (*ContextFrame) Format

func (cf *ContextFrame) Format() string

Format renders the context frame as a text block for injection into tool results. Returns empty string if no facts are present.

func (*ContextFrame) RemainingTokens

func (cf *ContextFrame) RemainingTokens() int

RemainingTokens returns how many tokens are left in the budget.

type EngineConfig

type EngineConfig struct {
	TokenBudget        int      `json:"token_budget"`
	MaxFacts           int      `json:"max_facts"`
	RecencyWeight      float64  `json:"recency_weight"`
	FrequencyWeight    float64  `json:"frequency_weight"`
	LevelWeight        float64  `json:"level_weight"`
	KeywordWeight      float64  `json:"keyword_weight"`
	DecayHalfLifeHours float64  `json:"decay_half_life_hours"`
	Enabled            bool     `json:"enabled"`
	SkipTools          []string `json:"skip_tools,omitempty"`
	// contains filtered or unexported fields
}

EngineConfig holds configuration for the Proactive Context Engine.

func DefaultEngineConfig

func DefaultEngineConfig() EngineConfig

DefaultEngineConfig returns sensible defaults for the context engine.

func (*EngineConfig) BuildSkipSet

func (c *EngineConfig) BuildSkipSet()

BuildSkipSet builds the O(1) lookup set from SkipTools slice. Must be called after deserialization or manual SkipTools changes.

func (*EngineConfig) ShouldSkip

func (c *EngineConfig) ShouldSkip(toolName string) bool

ShouldSkip returns true if the given tool name is in the skip list.

func (*EngineConfig) Validate

func (c *EngineConfig) Validate() error

Validate checks the configuration for errors.

type FactProvider

type FactProvider interface {
	// GetRelevantFacts returns facts potentially relevant to the given tool arguments.
	GetRelevantFacts(args map[string]interface{}) ([]*memory.Fact, error)

	// GetL0Facts returns all L0 (project-level) facts — always included in context.
	GetL0Facts() ([]*memory.Fact, error)

	// RecordAccess increments the access counter for a fact.
	RecordAccess(factID string)
}

FactProvider abstracts fact retrieval for the context engine. This decouples the engine from specific storage implementations.

type RelevanceScorer

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

RelevanceScorer computes relevance scores for facts based on multiple signals: keyword match, recency decay, access frequency, and hierarchy level.

func NewRelevanceScorer

func NewRelevanceScorer(cfg EngineConfig) *RelevanceScorer

NewRelevanceScorer creates a scorer with the given configuration.

func (*RelevanceScorer) RankFacts

func (rs *RelevanceScorer) RankFacts(facts []*memory.Fact, keywords []string, accessCounts map[string]int) []*ScoredFact

RankFacts scores and sorts all facts by relevance, filtering out archived ones. Returns ScoredFacts sorted by score descending.

func (*RelevanceScorer) ScoreFact

func (rs *RelevanceScorer) ScoreFact(fact *memory.Fact, keywords []string, accessCount int) float64

ScoreFact computes a composite relevance score for a single fact. Score is in [0.0, 1.0]. Archived facts always return 0.

type ScoredFact

type ScoredFact struct {
	Fact         *memory.Fact `json:"fact"`
	Score        float64      `json:"score"`
	AccessCount  int          `json:"access_count"`
	LastAccessed time.Time    `json:"last_accessed,omitempty"`
}

ScoredFact pairs a Fact with its computed relevance score and access metadata.

func NewScoredFact

func NewScoredFact(fact *memory.Fact, score float64) *ScoredFact

NewScoredFact creates a ScoredFact with the given score.

func (*ScoredFact) EstimateTokens

func (sf *ScoredFact) EstimateTokens() int

EstimateTokens returns an approximate token count for this fact's content. Uses the ~4 chars per token heuristic plus overhead for formatting.

func (*ScoredFact) RecordAccess

func (sf *ScoredFact) RecordAccess()

RecordAccess increments the access counter and updates the timestamp.

type TokenBudget

type TokenBudget struct {
	MaxTokens int `json:"max_tokens"`
	// contains filtered or unexported fields
}

TokenBudget tracks token consumption for context injection.

func NewTokenBudget

func NewTokenBudget(max int) *TokenBudget

NewTokenBudget creates a token budget with the given maximum. If max is <= 0, uses DefaultTokenBudget.

func (*TokenBudget) Remaining

func (tb *TokenBudget) Remaining() int

Remaining returns the number of tokens left.

func (*TokenBudget) Reset

func (tb *TokenBudget) Reset()

Reset resets the budget to full capacity.

func (*TokenBudget) TryConsume

func (tb *TokenBudget) TryConsume(n int) bool

TryConsume attempts to consume n tokens. Returns true if successful.

Jump to

Keyboard shortcuts

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