cortex

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 8, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultSoul = `` /* 605-byte string literal not displayed */

DefaultSoul is the default personality when no SOUL.md exists

View Source
const DefaultUserProfile = `` /* 259-byte string literal not displayed */

DefaultUserProfile is the default USER.md template

Variables

This section is empty.

Functions

This section is empty.

Types

type CachedPrompt added in v0.4.10

type CachedPrompt struct {
	Key         string
	Prefix      string  // The cached prefix content
	CacheBreaks []int64 // Message indices where cache breaks occur
	CreatedAt   time.Time
	LastUsedAt  time.Time
	HitCount    int
	Tokens      int
}

CachedPrompt represents a cached prompt with its cache key

type CompressionResult added in v0.4.10

type CompressionResult struct {
	Messages     []provider.Message
	Summary      string
	Removed      int     // Number of messages removed
	Ratio        float64 // Actual compression ratio
	CompressedAt time.Time
}

CompressionResult contains the compressed context

func (*CompressionResult) MarshalJSON added in v0.4.10

func (r *CompressionResult) MarshalJSON() ([]byte, error)

MarshalJSON for CompressionResult

type CompressionStats added in v0.4.10

type CompressionStats struct {
	TotalCompressions int
	TotalRemoved      int
	AvgRatio          float64
	LastCompression   time.Time
}

CompressionStats tracks compression history

type ContextCompressor added in v0.4.10

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

ContextCompressor handles intelligent context compression Based on Hermes Agent's context_compressor.py approach

func NewContextCompressor added in v0.4.10

func NewContextCompressor(prov provider.Provider, threshold int, ratio float64) *ContextCompressor

NewContextCompressor creates a new context compressor

func (*ContextCompressor) Compress added in v0.4.10

func (cc *ContextCompressor) Compress(ctx context.Context, messages []provider.Message) (*CompressionResult, error)

Compress compresses the middle portion of conversation history

func (*ContextCompressor) CompressWithStrategy added in v0.4.10

func (cc *ContextCompressor) CompressWithStrategy(
	ctx context.Context,
	messages []provider.Message,
	strategy string,
) (*CompressionResult, error)

CompressWithStrategy applies different compression strategies

func (*ContextCompressor) FormatCompressedMessages added in v0.4.10

func (cc *ContextCompressor) FormatCompressedMessages(result *CompressionResult) []map[string]interface{}

FormatCompressedMessages formats messages for display with compression indicators

func (*ContextCompressor) GetStats added in v0.4.10

func (cc *ContextCompressor) GetStats() map[string]interface{}

GetStats returns compression statistics

func (*ContextCompressor) ShouldCompress added in v0.4.10

func (cc *ContextCompressor) ShouldCompress(messages []provider.Message) bool

ShouldCompress checks if context needs compression

type EffectivenessEvaluator added in v0.4.10

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

EffectivenessEvaluator evaluates trajectory effectiveness

func NewEffectivenessEvaluator added in v0.4.10

func NewEffectivenessEvaluator() *EffectivenessEvaluator

NewEffectivenessEvaluator creates a new evaluator

func (*EffectivenessEvaluator) AnalyzeTrend added in v0.4.10

func (e *EffectivenessEvaluator) AnalyzeTrend(
	scores []EffectivenessScore,
	trajectories []Trajectory,
) map[string]interface{}

AnalyzeTrend analyzes score trends over time

func (*EffectivenessEvaluator) Evaluate added in v0.4.10

func (e *EffectivenessEvaluator) Evaluate(trajectory *Trajectory) EffectivenessScore

Evaluate evaluates a single trajectory

func (*EffectivenessEvaluator) EvaluateBatch added in v0.4.10

func (e *EffectivenessEvaluator) EvaluateBatch(trajectories []Trajectory) []EffectivenessScore

EvaluateBatch evaluates multiple trajectories

func (*EffectivenessEvaluator) GetAverageScore added in v0.4.10

func (e *EffectivenessEvaluator) GetAverageScore(scores []EffectivenessScore) float64

GetAverageScore calculates the average score across multiple trajectories

func (*EffectivenessEvaluator) GetSuccessRate added in v0.4.10

func (e *EffectivenessEvaluator) GetSuccessRate(scores []EffectivenessScore) float64

GetSuccessRate calculates the success rate

func (*EffectivenessEvaluator) GetTopPerformers added in v0.4.10

