Documentation
¶
Index ¶
- Constants
- Variables
- func Activation(m Memory, at time.Time, p RetentionPolicy) float64
- func CalendarDaysBetween(from, to string) (int, error)
- func Migrations() fs.FS
- func ObservationID(sender, text, createdAt, conversationUUID string) string
- func ResolveDateExpression(expression string, anchor time.Time, zone string) (string, string, error)
- type API
- type Candidate
- type CandidateDecision
- type ClassificationInput
- type ClassificationPrediction
- type ClassificationResult
- type Classifier
- type Consolidation
- type ConsolidationCounts
- type ConsolidationOptions
- type ConsolidationResult
- type Embedder
- type Engine
- func (e *Engine) ClassifyCandidates(ctx context.Context, user string, candidates []Candidate) (ClassificationResult, error)
- func (e *Engine) Consolidate(ctx context.Context, userID string, opts ConsolidationOptions) (ConsolidationResult, error)
- func (e *Engine) Evidence(ctx context.Context, user, id string) ([]Observation, error)
- func (e *Engine) Feedback(ctx context.Context, f Feedback) error
- func (e *Engine) Forget(ctx context.Context, user, id string) (ForgetResult, error)
- func (e *Engine) ForgetObservation(ctx context.Context, user, id string) (ForgetResult, error)
- func (e *Engine) Index(ctx context.Context, user string, limit int) (IndexResult, error)
- func (e *Engine) IndexObservationWindows(ctx context.Context, user string, limit int) (IndexResult, error)
- func (e *Engine) IndexObservations(ctx context.Context, user string, limit int) (IndexResult, error)
- func (e *Engine) Maintain(ctx context.Context, user string, at time.Time, limit int) (MaintenanceResult, error)
- func (e *Engine) Memories(ctx context.Context, userID string) ([]Memory, error)
- func (e *Engine) Observe(ctx context.Context, obs []Observation) (int, error)
- func (e *Engine) Profile(ctx context.Context, userID, tier string) (string, error)
- func (e *Engine) Recall(ctx context.Context, userID, query string, limit int) ([]Hit, error)
- func (e *Engine) RecallEvidence(ctx context.Context, user string, queries []string, opts RecallOptions) (EvidenceRecallResult, error)
- func (e *Engine) RecallObservationWindows(ctx context.Context, user, query string, opts RecallOptions) (WindowRecallResult, error)
- func (e *Engine) RecallObservations(ctx context.Context, user, query string, opts RecallOptions) (ObservationRecallResult, error)
- func (e *Engine) RecallWithOptions(ctx context.Context, user, query string, opts RecallOptions) (RecallResult, error)
- func (e *Engine) ResolveEventDates(ctx context.Context, user, zone string, candidates []Candidate) ([]EventDate, error)
- func (e *Engine) SetRetention(ctx context.Context, user, id string, r Retention) error
- func (e *Engine) WriteSignal(ctx context.Context, signal Signal) error
- type EventDate
- type EvidenceRecallResult
- type Feedback
- type ForgetResult
- type HTTPClassifier
- type HTTPSegmenter
- type Hit
- type IndexResult
- type Kind
- type MaintenanceResult
- type Memory
- type Model
- type Observation
- type ObservationHit
- type ObservationInput
- type ObservationRecallResult
- type ObservationWindow
- type Op
- type OpKind
- type Option
- type RecallOptions
- type RecallResult
- type Retention
- type RetentionPolicy
- type SegmentInput
- type SegmentSpan
- type SegmentedText
- type Signal
- type Store
- func (s *Store) ApplyMigrations(ctx context.Context, fsys fs.FS) error
- func (s *Store) Close()
- func (s *Store) Memories(ctx context.Context, userID string) ([]Memory, error)
- func (s *Store) RecallByText(ctx context.Context, userID, query string, limit int) ([]Memory, error)
- func (s *Store) WriteObservations(ctx context.Context, obs []Observation) (int, error)
- func (s *Store) WriteSignal(ctx context.Context, sig Signal) error
- type WindowHit
- type WindowRecallResult
- type WindowSegmenter
Constants ¶
const ( DefaultChunkSize = 200 MaxObservationsPerConsolidation = DefaultChunkSize * 100 MaxContextBytes = 1024 * 1024 MaxSummaryCharacters = 512 ConsolidationTimeout = 30 * time.Minute ModelTimeout = 2 * time.Minute )
const ClassificationPolicyVersion = "cortex-candidate-v1"
const MaxClassificationCandidates = 128
const MaxObservationWindows = 100000
const MaxRecallMemories = 10000
const MaxRecallObservations = 20000
const ObservationWindowOverlap = 128
const ObservationWindowSize = 512
These are Unicode code-point bounds, not tokenizer limits. An embedding provider must accept 512 code points without truncation or use a compatible preprocessing contract identified by Embedder.Model().
Variables ¶
var ErrConsolidationBusy = errors.New("consolidation already running for user")
var ErrMemoryNotFound = errors.New("memory not found for user")
var ErrNoObservations = errors.New("no unconsolidated observations")
var ErrObservationCapacity = errors.New("observation set exceeds exact retrieval capacity")
var ErrRecallCapacity = errors.New("active memory set exceeds exact retrieval capacity; archive memories before recalling")
var ErrWindowCapacity = errors.New("observation window capacity exceeded")
Functions ¶
func Activation ¶ added in v1.0.1
func Activation(m Memory, at time.Time, p RetentionPolicy) float64
Activation is a deterministic relevance multiplier. Reading never changes it.
func CalendarDaysBetween ¶ added in v1.3.0
CalendarDaysBetween subtracts civil dates, independently of DST day length.
func Migrations ¶
Migrations is the embedded SQL migration set rooted at "migrations". Pass directly to (*Store).ApplyMigrations.
func ObservationID ¶
func ResolveDateExpression ¶ added in v1.3.0
func ResolveDateExpression(expression string, anchor time.Time, zone string) (string, string, error)
ResolveDateExpression supports explicit ISO/English dates, today, yesterday, N days ago and last <weekday>. Last weekday means strictly before the anchor. Ambiguous week/month expressions and dates without a year remain unresolved.
Types ¶
type Candidate ¶ added in v1.2.0
type Candidate struct {
ID string `json:"id"`
ObservationID string `json:"observation_id"`
StartRune int `json:"start_rune"`
EndRune int `json:"end_rune"`
}
A candidate identifies an exact, preferably atomic, source span. Extraction and review belong to the caller. Offsets count Unicode code points.
type CandidateDecision ¶ added in v1.2.0
type ClassificationInput ¶ added in v1.2.0
type ClassificationPrediction ¶ added in v1.2.0
type ClassificationPrediction struct {
ID string `json:"id"`
Retention map[string]float64 `json:"retention"`
Kind map[string]float64 `json:"kind"`
}
Probabilities are model estimates, not evidence confidence. Calibration must be measured on independent labels before setting an operational threshold.
type ClassificationResult ¶ added in v1.2.0
type ClassificationResult struct {
Mode string `json:"mode"`
Model string `json:"model"`
PolicyVersion string `json:"policy_version"`
Decisions []CandidateDecision `json:"decisions"`
}
type Classifier ¶ added in v1.2.0
type Classifier interface {
Model() string
Classify(context.Context, []ClassificationInput) ([]ClassificationPrediction, error)
}
type Consolidation ¶
type Consolidation struct {
ID string `json:"id"`
UserID string `json:"user_id"`
Status string `json:"status"`
ObservationIDs []string `json:"observation_ids"`
Model string `json:"model"`
ResolvedModel string `json:"resolved_model,omitempty"`
PromptVersion string `json:"prompt_version"`
StartedAt time.Time `json:"started_at"`
CompletedAt *time.Time `json:"completed_at,omitempty"`
Counts ConsolidationCounts `json:"counts"`
ErrorMessage string `json:"error_message,omitempty"`
}
Consolidation tracks one saved, bounded chunk of work.
type ConsolidationCounts ¶
type ConsolidationOptions ¶
type ConsolidationResult ¶
type ConsolidationResult struct {
Runs []Consolidation `json:"runs"`
Counts ConsolidationCounts `json:"counts"`
ContextLimited bool `json:"context_limited"`
Index *IndexResult `json:"index,omitempty"`
// UnreferencedObservationIDs lists completed observations that supported no
// operation. These may be irrelevant or ambiguous, not necessarily missed facts.
UnreferencedObservationIDs []string `json:"unreferenced_observation_ids,omitempty"`
FormatRepairs int `json:"format_repairs,omitempty"`
}
type Embedder ¶ added in v1.0.1
Embedder is an optional provider-neutral boundary. Model must identify both weights and preprocessing; changing either requires a new model identifier.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
func (*Engine) ClassifyCandidates ¶ added in v1.2.0
func (e *Engine) ClassifyCandidates(ctx context.Context, user string, candidates []Candidate) (ClassificationResult, error)
ClassifyCandidates is deliberately shadow-only: no operation is applied and no training data is stored. The host may keep this report in a private journal. Deleted, changed, or ineligible source evidence invalidates the whole response.
func (*Engine) Consolidate ¶
func (e *Engine) Consolidate(ctx context.Context, userID string, opts ConsolidationOptions) (ConsolidationResult, error)
Consolidate processes the pending snapshot sequentially. Successful chunks remain committed if a later chunk fails; retries select only pending work.
func (*Engine) Evidence ¶ added in v1.0.1
Evidence returns source observations for one memory in the same user scope.
func (*Engine) Feedback ¶ added in v1.0.1
Feedback records an explicit application outcome. A shown/unused result or an unknown outcome changes no utility. An identical event ID is a safe retry.
func (*Engine) Forget ¶ added in v1.0.1
Forget removes a memory, connected versions and memories sharing its evidence. Whole source observations are removed, so a multi-fact source can remove more than one memory. One-way import tombstones prevent exact evidence replay.
func (*Engine) ForgetObservation ¶ added in v1.1.0
ForgetObservation removes original evidence even when consolidation retained no memory for it. Derived memories and exact-content copies are removed too. A missing observation is already forgotten and returns an empty result.
func (*Engine) Index ¶ added in v1.0.1
Index refreshes a bounded batch of missing embeddings. Inference occurs outside transactions. Publication rechecks content and current status, so a concurrent correction or forget cannot publish a stale vector.
func (*Engine) IndexObservationWindows ¶ added in v1.2.0
func (e *Engine) IndexObservationWindows(ctx context.Context, user string, limit int) (IndexResult, error)
IndexObservationWindows is a separate explicit consent boundary for sending raw evidence to an embedder. A complete observation is published atomically. Indexed counts observations; limit never slices an observation's windows.
func (*Engine) IndexObservations ¶ added in v1.1.0
func (e *Engine) IndexObservations(ctx context.Context, user string, limit int) (IndexResult, error)
IndexObservations is opt-in and separate from Index: enabling memory embeddings does not automatically send raw conversations to an embedding provider.
func (*Engine) Maintain ¶ added in v1.0.1
func (e *Engine) Maintain(ctx context.Context, user string, at time.Time, limit int) (MaintenanceResult, error)
Maintain archives at most limit eligible memories. Expiry takes precedence over pinning. No raw evidence is deleted by relevance-based maintenance.
func (*Engine) RecallEvidence ¶ added in v1.3.0
func (e *Engine) RecallEvidence(ctx context.Context, user string, queries []string, opts RecallOptions) (EvidenceRecallResult, error)
RecallEvidence merges up to four caller-supplied query variants. The host owns query generation and event identity. It does not infer either here.
func (*Engine) RecallObservationWindows ¶ added in v1.2.0
func (e *Engine) RecallObservationWindows(ctx context.Context, user, query string, opts RecallOptions) (WindowRecallResult, error)
RecallObservationWindows returns excerpts with original offsets and source attribution. ObservedAt is message time, never an inferred event date. Lifecycle eligibility is rechecked after external inference, as in raw recall.
func (*Engine) RecallObservations ¶ added in v1.1.0
func (e *Engine) RecallObservations(ctx context.Context, user, query string, opts RecallOptions) (ObservationRecallResult, error)
RecallObservations searches original evidence without turning it into a fact. It preserves attribution and does not change Recall's memory-only contract. The host must evaluate speaker, timestamp and uncertainty before using a hit.
func (*Engine) RecallWithOptions ¶ added in v1.0.1
func (e *Engine) RecallWithOptions(ctx context.Context, user, query string, opts RecallOptions) (RecallResult, error)
RecallWithOptions fuses lexical and exact cosine ranks. The bounded exact scan avoids a mandatory vector extension or another database. No writes or automatic feedback occur during recall. Embedding failure is an error; an application may explicitly retry with LexicalOnly.
func (*Engine) ResolveEventDates ¶ added in v1.3.0
func (*Engine) SetRetention ¶ added in v1.0.1
type EventDate ¶ added in v1.3.0
type EventDate struct {
Candidate Candidate `json:"candidate"`
Text string `json:"text"`
Date string `json:"date,omitempty"`
Rule string `json:"rule,omitempty"`
Resolved bool `json:"resolved"`
ObservedAt time.Time `json:"observed_at"`
Timezone string `json:"timezone"`
ContentHash string `json:"content_hash"`
}
EventDate retains the exact source span and the rule used to resolve it. Resolved means the date expression was parsed, not that the event occurred.
type EvidenceRecallResult ¶ added in v1.3.0
type EvidenceRecallResult struct {
Hits []WindowHit `json:"hits"`
Queries int `json:"queries"`
Sources int `json:"sources"`
Truncated bool `json:"truncated"`
IndexIncomplete bool `json:"index_incomplete"`
ChangedDuringRead bool `json:"changed_during_read"`
Coverage string `json:"coverage"`
}
EvidenceRecallResult describes retrieved evidence, not an exhaustive event inventory. Multiple windows or messages may describe the same real event.
type ForgetResult ¶ added in v1.0.1
type HTTPClassifier ¶ added in v1.2.0
type HTTPClassifier struct {
// contains filtered or unexported fields
}
HTTPClassifier adapts an optional host-supplied classifier service. It does not load weights, train, retry, or send data until ClassifyCandidates is called.
func NewHTTPClassifier ¶ added in v1.2.0
func NewHTTPClassifier(endpoint, model, key string) (*HTTPClassifier, error)
func (*HTTPClassifier) Classify ¶ added in v1.2.0
func (c *HTTPClassifier) Classify(ctx context.Context, inputs []ClassificationInput) ([]ClassificationPrediction, error)
func (*HTTPClassifier) Model ¶ added in v1.2.0
func (c *HTTPClassifier) Model() string
type HTTPSegmenter ¶ added in v1.3.0
type HTTPSegmenter struct {
// contains filtered or unexported fields
}
func NewHTTPSegmenter ¶ added in v1.3.0
func NewHTTPSegmenter(endpoint, id, key string, maxTokens int) (*HTTPSegmenter, error)
func (*HTTPSegmenter) ID ¶ added in v1.3.0
func (c *HTTPSegmenter) ID() string
func (*HTTPSegmenter) MaxTokens ¶ added in v1.3.0
func (c *HTTPSegmenter) MaxTokens() int
func (*HTTPSegmenter) Split ¶ added in v1.3.0
func (c *HTTPSegmenter) Split(ctx context.Context, inputs []SegmentInput) ([]SegmentedText, error)
type IndexResult ¶ added in v1.0.1
type MaintenanceResult ¶ added in v1.0.1
type Memory ¶
type Memory struct {
ID string `json:"id"`
UserID string `json:"user_id"`
Kind Kind `json:"kind"`
Summary string `json:"summary"`
Confidence float64 `json:"confidence"`
ReinforcedCount int `json:"reinforced_count"`
BornAt time.Time `json:"born_at"`
LastSeenAt time.Time `json:"last_seen_at"`
ContradictedBy string `json:"contradicted_by,omitempty"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
Sources []string `json:"sources"`
ArchivedAt *time.Time `json:"archived_at,omitempty"`
Pinned bool `json:"pinned"`
Utility float64 `json:"utility"`
OutcomeCount int `json:"outcome_count"`
}
type Model ¶
type Model interface {
Complete(context.Context, []llm.Message) (llm.Response, error)
Model() string
}
Model is the inference boundary; production uses llm.Client.
type Observation ¶
type Observation struct {
ID string `json:"id"`
UserID string `json:"user_id"`
Source string `json:"source"`
Content string `json:"content"`
Refs map[string]any `json:"refs"`
Salience float64 `json:"salience"`
At time.Time `json:"at"`
IdempotencyKey string `json:"idempotency_key"`
ToolName string `json:"tool_name,omitempty"`
IntentID string `json:"intent_id,omitempty"`
OutcomeClass string `json:"outcome_class,omitempty"`
TurnIndex *int `json:"turn_index,omitempty"`
}
func LoadClaudeExport ¶
func LoadClaudeExport(dir, userID string) ([]Observation, int, error)
LoadClaudeExport reads conversations.json + design_chats/*.json from a Claude.ai export directory and returns them flattened into Observations for the given user. Idempotency keys are deterministic so re-imports insert nothing.
type ObservationHit ¶ added in v1.1.0
type ObservationHit struct {
Observation Observation `json:"observation"`
Score float64 `json:"score"`
}
type ObservationInput ¶
type ObservationInput struct {
Sender string `json:"sender"`
Source string `json:"source"`
Content string `json:"content"`
At time.Time `json:"at"`
ConversationUUID string `json:"conversation_uuid"`
ConversationName string `json:"conversation_name"`
Refs map[string]any `json:"refs"`
ToolName string `json:"tool_name,omitempty"`
IntentID string `json:"intent_id,omitempty"`
OutcomeClass string `json:"outcome_class,omitempty"`
TurnIndex *int `json:"turn_index,omitempty"`
}
ObservationInput is the wire shape for POST /v1/observations. Shared between the API and cortex-import; one source of truth keeps the JSON schema in sync across processes.
func (ObservationInput) ToObservation ¶
func (p ObservationInput) ToObservation(userID string) Observation
ToObservation builds the canonical internal Observation, computing the deterministic ID + idempotency key from (sender, content, at, conversation).
type ObservationRecallResult ¶ added in v1.1.0
type ObservationRecallResult struct {
Hits []ObservationHit `json:"hits"`
Mode string `json:"mode"`
Indexed int `json:"indexed"`
Candidates int `json:"candidates"`
Incomplete bool `json:"incomplete"`
}
type ObservationWindow ¶ added in v1.2.0
type ObservationWindow struct {
ObservationID string `json:"observation_id"`
StartRune int `json:"start_rune"`
EndRune int `json:"end_rune"`
Text string `json:"text"`
}
func SplitObservation ¶ added in v1.2.0
func SplitObservation(o Observation) ([]ObservationWindow, error)
SplitObservation covers the entire input with deterministic overlapping windows. Offsets are half-open Unicode code-point offsets in original text.
type Option ¶ added in v1.0.1
type Option func(*Engine)
func WithClassifier ¶ added in v1.2.0
func WithClassifier(classifier Classifier) Option
func WithEmbedder ¶ added in v1.0.1
func WithRetentionPolicy ¶ added in v1.0.1
func WithRetentionPolicy(policy RetentionPolicy) Option
func WithWindowSegmenter ¶ added in v1.3.0
func WithWindowSegmenter(segmenter WindowSegmenter) Option
type RecallOptions ¶ added in v1.0.1
type RecallResult ¶ added in v1.0.1
type RetentionPolicy ¶ added in v1.0.1
type RetentionPolicy struct {
HalfLife time.Duration `json:"half_life"`
ArchiveBelow float64 `json:"archive_below"`
MinAge time.Duration `json:"min_age"`
}
RetentionPolicy controls relevance, not the truth of the underlying evidence. A zero HalfLife disables time decay. Maintenance is always an explicit call.
func DefaultRetentionPolicy ¶ added in v1.0.1
func DefaultRetentionPolicy() RetentionPolicy
type SegmentInput ¶ added in v1.3.0
type SegmentSpan ¶ added in v1.3.0
type SegmentedText ¶ added in v1.3.0
type SegmentedText struct {
ID string `json:"id"`
Windows []SegmentSpan `json:"windows"`
}
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
func (*Store) ApplyMigrations ¶
func (*Store) RecallByText ¶
func (*Store) WriteObservations ¶
type WindowRecallResult ¶ added in v1.2.0
type WindowRecallResult struct {
Hits []WindowHit `json:"hits"`
Mode string `json:"mode"`
Indexed int `json:"indexed"`
Candidates int `json:"candidates"`
Incomplete bool `json:"incomplete"`
Segmentation string `json:"segmentation,omitempty"`
Matched int `json:"matched"`
Truncated bool `json:"truncated"`
}
type WindowSegmenter ¶ added in v1.3.0
type WindowSegmenter interface {
ID() string
MaxTokens() int
Split(context.Context, []SegmentInput) ([]SegmentedText, error)
}
WindowSegmenter uses the embedding provider's exact tokenizer, including special tokens. Its identity must change with tokenizer or window policy. Returned offsets refer to the original Unicode text, never a decoded copy. The embedding provider must independently reject inputs beyond its limit.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
cortex
command
|
|
|
cortex-import
command
|
|
|
cortex-once
command
|
|
|
Package llm provides a small client for an OpenAI-compatible chat endpoint.
|
Package llm provides a small client for an OpenAI-compatible chat endpoint. |
|
Package prompts embeds the human-reviewable memory consolidation prompts.
|
Package prompts embeds the human-reviewable memory consolidation prompts. |