memory

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 12, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExtractConventions

func ExtractConventions(text string) []string

ExtractConventions scans text for convention-like statements.

func Save

func Save(m *Memory) error

Save persists a memory.

Types

type ActivityTracker

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

ActivityTracker monitors memory save activity and nudges the agent to persist learnings when saves have been idle for too long.

func NewActivityTracker

func NewActivityTracker(nudgeAfter time.Duration) *ActivityTracker

NewActivityTracker creates a tracker that nudges after the given duration of inactivity.

func (*ActivityTracker) NudgeMessage

func (a *ActivityTracker) NudgeMessage() string

NudgeMessage returns a nudge string if the agent hasn't saved memories recently, or "" if no nudge is needed.

func (*ActivityTracker) RecordSave

func (a *ActivityTracker) RecordSave()

RecordSave records that a memory save just occurred.

type AutoCapture

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

AutoCapture extracts memorable content from tool results without explicit agent calls. It analyzes tool outputs and automatically stores conventions, decisions, bugs, and file-level knowledge into yaad's graph.

func NewAutoCapture

func NewAutoCapture(bridge *YaadBridge) *AutoCapture

NewAutoCapture creates an auto-capture processor that consumes tool results in the background and stores extracted memories.

func (*AutoCapture) ExtractFromAssistantResponse

func (ac *AutoCapture) ExtractFromAssistantResponse(ctx context.Context, text string)

ExtractFromAssistantResponse analyzes assistant text for memorable content and stores it via the bridge. Called from the agent loop when the LLM produces text that contains implicit conventions or decisions.

func (*AutoCapture) Ingest

func (ac *AutoCapture) Ingest(toolName string, args map[string]interface{}, output string, isErr bool)

Ingest queues a tool result for background memory extraction.

func (*AutoCapture) Metrics

func (ac *AutoCapture) Metrics() CaptureMetrics

Metrics returns capture statistics.

func (*AutoCapture) Stop

func (ac *AutoCapture) Stop()

Stop halts background processing.

type AutoDreamConfig

type AutoDreamConfig struct {
	Enabled           bool
	MinElapsedTime    time.Duration // minimum time since last dream
	MinNewSessions    int           // minimum new sessions since last dream
	ConsolidatePrompt string        // prompt for the dream agent
}

AutoDreamConfig controls when background memory consolidation triggers.

func DefaultAutoDreamConfig

func DefaultAutoDreamConfig() AutoDreamConfig

DefaultAutoDreamConfig returns the default auto-dream settings.

type AutoDreamState

type AutoDreamState struct {
	LastDreamTime time.Time `json:"last_dream_time"`
	SessionsSince int       `json:"sessions_since"`
	DreamCount    int       `json:"dream_count"`
	LastError     string    `json:"last_error,omitempty"`
	// contains filtered or unexported fields
}

AutoDreamState tracks the last dream execution.

func NewAutoDreamState

func NewAutoDreamState() *AutoDreamState

NewAutoDreamState creates a new auto-dream state.

func (*AutoDreamState) MarkDreamComplete

func (s *AutoDreamState) MarkDreamComplete()

MarkDreamComplete records a successful dream execution.

func (*AutoDreamState) MarkDreamFailed

func (s *AutoDreamState) MarkDreamFailed(err error)

MarkDreamFailed records a failed dream attempt.

func (*AutoDreamState) RecordSession

func (s *AutoDreamState) RecordSession()

RecordSession increments the session counter.

func (*AutoDreamState) ShouldDream

func (s *AutoDreamState) ShouldDream(cfg AutoDreamConfig) bool

ShouldDream checks if conditions are met for a background dream.

type AutoMemory

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

AutoMemory manages automatic memory extraction and storage for a project.

func NewAutoMemory

func NewAutoMemory(projectDir string) *AutoMemory

NewAutoMemory creates a new AutoMemory rooted at ~/.hawk/projects/<hash>/memory/.

func (*AutoMemory) Format

func (am *AutoMemory) Format() string

Format returns memory content formatted for prompt injection.

func (*AutoMemory) LoadStartup

func (am *AutoMemory) LoadStartup() string

LoadStartup reads the first 200 lines (max 25KB) of MEMORY.md from the memory directory.

func (*AutoMemory) Search

func (am *AutoMemory) Search(query string) []string

Search greps across all .md files in the memory directory for lines matching query.

func (*AutoMemory) ShouldRemember

func (am *AutoMemory) ShouldRemember(content string) bool

ShouldRemember returns true if content contains trigger words indicating the user is correcting, emphasizing, or asking the assistant to remember something.

func (*AutoMemory) Write

func (am *AutoMemory) Write(topic, content string) error

Write appends content to a topic-specific markdown file in the memory directory.

type CaptureMetrics

type CaptureMetrics struct {
	Captured       int
	Skipped        int
	ConventionsOut int
	DecisionsOut   int
	BugsOut        int
	FilesOut       int
	// contains filtered or unexported fields
}

