learning

package
v0.0.0-...-8155ea7 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2026 License: GPL-2.0, GPL-3.0 Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MsPerDay = 24 * 60 * 60 * 1000

	// Default decay rate (Ebbinghaus-inspired)
	DefaultDecayRate = 0.05

	// Scoring weights
	WeightFTS5       = 0.4
	WeightTemporal   = 0.3
	WeightImportance = 0.3

	// Signal confidence levels
	ConfidencePositive   = 0.8
	ConfidenceNegative   = 0.85
	ConfidenceCorrection = 0.95
	ConfidenceImplicit   = 0.7
)

Constants for time calculations

Variables

This section is empty.

Functions

func DaysSince

func DaysSince(timestampMs int64) float64

DaysSince calculates days since a timestamp

func MaxFloat64

func MaxFloat64(a, b float64) float64

MaxFloat64 returns the maximum of two float64 values

func MinFloat64

func MinFloat64(a, b float64) float64

MinFloat64 returns the minimum of two float64 values

func MinInt

func MinInt(a, b int) int

MinInt returns the minimum of two integers

func MsToTime

func MsToTime(ms int64) time.Time

MsToTime converts milliseconds to time.Time

func NowMs

func NowMs() int64

NowMs returns current time in milliseconds

Types

type AgentIntegration

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

AgentIntegration wraps the learning engine for agent integration

func NewAgentIntegration

func NewAgentIntegration(engine *Engine, adaptiveMemory *adaptive_memory.Engine, userID string) *AgentIntegration

NewAgentIntegration creates a new agent integration wrapper

func (*AgentIntegration) AnalyzeConversation

func (a *AgentIntegration) AnalyzeConversation(
	userMessage string,
	assistantMessage string,
	history []Message,
	toolCalls []ToolCall,
	toolResults []ToolResult,
) AnalysisResult

AnalyzeConversation analyzes a conversation after response generation

func (*AgentIntegration) ApplySuggestion

func (a *AgentIntegration) ApplySuggestion(id string) bool

ApplySuggestion applies a suggestion

func (*AgentIntegration) BuildLearnedContextForPrompt

func (a *AgentIntegration) BuildLearnedContextForPrompt(query string) string

BuildLearnedContextForPrompt builds a context section for LLM prompts

func (*AgentIntegration) Close

func (a *AgentIntegration) Close() error

Close closes the integration

func (*AgentIntegration) DismissSuggestion

func (a *AgentIntegration) DismissSuggestion(id string) bool

DismissSuggestion dismisses a suggestion

func (*AgentIntegration) GetAvoidedTools

func (a *AgentIntegration) GetAvoidedTools() []string

GetAvoidedTools returns a list of tools to avoid based on low preference or high failure rate

func (*AgentIntegration) GetBehavioralInsights

func (a *AgentIntegration) GetBehavioralInsights() string

GetBehavioralInsights returns behavioral insights

func (*AgentIntegration) GetBehavioralScore

func (a *AgentIntegration) GetBehavioralScore() BehavioralScore

GetBehavioralScore returns the current behavioral score

func (*AgentIntegration) GetLearnedContext

func (a *AgentIntegration) GetLearnedContext() string

GetLearnedContext returns formatted context for prompt injection

func (*AgentIntegration) GetPreferredTools

func (a *AgentIntegration) GetPreferredTools(minPreference float64) []string

GetPreferredTools returns a list of preferred tools based on user preference score

func (*AgentIntegration) GetProactiveNotes

func (a *AgentIntegration) GetProactiveNotes() string

GetProactiveNotes returns proactive notes

func (*AgentIntegration) GetRecentCorrections

func (a *AgentIntegration) GetRecentCorrections() string

GetRecentCorrections returns recent corrections context

func (*AgentIntegration) GetStats

func (a *AgentIntegration) GetStats() Stats

GetStats returns learning engine statistics

func (*AgentIntegration) GetSuggestions

func (a *AgentIntegration) GetSuggestions() []Suggestion

