memory

package
v0.0.0-...-8acab51 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2026 License: MIT Imports: 33 Imported by: 0

Documentation

Overview

Package memory provides conversation history storage using SQLite.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidPath indicates a caller supplied a memory path outside the memory root.
	ErrInvalidPath = errors.New("invalid memory path")
	// ErrInvalidDailyLogDate indicates a caller supplied an invalid daily log date.
	ErrInvalidDailyLogDate = errors.New("invalid daily log date")
)
View Source
var ErrDreamDisabled = errors.New("dream service disabled")
View Source
var ErrNotFound = errors.New("memory not found")

ErrNotFound is returned when a memory is not found.

Functions

func DefaultChatAttachmentDir

func DefaultChatAttachmentDir(dataDir string) string

DefaultChatAttachmentDir returns the canonical external attachment directory under the runtime data dir.

func ExtractImportantContent

func ExtractImportantContent(content string, maxSentences int) string

ExtractImportantContent extracts important sentences from content.

func NewEntryID

func NewEntryID() string

NewEntryID generates a new unique entry ID.

Types

type ContentType

type ContentType string

ContentType represents the format of memory content.

const (
	ContentTypeText     ContentType = "text"
	ContentTypeJSON     ContentType = "json"
	ContentTypeMarkdown ContentType = "markdown"
)

type Conversation

type Conversation struct {
	ID                 string    `json:"id"`
	Title              string    `json:"title"`
	UserID             string    `json:"user_id,omitempty"`
	Pinned             bool      `json:"pinned"`
	AutoTitleFinalized bool      `json:"-"`
	CreatedAt          time.Time `json:"created_at"`
	UpdatedAt          time.Time `json:"updated_at"`
}

Conversation represents a conversation.

type ConversationCommandState

type ConversationCommandState struct {
	ConversationID            string    `json:"conversation_id"`
	SelectedProviderID        string    `json:"selected_provider_id,omitempty"`
	SelectedModelID           string    `json:"selected_model_id,omitempty"`
	LastGoodProviderID        string    `json:"last_good_provider_id,omitempty"`
	LastGoodModelID           string    `json:"last_good_model_id,omitempty"`
	LastGoodNativeSurfaceMode string    `json:"last_good_native_surface_mode,omitempty"`
	AgentcoreRunnerRef        string    `json:"agentcore_runner_ref,omitempty"`
	Offline                   bool      `json:"offline"`
	WebSearchEnabled          bool      `json:"web_search_enabled"`
	DeepResearchEnabled       bool      `json:"deep_research_enabled"`
	UpdatedAt                 time.Time `json:"updated_at"`
}

ConversationCommandState stores persisted per-conversation deterministic chat command state.

type DailyEntry

type DailyEntry struct {
	Date    string `json:"date"`
	Content string `json:"content"`
}

DailyEntry represents a daily log entry.

type DreamCandidate

type DreamCandidate struct {
	Content   string    `json:"content"`
	Category  string    `json:"category"`
	Source    string    `json:"source"`
	CreatedAt time.Time `json:"created_at"`
}

type DreamConfig

type DreamConfig struct {
	Enabled               bool   `json:"enabled" yaml:"enabled"`
	ArchiveDir            string `json:"archive_dir" yaml:"archive_dir"`
	Schedule              string `json:"schedule" yaml:"schedule"`
	PromoteDailyAfterDays int    `json:"promote_daily_after_days" yaml:"promote_daily_after_days"`
	ArchiveDailyAfterDays int    `json:"archive_daily_after_days" yaml:"archive_daily_after_days"`
	SessionMinMessages    int    `json:"session_min_messages" yaml:"session_min_messages"`
	MaxPromotionsPerRun   int    `json:"max_promotions_per_run" yaml:"max_promotions_per_run"`
}

func DefaultDreamConfig

func DefaultDreamConfig() DreamConfig

type DreamRunResult

type DreamRunResult struct {
	RunID              string `json:"run_id"`
	PromotedCount      int    `json:"promoted_count"`
	ArchivedDailyCount int    `json:"archived_daily_count"`
	ProcessedCapsules  int    `json:"processed_capsules"`
}

type DreamService

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

func NewDreamService

func NewDreamService(layered *LayeredMemoryService, workspaceDir string, cfg DreamConfig) (*DreamService, error)

func (*DreamService) ArchiveSession

func (s *DreamService) ArchiveSession(ctx context.Context, sess *session.Session, reason session.EndReason) (string, error)

func (*DreamService) Config

func (s *DreamService) Config() DreamConfig

func (*DreamService) RunConsolidation

func (s *DreamService) RunConsolidation(ctx context.Context) (DreamRunResult, error)

func (*DreamService) Status

func (s *DreamService) Status(ctx context.Context) (DreamStatus, error)

func (*DreamService) WorkspaceArchiveDir

func (s *DreamService) WorkspaceArchiveDir() string

func (*DreamService) WorkspaceKey

func (s *DreamService) WorkspaceKey() string

type DreamSessionCapsule

type DreamSessionCapsule struct {
	ArtifactID   string           `json:"artifact_id"`
	WorkspaceKey string           `json:"workspace_key"`
	SessionID    string           `json:"session_id"`
	Reason       string           `json:"reason"`
	Title        string           `json:"title,omitempty"`
	Summary      string           `json:"summary,omitempty"`
	Tags         []string         `json:"tags,omitempty"`
	MessageCount int              `json:"message_count"`
	CreatedAt    time.Time        `json:"created_at"`
	UpdatedAt    time.Time        `json:"updated_at"`
	EndedAt      time.Time        `json:"ended_at"`
	Excerpt      string           `json:"excerpt,omitempty"`
	Candidates   []DreamCandidate `json:"candidates,omitempty"`
}

type DreamSessionHook

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

func NewDreamSessionHook

func NewDreamSessionHook(service *DreamService) *DreamSessionHook