CaptureMetrics tracks auto-capture statistics.

type CodeMemoryLinker

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

CodeMemoryLinker creates bidirectional links between indexed code chunks and memory graph nodes. When code is indexed, it auto-links to memories that reference that file. Enables "show all memories about this function."

func NewCodeMemoryLinker

func NewCodeMemoryLinker(bridge *YaadBridge) *CodeMemoryLinker

NewCodeMemoryLinker creates a linker that bridges code index and memory graph.

func (*CodeMemoryLinker) InvalidateCache

func (cl *CodeMemoryLinker) InvalidateCache(path string)

InvalidateCache removes cached links for a file (call after file is deleted/moved).

func (*CodeMemoryLinker) LinkFileToMemories

func (cl *CodeMemoryLinker) LinkFileToMemories(path string) error

LinkFileToMemories finds all memory nodes that reference a file path and creates 'touches' edges between them and a file anchor node.

func (*CodeMemoryLinker) MemoriesForFile

func (cl *CodeMemoryLinker) MemoriesForFile(path string) ([]string, error)

MemoriesForFile returns all memory nodes linked to a specific file.

func (*CodeMemoryLinker) MemoriesForSymbol

func (cl *CodeMemoryLinker) MemoriesForSymbol(symbol string) ([]string, error)

MemoriesForSymbol returns memories related to a code symbol (function, class, etc).

func (*CodeMemoryLinker) OnFileChanged

func (cl *CodeMemoryLinker) OnFileChanged(path string) []string

OnFileChanged is called when a file is modified. It checks what memories are linked and returns impact information.

type CodeSearchResult

type CodeSearchResult struct {
	Path      string
	StartLine int
	EndLine   int
	Content   string
	Symbol    string
	Score     float64
}

CodeSearchResult represents a code chunk returned by a search.

type CompactResult

type CompactResult struct {
	ID    string  `json:"id"`
	Type  string  `json:"type"`
	Title string  `json:"title"` // first 100 chars of content
	Score float64 `json:"score"`
}

CompactResult is a lightweight search result (~50 tokens vs ~500 for full content).

type ConfidenceTracker

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

ConfidenceTracker adjusts memory confidence based on session outcomes. When a session succeeds, accessed memories get a confidence boost. When a session fails, accessed memories get flagged for review.

func NewConfidenceTracker

func NewConfidenceTracker(bridge *YaadBridge) *ConfidenceTracker

NewConfidenceTracker creates a tracker that adjusts confidence from outcomes.

func (*ConfidenceTracker) AccessedCount

func (ct *ConfidenceTracker) AccessedCount() int

AccessedCount returns how many unique memories were accessed.

func (*ConfidenceTracker) BoostByType

func (ct *ConfidenceTracker) BoostByType(nodeType string, amount float64)

BoostByType boosts all memories of a given type (useful for post-success reinforcement).

func (*ConfidenceTracker) OnSessionFailure

func (ct *ConfidenceTracker) OnSessionFailure()

OnSessionFailure applies a small confidence penalty to accessed memories, signaling they may contain incorrect or misleading information.

func (*ConfidenceTracker) OnSessionSuccess

func (ct *ConfidenceTracker) OnSessionSuccess()

OnSessionSuccess boosts confidence for all memories accessed during this session.

func (*ConfidenceTracker) RecordAccess

func (ct *ConfidenceTracker) RecordAccess(nodeIDs ...string)

RecordAccess notes that a memory was accessed/used during this session.

func (*ConfidenceTracker) RecordRecall

func (ct *ConfidenceTracker) RecordRecall(results []CompactResult)

RecordRecall tracks memories returned by a recall operation.

func (*ConfidenceTracker) Reset

func (ct *ConfidenceTracker) Reset()

Reset clears access tracking (call at session start).

type ConflictInfo

type ConflictInfo struct {
	ExistingContent string
	NewContent      string
	ExistingAgent   string
	NewAgent        string
	NodeType        string
}

ConflictInfo describes a detected conflict between agent memories.

type ContinuityReport

type ContinuityReport struct {
	TotalSessions      int     `json:"total_sessions"`
	SessionsWithMemory int     `json:"sessions_with_memory"`
	AvgScore           float64 `json:"avg_score"`
	TotalTokensSaved   int     `json:"total_tokens_saved"`
	AvgReExplanations  float64 `json:"avg_re_explanations"`
	SuccessRate        float64 `json:"success_rate"`
	MemoryContribution float64 `json:"memory_contribution"` // 0-1 how much memory helped
}

ContinuityReport summarizes memory effectiveness over time.

type ContinuitySession