GetSuggestions returns active suggestions

func (*AgentIntegration) GetToolPreferences

func (a *AgentIntegration) GetToolPreferences() string

GetToolPreferences returns tool preference context

func (*AgentIntegration) GetWorkflowPatterns

func (a *AgentIntegration) GetWorkflowPatterns() string

GetWorkflowPatterns returns workflow pattern context

func (*AgentIntegration) RecordToolCall

func (a *AgentIntegration) RecordToolCall(toolName string, success bool, durationMs int64, context string)

RecordToolCall records a tool call for tracking

func (*AgentIntegration) RecordUserFeedback

func (a *AgentIntegration) RecordUserFeedback(toolName string, accepted bool)

RecordUserFeedback records user feedback on a tool result

func (*AgentIntegration) RunEvolution

func (a *AgentIntegration) RunEvolution() EvolutionResult

RunEvolution runs pattern evolution (should be called periodically)

func (*AgentIntegration) ShouldUseTool

func (a *AgentIntegration) ShouldUseTool(toolName string) (bool, string)

ShouldUseTool returns a recommendation on whether to use a specific tool

type AnalysisContext

type AnalysisContext struct {
	UserID            string
	SessionID         string
	MessageHistory    []Message
	RecentToolCalls   []ToolCall
	RecentToolResults []ToolResult
	CurrentPatterns   []EnhancedPattern
	BehavioralScore   BehavioralScore
}

AnalysisContext provides context for pattern analysis

type AnalysisResult

type AnalysisResult struct {
	Signals        []DetectedSignal       `json:"signals"`
	NewPatterns    []EnhancedPattern      `json:"new_patterns"`
	PatternUpdates []PatternUpdate        `json:"pattern_updates"`
	Contradictions []PatternContradiction `json:"contradictions,omitempty"`
	Suggestions    []ProactiveSuggestion  `json:"suggestions"`
}

AnalysisResult contains the results of pattern analysis

type BehavioralScore

type BehavioralScore struct {
	Overall float64 `json:"overall"` // Combined score 0.0 - 1.0

	Dimensions struct {
		ResponseQuality  float64 `json:"response_quality"`  // User satisfaction with responses
		ToolEfficiency   float64 `json:"tool_efficiency"`   // Success rate of tool usage
		ContextRelevance float64 `json:"context_relevance"` // How well context is used
		CorrectionRate   float64 `json:"correction_rate"`   // Frequency of user corrections (lower is better)
		AdaptationSpeed  float64 `json:"adaptation_speed"`  // How quickly agent adapts
	} `json:"dimensions"`

	Trends struct {
		ResponseQuality  TrendDirection `json:"response_quality"`
		ToolEfficiency   TrendDirection `json:"tool_efficiency"`
		ContextRelevance TrendDirection `json:"context_relevance"`
	} `json:"trends"`

	BasedOn struct {
		SampleSize  int   `json:"sample_size"`
		TimeWindow  int64 `json:"time_window"`  // ms
		LastUpdated int64 `json:"last_updated"` // Unix timestamp (ms)
	} `json:"based_on"`
}

BehavioralScore represents multi-dimensional behavioral scoring

type BehavioralScorer

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

BehavioralScorer calculates multi-dimensional behavioral scores

func NewBehavioralScorer

func NewBehavioralScorer(config Config) *BehavioralScorer

NewBehavioralScorer creates a new behavioral scorer

func (*BehavioralScorer) CalculateScore

func (s *BehavioralScorer) CalculateScore(patterns []EnhancedPattern, toolUsage []ToolUsagePattern) BehavioralScore

CalculateScore calculates a comprehensive behavioral score from patterns and tool usage

func (*BehavioralScorer) CalculateTrend

func (s *BehavioralScorer) CalculateTrend(values []float64) TrendDirection

CalculateTrend determines trend direction from a series of values

func (*BehavioralScorer) UpdateBehavioralScore

