Documentation
¶
Index ¶
- Variables
- func BoostNode(ctx context.Context, store storage.Storage, id string, boost float64) error
- func CacheKey(opts RecallOpts) string
- func DetectOpenLoop(text string, minLen int) string
- func DetectResolution(text string) bool
- func ExpandQuery(query string) string
- func ExportHTML(ctx context.Context, store storage.Storage) (string, error)
- func FormatContext(nodes []*storage.Node) string
- func FuzzyMatch(query, content string) bool
- func GarbageCollect(ctx context.Context, store storage.Storage, cfg DecayConfig) (int, error)
- func GracefulShutdown(e *Engine)
- func IsValidNodeType(typ string) bool
- func IsWellSpaced(accessTimes []time.Time, config SpacingConfig) bool
- func MMRRerank(nodes []*storage.Node, scores map[string]float64, lambda float64, k int) []*storage.Node
- func NormalizeBM25(rawScore float64, queryTermCount int) float64
- func QueryTermCount(query string) int
- func RunDecay(ctx context.Context, store storage.Storage, cfg DecayConfig) error
- func ShortestPath(ctx context.Context, store storage.Storage, fromID, toID string) ([]string, error)
- func SpacingScore(accessTimes []time.Time, config SpacingConfig) float64
- func SpreadAttenuatedBoost(similarity float64, numLinked int, decay float64) float64
- func StartupSelfTest(ctx context.Context, store storage.Storage) error
- func SupersedeEdge(edge *TemporalEdge)
- func TimelineFilter(limit int) storage.NodeFilter
- func TrimToTokenBudget(nodes []*storage.Node, budget int) []*storage.Node
- type AccessTracker
- type AuditEntry
- type AuditLog
- type BloomFilter
- type Community
- type CommunityDetector
- type ConflictCandidate
- type ContextPacker
- type ContextualScoring
- type ConversationSummarizer
- type CuriosityConfig
- type CuriosityEngine
- type DecayConfig
- type DirectiveType
- type EdgeInput
- type Engine
- func (e *Engine) Branch(ctx context.Context, nodeID, newContent, newType string) (*storage.Node, error)
- func (e *Engine) CachedRecall(nodes []*storage.Node)
- func (e *Engine) Close()
- func (e *Engine) Compact(ctx context.Context, project string) (int, error)
- func (e *Engine) CompressSession(ctx context.Context, sessionID, project string) (*storage.Node, error)
- func (e *Engine) Context(ctx context.Context, project string) (*RecallResult, error)
- func (e *Engine) Feedback(ctx context.Context, id string, action FeedbackAction, newContent string) error
- func (e *Engine) FindConflictCandidates(ctx context.Context, nodeID, content string, limit int) ([]ConflictCandidate, error)
- func (e *Engine) Forget(ctx context.Context, id string) error
- func (e *Engine) FusedRecall(ctx context.Context, opts RecallOpts) (*RecallResult, error)
- func (e *Engine) GetMemoryStats(ctx context.Context) (*MemoryStats, error)
- func (e *Engine) GetMetrics() Metrics
- func (e *Engine) GetNodeHistory(ctx context.Context, nodeID string) ([]NodeHistoryEntry, error)
- func (e *Engine) GetUserProfile(ctx context.Context, project string) (*UserProfile, error)
- func (e *Engine) Graph() graph.Graph
- func (e *Engine) Integrity() *MemoryIntegrity
- func (e *Engine) MentalModel(ctx context.Context, project string) (*mental.Model, error)
- func (e *Engine) PendingNodes(ctx context.Context, project string, threshold float64) ([]*storage.Node, error)
- func (e *Engine) Profile(ctx context.Context, project string) (*profile.Profile, error)
- func (e *Engine) Query(ctx context.Context, question string, project string) (*QueryResult, error)
- func (e *Engine) Recall(ctx context.Context, opts RecallOpts) (*RecallResult, error)
- func (e *Engine) Remember(ctx context.Context, in RememberInput) (*storage.Node, error)
- func (e *Engine) Rollback(ctx context.Context, id string, version int) error
- func (e *Engine) SelfLink(ctx context.Context, node *storage.Node)
- func (e *Engine) StartSession(ctx context.Context, project, agent string) (string, error)
- func (e *Engine) Status(ctx context.Context, project string) (*Status, error)
- func (e *Engine) Store() storage.Storage
- func (e *Engine) UpdateUserPreference(ctx context.Context, project, key, value string) error
- func (e *Engine) VectorSearch(query []float32, k int) []string
- func (e *Engine) WithIntegrity(mi *MemoryIntegrity) *Engine
- func (e *Engine) WithSummarizer(s compact.Summarizer) *Engine
- type Entity
- type EntityIndex
- type EpistemicConfig
- type EpistemicDirective
- type EpistemicEngine
- func (e *EpistemicEngine) CreateDirective(dtype DirectiveType, question, context string, priority float64, ...) *EpistemicDirective
- func (e *EpistemicEngine) ExpireOld() int
- func (e *EpistemicEngine) GetForSession() []*EpistemicDirective
- func (e *EpistemicEngine) Resolve(directiveID, resolution string) bool
- type ExplorationTarget
- type FeedbackAction
- type FeedbackSignal
- type GitLearner
- type GraphDiff
- type HNSW
- type HandoffSummary
- type HealthCheck
- type HealthChecker
- type HealthReport
- type HealthStatus
- type HierarchicalMemory
- type HierarchyLevel
- type HybridSearch
- type IngestResult
- type Ingester
- func (ing *Ingester) DetectStack(ctx context.Context, projectDir string) (*IngestResult, error)
- func (ing *Ingester) IngestClaudeMD(ctx context.Context, path string) (*IngestResult, error)
- func (ing *Ingester) IngestCodeFile(ctx context.Context, path string) (*IngestResult, error)
- func (ing *Ingester) IngestConversation(ctx context.Context, text string) (*IngestResult, error)
- func (ing *Ingester) IngestCursorRules(ctx context.Context, path string) (*IngestResult, error)
- func (ing *Ingester) IngestDirectory(ctx context.Context, dir string) (*IngestResult, error)
- func (ing *Ingester) IngestFile(ctx context.Context, path string) (*IngestResult, error)
- func (ing *Ingester) IngestMarkdown(ctx context.Context, content, source string) (*IngestResult, error)
- type LLMExtractor
- type LabileMemory
- type LearnResult
- type MemoryCluster
- type MemoryExpiry
- type MemoryIntegrity
- type MemoryStats
- type MemorySuggestion
- type Metrics
- type NodeHistoryEntry
- type OpenLoop
- type PackedContext
- type PageRank
- type ProactiveContext
- type ProspectiveConfig
- type ProspectiveEngine
- func (e *ProspectiveEngine) CheckTriggers(messageText string, messageEmbedding []float32) []*ProspectiveMemory
- func (e *ProspectiveEngine) CleanExpired() int
- func (e *ProspectiveEngine) Create(triggerCondition, action, sourceSession string, triggerEmbedding []float32, ...) *ProspectiveMemory
- func (e *ProspectiveEngine) GetActive() []*ProspectiveMemory
- type ProspectiveMemory
- type QueryCache
- type QueryMetrics
- type QueryPlan
- type QueryPlanner
- type QueryResult
- type Quiz
- type QuizQuestion
- type QuizResult
- type RankedNode
- type RateLimiter
- type RecallOpts
- type RecallResult
- type ReconsolidationConfig
- type ReconsolidationEngine
- func (e *ReconsolidationEngine) Cleanup() int
- func (e *ReconsolidationEngine) FlagContradiction(chunkID string)
- func (e *ReconsolidationEngine) GetContradicted() []string
- func (e *ReconsolidationEngine) IsLabile(chunkID string) bool
- func (e *ReconsolidationEngine) OnRecall(chunkID string)
- func (e *ReconsolidationEngine) Strengthen(chunkID string) float64
- type RememberInput
- type ScoredNode
- type ScoringConfig
- type SessionHandoff
- type SomaticConfig
- type SomaticEngine
- type SomaticMarker
- type SpacingConfig
- type Sparsifier
- type SparsifyResult
- type Status
- type SuggestedEdge
- type SummarizedMemory
- type TemplateMemory
- type TemplateSet
- type Templates
- type TemporalEdge
- type TemporalFilter
- func (tf *TemporalFilter) ActiveEdges(ctx context.Context, nodeID string) ([]*storage.Edge, error)
- func (tf *TemporalFilter) ChangedBetween(ctx context.Context, start, end time.Time, limit int) ([]*storage.Node, error)
- func (tf *TemporalFilter) FilterByTime(ctx context.Context, nodes []*storage.Node, query TemporalQuery) []*storage.Node
- func (tf *TemporalFilter) IsSuperseded(ctx context.Context, nodeID string) (bool, string)
- func (tf *TemporalFilter) RecentSince(ctx context.Context, since time.Time, limit int) ([]*storage.Node, error)
- type TemporalQuery
- type UserProfile
- type ZeigarnikChunk
- type ZeigarnikConfig
- type ZeigarnikEngine
- func (e *ZeigarnikEngine) CloseLoop(chunkID string)
- func (e *ZeigarnikEngine) DecayMultiplier(chunkID string) float64
- func (e *ZeigarnikEngine) GetActiveLoops(limit int) []*OpenLoop
- func (e *ZeigarnikEngine) MarkOpenLoop(chunkID, context string)
- func (e *ZeigarnikEngine) ScanChunks(chunks []ZeigarnikChunk) int
Constants ¶
This section is empty.
Variables ¶
var DefaultDecayConfig = DecayConfig{
HalfLifeDays: 30,
MinConfidence: 0.1,
BoostOnAccess: 0.2,
}
Functions ¶
func CacheKey ¶
func CacheKey(opts RecallOpts) string
CacheKey builds a cache key from recall options.
func DetectOpenLoop ¶
func DetectResolution ¶
func ExpandQuery ¶
ExpandQuery adds related terms to improve BM25 recall. Handles common coding synonyms and abbreviations.
Examples:
"auth" → "auth authentication authorize" "db" → "db database" "config" → "config configuration settings"
func ExportHTML ¶
ExportHTML generates a standalone HTML file with an interactive memory graph. The file can be shared — no server required, opens in any browser.
func FormatContext ¶
FormatContext formats nodes as a markdown context block for injection. Uses tiered injection (Cursor-inspired):
- Pinned: full content always shown
- Hot tier (tier 1): full content
- Warm tier (tier 2): summary/gloss only (full content available via recall)
- Cold tier: omitted from context
func FuzzyMatch ¶
FuzzyMatch checks if query approximately matches content despite typos. Uses Levenshtein-inspired approach: if edit distance / length < 0.3, it's a match.
func GarbageCollect ¶
GarbageCollect removes nodes below min_confidence (except anchors: file/entity).
func GracefulShutdown ¶
func GracefulShutdown(e *Engine)
GracefulShutdown flushes all pending operations before closing.
func IsValidNodeType ¶
IsValidNodeType reports whether typ is a recognized node type.
func IsWellSpaced ¶
func IsWellSpaced(accessTimes []time.Time, config SpacingConfig) bool
func MMRRerank ¶
func MMRRerank(nodes []*storage.Node, scores map[string]float64, lambda float64, k int) []*storage.Node
MMRRerank applies Maximal Marginal Relevance to diversify results. MMR = λ * relevance(doc) - (1-λ) * max_sim(doc, selected) Prevents near-duplicate results from dominating the output.
func NormalizeBM25 ¶
NormalizeBM25 applies sigmoid normalization to raw BM25 scores with query-length-adaptive parameters. Based on Mem0 v3's approach.
Short queries (1-3 terms): midpoint=5.0, steepness=0.7 Medium queries (4-6 terms): midpoint=7.0, steepness=0.6 Long queries (7-14 terms): midpoint=10.0, steepness=0.5 Very long queries (15+): midpoint=12.0, steepness=0.4
func QueryTermCount ¶
QueryTermCount counts significant terms in a query (for BM25 normalization).
func RunDecay ¶
RunDecay applies half-life decay to all nodes in the store. Orphan nodes (0 edges) and superseded nodes decay 2× faster.
func ShortestPath ¶
func ShortestPath(ctx context.Context, store storage.Storage, fromID, toID string) ([]string, error)
ShortestPath finds the shortest path between two nodes using BFS. Returns the path as a list of node IDs, or nil if no path exists.
func SpacingScore ¶
func SpacingScore(accessTimes []time.Time, config SpacingConfig) float64
func SpreadAttenuatedBoost ¶
SpreadAttenuatedBoost computes entity boost with spread attenuation. Penalizes entities that link to many memories (too generic). Based on Mem0 v3: boost = similarity * 0.5 * 1/(1 + decay*(numLinked-1)²)
func StartupSelfTest ¶
StartupSelfTest runs quick smoke tests to verify system integrity. Returns nil if all checks pass, error describing what's wrong otherwise.
func SupersedeEdge ¶
func SupersedeEdge(edge *TemporalEdge)
func TimelineFilter ¶
func TimelineFilter(limit int) storage.NodeFilter
TimelineFilter returns a NodeFilter suitable for timeline display.
Types ¶
type AccessTracker ¶
type AccessTracker struct {
// contains filtered or unexported fields
}
AccessTracker batches node access events to reduce SQLite UPDATE churn. Instead of updating nodes.access_count on every recall (which causes write contention under concurrent load), it INSERTs lightweight rows into access_log and periodically flushes them in a single aggregated UPDATE.
func NewAccessTracker ¶
func NewAccessTracker(store storage.Storage, interval time.Duration) *AccessTracker
NewAccessTracker creates a tracker that flushes every interval.
func (*AccessTracker) Flush ¶
func (at *AccessTracker) Flush(ctx context.Context)
Flush immediately applies all pending access counts to nodes.
func (*AccessTracker) Log ¶
func (at *AccessTracker) Log(ctx context.Context, nodeID string)
Log records an access for the given node ID (best-effort, non-blocking).
func (*AccessTracker) Stop ¶
func (at *AccessTracker) Stop()
Stop halts the background flusher. Safe to call multiple times.
type AuditEntry ¶
type AuditEntry struct {
Timestamp time.Time `json:"ts"`
Operation string `json:"op"` // remember, recall, forget, link, feedback
NodeID string `json:"node_id,omitempty"`
NodeType string `json:"node_type,omitempty"`
Agent string `json:"agent,omitempty"`
Details string `json:"details,omitempty"`
}
AuditEntry is a single audit record.
type AuditLog ¶
type AuditLog struct {
// contains filtered or unexported fields
}
AuditLog records all memory operations for traceability. Stores: who did what, when, on which node. Persists to .yaad/audit.jsonl (append-only).
func NewAuditLog ¶
NewAuditLog creates or opens the audit log file.
type BloomFilter ¶
type BloomFilter struct {
// contains filtered or unexported fields
}
BloomFilter provides O(1) negative lookups for memory content. If the filter says "not present", it's guaranteed not in the store. If it says "maybe present", we proceed with the FTS5 query. Eliminates ~40-60% of unnecessary SQLite queries for miss cases.
Parameters tuned for coding memory: - Expected items: 10,000 memories - False positive rate: 1% - Bit array size: ~96KB (minimal memory overhead)
func NewBloomFilter ¶
func NewBloomFilter(expectedItems int, fpRate float64) *BloomFilter
NewBloomFilter creates a bloom filter optimized for the expected number of items.
func (*BloomFilter) Add ¶
func (bf *BloomFilter) Add(term string)
Add inserts a term into the bloom filter.
func (*BloomFilter) AddTerms ¶
func (bf *BloomFilter) AddTerms(content string)
AddTerms indexes all significant terms from content.
func (*BloomFilter) Count ¶
func (bf *BloomFilter) Count() int
Count returns the number of items added.
func (*BloomFilter) FalsePositiveRate ¶
func (bf *BloomFilter) FalsePositiveRate() float64
FalsePositiveRate returns the estimated current FP rate.
func (*BloomFilter) MayContain ¶
func (bf *BloomFilter) MayContain(term string) bool
MayContain returns false if the term is DEFINITELY not in the filter. Returns true if it MIGHT be present (check FTS5 to confirm).
func (*BloomFilter) MayContainAny ¶
func (bf *BloomFilter) MayContainAny(query string) bool
MayContainAny returns true if any of the query terms might be present.
type Community ¶
type Community struct {
ID int
NodeIDs []string
Summary string
Size int
Types map[string]int // type → count
}
Community represents a cluster of related memories.
type CommunityDetector ¶
type CommunityDetector struct {
// contains filtered or unexported fields
}
CommunityDetector finds clusters of related memories in the graph using label propagation (lightweight, no external deps). Each community gets a summary enabling "what are the main themes?" global queries.
Based on GraphRAG (Microsoft): community detection → summarization → global retrieval.
func NewCommunityDetector ¶
func NewCommunityDetector(store storage.Storage) *CommunityDetector
NewCommunityDetector creates a detector.
func (*CommunityDetector) Detect ¶
Detect finds communities using iterative label propagation. Each node starts with its own label. Iteratively, each node adopts the most frequent label among its neighbors. Converges in ~5 iterations.
func (*CommunityDetector) FindCommunityForQuery ¶
func (cd *CommunityDetector) FindCommunityForQuery(communities []Community, query string) *Community
FindCommunityForQuery returns the most relevant community for a query.
type ConflictCandidate ¶
ConflictCandidate represents a potential conflicting node found via FTS.
type ContextPacker ¶
type ContextPacker struct {
// contains filtered or unexported fields
}
ContextPacker optimizes what gets injected into an agent's context window. Packs maximum information density within a token budget by:
- Prioritizing by PageRank importance + confidence + recency
- Deduplicating similar content
- Compressing verbose memories into concise forms
- Respecting type quotas (max N conventions, M decisions, etc.)
func NewContextPacker ¶
func NewContextPacker(budget int) *ContextPacker
NewContextPacker creates a packer with the given token budget.
func (*ContextPacker) Pack ¶
func (cp *ContextPacker) Pack(nodes []*storage.Node) *PackedContext
Pack selects and formats the optimal subset of nodes for the context window.
type ContextualScoring ¶
type ContextualScoring struct {
// contains filtered or unexported fields
}
ContextualScoring boosts memories that match the current session's topic. Detects the session topic from recent queries and boosts related content.
func NewContextualScoring ¶
func NewContextualScoring() *ContextualScoring
NewContextualScoring creates a contextual scorer.
func (*ContextualScoring) LastActivity ¶
func (cs *ContextualScoring) LastActivity() time.Time
LastActivity returns when the last query was recorded.
func (*ContextualScoring) RecordQuery ¶
func (cs *ContextualScoring) RecordQuery(query string)
RecordQuery adds a query to the topic window.
func (*ContextualScoring) Reset ¶
func (cs *ContextualScoring) Reset()
Reset clears topic history (call at session start).
func (*ContextualScoring) TopicBoost ¶
func (cs *ContextualScoring) TopicBoost(node *storage.Node) float64
TopicBoost returns a multiplier for nodes that relate to recent session topics.
type ConversationSummarizer ¶
type ConversationSummarizer struct{}
ConversationSummarizer compresses multi-turn conversations into single memories. Used when ingesting long transcripts — extracts the key takeaways.
func (*ConversationSummarizer) Summarize ¶
func (cs *ConversationSummarizer) Summarize(conversation string, maxMemories int) []SummarizedMemory
Summarize extracts key points from a conversation into concise memories.
type CuriosityConfig ¶
func DefaultCuriosityConfig ¶
func DefaultCuriosityConfig() CuriosityConfig
type CuriosityEngine ¶
type CuriosityEngine struct {
// contains filtered or unexported fields
}
func NewCuriosityEngine ¶
func NewCuriosityEngine(config CuriosityConfig) *CuriosityEngine
func (*CuriosityEngine) AddTarget ¶
func (e *CuriosityEngine) AddTarget(topic, gapType string, priority float64) *ExplorationTarget
func (*CuriosityEngine) GetTopTargets ¶
func (e *CuriosityEngine) GetTopTargets(limit int) []*ExplorationTarget
func (*CuriosityEngine) MarkExplored ¶
func (e *CuriosityEngine) MarkExplored(targetID, findings string) bool
type DecayConfig ¶
type DecayConfig struct {
HalfLifeDays float64 // default 30
MinConfidence float64 // default 0.1 — below this, eligible for GC
BoostOnAccess float64 // default 0.2
}
DecayConfig controls decay behaviour.
type DirectiveType ¶
type DirectiveType string
const ( DirectiveContradiction DirectiveType = "contradiction" DirectiveKnowledgeGap DirectiveType = "knowledge_gap" DirectiveLowConfidence DirectiveType = "low_confidence" DirectiveStaleFact DirectiveType = "stale_fact" )
type Engine ¶
type Engine struct {
DecayConfig DecayConfig
// contains filtered or unexported fields
}
Engine is the core memory engine wrapping graph + storage.
func (*Engine) Branch ¶
func (e *Engine) Branch(ctx context.Context, nodeID, newContent, newType string) (*storage.Node, error)
Branch creates a new node branching off from the given nodeID. The new node inherits the parent's project and scope but carries the provided newContent and newType. An edge of type "caused_by" links the branch node back to its parent, forming a DAG branch.
func (*Engine) CachedRecall ¶
CachedRecall wraps FusedRecall with caching.
func (*Engine) Close ¶
func (e *Engine) Close()
Close shuts down the engine and its background workers.
func (*Engine) CompressSession ¶
func (e *Engine) CompressSession(ctx context.Context, sessionID, project string) (*storage.Node, error)
CompressSession creates a session summary node linking all memories from the session.
func (*Engine) Context ¶
Context returns the hot-tier subgraph for session start injection. Pinned nodes always appear first (guaranteed 500-token budget), followed by hot-tier and active tasks filling the remaining budget.
func (*Engine) Feedback ¶
func (e *Engine) Feedback(ctx context.Context, id string, action FeedbackAction, newContent string) error
Feedback applies user feedback to a memory node.
func (*Engine) FindConflictCandidates ¶
func (e *Engine) FindConflictCandidates(ctx context.Context, nodeID, content string, limit int) ([]ConflictCandidate, error)
FindConflictCandidates searches for existing nodes that may conflict with the given content. Uses FTS search scoped to the same node type, returning candidates above a score threshold.
func (*Engine) FusedRecall ¶
func (e *Engine) FusedRecall(ctx context.Context, opts RecallOpts) (*RecallResult, error)
FusedRecall performs multi-signal retrieval combining:
- BM25 keyword search (via existing SearchNodes FTS5)
- Graph traversal (via existing IntentBFS from seed nodes)
- Recency signal (recently accessed/modified nodes)
Then fuses results using Reciprocal Rank Fusion (RRF).
This is inspired by mem0's multi-signal retrieval architecture which combines semantic search, BM25, and entity-graph traversal with RRF to produce higher-quality recall than any single signal alone.
Unlike the existing Recall method (which uses BM25 seeds then graph expansion with a confidence*recency heuristic), FusedRecall treats each signal as an independent ranked list and merges them with a principled rank-fusion algorithm. This avoids the score-space mismatch problem where BM25 scores, graph distances, and timestamps are on different scales.
func (*Engine) GetMemoryStats ¶
func (e *Engine) GetMemoryStats(ctx context.Context) (*MemoryStats, error)
GetMemoryStats returns aggregate statistics about the memory graph.
func (*Engine) GetMetrics ¶
GetMetrics returns a copy of the engine's operational metrics.
func (*Engine) GetNodeHistory ¶
GetNodeHistory returns the version history of a memory node.
func (*Engine) GetUserProfile ¶
GetUserProfile returns the user profile for a project, built from preference nodes.
func (*Engine) Integrity ¶
func (e *Engine) Integrity() *MemoryIntegrity
Integrity returns the engine's memory integrity checker (may be nil).
func (*Engine) MentalModel ¶
MentalModel generates an auto-evolving project summary.
func (*Engine) PendingNodes ¶
func (e *Engine) PendingNodes(ctx context.Context, project string, threshold float64) ([]*storage.Node, error)
PendingNodes returns low-confidence nodes that may need review. Limited to 1000 nodes to prevent unbounded memory use on large graphs.
func (*Engine) Profile ¶
Profile returns an auto-maintained user/project profile (static facts + dynamic context).
func (*Engine) Query ¶
Query answers a natural language question by retrieving relevant memories and synthesizing an answer from them. No LLM required — uses template-based synthesis from high-confidence retrieved nodes.
How it works:
- Parse the question — classify intent using the existing intent package
- Retrieve — call FusedRecall with the question as the query
- Rank and filter — keep only nodes with confidence > 0.3
- Synthesize — format retrieved memories into a coherent answer using intent-specific templates
- Calculate confidence — average confidence of the used nodes
func (*Engine) Recall ¶
func (e *Engine) Recall(ctx context.Context, opts RecallOpts) (*RecallResult, error)
Recall performs graph-aware hybrid search: BM25 seed → graph expand → rank.
func (*Engine) Remember ¶
Remember creates a memory node with privacy filtering, dedup, and entity extraction.
func (*Engine) SelfLink ¶
SelfLink finds existing nodes semantically related to the new node and creates typed edges. Inspired by A-MEM's Zettelkasten self-organizing approach. Runs as a best-effort step during Remember() — failures don't block storage.
func (*Engine) StartSession ¶
StartSession creates a new session record and returns its ID.
func (*Engine) UpdateUserPreference ¶
UpdateUserPreference stores or updates a single preference as a yaad node.
func (*Engine) VectorSearch ¶
VectorSearch performs HNSW-accelerated nearest neighbor search. Returns node IDs ranked by vector similarity.
func (*Engine) WithIntegrity ¶
func (e *Engine) WithIntegrity(mi *MemoryIntegrity) *Engine
WithIntegrity sets the memory integrity checker for signature persistence.
func (*Engine) WithSummarizer ¶
func (e *Engine) WithSummarizer(s compact.Summarizer) *Engine
WithSummarizer sets a custom summarizer for compaction (e.g., LLM-backed).
type Entity ¶
Entity represents an auto-extracted entity from content.
func ExtractEntities ¶
ExtractEntities pulls file paths, packages, functions, and classes from content.
type EntityIndex ¶
type EntityIndex struct {
// contains filtered or unexported fields
}
EntityIndex maintains a parallel index of entities (functions, files, libraries, classes, APIs) extracted from memory content. During retrieval, query entities are matched against this index to boost relevant memories.
Based on Mem0 v3's approach: extract entities on ingestion, boost on retrieval. But faster: regex-based extraction (no LLM call), O(1) lookup via map.
func (*EntityIndex) BoostScores ¶
func (ei *EntityIndex) BoostScores(query string) map[string]float64
BoostScores takes a query, extracts entities from it, and returns boost multipliers for node IDs that share entities with the query. Returns map[nodeID] → boost factor (1.0 = no boost, higher = more entity overlap).
func (*EntityIndex) IndexNode ¶
func (ei *EntityIndex) IndexNode(node *storage.Node)
IndexNode extracts entities from a node and adds them to the index.
func (*EntityIndex) LoadFromStore ¶
LoadFromStore rebuilds the entity index from all nodes in the store.
func (*EntityIndex) RemoveNode ¶
func (ei *EntityIndex) RemoveNode(nodeID string)
RemoveNode removes a node from the entity index.
func (*EntityIndex) Size ¶
func (ei *EntityIndex) Size() int
Size returns the number of unique entities tracked.
type EpistemicConfig ¶
type EpistemicConfig struct {
Enabled bool `json:"enabled"`
MaxActiveDirectives int `json:"max_active_directives"`
MaxPerSession int `json:"max_per_session"`
MinPriority float64 `json:"min_priority"`
ExpiryDays int `json:"expiry_days"`
}
func DefaultEpistemicConfig ¶
func DefaultEpistemicConfig() EpistemicConfig
type EpistemicDirective ¶
type EpistemicDirective struct {
ID string `json:"id"`
Type DirectiveType `json:"type"`
Question string `json:"question"`
Context string `json:"context"`
Priority float64 `json:"priority"`
CreatedAt time.Time `json:"created_at"`
ResolvedAt *time.Time `json:"resolved_at,omitempty"`
Resolution string `json:"resolution,omitempty"`
SourceEntityIDs []string `json:"source_entity_ids"`
Attempts int `json:"attempts"`
}
type EpistemicEngine ¶
type EpistemicEngine struct {
// contains filtered or unexported fields
}
func NewEpistemicEngine ¶
func NewEpistemicEngine(config EpistemicConfig) *EpistemicEngine
func (*EpistemicEngine) CreateDirective ¶
func (e *EpistemicEngine) CreateDirective(dtype DirectiveType, question, context string, priority float64, sourceEntityIDs []string) *EpistemicDirective
func (*EpistemicEngine) ExpireOld ¶
func (e *EpistemicEngine) ExpireOld() int
func (*EpistemicEngine) GetForSession ¶
func (e *EpistemicEngine) GetForSession() []*EpistemicDirective
func (*EpistemicEngine) Resolve ¶
func (e *EpistemicEngine) Resolve(directiveID, resolution string) bool
type ExplorationTarget ¶
type FeedbackAction ¶
type FeedbackAction string
FeedbackAction represents what to do with a pending memory.
const ( FeedbackApprove FeedbackAction = "approve" FeedbackEdit FeedbackAction = "edit" FeedbackDiscard FeedbackAction = "discard" )
type FeedbackSignal ¶
type FeedbackSignal struct {
// contains filtered or unexported fields
}
FeedbackSignal tracks which memories were useful vs irrelevant. Enables: demote nodes explicitly marked irrelevant, boost nodes that led to successful outcomes. Learns over time which memories matter.
func NewFeedbackSignal ¶
func NewFeedbackSignal(store storage.Storage) *FeedbackSignal
NewFeedbackSignal creates a feedback tracker.
func (*FeedbackSignal) ApplyToNodes ¶
func (fs *FeedbackSignal) ApplyToNodes(ctx context.Context) int
ApplyToNodes adjusts confidence based on accumulated feedback.
func (*FeedbackSignal) BoostMultiplier ¶
func (fs *FeedbackSignal) BoostMultiplier(nodeID string) float64
BoostMultiplier returns a score multiplier based on feedback history. Positive feedback → boost (up to 1.5x), negative → penalty (down to 0.5x).
func (*FeedbackSignal) MarkIrrelevant ¶
func (fs *FeedbackSignal) MarkIrrelevant(nodeID string)
MarkIrrelevant indicates a memory was not useful (noise).
func (*FeedbackSignal) MarkRelevant ¶
func (fs *FeedbackSignal) MarkRelevant(nodeID string)
MarkRelevant indicates a memory was useful in context.
type GitLearner ¶
type GitLearner struct {
// contains filtered or unexported fields
}
GitLearner extracts memories from git history automatically. Scans commit messages, diffs, and blame data to discover:
- Architecture decisions (from commit messages with "chose", "decided", "switched")
- Conventions (from repeated patterns across commits)
- Bug patterns (from fix/hotfix commits)
- File purposes (from first-commit messages)
No other memory tool does this. Your project's entire history becomes memory.
func NewGitLearner ¶
func NewGitLearner(dir string, engine *Engine) *GitLearner
NewGitLearner creates a learner for a project directory.
func (*GitLearner) LearnFromBlame ¶
func (gl *GitLearner) LearnFromBlame(ctx context.Context, filePath string) error
LearnFromBlame extracts file-level knowledge from git blame. Discovers who owns what and when major changes happened.
func (*GitLearner) LearnFromHistory ¶
func (gl *GitLearner) LearnFromHistory(ctx context.Context, limit int, since time.Time) (*LearnResult, error)
LearnFromHistory scans git log and extracts memories. limit: max commits to scan (0 = all). since: only commits after this date.
func (*GitLearner) Suggest ¶
func (gl *GitLearner) Suggest(ctx context.Context) ([]MemorySuggestion, error)
Suggest analyzes recent changes and suggests memories to store.
type GraphDiff ¶
type GraphDiff struct {
Added []*storage.Node
Modified []*storage.Node
Removed []string // IDs of removed/archived nodes
}
GraphDiff shows what memories changed between two points in time.
type HNSW ¶
type HNSW struct {
M int // max connections per layer
// contains filtered or unexported fields
}
HNSW implements Hierarchical Navigable Small World graph for approximate nearest neighbor search. Pure Go, zero dependencies.
Based on: Malkov & Yashunin, "Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs" (2018).
Parameters tuned for coding memory workloads (1K-50K vectors, 384D):
- M = 16 (max connections per layer)
- efConstruct = 200 (construction beam width)
- efSearch = 100 (search beam width)
- mL = 1/ln(M) (level generation factor)
type HandoffSummary ¶
type HandoffSummary struct {
SessionID string `json:"session_id"`
Duration string `json:"duration"`
Accomplished []string `json:"accomplished"`
Decisions []string `json:"decisions"`
Conventions []string `json:"conventions"`
BugsFound []string `json:"bugs_found"`
InProgress []string `json:"in_progress"`
NextSteps []string `json:"next_steps"`
}
HandoffSummary is the structured output of session analysis.
type HealthCheck ¶
type HealthCheck struct {
Name string `json:"name"`
Status HealthStatus `json:"status"`
Message string `json:"message,omitempty"`
Latency time.Duration `json:"latency"`
}
HealthCheck is an individual health check result.
type HealthChecker ¶
type HealthChecker struct {
// contains filtered or unexported fields
}
HealthChecker runs diagnostic checks on the system.
func NewHealthChecker ¶
func NewHealthChecker(store storage.Storage) *HealthChecker
NewHealthChecker creates a health checker.
func (*HealthChecker) Check ¶
func (hc *HealthChecker) Check(ctx context.Context) *HealthReport
Check runs all health checks and returns a report.
type HealthReport ¶
type HealthReport struct {
Status HealthStatus `json:"status"`
Uptime time.Duration `json:"uptime"`
Checks []HealthCheck `json:"checks"`
NodeCount int `json:"node_count"`
EdgeCount int `json:"edge_count"`
DBSize int64 `json:"db_size_bytes"`
CacheHits int `json:"cache_hits"`
LastRecall time.Duration `json:"last_recall_latency"`
}
HealthReport provides detailed system health information.
type HealthStatus ¶
type HealthStatus string
HealthStatus represents the overall system health.
const ( HealthHealthy HealthStatus = "healthy" HealthDegraded HealthStatus = "degraded" HealthUnhealthy HealthStatus = "unhealthy" )
type HierarchicalMemory ¶
type HierarchicalMemory struct {
// contains filtered or unexported fields
}
HierarchicalMemory implements RAPTOR-style multi-level abstraction. Memories are organized in layers:
- Level 0: Individual memories (leaf nodes)
- Level 1: Topic clusters (grouped by entity overlap)
- Level 2: Domain summaries (architecture, testing, deployment, etc.)
Retrieval can target specific levels: detailed queries hit level 0, broad queries hit level 2, default hits all levels with RRF fusion.
func NewHierarchicalMemory ¶
func NewHierarchicalMemory(store storage.Storage) *HierarchicalMemory
NewHierarchicalMemory creates the hierarchy builder.
func (*HierarchicalMemory) Build ¶
func (hm *HierarchicalMemory) Build(ctx context.Context) error
Build constructs the hierarchy from current memory state. Call periodically (e.g., at session end) to keep hierarchy fresh.
func (*HierarchicalMemory) FormatLevel ¶
func (hm *HierarchicalMemory) FormatLevel(level int) string
FormatLevel returns a readable summary of a hierarchy level.
func (*HierarchicalMemory) RetrieveAdaptive ¶
func (hm *HierarchicalMemory) RetrieveAdaptive(query string) int
RetrieveAdaptive picks the right level based on query specificity. Specific queries (file names, function names) → Level 0 Topic queries ("auth", "testing") → Level 1 Global queries ("what are the main patterns?") → Level 2
func (*HierarchicalMemory) RetrieveAtLevel ¶
func (hm *HierarchicalMemory) RetrieveAtLevel(query string, level int) []MemoryCluster
RetrieveAtLevel searches within a specific abstraction level.
type HierarchyLevel ¶
type HierarchyLevel struct {
Level int
Clusters []MemoryCluster
}
HierarchyLevel represents one abstraction layer.
type HybridSearch ¶
type HybridSearch struct {
// contains filtered or unexported fields
}
HybridSearch performs 3-stage retrieval: BM25 → vector → graph expansion → RRF fusion.
func NewHybridSearch ¶
func NewHybridSearch(store storage.Storage, g graph.Graph, provider embeddings.Provider) *HybridSearch
NewHybridSearch creates a hybrid search engine.
func (*HybridSearch) Search ¶
func (h *HybridSearch) Search(ctx context.Context, query string, opts RecallOpts) ([]*ScoredNode, error)
Search runs hybrid search and returns ranked nodes. 4-path retrieval: BM25 + vector + graph (intent-aware) + temporal recency Based on Hindsight's multi-strategy approach.
type IngestResult ¶
type IngestResult struct {
Source string
Conventions int
Decisions int
Bugs int
Specs int
Tasks int
Preferences int
Files int
Total int
Skipped int
}
IngestResult tracks what was extracted from a source.
type Ingester ¶
type Ingester struct {
// contains filtered or unexported fields
}
Ingester handles bulk memory creation from various sources: conversations, markdown files, code files, CLAUDE.md, .cursorrules.
func NewIngester ¶
NewIngester creates an ingester bound to an engine.
func (*Ingester) DetectStack ¶
DetectStack scans package files and returns the detected tech stack.
func (*Ingester) IngestClaudeMD ¶
IngestClaudeMD imports from a CLAUDE.md file (conventions, rules, patterns).
func (*Ingester) IngestCodeFile ¶
IngestCodeFile extracts specs from source code (functions, types, package purpose).
func (*Ingester) IngestConversation ¶
IngestConversation parses a conversation transcript (alternating Human/Assistant) and extracts decisions, conventions, bugs mentioned.
func (*Ingester) IngestCursorRules ¶
IngestCursorRules imports from a .cursorrules file.
func (*Ingester) IngestDirectory ¶
IngestDirectory scans a project directory and ingests all relevant files.
func (*Ingester) IngestFile ¶
IngestFile parses a markdown file from disk.
func (*Ingester) IngestMarkdown ¶
func (ing *Ingester) IngestMarkdown(ctx context.Context, content, source string) (*IngestResult, error)
IngestMarkdown parses a markdown file and extracts memories from headers and lists.
type LLMExtractor ¶
type LLMExtractor struct {
// contains filtered or unexported fields
}
LLMExtractor uses an LLM to extract entities from content. Falls back to regex extraction if LLM is unavailable.
func NewLLMExtractor ¶
func NewLLMExtractor(apiKey, baseURL, model string) *LLMExtractor
NewLLMExtractor creates an LLM-based entity extractor. baseURL: "https://api.openai.com" or any OpenAI-compatible endpoint.
type LabileMemory ¶
type LearnResult ¶
type LearnResult struct {
Decisions int
Conventions int
Bugs int
Files int
Skipped int
Duration time.Duration
}
LearnResult reports what was extracted from git history.
type MemoryCluster ¶
type MemoryCluster struct {
ID string
Summary string
NodeIDs []string
Keywords []string
Size int
AvgConf float64
}
MemoryCluster is a group of related memories with a summary.
type MemoryExpiry ¶
type MemoryExpiry struct {
// contains filtered or unexported fields
}
MemoryExpiry handles automatic deletion of memories past their TTL.
func NewMemoryExpiry ¶
func NewMemoryExpiry(defaultTTL time.Duration) *MemoryExpiry
NewMemoryExpiry creates an expiry manager.
type MemoryIntegrity ¶
type MemoryIntegrity struct {
// contains filtered or unexported fields
}
MemoryIntegrity provides HMAC-SHA256 signing and verification for memory nodes. Detects if memories were tampered with outside yaad (e.g., direct SQLite edits). The signing key is stored in .yaad/integrity.key (auto-generated on first use).
func NewMemoryIntegrity ¶
func NewMemoryIntegrity(yaadDir string) (*MemoryIntegrity, error)
NewMemoryIntegrity creates an integrity checker, loading or generating the key.
func (*MemoryIntegrity) Sign ¶
func (mi *MemoryIntegrity) Sign(node *storage.Node) string
Sign generates an HMAC-SHA256 signature for a memory node's content.
func (*MemoryIntegrity) Verify ¶
func (mi *MemoryIntegrity) Verify(node *storage.Node, expectedSig string) bool
Verify checks if a node's content matches its expected signature.
func (*MemoryIntegrity) VerifyBatch ¶
func (mi *MemoryIntegrity) VerifyBatch(nodes []*storage.Node, signatures map[string]string) []string
VerifyBatch checks multiple nodes and returns IDs of tampered ones.
type MemoryStats ¶
type MemoryStats struct {
TotalNodes int
NodesByType map[string]int
TotalEdges int
LastUpdated time.Time
TopTopics []string // top 5 most-connected node subjects
}
MemoryStats holds aggregate statistics about the memory graph.
type MemorySuggestion ¶
type MemorySuggestion struct {
Content string `json:"content"`
Type string `json:"type"`
Confidence float64 `json:"confidence"`
Reason string `json:"reason"`
}
MemorySuggestion is a recommended memory to store.
type NodeHistoryEntry ¶
type NodeHistoryEntry struct {
Version int `json:"version"`
Content string `json:"content"`
ChangedBy string `json:"changed_by"`
Reason string `json:"reason"`
ChangedAt string `json:"changed_at"`
}
NodeHistoryEntry represents one version of a memory node.
type PackedContext ¶
PackedContext is the optimized output ready for prompt injection.
type PageRank ¶
type PageRank struct {
// contains filtered or unexported fields
}
PageRank computes importance scores for memory nodes based on graph structure. Nodes with more inbound links from important nodes score higher. Used to surface the most "central" memories in the graph.
Algorithm: iterative power method with damping factor 0.85. Converges in ~20 iterations for typical memory graphs (<10K nodes).
func NewPageRank ¶
NewPageRank creates a PageRank computer.
type ProactiveContext ¶
type ProactiveContext struct {
// contains filtered or unexported fields
}
ProactiveContext predicts what context the agent will likely need next by analyzing recent access patterns and graph connectivity.
func NewProactiveContext ¶
func NewProactiveContext(eng *Engine, search *HybridSearch) *ProactiveContext
NewProactiveContext creates a proactive context predictor.
func (*ProactiveContext) Predict ¶
func (p *ProactiveContext) Predict(ctx context.Context, project string, budget int) ([]*storage.Node, error)
Predict returns nodes likely needed in the next session based on: 1. Recently accessed nodes and their neighbors 2. Active tasks and their dependencies 3. High-centrality nodes in the project subgraph
type ProspectiveConfig ¶
type ProspectiveConfig struct {
Enabled bool `json:"enabled"`
TriggerThreshold float64 `json:"trigger_threshold"`
DefaultTTL time.Duration `json:"default_ttl"`
MaxActive int `json:"max_active"`
}
func DefaultProspectiveConfig ¶
func DefaultProspectiveConfig() ProspectiveConfig
type ProspectiveEngine ¶
type ProspectiveEngine struct {
// contains filtered or unexported fields
}
func NewProspectiveEngine ¶
func NewProspectiveEngine(config ProspectiveConfig) *ProspectiveEngine
func (*ProspectiveEngine) CheckTriggers ¶
func (e *ProspectiveEngine) CheckTriggers(messageText string, messageEmbedding []float32) []*ProspectiveMemory
func (*ProspectiveEngine) CleanExpired ¶
func (e *ProspectiveEngine) CleanExpired() int
func (*ProspectiveEngine) Create ¶
func (e *ProspectiveEngine) Create(triggerCondition, action, sourceSession string, triggerEmbedding []float32, priority float64) *ProspectiveMemory
func (*ProspectiveEngine) GetActive ¶
func (e *ProspectiveEngine) GetActive() []*ProspectiveMemory
type ProspectiveMemory ¶
type ProspectiveMemory struct {
ID string `json:"id"`
TriggerCondition string `json:"trigger_condition"`
TriggerEmbedding []float32 `json:"trigger_embedding,omitempty"`
Action string `json:"action"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
TriggeredAt *time.Time `json:"triggered_at,omitempty"`
SourceSession string `json:"source_session,omitempty"`
Priority float64 `json:"priority"`
}
type QueryCache ¶
type QueryCache struct {
// contains filtered or unexported fields
}
QueryCache is an LRU cache for recall results. Eliminates redundant SQLite queries for frequently-asked questions within a session. Auto-invalidates on writes (Remember, Forget, Feedback).
func NewQueryCache ¶
func NewQueryCache(maxSize int, ttl time.Duration) *QueryCache
NewQueryCache creates a cache with configurable size and TTL.
func (*QueryCache) Get ¶
func (c *QueryCache) Get(key string) *RecallResult
Get retrieves a cached result. Returns nil if miss or stale.
func (*QueryCache) Invalidate ¶
func (c *QueryCache) Invalidate()
Invalidate bumps the version, making all cached entries stale. Called after any write operation (Remember, Forget, Feedback, etc).
func (*QueryCache) Put ¶
func (c *QueryCache) Put(key string, result *RecallResult)
Put stores a result in the cache.
func (*QueryCache) Stats ¶
func (c *QueryCache) Stats() (size int, version uint64)
Stats returns cache hit/miss info.
type QueryMetrics ¶
type QueryMetrics struct {
Query string
Duration time.Duration
ResultCount int
SignalsUsed []string
WasUseful bool
}
QueryMetrics tracks retrieval performance for auto-tuning.
type QueryPlan ¶
type QueryPlan struct {
UseBM25 bool
UseVector bool
UseGraph bool
UseRecency bool
UseEntity bool
GraphDepth int
BM25Limit int
Intent intent.Intent
TemporalOnly bool
}
QueryPlan describes which retrieval signals to use.
type QueryPlanner ¶
type QueryPlanner struct {
// contains filtered or unexported fields
}
QueryPlanner implements intelligent query routing based on Qdrant's cardinality estimation and Cognee's auto-routing approach. Instead of always running all 5 retrieval signals, it selects the optimal subset based on query characteristics.
Techniques from:
- Qdrant: Cardinality-based path selection
- Cognee: Intent-aware routing to specialized retrievers
- Mem0: Query-adaptive parameters
func NewQueryPlanner ¶
func NewQueryPlanner(nodeCount int, hasVectors, hasGraph bool) *QueryPlanner
NewQueryPlanner creates a planner with context about the index.
func (*QueryPlanner) EstimateCardinality ¶
func (qp *QueryPlanner) EstimateCardinality(query string) float64
EstimateCardinality estimates how many results a query will return. Used to decide if expensive signals (vector, graph) are worth running. Based on Qdrant's Agresti-Coull sampling approach (simplified).
func (*QueryPlanner) Plan ¶
func (qp *QueryPlanner) Plan(query string, opts RecallOpts) QueryPlan
Plan analyzes a query and decides the optimal retrieval strategy.
type QueryResult ¶
type QueryResult struct {
Answer string // synthesized answer from retrieved memories
Sources []*storage.Node // the memories used to form the answer
Confidence float64 // 0-1, based on relevance scores of retrieved nodes
}
QueryResult holds the answer to a natural language query.
type Quiz ¶
type Quiz struct {
// contains filtered or unexported fields
}
Quiz tests how well an agent (or developer) remembers project knowledge. Generates questions from stored memories and checks answers. Useful for validating that the memory system is capturing the right things.
func (*Quiz) CheckAnswer ¶
func (q *Quiz) CheckAnswer(question QuizQuestion, answer string) bool
CheckAnswer verifies if a given answer matches the stored memory.
type QuizQuestion ¶
type QuizQuestion struct {
Question string `json:"question"`
Answer string `json:"answer"`
Type string `json:"type"`
NodeID string `json:"node_id"`
}
QuizQuestion is a generated question with its expected answer.
type QuizResult ¶
type QuizResult struct {
Total int `json:"total"`
Correct int `json:"correct"`
Score float64 `json:"score"` // 0-100
}
QuizResult tracks how well the quiz was answered.
type RankedNode ¶
RankedNode pairs a node with its PageRank score.
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter implements a token bucket rate limiter for the REST API. Prevents abuse and ensures fair usage for solo developers running multiple agents simultaneously.
func NewRateLimiter ¶
func NewRateLimiter(ratePerSec float64, maxBurst int) *RateLimiter
NewRateLimiter creates a limiter with given rate (req/sec) and burst capacity.
func (*RateLimiter) Allow ¶
func (rl *RateLimiter) Allow() bool
Allow checks if a request is allowed. Returns true if within limits.
func (*RateLimiter) Remaining ¶
func (rl *RateLimiter) Remaining() int
Remaining returns how many requests are available right now.
type RecallOpts ¶
type RecallOpts struct {
Query string
Depth int
Limit int
Budget int // max tokens in response (0 = no cap)
Type string
Tier int
Project string
}
RecallOpts configures a recall search.
type RecallResult ¶
RecallResult holds search results.
type ReconsolidationConfig ¶
type ReconsolidationConfig struct {
Enabled bool `json:"enabled"`
LabileWindow time.Duration `json:"labile_window"`
StrengthBonus float64 `json:"strength_bonus"`
}
func DefaultReconsolidationConfig ¶
func DefaultReconsolidationConfig() ReconsolidationConfig
type ReconsolidationEngine ¶
type ReconsolidationEngine struct {
// contains filtered or unexported fields
}
func NewReconsolidationEngine ¶
func NewReconsolidationEngine(config ReconsolidationConfig) *ReconsolidationEngine
func (*ReconsolidationEngine) Cleanup ¶
func (e *ReconsolidationEngine) Cleanup() int
func (*ReconsolidationEngine) FlagContradiction ¶
func (e *ReconsolidationEngine) FlagContradiction(chunkID string)
func (*ReconsolidationEngine) GetContradicted ¶
func (e *ReconsolidationEngine) GetContradicted() []string
func (*ReconsolidationEngine) IsLabile ¶
func (e *ReconsolidationEngine) IsLabile(chunkID string) bool
func (*ReconsolidationEngine) OnRecall ¶
func (e *ReconsolidationEngine) OnRecall(chunkID string)
func (*ReconsolidationEngine) Strengthen ¶
func (e *ReconsolidationEngine) Strengthen(chunkID string) float64
type RememberInput ¶
type RememberInput struct {
Type string // convention|decision|bug|spec|task|preference
Content string
Summary string // doubles as short searchable title (Engram Title)
Scope string // global|project
Project string
Tier int
Tags string
Key string // optional unique key per project (upsert: same key → update, not duplicate)
TopicKey string // topic-based upsert dedup key (Engram pattern); stored in Tags as "topic:<key>"
Pinned bool // pinned nodes always appear in context output
Session string
Agent string
// Optional: explicit edges to create
Edges []EdgeInput
}
RememberInput is the input for creating a memory node.
type ScoredNode ¶
ScoredNode is a node with a combined relevance score.
func Rerank ¶
func Rerank(ctx context.Context, nodes []*ScoredNode, store storage.Storage) []*ScoredNode
Rerank re-scores nodes combining RRF score, graph centrality, recency, and confidence.
type ScoringConfig ¶
type ScoringConfig struct {
BM25Weight float64 // weight for BM25 signal in fusion (default 0.4)
VectorWeight float64 // weight for vector signal (default 0.3)
GraphWeight float64 // weight for graph signal (default 0.2)
RecencyWeight float64 // weight for recency signal (default 0.1)
EntityBoostCap float64 // max entity boost multiplier (default 2.0)
MMRLambda float64 // diversity vs relevance tradeoff (default 0.7)
SpreadDecay float64 // entity spread attenuation factor (default 0.001)
}
ScoringConfig holds tunable parameters for retrieval scoring.
func DefaultScoringConfig ¶
func DefaultScoringConfig() ScoringConfig
DefaultScoringConfig returns production-tuned scoring parameters.
type SessionHandoff ¶
type SessionHandoff struct {
// contains filtered or unexported fields
}
SessionHandoff implements MemGPT-style automatic session summary generation. At session end, it produces a concise handoff summary that captures:
- What was accomplished
- Decisions made
- Conventions established
- Bugs found/fixed
- What's in progress
The next session gets this injected automatically so the agent picks up exactly where it left off.
func NewSessionHandoff ¶
func NewSessionHandoff(store storage.Storage) *SessionHandoff
NewSessionHandoff creates a handoff generator.
func (*SessionHandoff) FormatForInjection ¶
func (sh *SessionHandoff) FormatForInjection(summary *HandoffSummary) string
FormatForInjection converts the handoff into a markdown string for prompt injection.
func (*SessionHandoff) Generate ¶
func (sh *SessionHandoff) Generate(ctx context.Context, sessionID string, duration time.Duration) (*HandoffSummary, error)
Generate produces a handoff summary from memories created during a session.
func (*SessionHandoff) GetLastSessionSummary ¶
func (sh *SessionHandoff) GetLastSessionSummary(ctx context.Context, project string) string
GetLastSessionSummary retrieves and formats the previous session's handoff.
type SomaticConfig ¶
type SomaticConfig struct {
Enabled bool `json:"enabled"`
SkipThreshold float64 `json:"skip_threshold"`
BoostThreshold float64 `json:"boost_threshold"`
}
func DefaultSomaticConfig ¶
func DefaultSomaticConfig() SomaticConfig
type SomaticEngine ¶
type SomaticEngine struct {
// contains filtered or unexported fields
}
func NewSomaticEngine ¶
func NewSomaticEngine(config SomaticConfig) *SomaticEngine
func (*SomaticEngine) GetMarker ¶
func (e *SomaticEngine) GetMarker(region string) *SomaticMarker
func (*SomaticEngine) RecordOutcome ¶
func (e *SomaticEngine) RecordOutcome(region string, success bool)
func (*SomaticEngine) ShouldBoost ¶
func (e *SomaticEngine) ShouldBoost(region string) bool
func (*SomaticEngine) ShouldSkip ¶
func (e *SomaticEngine) ShouldSkip(region string) bool
type SomaticMarker ¶
type SpacingConfig ¶
type SpacingConfig struct {
OptimalInterval time.Duration `json:"optimal_interval"`
MaxBonus float64 `json:"max_bonus"`
CrammingPenalty float64 `json:"cramming_penalty"`
}
func DefaultSpacingConfig ¶
func DefaultSpacingConfig() SpacingConfig
type Sparsifier ¶
type Sparsifier struct {
// contains filtered or unexported fields
}
Sparsifier implements Memory³-style memory sparsification. As the graph grows, it:
- Merges near-duplicate memories (same entities, similar content)
- Compresses low-value clusters into single summary nodes
- Prunes truly orphaned nodes with no edges and low confidence
This keeps the memory graph lean and fast as it scales.
func NewSparsifier ¶
func NewSparsifier(store storage.Storage) *Sparsifier
NewSparsifier creates a memory sparsification engine.
func (*Sparsifier) Run ¶
func (s *Sparsifier) Run(ctx context.Context) (*SparsifyResult, error)
Run executes all sparsification passes. Safe to call periodically (e.g., weekly).
type SparsifyResult ¶
SparsifyResult reports what was cleaned up.
type SuggestedEdge ¶
type SuggestedEdge struct {
FromID string `json:"from_id"`
FromType string `json:"from_type"`
ToID string `json:"to_id"`
ToType string `json:"to_type"`
EdgeType string `json:"edge_type"`
Reason string `json:"reason"`
}
SuggestedEdge is a recommended edge to create.
func SuggestLinks ¶
SuggestLinks finds orphan nodes and suggests edges to connect them.
type SummarizedMemory ¶
SummarizedMemory is a compressed memory extracted from conversation.
type TemplateMemory ¶
TemplateMemory is a pre-built memory.
type TemplateSet ¶
type TemplateSet struct {
Name string
Stack string
Memories []TemplateMemory
}
TemplateSet is a collection of starter memories for a stack.
type Templates ¶
type Templates struct{}
Templates provides pre-built memory sets for common tech stacks.
func (*Templates) Available ¶
func (t *Templates) Available() []TemplateSet
Available returns all available templates.
type TemporalEdge ¶
type TemporalEdge struct {
SourceID string `json:"source_id"`
TargetID string `json:"target_id"`
RelationType string `json:"relation_type"`
ValidFrom *time.Time `json:"valid_from,omitempty"`
ValidUntil *time.Time `json:"valid_until,omitempty"`
Confidence float64 `json:"confidence"`
Evidence string `json:"evidence,omitempty"`
}
func FilterActiveEdges ¶
func FilterActiveEdges(edges []*TemporalEdge, at time.Time) []*TemporalEdge
func FilterCurrentEdges ¶
func FilterCurrentEdges(edges []*TemporalEdge) []*TemporalEdge
func (*TemporalEdge) IsActiveAt ¶
func (e *TemporalEdge) IsActiveAt(t time.Time) bool
func (*TemporalEdge) IsCurrentlyActive ¶
func (e *TemporalEdge) IsCurrentlyActive() bool
type TemporalFilter ¶
type TemporalFilter struct {
// contains filtered or unexported fields
}
TemporalFilter enables time-bounded memory retrieval. Based on Zep's valid_at/invalid_at interval model layered on top of yaad's temporal backbone.
Supports queries like:
- "What was true at time X?" (point-in-time)
- "What changed between X and Y?" (range)
- "What's currently valid?" (active only)
func NewTemporalFilter ¶
func NewTemporalFilter(store storage.Storage) *TemporalFilter
NewTemporalFilter creates a temporal filter.
func (*TemporalFilter) ActiveEdges ¶
ActiveEdges returns only currently-valid edges (invalid_at is zero).
func (*TemporalFilter) ChangedBetween ¶
func (tf *TemporalFilter) ChangedBetween(ctx context.Context, start, end time.Time, limit int) ([]*storage.Node, error)
ChangedBetween returns nodes that were created or modified in a time range.
func (*TemporalFilter) FilterByTime ¶
func (tf *TemporalFilter) FilterByTime(ctx context.Context, nodes []*storage.Node, query TemporalQuery) []*storage.Node
FilterByTime returns nodes that match the temporal constraints.
func (*TemporalFilter) IsSuperseded ¶
IsSuperseded checks if a node has been superseded by another via edge.
type TemporalQuery ¶
type TemporalQuery struct {
After time.Time // only nodes created/updated after this time
Before time.Time // only nodes created/updated before this time
ActiveOnly bool // only nodes not superseded (no invalid_at on edges)
}
TemporalQuery specifies time constraints for retrieval.
type UserProfile ¶
type UserProfile struct {
Preferences map[string]string // e.g., "indent": "tabs", "test_framework": "testify"
Patterns []string // observed patterns: "always runs tests after edit"
UpdatedAt time.Time
}
UserProfile holds user preferences and observed patterns for a project.
type ZeigarnikChunk ¶
type ZeigarnikConfig ¶
type ZeigarnikConfig struct {
Enabled bool `json:"enabled"`
DecayResistance float64 `json:"decay_resistance"`
MinTextLength int `json:"min_text_length"`
}
func DefaultZeigarnikConfig ¶
func DefaultZeigarnikConfig() ZeigarnikConfig
type ZeigarnikEngine ¶
type ZeigarnikEngine struct {
// contains filtered or unexported fields
}
func NewZeigarnikEngine ¶
func NewZeigarnikEngine(config ZeigarnikConfig) *ZeigarnikEngine
func (*ZeigarnikEngine) CloseLoop ¶
func (e *ZeigarnikEngine) CloseLoop(chunkID string)
func (*ZeigarnikEngine) DecayMultiplier ¶
func (e *ZeigarnikEngine) DecayMultiplier(chunkID string) float64
func (*ZeigarnikEngine) GetActiveLoops ¶
func (e *ZeigarnikEngine) GetActiveLoops(limit int) []*OpenLoop
func (*ZeigarnikEngine) MarkOpenLoop ¶
func (e *ZeigarnikEngine) MarkOpenLoop(chunkID, context string)
func (*ZeigarnikEngine) ScanChunks ¶
func (e *ZeigarnikEngine) ScanChunks(chunks []ZeigarnikChunk) int
Source Files
¶
- access_tracker.go
- audit.go
- bloom.go
- branch.go
- budget.go
- cache.go
- community.go
- context_pack.go
- curiosity.go
- decay.go
- entities.go
- entity_boost.go
- epistemic.go
- export_html.go
- feedback.go
- feedback_signal.go
- fused_recall.go
- git_learn.go
- health.go
- hierarchy.go
- hnsw.go
- ingest.go
- integrity.go
- llm_entities.go
- memory.go
- pagerank.go
- proactive.go
- profile.go
- prospective.go
- query.go
- query_expand.go
- query_planner.go
- quiz.go
- ratelimit.go
- reconsolidation.go
- rerank.go
- scoring.go
- search.go
- selflink.go
- session.go
- session_handoff.go
- somatic.go
- spacing.go
- sparsify.go
- stats.go
- temporal_filter.go
- temporal_validity.go
- zeigarnik.go