memory

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: May 26, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package memory provides knowledge, experience, and memory consolidation types.

Public types: KnowledgeEntry, KnowledgeStats, KnowledgeBase, Experience, ExperienceStats, ExperienceStore, RawMemory, ConsolidatedMemory, ConsolidatorStats, MemoryConsolidator.

Public functions: NewKnowledgeBase, NewExperienceStore, NewMemoryConsolidator.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ConsolidatedMemory

type ConsolidatedMemory struct {
	ID         string     `json:"id"`
	Category   string     `json:"category"` // "fact", "convention", "decision", "warning", "skill"
	Content    string     `json:"content"`
	Confidence float64    `json:"confidence"`
	References []string   `json:"references"`
	CreatedAt  time.Time  `json:"created_at"`
	ExpiresAt  *time.Time `json:"expires_at,omitempty"`
}

ConsolidatedMemory represents a processed, structured long-term memory.

type ConsolidatorStats

type ConsolidatorStats struct {
	RawCount          int       `json:"raw_count"`
	ProcessedCount    int       `json:"processed_count"`
	ConsolidatedCount int       `json:"consolidated_count"`
	FactCount         int       `json:"fact_count"`
	ConventionCount   int       `json:"convention_count"`
	DecisionCount     int       `json:"decision_count"`
	WarningCount      int       `json:"warning_count"`
	SkillCount        int       `json:"skill_count"`
	AvgConfidence     float64   `json:"avg_confidence"`
	LastConsolidation time.Time `json:"last_consolidation"`
}

ConsolidatorStats holds aggregate statistics about the memory consolidator.

type Experience

type Experience struct {
	ID            string        `json:"id"`
	Task          string        `json:"task"`
	Approach      string        `json:"approach"`
	Steps         []string      `json:"steps"`
	Outcome       string        `json:"outcome"`
	ToolsUsed     []string      `json:"tools_used"`
	FilesModified []string      `json:"files_modified"`
	TokensUsed    int           `json:"tokens_used"`
	Duration      time.Duration `json:"duration"`
	Score         float64       `json:"score"`
	Tags          []string      `json:"tags"`
	CreatedAt     time.Time     `json:"created_at"`
	UsedCount     int           `json:"used_count"`
}

Experience represents a single recorded task completion with its context and outcome.

type ExperienceStats

type ExperienceStats struct {
	TotalExperiences int            `json:"total_experiences"`
	AvgScore         float64        `json:"avg_score"`
	AvgTokens        int            `json:"avg_tokens"`
	AvgDuration      time.Duration  `json:"avg_duration"`
	ByOutcome        map[string]int `json:"by_outcome"`
	TopTags          []string       `json:"top_tags"`
	TopTools         []string       `json:"top_tools"`
}

ExperienceStats holds aggregate statistics about the experience store.

type ExperienceStore

type ExperienceStore struct {
	Experiences []*Experience
	Dir         string
	// contains filtered or unexported fields
}

ExperienceStore manages a collection of experiences with persistence.

func NewExperienceStore

func NewExperienceStore(dir string) *ExperienceStore

NewExperienceStore creates a new ExperienceStore that persists to the given directory.

func (*ExperienceStore) BuildExperienceContext

func (es *ExperienceStore) BuildExperienceContext(task string, maxTokens int) string

BuildExperienceContext formats relevant experiences for prompt injection.

func (*ExperienceStore) Deduplicate

func (es *ExperienceStore) Deduplicate() int

Deduplicate removes experiences that are too similar to each other, keeping the one with the higher score.

func (*ExperienceStore) FindRelevant

func (es *ExperienceStore) FindRelevant(task string, limit int) []*Experience

FindRelevant returns the most relevant experiences for a given task description.

func (*ExperienceStore) Generalize

func (es *ExperienceStore) Generalize(exp *Experience) *Experience

Generalize creates a generalized version of an experience by stripping specific details.

