engine

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: May 16, 2026 License: MIT Imports: 39 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultDecayConfig = DecayConfig{
	HalfLifeDays:  30,
	MinConfidence: 0.1,
	BoostOnAccess: 0.2,
}

Functions

func BoostNode

func BoostNode(ctx context.Context, store storage.Storage, id string, boost float64) error

BoostNode increases confidence of a node on access (capped at 1.0).

func CacheKey

func CacheKey(opts RecallOpts) string

CacheKey builds a cache key from recall options.

func DetectOpenLoop

func DetectOpenLoop(text string, minLen int) string

func DetectResolution

func DetectResolution(text string) bool

func ExpandQuery

func ExpandQuery(query string) string

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

func ExportHTML(ctx context.Context, store storage.Storage) (string, error)

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

func FormatContext(nodes []*storage.Node) string

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

func FuzzyMatch(query, content string) bool

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

func GarbageCollect(ctx context.Context, store storage.Storage, cfg DecayConfig) (int, error)

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

func IsValidNodeType(typ string) bool

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

func NormalizeBM25(rawScore float64, queryTermCount int) float64

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

func QueryTermCount(query string) int

QueryTermCount counts significant terms in a query (for BM25 normalization).

func RunDecay

func RunDecay(ctx context.Context, store storage.Storage, cfg DecayConfig) error

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

func SpreadAttenuatedBoost(similarity float64, numLinked int, decay float64) float64

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

func StartupSelfTest(ctx context.Context, store storage.Storage) error

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.

func TrimToTokenBudget

func TrimToTokenBudget(nodes []*storage.Node, budget int) []*storage.Node

TrimToTokenBudget trims a node list to fit within a token budget. Approximation: 1 token ≈ 4 characters.

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

func NewAuditLog(yaadDir string) (*AuditLog, error)

NewAuditLog creates or opens the audit log file.

func (*AuditLog) Close

func (al *AuditLog) Close()

Close flushes and closes the audit log.

func (*AuditLog) Count

func (al *AuditLog) Count() int

Count returns number of entries logged this session.

func (*AuditLog) Log

func (al *AuditLog) Log(op, nodeID, nodeType, agent, details string)

Log records an operation.

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

func (cd *CommunityDetector) Detect(ctx context.Context, maxIter int) ([]Community, error)

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.

func (*CommunityDetector) Summarize

func (cd *CommunityDetector) Summarize(ctx context.Context, communities []Community) []Community

Summarize generates a summary for each community based on its node contents.

type ConflictCandidate

type ConflictCandidate struct {
	NodeID  string
	Content string
	Score   float64
}

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

type CuriosityConfig struct {
	Enabled    bool `json:"enabled"`
	MaxTargets int  `json:"max_targets"`
}

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 EdgeInput

type EdgeInput struct {
	ToID string
	Type string
}

EdgeInput describes an edge to create alongside a node.

type Engine

type Engine struct {
	DecayConfig DecayConfig
	// contains filtered or unexported fields
}

Engine is the core memory engine wrapping graph + storage.

func New

func New(store storage.Storage, g graph.Graph) *Engine

New creates a memory engine.

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

func (e *Engine) CachedRecall(nodes []*storage.Node)

CachedRecall wraps FusedRecall with caching.

func (*Engine) Close

func (e *Engine) Close()

Close shuts down the engine and its background workers.

func (*Engine) Compact

func (e *Engine) Compact(ctx context.Context, project string) (int, error)

Compact merges low-confidence memories to keep the graph lean.

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

func (e *Engine) Context(ctx context.Context, project string) (*RecallResult, error)

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) Forget

func (e *Engine) Forget(ctx context.Context, id string) error

Forget archives a node by setting confidence to 0.

func (*Engine) FusedRecall

func (e *Engine) FusedRecall(ctx context.Context, opts RecallOpts) (*RecallResult, error)

FusedRecall performs multi-signal retrieval combining:

  1. BM25 keyword search (via existing SearchNodes FTS5)
  2. Graph traversal (via existing IntentBFS from seed nodes)
  3. 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

func (e *Engine) GetMetrics() Metrics

GetMetrics returns a copy of the engine's operational metrics.

func (*Engine) GetNodeHistory

func (e *Engine) GetNodeHistory(ctx context.Context, nodeID string) ([]NodeHistoryEntry, error)

GetNodeHistory returns the version history of a memory node.

func (*Engine) GetUserProfile

func (e *Engine) GetUserProfile(ctx context.Context, project string) (*UserProfile, error)

GetUserProfile returns the user profile for a project, built from preference nodes.

func (*Engine) Graph

func (e *Engine) Graph() graph.Graph

Graph returns the underlying graph engine.