func (s *BehavioralScorer) UpdateBehavioralScore(current BehavioralScore, newSignal DetectedSignal) BehavioralScore

UpdateBehavioralScore updates a behavioral score with new data

type Config

type Config struct {
	DBPath                       string  `json:"db_path"`
	Language                     string  `json:"language"`                       // Default: "auto" (options: "en", "zh", "auto")
	MinConfidence                float64 `json:"min_confidence"`                 // Default: 0.7
	MaxExamples                  int     `json:"max_examples"`                   // Default: 10
	EnableSemanticDetection      bool    `json:"enable_semantic_detection"`      // Default: true
	EnableImplicitSignals        bool    `json:"enable_implicit_signals"`        // Default: true
	EnableBehavioralScoring      bool    `json:"enable_behavioral_scoring"`      // Default: true
	EnablePatternEvolution       bool    `json:"enable_pattern_evolution"`       // Default: false (enable after testing)
	EnableContradictionDetection bool    `json:"enable_contradiction_detection"` // Default: false
	EnableSuggestions            bool    `json:"enable_suggestions"`             // Default: false
	DecayOlderThanDays           int     `json:"decay_older_than_days"`          // Default: 7
	PruneOlderThanDays           int     `json:"prune_older_than_days"`          // Default: 30
	MergeSimilarityThreshold     float64 `json:"merge_similarity_threshold"`     // Default: 0.8
}

Config holds configuration for the learning engine

func DefaultConfig

func DefaultConfig(dbPath string) Config

DefaultConfig returns sensible defaults

type ContradictionResolution

type ContradictionResolution struct {
	Strategy       string `json:"strategy"`                  // keep_newer, keep_stronger, merge, contextualize, ask_user
	Winner         string `json:"winner,omitempty"`          // Pattern ID that won
	MergedPattern  string `json:"merged_pattern,omitempty"`  // New pattern ID if merged
	ContextualNote string `json:"contextual_note,omitempty"` // Explanation of context-dependent applicability
	ResolvedAt     int64  `json:"resolved_at"`               // Unix timestamp (ms)
}

ContradictionResolution represents how a contradiction was resolved

type DetectedSignal

type DetectedSignal struct {
	Type             PatternCategory `json:"type"` // positive, negative, correction, preference, implicit
	Confidence       float64         `json:"confidence"`
	Source           PatternSource   `json:"source"`
	Category         PatternCategory `json:"category"`
	Context          string          `json:"context"`
	ExtractedPattern string          `json:"extracted_pattern,omitempty"`
	Timestamp        int64           `json:"timestamp"` // Unix timestamp (ms)
}

DetectedSignal represents a signal detected from user interaction

type DetectionContext

type DetectionContext struct {
	UserMessage         string
	AssistantMessage    string
	History             []Message
	ToolCalls           []ToolCall
	PreviousToolResults []ToolResult
}

DetectionContext contains the context for pattern detection

type Engine

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

Engine is the main learning engine that coordinates all components

func NewEngine

func NewEngine(config Config) (*Engine, error)

NewEngine creates a new learning engine

func (*Engine) Analyze

func (e *Engine) Analyze(ctx AnalysisContext) AnalysisResult

Analyze analyzes a conversation context and extracts patterns

func (*Engine) ApplySuggestion

func (e *Engine) ApplySuggestion(id string) bool

ApplySuggestion marks a suggestion as applied

func (*Engine) Close

func (e *Engine) Close() error

Close closes the learning engine and releases resources

func (*Engine) DeletePattern

func (e *Engine) DeletePattern(id string) error

DeletePattern deletes a pattern by ID

func (*Engine) DismissSuggestion

func (e *Engine) DismissSuggestion(id string) bool

DismissSuggestion dismisses a suggestion

func (*Engine) Evolve

func (e *Engine) Evolve() EvolutionResult

Evolve runs pattern evolution (decay, merge, prune)

func (*Engine) GetAllPatterns

func (e *Engine) GetAllPatterns() []EnhancedPattern

