domain

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 23, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package domain defines the core domain models and business rules for Cortex.

This package contains the pure domain types that represent the core concepts of the memory system: Observations, Sessions, Knowledge Graph Edges, Prompts, and Importance Scoring. These types are independent of storage mechanisms and can be used across different layers of the application.

Index

Constants

View Source
const (
	TypeManual    = "manual"
	TypeToolUse   = "tool_use"
	TypeDecision  = "decision"
	TypeBugfix    = "bugfix"
	TypePattern   = "pattern"
	TypeConfig    = "config"
	TypeDiscovery = "discovery"
	TypeLearning  = "learning"
)

Observation types - common values for the Type field

View Source
const (
	ScopeProject  = "project"
	ScopePersonal = "personal"
)

Scope types - common values for the Scope field

View Source
const (
	SourceManual = "manual"
	SourceAI     = "ai"
	SourceAuto   = "auto"
	SourceImport = "import"
)

Source types - common values for the Source field

View Source
const (
	RelationReferences  = "references"
	RelationRelatesTo   = "relates_to"
	RelationFollows     = "follows"
	RelationContradicts = "contradicts"
	RelationSupersedes  = "supersedes"
)

Relation types - common values for Edge.RelationType

View Source
const (
	EntityFile     = "file"
	EntityURL      = "url"
	EntityPackage  = "package"
	EntitySymbol   = "symbol"
	EntityConcept  = "concept"
	EntitySQLTable = "sql_table"
	EntityEndpoint = "endpoint"
	EntityEnvVar   = "env_var"
	EntityVersion  = "version"
	EntityCLIFlag  = "cli_flag"
	EntityError    = "error"
)

Entity types

View Source
const (
	EvolutionOriginal     = "original"
	EvolutionModified     = "modified"
	EvolutionSuperseded   = "superseded"
	EvolutionContradicted = "contradicted"
)

Evolution types for temporal graph edges

View Source
const (
	FactStateCurrent    = "current"
	FactStateHistorical = "historical"
	FactStateDeprecated = "deprecated"
	FactStateSuperseded = "superseded"
)

Fact states for temporal graph edges

View Source
const (
	RelationTemporal = "temporal" // Tracks how facts evolve over time
)

Additional temporal relation types.

Variables

View Source
var (
	// ErrNotFound indicates that the requested entity was not found.
	ErrNotFound = errors.New("entity not found")

	// ErrAlreadyExists indicates that an entity with the same key already exists.
	ErrAlreadyExists = errors.New("entity already exists")

	// ErrInvalidInput indicates that the input data is invalid.
	ErrInvalidInput = errors.New("invalid input")

	// ErrConflict indicates a conflict with the current state (e.g., optimistic locking).
	ErrConflict = errors.New("conflict with current state")

	// ErrUnauthorized indicates lack of permissions for the operation.
	ErrUnauthorized = errors.New("unauthorized")

	// ErrSessionEnded indicates an attempt to modify an ended session.
	ErrSessionEnded = errors.New("session has already ended")

	// ErrInvalidRelation indicates an invalid edge relation type.
	ErrInvalidRelation = errors.New("invalid relation type")

	// ErrCircularReference indicates a circular reference in the knowledge graph.
	ErrCircularReference = errors.New("circular reference detected")

	// ErrVectorSearchDisabled indicates that vector search is not available.
	// This happens when the cortex_vectors build tag is not enabled.
	ErrVectorSearchDisabled = errors.New("vector search is disabled - rebuild with cortex_vectors tag")

	// ErrInvalidEmbedding indicates an invalid embedding vector.
	ErrInvalidEmbedding = errors.New("invalid embedding vector")
)

Common domain errors that can be returned by repository implementations.

Functions

func IsConflictError

func IsConflictError(err error) bool

IsConflictError checks if an error is a ConflictError.

func IsNotFoundError

func IsNotFoundError(err error) bool

IsNotFoundError checks if an error is a NotFoundError.

func IsValidationError

func IsValidationError(err error) bool