func (e *EffectivenessEvaluator) GetTopPerformers(
	scores []EffectivenessScore,
	n int,
) []EffectivenessScore

GetTopPerformers returns the top N performing trajectories

type EffectivenessScore added in v0.4.10

type EffectivenessScore struct {
	TrajectoryID string  `json:"trajectory_id"`
	Success      bool    `json:"success"`
	Efficiency   float64 `json:"efficiency"`    // 0-1, based on turns vs optimal
	Quality      float64 `json:"quality"`       // 0-1, based on output quality
	ToolAccuracy float64 `json:"tool_accuracy"` // 0-1, correct tool usage
	OverallScore float64 `json:"overall_score"` // Weighted combination
}

EffectivenessScore represents a trajectory's effectiveness

type GEPAEngine added in v0.4.10

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

GEPAEngine is the main GEPA orchestrator

func NewGEPAEngine added in v0.4.10

func NewGEPAEngine(baseDir string, prov provider.Provider, trajectoryStore *TrajectoryStore) *GEPAEngine

NewGEPAEngine creates a new GEPA engine

func (*GEPAEngine) ApplyBestStrategy added in v0.4.10

func (g *GEPAEngine) ApplyBestStrategy(soul *SoulManager, systemPrompt string) (string, error)

ApplyBestStrategy applies the best strategy to the system

func (*GEPAEngine) GetGenerations added in v0.4.10

func (g *GEPAEngine) GetGenerations() []Generation

GetGenerations returns all generations

func (*GEPAEngine) GetStats added in v0.4.10

func (g *GEPAEngine) GetStats() map[string]interface{}

GetStats returns GEPA engine statistics

func (*GEPAEngine) Reset added in v0.4.10

func (g *GEPAEngine) Reset() error

Reset resets the GEPA engine

func (*GEPAEngine) Start added in v0.4.10

func (g *GEPAEngine) Start(ctx context.Context) error

Start starts the GEPA evolution process

type Generation added in v0.4.10

type Generation struct {
	ID           int                    `json:"id"`
	Timestamp    time.Time              `json:"timestamp"`
	Strategies   []OptimizationStrategy `json:"strategies"`
	BestStrategy *OptimizationStrategy  `json:"best_strategy"`
	AvgFitness   float64                `json:"avg_fitness"`
	Improvement  float64                `json:"improvement"`
	Trajectories []string               `json:"trajectory_ids"`
}

Generation represents one evolution iteration

type Manager

type Manager struct {

	// Core systems
	Snapshot     *memory.SnapshotManager          // System 4: Frozen snapshot memory
	Trigger      *trigger.MessageTrigger          // System 1 + 2: Nudge mechanism
	Review       *review.EnhancedBackgroundReview // System 3: Background review
	Perception   *perception.Parser               // Layer 1: Intent classification
	Cognition    *cognition.Planner               // Layer 2: Planning and decision making
	LLMPlanner   *cognition.LLMPlanner            // LLM-based planning (NEW)
	Execution    *execution.Manager               // Layer 3: Checkpoint + Resume
	FTSMemory    *memory.FTSStore                 // System 5: FTS full-text search
	SkillCreator *skills.EnhancedAutoCreator      // System 6: Auto skill evolution

	// NEW: Hermes-inspired systems
	Soul              *SoulManager       // System personality (SOUL.md)
	UserProfile       *UserProfile       // User preferences (USER.md)
	PromptCache       *PromptCache       // Prompt caching
	ContextCompressor *ContextCompressor // Context compression
	TrajectoryStore   *TrajectoryStore   // Trajectory learning
	GEPAEngine        *GEPAEngine        // Self-evolution engine

	LastPerception *perception.PerceptionResult
	LastDecision   *cognition.Decision   // Last cognition decision
	LastCheckpoint *execution.Checkpoint // Current execution checkpoint
	// contains filtered or unexported fields
}

Manager integrates all Cortex Agent systems with Hermes Agent-inspired features: 1. User Message Trigger 2. Periodic Nudge Mechanism 3. Background Review System 4. Dual File Storage (MEMORY.md + USER.md) 5. Holographic Memory (SQLite FTS5) 6. Memory Manager with Frozen Snapshot 7. SOUL.md System Personality (NEW) 8. LLM Planner (NEW) 9. Prompt Caching (NEW) 10. Context Compression (NEW) 12. GEPA Self-Evolution Engine (NEW)

