Documentation
¶
Overview ¶
Package memory defines the core types and scoring algorithms for Engram.
Index ¶
- Constants
- Variables
- func ComputeValidUntil(cfg TTLConfig, memType MemoryType, importance float64, tags []string, ...) float64
- func ContentHash(content, modelKey string) string
- func Score(m *Memory, cosineSim float64, weights ScoringWeights, decay DecayConfig) float64
- type CollectionStats
- type DecayConfig
- type EmbedCache
- type Filter
- type FilterOp
- type Memory
- type MemoryType
- type Option
- type ScoredMemory
- type ScoringWeights
- type ScrollOptions
- type SearchOptions
- type Store
- type TTLConfig
Constants ¶
const ( LifecycleActive = "active" LifecycleDeprecated = "deprecated" LifecycleArchived = "archived" )
Lifecycle FSM state constants (v0.2).
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 ¶
var ValidTypes = map[MemoryType]bool{ TypeIdentity: true, TypeEvent: true, TypeInsight: true, TypeDirective: true, }
ValidTypes is the set of all valid memory types.
Functions ¶
func ComputeValidUntil ¶ added in v0.2.0
func ComputeValidUntil(cfg TTLConfig, memType MemoryType, importance float64, tags []string, explicitValidUntil float64) float64
ComputeValidUntil calculates the valid_until timestamp for a memory.
Rules:
- If the caller provided a non-zero valid_until, it is returned unchanged (explicit override always wins).
- Otherwise the TTL matrix is consulted: type × importance band → duration.
- Duration 0 means permanent (returns 0).
- Special tag overrides: "permanent" tag → returns 0 (never expires). "time-sensitive" or "location" tag → forces 7-day TTL (unless permanent).
func ContentHash ¶ added in v0.2.0
ContentHash computes a 32-hex-char cache key for an embedding request. modelKey should encode the model name and version (e.g. "voyage-3/v1") so that model upgrades automatically invalidate stale cache entries.
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.
Final formula (W17 v1.1):
final = confidence × (w_rel·relevance + w_rec·recency + w_imp·importance)
where `confidence` is m.Confidence when > 0, else 1.0 (backward compat for pre-v1.1 memories that never set the field). Reflection-origin insights self-report a grounding score in [0, 1]; low-confidence ones are kept out of Engram entirely and saved to Obsidian drafts instead.
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 EmbedCache ¶ added in v0.2.0
type EmbedCache interface {
Get(contentHash string) ([]float32, bool)
Put(contentHash string, vector []float32)
// Stats returns cumulative hit and miss counts since creation.
Stats() (hits, misses int64)
}
EmbedCache caches content hash → embedding vector pairs. Embeddings are deterministic (same content + model always produces the same vector), so entries never expire.
func NewEmbedCache ¶ added in v0.2.0
func NewEmbedCache(capacity int) EmbedCache
NewEmbedCache returns an in-memory LRU embed cache. capacity is the max number of entries; 0 defaults to 10000 (~40 MB at 1024-dim float32).
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 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
// ReflectedAt is the Unix timestamp when this memory was processed by the
// Reflection Engine. Zero means it has not been reflected yet.
// Replaces the legacy metadata["reflected"] bool field (W16).
ReflectedAt float64 `json:"reflected_at,omitempty"`
// Confidence is a 0-1 grounding score self-reported by the Reflection
// Engine (W17 v1.1) for reflection-origin insights. Zero means "not set"
// and is treated as 1.0 in scoring for backward compatibility with
// pre-v1.1 memories. Used as a multiplier on the final relevance score.
Confidence float64 `json:"confidence,omitempty"`
ArchivedAt float64 `json:"archived_at,omitempty"`
ArchiveReason string `json:"archive_reason,omitempty"`
// LifecycleStatus is the FSM state of the memory (v0.2).
// Valid values: "active" (default), "deprecated", "archived".
// Transitions via PATCH: active→deprecated, active→archived, deprecated→archived.
// Restore via POST /{id}/reset: archived→active, deprecated→active.
LifecycleStatus string `json:"lifecycle_status,omitempty"`
// LastAccessedSource records the X-Caller-Type of the last search that hit this memory.
LastAccessedSource string `json:"last_accessed_source,omitempty"`
// Collection is the logical collection this memory belongs to (e.g. engram_user, engram_reflection).
// Set at write time by the server using its configured collection name.
Collection string `json:"collection,omitempty"`
}
Memory is a single unit of stored knowledge.
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 WithConfidence ¶ added in v0.2.0
func WithImportance ¶
func WithMetadata ¶
func WithSource ¶
func WithType ¶
func WithType(t MemoryType) Option
func WithValidUntil ¶
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
ExcludeArchived bool // when true, memories with lifecycle_status="archived" are excluded
}
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.
type TTLConfig ¶ added in v0.2.0
type TTLConfig struct {
Rules map[MemoryType][3]time.Duration // [low (<5), mid (5-7), high (≥8)]
}
TTLConfig holds the TTL matrix: type × importance band → duration. Duration 0 means the memory never expires.
func DefaultTTLConfig ¶ added in v0.2.0
func DefaultTTLConfig() TTLConfig
DefaultTTLConfig returns the recommended TTL matrix.
| type | importance < 5 | importance 5-7 | importance ≥ 8 | |-----------|----------------|----------------|----------------| | identity | permanent | permanent | permanent | | directive | 90d | permanent | permanent | | insight | 30d | 90d | permanent | | event | 3d | 7d | 30d |