func (*ExperienceStore) Load

func (es *ExperienceStore) Load() error

Load reads experiences from the JSON file in the store directory.

func (*ExperienceStore) Prune

func (es *ExperienceStore) Prune(maxAge time.Duration, minScore float64) int

Prune removes experiences older than maxAge or below minScore.

func (*ExperienceStore) Record

func (es *ExperienceStore) Record(task, approach, outcome string, steps, tools, files []string, tokens int, duration time.Duration) *Experience

Record creates a new experience entry from a completed task.

func (*ExperienceStore) Save

func (es *ExperienceStore) Save() error

Save persists all experiences to a JSON file in the store directory.

func (*ExperienceStore) Stats

func (es *ExperienceStore) Stats() ExperienceStats

Stats returns aggregate statistics about the experience store.

type KnowledgeBase

type KnowledgeBase struct {
	Entries    map[string]*KnowledgeEntry `json:"entries"`
	Categories map[string][]string        `json:"categories"`
	Dir        string                     `json:"-"`
	// contains filtered or unexported fields
}

KnowledgeBase stores distilled patterns extracted from successful sessions.

func NewKnowledgeBase

func NewKnowledgeBase(dir string) *KnowledgeBase

NewKnowledgeBase creates a new KnowledgeBase that persists to the given directory.

func (*KnowledgeBase) Add

func (kb *KnowledgeBase) Add(entry *KnowledgeEntry) error

Add inserts a new knowledge entry into the base.

func (*KnowledgeBase) BuildContextForTask

func (kb *KnowledgeBase) BuildContextForTask(task string, maxTokens int) string

BuildContextForTask formats relevant knowledge for prompt injection, respecting a token budget.

func (*KnowledgeBase) ExtractFromSession

func (kb *KnowledgeBase) ExtractFromSession(messages []string, outcome string) []*KnowledgeEntry

ExtractFromSession uses heuristics to extract knowledge entries from a session's messages and outcome.

func (*KnowledgeBase) FormatEntry

func (kb *KnowledgeBase) FormatEntry(entry *KnowledgeEntry) string

FormatEntry formats a knowledge entry for display or prompt injection.

func (*KnowledgeBase) GetByCategory

func (kb *KnowledgeBase) GetByCategory(category string) []*KnowledgeEntry

GetByCategory returns all entries in the given category.

func (*KnowledgeBase) Load

func (kb *KnowledgeBase) Load() error

Load reads the knowledge base from disk.

func (*KnowledgeBase) Merge

func (kb *KnowledgeBase) Merge(other *KnowledgeBase)

Merge combines another KnowledgeBase into this one, deduplicating by content similarity.

func (*KnowledgeBase) Prune

func (kb *KnowledgeBase) Prune(minConfidence float64, maxAge time.Duration)

Prune removes entries below minimum confidence or older than maxAge.

func (*KnowledgeBase) Save

func (kb *KnowledgeBase) Save() error

Save persists the knowledge base to JSON files in the configured directory.

func (*KnowledgeBase) Search

func (kb *KnowledgeBase) Search(query string, limit int) []*KnowledgeEntry

Search performs keyword search ranked by relevance, usage, and recency.

func (*KnowledgeBase) Stats

func (kb *KnowledgeBase) Stats() KnowledgeStats

Stats returns aggregate statistics about the knowledge base.

type KnowledgeEntry

type KnowledgeEntry struct {
	ID         string    `json:"id"`
	Title      string    `json:"title"`
	Content    string    `json:"content"`
	Category   string    `json:"category"` // "pattern", "anti-pattern", "convention", "shortcut", "gotcha"
	Language   string    `json:"language"`
	Tags       []string  `json:"tags"`
	Examples   []string  `json:"examples"`
	Confidence float64   `json:"confidence"`
	UsageCount int       `json:"usage_count"`
	LastUsed   time.Time `json:"last_used"`
	CreatedAt  time.Time `json:"created_at"`
	Source     string    `json:"source"`
}

