memory

package
v0.4.4 Latest Latest
Warning

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

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

Documentation

Overview

Package memory provides a persistent memory system with FTS5 full-text search inspired by Cortex Agent's memory architecture

Index

Constants

View Source
const (
	MemoryLimitChars = 2200 // MEMORY.md max chars
	UserLimitChars   = 1375 // USER.md max chars
)

Character limits (not tokens) because char counts are model-independent This simulates human memory - you don't remember every word, just the conclusions

Variables

This section is empty.

Functions

This section is empty.

Types

type CacheConfig

type CacheConfig struct {
	Enabled    bool
	MaxEntries int
	TTL        time.Duration
}

CacheConfig configures the result cache

type CacheEntry

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

CacheEntry represents a cached search result

type EnhancedFTSStore

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

EnhancedFTSStore provides advanced full-text search with semantic capabilities

func NewEnhancedFTSStore

func NewEnhancedFTSStore(baseDir string) (*EnhancedFTSStore, error)

NewEnhancedFTSStore creates an enhanced FTS store with semantic search

func (*EnhancedFTSStore) Add

Add adds a new memory with deduplication and summarization

func (*EnhancedFTSStore) AddSynonym

func (f *EnhancedFTSStore) AddSynonym(term string, synonyms []string)

AddSynonym adds a synonym mapping

func (*EnhancedFTSStore) Cleanup

func (f *EnhancedFTSStore) Cleanup(olderThan time.Duration, minImportance int) (int, error)

Cleanup removes old or low-importance memories

func (*EnhancedFTSStore) ClearCache

func (f *EnhancedFTSStore) ClearCache()

ClearCache clears the search cache

func (*EnhancedFTSStore) Close

func (f *EnhancedFTSStore) Close() error

Close closes the FTS store

func (*EnhancedFTSStore) GetContext

func (f *EnhancedFTSStore) GetContext(query string, maxTokens int) string

GetContext retrieves relevant context with cross-session linking

func (*EnhancedFTSStore) GetCrossSessionMemories

func (f *EnhancedFTSStore) GetCrossSessionMemories(query string, currentSession string, limit int) ([]SearchResult, error)

GetCrossSessionMemories retrieves memories from previous sessions

func (*EnhancedFTSStore) GetDBStats

func (f *EnhancedFTSStore) GetDBStats() (map[string]interface{}, error)

GetDBStats returns database statistics

func (*EnhancedFTSStore) GetRelatedMemories

func (f *EnhancedFTSStore) GetRelatedMemories(memoryID int64, limit int) ([]EnhancedMemoryRecord, error)

GetRelatedMemories retrieves related memories via links

func (*EnhancedFTSStore) GetStats

func (f *EnhancedFTSStore) GetStats() *FTSStats

GetStats returns search statistics

func (*EnhancedFTSStore) Search

func (f *EnhancedFTSStore) Search(query string, options *EnhancedSearchOptions) ([]SearchResult, error)

Search performs enhanced full-text search with caching

func (*EnhancedFTSStore) SetCacheEnabled

func (f *EnhancedFTSStore) SetCacheEnabled(enabled bool)

SetCacheEnabled enables or disables caching

func (*EnhancedFTSStore) SetDecayConfig

func (f *EnhancedFTSStore) SetDecayConfig(config *ImportanceDecayConfig)

SetDecayConfig updates the importance decay configuration

type EnhancedMemoryRecord

type EnhancedMemoryRecord struct {
	MemoryRecord
	Summary         string    `json:"summary,omitempty"`
	ContentHash     string    `json:"content_hash,omitempty"`
	ParentID        int64     `json:"parent_id,omitempty"`
	LastAccessed    time.Time `json:"last_accessed"`
	AccessCount     int       `json:"access_count"`
	SimilarMemories []int64   `json:"similar_memories,omitempty"`
}

EnhancedMemoryRecord extends MemoryRecord with additional metadata

type EnhancedSearchOptions

type EnhancedSearchOptions struct {
	// Basic options
	Limit  int
	Offset int

	// Semantic options
	UseSynonyms   bool
	MinSimilarity float64

	// Time-based options
	TimeRange     *TimeRange
	SessionFilter []string

	// Content filters
	ContentTypes  []string
	MinImportance int
	Tags          []string

	// Ranking options
	BoostRecent     bool
	BoostImportance bool
	BoostFrequency  bool

	// Context options
	IncludeRelated bool
	MaxRelated     int
}