func (*Engine) Integrity

func (e *Engine) Integrity() *MemoryIntegrity

Integrity returns the engine's memory integrity checker (may be nil).

func (*Engine) MentalModel

func (e *Engine) MentalModel(ctx context.Context, project string) (*mental.Model, error)

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

func (e *Engine) Profile(ctx context.Context, project string) (*profile.Profile, error)

Profile returns an auto-maintained user/project profile (static facts + dynamic context).

func (*Engine) Query

func (e *Engine) Query(ctx context.Context, question string, project string) (*QueryResult, error)

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:

  1. Parse the question — classify intent using the existing intent package
  2. Retrieve — call FusedRecall with the question as the query
  3. Rank and filter — keep only nodes with confidence > 0.3
  4. Synthesize — format retrieved memories into a coherent answer using intent-specific templates
  5. 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

func (e *Engine) Remember(ctx context.Context, in RememberInput) (*storage.Node, error)

Remember creates a memory node with privacy filtering, dedup, and entity extraction.

func (*Engine) Rollback

func (e *Engine) Rollback(ctx context.Context, id string, version int) error

Rollback restores a node to a previous version.

func (e *Engine) SelfLink(ctx context.Context, node *storage.Node)

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

func (e *Engine) StartSession(ctx context.Context, project, agent string) (string, error)

StartSession creates a new session record and returns its ID.

func (*Engine) Status

func (e *Engine) Status(ctx context.Context, project string) (*Status, error)

func (*Engine) Store

func (e *Engine) Store() storage.Storage

Store returns the underlying store.

func (*Engine) UpdateUserPreference

func (e *Engine) UpdateUserPreference(ctx context.Context, project, key, value string) error

UpdateUserPreference stores or updates a single preference as a yaad node.

func (*Engine) VectorSearch

func (e *Engine) VectorSearch(query []float32, k int) []string

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

type Entity struct {
	Name string
	Type string // "file" or "entity"
}

Entity represents an auto-extracted entity from content.

func ExtractEntities

func ExtractEntities(content string) []Entity

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 NewEntityIndex

func NewEntityIndex() *EntityIndex

NewEntityIndex creates a new entity index.

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

func (ei *EntityIndex) LoadFromStore(ctx context.Context, store storage.Storage) error

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 ExplorationTarget struct {
	ID         string     `json:"id"`
	Topic      string     `json:"topic"`
	GapType    string     `json:"gap_type"`
	Priority   float64    `json:"priority"`
	CreatedAt  time.Time  `json:"created_at"`
	ExploredAt *time.Time `json:"explored_at,omitempty"`
	Findings   string     `json:"findings,omitempty"`
}

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.

func DiffSince

func DiffSince(ctx context.Context, store storage.Storage, sinceVersion int) (*GraphDiff, error)

DiffSince returns nodes added or modified since the given node count snapshot.

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)

func NewHNSW

func NewHNSW(dim int) *HNSW

NewHNSW creates an HNSW index with default parameters for coding memory.

func (*HNSW) Contains

func (h *HNSW) Contains(id string) bool

Contains checks if an ID is in the index.

func (*HNSW) Insert

func (h *HNSW) Insert(id string, vector []float32)

Insert adds a vector to the index.

func (*HNSW) Remove

func (h *HNSW) Remove(id string)