type ContinuitySession struct {
	SessionID        string        `json:"session_id"`
	StartedAt        time.Time     `json:"started_at"`
	Duration         time.Duration `json:"duration"`
	MemoryInjected   bool          `json:"memory_injected"`
	MemoriesAccessed int           `json:"memories_accessed"`
	TokensFromMemory int           `json:"tokens_from_memory"`
	TokensSaved      int           `json:"tokens_saved"`
	ReExplanations   int           `json:"re_explanations"`
	TaskSuccess      bool          `json:"task_success"`
	Score            float64       `json:"score"`
}

ContinuitySession records memory effectiveness for a single session.

type ContinuityTracker

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

ContinuityTracker measures the effectiveness of memory across sessions. It tracks token savings, re-explanation avoidance, and generates a "memory continuity score" that shows how much memory helps.

func NewContinuityTracker

func NewContinuityTracker(projectDir string) *ContinuityTracker

NewContinuityTracker creates a tracker that persists across sessions.

func (*ContinuityTracker) EndSession

func (ct *ContinuityTracker) EndSession(success bool)

EndSession closes the current session and computes its score.

func (*ContinuityTracker) FormatSummary

func (ct *ContinuityTracker) FormatSummary() string

FormatSummary returns a human-readable session summary.

func (*ContinuityTracker) RecordMemoryUse

func (ct *ContinuityTracker) RecordMemoryUse(memoriesAccessed, tokensUsed int)

RecordMemoryUse records that memory was accessed during the current session.

func (*ContinuityTracker) RecordReExplanation

func (ct *ContinuityTracker) RecordReExplanation()

RecordReExplanation notes that the user had to re-explain something.

func (*ContinuityTracker) Report

func (ct *ContinuityTracker) Report() ContinuityReport

Report generates an aggregate report across all tracked sessions.

func (*ContinuityTracker) Save

func (ct *ContinuityTracker) Save()

Save persists the tracker state.

func (*ContinuityTracker) StartSession

func (ct *ContinuityTracker) StartSession(sessionID string, memoryInjected bool)

StartSession begins tracking a new session.

type CrossProjectMemory

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

CrossProjectMemory manages global user-level memories that transfer across all projects. Things like coding style preferences, favorite libraries, and workflow patterns are stored with scope:"global" and injected regardless of which project the user is working in.

func NewCrossProjectMemory

func NewCrossProjectMemory(bridge *YaadBridge) *CrossProjectMemory

NewCrossProjectMemory creates a cross-project memory manager.

func (*CrossProjectMemory) DetectGlobalPatterns

func (cp *CrossProjectMemory) DetectGlobalPatterns(projectMemories []string) []string

DetectGlobalPatterns analyzes project-local memories and promotes recurring patterns to global scope. E.g., if the user uses "tabs" in 3+ projects, promote to global preference.

func (*CrossProjectMemory) GetConventions

func (cp *CrossProjectMemory) GetConventions() ([]string, error)

GetConventions returns all global coding conventions.

func (*CrossProjectMemory) GetPreferences

func (cp *CrossProjectMemory) GetPreferences() ([]string, error)

GetPreferences returns all global preference memories.

func (*CrossProjectMemory) InjectGlobalContext

func (cp *CrossProjectMemory) InjectGlobalContext(budget int) string

InjectGlobalContext builds a context string from global memories for prompt injection.

func (*CrossProjectMemory) PromoteToGlobal

func (cp *CrossProjectMemory) PromoteToGlobal(memories []string) error

PromoteToGlobal takes project-local memories and promotes them to global scope.

func (*CrossProjectMemory) RecallGlobal

func (cp *CrossProjectMemory) RecallGlobal(query string, budget int) (string, error)

RecallGlobal retrieves global memories relevant to a query.

func (*CrossProjectMemory) StoreGlobal

func (cp *CrossProjectMemory) StoreGlobal(content, nodeType string) error

StoreGlobal saves a memory with global scope (applies to all projects).

type DiffResult

type DiffResult struct {
	NewFiles      []string
	ModifiedFiles []string
	DeletedFiles  []string
	NewDeps       []string
	Commits       []string
}

DiffResult holds the analysis of what changed during a session.

type DistilledSkill

type DistilledSkill struct {
	Name        string   `json:"name"`
	Description string   `json:"description"`
	Steps       []string `json:"steps"`
	Tools       []string `json:"tools"`
	Patterns    []string `json:"patterns"` // reusable patterns discovered
}

DistilledSkill represents a reusable skill extracted from a completed task.

type DreamResult

type DreamResult struct {
	ConsolidatedMemory string
	MemoriesProcessed  int
	Duration           time.Duration
}

DreamResult holds the outcome of a dream operation.

func RunDream

func RunDream(ctx context.Context, cfg AutoDreamConfig, agentFn func(ctx context.Context, prompt string) (string, error)) (*DreamResult, error)

RunDream executes background memory consolidation. agentFn is called with the consolidation prompt and should return the LLM response.

type EnhancedMemoryManager

