memory

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 11, 2026 License: AGPL-3.0 Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const CodeMemoryClassName = "CodeMemory"

CodeMemoryClassName is the Weaviate class name for code memories.

Variables

View Source
var (
	ErrMemoryNotFound      = errors.New("memory not found")
	ErrInvalidMemoryType   = errors.New("invalid memory type")
	ErrInvalidMemorySource = errors.New("invalid memory source")
	ErrInvalidConfidence   = errors.New("confidence must be between 0.0 and 1.0")
	ErrEmptyContent        = errors.New("memory content cannot be empty")
	ErrEmptyScope          = errors.New("memory scope cannot be empty")
	ErrMemoryAlreadyExists = errors.New("memory with this ID already exists")
)

Sentinel errors for memory operations.

ValidMemorySources is the set of valid memory sources.

ValidMemoryTypes is the set of valid memory types.

Functions

func DeleteCodeMemorySchema

func DeleteCodeMemorySchema(ctx context.Context, client *weaviate.Client) error

DeleteCodeMemorySchema removes the CodeMemory class from Weaviate.

Description:

Deletes the CodeMemory class and all its objects.
Use with caution - this is irreversible.

Inputs:

ctx - Context for cancellation
client - Weaviate client

Outputs:

error - Non-nil if deletion fails

func EnsureCodeMemorySchema

func EnsureCodeMemorySchema(ctx context.Context, client *weaviate.Client) error

EnsureCodeMemorySchema creates the CodeMemory class if it doesn't exist.

Description:

Checks if the CodeMemory class exists in Weaviate and creates it if not.
This operation is idempotent.

Inputs:

ctx - Context for cancellation
client - Weaviate client

Outputs:

error - Non-nil if schema creation fails

func GetCodeMemorySchema

func GetCodeMemorySchema() *models.Class

GetCodeMemorySchema returns the Weaviate schema for CodeMemory class.

Description:

Defines the schema for storing code memories in Weaviate.
Uses text2vec-transformers for vectorizing content and scope fields.

Outputs:

*models.Class - The Weaviate class definition

Types

type CleanupResult

type CleanupResult struct {
	// MemoriesArchived is the count of memories archived due to staleness.
	MemoriesArchived int

	// MemoriesDeleted is the count of memories deleted due to low confidence.
	MemoriesDeleted int

	// Errors contains any non-fatal errors encountered.
	Errors []string
}

CleanupResult contains the results of a cleanup run.

type CodeMemory

type CodeMemory struct {
	// MemoryID is the unique identifier (UUID).
	MemoryID string `json:"memory_id"`

	// Content is the learned rule or constraint.
	Content string `json:"content"`

	// MemoryType categorizes the memory.
	MemoryType MemoryType `json:"memory_type"`

	// Scope is a file glob pattern indicating where this memory applies.
	Scope string `json:"scope"`

	// Confidence is a score from 0.0 to 1.0 indicating reliability.
	Confidence float64 `json:"confidence"`

	// Source indicates how this memory was learned.
	Source MemorySource `json:"source"`

	// CreatedAt is when the memory was first stored (Unix milliseconds UTC).
	CreatedAt int64 `json:"created_at"`

	// LastUsed is when the memory was last retrieved (Unix milliseconds UTC).
	LastUsed int64 `json:"last_used"`

	// UseCount tracks how many times this memory has been retrieved.
	UseCount int `json:"use_count"`

	// DataSpace is the project isolation key.
	DataSpace string `json:"data_space"`

	// Status indicates the lifecycle stage.
	Status MemoryStatus `json:"status"`
}

CodeMemory represents a learned constraint or pattern.

func (*CodeMemory) Validate

func (m *CodeMemory) Validate() error

Validate checks that the memory has valid fields.

Description:

Validates all required fields and constraints on a CodeMemory.
Should be called before storing a new memory.

Outputs:

error - Non-nil if validation fails

type LifecycleConfig