func (*DreamSessionHook) OnSessionEnd

func (h *DreamSessionHook) OnSessionEnd(ctx context.Context, sess *session.Session, reason session.EndReason) error

type DreamStatus

type DreamStatus struct {
	Enabled           bool       `json:"enabled"`
	ArchiveDir        string     `json:"archive_dir"`
	LastRunAt         *time.Time `json:"last_run_at,omitempty"`
	PendingCapsules   int        `json:"pending_capsules"`
	ArchivedDailyLogs int        `json:"archived_daily_logs"`
	PromotedCount     int        `json:"promoted_count"`
}

type DualWriteBackend

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

DualWriteBackend implements MemoryBackend by writing to both Markdown (primary, sync, source of truth) and SQLite/MemoryService (secondary, async, for hybrid search). Reads prefer secondary (hybrid search); degrade to primary if unavailable.

func NewDualWriteBackend

func NewDualWriteBackend(primary *PureMarkdownBackend, secondary *MemoryService) *DualWriteBackend

NewDualWriteBackend creates a dual-write backend.

func (*DualWriteBackend) Close

func (d *DualWriteBackend) Close()

Close stops the async writer and waits for pending ops to drain.

func (*DualWriteBackend) Forget

func (d *DualWriteBackend) Forget(ctx context.Context, id string) error

Forget deletes from Markdown (sync) and enqueues async delete on secondary.

func (*DualWriteBackend) ForgetAll

func (d *DualWriteBackend) ForgetAll(ctx context.Context) error

ForgetAll clears Markdown (sync) and enqueues async clear on secondary.

func (*DualWriteBackend) Get

Get reads from Markdown (source of truth).

func (*DualWriteBackend) Name

func (d *DualWriteBackend) Name() string

func (*DualWriteBackend) Prune

func (d *DualWriteBackend) Prune(ctx context.Context) (int, error)

Prune prunes both backends.

func (*DualWriteBackend) Recall

func (d *DualWriteBackend) Recall(ctx context.Context, query string, limit int) ([]SearchResult, error)

Recall prefers secondary (hybrid search); degrades to primary (markdown keyword).

func (*DualWriteBackend) Remember

func (d *DualWriteBackend) Remember(ctx context.Context, content string, tags []string) (*MemoryChunk, error)

Remember writes to Markdown (sync) and enqueues async write to secondary.

func (*DualWriteBackend) Stats

func (d *DualWriteBackend) Stats(ctx context.Context) (*MemoryStats, error)

Stats returns primary stats with backend name "dual".

type Duration

type Duration time.Duration

Duration wraps time.Duration for JSON serialization as a string (e.g. "24h", "30m").

func (Duration) MarshalJSON

func (d Duration) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Duration) UnmarshalJSON

func (d *Duration) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler.

type EntryStatus

type EntryStatus string

EntryStatus represents the lifecycle state of a memory entry.

const (
	EntryStatusActive  EntryStatus = "active"
	EntryStatusExpired EntryStatus = "expired"
	EntryStatusDeleted EntryStatus = "deleted"
)

type FileInfo

type FileInfo struct {
	Path       string    `json:"path"`
	Name       string    `json:"name"`
	Size       int64     `json:"size"`
	ModifiedAt time.Time `json:"modified_at"`
}

FileInfo holds information about a Markdown file.

type HybridSearchConfig

type HybridSearchConfig struct {
	VectorWeight  float32 // Weight for vector search (default 0.7)
	KeywordWeight float32 // Weight for keyword search (default 0.3)
	MinScore      float32 // Minimum combined score (default 0.5)
	MaxResults    int     // Maximum results to return (default 10)
}

HybridSearchConfig holds hybrid search configuration.

type HybridSearchResult

type HybridSearchResult struct {
	Chunk         MemoryChunk `json:"chunk"`
	VectorScore   float32     `json:"vector_score,omitempty"`
	KeywordScore  float32     `json:"keyword_score,omitempty"`
	CombinedScore float32     `json:"combined_score"`
	MatchTypes    []string    `json:"match_types"`
	Highlights    []string    `json:"highlights,omitempty"`
	MatchedTerms  []string    `json:"matched_terms,omitempty"`
}

HybridSearchResult represents a combined search result.

type HybridSearchStats

type HybridSearchStats struct {
	VectorStoreStats  VectorStoreStats `json:"vector_store"`
	VectorWeight      float32          `json:"vector_weight"`
	KeywordWeight     float32          `json:"keyword_weight"`
	EmbeddingProvider string           `json:"embedding_provider,omitempty"`
}

HybridSearchStats holds hybrid search statistics.

type HybridSearcher

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

HybridSearcher combines vector and keyword search.

func NewHybridSearcher

func NewHybridSearcher(store *VectorStore, provider embedding.Provider, cfg config.MemoryConfig) *HybridSearcher

NewHybridSearcher creates a new hybrid searcher.

func (*HybridSearcher) Clear

func (h *HybridSearcher) Clear(ctx context.Context) error

Clear removes all chunks.

func (*HybridSearcher) Delete

func (h *HybridSearcher) Delete(ctx context.Context, id string) error

Delete deletes a memory chunk.

func (*HybridSearcher) Get

func (h *HybridSearcher) Get(ctx context.Context, id string) (*MemoryChunk, error)

Get retrieves a memory chunk by ID.

func (*HybridSearcher) Prune

func (h *HybridSearcher) Prune(ctx context.Context) (int, error)

Prune removes old chunks.

func (*HybridSearcher) Search

func (h *HybridSearcher) Search(ctx context.Context, query string, limit int) ([]HybridSearchResult, error)

Search performs hybrid search combining vector and keyword search.

func (*HybridSearcher) SearchWithOptions

func (h *HybridSearcher) SearchWithOptions(ctx context.Context, query string, opts SearchOptions) ([]HybridSearchResult, error)

SearchWithOptions performs hybrid search with additional options.