type EnhancedMemoryManager struct {
	*MemoryManager

	AutoCapture  *AutoCapture
	Proactive    *ProactiveContext
	Confidence   *ConfidenceTracker
	Retrieval    *RetrievalMetrics
	CodeLinks    *CodeMemoryLinker
	SessionDiff  *SessionDiffAnalyzer
	Continuity   *ContinuityTracker
	CrossProject *CrossProjectMemory
	GraphBudget  *GraphAwareBudget
	Shared       *SharedMemory // nil unless in mission mode
	// contains filtered or unexported fields
}

EnhancedMemoryManager extends MemoryManager with all the new subsystems: auto-capture, proactive context, confidence tracking, retrieval metrics, code-memory links, session diff, continuity scoring, cross-project memory, and shared memory for mission mode.

func NewEnhancedMemoryManager

func NewEnhancedMemoryManager(projectDir string) *EnhancedMemoryManager

NewEnhancedMemoryManager creates a fully-integrated memory system with all subsystems.

func (*EnhancedMemoryManager) Close

func (em *EnhancedMemoryManager) Close()

Close shuts down all subsystems gracefully.

func (*EnhancedMemoryManager) DiagnosticReport

func (em *EnhancedMemoryManager) DiagnosticReport(_ context.Context) string

DiagnosticReport generates a detailed diagnostic for troubleshooting.

func (*EnhancedMemoryManager) EnableMissionMode

func (em *EnhancedMemoryManager) EnableMissionMode(missionID, agentID string)

EnableMissionMode activates shared memory for parallel agent coordination.

func (*EnhancedMemoryManager) EndSession

func (em *EnhancedMemoryManager) EndSession(success bool)

EndSession performs end-of-session processing: diff analysis, confidence updates, metric persistence, and continuity scoring.

func (*EnhancedMemoryManager) FormatForPrompt

func (em *EnhancedMemoryManager) FormatForPrompt() string

FormatForPrompt builds the full memory context for prompt injection, combining all sources: graph budget, global, proactive, and mission.

func (*EnhancedMemoryManager) GlobalContext

func (em *EnhancedMemoryManager) GlobalContext(budget int) string

GlobalContext returns cross-project user preferences for injection.

func (*EnhancedMemoryManager) HealthCheck

func (em *EnhancedMemoryManager) HealthCheck() map[string]interface{}

HealthCheck verifies the memory system is working correctly.

func (*EnhancedMemoryManager) OnToolResult

func (em *EnhancedMemoryManager) OnToolResult(toolName string, args map[string]interface{}, output string, isErr bool)

OnToolResult processes a tool result for auto-capture.

func (*EnhancedMemoryManager) ProactiveContextForFile

func (em *EnhancedMemoryManager) ProactiveContextForFile(path string) string

ProactiveContextForFile returns memories relevant to a file being worked on.

func (*EnhancedMemoryManager) Recall

func (em *EnhancedMemoryManager) Recall(query string, tokenBudget int) (string, error)

Recall performs an enhanced recall that tracks metrics and confidence. Implements engine.MemoryRecaller interface.

func (*EnhancedMemoryManager) RecallFromMission

func (em *EnhancedMemoryManager) RecallFromMission(query string, budget int) (string, error)

RecallFromMission retrieves shared memories from the mission namespace.

func (*EnhancedMemoryManager) Remember

func (em *EnhancedMemoryManager) Remember(content, category string) error

Remember stores memory and routes through auto-capture pipeline. Implements engine.MemoryRecaller interface.

func (*EnhancedMemoryManager) ShareWithMission

func (em *EnhancedMemoryManager) ShareWithMission(content, nodeType string) error

ShareWithMission stores a memory visible to all agents in the mission.

func (*EnhancedMemoryManager) StartSession

func (em *EnhancedMemoryManager) StartSession(sessionID string)

StartSession initializes all session-level tracking.

func (*EnhancedMemoryManager) StatusSummary

func (em *EnhancedMemoryManager) StatusSummary() string

StatusSummary returns a concise status line for the memory system.

type EvolvingMemory

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

EvolvingMemory manages usage guidelines learned from problem-solving.

func NewEvolvingMemory

func NewEvolvingMemory() *EvolvingMemory

NewEvolvingMemory creates a new EvolvingMemory with the default storage path.

func (*EvolvingMemory) Decay

func (em *EvolvingMemory) Decay()

Decay reduces confidence of unused guidelines over time. Guidelines with confidence below 0.1 are removed.

func (*EvolvingMemory) Format

func (em *EvolvingMemory) Format(topK int) string

Format returns guidelines formatted for prompt injection.

func (*EvolvingMemory) Guidelines

func (em *EvolvingMemory) Guidelines() []UsageGuideline

Guidelines returns a copy of all current guidelines.

func (*EvolvingMemory) Learn

func (em *EvolvingMemory) Learn(pattern, lesson, source string)