type LifecycleConfig struct {
	// StaleThreshold is how long before a memory is considered stale.
	StaleThreshold time.Duration

	// MinActiveConfidence is the minimum confidence for active status.
	MinActiveConfidence float64

	// ConfidenceBoostOnValidation is how much to increase confidence on validation.
	ConfidenceBoostOnValidation float64

	// ConfidenceDecayOnContradiction is how much to decrease confidence on contradiction.
	ConfidenceDecayOnContradiction float64

	// DeleteBelowConfidence is the confidence threshold below which memories are deleted.
	DeleteBelowConfidence float64
}

LifecycleConfig configures the memory lifecycle manager.

func DefaultLifecycleConfig

func DefaultLifecycleConfig() LifecycleConfig

DefaultLifecycleConfig returns sensible defaults.

type LifecycleManager

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

LifecycleManager handles memory lifecycle transitions.

func NewLifecycleManager

func NewLifecycleManager(client *weaviate.Client, store *MemoryStore, dataSpace string) (*LifecycleManager, error)

NewLifecycleManager creates a new lifecycle manager.

Description:

Creates a LifecycleManager for handling memory lifecycle transitions
including archival, validation, and contradiction handling.

Inputs:

client - Weaviate client. Must not be nil.
store - MemoryStore for updates. Must not be nil.
dataSpace - Project isolation key.

Outputs:

*LifecycleManager - The configured manager
error - Non-nil if client or store is nil

Thread Safety: All methods are safe for concurrent use.

func NewLifecycleManagerWithConfig

func NewLifecycleManagerWithConfig(client *weaviate.Client, store *MemoryStore, dataSpace string, config LifecycleConfig) *LifecycleManager

NewLifecycleManagerWithConfig creates a manager with custom configuration.

func (*LifecycleManager) ContradictMemory

func (m *LifecycleManager) ContradictMemory(ctx context.Context, memoryID, reason string) error

ContradictMemory handles when evidence contradicts a memory.

Description:

Decreases confidence significantly when a memory is found to be
incorrect or outdated. If confidence drops below threshold, deletes.

Inputs:

ctx - Context for cancellation
memoryID - The memory's unique identifier
reason - Why the memory is being contradicted

Outputs:

error - Non-nil if update fails or memory not found

func (*LifecycleManager) PromoteToActive

func (m *LifecycleManager) PromoteToActive(ctx context.Context, memoryID string) (bool, error)

PromoteToActive promotes a memory to active status if confidence is high enough.

Description:

Checks if a memory's confidence meets the threshold for active status
and promotes it from created/archived to active.

Inputs:

ctx - Context for cancellation
memoryID - The memory's unique identifier

Outputs:

bool - Whether the memory was promoted
error - Non-nil if check/update fails

func (*LifecycleManager) RunCleanup

func (m *LifecycleManager) RunCleanup(ctx context.Context) (*CleanupResult, error)

RunCleanup performs lifecycle maintenance on memories.

Description:

Archives memories that haven't been used within the stale threshold.
Deletes memories with confidence below a critical threshold.
This should be run periodically (e.g., daily via cron).

Inputs:

ctx - Context for cancellation

Outputs:

*CleanupResult - Statistics about cleanup actions
error - Non-nil if cleanup fails completely

func (*LifecycleManager) ValidateMemory

func (m *LifecycleManager) ValidateMemory(ctx context.Context, memoryID string) error

ValidateMemory boosts confidence when a memory is confirmed useful.

Description:

Increases the confidence score when the agent or user confirms
that a memory was helpful. Also reactivates archived memories.

Inputs:

ctx - Context for cancellation
memoryID - The memory's unique identifier

Outputs:

error - Non-nil if update fails or memory not found

func (*LifecycleManager) ValidateScopes

func (m *LifecycleManager) ValidateScopes(ctx context.Context, currentFiles []string) (*ScopeValidationResult, error)

ValidateScopes checks memory scopes against current project files.

Description

After a graph rebuild, call this method with the current file list to detect memories whose scope patterns no longer match any files. Such memories are marked as Orphaned because they reference files that no longer exist.

