cortex

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: MIT Imports: 29 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Cortex

A small PostgreSQL memory engine: Observe, Recall, and Consolidate. Inference uses the provider-neutral llm package and a normal, non-streaming OpenAI-compatible /chat/completions endpoint. The default target is Open Agent API with gpt-6-luna-medium.

Install

Use the tagged Go package:

go get github.com/teslashibe/cortex@v1.3.0

Install the commands with Go:

go install github.com/teslashibe/cortex/cmd/cortex@v1.3.0
go install github.com/teslashibe/cortex/cmd/cortex-import@v1.3.0
go install github.com/teslashibe/cortex/cmd/cortex-once@v1.3.0

Prebuilt command archives and checksums are available from the v1.3.0 release. For the source examples below, clone this repository and run the commands from its root directory.

Run

Requires Go 1.26.10 or newer and PostgreSQL with permission to install pg_trgm.

export DATABASE_URL='postgres://user:pass@localhost/cortex?sslmode=disable'
export LLM_BASE_URL='http://127.0.0.1:8088/v1'
# Set LLM_API_KEY if your gateway requires authentication.
go run ./cmd/cortex

The API binds to 127.0.0.1:8090 by default. It is a trusted-localhost API: it does not authenticate callers or authorize the requested user_id. Database mutations are scoped by user, but that is not an authentication boundary. Do not expose the listener to an untrusted network without an authenticating proxy.

The profile tier filter is a display heuristic, not a privacy or authorization boundary. A trusted caller can request the internal tier or recall unfiltered memories. The embedding application must enforce access and sharing decisions.

Configuration:

  • DATABASE_URL: required PostgreSQL connection string.
  • LLM_BASE_URL: defaults to http://127.0.0.1:8088/v1.
  • LLM_API_KEY: optional bearer token; required only if the gateway requires it.
  • CORTEX_MODEL: defaults to gpt-6-luna-medium.
  • CORTEX_LISTEN: defaults to 127.0.0.1:8090.

There are no Anthropic keys, effort knobs, batch submit/poll workers, or automatic consolidation/decay cron jobs. The application schedules consolidation and maintenance. Model requests have a two-minute timeout and a complete consolidation request has a 30-minute timeout. The adapter sends faithful: false and prewarm: false, which are Open Agent API extensions. Check support before using another chat endpoint. Transport failures are not automatically retried. One additional model call may repair a successful response that violates the JSON or summary-length contract; format_repairs reports these attempts. If repair fails, the chunk remains pending.

Import and consolidate

The existing cortex-once command name is retained. It optionally imports a Claude export, synchronously consolidates pending observations, and prints a profile. The export format is independent of the inference provider.

go run ./cmd/cortex-once --dir /path/to/claude-export --user demo-user --tier internal
# Consolidate already-imported observations without another import:
go run ./cmd/cortex-once --user demo-user --chunk 100 --by-day

--chunk is a maximum observation count (1–200, default 200). --by-day keeps UTC days separate while preserving chronological processing. Each chunk sees the memories committed by earlier chunks. --resume, polling, and batch-specific flags are removed; rerun the same command to process whatever remains pending. cortex-import remains available for importing through the HTTP API. Both import commands default to the default user scope; pass --user explicitly when keeping separate histories.

HTTP

  • POST /v1/observations: JSON {user_id, observations: [...]}.
  • GET /v1/recall?user=&q=&limit=: ranked, current memories; no automatic feedback writes.
  • GET /v1/observations/recall?user=&q=&limit=: original evidence, separate from validated memories.
  • POST /v1/observations/index?user=: opt-in raw observation embeddings, 1,000 per call.
  • DELETE /v1/observations/{id}?user=: forget an observation and derived memories, including when consolidation retained nothing.
  • POST /v1/consolidate?user=: synchronous consolidation, returning saved run IDs and counts. unreferenced_observation_ids lists processed observations that supported no operation; it does not prove those observations contained a missed fact. An empty backlog returns status: "noop"; a concurrent request for the same user returns HTTP 409. Partial failure includes already-completed runs and the failed run in result.
  • POST /v1/dream?user=: compatibility alias for the same synchronous handler. The old batch response and force semantics are not retained.
  • GET /v1/profile/{user}?tier=public|internal: Markdown, or JSON when requested with Accept: application/json.
  • POST /v1/signals: explicit feedback, with user-scoped memory validation.
  • GET /healthz: health and embedded prompt version.