func NewManager

func NewManager(baseDir string, prov provider.Provider) *Manager

NewManager creates a new Cortex integration manager Initializes all Cortex systems including Hermes Agent-inspired features

func NewManagerWithConfig deprecated added in v0.4.16

func NewManagerWithConfig(baseDir string, prov provider.Provider, config *ManagerConfig) *Manager

Deprecated: Use NewManagerWithProfileAndConfig instead

func NewManagerWithProfile added in v0.4.10

func NewManagerWithProfile(baseDir string, prov provider.Provider, profile string) *Manager

NewManagerWithProfile creates a new Cortex manager with specific profile The profile parameter specifies which profile's user.md to load

func NewManagerWithProfileAndConfig added in v0.4.16

func NewManagerWithProfileAndConfig(baseDir string, prov provider.Provider, profile string, config *ManagerConfig) *Manager

NewManagerWithProfileAndConfig creates a new Cortex manager with profile and custom config

func (*Manager) AddMemoryInsight

func (m *Manager) AddMemoryInsight(insight string, importance int) error

AddMemoryInsight stores a learned insight in FTS memory

func (*Manager) AnalyzeToolSequence

func (m *Manager) AnalyzeToolSequence(task string, tools []string)

AnalyzeToolSequence analyzes a tool sequence for pattern recognition

func (*Manager) AppendMemory

func (m *Manager) AppendMemory(line string) error

AppendMemory adds a line to the memory file Writes to disk immediately but does NOT refresh frozen snapshot

func (*Manager) AppendUser

func (m *Manager) AppendUser(line string) error

AppendUser adds a line to the user profile Writes to disk immediately but does NOT refresh frozen snapshot

func (*Manager) BindSkillsManager added in v0.4.16

func (m *Manager) BindSkillsManager(sm *skills.Manager)

BindSkillsManager connects the cortex skill auto creator to the skills Manager so auto-generated skills are visible via /api/skills.

func (*Manager) CompleteExecution

func (m *Manager) CompleteExecution()

CompleteExecution marks execution as successfully completed

func (*Manager) FindResumableTask

func (m *Manager) FindResumableTask(description string) *execution.Checkpoint

FindResumableTask checks if there's a resumable checkpoint

func (*Manager) GetClarificationQuestion

func (m *Manager) GetClarificationQuestion() string

GetClarificationQuestion returns the question to ask user for clarification

func (*Manager) GetDetectedPatterns

func (m *Manager) GetDetectedPatterns() []skills.Pattern

GetDetectedPatterns returns all currently detected patterns

func (*Manager) GetExecutionPlan

func (m *Manager) GetExecutionPlan() *cognition.ExecutionPlan

GetExecutionPlan returns the current execution plan

func (*Manager) GetExecutionProgress

func (m *Manager) GetExecutionProgress() *execution.Progress

GetExecutionProgress returns the current execution progress

func (*Manager) GetGeneratedSkills

func (m *Manager) GetGeneratedSkills() []string

GetGeneratedSkills returns all auto-generated skills

func (*Manager) GetIntent

func (m *Manager) GetIntent() perception.IntentType

GetIntent returns the classified intent type

func (*Manager) GetLastDecision

func (m *Manager) GetLastDecision() *cognition.Decision

GetLastDecision returns the last cognition decision

func (*Manager) GetLastPerception

func (m *Manager) GetLastPerception() *perception.PerceptionResult

GetLastPerception returns the result from the perception layer This can be used by the decision layer to: - Adjust max turns based on task complexity - Change tool selection based on intent - Request clarification if noise is detected

func (*Manager) GetMemoryStats

func (m *Manager) GetMemoryStats() map[string]interface{}

GetMemoryStats returns statistics about the memory store

func (*Manager) GetMemoryVersion

func (m *Manager) GetMemoryVersion() int

GetMemoryVersion returns the current memory version

func (*Manager) GetPromptContext

func (m *Manager) GetPromptContext() string

GetPromptContext returns the memory context to include in system prompt Uses the frozen snapshot, not the latest version

func (*Manager) GetRecommendedMaxTurns

func (m *Manager) GetRecommendedMaxTurns() int

GetRecommendedMaxTurns returns the recommended max turns based on task complexity

func (*Manager) GetRetrievalHints