IsValidationError checks if an error is a ValidationError.

Types

type AggregatedMetrics

type AggregatedMetrics struct {
	TimeRange           *TimeRange `json:"time_range,omitempty"`
	TotalOperations     int        `json:"total_operations"`
	SuccessfulOps       int        `json:"successful_ops"`
	FailedOps           int        `json:"failed_ops"`
	AvgDurationMs       float64    `json:"avg_duration_ms"`
	TotalMemoryUsage    int64      `json:"total_memory_usage"`
	AvgObservationCount float64    `json:"avg_observation_count"`
	AvgEdgeCount        float64    `json:"avg_edge_count"`
	AvgQueryComplexity  float64    `json:"avg_query_complexity"`
	AvgConfidenceScore  float64    `json:"avg_confidence_score"`
	EvaluatedAt         time.Time  `json:"evaluated_at"`
}

AggregatedMetrics represents rolled-up performance metrics for a time range.

type ConflictError

type ConflictError struct {
	Entity string
	Reason string
}

ConflictError wraps ErrConflict with details about the conflict.

func (*ConflictError) Error

func (e *ConflictError) Error() string

func (*ConflictError) Unwrap

func (e *ConflictError) Unwrap() error

type Edge

type Edge struct {
	ID           int64      `json:"id"`
	FromObsID    int64      `json:"from_obs_id"`
	ToObsID      int64      `json:"to_obs_id"`
	RelationType string     `json:"relation_type"`        // references, relates_to, follows
	Weight       float64    `json:"weight"`               // Strength of relationship (0.0 to 10.0, default 1.0)
	Confidence   float64    `json:"confidence"`           // Confidence in this relationship (0.0 to 1.0)
	Source       string     `json:"source,omitempty"`     // Who/what created this edge
	Reasoning    string     `json:"reasoning,omitempty"`  // Why this relationship exists
	ValidFrom    *time.Time `json:"valid_from,omitempty"` // Temporal validity start
	InvalidAt    *time.Time `json:"invalid_at,omitempty"` // Temporal validity end (NULL = still valid)
	CreatedAt    time.Time  `json:"created_at"`

	// Enhanced temporal graph fields
	EvolutionID   *int64 `json:"evolution_id,omitempty"`  // Track edge evolution (NULL = original)
	EvolutionType string `json:"evolution_type"`          // evolution types: original, modified, superseded, contradicted
	FactState     string `json:"fact_state"`              // fact states: current, historical, deprecated, superseded
	ChangeReason  string `json:"change_reason,omitempty"` // Why the edge changed
}

Edge represents a relationship between two observations in the knowledge graph. Edges enable semantic navigation and discovery of related knowledge with temporal awareness.

type EntityLink struct {
	ID            int64     `json:"id"`
	ObservationID int64     `json:"observation_id"`
	EntityType    string    `json:"entity_type"` // file, url, package, symbol, concept
	EntityValue   string    `json:"entity_value"`
	CreatedAt     time.Time `json:"created_at"`
}

EntityLink represents an extracted entity from an observation.

type EntityRepository

type EntityRepository interface {
	// SaveLinks stores extracted entity links for an observation.
	SaveLinks(ctx context.Context, links []*EntityLink) error

	// GetByObservation retrieves all entity links for an observation.
	GetByObservation(ctx context.Context, obsID int64) ([]*EntityLink, error)

	// FindByEntity retrieves observations that reference a given entity.
	FindByEntity(ctx context.Context, entityType, entityValue string) ([]*EntityLink, error)

	// DeleteByObservation removes all entity links for an observation.
	DeleteByObservation(ctx context.Context, obsID int64) error
}

EntityRepository defines the interface for entity linking operations.

type GraphRepository