Consolidation safety and semantics

A PostgreSQL connection advisory lock serializes consolidation per user across processes. The locked connection remains reserved during inference, but no transaction remains open during a network call. This requires a direct PostgreSQL connection or session-pooling proxy; transaction-pooling proxies are not supported. The lock releases automatically if the database connection dies. Hash collisions can conservatively serialize two unrelated users, never mix their data.

The consolidations table records each chunk's exact observation IDs, model, prompt-content hash, status, counts, and error. Applying all operations, acknowledging those exact observation IDs, and completing the run happens in one transaction. Re-completing an already completed run is a no-op. An explicit empty ops array is a valid completion; malformed envelopes, unknown fields, duplicate JSON keys, nulls, invalid IDs, or invalid confidence values reject the whole chunk. Fact mutations require sources from that chunk; memory references must belong to the same user and still be current.

A crash before commit leaves observations pending. On the next request, after acquiring the user lock, an interrupted running row is marked failed and its observations are eligible again. A retry can make another inference request, but cannot apply a completed chunk twice. There is no persistent queue or background retry loop. Successfully completed earlier chunks are retained if a later chunk fails. New arrivals are handled on the next request, not acknowledged by a time cutoff. A request selects at most 20,000 observations.

Serialized context is capped at 1 MiB and chunks shrink to fit without truncating observation content. Consolidation considers at most 500 memories selected by lexical overlap, pinning and evidence recency; context_limited reports when the set is a subset. It never truncates an individual observation. If one full observation plus the selected context still exceeds the budget, the operation fails visibly. Exact retrieval and consolidation support at most 10,000 active memories per user and fail explicitly beyond that limit.

All model-facing instructions live in prompts/system.md and prompts/consolidation.md and prompts/repair.md. Typed JSON carries complete observations and current memories, including IDs, timestamps, user/sender references, and source IDs. Prompt versioning is derived from the contents of all three embedded Markdown files.

New and reinforced memories preserve observation provenance. Contradictions create a replacement and retain the old memory as history; contradicted and expired memories are excluded from both current recall and profiles. Evidence confidence does not automatically decay with age. Relevance does decay, with a 90-day base half-life and reinforcement-based preservation. With an embedder configured, recall fuses lexical and exact cosine ranks. There is no fuzzy auto-merge that might erase distinct facts; the model explicitly reinforces existing IDs.

Observation idempotency keys are unique within each user. Generated IDs include the user while import/API idempotency keys remain compatible with legacy imports, so repeated imports of the same payload remain no-ops. Migration 003 preserves all prior migration files and historical data, retires only legacy in-flight batch rows as failed, and never acknowledges their observations.

Retrieve original evidence when needed

Recall returns validated memories. RecallObservations returns original observations with their speaker metadata and timestamps. Call the second method explicitly when an answer needs evidence that consolidation may have omitted. Raw evidence can contain quotations, assistant suggestions or outdated details; it must not be treated as a validated fact or as instructions.

// Send raw text to the configured embedder only after the host authorizes it.
index, err := engine.IndexObservations(ctx, userID, 1000)
_ = index // If Incomplete, call again to index the next bounded batch.
if err != nil { return err }
evidence, err := engine.RecallObservations(ctx, userID, question,
    cortex.RecallOptions{Limit: 5})
_ = evidence // Enforce a reader budget and preserve source attribution.