func (m *Manager) GetRetrievalHints() []cognition.RetrievalHint

GetRetrievalHints returns hints for memory retrieval

func (*Manager) GetSkillEvolutionStats

func (m *Manager) GetSkillEvolutionStats() map[string]interface{}

GetSkillEvolutionStats returns statistics about skill generation

func (*Manager) GetSystemStatus

func (m *Manager) GetSystemStatus() map[string]interface{}

GetSystemStatus returns status of all six Cortex systems

func (*Manager) GetTaskComplexity

func (m *Manager) GetTaskComplexity() perception.TaskComplexity

GetTaskComplexity returns the estimated task complexity

func (*Manager) GetTurnCount

func (m *Manager) GetTurnCount() int

GetTurnCount returns the current turn count

func (*Manager) GetUserContext

func (m *Manager) GetUserContext() string

GetUserContext returns the user profile for system prompt Uses the frozen snapshot

func (*Manager) HasNoise

func (m *Manager) HasNoise() bool

HasNoise returns true if noise was detected in input

func (*Manager) IsEnabled added in v0.4.16

func (m *Manager) IsEnabled() bool

IsEnabled returns whether the Cortex system is enabled

func (*Manager) NeedsClarification

func (m *Manager) NeedsClarification() bool

NeedsClarification returns true if clarification should be requested

func (*Manager) OnSessionEnd

func (m *Manager) OnSessionEnd()

OnSessionEnd is called when a session completes Refreshes the memory snapshot and finalizes skill pattern analysis Extracts information from conversation history for memory building

func (*Manager) OnTurnEnd

func (m *Manager) OnTurnEnd()

OnTurnEnd is called at the end of each LLM turn Triggers mid-turn learning: records tool calls for skill pattern detection

func (*Manager) OnTurnStart

func (m *Manager) OnTurnStart()

OnTurnStart is called at the beginning of each LLM turn Freezes the memory snapshot for prefix cache protection

func (*Manager) OnUserMessage

func (m *Manager) OnUserMessage(input string)

OnUserMessage handles a new user message, triggering: - Layer 1: Perception (intent classification, noise detection) - Layer 2: Cognition (task planning, memory retrieval hints) - Turn counter increment - Nudge if threshold reached (async) - Skill creation flow initialization

func (*Manager) Reset

func (m *Manager) Reset()

Reset resets the turn counter for a new session

func (*Manager) SearchMemory

func (m *Manager) SearchMemory(query string, limit int) []memory.SearchResult

SearchMemory performs full-text search across all conversation history

func (*Manager) SetConversationHistory added in v0.4.14

func (m *Manager) SetConversationHistory(history []struct {
	Role    string
	Content string
})

SetConversationHistory sets the conversation history for memory extraction

func (*Manager) ShouldUseSubAgents

func (m *Manager) ShouldUseSubAgents() bool

ShouldUseSubAgents returns true if sub-agents should be enabled

func (*Manager) Start

func (m *Manager) Start() error

Start initializes all Cortex systems Systems started in order of dependency:

func (*Manager) StartExecution

func (m *Manager) StartExecution(task string) *execution.Progress

StartExecution begins a new execution with checkpoint support

func (*Manager) SuggestRecoveryAction

func (m *Manager) SuggestRecoveryAction(err error) execution.RecoveryAction

SuggestRecoveryAction suggests what to do after failure

func (*Manager) UpdateExecutionStep

func (m *Manager) UpdateExecutionStep(stepID int, stepName string)

UpdateExecutionStep updates the current step

type ManagerConfig added in v0.4.16

type ManagerConfig struct {
	// Master switch
	Enabled bool // Enable/disable Cortex system

	// Review settings
	ReviewInterval      time.Duration
	ReviewEnabled       bool
	SkillMinPatternFreq int // Minimum frequency for skill pattern detection

	// Perception settings
	PerceptionConfidenceThreshold float64
	PerceptionMaxHistory          int

	// Cognition settings
	PlanningMaxSteps int
	PlanningTimeout  time.Duration

	// Trigger settings
	NudgeInterval time.Duration
	NudgeEnabled  bool
}

ManagerConfig holds configuration for Cortex systems

type OptimizationStrategy added in v0.4.10