Learn adds a new guideline or strengthens an existing one if a similar pattern exists.

func (*EvolvingMemory) Load

func (em *EvolvingMemory) Load() error

Load reads persisted guidelines from disk.

func (*EvolvingMemory) Retrieve

func (em *EvolvingMemory) Retrieve(context string, topK int) []UsageGuideline

Retrieve returns the top-K guidelines most relevant to the given context string.

func (*EvolvingMemory) Save

func (em *EvolvingMemory) Save() error

Save persists guidelines to disk.

func (*EvolvingMemory) Strengthen

func (em *EvolvingMemory) Strengthen(id string)

Strengthen increases confidence for a guideline that was useful.

type FullResult

type FullResult struct {
	ID      string `json:"id"`
	Content string `json:"content"`
	Type    string `json:"type"`
}

FullResult contains the complete content for a node.

type GraphAwareBudget

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

GraphAwareBudget makes memory allocation smarter by using yaad's graph to determine what context to inject. It considers: - Active file subgraphs (what memories relate to files being worked on) - Confidence and staleness (prioritize high-confidence, non-stale memories) - Task complexity (more memory for complex multi-file tasks) - Impact analysis (what's affected by current changes)

func NewGraphAwareBudget

func NewGraphAwareBudget(bridge *YaadBridge, proactive *ProactiveContext) *GraphAwareBudget

NewGraphAwareBudget creates a graph-aware memory budget allocator.

func (*GraphAwareBudget) BuildInjection

func (gb *GraphAwareBudget) BuildInjection(query string, activeFiles []string, budget int) string

BuildInjection constructs the optimal memory context within the given budget. It prioritizes by: pinned > high-confidence > file-relevant > recent.

func (*GraphAwareBudget) ComputeBudget

func (gb *GraphAwareBudget) ComputeBudget(activeFiles []string, taskComplexity float64) int

ComputeBudget determines how many tokens to allocate for memory based on task complexity and graph density.

type Memory

type Memory struct {
	ID        string    `json:"id"`
	Content   string    `json:"content"`
	Tags      []string  `json:"tags,omitempty"`
	CreatedAt time.Time `json:"created_at"`
	Source    string    `json:"source,omitempty"` // session ID or file
}

Memory stores extracted memories from sessions.

func Consolidate

func Consolidate(memories []*Memory) []*Memory

Consolidate merges similar memories.

func ExtractFromSession

func ExtractFromSession(sessionID string, messages []string) []*Memory

ExtractFromSession extracts memories from a session transcript.

func List

func List() ([]*Memory, error)

List returns all memories.

func Load

func Load(id string) (*Memory, error)

Load reads a memory by ID.

func Search(query string) ([]*Memory, error)

Search finds memories matching a query.

type MemoryEntry

type MemoryEntry struct {
	ID          string      `json:"id"`
	Layer       MemoryLayer `json:"layer"`
	Content     string      `json:"content"`
	Tags        []string    `json:"tags,omitempty"`
	Priority    float64     `json:"priority"`
	CreatedAt   time.Time   `json:"created_at"`
	AccessedAt  time.Time   `json:"accessed_at"`
	AccessCount int         `json:"access_count"`
}

MemoryEntry is a single memory stored in the ZenBrain.

type MemoryEvent

type MemoryEvent struct {
	Type      string    `json:"type"` // "added", "updated", "conflict"
	NodeType  string    `json:"node_type"`
	Content   string    `json:"content"`
	AgentID   string    `json:"agent_id"`
	MissionID string    `json:"mission_id"`
	Timestamp time.Time `json:"timestamp"`
}

MemoryEvent represents a memory change that other agents should know about.

type MemoryInjection

type MemoryInjection struct {
	Content    string
	TokenCount int
	Source     string // "graph", "global", "proactive", "file"
	Priority   float64
}

MemoryInjection represents prioritized memory content for prompt injection.

type MemoryLayer

type MemoryLayer int

MemoryLayer identifies which layer a memory belongs to.

const (
	LayerWorking    MemoryLayer = iota // current task context (cleared each task)
	LayerShortTerm                     // this session (cleared on session end)
	LayerEpisodic                      // past sessions (what happened)
	LayerSemantic                      // facts and knowledge (what is true)
	LayerProcedural                    // how-to knowledge (how to do things)
	LayerCore                          // fundamental preferences (never expires)
	LayerCross                         // cross-project patterns

)

func (MemoryLayer) String

func (l MemoryLayer) String() string

String returns a human-readable name for the layer.

type MemoryManager

type MemoryManager struct {
	Core     *Memory // nil-safe; used via package-level funcs
	Auto     *AutoMemory
	Evolving *EvolvingMemory
	Zen      *ZenBrain
	Yaad     *YaadBridge
}

MemoryManager is a unified facade that coordinates all memory subsystems and implements the engine.MemoryRecaller interface.

func NewMemoryManager