GetAllPatterns returns all patterns

func (*Engine) GetBehavioralScore

func (e *Engine) GetBehavioralScore() BehavioralScore

GetBehavioralScore returns the current behavioral score

func (*Engine) GetContext

func (e *Engine) GetContext() EnhancedLearnedContext

GetContext returns the learned context for injection into prompts

func (*Engine) GetContextString

func (e *Engine) GetContextString() string

GetContextString returns the context as a formatted string for prompt injection

func (*Engine) GetPatternsByCategory

func (e *Engine) GetPatternsByCategory(category PatternCategory) []EnhancedPattern

GetPatternsByCategory returns patterns filtered by category

func (*Engine) GetStats

func (e *Engine) GetStats() Stats

GetStats returns statistics about the learning engine

func (*Engine) GetSuggestions

func (e *Engine) GetSuggestions() []Suggestion

GetSuggestions returns current suggestions

func (*Engine) GetToolUsagePatterns

func (e *Engine) GetToolUsagePatterns() []ToolUsagePattern

GetToolUsagePatterns returns all tool usage patterns

func (*Engine) RecordToolAcceptance

func (e *Engine) RecordToolAcceptance(toolName string)

RecordToolAcceptance records when a user accepts a tool result

func (*Engine) RecordToolExecution

func (e *Engine) RecordToolExecution(record ToolExecutionRecord)

RecordToolExecution records a tool execution for tracking

func (*Engine) RecordToolRejection

func (e *Engine) RecordToolRejection(toolName string)

RecordToolRejection records when a user rejects a tool result

func (*Engine) RefreshSuggestions

func (e *Engine) RefreshSuggestions()

RefreshSuggestions regenerates suggestions based on current patterns

func (*Engine) SearchPatterns

func (e *Engine) SearchPatterns(query string, limit int) ([]EnhancedPattern, error)

SearchPatterns searches for patterns matching a query

func (*Engine) UpdateTrend

func (e *Engine) UpdateTrend()

UpdateTrend updates tool usage trends

type EnhancedLearnedContext

type EnhancedLearnedContext struct {
	Preferences        string `json:"preferences"`
	Patterns           string `json:"patterns"`
	RecentCorrections  string `json:"recent_corrections"`
	ToolPreferences    string `json:"tool_preferences"`
	WorkflowPatterns   string `json:"workflow_patterns"`
	BehavioralInsights string `json:"behavioral_insights"`
	ProactiveNotes     string `json:"proactive_notes"`
}

EnhancedLearnedContext represents the context assembled from learned patterns

type EnhancedPattern

type EnhancedPattern struct {
	ID               string           `json:"id"`
	Category         PatternCategory  `json:"category"`
	Source           PatternSource    `json:"source"`
	Pattern          string           `json:"pattern"`           // Human-readable pattern description
	Confidence       float64          `json:"confidence"`        // 0.0 - 1.0
	Support          int              `json:"support"`           // Number of supporting instances
	Contradiction    int              `json:"contradiction"`     // Number of contradicting instances
	FirstObserved    int64            `json:"first_observed"`    // Unix timestamp (ms)
	LastObserved     int64            `json:"last_observed"`     // Unix timestamp (ms)
	ObservationCount int              `json:"observation_count"` // Total observations
	Triggers         []string         `json:"triggers"`          // Contexts where this pattern applies
	Examples         []PatternExample `json:"examples"`          // Supporting examples (max 10)
	RelatedPatterns  []string         `json:"related_patterns"`  // IDs of semantically related patterns
	Supersedes       []string         `json:"supersedes"`        // IDs of patterns this one replaces
	DecayRate        float64          `json:"decay_rate"`        // Custom decay rate (default: 0.05)
	LastDecayAt      int64            `json:"last_decay_at"`     // Last decay timestamp
	Metadata         map[string]any   `json:"metadata"`          // Additional metadata
}

EnhancedPattern represents a detected behavioral pattern with metadata

type EvolutionResult

