knowledge

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Mar 9, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrKnowledgeNotFound = errors.New("knowledge not found")
	ErrLearningNotFound  = errors.New("learning not found")
)

Functions

This section is empty.

Types

type AuditEntry

type AuditEntry struct {
	SessionKey string
	Action     string
	Actor      string
	Target     string
	Details    map[string]interface{}
}

AuditEntry is the domain type for audit log writes.

type ContextItem

type ContextItem struct {
	Layer    ContextLayer
	Key      string
	Content  string
	Score    float64
	Source   string
	Category string
}

ContextItem represents a single item from any context layer.

type ContextLayer

type ContextLayer int

ContextLayer represents the 6 context layers in the self-learning architecture.

const (
	LayerToolRegistry      ContextLayer = iota + 1
	LayerUserKnowledge                  // User rules, preferences, definitions, facts
	LayerSkillPatterns                  // Known working tool chains and workflows
	LayerExternalKnowledge              // Docs, wiki, MCP integration
	LayerAgentLearnings                 // Error patterns, discovered fixes
	LayerRuntimeContext                 // Session history, tool results, env state
	LayerObservations                   // Compressed conversation observations
	LayerReflections                    // Condensed observation reflections
	LayerPendingInquiries               // Proactive librarian pending questions
)

func (ContextLayer) Valid

func (l ContextLayer) Valid() bool

Valid reports whether l is a known context layer.

func (ContextLayer) Values

func (l ContextLayer) Values() []ContextLayer

Values returns all known context layers.

type ContextRetriever

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

ContextRetriever searches the context layers and assembles augmented prompts.

func NewContextRetriever

func NewContextRetriever(store *Store, maxPerLayer int, logger *zap.SugaredLogger) *ContextRetriever

NewContextRetriever creates a new context retriever.

func (*ContextRetriever) AssemblePrompt

func (r *ContextRetriever) AssemblePrompt(basePrompt string, result *RetrievalResult) string

AssemblePrompt builds an augmented system prompt from base prompt and retrieved context.

func (*ContextRetriever) Retrieve

Retrieve searches the requested context layers and returns relevant items.

func (*ContextRetriever) WithInquiryProvider

func (r *ContextRetriever) WithInquiryProvider(p InquiryProvider) *ContextRetriever

WithInquiryProvider sets the inquiry provider for proactive librarian context.

func (*ContextRetriever) WithRuntimeContext

func (r *ContextRetriever) WithRuntimeContext(p RuntimeContextProvider) *ContextRetriever

WithRuntimeContext sets the runtime context provider.

func (*ContextRetriever) WithSkillProvider

func (r *ContextRetriever) WithSkillProvider(p SkillProvider) *ContextRetriever

WithSkillProvider sets the skill provider for context retrieval.

func (*ContextRetriever) WithToolRegistry

func (r *ContextRetriever) WithToolRegistry(p ToolRegistryProvider) *ContextRetriever

WithToolRegistry sets the tool registry provider.

type ExternalRefEntry

type ExternalRefEntry struct {
	Name     string
	RefType  string
	Location string
	Summary  string
	Metadata map[string]interface{}
}

ExternalRefEntry is the domain type for external reference CRUD operations.

type InquiryProvider

type InquiryProvider interface {
	PendingInquiryItems(ctx context.Context, sessionKey string, limit int) ([]ContextItem, error)
}

InquiryProvider supplies pending knowledge inquiries for context injection.

type KnowledgeEntry

type KnowledgeEntry struct {
	Key      string
	Category entknowledge.Category
	Content  string
	Tags     []string
	Source   string
}

KnowledgeEntry is the domain type for knowledge CRUD operations.

type LearningEntry

type LearningEntry struct {
	Trigger      string
	ErrorPattern string
	Diagnosis    string
	Fix          string
	Category     entlearning.Category
	Tags         []string
}

LearningEntry is the domain type for learning CRUD operations.

type LearningStats

type LearningStats struct {
	TotalCount       int                          `json:"total_count"`
	ByCategory       map[entlearning.Category]int `json:"by_category"`
	AvgConfidence    float64                      `json:"avg_confidence"`
	OldestEntry      time.Time                    `json:"oldest_entry,omitempty"`
	NewestEntry      time.Time                    `json:"newest_entry,omitempty"`
	TotalOccurrences int                          `json:"total_occurrences"`
	TotalSuccesses   int                          `json:"total_successes"`
}

LearningStats holds aggregate statistics about learning entries.

type RetrievalRequest

type RetrievalRequest struct {
	Query       string
	SessionKey  string
	Tags        []string
	Layers      []ContextLayer // nil means all layers
	MaxPerLayer int            // 0 uses config default
}

RetrievalRequest specifies what context to retrieve.

type RetrievalResult

type RetrievalResult struct {
	Items      map[ContextLayer][]ContextItem
	TotalItems int
}

RetrievalResult contains retrieved context items grouped by layer.

type RuntimeContext

type RuntimeContext struct {
	SessionKey        string
	ChannelType       string // "telegram", "discord", "slack", "direct"
	ActiveToolCount   int
	EncryptionEnabled bool
	KnowledgeEnabled  bool
	MemoryEnabled     bool
}

RuntimeContext holds the current session and system state.

type RuntimeContextProvider

type RuntimeContextProvider interface {
	GetRuntimeContext() RuntimeContext
}

RuntimeContextProvider supplies current session/system state.

type SkillInfo