This solves the "Ephemeral Graph vs Persistent Memory" problem where: 1. Agent learns: "Always check auth in `pkg/users/handler.go`" 2. User refactors: `pkg/users/` → `internal/identity/` 3. Graph rebuilds correctly (source-driven) 4. This method detects the memory is now orphaned

Inputs

  • ctx: Context for cancellation.
  • currentFiles: List of file paths currently in the project.

Outputs

  • *ScopeValidationResult: Statistics about validation.
  • error: Non-nil if validation fails completely.

Thread Safety

Safe for concurrent use.

type ListRequest

type ListRequest struct {
	Limit           int     `form:"limit"`
	Offset          int     `form:"offset"`
	MemoryType      string  `form:"memory_type"`
	IncludeArchived bool    `form:"include_archived"`
	MinConfidence   float64 `form:"min_confidence"`
}

ListRequest is the HTTP request for listing memories.

type MemoriesResponse

type MemoriesResponse struct {
	Memories []CodeMemory `json:"memories"`
	Total    int          `json:"total"`
}

MemoriesResponse is the HTTP response for multiple memories.

type MemoryResponse

type MemoryResponse struct {
	Memory CodeMemory `json:"memory"`
}

MemoryResponse is the HTTP response for a single memory.

type MemoryRetriever

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

MemoryRetriever handles semantic retrieval of code memories.

func NewMemoryRetriever

func NewMemoryRetriever(client *weaviate.Client, store *MemoryStore, dataSpace string) (*MemoryRetriever, error)

NewMemoryRetriever creates a new memory retriever.

Description:

Creates a MemoryRetriever for semantic search and ranked retrieval.

Inputs:

client - Weaviate client. Must not be nil.
store - MemoryStore for updates. Must not be nil.
dataSpace - Project isolation key.

Outputs:

*MemoryRetriever - The configured retriever
error - Non-nil if client or store is nil

Thread Safety: Retrieve methods are safe for concurrent use.

func NewMemoryRetrieverWithConfig

func NewMemoryRetrieverWithConfig(client *weaviate.Client, store *MemoryStore, dataSpace string, config RetrieverConfig) *MemoryRetriever

NewMemoryRetrieverWithConfig creates a retriever with custom configuration.

func (*MemoryRetriever) Retrieve

func (r *MemoryRetriever) Retrieve(ctx context.Context, opts RetrieveOptions) ([]RetrieveResult, error)

Retrieve performs semantic retrieval of relevant memories.

Description:

Searches for memories semantically similar to the query, filters by scope,
and ranks results by confidence × recency × relevance. Automatically
updates lastUsed timestamps for retrieved memories.

Inputs:

ctx - Context for cancellation
opts - Retrieval options including query, scope, and limits

Outputs:

[]RetrieveResult - Ranked results with scores
error - Non-nil if search fails

func (*MemoryRetriever) RetrieveForFiles

func (r *MemoryRetriever) RetrieveForFiles(ctx context.Context, query string, files []string, limit int) ([]RetrieveResult, error)

RetrieveForFiles retrieves memories relevant to specific files.

Description:

Convenience method that searches for memories matching the given
file paths. Checks each memory's scope against the files.

Inputs:

ctx - Context for cancellation
query - Semantic search query
files - File paths to check scopes against
limit - Maximum results

Outputs:

[]RetrieveResult - Ranked results relevant to the files
error - Non-nil if search fails

type MemorySource

type MemorySource string

MemorySource represents how a memory was learned.

const (
	SourceAgentDiscovery MemorySource = "agent_discovery"
	SourceUserFeedback   MemorySource = "user_feedback"
	SourceTestFailure    MemorySource = "test_failure"
	SourceCodeReview     MemorySource = "code_review"
	SourceManual         MemorySource = "manual"
)

type MemoryStatus

type MemoryStatus string

MemoryStatus represents the lifecycle status of a memory.

const (
	StatusActive   MemoryStatus = "active"
	StatusArchived MemoryStatus = "archived"
	// StatusOrphaned indicates a memory's scope no longer matches any files.
	// This happens when files are deleted or refactored and the memory's
	// file glob pattern no longer matches any existing files.
	StatusOrphaned MemoryStatus = "orphaned"
)