type GraphRepository interface {
	// CreateEdge creates a relationship between two observations.
	CreateEdge(ctx context.Context, edge *Edge) error

	// GetRelated retrieves observations related to the given observation ID,
	// up to the specified depth (for graph traversal).
	GetRelated(ctx context.Context, obsID int64, depth int) ([]*Observation, error)

	// DeleteEdge removes a relationship between observations.
	DeleteEdge(ctx context.Context, id int64) error

	// GetEdgesForObservation retrieves all edges where the observation is either source or target.
	GetEdgesForObservation(ctx context.Context, obsID int64) ([]*Edge, error)

	// GetEdge retrieves a specific edge by its ID.
	GetEdge(ctx context.Context, id int64) (*Edge, error)

	// GetEvolutionChain retrieves all edges that share the same evolution chain.
	GetEvolutionChain(ctx context.Context, fromObsID, toObsID int64) ([]*Edge, error)

	// CountEdgesByObservation counts edges connected to a specific observation.
	CountEdgesByObservation(ctx context.Context, obsID int64) (int, error)

	// CountAllEdges counts all edges in the system.
	CountAllEdges(ctx context.Context) (int, error)

	// GetContradictions retrieves edges marked as contradictions in a time range.
	GetContradictions(ctx context.Context, from, to time.Time) ([]*Edge, error)

	// UpdateEdge updates an existing edge.
	UpdateEdge(ctx context.Context, edge *Edge) error
}

GraphRepository defines the interface for knowledge graph operations. This enables semantic relationships between observations.

type HealthCheck

type HealthCheck struct {
	Status           string    `json:"status"` // healthy, degraded, critical
	CheckTime        time.Time `json:"check_time"`
	TotalOperations  int       `json:"total_operations"`
	FailedOperations int       `json:"failed_operations"`
	SlowOperations   int       `json:"slow_operations"`
	AvgDurationMs    float64   `json:"avg_duration_ms"`
	Message          string    `json:"message"`
}

HealthCheck represents system health status.

type ImportanceScore

type ImportanceScore struct {
	ObservationID int64     `json:"observation_id"`
	Score         float64   `json:"score"`         // Importance score (0.0 to 5.0)
	AccessCount   int       `json:"access_count"`  // Number of times accessed
	LastAccessed  time.Time `json:"last_accessed"` // Last access timestamp
	UpdatedAt     time.Time `json:"updated_at"`
}

ImportanceScore tracks the importance of an observation based on access patterns, recency, and other metrics.

type Metrics

type Metrics struct {
	ID               int64     `json:"id"`
	SessionID        string    `json:"session_id"`
	OperationType    string    `json:"operation_type"`     // save, search, relate, get_related, etc.
	Duration         int64     `json:"duration_ms"`        // Operation duration in milliseconds
	ResultCount      int       `json:"result_count"`       // Number of results returned
	Success          bool      `json:"success"`            // Whether operation succeeded
	Error            string    `json:"error,omitempty"`    // Error message if failed
	MemoryUsage      int64     `json:"memory_usage_bytes"` // Memory usage in bytes
	Timestamp        time.Time `json:"timestamp"`
	ObservationCount int       `json:"observation_count"` // Total observations in system
	EdgeCount        int       `json:"edge_count"`        // Total edges in knowledge graph
	QueryComplexity  float64   `json:"query_complexity"`  // Estimated query complexity (0.0-1.0)
	ConfidenceScore  float64   `json:"confidence_score"`  // Average confidence score
}

Metrics represents observability metrics for memory system performance.

type MetricsRepository

type MetricsRepository interface {
	// CreateMetric records a performance metric.
	CreateMetric(ctx context.Context, metric *Metrics) error

	// GetTemporalMetrics retrieves metrics for a session within a time range.
	GetTemporalMetrics(ctx context.Context, sessionID string, from, to time.Time) ([]*Metrics, error)

	// GetByOperationType retrieves metrics filtered by operation type.
	GetByOperationType(ctx context.Context, operationType string, from, to time.Time) ([]*Metrics, error)

	// GetAggregatedMetrics gets aggregated metrics for a time range.
	GetAggregatedMetrics(ctx context.Context, from, to time.Time) (*AggregatedMetrics, error)
}

MetricsRepository defines the interface for observability metrics.