EnhancedSearchOptions provides advanced search options

type FTSStats

type FTSStats struct {
	TotalSearches int64           `json:"total_searches"`
	TotalHits     int64           `json:"total_hits"`
	AvgLatencyMs  float64         `json:"avg_latency_ms"`
	CacheHits     int64           `json:"cache_hits"`
	CacheMisses   int64           `json:"cache_misses"`
	QueryCounts   map[string]int  `json:"query_counts"`
	TopTerms      []TermFrequency `json:"top_terms"`
}

FTSStats holds search statistics

type FTSStore

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

FTSStore provides full-text search across all conversation history This is System 5 of the Cortex six systems: "Holographic memory retrieval with SQLite FTS5"

func NewFTSStore

func NewFTSStore(baseDir string) (*FTSStore, error)

NewFTSStore creates a new FTS-based memory store

func (*FTSStore) Add

func (f *FTSStore) Add(memory *MemoryRecord) error

Add adds a new memory to the FTS store

func (*FTSStore) AddInsight

func (f *FTSStore) AddInsight(sessionID string, insight string, importance int) error

AddInsight adds a structured insight learned from conversation

func (*FTSStore) CleanupOld

func (f *FTSStore) CleanupOld(olderThan time.Duration, keepMinImportance int) (int, error)

CleanupOld removes old memories beyond retention policy

func (*FTSStore) Close

func (f *FTSStore) Close() error

Close closes the database connection

func (*FTSStore) GetContext

func (f *FTSStore) GetContext(query string, maxTokens int) string

GetContext retrieves relevant context for a query This is used to augment the system prompt with relevant memories

func (*FTSStore) GetInsights

func (f *FTSStore) GetInsights(minImportance int) ([]MemoryRecord, error)

GetInsights retrieves all learned insights

func (*FTSStore) GetSession

func (f *FTSStore) GetSession(sessionID string) ([]MemoryRecord, error)

GetSession retrieves all memories for a specific session

func (*FTSStore) GetStats

func (f *FTSStore) GetStats() (map[string]interface{}, error)

GetStats returns statistics about the memory store

func (*FTSStore) Search

func (f *FTSStore) Search(query string, limit int) ([]SearchResult, error)

Search performs a full-text search across all memories

type ImportanceDecayConfig

type ImportanceDecayConfig struct {
	BaseDecayRate float64       // Daily decay rate (0-1)
	MinImportance int           // Minimum importance floor
	DecayInterval time.Duration // How often to apply decay
}

ImportanceDecayConfig configures how memory importance decays over time

type Memory

type Memory struct {
	ID          string     `json:"id"`
	Type        MemoryType `json:"type"`
	Content     string     `json:"content"`
	Scope       string     `json:"scope,omitempty"`      // Hierarchical path like /infrastructure/database
	Categories  []string   `json:"categories,omitempty"` // Tags
	Importance  float64    `json:"importance"`           // 0.0 - 1.0
	Metadata    string     `json:"metadata,omitempty"`   // JSON metadata
	CreatedAt   time.Time  `json:"created_at"`
	UpdatedAt   time.Time  `json:"updated_at"`
	LastAccess  time.Time  `json:"last_access"`
	AccessCount int        `json:"access_count"`
	SessionID   string     `json:"session_id,omitempty"` // Associated session
	Source      string     `json:"source,omitempty"`     // How it was created
}

Memory represents a single memory entry

type MemoryCompressor

type MemoryCompressor struct {
}

MemoryCompressor handles memory summarization when limits are reached

type MemoryConfig

type MemoryConfig struct {
	DBPath             string
	MaxContentLength   int    // Max characters per memory
	MaxAgentMemLength  int    // Max characters for agent memory file
	MaxUserMemLength   int    // Max characters for user memory file
	AutoSummarize      bool   // Enable automatic summarization
	SummarizeThreshold int    // Threshold for summarization (characters)
	LLMProvider        string // LLM provider for summarization
}

MemoryConfig holds configuration for the memory system

