Documentation
¶
Overview ¶
Package memory provides a persistent memory system with FTS5 full-text search inspired by Cortex Agent's memory architecture
Index ¶
- Constants
- func CalculateRelevanceScore(mem *Memory, query string, now time.Time) float64
- func SummarizeMemories(memories []*Memory) string
- type FTSStore
- func (f *FTSStore) Add(memory *MemoryRecord) error
- func (f *FTSStore) AddInsight(sessionID string, insight string, importance int) error
- func (f *FTSStore) CleanupOld(olderThan time.Duration, keepMinImportance int) (int, error)
- func (f *FTSStore) Close() error
- func (f *FTSStore) GetContext(query string, maxTokens int) string
- func (f *FTSStore) GetInsights(minImportance int) ([]MemoryRecord, error)
- func (f *FTSStore) GetSession(sessionID string) ([]MemoryRecord, error)
- func (f *FTSStore) GetStats() (map[string]interface{}, error)
- func (f *FTSStore) Search(query string, limit int) ([]SearchResult, error)
- type Memory
- type MemoryCompressor
- type MemoryConfig
- type MemoryExtractor
- func (me *MemoryExtractor) ExtractMemories(ctx context.Context, messages []provider.Message, sessionID string) ([]*Memory, error)
- func (me *MemoryExtractor) GetTopMemories(query string, limit int, now time.Time, memTypes ...MemoryType) []*Memory
- func (me *MemoryExtractor) ShouldExtract(turn int) bool
- func (me *MemoryExtractor) StoreMemories(memories []*Memory) error
- type MemoryExtractorConfig
- type MemoryRecord
- type MemoryStats
- type MemoryTool
- type MemoryType
- type SearchResult
- type SnapshotManager
- func (sm *SnapshotManager) AppendToMemory(line string) error
- func (sm *SnapshotManager) AppendToUser(line string) error
- func (sm *SnapshotManager) GetLatestMemory() string
- func (sm *SnapshotManager) GetLatestUser() string
- func (sm *SnapshotManager) GetMemoryForPrompt() string
- func (sm *SnapshotManager) GetUserForPrompt() string
- func (sm *SnapshotManager) GetVersion() int
- func (sm *SnapshotManager) Load() error
- func (sm *SnapshotManager) OnTurnStart()
- func (sm *SnapshotManager) RefreshSnapshot()
- func (sm *SnapshotManager) UpdateMemory(content string) error
- func (sm *SnapshotManager) UpdateUser(content string) error
- type Store
- func (s *Store) AppendAgentMemory(content string) error
- func (s *Store) AppendUserMemory(content string) error
- func (s *Store) Close() error
- func (s *Store) Delete(id string) error
- func (s *Store) DeleteByScope(scope string) error
- func (s *Store) GetCommandTrustLevel(commandHash string) (action string, count int, err error)
- func (s *Store) List(memoryType MemoryType, limit, offset int) ([]*Memory, error)
- func (s *Store) ReadAgentMemory() (string, error)
- func (s *Store) ReadUserMemory() (string, error)
- func (s *Store) Recall(query string, limit int, memoryTypes ...MemoryType) ([]*Memory, error)
- func (s *Store) RecordCommandAction(command, action, sessionID string) error
- func (s *Store) Search(query string, limit int) ([]*Memory, error)
- func (s *Store) Stats() (*MemoryStats, error)
- func (s *Store) Store(m *Memory) error
- func (s *Store) Summarize(memories []*Memory) (string, error)
- func (s *Store) Update(m *Memory) error
- func (s *Store) WriteAgentMemory(content string) error
- func (s *Store) WriteUserMemory(content string) error
- type ToolFunction
- type ToolResult
Constants ¶
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 ¶
func CalculateRelevanceScore ¶ added in v0.5.1
CalculateRelevanceScore calculates the relevance of a memory considering decay
func SummarizeMemories ¶ added in v0.5.1
SummarizeMemories generates a summary of retrieved memories for injection
Types ¶
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 ¶
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 ¶
AddInsight adds a structured insight learned from conversation
func (*FTSStore) CleanupOld ¶
CleanupOld removes old memories beyond retention policy
func (*FTSStore) GetContext ¶
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
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. Uses a section-aware strategy: preserves structure (headers, key facts) while trimming verbose sections and removing duplicates.
func (*MemoryCompressor) CompressMemory ¶ added in v0.4.12
func (mc *MemoryCompressor) CompressMemory(content string, limit int) string
CompressMemory uses a section-aware strategy to compress memory: 1. Split by sections (## headers) 2. Keep all section headers 3. Within each section, keep the first and last sentence 4. Deduplicate consecutive identical lines 5. If still over limit, keep first 60% and last 40% of sections
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 MemoryExtractor ¶ added in v0.5.1
type MemoryExtractor struct {
// contains filtered or unexported fields
}
MemoryExtractor handles semantic extraction of memories from conversations
func NewMemoryExtractor ¶ added in v0.5.1
func NewMemoryExtractor(prov provider.Provider, store *Store, cfg MemoryExtractorConfig) *MemoryExtractor
NewMemoryExtractor creates a new memory extractor
func (*MemoryExtractor) ExtractMemories ¶ added in v0.5.1
func (me *MemoryExtractor) ExtractMemories(ctx context.Context, messages []provider.Message, sessionID string) ([]*Memory, error)
ExtractMemories extracts memories from a conversation segment using LLM
func (*MemoryExtractor) GetTopMemories ¶ added in v0.5.1
func (me *MemoryExtractor) GetTopMemories(query string, limit int, now time.Time, memTypes ...MemoryType) []*Memory
GetTopMemories retrieves the most relevant memories considering all factors
func (*MemoryExtractor) ShouldExtract ¶ added in v0.5.1
func (me *MemoryExtractor) ShouldExtract(turn int) bool
ShouldExtract checks if it's time to extract memories
func (*MemoryExtractor) StoreMemories ¶ added in v0.5.1
func (me *MemoryExtractor) StoreMemories(memories []*Memory) error
StoreMemories stores extracted memories
type MemoryExtractorConfig ¶ added in v0.5.1
MemoryExtractorConfig configures the memory extractor
func DefaultMemoryExtractorConfig ¶ added in v0.5.1
func DefaultMemoryExtractorConfig() MemoryExtractorConfig
DefaultMemoryExtractorConfig returns default config
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 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 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. This protects prefix cache from being invalidated mid-conversation.
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(memCfg *MemoryConfig) (*Store, error)
NewStore creates a new memory store
func (*Store) AppendAgentMemory ¶
AppendAgentMemory appends content to agent memory (Cortex-style)
func (*Store) AppendUserMemory ¶
AppendUserMemory appends content to user memory (Cortex-style)
func (*Store) DeleteByScope ¶
DeleteByScope removes all memories in a scope
func (*Store) GetCommandTrustLevel ¶
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 ¶
ReadAgentMemory reads the Cortex-style agent memory file
func (*Store) ReadUserMemory ¶
ReadUserMemory reads the Cortex-style user profile file
func (*Store) RecordCommandAction ¶
RecordCommandAction records a command approval/denial
func (*Store) Stats ¶
func (s *Store) Stats() (*MemoryStats, error)
func (*Store) WriteAgentMemory ¶
WriteAgentMemory writes to the Cortex-style agent memory file
func (*Store) WriteUserMemory ¶
WriteUserMemory writes to the Cortex-style user profile file
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