type OptimizationStrategy struct {
	ID          string          `json:"id"`
	Name        string          `json:"name"`
	Description string          `json:"description"`
	Target      string          `json:"target"` // "soul", "system", "skills"
	Changes     []PromptChange  `json:"changes"`
	Fitness     float64         `json:"fitness"`
	Applied     bool            `json:"applied"`
	AppliedAt   *time.Time      `json:"applied_at,omitempty"`
	Results     *StrategyResult `json:"results,omitempty"`
}

OptimizationStrategy represents a prompt optimization strategy

type PromptCache added in v0.4.10

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

PromptCache implements Anthropic/OpenAI-style prompt caching

func NewPromptCache added in v0.4.10

func NewPromptCache(provider provider.Provider, cacheDir string) (*PromptCache, error)

NewPromptCache creates a new prompt cache

func (*PromptCache) AddCacheBreak added in v0.4.10

func (pc *PromptCache) AddCacheBreak(key string, messageIndex int64) error

AddCacheBreak marks a message index as a cache break point

func (*PromptCache) BuildMessagesWithCache added in v0.4.10

func (pc *PromptCache) BuildMessagesWithCache(
	systemPrefix string,
	memoryCtx string,
	userCtx string,
	conversation []provider.Message,
) ([]provider.Message, string, error)

BuildMessagesWithCache builds messages with cache control hints Returns messages with cache_control metadata for providers that support it

func (*PromptCache) CachePrefix added in v0.4.10

func (pc *PromptCache) CachePrefix(ctx context.Context, prefixContent string) (string, error)

CachePrefix generates a cache key and stores the prefix The prefix typically includes: system prompt, SOUL, MEMORY, USER, skills

func (*PromptCache) Clear added in v0.4.10

func (pc *PromptCache) Clear() error

Clear removes all cache entries

func (*PromptCache) GetCacheStats added in v0.4.10

func (pc *PromptCache) GetCacheStats() map[string]interface{}

GetCacheStats returns cache statistics

func (*PromptCache) GetCachedPrefix added in v0.4.10

func (pc *PromptCache) GetCachedPrefix(key string) (string, bool)

GetCachedPrefix retrieves a cached prefix by key

type PromptChange added in v0.4.10

type PromptChange struct {
	Type       string `json:"type"`    // "add", "remove", "modify", "reorder"
	Section    string `json:"section"` // Section name
	OldContent string `json:"old_content"`
	NewContent string `json:"new_content"`
	Reason     string `json:"reason"`
}

PromptChange represents a single prompt modification

type PromptOptimizer added in v0.4.10

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

PromptOptimizer applies optimization strategies to prompts

func NewPromptOptimizer added in v0.4.10

func NewPromptOptimizer(prov provider.Provider) *PromptOptimizer

NewPromptOptimizer creates a new prompt optimizer

func (*PromptOptimizer) Optimize added in v0.4.10

func (o *PromptOptimizer) Optimize(prompt string, changes []PromptChange) (string, error)

Optimize applies optimization changes to a prompt

func (*PromptOptimizer) OptimizeWithLLM added in v0.4.10

func (o *PromptOptimizer) OptimizeWithLLM(
	ctx context.Context,
	prompt string,
	strategy *OptimizationStrategy,
) (string, error)

OptimizeWithLLM uses LLM to optimize a prompt

func (*PromptOptimizer) PreviewChanges added in v0.4.10

func (o *PromptOptimizer) PreviewChanges(prompt string, changes []PromptChange) string

PreviewChanges shows what changes would look like without applying

func (*PromptOptimizer) RollbackChanges added in v0.4.10

func (o *PromptOptimizer) RollbackChanges(optimizedPrompt string, changes []PromptChange, originalPrompt string) string

RollbackChanges rolls back applied changes (requires original)

func (*PromptOptimizer) ValidateChanges added in v0.4.10

func (o *PromptOptimizer) ValidateChanges(prompt string, changes []PromptChange) []error

ValidateChanges validates that changes can be applied to a prompt

type ScoringWeights added in v0.4.10

type ScoringWeights struct {
	SuccessWeight      float64 // Weight of success/failure
	EfficiencyWeight   float64 // Weight of turn efficiency
	QualityWeight      float64 // Weight of output quality
	ToolAccuracyWeight float64 // Weight of correct tool usage
}

ScoringWeights defines the weight of each scoring dimension

func DefaultScoringWeights added in v0.4.10

func DefaultScoringWeights() ScoringWeights

