memory

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2026 License: MIT Imports: 5 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package memory defines the core types and scoring algorithms for Engram.

Index

Constants

View Source
const DefaultDedupThreshold = 0.92

DefaultDedupThreshold is the cosine similarity above which a new memory is considered a duplicate of an existing one and will be skipped.

Variables

ValidTypes is the set of all valid memory types.

Functions

func Score

func Score(m *Memory, cosineSim float64, weights ScoringWeights, decay DecayConfig) float64

Score computes the final score for a memory given its raw cosine similarity.

Types

type CollectionStats

type CollectionStats struct {
	PointCount   uint64
	VectorCount  uint64
	IndexedCount uint64
	SegmentCount uint64
	Status       string
}

CollectionStats holds collection-level statistics.

type DecayConfig

type DecayConfig struct {
	Identity  float64 // default: 1.0 (no decay)
	Event     float64 // default: 0.99 (~69h half-life)
	Insight   float64 // default: 0.9998 (~144d half-life)
	Directive float64 // default: 1.0 (no decay)
}

DecayConfig holds per-type decay factors.

func DefaultDecayConfig

func DefaultDecayConfig() DecayConfig

DefaultDecayConfig returns the default decay configuration.

func (DecayConfig) DecayFactor

func (dc DecayConfig) DecayFactor(t MemoryType) float64

DecayFactor returns the decay factor for a given memory type.

type Filter

type Filter struct {
	Field string
	Op    FilterOp
	Value any // string, []string, float64, [2]float64 (for range)
}

Filter is a single field filter for search.

type FilterOp

type FilterOp string

FilterOp is a filter operation.

const (
	OpEq    FilterOp = "eq"
	OpIn    FilterOp = "in"
	OpGte   FilterOp = "gte"
	OpLte   FilterOp = "lte"
	OpRange FilterOp = "range"
)

type Memory

type Memory struct {
	ID             string         `json:"id"`
	Type           MemoryType     `json:"type"`
	Content        string         `json:"content"`
	Source         string         `json:"source"`     // "user", "agent", "system"
	Importance     float64        `json:"importance"` // 1-10
	Tags           []string       `json:"tags"`
	CreatedAt      float64        `json:"created_at"` // UTC Unix timestamp
	UpdatedAt      float64        `json:"updated_at"`
	Metadata       map[string]any `json:"metadata,omitempty"`
	ValidUntil     float64        `json:"valid_until,omitempty"`      // 0 = never expires
	SupersededBy   string         `json:"superseded_by,omitempty"`    // "" = not superseded
	AccessCount    int64          `json:"access_count"`               // search hit count
	LastAccessedAt float64        `json:"last_accessed_at,omitempty"` // 0 = never accessed
}

Memory is a single unit of stored knowledge.

func New

func New(content string, opts ...Option) *Memory

New creates a new Memory with defaults.

func (*Memory) Validate

func (m *Memory) Validate() error

Validate checks that a Memory has valid fields.

type MemoryType

type MemoryType string

MemoryType represents the category of a memory.

const (
	// TypeIdentity represents stable facts about the user (name, job, preferences, relationships).
	TypeIdentity MemoryType = "identity"
	// TypeEvent represents something that happened or was observed.
	TypeEvent MemoryType = "event"
	// TypeInsight represents inferred patterns, reflections, or conclusions.
	TypeInsight MemoryType = "insight"
	// TypeDirective represents explicit instructions from the user.
	TypeDirective MemoryType = "directive"
)

type Option

type Option func(*Memory)

Option configures a Memory during creation.

func WithImportance

func WithImportance(i float64) Option

func WithMetadata

func WithMetadata(md map[string]any) Option

func WithSource

func WithSource(s string) Option

func WithTags

func WithTags(tags ...string) Option

func WithType

func WithType(t MemoryType) Option

func WithValidUntil

func WithValidUntil(t float64) Option

type ScoredMemory

type ScoredMemory struct {
	Memory
	Score  float64   `json:"score"`            // Final weighted score
	Vector []float32 `json:"vector,omitempty"` // Embedding vector (populated when with_vectors=true)
}

ScoredMemory is a Memory with a computed relevance score.

func IsDuplicate

func IsDuplicate(candidates []ScoredMemory, threshold float64) *ScoredMemory

IsDuplicate checks if any of the scored candidates are above the dedup threshold. Returns the best matching memory if duplicate, nil otherwise.

func MMR

func MMR(candidates []ScoredMemory, vectors [][]float32, topK int, lambda float64) []ScoredMemory

MMR performs Maximal Marginal Relevance reranking to balance relevance and diversity. lambda controls the tradeoff: 1.0 = pure relevance, 0.0 = pure diversity.

type ScoringWeights

type ScoringWeights struct {
	Relevance  float64 // default: 1.0
	Recency    float64 // default: 0.5
	Importance float64 // default: 0.3
}

ScoringWeights holds the weights for the three scoring components.

func DefaultScoringWeights

func DefaultScoringWeights() ScoringWeights

DefaultScoringWeights returns the default scoring weights.

type ScrollOptions

type ScrollOptions struct {
	Limit   int
	Filters []Filter
	Offset  string // opaque offset token from previous Scroll call; empty for first page
}

ScrollOptions configures a filter-based scroll query (no vector needed).

type SearchOptions

type SearchOptions struct {
	Limit   int
	Filters []Filter
}

SearchOptions configures a vector search query.

type Store

type Store interface {
	// Insert stores a memory with its embedding vector.
	Insert(ctx context.Context, mem *Memory, vector []float32) error

	// Search returns scored memories matching the query vector.
	// Results are ordered by raw cosine similarity (caller applies final scoring).
	Search(ctx context.Context, vector []float32, opts SearchOptions) ([]ScoredMemory, error)

	// Scroll returns memories matching filters without requiring a query vector.
	// Results are ordered by creation time (newest first). Use offset for pagination.
	Scroll(ctx context.Context, opts ScrollOptions) ([]Memory, string, error)

	// Delete removes memories by IDs. Returns the number of successfully deleted items.
	Delete(ctx context.Context, ids []string) (int, error)

	// Update modifies payload fields of an existing memory without re-embedding.
	Update(ctx context.Context, id string, fields map[string]any) error

	// SearchByIDs retrieves specific memories by their IDs.
	SearchByIDs(ctx context.Context, ids []string) ([]Memory, error)

	// EnsureCollection creates the collection and indexes if they don't exist.
	EnsureCollection(ctx context.Context) error

	// Stats returns collection statistics.
	Stats(ctx context.Context) (*CollectionStats, error)

	// DeleteExpired removes all memories whose valid_until > 0 AND valid_until < now.
	// Returns the number of deleted memories.
	DeleteExpired(ctx context.Context) (int, error)
}

Store is the abstract interface for vector storage backends. Implementations must be safe for concurrent use.

Jump to

Keyboard shortcuts

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