func (*HybridSearcher) Stats

Stats returns statistics.

func (*HybridSearcher) Store

func (h *HybridSearcher) Store(ctx context.Context, content string, metadata map[string]string) (*MemoryChunk, error)

Store stores content with automatic embedding.

type ImportanceConfig

type ImportanceConfig struct {
	// Weight factors (0-1)
	RecencyWeight float32 // How much recency matters
	LengthWeight  float32 // How much content length matters
	KeywordWeight float32 // How much important keywords matter
	AccessWeight  float32 // How much access frequency matters

	// Important keywords that boost score
	ImportantKeywords []string

	// Decay settings
	RecencyDecayDays int // Days after which recency score starts decaying
}

ImportanceConfig holds configuration for importance scoring.

func DefaultImportanceConfig

func DefaultImportanceConfig() ImportanceConfig

DefaultImportanceConfig returns default importance scoring configuration.

type ImportanceDetails

type ImportanceDetails struct {
	CombinedScore   float32  `json:"combined_score"`
	RecencyScore    float32  `json:"recency_score"`
	LengthScore     float32  `json:"length_score"`
	KeywordScore    float32  `json:"keyword_score"`
	AccessScore     float32  `json:"access_score"`
	MatchedKeywords []string `json:"matched_keywords,omitempty"`
}

ImportanceDetails holds detailed importance scoring breakdown.

type ImportanceScorer

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

ImportanceScorer calculates importance scores for memory chunks.

func NewImportanceScorer

func NewImportanceScorer(cfg ImportanceConfig) *ImportanceScorer

NewImportanceScorer creates a new importance scorer.

func (*ImportanceScorer) Score

func (s *ImportanceScorer) Score(chunk *MemoryChunk) float32

Score calculates the importance score for a memory chunk.

func (*ImportanceScorer) ScoreWithDetails

func (s *ImportanceScorer) ScoreWithDetails(chunk *MemoryChunk) ImportanceDetails

ScoreWithDetails returns detailed scoring breakdown.

type LayeredMemoryConfig

type LayeredMemoryConfig struct {
	// BaseDir is the root directory for daily log files (memory/ subdirectory).
	BaseDir string
	// LongTermDir is the directory where MEMORY.md lives (workspace root).
	// If empty, defaults to BaseDir for backward compatibility.
	LongTermDir string
	// DailyRetentionDays is how many days to keep daily logs (default: 30).
	DailyRetentionDays int
	// AutoPromoteThreshold is the minimum score for auto-promotion to long-term (0-1).
	AutoPromoteThreshold float32
}

LayeredMemoryConfig holds configuration for the layered memory system.

type LayeredMemoryService

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

LayeredMemoryService provides a dual-layer memory architecture. Layer 1: Daily logs - append-only notes for each day Layer 2: Long-term memory - curated persistent knowledge

func NewLayeredMemoryService

func NewLayeredMemoryService(baseService *UnifiedMemoryService, config LayeredMemoryConfig) (*LayeredMemoryService, error)

NewLayeredMemoryService creates a new layered memory service.

func (*LayeredMemoryService) AppendToDaily

func (s *LayeredMemoryService) AppendToDaily(ctx context.Context, content string, tags []string) error

AppendToDaily appends content to today's daily log.

func (*LayeredMemoryService) GetConfig

GetConfig returns the current configuration.

func (*LayeredMemoryService) GetDailyLog

func (s *LayeredMemoryService) GetDailyLog(ctx context.Context, date string) (string, error)

GetDailyLog reads a specific day's log.

func (*LayeredMemoryService) GetLongTermMemory

func (s *LayeredMemoryService) GetLongTermMemory(ctx context.Context) (string, error)

GetLongTermMemory reads the long-term memory file.

func (*LayeredMemoryService) ListDailyLogs

func (s *LayeredMemoryService) ListDailyLogs(ctx context.Context) ([]string, error)

ListDailyLogs returns a list of available daily log dates.

func (*LayeredMemoryService) PromoteToLongTerm

func (s *LayeredMemoryService) PromoteToLongTerm(ctx context.Context, content string, category string) error

PromoteToLongTerm promotes content to the long-term memory layer.

func (*LayeredMemoryService) PruneDailyLogs

func (s *LayeredMemoryService) PruneDailyLogs(ctx context.Context) (int, error)

PruneDailyLogs removes daily logs older than retention period.

func (*LayeredMemoryService) Recall

func (s *LayeredMemoryService) Recall(ctx context.Context, query string, limit int) ([]SearchResult, error)

Recall searches relevant memories via the base service.

func (*LayeredMemoryService) WarmIndex

func (s *LayeredMemoryService) WarmIndex()

WarmIndex pre-loads the memory search index into memory so that subsequent Recall() calls are faster. Safe to call concurrently; no-op if base service doesn't support index warming.

type MarkdownMemoryStore

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

MarkdownMemoryStore provides Markdown-based memory storage for agent queries. This allows agents to search and read memories stored as human-readable Markdown files.

func NewMarkdownMemoryStore

func NewMarkdownMemoryStore(baseDir string) *MarkdownMemoryStore

NewMarkdownMemoryStore creates a new Markdown memory store.

func (*MarkdownMemoryStore) GetLongTermMemory

func (s *MarkdownMemoryStore) GetLongTermMemory(ctx context.Context) (string, error)

GetLongTermMemory reads the MEMORY.md file.

func (*MarkdownMemoryStore) GetRecentEntries

func (s *MarkdownMemoryStore) GetRecentEntries(ctx context.Context, days int) ([]DailyEntry, error)

GetRecentEntries returns recent entries from daily logs.

func (*MarkdownMemoryStore) ListFiles

func (s *MarkdownMemoryStore) ListFiles(ctx context.Context) ([]FileInfo, error)

ListFiles lists all Markdown files in the memory directory.

func (*MarkdownMemoryStore) ReadFile