Remove marks a node as deleted (logical delete, doesn't restructure).

func (*HNSW) Search

func (h *HNSW) Search(query []float32, k int) ([]string, []float32)

Search finds the k nearest neighbors to the query vector. Returns (nodeIDs, distances) sorted by distance ascending.

func (*HNSW) Size

func (h *HNSW) Size() int

Size returns the number of vectors in the index.

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

func NewIngester(engine *Engine) *Ingester

NewIngester creates an ingester bound to an engine.

func (*Ingester) DetectStack

func (ing *Ingester) DetectStack(ctx context.Context, projectDir string) (*IngestResult, error)

DetectStack scans package files and returns the detected tech stack.

func (*Ingester) IngestClaudeMD

func (ing *Ingester) IngestClaudeMD(ctx context.Context, path string) (*IngestResult, error)

IngestClaudeMD imports from a CLAUDE.md file (conventions, rules, patterns).

func (*Ingester) IngestCodeFile

func (ing *Ingester) IngestCodeFile(ctx context.Context, path string) (*IngestResult, error)

IngestCodeFile extracts specs from source code (functions, types, package purpose).

func (*Ingester) IngestConversation

func (ing *Ingester) IngestConversation(ctx context.Context, text string) (*IngestResult, error)

IngestConversation parses a conversation transcript (alternating Human/Assistant) and extracts decisions, conventions, bugs mentioned.

func (*Ingester) IngestCursorRules

func (ing *Ingester) IngestCursorRules(ctx context.Context, path string) (*IngestResult, error)

IngestCursorRules imports from a .cursorrules file.

func (*Ingester) IngestDirectory

func (ing *Ingester) IngestDirectory(ctx context.Context, dir string) (*IngestResult, error)

IngestDirectory scans a project directory and ingests all relevant files.

func (*Ingester) IngestFile

func (ing *Ingester) IngestFile(ctx context.Context, path string) (*IngestResult, error)

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.

func (*LLMExtractor) Extract

func (e *LLMExtractor) Extract(ctx context.Context, content string) []Entity

Extract returns entities from content using the LLM. Returns regex-extracted entities if LLM call fails.

type LabileMemory

type LabileMemory struct {
	ChunkID      string    `json:"chunk_id"`
	RecalledAt   time.Time `json:"recalled_at"`
	Strengthened bool      `json:"strengthened"`
	Contradicted bool      `json:"contradicted"`
}

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.

func (*MemoryExpiry) IsExpired

func (me *MemoryExpiry) IsExpired(createdAt time.Time, pinned bool) bool

IsExpired checks if a node has exceeded its TTL.

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 Metrics

type Metrics struct {
	Remembers   int64
	Recalls     int64
	Errors      int64
	NodesStored int64
}

Metrics tracks basic engine operation counters.

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 OpenLoop

type OpenLoop struct {
	ChunkID    string    `json:"chunk_id"`
	Context    string    `json:"context"`
	DetectedAt time.Time `json:"detected_at"`
	Resolved   bool      `json:"resolved"`
}

type PackedContext

type PackedContext struct {
	Content    string
	TokensUsed int
	NodesUsed  int
	TypeCounts map[string]int
}

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

func NewPageRank(store storage.Storage) *PageRank

NewPageRank creates a PageRank computer.

func (*PageRank) Compute

func (pr *PageRank) Compute(ctx context.Context, limit int) ([]RankedNode, error)

Compute runs PageRank and returns nodes sorted by importance.

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) Clear

func (c *QueryCache) Clear()

Clear empties the cache entirely.

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 NewQuiz

func NewQuiz(store storage.Storage) *Quiz

NewQuiz creates a quiz generator.

func (*Quiz) CheckAnswer

func (q *Quiz) CheckAnswer(question QuizQuestion, answer string) bool

CheckAnswer verifies if a given answer matches the stored memory.

func (*Quiz) Generate

func (q *Quiz) Generate(ctx context.Context, count int) ([]QuizQuestion, error)

Generate creates quiz questions from stored memories.

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

type RankedNode struct {
	Node  *storage.Node
	Score float64
}

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

type RecallResult struct {
	Nodes []*storage.Node
	Edges []*storage.Edge
}

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

type ScoredNode struct {
	Node  *storage.Node
	Score float64
}

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 SomaticMarker struct {
	Region     string  `json:"region"`
	Valence    float64 `json:"valence"`
	Arousal    float64 `json:"arousal"`
	Confidence float64 `json:"confidence"`
	Accesses   int     `json:"accesses"`
}

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:

  1. Merges near-duplicate memories (same entities, similar content)
  2. Compresses low-value clusters into single summary nodes
  3. 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

type SparsifyResult struct {
	Merged     int
	Compressed int
	Pruned     int
}

SparsifyResult reports what was cleaned up.

type Status

type Status struct {
	Nodes    int
	Edges    int
	Sessions int
}

Status returns basic stats.

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(ctx context.Context, store storage.Storage) ([]SuggestedEdge, error)

SuggestLinks finds orphan nodes and suggests edges to connect them.

type SummarizedMemory

type SummarizedMemory struct {
	Content string
	Type    string
}

SummarizedMemory is a compressed memory extracted from conversation.

type TemplateMemory

type TemplateMemory struct {
	Content string
	Type    string
}

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) Apply

func (t *Templates) Apply(ctx context.Context, eng *Engine, templateName string) (int, error)

Apply stores a template's memories into the engine.

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

func (tf *TemporalFilter) ActiveEdges(ctx context.Context, nodeID string) ([]*storage.Edge, error)

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

func (tf *TemporalFilter) IsSuperseded(ctx context.Context, nodeID string) (bool, string)

IsSuperseded checks if a node has been superseded by another via edge.

func (*TemporalFilter) RecentSince

func (tf *TemporalFilter) RecentSince(ctx context.Context, since time.Time, limit int) ([]*storage.Node, error)

RecentSince returns nodes created or updated since the given time.

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 ZeigarnikChunk struct {
	ID   string
	Text string
}

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

Jump to

Keyboard shortcuts

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