type MemoryStore

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

MemoryStore handles storage and retrieval of code memories in Weaviate.

func NewMemoryStore

func NewMemoryStore(client *weaviate.Client, dataSpace string) (*MemoryStore, error)

NewMemoryStore creates a new memory store.

Description:

Creates a MemoryStore configured for a specific data space.
The data space is used for project isolation.

Inputs:

client - Weaviate client. Must not be nil.
dataSpace - Project isolation key. Must not be empty.

Outputs:

*MemoryStore - The configured memory store
error - Non-nil if client is nil or dataSpace is empty

Thread Safety: Individual methods are safe for concurrent use. However, compound operations (e.g., Get then UpdateConfidence) may have race conditions and should use external synchronization if atomicity is required.

func NewMemoryStoreWithConfig

func NewMemoryStoreWithConfig(client *weaviate.Client, config MemoryStoreConfig) *MemoryStore

NewMemoryStoreWithConfig creates a memory store with custom configuration.

func (*MemoryStore) Archive

func (s *MemoryStore) Archive(ctx context.Context, memoryID string) error

Archive sets a memory's status to archived.

Description:

Marks a memory as archived. Archived memories are not returned
by default in retrieval queries but are not deleted.

Inputs:

ctx - Context for cancellation
memoryID - The memory's unique identifier

Outputs:

error - Non-nil if update fails or memory not found

func (*MemoryStore) Delete

func (s *MemoryStore) Delete(ctx context.Context, memoryID string) error

Delete removes a memory from Weaviate.

Description:

Permanently deletes a memory. This cannot be undone.

Inputs:

ctx - Context for cancellation
memoryID - The memory's unique identifier

Outputs:

error - Non-nil if deletion fails or memory not found

func (*MemoryStore) Get

func (s *MemoryStore) Get(ctx context.Context, memoryID string) (*CodeMemory, error)

Get retrieves a memory by its ID.

Description:

Fetches a single memory by its memoryId field.

Inputs:

ctx - Context for cancellation
memoryID - The memory's unique identifier

Outputs:

*CodeMemory - The found memory
error - Non-nil if not found or query fails

func (*MemoryStore) List

func (s *MemoryStore) List(ctx context.Context, limit, offset int, memoryType string, includeArchived bool, minConfidence float64) ([]CodeMemory, error)

List retrieves memories for the data space.

Description:

Lists memories with optional filtering by type, status, and confidence.

Inputs:

ctx - Context for cancellation
limit - Maximum number of results (default 10)
offset - Number of results to skip (for pagination)
memoryType - Optional filter by memory type
includeArchived - Whether to include archived memories
minConfidence - Minimum confidence threshold

Outputs:

[]CodeMemory - The found memories
error - Non-nil if query fails

func (*MemoryStore) MarkUsed

func (s *MemoryStore) MarkUsed(ctx context.Context, memoryID string) error

MarkUsed updates the last_used timestamp and increments use_count.

Description:

Called when a memory is retrieved to track usage patterns.
Updates lastUsed to now and increments useCount.

Inputs:

ctx - Context for cancellation
memoryID - The memory's unique identifier

Outputs:

error - Non-nil if update fails or memory not found

func (*MemoryStore) Store

func (s *MemoryStore) Store(ctx context.Context, memory CodeMemory) (*CodeMemory, error)

Store persists a new code memory to Weaviate.

Description:

Validates and stores a new memory. Sets defaults for optional fields
like MemoryID, CreatedAt, LastUsed, Status, and DataSpace.

Inputs:

ctx - Context for cancellation
memory - The memory to store. Content, MemoryType, Scope, and Source are required.

Outputs:

*CodeMemory - The stored memory with generated fields populated
error - Non-nil if validation or storage fails

func (*MemoryStore) UpdateConfidence

func (s *MemoryStore) UpdateConfidence(ctx context.Context, memoryID string, delta float64) error

UpdateConfidence adjusts a memory's confidence score.

Description:

Increases or decreases the confidence score by the given delta.
The result is clamped to [0.0, 1.0].