Without an embedder, observation search is lexical. Set LexicalOnly: true to request this explicitly when a configured provider is unavailable. The exact scan rejects sets above 20,000 eligible observations. Sources supporting a superseded, archived or expired memory are excluded, even if shared with another fact. Use ForgetObservation to remove an unretained source; deleting it also removes exact-content copies, derived memories and associated vectors.

Retrieve bounded source excerpts

Use source windows when a whole observation would consume too much reader context:

_, err := engine.IndexObservationWindows(ctx, userID, 1000)
if err != nil { return err }
windows, err := engine.RecallObservationWindows(ctx, userID, question,
    cortex.RecallOptions{Limit: 8})
_ = windows

Each hit has exact text, parent observation ID, half-open Unicode code-point positions, speaker references, and observed_at. This timestamp is the message time; event dates need evidence from its text. Windows contain at most 512 code points with 128 overlap by default. These are character bounds, not token bounds: choose an encoder that accepts them without truncation, or configure WithWindowSegmenter. A user's full eligible window set is capped at 100,000. Token-aware coverage is checked as segmentation results arrive; an invalid or over-capacity result prevents vector publication.

POST /v1/observations/windows/index?user= explicitly indexes this representation. GET /v1/observations/windows?user=&q=&limit= returns excerpts; mode=lexical selects lexical-only retrieval. Existing whole-observation routes are unchanged. Window indexing reports complete observations indexed, while recall reports indexed windows. Index publication is atomic per observation and deletion cascades to every window. The same lifecycle and owner checks apply to both source paths.

The optional HTTPSegmenter uses an exact tokenizer service. Set CORTEX_SEGMENTER_URL, CORTEX_SEGMENTER_ID, and CORTEX_SEGMENTER_MAX_TOKENS (plus CORTEX_SEGMENTER_KEY if needed). Cortex validates full source coverage, original offsets, progress, and declared token counts. The embedding service must independently reject oversized inputs; Cortex cannot verify a remote tokenizer's claim. Vector namespaces include segmentation identity, so changing the tokenizer or policy requires reindexing. An optional local ONNX adapter performs both segmentation and strict embedding checks with one tokenizer. Configured segmentation sends sources to that endpoint during window recall too.

Retrieve events and resolve dates

RecallEvidence merges one to four explicit query variants, deduplicates windows, and rechecks source eligibility. POST /v1/evidence/recall accepts {"user_id":"example","queries":["museum visit","gallery trip"],"limit":40}. Results include truncated, index_incomplete, and changed_during_read. The sources count is a count of retrieved observations, not distinct real events. The host owns query generation, event identity, corrections, and evidence budgets. Even an untruncated result reports coverage: "retrieved_evidence_only".