func DefaultConfig

func DefaultConfig() *MemoryConfig

DefaultConfig returns the default memory configuration

type MemoryRecord

type MemoryRecord struct {
	ID          int       `json:"id"`
	SessionID   string    `json:"session_id"`
	TurnNumber  int       `json:"turn_number"`
	Role        string    `json:"role"`
	Content     string    `json:"content"`
	ContentType string    `json:"content_type"`
	Tags        []string  `json:"tags,omitempty"`
	Importance  int       `json:"importance"`
	CreatedAt   time.Time `json:"created_at"`
}

MemoryRecord represents a single memory entry

type MemoryStats

type MemoryStats struct {
	TotalMemories int
	ByType        map[MemoryType]int
	TotalSearches int
	AvgImportance float64
	LastUpdated   time.Time
}

Stats returns memory statistics

type MemoryTool

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

MemoryTool provides CLI commands for memory operations

func NewMemoryTool

func NewMemoryTool(store *Store) *MemoryTool

NewMemoryTool creates a new memory tool

func (*MemoryTool) Commands

func (m *MemoryTool) Commands() []*cobra.Command

Commands returns the memory CLI commands

type MemoryType

type MemoryType string

Memory types

const (
	TypeAgent      MemoryType = "agent"      // Agent's own notes
	TypeUser       MemoryType = "user"       // User profile and preferences
	TypeSession    MemoryType = "session"    // Session-specific information
	TypeProject    MemoryType = "project"    // Project-related memories
	TypeKnowledge  MemoryType = "knowledge"  // General knowledge
	TypePreference MemoryType = "preference" // User preferences
)

type SearchCache

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

SearchCache implements LRU caching for search results

type SearchResult

type SearchResult struct {
	MemoryRecord
	Rank    float64 `json:"rank"`    // BM25 score, lower = better
	Snippet string  `json:"snippet"` // Highlighted snippet
}

SearchResult represents a search result with rank

type SessionLink struct {
	SourceID  int64     `json:"source_id"`
	TargetID  int64     `json:"target_id"`
	LinkType  string    `json:"link_type"` // "related", "follows", "references"
	CreatedAt time.Time `json:"created_at"`
	Strength  float64   `json:"strength"` // 0-1
}

SessionLink represents a link between memories across sessions

type SnapshotManager

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

SnapshotManager implements the "frozen snapshot" pattern from Cortex Agent Memory updates are written to disk immediately but the current turn uses a frozen snapshot to protect prefix cache This is crucial for cost optimization with Anthropic's prefix caching

func NewSnapshotManager

func NewSnapshotManager(baseDir string) *SnapshotManager

NewSnapshotManager creates a new snapshot manager

func (*SnapshotManager) AppendToMemory

func (sm *SnapshotManager) AppendToMemory(line string) error

AppendToMemory appends a line to memory

func (*SnapshotManager) AppendToUser

func (sm *SnapshotManager) AppendToUser(line string) error

AppendToUser appends a line to user profile

func (*SnapshotManager) GetLatestMemory

func (sm *SnapshotManager) GetLatestMemory() string

GetLatestMemory returns the latest memory (not frozen)

func (*SnapshotManager) GetLatestUser

func (sm *SnapshotManager) GetLatestUser() string

GetLatestUser returns the latest user profile (not frozen)

func (*SnapshotManager) GetMemoryForPrompt

func (sm *SnapshotManager) GetMemoryForPrompt() string

GetMemoryForPrompt returns the memory content to include in system prompt Uses the frozen snapshot, NOT the latest

func (*SnapshotManager) GetUserForPrompt

func (sm *SnapshotManager) GetUserForPrompt() string

GetUserForPrompt returns the user profile to include in system prompt Uses the frozen snapshot, NOT the latest

func (*SnapshotManager) GetVersion

func (sm *SnapshotManager) GetVersion() int

GetVersion returns the current memory version

func (*SnapshotManager) Load

func (sm *SnapshotManager) Load() error

Load loads the latest memory from disk

func (*SnapshotManager) OnTurnStart

func (sm *SnapshotManager) OnTurnStart()

OnTurnStart is called at the beginning of each turn Uses the frozen snapshot for this turn, does NOT refresh