func (s *MarkdownMemoryStore) ReadFile(ctx context.Context, relPath string, fromLine, numLines int) (string, error)

ReadFile reads a Markdown file by relative path.

func (*MarkdownMemoryStore) Search

func (s *MarkdownMemoryStore) Search(ctx context.Context, query string, maxResults int) ([]MarkdownSearchResult, error)

Search searches all Markdown files for the given query.

func (*MarkdownMemoryStore) SetLongTermDir

func (s *MarkdownMemoryStore) SetLongTermDir(dir string)

SetLongTermDir sets the directory where MEMORY.md lives (e.g. workspace root).

type MarkdownSearchResult

type MarkdownSearchResult struct {
	FilePath   string   `json:"file_path"`
	FileName   string   `json:"file_name"`
	LineNumber int      `json:"line_number"`
	Content    string   `json:"content"`
	Context    []string `json:"context,omitempty"` // Lines around the match
	Score      float32  `json:"score"`
	MatchType  string   `json:"match_type"` // "exact", "fuzzy", "heading"
}

MarkdownSearchResult represents a search result from Markdown files.

type MemoryBackend

type MemoryBackend interface {
	// Remember stores a new memory.
	Remember(ctx context.Context, content string, tags []string) (*MemoryChunk, error)
	// Recall retrieves relevant memories.
	Recall(ctx context.Context, query string, limit int) ([]SearchResult, error)
	// Forget removes a memory by ID.
	Forget(ctx context.Context, id string) error
	// ForgetAll removes all memories.
	ForgetAll(ctx context.Context) error
	// Get retrieves a memory by ID.
	Get(ctx context.Context, id string) (*MemoryChunk, error)
	// Prune removes old memories.
	Prune(ctx context.Context) (int, error)
	// Stats returns memory statistics.
	Stats(ctx context.Context) (*MemoryStats, error)
	// Name returns the backend name.
	Name() string
}

MemoryBackend defines the interface for memory storage backends.

type MemoryChunk

type MemoryChunk struct {
	ID        string            `json:"id"`
	Content   string            `json:"content"`
	Metadata  map[string]string `json:"metadata,omitempty"`
	CreatedAt time.Time         `json:"created_at"`
	UpdatedAt time.Time         `json:"updated_at"`
}

MemoryChunk represents a unit of stored memory.

type MemoryEntry

type MemoryEntry struct {
	ID          string         `json:"id"`
	Namespace   string         `json:"namespace"`
	Content     string         `json:"content"`
	ContentType ContentType    `json:"content_type"`
	Category    string         `json:"category,omitempty"`
	Tags        []string       `json:"tags,omitempty"`
	Metadata    map[string]any `json:"metadata,omitempty"`
	Embedding   []float32      `json:"-"`
	Importance  float32        `json:"importance"`
	Source      string         `json:"source,omitempty"`

	// Versioning
	Version  int    `json:"version"`
	ParentID string `json:"parent_id,omitempty"`

	// Lifecycle
	Status    EntryStatus `json:"status"`
	TTL       Duration    `json:"ttl,omitempty"`
	CreatedAt time.Time   `json:"created_at"`
	UpdatedAt time.Time   `json:"updated_at"`
	ExpiresAt *time.Time  `json:"expires_at,omitempty"`
	DeletedAt *time.Time  `json:"deleted_at,omitempty"`
}

MemoryEntry is the enhanced memory unit with versioning, TTL, and namespace support. It extends the existing MemoryChunk with additional fields from the PRD.

func NewMemoryEntry

func NewMemoryEntry(namespace, content string) *MemoryEntry

NewMemoryEntry creates a new MemoryEntry with defaults.

func (*MemoryEntry) ComputeExpiresAt

func (e *MemoryEntry) ComputeExpiresAt()

ComputeExpiresAt sets ExpiresAt based on TTL and CreatedAt. If TTL is 0, ExpiresAt is nil (permanent).

func (*MemoryEntry) IsExpired

func (e *MemoryEntry) IsExpired() bool

IsExpired returns true if the entry has a TTL and it has passed.

func (*MemoryEntry) NewVersion

func (e *MemoryEntry) NewVersion(content string) *MemoryEntry

NewVersion creates a new version of this entry with updated content. The new entry gets a new ID, incremented version, and parent_id pointing to this entry.

func (*MemoryEntry) SoftDelete

func (e *MemoryEntry) SoftDelete()

SoftDelete marks the entry as deleted.

type MemoryExtractor

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

MemoryExtractor extracts important memories from daily logs to long-term memory.

func NewMemoryExtractor

func NewMemoryExtractor(layeredMemory *LayeredMemoryService) *MemoryExtractor

NewMemoryExtractor creates a new memory extractor.

func (*MemoryExtractor) ExtractFromDailyLogs

func (e *MemoryExtractor) ExtractFromDailyLogs(ctx context.Context, daysOld int) (int, error)

ExtractFromDailyLogs extracts important content from daily logs older than daysOld.

func (*MemoryExtractor) SetMinScore

func (e *MemoryExtractor) SetMinScore(score float32)

SetMinScore sets the minimum importance score for promotion.

type MemoryLayer

type MemoryLayer string

MemoryLayer represents a layer type in the dual-layer architecture.

const (
	// LayerDaily represents the daily log layer (ephemeral, append-only).
	LayerDaily MemoryLayer = "daily"
	// LayerLongTerm represents the long-term memory layer (curated, persistent).
	LayerLongTerm MemoryLayer = "longterm"
)

type MemoryService

type MemoryService struct {
	Searcher *HybridSearcher
}

MemoryService provides a high-level interface for memory operations.

func NewMemoryService

func NewMemoryService(searcher *HybridSearcher) *MemoryService

NewMemoryService creates a new memory service.

func (*MemoryService) Forget

func (s *MemoryService) Forget(ctx context.Context, id string) error

Forget removes a memory.