type EvolutionResult struct {
	PatternsDecayed        int `json:"patterns_decayed"`
	PatternsMerged         int `json:"patterns_merged"`
	PatternsPruned         int `json:"patterns_pruned"`
	PatternsGeneralized    int `json:"patterns_generalized"`
	ContradictionsResolved int `json:"contradictions_resolved"`
}

EvolutionResult contains the results of pattern evolution

type Message

type Message struct {
	Role    string `json:"role"` // user, assistant, system, tool
	Content string `json:"content"`
}

Message represents a simplified message for analysis

type PatternCategory

type PatternCategory string

PatternCategory defines the category of a behavioral pattern

const (
	// User preference patterns
	CategoryPreferenceCommunication PatternCategory = "preference_communication" // "I prefer concise responses"
	CategoryPreferenceWorkflow      PatternCategory = "preference_workflow"      // "Always run tests after code changes"
	CategoryPreferenceTool          PatternCategory = "preference_tool"          // "Use TypeScript instead of JavaScript"

	// Feedback patterns
	CategorySuccessIndicator PatternCategory = "success_indicator" // Positive feedback on specific approach
	CategoryFailureIndicator PatternCategory = "failure_indicator" // Negative feedback on specific approach

	// Correction patterns
	CategoryCorrectionExplicit PatternCategory = "correction_explicit" // Direct correction from user
	CategoryCorrectionImplicit PatternCategory = "correction_implicit" // Inferred correction from behavior

	// Aggregated patterns
	CategoryBehavioralTrend PatternCategory = "behavioral_trend" // Aggregated pattern over time
)

type PatternContradiction

type PatternContradiction struct {
	ID                string                   `json:"id"`
	PatternA          string                   `json:"pattern_a"`          // Pattern ID
	PatternB          string                   `json:"pattern_b"`          // Pattern ID
	ContradictionType string                   `json:"contradiction_type"` // direct, contextual, temporal
	Severity          float64                  `json:"severity"`           // 0.0 - 1.0
	Resolution        *ContradictionResolution `json:"resolution,omitempty"`
	DetectedAt        int64                    `json:"detected_at"` // Unix timestamp (ms)
}

PatternContradiction represents a detected contradiction between patterns

type PatternDetector

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

PatternDetector detects behavioral patterns from conversations

func NewPatternDetector

func NewPatternDetector(config Config) *PatternDetector

NewPatternDetector creates a new pattern detector

func (*PatternDetector) DetectSignals

func (d *PatternDetector) DetectSignals(ctx DetectionContext) []DetectedSignal

DetectSignals detects all types of signals from the detection context

type PatternEvolver

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

PatternEvolver handles pattern evolution: decay, merge, prune, and generalize

func NewPatternEvolver

func NewPatternEvolver(config Config) *PatternEvolver

NewPatternEvolver creates a new pattern evolver

func (*PatternEvolver) Decay

func (e *PatternEvolver) Decay(patterns []EnhancedPattern) []EnhancedPattern

Decay applies temporal decay to pattern confidence

func (*PatternEvolver) Evolve

Evolve runs all evolution operations on patterns

func (*PatternEvolver) Generalize

func (e *PatternEvolver) Generalize(patterns []EnhancedPattern) ([]EnhancedPattern, int)

Generalize creates generalized patterns from related specific patterns

func (*PatternEvolver) Merge

func (e *PatternEvolver) Merge(patterns []EnhancedPattern) ([]EnhancedPattern, []string)

Merge combines similar patterns into generalized patterns

func (*PatternEvolver) Prune

func (e *PatternEvolver) Prune(patterns []EnhancedPattern) []string

Prune removes low-value patterns

type PatternExample

type PatternExample struct {
	Timestamp        int64    `json:"timestamp"`
	UserMessage      string   `json:"user_message"`
	AssistantMessage string   `json:"assistant_message"`
	ToolCalls        []string `json:"tool_calls,omitempty"`
	Outcome          string   `json:"outcome"` // positive, negative, neutral
	Confidence       float64  `json:"confidence"`
}