type NotFoundError

type NotFoundError struct {
	Type string // "observation", "session", "edge", "prompt"
	ID   interface{}
}

NotFoundError wraps ErrNotFound with context about what was not found.

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

func (*NotFoundError) Unwrap

func (e *NotFoundError) Unwrap() error

type Observation

type Observation struct {
	ID         int64     `json:"id"`
	Title      string    `json:"title"`
	Content    string    `json:"content"`
	Type       string    `json:"type"`    // manual, tool_use, decision, bugfix, etc.
	Project    string    `json:"project"` // Project name or identifier
	Scope      string    `json:"scope"`   // project, personal
	SessionID  string    `json:"session_id"`
	TopicKey   string    `json:"topic_key"`  // Optional topic key for upserts
	Confidence float64   `json:"confidence"` // Confidence score (0.0 to 1.0), default 1.0
	Source     string    `json:"source"`     // Origin: manual, ai, auto, import
	Tags       []string  `json:"tags,omitempty"`
	CreatedAt  time.Time `json:"created_at"`
	UpdatedAt  time.Time `json:"updated_at"`
}

Observation represents a single piece of knowledge or memory captured during an AI coding session. It can be a manual note, tool usage record, decision, bugfix, pattern, or any other type of observation.

type ObservationFilter

type ObservationFilter struct {
	Project         string     `json:"project,omitempty"`
	Scope           string     `json:"scope,omitempty"`
	Type            string     `json:"type,omitempty"`
	Source          string     `json:"source,omitempty"`
	SessionID       string     `json:"session_id,omitempty"`
	Tags            []string   `json:"tags,omitempty"`
	MinConfidence   float64    `json:"min_confidence,omitempty"`
	Limit           int        `json:"limit,omitempty"`
	Offset          int        `json:"offset,omitempty"`
	CreatedBefore   *time.Time `json:"created_before,omitempty"`
	CreatedAfter    *time.Time `json:"created_after,omitempty"`
	OrderAsc        bool       `json:"order_asc,omitempty"`
	IncludeArchived bool       `json:"include_archived,omitempty"`
}

ObservationFilter provides filtering options for listing observations.

type ObservationRepository

type ObservationRepository interface {
	// Save creates a new observation or updates an existing one if it has a topic_key.
	Save(ctx context.Context, obs *Observation) error

	// GetByID retrieves an observation by its ID.
	GetByID(ctx context.Context, id int64) (*Observation, error)

	// GetByTopicKey retrieves an observation by its topic key within a project.
	// Returns ErrNotFound if no matching observation exists.
	GetByTopicKey(ctx context.Context, project, topicKey string) (*Observation, error)

	// Update modifies an existing observation.
	Update(ctx context.Context, obs *Observation) error

	// Delete removes an observation (soft delete by default).
	Delete(ctx context.Context, id int64) error

	// List retrieves observations based on filter criteria.
	List(ctx context.Context, filter ObservationFilter) ([]*Observation, error)

	// CountAll counts all observations in the system.
	CountAll(ctx context.Context) (int, error)

	// CountByRoot counts observations related to a root observation.
	CountByRoot(ctx context.Context, rootObsID int64) (int, error)

	// GetBySource retrieves observations filtered by source type.
	GetBySource(ctx context.Context, source string, limit int) ([]*Observation, error)

	// GetByType retrieves observations filtered by type.
	GetByType(ctx context.Context, obsType string, limit int) ([]*Observation, error)
}

ObservationRepository defines the interface for observation persistence operations. Implementations must handle CRUD operations and support filtering.

type Prompt

type Prompt struct {
	ID        int64     `json:"id"`
	Content   string    `json:"content"`
	Project   string    `json:"project"`
	SessionID string    `json:"session_id"`
	CreatedAt time.Time `json:"created_at"`
}

Prompt represents a user prompt captured during a session for replay and context understanding.

type PromptRepository