ResolveEventDates and POST /v1/evidence/dates accept an explicit IANA timezone and exact source-span candidates, using the same candidate shape as classification. Supported expressions are ISO or English dates with a year, today, yesterday, N days ago, and last <weekday> (strictly before the observation's local date). Other expressions return resolved: false. Results preserve the text, source hash, rule and observation timestamp. Resolving a quoted or hypothetical date does not establish that an event occurred. CalendarDaysBetween subtracts civil dates, avoiding daylight-saving errors. No event records are written automatically.

Train and inspect a classifier

The optional Classifier interface accepts exact candidate spans. Configure it with WithClassifier, or set CORTEX_CLASSIFIER_URL and CORTEX_CLASSIFIER_MODEL for the HTTP adapter. POST /v1/classify accepts:

{"user_id":"example","candidates":[{"id":"candidate-1","observation_id":"source-id","start_rune":0,"end_rune":24}]}

The source must exist in that user's eligible observations. Spans are at most 512 code points; requests contain at most 128 candidates. Results separate retention (durable, temporary, ignore, uncertain) from the six memory kinds. They include all class probabilities, model and policy versions, and source hashes. Probabilities do not replace evidence confidence.

Classification is shadow-only. It never changes memories or stores training examples. Source eligibility is checked again after inference. The host owns extraction, annotation review, private journals, and any later adoption decision. See the classifier workflow for local baseline and SetFit training, data partitioning, calibration, and a provisional labeling tool. Actual sessions, labels, model artifacts, and per-example evaluations belong outside Git. A deleted source must also be removed from any host-managed exports; source deletion does not erase information from separately trained weights.

Checks

go test ./...
go vet ./...
go build ./...
# Optional: a dedicated disposable test database, never DATABASE_URL.
CORTEX_TEST_DATABASE_URL='postgres://user:pass@localhost/cortex_test?sslmode=disable' go test ./...

Database regression tests are skipped unless CORTEX_TEST_DATABASE_URL is explicitly set. They create an isolated schema and remove only that schema on completion. Use a dedicated test database with schema/extension permissions. Tests use a fake inference boundary; they do not call a live model.

See the synthetic walkthrough for sample observations and the design note for the storage and inference boundaries.

License

MIT. See LICENSE and THIRD_PARTY_NOTICES.md.

Semantic retrieval and lifecycle

Embeddings are optional. Configure CORTEX_EMBEDDING_URL, CORTEX_EMBEDDING_MODEL, and optionally CORTEX_EMBEDDING_KEY to use a standard OpenAI-compatible /embeddings service. The chat gateway and embedding service can be different providers. No model weights or vector extension are bundled. Embeddings are stored as PostgreSQL arrays and searched by exact cosine distance within the bounded active set. An approximate index is not required.

The Go API accepts WithEmbedder(embedder) and WithRetentionPolicy(policy) options on NewEngine. An embedder implements Model() string and Embed(context.Context, []string) ([][]float64, error). Use a model identifier that includes the weights and preprocessing version.

Successful consolidation attempts a bounded embedding refresh. Its index result reports incomplete indexing without rolling back committed facts. POST /v1/index?user=... retries missing embeddings. Recall returns its mode, indexed count and incomplete flag. A provider error does not silently downgrade to lexical search; request mode=lexical explicitly when a fallback is wanted.

Additional operations:

  • POST /v1/maintain?user=...: archive up to 1,000 expired or low-activation memories.
  • PUT /v1/memories/{id}/retention?user=...: set pinned, expires_at, and restore.
  • DELETE /v1/memories/{id}?user=...: forget a memory and its connected source lineage.
  • POST /v1/feedback: record id, user_id, memory_id, retrieval_id, used, and optional boolean success.
  • GET /v1/evidence?user=...&memory=...: inspect up to 1,000 supporting observations.

The corresponding Go methods are Maintain, SetRetention, Forget, Feedback, Evidence, Index, and RecallWithOptions. An identical feedback event ID can be retried; a changed event with the same user-scoped ID is rejected. Only a used memory with a known outcome changes utility. Reads and unused results do not train it. This is an inspectable running estimate, not a learned model.

Decay changes relevance, not evidence confidence. The default policy archives unpinned memories below 0.05 activation once they are at least 30 days old, when Maintain is called. Set a zero half-life to disable age decay. Explicit expiry applies to pinned memories too. Archive preserves evidence and can be restored.

Forgetting is permanent. It removes connected contradiction versions and any memories sharing source observations, so forgetting one fact from a multi-fact observation can remove several facts. It deletes those source observations and related embeddings and feedback. User-scoped hashes suppress identical content or idempotency keys on reimport. Reworded new evidence is not semantic-matched against a deleted secret. Previously sent provider prompts cannot be recalled.

Migration 004 preserves existing facts and derives evidence dates from their sources where available. Upgrade all writers before enabling forgetting or maintenance. Older binaries can write data without these new policies.

Papers

See the academic manuscript, source, and historical papers.

Documentation

Index

Constants

View Source
const (
	DefaultChunkSize                = 200
	MaxObservationsPerConsolidation = DefaultChunkSize * 100
	MaxContextBytes                 = 1024 * 1024
	MaxSummaryCharacters            = 512
	ConsolidationTimeout            = 30 * time.Minute
	ModelTimeout                    = 2 * time.Minute
)
View Source
const ClassificationPolicyVersion = "cortex-candidate-v1"
View Source
const MaxClassificationCandidates = 128
View Source
const MaxObservationWindows = 100000
View Source
const MaxRecallMemories = 10000
View Source
const MaxRecallObservations = 20000
View Source
const ObservationWindowOverlap = 128
View Source
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

View Source
var ErrConsolidationBusy = errors.New("consolidation already running for user")
View Source
var ErrMemoryNotFound = errors.New("memory not found for user")
View Source
var ErrNoObservations = errors.New("no unconsolidated observations")
View Source
var ErrObservationCapacity = errors.New("observation set exceeds exact retrieval capacity")
View Source
var ErrRecallCapacity = errors.New("active memory set exceeds exact retrieval capacity; archive memories before recalling")
View Source
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

func CalendarDaysBetween(from, to string) (int, error)

CalendarDaysBetween subtracts civil dates, independently of DST day length.

func Migrations

func Migrations() fs.FS

Migrations is the embedded SQL migration set rooted at "migrations". Pass directly to (*Store).ApplyMigrations.

func ObservationID

func ObservationID(sender, text, createdAt, conversationUUID string) string

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 API

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

func NewAPI

func NewAPI(e *Engine) *API

func (*API) Routes

func (a *API) Routes() *http.ServeMux

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 CandidateDecision struct {
	Candidate   Candidate                `json:"candidate"`
	ContentHash string                   `json:"content_hash"`
	Retention   string                   `json:"retention"`
	Kind        Kind                     `json:"kind"`
	Abstain     bool                     `json:"abstain"`
	Prediction  ClassificationPrediction `json:"prediction"`
}

type ClassificationInput added in v1.2.0

type ClassificationInput struct {
	ID         string         `json:"id"`
	Text       string         `json:"text"`
	Context    string         `json:"context"`
	Source     string         `json:"source"`
	Refs       map[string]any `json:"refs"`
	ObservedAt string         `json:"observed_at"`
}

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 ConsolidationCounts struct {
	ObservationsProcessed int `json:"observations_processed"`
	MemoriesCreated       int `json:"memories_created"`
	MemoriesReinforced    int `json:"memories_reinforced"`
	TokensUsed            int `json:"tokens_used"`
}

type ConsolidationOptions

type ConsolidationOptions struct {
	ChunkSize int
	ByDay     bool
}

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

type Embedder interface {
	Model() string
	Embed(context.Context, []string) ([][]float64, error)
}

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 NewEngine

func NewEngine(store *Store, model Model, options ...Option) *Engine

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

func (e *Engine) Evidence(ctx context.Context, user, id string) ([]Observation, error)

Evidence returns source observations for one memory in the same user scope.

func (*Engine) Feedback added in v1.0.1

func (e *Engine) Feedback(ctx context.Context, f Feedback) error

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

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

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

func (e *Engine) ForgetObservation(ctx context.Context, user, id string) (ForgetResult, error)

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

func (e *Engine) Index(ctx context.Context, user string, limit int) (IndexResult, error)

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

func (e *Engine) Memories(ctx context.Context, userID string) ([]Memory, error)

func (*Engine) Observe

func (e *Engine) Observe(ctx context.Context, obs []Observation) (int, error)

Observe writes a batch of raw observations, idempotently within each user.

func (*Engine) Profile

func (e *Engine) Profile(ctx context.Context, userID, tier string) (string, error)

func (*Engine) Recall

func (e *Engine) Recall(ctx context.Context, userID, query string, limit int) ([]Hit, error)

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 (e *Engine) ResolveEventDates(ctx context.Context, user, zone string, candidates []Candidate) ([]EventDate, error)

func (*Engine) SetRetention added in v1.0.1

func (e *Engine) SetRetention(ctx context.Context, user, id string, r Retention) error

func (*Engine) WriteSignal

func (e *Engine) WriteSignal(ctx context.Context, signal Signal) error

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 Feedback added in v1.0.1

type Feedback struct {
	ID          string `json:"id"`
	UserID      string `json:"user_id"`
	MemoryID    string `json:"memory_id"`
	RetrievalID string `json:"retrieval_id"`
	Used        bool   `json:"used"`
	Success     *bool  `json:"success,omitempty"`
}

type ForgetResult added in v1.0.1

type ForgetResult struct {
	Memories     int `json:"memories"`
	Observations int `json:"observations"`
}

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 (*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 Hit

type Hit struct {
	Memory Memory
	Score  float64
}

type IndexResult added in v1.0.1

type IndexResult struct {
	Indexed    int  `json:"indexed"`
	Incomplete bool `json:"incomplete"`
}

type Kind

type Kind string
const (
	KindFact         Kind = "fact"
	KindBehavior     Kind = "behavior"
	KindPreference   Kind = "preference"
	KindRelationship Kind = "relationship"
	KindProject      Kind = "project"
	KindRoutine      Kind = "routine"
)

func (Kind) Valid

func (k Kind) Valid() bool

type MaintenanceResult added in v1.0.1

type MaintenanceResult struct {
	Examined int  `json:"examined"`
	Archived int  `json:"archived"`
	More     bool `json:"more"`
}

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 Op

type Op struct {
	Kind    OpKind
	Memory  Memory
	OldID   string
	Reason  string
	Sources []string
}

type OpKind

type OpKind string
const (
	OpInsert     OpKind = "insert"
	OpReinforce  OpKind = "reinforce"
	OpContradict OpKind = "contradict"
)

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 WithEmbedder(embedder Embedder) Option

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 RecallOptions struct {
	Limit       int
	LexicalOnly bool
}

type RecallResult added in v1.0.1

type RecallResult struct {
	Hits       []Hit  `json:"hits"`
	Mode       string `json:"mode"`
	Indexed    int    `json:"indexed"`
	Candidates int    `json:"candidates"`
	Incomplete bool   `json:"incomplete"`
}

type Retention added in v1.0.1

type Retention struct {
	Pinned    bool       `json:"pinned"`
	ExpiresAt *time.Time `json:"expires_at,omitempty"`
	Restore   bool       `json:"restore"`
}

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 SegmentInput struct {
	ID   string `json:"id"`
	Text string `json:"text"`
}

type SegmentSpan added in v1.3.0

type SegmentSpan struct {
	StartRune int `json:"start_rune"`
	EndRune   int `json:"end_rune"`
	Tokens    int `json:"tokens"`
}

type SegmentedText added in v1.3.0

type SegmentedText struct {
	ID      string        `json:"id"`
	Windows []SegmentSpan `json:"windows"`
}

type Signal

type Signal struct {
	ID          string
	UserID      string
	MemoryID    string
	SignalType  string
	SignalValue float64
	Metadata    map[string]any
}

type Store

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

func NewStore

func NewStore(ctx context.Context, dsn string) (*Store, error)

func (*Store) ApplyMigrations

func (s *Store) ApplyMigrations(ctx context.Context, fsys fs.FS) error

func (*Store) Close

func (s *Store) Close()

func (*Store) Memories

func (s *Store) Memories(ctx context.Context, userID string) ([]Memory, error)

func (*Store) RecallByText

func (s *Store) RecallByText(ctx context.Context, userID, query string, limit int) ([]Memory, error)

func (*Store) WriteObservations

func (s *Store) WriteObservations(ctx context.Context, obs []Observation) (int, error)

func (*Store) WriteSignal

func (s *Store) WriteSignal(ctx context.Context, sig Signal) error

type WindowHit added in v1.2.0

type WindowHit struct {
	Window     ObservationWindow `json:"window"`
	Source     string            `json:"source"`
	Refs       map[string]any    `json:"refs"`
	ObservedAt string            `json:"observed_at"`
	Score      float64           `json:"score"`
}

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.

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.

Jump to

Keyboard shortcuts

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