func (*MemoryService) ForgetAll

func (s *MemoryService) ForgetAll(ctx context.Context) error

ForgetAll removes all memories.

func (*MemoryService) Get

func (s *MemoryService) Get(ctx context.Context, id string) (*MemoryChunk, error)

Get retrieves a memory by ID.

func (*MemoryService) GetSearcher

func (s *MemoryService) GetSearcher() *HybridSearcher

GetSearcher returns the underlying HybridSearcher.

func (*MemoryService) Name

func (s *MemoryService) Name() string

Name returns the backend name.

func (*MemoryService) Prune

func (s *MemoryService) Prune(ctx context.Context) (int, error)

Prune removes old memories.

func (*MemoryService) Recall

func (s *MemoryService) Recall(ctx context.Context, query string, limit int) ([]SearchResult, error)

Recall retrieves relevant memories as SearchResult (matches MemoryBackend interface).

func (*MemoryService) Remember

func (s *MemoryService) Remember(ctx context.Context, content string, tags []string) (*MemoryChunk, error)

Remember stores a memory.

func (*MemoryService) RememberWithMetadata

func (s *MemoryService) RememberWithMetadata(ctx context.Context, content string, metadata map[string]string) (*MemoryChunk, error)

func (*MemoryService) Stats

func (s *MemoryService) Stats(ctx context.Context) (*MemoryStats, error)

Stats returns memory statistics.

type MemoryStats

type MemoryStats struct {
	TotalChunks    int    `json:"total_chunks"`
	TotalSizeBytes int64  `json:"total_size_bytes"`
	OldestChunk    string `json:"oldest_chunk,omitempty"`
	NewestChunk    string `json:"newest_chunk,omitempty"`
	Backend        string `json:"backend"`
}

MemoryStats holds unified memory statistics.

type Message

type Message struct {
	ID             string              `json:"id"`
	ConversationID string              `json:"conversation_id"`
	Role           string              `json:"role"`
	Content        string              `json:"content"`
	ToolCalls      []ToolCall          `json:"tool_calls,omitempty"`
	ToolCallID     string              `json:"tool_call_id,omitempty"`
	ToolName       string              `json:"tool_name,omitempty"`
	Provider       string              `json:"provider,omitempty"`
	Model          string              `json:"model,omitempty"`
	Stats          *MessageStats       `json:"stats,omitempty"`
	Attachments    []MessageAttachment `json:"attachments,omitempty"`
	CreatedAt      time.Time           `json:"created_at"`
}

Message represents a chat message.

type MessageAttachment

type MessageAttachment struct {
	Type     string  `json:"type"`               // "image", "file", "audio", or "video"
	Name     string  `json:"name"`               // filename
	MimeType string  `json:"mime_type"`          // MIME type
	Data     string  `json:"data"`               // base64 encoded data
	Duration float64 `json:"duration,omitempty"` // audio duration in seconds
}

MessageAttachment represents an attachment in a message.

type MessageStats

type MessageStats struct {
	InputTokens     int     `json:"input_tokens"`
	OutputTokens    int     `json:"output_tokens"`
	TotalTokens     int     `json:"total_tokens"`
	LatencyMs       int64   `json:"latency_ms"`
	TTFTMs          int64   `json:"ttft_ms"`
	TokensPerSecond float64 `json:"tokens_per_second"`
}

MessageStats represents statistics for a message.

type Namespace

type Namespace struct {
	ID        string          `json:"id"`
	Config    NamespaceConfig `json:"config"`
	CreatedAt time.Time       `json:"created_at"`
	UpdatedAt time.Time       `json:"updated_at"`
}

Namespace represents an isolated memory namespace.

type NamespaceConfig

type NamespaceConfig struct {
	EmbeddingDim int      `json:"embedding_dim"`
	DefaultTTL   Duration `json:"default_ttl,omitempty"`
	MaxEntries   int      `json:"max_entries"`
	MaxSizeBytes int64    `json:"max_size_bytes"`
}

NamespaceConfig holds per-namespace settings.

func DefaultNamespaceConfig

func DefaultNamespaceConfig() NamespaceConfig

DefaultNamespaceConfig returns sensible defaults.

type NamespaceStats

type NamespaceStats struct {
	NamespaceID  string `json:"namespace_id"`
	EntryCount   int    `json:"entry_count"`
	TotalSize    int64  `json:"total_size_bytes"`
	ActiveCount  int    `json:"active_count"`
	ExpiredCount int    `json:"expired_count"`
	DeletedCount int    `json:"deleted_count"`
}

NamespaceStats holds usage statistics for a namespace.

type NamespaceStore

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

NamespaceStore manages namespace CRUD backed by SQLite.

func NewNamespaceStore

func NewNamespaceStore(db *sql.DB) (*NamespaceStore, error)

NewNamespaceStore creates a NamespaceStore and initializes the schema.

func NewNamespaceStoreWithReadDB

func NewNamespaceStoreWithReadDB(writeDB, readDB *sql.DB) (*NamespaceStore, error)

NewNamespaceStoreWithReadDB creates a NamespaceStore with separate write and read database handles and initializes the schema.

func (*NamespaceStore) Create

func (s *NamespaceStore) Create(ctx context.Context, ns *Namespace) error

Create creates a new namespace. Returns error if it already exists.

func (*NamespaceStore) Delete

func (s *NamespaceStore) Delete(ctx context.Context, id string) error

Delete removes a namespace.

func (*NamespaceStore) Get

func (s *NamespaceStore) Get(ctx context.Context, id string) (*Namespace, error)

Get retrieves a namespace by ID.

func (*NamespaceStore) List

func (s *NamespaceStore) List(ctx context.Context) ([]*Namespace, error)

List returns all namespaces.

func (*NamespaceStore) UpdateConfig

func (s *NamespaceStore) UpdateConfig(ctx context.Context, id string, cfg NamespaceConfig) error