PatternExample represents a single example supporting a pattern

type PatternSource

type PatternSource string

PatternSource defines where a pattern was detected

const (
	SourceExplicitFeedback PatternSource = "explicit_feedback"         // User said "good job" or "wrong"
	SourceImplicitBehavior PatternSource = "implicit_behavior"         // User accepted/rejected tool result
	SourceToolUsageSuccess PatternSource = "tool_usage_success"        // Tool completed successfully
	SourceToolUsageFailure PatternSource = "tool_usage_failure"        // Tool failed or was rejected
	SourceConversationFlow PatternSource = "conversation_flow"         // Natural conversation patterns
	SourceCrossSession     PatternSource = "cross_session_correlation" // Pattern detected across sessions
)

type PatternUpdate

type PatternUpdate struct {
	PatternID string         `json:"pattern_id"`
	Updates   map[string]any `json:"updates"`
	Reason    string         `json:"reason"`
}

PatternUpdate represents an update to an existing pattern

type ProactiveSuggestion

type ProactiveSuggestion struct {
	ID              string           `json:"id"`
	Type            string           `json:"type"` // optimization, preference, workflow, tool_usage, correction
	Title           string           `json:"title"`
	Description     string           `json:"description"`
	Confidence      float64          `json:"confidence"`
	Impact          string           `json:"impact"`   // high, medium, low
	BasedOn         []string         `json:"based_on"` // Pattern IDs
	Evidence        string           `json:"evidence"` // Human-readable explanation
	SuggestedAction *SuggestedAction `json:"suggested_action,omitempty"`
	CreatedAt       int64            `json:"created_at"` // Unix timestamp (ms)
	Dismissed       bool             `json:"dismissed"`
	Applied         bool             `json:"applied"`
}

ProactiveSuggestion represents a suggestion for improvement

type SemanticIndicator

type SemanticIndicator struct {
	Keywords []string
	Weight   float64
}

SemanticIndicator represents a set of keywords with associated weight

type Stats

type Stats struct {
	TotalPatterns          int                     `json:"total_patterns"`
	HighConfidencePatterns int                     `json:"high_confidence_patterns"`
	PatternsByCategory     map[PatternCategory]int `json:"patterns_by_category"`
	AvgConfidence          float64                 `json:"avg_confidence"`
	BehavioralScore        BehavioralScore         `json:"behavioral_score"`
	ToolUsagePatterns      int                     `json:"tool_usage_patterns"`
	PendingContradictions  int                     `json:"pending_contradictions"`
	PendingSuggestions     int                     `json:"pending_suggestions"`
}

Stats contains statistics about the learning engine

type Store

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

Store persists learning data using SQLite

func NewStore

func NewStore(dbPath string) (*Store, error)

NewStore creates a new learning store

func (*Store) Close

func (s *Store) Close() error

Close closes the database connection

func (*Store) DeletePattern

func (s *Store) DeletePattern(id string) error

DeletePattern deletes a pattern by ID

func (*Store) DeletePatterns

func (s *Store) DeletePatterns(ids []string) error

DeletePatterns deletes multiple patterns by ID

func (*Store) GetActiveSuggestions

func (s *Store) GetActiveSuggestions() ([]Suggestion, error)

GetActiveSuggestions retrieves non-dismissed, non-applied suggestions

func (*Store) GetAllPatterns

func (s *Store) GetAllPatterns() ([]EnhancedPattern, error)

GetAllPatterns retrieves all patterns

func (*Store) GetAllToolUsage

func (s *Store) GetAllToolUsage() ([]ToolUsagePattern, error)

GetAllToolUsage retrieves all tool usage statistics

func (*Store) GetPattern

func (s *Store) GetPattern(id string) (*EnhancedPattern, error)

GetPattern retrieves a pattern by ID

func (*Store) GetPatternsByCategory