type PromptRepository interface {
	// Save stores a user prompt for later retrieval.
	Save(ctx context.Context, prompt *Prompt) error

	// List retrieves recent prompts for a project.
	List(ctx context.Context, project string, limit int) ([]*Prompt, error)
}

PromptRepository defines the interface for user prompt storage.

type QualityMetrics

type QualityMetrics struct {
	ID                   int64     `json:"id"`
	SessionID            string    `json:"session_id"`
	EvaluationType       string    `json:"evaluation_type"`       // relevance, completeness, consistency, temporal_accuracy
	Score                float64   `json:"score"`                 // Score 0.0-1.0
	TotalQueries         int       `json:"total_queries"`         // Number of queries evaluated
	SuccessfulRetrievals int       `json:"successful_retrievals"` // Number of successful retrievals
	AverageLatency       float64   `json:"average_latency_ms"`    // Average response time
	AverageRelevance     float64   `json:"average_relevance"`     // Average relevance score
	TemporalAccuracy     float64   `json:"temporal_accuracy"`     // How well temporal facts are preserved
	KnowledgeCoverage    float64   `json:"knowledge_coverage"`    // How much relevant knowledge is covered
	EvaluatedAt          time.Time `json:"evaluated_at"`
}

QualityMetrics represents memory quality evaluation metrics.

type QualityMetricsRepository

type QualityMetricsRepository interface {
	// CreateQualityMetric records a quality evaluation result.
	CreateQualityMetric(ctx context.Context, quality *QualityMetrics) error

	// GetBySession retrieves quality metrics for a session.
	GetBySession(ctx context.Context, sessionID string, limit int) ([]*QualityMetrics, error)

	// GetByType retrieves quality metrics filtered by evaluation type.
	GetByType(ctx context.Context, evaluationType string, from, to time.Time) ([]*QualityMetrics, error)

	// GetLatest gets the most recent quality metrics.
	GetLatest(ctx context.Context, limit int) ([]*QualityMetrics, error)
}

QualityMetricsRepository defines the interface for quality evaluation.

type ScoringRepository

type ScoringRepository interface {
	// GetScore retrieves the importance score for an observation.
	GetScore(ctx context.Context, obsID int64) (*ImportanceScore, error)

	// UpdateScore adjusts the importance score for an observation.
	// The increment can be positive (increase importance) or negative.
	UpdateScore(ctx context.Context, obsID int64, increment float64) error

	// GetTop retrieves the most important observations for a project.
	GetTop(ctx context.Context, project string, limit int) ([]*ImportanceScore, error)
}

ScoringRepository defines the interface for importance scoring operations. This enables adaptive relevance ranking based on usage patterns.

type SearchOptions

type SearchOptions struct {
	Query       string     `json:"query"`
	Type        string     `json:"type,omitempty"`
	Project     string     `json:"project,omitempty"`
	Scope       string     `json:"scope,omitempty"`
	Limit       int        `json:"limit,omitempty"`
	FusionK     float64    `json:"fusion_k,omitempty"`     // RRF constant (default 60, lower = favor top ranks)
	GraphExpand bool       `json:"graph_expand,omitempty"` // Boost graph neighbors of top results
	AsOf        *time.Time `json:"as_of,omitempty"`        // Temporal point-in-time filter for graph expansion
}

SearchOptions provides options for full-text search queries.

type SearchRepository

type SearchRepository interface {
	// Search performs a full-text search with optional filters.
	Search(ctx context.Context, query string, opts SearchOptions) ([]*SearchResult, error)
}

SearchRepository defines the interface for full-text search operations. Implementations should use FTS5 or similar for efficient text search.

type SearchResult

type SearchResult struct {
	Observation
	Rank           float64              `json:"rank"` // Relevance score from FTS
	ScoreBreakdown SearchScoreBreakdown `json:"score_breakdown,omitempty"`
}

SearchResult represents a search result with relevance ranking.

type SearchScoreBreakdown