UpdateConfig updates the config for a namespace.

type PureMarkdownBackend

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

PureMarkdownBackend implements MemoryBackend using only Markdown files. No SQLite database required - all data stored as human-readable Markdown.

Storage layout:

  • daily/<date>.md — append-only daily log (one per day, pruned after 30 days)
  • MEMORY.md — curated long-term knowledge (managed by LayeredMemoryService)

func NewPureMarkdownBackend

func NewPureMarkdownBackend(baseDir string) (*PureMarkdownBackend, error)

NewPureMarkdownBackend creates a new pure Markdown backend.

func (*PureMarkdownBackend) Forget

func (b *PureMarkdownBackend) Forget(ctx context.Context, id string) error

Forget removes a daily log file by relative path.

func (*PureMarkdownBackend) ForgetAll

func (b *PureMarkdownBackend) ForgetAll(ctx context.Context) error

ForgetAll removes all daily log files.

func (*PureMarkdownBackend) Get

Get reads a memory file.

func (*PureMarkdownBackend) Name

func (b *PureMarkdownBackend) Name() string

func (*PureMarkdownBackend) Prune

func (b *PureMarkdownBackend) Prune(ctx context.Context) (int, error)

Prune removes old daily logs.

func (*PureMarkdownBackend) Recall

func (b *PureMarkdownBackend) Recall(ctx context.Context, query string, limit int) ([]SearchResult, error)

Recall searches memories using keyword matching.

func (*PureMarkdownBackend) Remember

func (b *PureMarkdownBackend) Remember(ctx context.Context, content string, tags []string) (*MemoryChunk, error)

Remember appends a memory entry to today's daily log.

func (*PureMarkdownBackend) Stats

Stats returns memory statistics.

type SearchFilters

type SearchFilters struct {
	Categories    []string       `json:"categories,omitempty"`
	Tags          []string       `json:"tags,omitempty"`
	Source        string         `json:"source,omitempty"`
	CreatedAfter  *time.Time     `json:"created_after,omitempty"`
	CreatedBefore *time.Time     `json:"created_before,omitempty"`
	Metadata      map[string]any `json:"metadata,omitempty"`
}

SearchFilters contains optional filters for search.

type SearchOptions

type SearchOptions struct {
	Limit        int
	StartDate    *time.Time
	EndDate      *time.Time
	Highlight    bool
	HighlightTag string
}

SearchOptions holds optional search parameters.

type SearchQuery

type SearchQuery struct {
	Query         string         `json:"query"`
	Namespace     string         `json:"namespace"`
	TopK          int            `json:"top_k"`
	MinSimilarity float32        `json:"min_similarity,omitempty"`
	MinImportance float32        `json:"min_importance,omitempty"`
	Filters       *SearchFilters `json:"filters,omitempty"`
}

SearchQuery represents a search request against the memory store.

type SearchResult

type SearchResult struct {
	Chunk        MemoryChunk `json:"chunk"`
	Score        float32     `json:"score"`
	KeywordScore float32     `json:"keyword_score,omitempty"`
	MatchTypes   []string    `json:"match_types"`
}

SearchResult represents a memory search result.

type Store

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

Store provides conversation storage using SQLite.

func NewStore

func NewStore(dbPath string) (*Store, error)

NewStore creates a new memory store.

func NewStoreWithDB

func NewStoreWithDB(db *sql.DB) (*Store, error)

NewStoreWithDB creates a memory store using an existing shared database connection. The caller is responsible for managing the DB lifecycle (pragmas, connection pool, close).

func NewStoreWithOptions

func NewStoreWithOptions(dbPath string, opts StoreOptions) (*Store, error)

NewStoreWithOptions creates a new owned memory store with custom SQLite settings.

func NewStoreWithReadDB

func NewStoreWithReadDB(writeDB, readDB *sql.DB) (*Store, error)

NewStoreWithReadDB creates a memory store using separate shared write and read database connections. The caller is responsible for managing the DB lifecycle.

func (*Store) AddMessage

func (s *Store) AddMessage(ctx context.Context, conversationID string, msg Message, userID ...string) (*Message, error)

AddMessage adds a message to a conversation.

func (*Store) AddMessageTrusted

func (s *Store) AddMessageTrusted(ctx context.Context, conversationID string, msg Message) (*Message, error)

AddMessageTrusted adds a message without re-checking conversation ownership.

func (*Store) CleanupExpiredRuntimeState

func (s *Store) CleanupExpiredRuntimeState(ctx context.Context) error

CleanupExpiredRuntimeState prunes stale previous_response_id rows.

func (*Store) ClearConversationCommandState

func (s *Store) ClearConversationCommandState(ctx context.Context, conversationID string) error

ClearConversationCommandState removes persisted deterministic command state for a conversation. For authenticated conversations (with user_id), this clears both the shared user-scoped state and the conversation-specific override row.

func (*Store) ClearConversationPreviousResponseID

func (s *Store) ClearConversationPreviousResponseID(ctx context.Context, conversationID string) error

ClearConversationPreviousResponseID removes persisted continuation IDs for a conversation.

func (*Store) Close

func (s *Store) Close() error

Close closes the database connection if this Store owns it.

func (*Store) CountMessages

func (s *Store) CountMessages(ctx context.Context, conversationID string, userID ...string) (int, error)

CountMessages returns the number of persisted messages in a conversation.

func (*Store) CreateConversation

func (s *Store) CreateConversation(ctx context.Context, title string, userID ...string) (*Conversation, error)

CreateConversation creates a new conversation.

func (*Store) CreateConversationWithID

func (s *Store) CreateConversationWithID(ctx context.Context, id, title string) (*Conversation, error)

CreateConversationWithID creates a conversation with a specific ID (for IM channels).

func (*Store) DeleteConversation

func (s *Store) DeleteConversation(ctx context.Context, id string, userID ...string) error

DeleteConversation deletes a conversation and its messages.