KnowledgeEntry represents a single piece of distilled knowledge.

type KnowledgeStats

type KnowledgeStats struct {
	TotalEntries  int            `json:"total_entries"`
	ByCategory    map[string]int `json:"by_category"`
	ByLanguage    map[string]int `json:"by_language"`
	AvgConfidence float64        `json:"avg_confidence"`
	MostUsed      []string       `json:"most_used"`
}

KnowledgeStats holds aggregate statistics about the knowledge base.

type MemoryConsolidator

type MemoryConsolidator struct {
	RawMemories          []RawMemory          `json:"raw_memories"`
	ConsolidatedMemories []ConsolidatedMemory `json:"consolidated_memories"`
	Dir                  string               `json:"-"`
	LastConsolidation    time.Time            `json:"last_consolidation"`
	// contains filtered or unexported fields
}

MemoryConsolidator processes raw session data into structured long-term memory during idle time, inspired by the "sleeptime" pattern.

func NewMemoryConsolidator

func NewMemoryConsolidator(dir string) *MemoryConsolidator

NewMemoryConsolidator creates a new MemoryConsolidator that persists data in dir.

func (*MemoryConsolidator) Consolidate

func (mc *MemoryConsolidator) Consolidate() ([]ConsolidatedMemory, error)

Consolidate processes unprocessed raw memories into structured consolidated memories. It extracts facts, conventions, decisions, and warnings, deduplicates them against existing consolidated memories, and marks raw memories as processed.

func (*MemoryConsolidator) Expire

func (mc *MemoryConsolidator) Expire()

Expire removes memories that have passed their expiration time.

func (*MemoryConsolidator) ExtractConventions

func (mc *MemoryConsolidator) ExtractConventions(raw []RawMemory) []ConsolidatedMemory

ExtractConventions identifies convention statements from raw memories. Patterns: "always", "never", "must", "should"

func (*MemoryConsolidator) ExtractDecisions

func (mc *MemoryConsolidator) ExtractDecisions(raw []RawMemory) []ConsolidatedMemory

ExtractDecisions identifies decision statements from raw memories. Patterns: "decided", "chose", "went with", "because"

func (*MemoryConsolidator) ExtractFacts

func (mc *MemoryConsolidator) ExtractFacts(raw []RawMemory) []ConsolidatedMemory

ExtractFacts identifies factual statements from raw memories. Patterns: "X is Y", "X uses Y", "X has Y"

func (*MemoryConsolidator) FormatMemories

func (mc *MemoryConsolidator) FormatMemories(memories []ConsolidatedMemory) string

FormatMemories formats consolidated memories into a human-readable string.

func (*MemoryConsolidator) Ingest

func (mc *MemoryConsolidator) Ingest(content, source, sessionID string)

Ingest adds raw content to the memory queue for later consolidation.

func (*MemoryConsolidator) Load

func (mc *MemoryConsolidator) Load() error

Load restores the consolidator state from disk.

func (*MemoryConsolidator) Recall

func (mc *MemoryConsolidator) Recall(query string, limit int) []ConsolidatedMemory

Recall searches consolidated memories by keyword relevance and returns up to limit results.

func (*MemoryConsolidator) Save

func (mc *MemoryConsolidator) Save() error

Save persists the consolidator state to disk.

func (*MemoryConsolidator) Stats

Stats returns aggregate statistics about the consolidator state.

type RawMemory

type RawMemory struct {
	Content   string    `json:"content"`
	Source    string    `json:"source"` // "session", "tool_output", "user_feedback"
	SessionID string    `json:"session_id"`
	Timestamp time.Time `json:"timestamp"`
	Processed bool      `json:"processed"`
}

RawMemory represents an unprocessed memory ingested from a session.

Jump to

Keyboard shortcuts

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