func (s *Store) GetPatternsByCategory(category PatternCategory) ([]EnhancedPattern, error)

GetPatternsByCategory retrieves patterns by category

func (*Store) GetRecentScores

func (s *Store) GetRecentScores(limit int) ([]BehavioralScore, error)

GetRecentScores retrieves recent behavioral scores

func (*Store) SavePattern

func (s *Store) SavePattern(pattern EnhancedPattern) error

SavePattern saves a pattern to the store

func (*Store) SaveScoreHistory

func (s *Store) SaveScoreHistory(score BehavioralScore) error

SaveScoreHistory saves a behavioral score to history

func (*Store) SaveSuggestion

func (s *Store) SaveSuggestion(suggestion Suggestion) error

SaveSuggestion saves a suggestion

func (*Store) SaveToolUsage

func (s *Store) SaveToolUsage(usage ToolUsagePattern) error

SaveToolUsage saves tool usage statistics

func (*Store) SearchPatterns

func (s *Store) SearchPatterns(query string, limit int) ([]EnhancedPattern, error)

SearchPatterns searches patterns using FTS5

type SuggestedAction

type SuggestedAction struct {
	Type    string         `json:"type"` // update_preference, modify_tool_usage, change_workflow
	Details map[string]any `json:"details"`
}

SuggestedAction represents an action that can be taken on a suggestion

type Suggester

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

Suggester generates proactive suggestions based on detected patterns

func NewSuggester

func NewSuggester(config Config) *Suggester

NewSuggester creates a new suggester

func (*Suggester) ApplySuggestion

func (s *Suggester) ApplySuggestion(suggestions []Suggestion, id string) []Suggestion

ApplySuggestion marks a suggestion as applied

func (*Suggester) DismissSuggestion

func (s *Suggester) DismissSuggestion(suggestions []Suggestion, id string) []Suggestion

DismissSuggestion marks a suggestion as dismissed

func (*Suggester) GenerateSuggestions

func (s *Suggester) GenerateSuggestions(
	patterns []EnhancedPattern,
	toolUsage []ToolUsagePattern,
	score BehavioralScore,
) []Suggestion

GenerateSuggestions generates proactive suggestions from patterns and tool usage

func (*Suggester) GetActiveSuggestions

func (s *Suggester) GetActiveSuggestions(suggestions []Suggestion) []Suggestion

GetActiveSuggestions returns only non-dismissed, non-applied suggestions

func (*Suggester) GetHighImpactSuggestions

func (s *Suggester) GetHighImpactSuggestions(suggestions []Suggestion) []Suggestion

GetHighImpactSuggestions returns only high-impact suggestions

type Suggestion

type Suggestion = ProactiveSuggestion

Suggestion is an alias for ProactiveSuggestion for convenience

type ToolCall

type ToolCall struct {
	ID        string         `json:"id"`
	Name      string         `json:"name"`
	Arguments map[string]any `json:"arguments"`
}

ToolCall represents a simplified tool call for analysis

type ToolExecutionRecord

type ToolExecutionRecord struct {
	ToolName    string
	Success     bool
	DurationMs  int64
	UserContext string
	Timestamp   int64
}

ToolExecutionRecord represents a single tool execution

type ToolResult

type ToolResult struct {
	ToolCallID string `json:"tool_call_id"`
	ToolName   string `json:"tool_name"`
	Tool       string `json:"tool"` // Simplified name for detection context
	Success    bool   `json:"success"`
	Result     string `json:"result"`
	DurationMs int64  `json:"duration_ms"`
}

ToolResult represents the result of a tool call

type ToolTracker

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

ToolTracker tracks tool usage patterns and statistics

func NewToolTracker

func NewToolTracker(config Config) *ToolTracker

NewToolTracker creates a new tool tracker

func (*ToolTracker) Export

func (t *ToolTracker) Export() map[string]*ToolUsagePattern

Export exports tool usage data for persistence

func (*ToolTracker) GetAllToolUsage

