cortex

package module
v1.1.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: 26 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.1.0

Install the commands with Go:

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

Prebuilt command archives and checksums are available from the v1.1.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.

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 March original and October implementation paper.

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 MaxRecallMemories = 10000
View Source
const MaxRecallObservations = 20000

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

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

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

func WithEmbedder(embedder Embedder) Option

func WithRetentionPolicy added in v1.0.1

func WithRetentionPolicy(policy RetentionPolicy) 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 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

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