DefaultScoringWeights returns default scoring weights

type SoulManager added in v0.4.10

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

SoulManager manages the system personality (SOUL.md)

func NewSoulManager added in v0.4.10

func NewSoulManager(baseDir string) *SoulManager

NewSoulManager creates a new soul manager

func (*SoulManager) GetSoul added in v0.4.10

func (m *SoulManager) GetSoul() string

GetSoul returns the current soul/personality

func (*SoulManager) GetSoulForPrompt added in v0.4.10

func (m *SoulManager) GetSoulForPrompt() string

GetSoulForPrompt returns the soul formatted for system prompt

func (*SoulManager) Load added in v0.4.10

func (m *SoulManager) Load() error

Load loads the SOUL.md file from disk

func (*SoulManager) ResetToDefault added in v0.4.10

func (m *SoulManager) ResetToDefault() error

ResetToDefault resets the soul to default personality

func (*SoulManager) SetSoul added in v0.4.10

func (m *SoulManager) SetSoul(content string) error

SetSoul updates the soul/personality

func (*SoulManager) UpdateFromFeedback added in v0.4.10

func (m *SoulManager) UpdateFromFeedback(feedback string) error

UpdateFromFeedback updates the soul based on user feedback

type StrategyGenerator added in v0.4.10

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

StrategyGenerator generates optimization strategies

func NewStrategyGenerator added in v0.4.10

func NewStrategyGenerator(prov provider.Provider) *StrategyGenerator

NewStrategyGenerator creates a new strategy generator

func (*StrategyGenerator) GenerateStrategies added in v0.4.10

func (g *StrategyGenerator) GenerateStrategies(
	ctx context.Context,
	scores []EffectivenessScore,
	populationSize int,
) ([]OptimizationStrategy, error)

GenerateStrategies generates optimization strategies based on effectiveness scores

func (*StrategyGenerator) RefineStrategy added in v0.4.10

func (g *StrategyGenerator) RefineStrategy(
	ctx context.Context,
	strategy *OptimizationStrategy,
	feedback string,
) (*OptimizationStrategy, error)

RefineStrategy refines a strategy based on feedback

type StrategyResult added in v0.4.10

type StrategyResult struct {
	BeforeSuccessRate float64   `json:"before_success_rate"`
	AfterSuccessRate  float64   `json:"after_success_rate"`
	Improvement       float64   `json:"improvement"`
	SampleSize        int       `json:"sample_size"`
	MeasuredAt        time.Time `json:"measured_at"`
}

StrategyResult tracks the outcome of applying a strategy

type Trajectory added in v0.4.10

type Trajectory struct {
	ID          string           `json:"id"`
	Task        string           `json:"task"`
	Description string           `json:"description"`
	Steps       []TrajectoryStep `json:"steps"`
	Result      string           `json:"result"`
	Success     bool             `json:"success"`
	Duration    time.Duration    `json:"duration"`
	StartTime   time.Time        `json:"start_time"`
	EndTime     time.Time        `json:"end_time"`
	Model       string           `json:"model,omitempty"`
	Provider    string           `json:"provider,omitempty"`
	Tags        []string         `json:"tags,omitempty"`
	Score       float64          `json:"score,omitempty"`
}

Trajectory represents a complete task execution trajectory

type TrajectoryPattern added in v0.4.10

type TrajectoryPattern struct {
	ID           string    `json:"id"`
	Pattern      string    `json:"pattern"`
	ToolSequence []string  `json:"tool_sequence"`
	SuccessRate  float64   `json:"success_rate"`
	Occurrences  int       `json:"occurrences"`
	LastSeen     time.Time `json:"last_seen"`
	SkillName    string    `json:"skill_name,omitempty"`
}

TrajectoryPattern represents a learned pattern from trajectories

type TrajectoryStep added in v0.4.10

type TrajectoryStep struct {
	ToolName   string                 `json:"tool_name"`
	ToolInput  string                 `json:"tool_input"`
	ToolOutput string                 `json:"tool_output"`
	Success    bool                   `json:"success"`
	Duration   time.Duration          `json:"duration"`
	Timestamp  time.Time              `json:"timestamp"`
	Metadata   map[string]interface{} `json:"metadata,omitempty"`
}

TrajectoryStep represents a single step in an execution trajectory

type TrajectoryStore added in v0.4.10

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