func (*SnapshotManager) RefreshSnapshot

func (sm *SnapshotManager) RefreshSnapshot()

RefreshSnapshot is called at session end or start of a new conversation Refreshes the frozen snapshot with latest memory

func (*SnapshotManager) UpdateMemory

func (sm *SnapshotManager) UpdateMemory(content string) error

UpdateMemory updates memory, writes to disk immediately but does NOT refresh the frozen snapshot

func (*SnapshotManager) UpdateUser

func (sm *SnapshotManager) UpdateUser(content string) error

UpdateUser updates user profile, writes to disk immediately but does NOT refresh the frozen snapshot

type Store

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

Store manages the persistent memory system

func NewStore

func NewStore(config *MemoryConfig) (*Store, error)

NewStore creates a new memory store

func (*Store) AppendAgentMemory

func (s *Store) AppendAgentMemory(content string) error

AppendAgentMemory appends content to agent memory (Cortex-style)

func (*Store) AppendUserMemory

func (s *Store) AppendUserMemory(content string) error

AppendUserMemory appends content to user memory (Cortex-style)

func (*Store) Close

func (s *Store) Close() error

Close closes the memory store

func (*Store) Delete

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

Delete removes a memory by ID

func (*Store) DeleteByScope

func (s *Store) DeleteByScope(scope string) error

DeleteByScope removes all memories in a scope

func (*Store) GetCommandTrustLevel

func (s *Store) GetCommandTrustLevel(commandHash string) (action string, count int, err error)

GetCommandTrustLevel returns how trusted a command pattern is

func (*Store) List

func (s *Store) List(memoryType MemoryType, limit, offset int) ([]*Memory, error)

List returns all memories, optionally filtered by type

func (*Store) ReadAgentMemory

func (s *Store) ReadAgentMemory() (string, error)

ReadAgentMemory reads the Cortex-style agent memory file

func (*Store) ReadUserMemory

func (s *Store) ReadUserMemory() (string, error)

ReadUserMemory reads the Cortex-style user profile file

func (*Store) Recall

func (s *Store) Recall(query string, limit int, memoryTypes ...MemoryType) ([]*Memory, error)

Recall searches for relevant memories based on query

func (*Store) RecordCommandAction

func (s *Store) RecordCommandAction(command, action, sessionID string) error

RecordCommandAction records a command approval/denial

func (*Store) Search

func (s *Store) Search(query string, limit int) ([]*Memory, error)

Search performs FTS5 full-text search

func (*Store) Stats

func (s *Store) Stats() (*MemoryStats, error)

func (*Store) Store

func (s *Store) Store(m *Memory) error

Store adds a new memory

func (*Store) Summarize

func (s *Store) Summarize(memories []*Memory) (string, error)

Summarize uses LLM to summarize memories

func (*Store) Update

func (s *Store) Update(m *Memory) error

Update updates an existing memory

func (*Store) WriteAgentMemory

func (s *Store) WriteAgentMemory(content string) error

WriteAgentMemory writes to the Cortex-style agent memory file

func (*Store) WriteUserMemory

func (s *Store) WriteUserMemory(content string) error

WriteUserMemory writes to the Cortex-style user profile file

type TermFrequency

type TermFrequency struct {
	Term      string `json:"term"`
	Frequency int    `json:"frequency"`
}

TermFrequency represents term frequency data

type TimeRange

type TimeRange struct {
	Start time.Time
	End   time.Time
}

TimeRange represents a time range for filtering

type ToolFunction

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

ToolFunction represents a callable memory tool (for API use)

func NewToolFunction

func NewToolFunction(store *Store) *ToolFunction

NewToolFunction creates a new memory tool function

func (*ToolFunction) Execute

func (t *ToolFunction) Execute(params map[string]interface{}) (*ToolResult, error)

Execute runs a memory operation

func (*ToolFunction) ToolDefinition

func (t *ToolFunction) ToolDefinition() map[string]interface{}

ToolDefinition returns the OpenAI-style tool definition

type ToolResult

type ToolResult struct {
	Success bool        `json:"success"`
	Data    interface{} `json:"data,omitempty"`
	Error   string      `json:"error,omitempty"`
}

ToolResult represents the result of a memory operation

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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