func (t *ToolTracker) GetAllToolUsage() []ToolUsagePattern

GetAllToolUsage returns all tool usage patterns

func (*ToolTracker) GetLastUsed

func (t *ToolTracker) GetLastUsed(toolName string) time.Time

GetLastUsed returns the timestamp when a tool was last used

func (*ToolTracker) GetLeastUsedTools

func (t *ToolTracker) GetLeastUsedTools(n int) []ToolUsagePattern

GetLeastUsedTools returns the top N least used tools (with at least one call)

func (*ToolTracker) GetMostUsedTools

func (t *ToolTracker) GetMostUsedTools(n int) []ToolUsagePattern

GetMostUsedTools returns the top N most used tools

func (*ToolTracker) GetPreferredTools

func (t *ToolTracker) GetPreferredTools(minCalls int, minPreference float64) []ToolUsagePattern

GetPreferredTools returns tools with high user preference

func (*ToolTracker) GetProblematicTools

func (t *ToolTracker) GetProblematicTools(minCalls int, maxSuccessRate float64) []ToolUsagePattern

GetProblematicTools returns tools with low success rates

func (*ToolTracker) GetStats

func (t *ToolTracker) GetStats() map[string]any

GetStats returns statistics about tool usage

func (*ToolTracker) GetToolUsage

func (t *ToolTracker) GetToolUsage(toolName string) *ToolUsagePattern

GetToolUsage returns usage pattern for a specific tool

func (*ToolTracker) GetToolUsageSince

func (t *ToolTracker) GetToolUsageSince(timestamp int64) []ToolExecutionRecord

GetToolUsageSince returns tool usage since a specific timestamp

func (*ToolTracker) LoadFromStore

func (t *ToolTracker) LoadFromStore(stats map[string]*ToolUsagePattern)

LoadFromStore loads tool usage data from the store

func (*ToolTracker) RecordExecution

func (t *ToolTracker) RecordExecution(record ToolExecutionRecord)

RecordExecution records a tool execution

func (*ToolTracker) RecordUserAcceptance

func (t *ToolTracker) RecordUserAcceptance(toolName string)

RecordUserAcceptance records when a user accepts a tool result

func (*ToolTracker) RecordUserRejection

func (t *ToolTracker) RecordUserRejection(toolName string)

RecordUserRejection records when a user rejects a tool result

func (*ToolTracker) Reset

func (t *ToolTracker) Reset()

Reset clears all tool usage statistics

func (*ToolTracker) UpdateTrends

func (t *ToolTracker) UpdateTrends()

UpdateTrends updates usage trends based on historical data

type ToolUsagePattern

type ToolUsagePattern struct {
	ToolName          string         `json:"tool_name"`
	TotalCalls        int            `json:"total_calls"`
	SuccessfulCalls   int            `json:"successful_calls"`
	FailedCalls       int            `json:"failed_calls"`
	UserRejectedCalls int            `json:"user_rejected_calls"` // Tool ran but user didn't like result
	UserAcceptedCalls int            `json:"user_accepted_calls"` // Tool ran and user liked result
	AvgDurationMs     int64          `json:"avg_duration_ms"`
	P50DurationMs     int64          `json:"p50_duration_ms"`
	P95DurationMs     int64          `json:"p95_duration_ms"`
	CommonContexts    []string       `json:"common_contexts"` // When is this tool typically used?
	CommonArgs        map[string]any `json:"common_args"`     // Common argument patterns
	UserPreference    float64        `json:"user_preference"` // -1.0 to 1.0 (avoid to prefer)
	UsageTrend        TrendDirection `json:"usage_trend"`
	LastUsed          int64          `json:"last_used"` // Unix timestamp (ms)
}

ToolUsagePattern tracks tool usage statistics

type TrendDirection

type TrendDirection string

TrendDirection indicates the direction of a trend

const (
	TrendImproving TrendDirection = "improving"
	TrendStable    TrendDirection = "stable"
	TrendDeclining TrendDirection = "declining"
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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