type SearchScoreBreakdown struct {
	Strategy       string  `json:"strategy,omitempty"`         // keyword, topic_key, hybrid
	TopicKeyExact  bool    `json:"topic_key_exact,omitempty"`  // exact topic key hit
	TopicKeyExpand bool    `json:"topic_key_expand,omitempty"` // topic key expansion (LIKE match)
	KeywordBM25    float64 `json:"keyword_bm25,omitempty"`     // raw BM25 score for keyword search
	FusionScore    float64 `json:"fusion_score,omitempty"`     // RRF score for hybrid search
	RecencyBoost   float64 `json:"recency_boost,omitempty"`    // recency decay multiplier (0-1)
	ImportanceRank float64 `json:"importance_rank,omitempty"`  // importance score contribution
}

SearchScoreBreakdown explains which retrieval path produced a result.

type Session

type Session struct {
	ID        string     `json:"id"`
	Project   string     `json:"project"`
	Directory string     `json:"directory"`
	StartedAt time.Time  `json:"started_at"`
	EndedAt   *time.Time `json:"ended_at,omitempty"`
	Summary   string     `json:"summary,omitempty"`
}

Session represents a coding session that groups related observations. Sessions track when work started and ended, along with an optional summary.

type SessionRepository

type SessionRepository interface {
	// Create starts a new coding session.
	Create(ctx context.Context, session *Session) error

	// GetByID retrieves a session by its ID.
	GetByID(ctx context.Context, id string) (*Session, error)

	// End marks a session as completed with an optional summary.
	End(ctx context.Context, id string, summary string) error

	// List retrieves sessions for a project, ordered by most recent first.
	List(ctx context.Context, project string) ([]*Session, error)
}

SessionRepository defines the interface for session lifecycle management.

type SystemMetrics

type SystemMetrics struct {
	SessionID          string         `json:"session_id"`
	TimeRange          *TimeRange     `json:"time_range"`
	TotalOperations    int            `json:"total_operations"`
	SuccessfulOps      int            `json:"successful_ops"`
	FailedOps          int            `json:"failed_ops"`
	AvgDurationMs      float64        `json:"avg_duration_ms"`
	TotalMemoryUsage   int64          `json:"total_memory_usage"`
	TotalObservations  int            `json:"total_observations"`
	TotalEdges         int            `json:"total_edges"`
	AvgQueryComplexity float64        `json:"avg_query_complexity"`
	AvgConfidence      float64        `json:"avg_confidence"`
	EvaluatedAt        time.Time      `json:"evaluated_at"`
	OperationBreakdown map[string]int `json:"operation_breakdown"`
	TopSlowOperations  []string       `json:"top_slow_operations"`
}

SystemMetrics represents aggregated system metrics.

type TemporalSnapshot

type TemporalSnapshot struct {
	ID                int64     `json:"id"`
	SnapshotKey       string    `json:"snapshot_key"` // Unique identifier for this snapshot
	Timestamp         time.Time `json:"timestamp"`
	Description       string    `json:"description,omitempty"`
	ObservationCount  int       `json:"observation_count"`
	EdgeCount         int       `json:"edge_count"`
	RootObservationID int64     `json:"root_observation_id,omitempty"` // Root observation for this snapshot
}

TemporalSnapshot represents a point-in-time snapshot of the knowledge graph.

type TemporalSnapshotRepository

type TemporalSnapshotRepository interface {
	// CreateSnapshot creates a point-in-time snapshot of the knowledge graph.
	CreateSnapshot(ctx context.Context, snapshot *TemporalSnapshot) error

	// GetByID retrieves a snapshot by its ID.
	GetByID(ctx context.Context, id int64) (*TemporalSnapshot, error)

	// GetBySnapshotKey retrieves snapshots by their key.
	GetBySnapshotKey(ctx context.Context, snapshotKey string) ([]*TemporalSnapshot, error)

	// GetSnapshotsInRange retrieves snapshots within a time range.
	GetSnapshotsInRange(ctx context.Context, from, to time.Time) ([]*TemporalSnapshot, error)

	// GetByRootObservation retrieves snapshots for a root observation.
	GetByRootObservation(ctx context.Context, rootObsID int64) ([]*TemporalSnapshot, error)
}