TrajectoryStore manages trajectory storage and learning

func NewTrajectoryStore added in v0.4.10

func NewTrajectoryStore(baseDir string) (*TrajectoryStore, error)

NewTrajectoryStore creates a new trajectory store

func (*TrajectoryStore) Clear added in v0.4.10

func (ts *TrajectoryStore) Clear() error

Clear removes all trajectories and patterns

func (*TrajectoryStore) GetPatterns added in v0.4.10

func (ts *TrajectoryStore) GetPatterns(minSuccessRate float64) []TrajectoryPattern

GetPatterns returns all learned patterns

func (*TrajectoryStore) GetStats added in v0.4.10

func (ts *TrajectoryStore) GetStats() map[string]interface{}

GetStats returns trajectory statistics

func (*TrajectoryStore) GetTopPatterns added in v0.4.10

func (ts *TrajectoryStore) GetTopPatterns(limit int) []TrajectoryPattern

GetTopPatterns returns the most successful patterns

func (*TrajectoryStore) GetTrajectories added in v0.4.10

func (ts *TrajectoryStore) GetTrajectories(limit int) []Trajectory

GetTrajectories returns all trajectories

func (*TrajectoryStore) RecordTrajectory added in v0.4.10

func (ts *TrajectoryStore) RecordTrajectory(trajectory *Trajectory) error

RecordTrajectory records a completed trajectory

func (*TrajectoryStore) SearchTrajectories added in v0.4.10

func (ts *TrajectoryStore) SearchTrajectories(query string, limit int) []Trajectory

SearchTrajectories searches trajectories by task description

type UserPreference added in v0.4.10

type UserPreference struct {
	Key        string    `json:"key"`
	Value      string    `json:"value"`
	Context    string    `json:"context,omitempty"`
	Source     string    `json:"source"`     // "explicit", "learned", "feedback"
	Confidence float64   `json:"confidence"` // 0.0-1.0
	CreatedAt  time.Time `json:"created_at"`
	UpdatedAt  time.Time `json:"updated_at"`
}

UserPreference represents a single user preference

type UserProfile added in v0.4.10

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

UserProfile manages the USER.md with structured preferences

func NewUserProfile added in v0.4.10

func NewUserProfile(baseDir string) *UserProfile

NewUserProfile creates a new user profile manager

func (*UserProfile) AddInterest added in v0.4.10

func (up *UserProfile) AddInterest(interest string) error

AddInterest adds an interest

func (*UserProfile) AddTech added in v0.4.10

func (up *UserProfile) AddTech(tech string) error

AddTech adds a technology to the tech stack

func (*UserProfile) Export added in v0.4.10

func (up *UserProfile) Export() ([]byte, error)

Export exports the profile as JSON

func (*UserProfile) GetAllPreferences added in v0.4.10

func (up *UserProfile) GetAllPreferences() []*UserPreference

GetAllPreferences returns all preferences

func (*UserProfile) GetForPrompt added in v0.4.10

func (up *UserProfile) GetForPrompt() string

GetForPrompt returns the user profile formatted for system prompt

func (*UserProfile) GetHighConfidence added in v0.4.10

func (up *UserProfile) GetHighConfidence(minConfidence float64) []*UserPreference

GetHighConfidence returns preferences with high confidence

func (*UserProfile) GetPreference added in v0.4.10

func (up *UserProfile) GetPreference(key string) *UserPreference

GetPreference returns a preference by key

func (*UserProfile) GetPreferencesBySource added in v0.4.10

func (up *UserProfile) GetPreferencesBySource(source string) []*UserPreference

GetPreferencesBySource returns preferences filtered by source

func (*UserProfile) Import added in v0.4.10

func (up *UserProfile) Import(data []byte) error

Import imports a profile from JSON

func (*UserProfile) LearnPreference added in v0.4.10

func (up *UserProfile) LearnPreference(key, value, context string) error

LearnPreference learns a preference from interaction

func (*UserProfile) Load added in v0.4.10

func (up *UserProfile) Load() error

Load loads the USER.md file

func (*UserProfile) Reset added in v0.4.10

func (up *UserProfile) Reset() error

Reset resets the user profile to default

func (*UserProfile) SetPreference added in v0.4.10

func (up *UserProfile) SetPreference(key, value string) error

SetPreference sets a user preference explicitly

Jump to

Keyboard shortcuts

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