func NewMemoryManager(projectDir string) *MemoryManager

NewMemoryManager creates a MemoryManager with all subsystems initialized.

func (*MemoryManager) FormatForPrompt

func (mm *MemoryManager) FormatForPrompt() string

FormatForPrompt gathers context from all subsystems into a single string suitable for prompt injection.

func (*MemoryManager) LoadStartup

func (mm *MemoryManager) LoadStartup() error

LoadStartup initializes all subsystems by loading persisted state from disk.

func (*MemoryManager) Recall

func (mm *MemoryManager) Recall(query string, tokenBudget int) (string, error)

Recall queries all memory subsystems and merges results, deduplicating by content. Implements engine.MemoryRecaller.

func (*MemoryManager) Remember

func (mm *MemoryManager) Remember(content, category string) error

Remember routes content to the appropriate subsystem based on category. Implements engine.MemoryRecaller.

type ProactiveContext

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

ProactiveContext provides file-aware, topic-aware memory injection. Instead of waiting for explicit recall calls, it tracks which files the agent is working on and proactively surfaces relevant memories.

func NewProactiveContext

func NewProactiveContext(bridge *YaadBridge) *ProactiveContext

NewProactiveContext creates a proactive context injector.

func (*ProactiveContext) ContextForActiveFiles

func (pc *ProactiveContext) ContextForActiveFiles(budget int) string

ContextForActiveFiles returns aggregated context for all currently active files. Called at strategic points (e.g., before each LLM query) to keep context fresh.

func (*ProactiveContext) ContextForFile

func (pc *ProactiveContext) ContextForFile(path string) string

ContextForFile returns relevant memories for a specific file path.

func (*ProactiveContext) ContextForTool

func (pc *ProactiveContext) ContextForTool(toolName string, args map[string]interface{}) string

ContextForTool returns proactive context based on the tool about to be used.

func (*ProactiveContext) ImpactAnalysis

func (pc *ProactiveContext) ImpactAnalysis(ctx context.Context, changedFile string) string

ImpactAnalysis checks what memories are affected by a file change. Returns formatted impact information or empty string.

func (*ProactiveContext) Reset

func (pc *ProactiveContext) Reset()

Reset clears injected memory tracking (e.g., at session boundaries).

func (*ProactiveContext) TrackFile

func (pc *ProactiveContext) TrackFile(path string)

TrackFile records that the agent is working on a specific file.

func (*ProactiveContext) TrackFiles

func (pc *ProactiveContext) TrackFiles(paths []string)

TrackFiles records multiple file interactions at once.

type RetrievalEntry

type RetrievalEntry struct {
	Query       string    `json:"query"`
	ResultCount int       `json:"result_count"`
	TokensUsed  int       `json:"tokens_used"`
	WasUseful   bool      `json:"was_useful"`
	Timestamp   time.Time `json:"timestamp"`
	SessionID   string    `json:"session_id"`
	ToolContext string    `json:"tool_context,omitempty"`
}

RetrievalEntry records a single recall operation and its effectiveness.

type RetrievalMetrics

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

RetrievalMetrics tracks memory retrieval effectiveness in real-time. It logs every recall operation, what was returned, and measures hit rate to enable auto-tuning of search parameters.

func NewRetrievalMetrics

func NewRetrievalMetrics(projectDir string) *RetrievalMetrics

NewRetrievalMetrics creates a metrics tracker that persists to disk.

func (*RetrievalMetrics) FormatSummary

func (rm *RetrievalMetrics) FormatSummary() string

FormatSummary returns a human-readable summary string.

func (*RetrievalMetrics) HitRate

func (rm *RetrievalMetrics) HitRate() float64

HitRate returns the percentage of recalls that returned results.

func (*RetrievalMetrics) MarkUseful

func (rm *RetrievalMetrics) MarkUseful()

MarkUseful marks the most recent recall as useful (agent actually used the result).

func (*RetrievalMetrics) RecordRecall

func (rm *RetrievalMetrics) RecordRecall(query string, resultCount, tokensUsed int, toolCtx string)

RecordRecall logs a memory recall operation.

func (*RetrievalMetrics) Report

func (rm *RetrievalMetrics) Report() RetrievalReport

Report generates a summary of retrieval effectiveness.

func (*RetrievalMetrics) Save

func (rm *RetrievalMetrics) Save()

Save persists metrics to disk.

func (*RetrievalMetrics) TokensSaved

func (rm *RetrievalMetrics) TokensSaved() int

TokensSaved estimates tokens saved by using memory vs re-explaining. Assumes an average re-explanation costs ~500 tokens.

func (*RetrievalMetrics) TotalRecalls

func (rm *RetrievalMetrics) TotalRecalls() int

TotalRecalls returns how many recall operations have been performed.

type RetrievalReport