func (*Store) DeleteMessages

func (s *Store) DeleteMessages(ctx context.Context, conversationID string, messageIDs []string) error

DeleteMessages deletes multiple messages by their IDs.

func (*Store) FinalizeAutoConversationTitle

func (s *Store) FinalizeAutoConversationTitle(ctx context.Context, id, title string, userID ...string) (bool, error)

FinalizeAutoConversationTitle updates a title only while auto titling is still pending. It atomically locks the conversation so automatic title generation can only succeed once.

func (*Store) GetConversation

func (s *Store) GetConversation(ctx context.Context, id string, userID ...string) (*Conversation, error)

GetConversation retrieves a conversation by ID.

func (*Store) GetConversationCommandState

func (s *Store) GetConversationCommandState(ctx context.Context, conversationID string) (ConversationCommandState, error)

GetConversationCommandState returns persisted deterministic command state for a conversation. For authenticated conversations (with user_id), provider/model/offline stay user-scoped while conversation-specific overrides such as agentcore runner ref remain conversation-scoped. Missing rows fall back to defaults: provider/model auto, offline=false, web=true, deep=true.

func (*Store) GetConversationPreviousResponseID

func (s *Store) GetConversationPreviousResponseID(ctx context.Context, conversationID string) (string, error)

GetConversationPreviousResponseID returns the latest persisted Responses continuation ID. The ID is conversation-scoped and expires automatically after TTL.

func (*Store) GetLatestAssistantMessage

func (s *Store) GetLatestAssistantMessage(ctx context.Context, conversationID string, userID ...string) (*Message, error)

GetLatestAssistantMessage returns the latest assistant message for a conversation.

func (*Store) GetMessages

func (s *Store) GetMessages(ctx context.Context, conversationID string, limit, offset int, userID ...string) ([]Message, error)

GetMessages retrieves messages for a conversation.

func (*Store) GetMessagesLite

func (s *Store) GetMessagesLite(ctx context.Context, conversationID string, limit, offset int, userID ...string) ([]Message, error)

GetMessagesLite retrieves messages without stats/attachments JSON payloads.

func (*Store) GetRecentMessages

func (s *Store) GetRecentMessages(ctx context.Context, conversationID string, limit int, userID ...string) ([]Message, error)

GetRecentMessages retrieves the latest messages for a conversation and returns them in chronological order.

func (*Store) GetRecentMessagesLite

func (s *Store) GetRecentMessagesLite(ctx context.Context, conversationID string, limit int, userID ...string) ([]Message, error)

GetRecentMessagesLite retrieves recent messages without stats/attachments JSON payloads.

func (*Store) ListConversations

func (s *Store) ListConversations(ctx context.Context, limit, offset int, userID ...string) ([]Conversation, error)

ListConversations lists conversations with pagination, optionally filtered by userID.

func (*Store) PinConversation

func (s *Store) PinConversation(ctx context.Context, id string, userID ...string) error

PinConversation pins a conversation.

func (*Store) PreviewAutoConversationTitle

func (s *Store) PreviewAutoConversationTitle(ctx context.Context, id, title string, userID ...string) (bool, error)

PreviewAutoConversationTitle updates a pending auto title without finalizing it. It only succeeds while automatic title generation is still pending.

func (*Store) Recover

func (s *Store) Recover() error

Recover attempts to reopen an owned SQLite store using the shared recovery flow.

func (*Store) SearchConversations

func (s *Store) SearchConversations(ctx context.Context, query string, limit int, userID ...string) ([]Conversation, error)

SearchConversations searches conversations by title, optionally filtered by userID.

func (*Store) SetConversationPreviousResponseID

func (s *Store) SetConversationPreviousResponseID(ctx context.Context, conversationID, responseID string) error

SetConversationPreviousResponseID stores the latest Responses continuation ID for a conversation.

func (*Store) UnpinConversation

func (s *Store) UnpinConversation(ctx context.Context, id string, userID ...string) error

UnpinConversation unpins a conversation.

func (*Store) UpdateConversationTitle

func (s *Store) UpdateConversationTitle(ctx context.Context, id, title string, userID ...string) error

UpdateConversationTitle updates a conversation title and prevents future auto-generated title writes.

func (*Store) UpdateMessageContent

func (s *Store) UpdateMessageContent(ctx context.Context, messageID, content string, stats *MessageStats) error

UpdateMessageContent updates the content (and optionally stats) of an existing message. Used for incremental persistence during streaming.

func (*Store) UpdateMessageContentFull

func (s *Store) UpdateMessageContentFull(ctx context.Context, messageID, content, provider, model string, stats *MessageStats) error

UpdateMessageContentFull updates a message's content, stats, and optionally provider/model.

func (*Store) UpsertConversationCommandState

func (s *Store) UpsertConversationCommandState(ctx context.Context, state ConversationCommandState) error

UpsertConversationCommandState stores deterministic command state for a conversation. For authenticated conversations (with user_id), provider/model/offline are persisted once per user while conversation-specific overrides are kept on the conversation row.

func (*Store) UpsertMessageContentFullTrusted

func (s *Store) UpsertMessageContentFullTrusted(ctx context.Context, msg Message) error

UpsertMessageContentFullTrusted inserts a message when absent or updates draft/final content in place.

type StoreOptions

type StoreOptions struct {
	Durability                  string
	WALAutoCheckpoint           int
	CheckpointInterval          time.Duration
	RuntimeStateCleanupInterval time.Duration
	AttachmentExternalStore     bool
	AttachmentDir               string
	MaxOpenConns                int
	MaxIdleConns                int
}

StoreOptions controls owned SQLite chat-store behavior.

func DefaultChatStoreOptions

func DefaultChatStoreOptions(dbPath string) StoreOptions

DefaultChatStoreOptions returns chat-optimized defaults for a dedicated handle.

func DefaultStoreOptions