TemporalSnapshotRepository defines the interface for temporal snapshots.

type TimeRange

type TimeRange struct {
	From time.Time `json:"from"`
	To   time.Time `json:"to"`
}

TimeRange represents a time range with start and end.

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

ValidationError wraps ErrInvalidInput with details about what failed validation.

func (*ValidationError) Error

func (e *ValidationError) Error() string

func (*ValidationError) Unwrap

func (e *ValidationError) Unwrap() error

type VectorRepository

type VectorRepository interface {
	// StoreEmbedding stores an embedding vector for an observation.
	// The embedding dimensions must be between 64 and 4096.
	// Returns an error if the observation doesn't exist or embedding dimension is wrong.
	StoreEmbedding(ctx context.Context, observationID int64, embedding []float32, model string) error

	// SearchByVector performs a similarity search using the query embedding.
	// Returns results sorted by cosine similarity (descending).
	// Returns ErrVectorSearchDisabled if vector search is not available.
	SearchByVector(ctx context.Context, opts VectorSearchOptions) ([]*VectorSearchResult, error)

	// GetEmbedding retrieves the embedding for an observation.
	// Returns ErrNotFound if no embedding exists for the observation.
	GetEmbedding(ctx context.Context, observationID int64) ([]float32, string, error)

	// DeleteEmbedding removes the embedding for an observation.
	DeleteEmbedding(ctx context.Context, observationID int64) error

	// IsAvailable returns true if vector search is enabled and available.
	IsAvailable() bool
}

VectorRepository defines the interface for vector similarity search operations. This enables semantic search using embeddings with cosine distance.

Note: This is an optional feature that requires the "cortex_vectors" build tag. When not enabled, all methods return ErrVectorSearchDisabled.

type VectorSearchOptions

type VectorSearchOptions struct {
	// Embedding is the query embedding vector (64-4096 dimensions depending on model).
	Embedding []float32
	// Limit is the maximum number of results to return.
	Limit int
	// Threshold is the minimum similarity score (0.0 to 1.0).
	// Results with similarity below this threshold are excluded.
	Threshold float64
	// Project filters results to a specific project (optional).
	Project string
	// Scope filters results to a specific scope (optional).
	Scope string
}

VectorSearchOptions provides options for vector similarity search.

type VectorSearchResult

type VectorSearchResult struct {
	Observation
	Similarity float64 `json:"similarity"` // Cosine similarity score (0.0 to 1.0)
}

VectorSearchResult represents a vector search result with similarity score.

Directories

Path Synopsis
Package dna generates Project DNA — a structured summary of a project's key decisions, patterns, tech stack, and gotchas extracted from observations.
Package dna generates Project DNA — a structured summary of a project's key decisions, patterns, tech stack, and gotchas extracted from observations.
Package entity implements entity extraction and linking for Cortex.
Package entity implements entity extraction and linking for Cortex.
Package graph provides business logic for managing relationships between observations in the knowledge graph.
Package graph provides business logic for managing relationships between observations in the knowledge graph.
Package lifecycle implements auto-archival and lifecycle management for Cortex.
Package lifecycle implements auto-archival and lifecycle management for Cortex.
Package memory provides the business logic layer for observation management.
Package memory provides the business logic layer for observation management.
Package observability provides metrics and quality evaluation for the Cortex memory system.
Package observability provides metrics and quality evaluation for the Cortex memory system.
Package scoring implements the importance scoring business logic for Cortex.
Package scoring implements the importance scoring business logic for Cortex.
Package search provides FTS5-based full-text search business logic for Cortex.
Package search provides FTS5-based full-text search business logic for Cortex.
Package session provides business logic for session management.
Package session provides business logic for session management.
Package temporal provides temporal graph semantics and evolution tracking for the knowledge graph in Cortex.
Package temporal provides temporal graph semantics and evolution tracking for the knowledge graph in Cortex.

Jump to

Keyboard shortcuts

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