type RetrievalReport struct {
	TotalRecalls      int      `json:"total_recalls"`
	HitRate           float64  `json:"hit_rate"`
	AvgResultCount    float64  `json:"avg_result_count"`
	AvgTokensPerCall  int      `json:"avg_tokens_per_call"`
	TotalTokensSaved  int      `json:"total_tokens_saved"`
	MostQueriedTopics []string `json:"most_queried_topics"`
}

RetrievalReport summarizes retrieval effectiveness across sessions.

type SessionDiffAnalyzer

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

SessionDiffAnalyzer examines what changed during a session and extracts memories from the diff: new files → purpose, new deps → choices, conventions followed/violated → confidence updates.

func NewSessionDiffAnalyzer

func NewSessionDiffAnalyzer(bridge *YaadBridge, projectDir string) *SessionDiffAnalyzer

NewSessionDiffAnalyzer creates a diff analyzer for a project directory.

func (*SessionDiffAnalyzer) AnalyzeEnd

func (sd *SessionDiffAnalyzer) AnalyzeEnd() *DiffResult

AnalyzeEnd computes the diff between session start and end, extracting memories.

func (*SessionDiffAnalyzer) SnapshotStart

func (sd *SessionDiffAnalyzer) SnapshotStart()

SnapshotStart captures the project state at session start for later diffing.

func (*SessionDiffAnalyzer) StoreMemoriesFromDiff

func (sd *SessionDiffAnalyzer) StoreMemoriesFromDiff(diff *DiffResult)

StoreMemoriesFromDiff extracts and stores memories based on the session diff.

type SharedMemory

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

SharedMemory enables real-time memory sharing between parallel agents in Hawk's mission mode. When one agent discovers something, all other agents in the same mission can see it immediately.

func NewSharedMemory

func NewSharedMemory(bridge *YaadBridge, missionID, agentID string) *SharedMemory

NewSharedMemory creates a shared memory instance for a specific mission.

func (*SharedMemory) GetAllShared

func (sm *SharedMemory) GetAllShared() ([]string, error)

GetAllShared returns all memories in the mission namespace.

func (*SharedMemory) OnMemoryEvent

func (sm *SharedMemory) OnMemoryEvent(fn func(MemoryEvent))

OnMemoryEvent registers a listener for memory events from other agents.

func (*SharedMemory) Recall

func (sm *SharedMemory) Recall(query string, budget int) (string, error)

Recall retrieves shared memories from the mission namespace.

func (*SharedMemory) Share

func (sm *SharedMemory) Share(content, nodeType string) error

Share stores a memory visible to all agents in the same mission.

type SkillDistiller

type SkillDistiller struct{}

SkillDistiller extracts reusable skills from successful task completions.

func (*SkillDistiller) BuildSkillPrompt

func (sd *SkillDistiller) BuildSkillPrompt(taskDescription string, toolsUsed []string, filesModified []string, outcome string) string

BuildSkillPrompt creates a prompt that asks the LLM to distill a completed task into a reusable skill document.

func (*SkillDistiller) ParseSkill

func (sd *SkillDistiller) ParseSkill(llmResponse string) (*DistilledSkill, error)

ParseSkill extracts the skill from the LLM response.

type SleeptimeAgent

type SleeptimeAgent struct {
	Frequency int // run every N turns
	// contains filtered or unexported fields
}

SleeptimeAgent runs a background LLM call to consolidate memory after conversation turns.

func NewSleeptimeAgent

func NewSleeptimeAgent(frequency int) *SleeptimeAgent

NewSleeptimeAgent creates a SleeptimeAgent that triggers every frequency turns.

func (*SleeptimeAgent) BuildConsolidationPrompt

func (sa *SleeptimeAgent) BuildConsolidationPrompt(transcript []string, memoryState string) string

BuildConsolidationPrompt creates the prompt for the background memory agent.

func (*SleeptimeAgent) ShouldRun

func (sa *SleeptimeAgent) ShouldRun() bool

ShouldRun increments the turn counter and returns true when it's time to consolidate.

type UsageGuideline

type UsageGuideline struct {
	ID         string    `json:"id"`
	Pattern    string    `json:"pattern"`    // when this situation occurs
	Lesson     string    `json:"lesson"`     // what to do / not do
	Source     string    `json:"source"`     // which session taught this
	Confidence float64   `json:"confidence"` // 0-1, increases with repeated confirmation
	Uses       int       `json:"uses"`       // how many times retrieved
	CreatedAt  time.Time `json:"created_at"`
}

UsageGuideline represents a lesson learned from problem-solving experience.

type YaadBridge

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

YaadBridge connects hawk's memory system to the yaad memory graph. If yaad is not initialized (missing DB), operations return a BridgeError and log a warning on first access.

func NewYaadBridge

func NewYaadBridge() *YaadBridge

NewYaadBridge initializes a bridge to yaad's SQLite store at ~/.yaad/data/yaad.db. Returns a bridge that silently no-ops if initialization fails.