func DefaultStoreOptions() StoreOptions

DefaultStoreOptions returns conservative defaults for generic callers.

type ToolCall

type ToolCall struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Arguments string `json:"arguments"`
}

ToolCall represents a tool call made by the LLM.

type ToolsAdapter

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

ToolsAdapter adapts UnifiedMemoryService to tools.MemoryServiceInterface.

func NewToolsAdapter

func NewToolsAdapter(service *UnifiedMemoryService) *ToolsAdapter

NewToolsAdapter creates a new tools adapter for the memory service.

func (*ToolsAdapter) Forget

func (a *ToolsAdapter) Forget(ctx context.Context, id string) error

Forget deletes a memory by ID.

func (*ToolsAdapter) Get

Get retrieves a memory by ID.

func (*ToolsAdapter) GetActiveBackend

func (a *ToolsAdapter) GetActiveBackend() string

GetActiveBackend returns the name of the active backend.

func (*ToolsAdapter) Recall

func (a *ToolsAdapter) Recall(ctx context.Context, query string, limit int) ([]tools.MemorySearchResult, error)

Recall searches memories and returns results in the tools interface format.

func (*ToolsAdapter) Remember

func (a *ToolsAdapter) Remember(ctx context.Context, content string, tags []string) (*tools.MemoryChunkResult, error)

Remember stores a new memory.

func (*ToolsAdapter) Stats

Stats returns memory statistics.

type UnifiedMemoryService

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

UnifiedMemoryService provides a unified interface backed by any MemoryBackend.

func NewUnifiedMemoryService

func NewUnifiedMemoryService(md *PureMarkdownBackend) *UnifiedMemoryService

NewUnifiedMemoryService creates a new unified memory service with a markdown backend.

func (*UnifiedMemoryService) Forget

func (s *UnifiedMemoryService) Forget(ctx context.Context, id string) error

Forget removes a memory by ID.

func (*UnifiedMemoryService) ForgetAll

func (s *UnifiedMemoryService) ForgetAll(ctx context.Context) error

ForgetAll removes all memories.

func (*UnifiedMemoryService) Get

Get retrieves a memory by ID.

func (*UnifiedMemoryService) GetActiveBackend

func (s *UnifiedMemoryService) GetActiveBackend() string

GetActiveBackend returns the name of the active backend.

func (*UnifiedMemoryService) Prune

func (s *UnifiedMemoryService) Prune(ctx context.Context) (int, error)

Prune removes old memories.

func (*UnifiedMemoryService) Recall

func (s *UnifiedMemoryService) Recall(ctx context.Context, query string, limit int) ([]SearchResult, error)

Recall retrieves relevant memories.

func (*UnifiedMemoryService) Remember

func (s *UnifiedMemoryService) Remember(ctx context.Context, content string, tags []string) (*MemoryChunk, error)

Remember stores a new memory.

func (*UnifiedMemoryService) SetBackend

func (s *UnifiedMemoryService) SetBackend(b MemoryBackend)

SetBackend swaps the active backend (e.g. from markdown to dual-write).

func (*UnifiedMemoryService) Stats

Stats returns memory statistics.

type VectorSearchResult

type VectorSearchResult struct {
	Chunk MemoryChunk
	Score float32
}

VectorSearchResult represents a vector search result.

type VectorStore

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

VectorStore provides SQLite-backed storage with sqlite-vec + FTS5.

func NewVectorStore

func NewVectorStore(cfg VectorStoreConfig) (*VectorStore, error)

NewVectorStore creates a new vector store.

func (*VectorStore) Clear

func (s *VectorStore) Clear(ctx context.Context) error

Clear removes all data.

func (*VectorStore) Close

func (s *VectorStore) Close() error

Close closes the database.

func (*VectorStore) Delete

func (s *VectorStore) Delete(ctx context.Context, id string) error

Delete removes a chunk by ID.

func (*VectorStore) Get

func (s *VectorStore) Get(ctx context.Context, id string) (*MemoryChunk, error)

Get retrieves a chunk by ID.

func (*VectorStore) HybridSearch

func (s *VectorStore) HybridSearch(ctx context.Context, queryEmb []float32, queryText string, limit int, vectorWeight, keywordWeight, minScore float32) ([]HybridSearchResult, error)

HybridSearch performs combined vector + keyword search with Go-layer normalization.

func (*VectorStore) Prune

func (s *VectorStore) Prune(ctx context.Context) (int, error)

Prune removes oldest chunks when over capacity.

func (*VectorStore) SearchKeyword

func (s *VectorStore) SearchKeyword(ctx context.Context, query string, limit int) ([]VectorSearchResult, error)

SearchKeyword performs FTS5 keyword search.

func (*VectorStore) SearchVector

func (s *VectorStore) SearchVector(ctx context.Context, queryEmb []float32, limit int, minScore float32) ([]VectorSearchResult, error)

SearchVector performs pure vector similarity search.

func (*VectorStore) Stats

Stats returns store statistics.

func (*VectorStore) Store

func (s *VectorStore) Store(ctx context.Context, content string, emb []float32, metadata map[string]string) (*MemoryChunk, error)

Store stores a memory chunk with its embedding.

type VectorStoreConfig

type VectorStoreConfig struct {
	DBPath       string
	EmbeddingDim int
	MaxChunks    int
	EnableFTS    bool
}

VectorStoreConfig holds configuration for the vector store.

type VectorStoreStats

type VectorStoreStats struct {
	ChunkCount   int    `json:"chunk_count"`
	MaxChunks    int    `json:"max_chunks"`
	EmbeddingDim int    `json:"embedding_dim"`
	FTSEnabled   bool   `json:"fts_enabled"`
	OldestChunk  string `json:"oldest_chunk,omitempty"`
	NewestChunk  string `json:"newest_chunk,omitempty"`
}

VectorStoreStats holds vector store statistics.

Jump to

Keyboard shortcuts

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