type SkillInfo struct {
	Name        string
	Description string
	Type        string
}

SkillInfo describes a single skill for context retrieval.

type SkillProvider

type SkillProvider interface {
	ListActiveSkillInfos(ctx context.Context) ([]SkillInfo, error)
}

SkillProvider supplies active skill information.

type Store

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

Store provides CRUD operations for knowledge, learning, skill, audit, and external ref entities.

func NewStore

func NewStore(client *ent.Client, logger *zap.SugaredLogger) *Store

NewStore creates a new knowledge store.

func (*Store) BoostLearningConfidence

func (s *Store) BoostLearningConfidence(ctx context.Context, id uuid.UUID, successDelta int, confidenceBoost float64) error

BoostLearningConfidence increments success count and recalculates confidence. When confidenceBoost > 0, it is added directly to the current confidence (for fractional graph propagation). When 0, the existing success/occurrence ratio is used. Confidence is always clamped to [0.1, 1.0].

func (*Store) DeleteKnowledge

func (s *Store) DeleteKnowledge(ctx context.Context, key string) error

DeleteKnowledge deletes a knowledge entry by key.

func (*Store) DeleteLearning

func (s *Store) DeleteLearning(ctx context.Context, id uuid.UUID) error

DeleteLearning deletes a single learning entry by UUID.

func (*Store) DeleteLearningsWhere

func (s *Store) DeleteLearningsWhere(ctx context.Context, category string, maxConfidence float64, olderThan time.Time) (int, error)

DeleteLearningsWhere deletes learning entries matching the given criteria and returns the number of deleted entries.

func (*Store) GetKnowledge

func (s *Store) GetKnowledge(ctx context.Context, key string) (*KnowledgeEntry, error)

GetKnowledge retrieves a knowledge entry by key.

func (*Store) GetLearning

func (s *Store) GetLearning(ctx context.Context, id uuid.UUID) (*LearningEntry, error)

GetLearning retrieves a learning entry by its UUID.

func (*Store) GetLearningStats

func (s *Store) GetLearningStats(ctx context.Context) (*LearningStats, error)

GetLearningStats returns aggregate statistics about stored learning entries.

func (*Store) IncrementKnowledgeUseCount

func (s *Store) IncrementKnowledgeUseCount(ctx context.Context, key string) error

IncrementKnowledgeUseCount increments the use count for a knowledge entry.

func (*Store) ListLearnings

func (s *Store) ListLearnings(ctx context.Context, category string, minConfidence float64, olderThan time.Time, limit, offset int) ([]*ent.Learning, int, error)

ListLearnings returns learning entries with optional filtering and pagination. Pass zero-value for parameters to skip a filter.

func (*Store) SaveAuditLog

func (s *Store) SaveAuditLog(ctx context.Context, entry AuditEntry) error

SaveAuditLog creates a new audit log entry.

func (*Store) SaveExternalRef

func (s *Store) SaveExternalRef(ctx context.Context, name, refType, location, summary string) error

SaveExternalRef creates or updates an external reference.

func (*Store) SaveKnowledge

func (s *Store) SaveKnowledge(ctx context.Context, sessionKey string, entry KnowledgeEntry) error

SaveKnowledge creates or updates a knowledge entry by key.

func (*Store) SaveLearning

func (s *Store) SaveLearning(ctx context.Context, sessionKey string, entry LearningEntry) error

SaveLearning creates a new learning entry.

func (*Store) SearchExternalRefs

func (s *Store) SearchExternalRefs(ctx context.Context, query string) ([]ExternalRefEntry, error)

SearchExternalRefs searches external references by name or summary. Uses per-keyword OR predicates to avoid SQLite LIKE pattern complexity limits.

func (*Store) SearchKnowledge

func (s *Store) SearchKnowledge(ctx context.Context, query string, category string, limit int) ([]KnowledgeEntry, error)

SearchKnowledge searches knowledge entries by content/key keyword matching. The query is split into individual keywords and matched with per-keyword OR predicates to avoid SQLite LIKE pattern complexity limits.

func (*Store) SearchLearningEntities

func (s *Store) SearchLearningEntities(ctx context.Context, errorPattern string, limit int) ([]*ent.Learning, error)

SearchLearningEntities searches learnings and returns raw Ent entities for confidence boosting. Uses per-keyword OR predicates to avoid SQLite LIKE pattern complexity limits.

func (*Store) SearchLearnings

func (s *Store) SearchLearnings(ctx context.Context, errorPattern string, category string, limit int) ([]LearningEntry, error)

SearchLearnings searches learnings by error pattern or trigger substring match. The query is split into individual keywords and matched with per-keyword OR predicates to avoid SQLite LIKE pattern complexity limits.

func (*Store) SetEmbedCallback

func (s *Store) SetEmbedCallback(cb types.EmbedCallback)

SetEmbedCallback sets the optional embedding hook.

func (*Store) SetGraphCallback

func (s *Store) SetGraphCallback(cb types.ContentCallback)

SetGraphCallback sets the optional graph relationship hook.

type ToolDescriptor

type ToolDescriptor struct {
	Name        string
	Description string
}

ToolDescriptor describes a single tool available to the agent.

type ToolRegistryProvider

type ToolRegistryProvider interface {
	ListTools() []ToolDescriptor
	SearchTools(query string, limit int) []ToolDescriptor
}

ToolRegistryProvider supplies available tool information.

Jump to

Keyboard shortcuts

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