func (*YaadBridge) ClearFileChunks

func (b *YaadBridge) ClearFileChunks(path string) error

ClearFileChunks removes all indexed chunks for a given file path.

func (*YaadBridge) Close

func (b *YaadBridge) Close()

Close shuts down the yaad engine and closes the database connection.

func (*YaadBridge) GetFileHash

func (b *YaadBridge) GetFileHash(path string) (string, error)

GetFileHash returns the stored hash for a file path, or empty string if not indexed.

func (*YaadBridge) GetFullContent

func (b *YaadBridge) GetFullContent(ids []string) ([]FullResult, error)

GetFullContent returns full content for specific node IDs.

func (*YaadBridge) IndexCodeChunk

func (b *YaadBridge) IndexCodeChunk(path, content, symbol, lang string, start, end, tokens int, hash string) error

IndexCodeChunk stores a code chunk in the yaad code index.

func (*YaadBridge) InitCodeIndex

func (b *YaadBridge) InitCodeIndex() error

InitCodeIndex creates the code index tables in yaad's store. Safe to call multiple times. Returns a BridgeError if yaad is not initialized.

func (*YaadBridge) IsReady

func (b *YaadBridge) IsReady() bool

IsReady is a public alias for Ready, exported for external consumers that need to check bridge status before batching operations.

func (*YaadBridge) ListIndexedPaths

func (b *YaadBridge) ListIndexedPaths() ([]string, error)

ListIndexedPaths returns all file paths that have indexed code chunks.

func (*YaadBridge) Ready

func (b *YaadBridge) Ready() bool

Ready reports whether the yaad bridge is initialized and usable.

func (*YaadBridge) Recall

func (b *YaadBridge) Recall(query string, tokenBudget int) (string, error)

Recall searches yaad's memory graph and returns formatted context that fits within the specified token budget. Returns a BridgeError if yaad is not initialized.

func (*YaadBridge) Remember

func (b *YaadBridge) Remember(content, category string) error

Remember stores content into yaad's memory graph under the given category. Category maps to yaad's node type (e.g., "convention", "decision", "bug", "preference"). Returns a BridgeError if yaad is not initialized.

func (*YaadBridge) SearchByType

func (b *YaadBridge) SearchByType(nodeType string, limit int) ([]string, []string, error)

SearchByType returns nodes matching the given type (label).

func (*YaadBridge) SearchCode

func (b *YaadBridge) SearchCode(query string, limit int) ([]CodeSearchResult, error)

SearchCode performs full-text search over indexed code chunks.

func (*YaadBridge) SearchCompact

func (b *YaadBridge) SearchCompact(query string, limit int) ([]CompactResult, error)

SearchCompact returns compact index entries (ID + title + score) without full content.

func (*YaadBridge) UpdateNodeContent

func (b *YaadBridge) UpdateNodeContent(id, newContent string) error

UpdateNodeContent updates the content of a node by ID.

type ZenBrain

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

ZenBrain is a 7-layer memory system inspired by neuroscience.

func NewZenBrain

func NewZenBrain() *ZenBrain

NewZenBrain creates a new ZenBrain with the default storage path.

func (*ZenBrain) Consolidate

func (zb *ZenBrain) Consolidate()

Consolidate promotes memories between layers based on access frequency:

  • ShortTerm entries accessed 3+ times move to Episodic
  • Episodic entries accessed 5+ times move to Semantic

func (*ZenBrain) FormatForPrompt

func (zb *ZenBrain) FormatForPrompt(maxTokens int) string

FormatForPrompt selects the most relevant memories across all layers and formats them for prompt injection, within the given token estimate.

func (*ZenBrain) LayerSize

func (zb *ZenBrain) LayerSize(layer MemoryLayer) int

LayerSize returns the number of entries in a specific layer.

func (*ZenBrain) Load

func (zb *ZenBrain) Load() error

Load reads persisted memories from disk and distributes them to layers.

func (*ZenBrain) Retrieve

func (zb *ZenBrain) Retrieve(query string, layers []MemoryLayer, topK int) []MemoryEntry

Retrieve returns the top-K entries across the specified layers that best match the query (by keyword overlap), sorted by relevance.

func (*ZenBrain) Save

func (zb *ZenBrain) Save() error

Save persists all layers to disk.

func (*ZenBrain) Sleep

func (zb *ZenBrain) Sleep()

Sleep runs consolidation, decay, and strengthening — analogous to memory sleep. It consolidates layers, decays unused memories, and strengthens frequently accessed ones.

func (*ZenBrain) Store

func (zb *ZenBrain) Store(layer MemoryLayer, content string, tags []string)

Store adds a memory to the specified layer.

func (*ZenBrain) TotalSize

func (zb *ZenBrain) TotalSize() int

TotalSize returns the total number of entries across all layers.

Jump to

Keyboard shortcuts

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