Inputs:

ctx - Context for cancellation
memoryID - The memory's unique identifier
delta - Amount to add to confidence (can be negative)

Outputs:

error - Non-nil if update fails or memory not found

type MemoryStoreConfig

type MemoryStoreConfig struct {
	// DataSpace is the project isolation key.
	DataSpace string

	// DefaultConfidence is the initial confidence for new memories.
	DefaultConfidence float64

	// MaxResults is the default limit for retrieval queries.
	MaxResults int
}

MemoryStoreConfig configures the memory store.

func DefaultMemoryStoreConfig

func DefaultMemoryStoreConfig() MemoryStoreConfig

DefaultMemoryStoreConfig returns sensible defaults.

type MemoryType

type MemoryType string

MemoryType represents the kind of learned knowledge.

const (
	MemoryTypeConstraint   MemoryType = "constraint"
	MemoryTypePattern      MemoryType = "pattern"
	MemoryTypeConvention   MemoryType = "convention"
	MemoryTypeBugPattern   MemoryType = "bug_pattern"
	MemoryTypeOptimization MemoryType = "optimization"
	MemoryTypeSecurity     MemoryType = "security"
)

type RetrieveOptions

type RetrieveOptions struct {
	// Query is the semantic search query.
	Query string

	// Scope filters memories by their scope (glob pattern).
	Scope string

	// Limit is the maximum number of results.
	Limit int

	// IncludeArchived includes archived memories in results.
	IncludeArchived bool

	// MinConfidence filters out memories below this threshold.
	MinConfidence float64
}

RetrieveOptions configures retrieval behavior.

type RetrieveRequest

type RetrieveRequest struct {
	Query           string  `json:"query" binding:"required"`
	Scope           string  `json:"scope"`
	Limit           int     `json:"limit"`
	IncludeArchived bool    `json:"include_archived"`
	MinConfidence   float64 `json:"min_confidence"`
}

RetrieveRequest is the HTTP request for retrieving memories.

type RetrieveResponse

type RetrieveResponse struct {
	Results []RetrieveResult `json:"results"`
}

RetrieveResponse is the HTTP response for memory retrieval.

type RetrieveResult

type RetrieveResult struct {
	// Memory is the retrieved memory.
	Memory CodeMemory `json:"memory"`

	// Score is the combined relevance score.
	Score float64 `json:"score"`
}

RetrieveResult contains a memory and its retrieval score.

type RetrieverConfig

type RetrieverConfig struct {
	// MaxResults is the default limit for retrieval queries.
	MaxResults int

	// ConfidenceWeight is the weight for confidence in ranking (0-1).
	ConfidenceWeight float64

	// RecencyWeight is the weight for recency in ranking (0-1).
	RecencyWeight float64

	// RelevanceWeight is the weight for semantic relevance in ranking (0-1).
	RelevanceWeight float64

	// RecencyDecayDays is how many days before recency score drops to 0.5.
	RecencyDecayDays float64

	// AutoMarkUsed automatically updates lastUsed on retrieval.
	AutoMarkUsed bool
}

RetrieverConfig configures the memory retriever.

func DefaultRetrieverConfig

func DefaultRetrieverConfig() RetrieverConfig

DefaultRetrieverConfig returns sensible defaults.

type ScopeValidationResult

type ScopeValidationResult struct {
	// MemoriesOrphaned is the count of memories marked as orphaned.
	MemoriesOrphaned int

	// MemoriesValidated is the count of memories with valid scopes.
	MemoriesValidated int

	// Errors contains any non-fatal errors encountered.
	Errors []string
}

ScopeValidationResult contains the results of scope validation.

type StoreRequest

type StoreRequest struct {
	Content    string     `json:"content" binding:"required"`
	MemoryType MemoryType `json:"memory_type" binding:"required"`
	Scope      string     `json:"scope" binding:"required"`
	Confidence float64    `json:"confidence"`
	Source     string     `json:"source"`
}

StoreRequest is the HTTP request for storing a memory.

Jump to

Keyboard shortcuts

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