cortex

package module
v1.5.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: 30 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 Go/PostgreSQL memory engine for language agents: Observe, Recall, and Consolidate. It keeps original observations, derives memories with source references, and retrieves current information across sessions.

Inference uses the provider-neutral llm package and a non-streaming OpenAI-compatible /chat/completions endpoint. The default target is Open Agent API with gpt-6-luna-medium.

Current status

The current software release is v1.5.0, an interim milestone with host-checked source selection and improved classifier diagnostics. The release notes record the completed engineering and research work, known limits, and remaining evaluation.

The latest paper is revision 8, Cortex: Sleep-Inspired Memory Consolidation for Language Agents. It reports corrected-source learning curves and fictional memory diagnostics. Classifiers remain advisory: the comparative learning target has not been met, and independent human review is outstanding. Software and paper versions are independent.

  • Implemented: source attribution, transactional consolidation, contradiction history, lexical and optional semantic retrieval, relevance decay, expiry, explicit forgetting, and outcome feedback.
  • Experimental: source-assisted answer generation and locally trained retention and memory-type classifiers. Classifier predictions never change memory state.
  • Supplied by the host: authentication, owner authorization, scheduling, provider permissions, and backup policy.

The evaluation results separate persistence checks from answer quality. This release has not demonstrated parity with other memory platforms or reliable autonomous classification.

Sleep-inspired design

Complementary learning systems and sleep research motivate a separation between rapid capture and slower integration. Observe records attributed source text; Consolidate processes pending observations into reusable memories; Recall retrieves eligible memories with their provenance.

Consolidation runs when the application calls it. A private research prototype tests source-grounded replay and recombined synthetic examples during classifier training. Generated examples stay separate from observed user history. The paper reports this development comparison and its limitations; Cortex does not simulate biological sleep. Relevance decay is an explicit retrieval policy, separate from evidence confidence.

Install

Use the tagged Go package:

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

Install the commands with Go:

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

Prebuilt command archives and checksums are available from the v1.5.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. Release validation uses PostgreSQL 17. The server applies embedded migrations on startup; use a database owned by the embedding application.

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

Core settings for cortex and cortex-once:

Variable Default or requirement
DATABASE_URL Required PostgreSQL connection string
LLM_BASE_URL http://127.0.0.1:8088/v1
LLM_API_KEY Optional bearer token; depends on the provider
CORTEX_MODEL gpt-6-luna-medium
CORTEX_LISTEN 127.0.0.1:8090; HTTP server only

Optional integrations configured by the HTTP server:

Variables Behavior
CORTEX_EMBEDDING_MODEL Enables embeddings; no embedding model is selected by default
CORTEX_EMBEDDING_URL, CORTEX_EMBEDDING_KEY Separate provider base URL and optional bearer token; the URL defaults to http://127.0.0.1:8088/v1
CORTEX_SEGMENTER_URL, CORTEX_SEGMENTER_ID, CORTEX_SEGMENTER_MAX_TOKENS Full segmentation endpoint, identity, and positive token limit; all required when enabling a segmenter
CORTEX_SEGMENTER_KEY Optional segmenter bearer token
CORTEX_CLASSIFIER_URL, CORTEX_CLASSIFIER_MODEL Full classification endpoint and model identity; both required when enabling classification
CORTEX_CLASSIFIER_KEY Optional classifier bearer token

Embedding URLs are base URLs: the client appends /embeddings. Segmenter and classifier URLs include their endpoint paths, such as /v1/segment and /classify. The Go API exposes the same integrations through WithEmbedder, WithWindowSegmenter, and WithClassifier. cortex-once configures only the consolidation model; the HTTP server owns the optional environment integrations.

The application schedules consolidation and maintenance. Model calls made by the commands 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; verify support with another chat provider. The default Open Agent API model alias selects medium reasoning. Cortex has no separate reasoning-effort setting or provider account pool.

Transport failures are not automatically retried. One additional model call per consolidation chunk may repair a successful response that violates its JSON or summary-length contract. format_repairs reports these attempts; a failed repair leaves the chunk pending.

Import and consolidate

cortex-once optionally imports a Claude export, synchronously consolidates pending observations, and prints a profile. The export format is independent of the inference provider. Both local commands support the export structure read by LoadClaudeExport; the API accepts observations from other sources.

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. Rerun the same command to process whatever remains pending. The synchronous command has no --resume or batch-polling mode. 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.

For an API walkthrough with fabricated observations and an explicit correction, see the synthetic example. Example data is separate from private conversation tests.

Host-selected consolidation

The development API adds Engine.ConsolidateSelected for applications that authorize specific observations and memory context. It takes 1–200 unique observation IDs, 0–500 memory IDs, and a required ConsolidationGuard callback. An empty memory selection means no existing memory context. Missing, foreign, inactive or already-processed inputs fail before inference. The complete serialized request must fit within 1 MiB; this path never silently reduces the selection or truncates its content.

The callback runs in two short database transactions, identified by review.Phase: inference before the model call and commit before applying its result. ConsolidationReview includes the run ID, namespace, selected IDs and a SHA-256 hash of the model and messages. Derive the namespace from the authenticated caller and lock the host's applicable permission rows in each callback. Those tables must be reachable through the same PostgreSQL database; they may live in a separate schema. Do not commit, roll back or retain the supplied transaction. The commit-phase locks remain held through the atomic memory changes and observation acknowledgement. ConsolidationPromptHash(model, messages) reproduces the reviewed hash so a host can verify the exact payload before dispatching a queued CLI call.

Avoid calling another Cortex mutation while holding the host's policy locks. Consolidation already holds a namespace lock and may be waiting for those policy rows. Commit revocation first and perform any cleanup afterward; the host's read checks must hide revoked content while cleanup is pending.

This operation calls the selected Model once. It uses Cortex's existing prompts, alias validation and memory operations, with no automatic format repair, chunk splitting, indexing or provider retry. Malformed output, changed input, revoked permission or cancellation leaves the selected observations pending. The result retains the run's selected and resolved model and reported usage.

Persist the run ID from the inference callback before dispatching external work. Store.Consolidation(ctx, namespace, runID) reads its saved outcome without invoking a model. An uncertain result requires reconciliation; calling ConsolidateSelected again can perform new provider work. A crashed process's in-flight run is marked failed when the namespace is next claimed, following the existing consolidation recovery contract.

This is a Go embedding API. It does not add an HTTP route or provide caller authentication, automatic source revocation, or cross-database transactions. The host must also check source access when displaying or recalling a memory.

HTTP

The listener is intended for a trusted host. Use user in query parameters for query-scoped operations, user_id in JSON bodies for body-scoped operations, and the path parameter for profiles. These identifiers do not authenticate a caller. GET search endpoints accept q and limit; mode=lexical explicitly selects lexical retrieval where supported. Profiles default to tier=public; request tier=internal explicitly for the full display. Tier selection is not an authorization boundary.

Method and path Operation
GET /healthz Process health and consolidation prompt version
POST /v1/observations Store {user_id, observations: [...]}
POST /v1/consolidate Consolidate the selected user's pending observations
POST /v1/dream Compatibility alias for synchronous consolidation
GET /v1/recall Ranked current memories
GET /v1/profile/{user} Markdown profile; JSON with Accept: application/json
POST /v1/index Refresh up to 1,000 memory embeddings
GET /v1/observations/recall Retrieve original observations
POST /v1/observations/index Index up to 1,000 original observations
GET /v1/observations/windows Retrieve source excerpts
POST /v1/observations/windows/index Index source windows for up to 1,000 observations
POST /v1/evidence/recall Retrieve across one to four explicit queries
POST /v1/evidence/dates Resolve source-bound date candidates in an explicit timezone
POST /v1/evidence/answer Generate an experimental answer with source quotations
GET /v1/evidence Inspect up to 1,000 sources for the requested memory
POST /v1/classify Return advisory classifications of exact source spans
POST /v1/maintain Archive up to 1,000 expired or low-activation memories
PUT /v1/memories/{id}/retention Set pinned, expires_at, or restore
DELETE /v1/memories/{id} Forget a memory and its connected source lineage
DELETE /v1/observations/{id} Forget an observation and derived memories
POST /v1/signals Store an explicit user-scoped signal
POST /v1/feedback Record idempotent, attributed memory-use feedback

An empty consolidation backlog returns status: "noop". Concurrent consolidation for the same user returns HTTP 409. A failure includes completed runs and the failed run in result. unreferenced_observation_ids lists processed observations that supported no operation; it does not establish that consolidation missed a fact. /v1/dream has the same synchronous behavior and provides no separate sleep process.

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.

Consolidation instructions live in prompts/system.md, prompts/consolidation.md, and prompts/repair.md. Their combined content hash versions the consolidation prompt. The optional evidence reader has separate prompts in evidence_answer.go.

Typed JSON preserves complete observation content, timestamps, and attribution. Request-local aliases reduce identifier-copying errors. Cortex resolves aliases to exact stored IDs before validating and committing operations. Historical memory source lists and observation idempotency keys are omitted from model context; provenance remains in storage.

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.

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.

Feedback accepts id, user_id, memory_id, retrieval_id, used, and an optional boolean success.

The lifecycle and indexing 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. Use WithRetentionPolicy with 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.

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.

Evidence answers

AnswerEvidence and POST /v1/evidence/answer are optional, experimental reader operations. They retrieve source windows, extract exact quotations, and compose an answer with cited fact IDs and any date assumptions. Calling the reader sends selected raw excerpts to the configured language model; the host must authorize that transfer.

After storing observations, submit a question with an explicit timestamp and IANA timezone:

curl --fail-with-body http://127.0.0.1:8090/v1/evidence/answer \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "user_id": "demo-user",
    "question": "What did I say about coffee?",
    "as_of": "2026-10-21T12:00:00-07:00",
    "timezone": "America/Los_Angeles",
    "lexical_only": true
  }'

Use POST /v1/observations/windows/index?user=demo-user to index windows with an embedder. Without embeddings, lexical window retrieval is available; indexing is not required for that mode. The reader does not index or consolidate for you.

The normal path uses three model calls, with at most one additional repair. Empty retrieval can return earlier. It supplies at most 80 excerpts and 32,000 serialized UTF-8 evidence bytes, including metadata. This is a byte limit, not a token limit. The operation never writes observations, memories, embeddings, feedback, or training labels.

The result includes facts, citations, assumptions, calculation, coverage, truncated, index_incomplete, model_calls, and format_repairs. Source eligibility is checked again after composition; an invalidated source causes an error without partial evidence. Exact quotation checks establish source support, while the interpretation remains model-generated.

Date differences use civil days or completed calendar months. Event counts rely on the model's event selections. A response can be conditional; neither an answered status nor untruncated retrieval proves that every relevant event was found. See the reader contract for date rules, query-plan fallback, and failure behavior.

Experimental classifiers

The local training tools fit two classification heads on a pretrained all-MiniLM-L6-v2 sentence encoder:

  • Retention: durable, temporary, ignore, or uncertain.
  • Type: fact, behavior, preference, relationship, project, or routine.

A frozen-encoder baseline trains the heads alone; a SetFit variant adapts the encoder before fitting the same heads. These are task-specific trained parameters built on a third-party encoder. Cortex does not train the external language model used for consolidation, and trained weights are not bundled.

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.

The joint policy abstains below 0.8 retention confidence, for an uncertain retention label, or below 0.8 type confidence on a retained candidate. These are experimental thresholds, not established error guarantees.

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.

Evaluation and benchmarks

The release was checked with PostgreSQL integration tests and Go's race detector, Python contract tests, builds, static analysis, vulnerability checks, and secret scanning. These checks cover the tested persistence and input contracts; they do not establish semantic completeness or general memory quality.

The revision 8 paper reports source audits, corrected-source learning curves, replay experiments, and fictional memory diagnostics. The original private inventory contained 2,814 selected user-role records from 119 sessions and 35 directory groups. Some records contain automatic context, and sessions can span related repositories. User role does not certify human authorship, and directory groups do not establish independent projects. Natural classification labels remain provisional model judgments without independent human review.

Source-assisted answers
Sixty-case LongMemEval sample Direct baseline Source-checked reader
Complete, unconditional answers 44/60 36/60
Conditional answers 1/60 11/60
Reference alignment, including conditional answers 45/60 (75.0%) 47/60 (78.3%)
Normal model-call budget 1 3, plus at most one repair

Both conditions could retrieve original messages. These scores do not isolate consolidated-memory quality. The two-case difference does not establish a reliable advantage, and the comparison did not equalize model-call cost. On the separate twelve-case development set, one run reached 12/12, including four conditional answers; the final repeat reached 11/12. Perfect repeatability has not been demonstrated.

Experimental classifiers

The historical adapted model was evaluated on 363 natural candidates from the original test partition; 310 had type labels. A later audit found machine or mixed authorship in nine test candidates and related-project overlap across partitions. The following frozen scores are diagnostics, not evidence of independent-project transfer. Removing affected test rows alone would not repair affected training.

Measure Adapted model Constant-label accuracy check
Retention agreement 233/363 (64.2%) Always temporary: 253/363 (69.7%)
Type agreement 285/310 (91.9%) Always project: 286/310 (92.3%)
Joint acceptance coverage 45/363 (12.4%) Not evaluated
Errors among accepted predictions 13/45 (28.9%) Not evaluated

Type labels are heavily imbalanced: 286/310 are projects, and the adapted model predicts project for 309/310 inputs. It recovered only 1/37 durable examples. Retention macro-F1 was 0.341; type macro-F1 was 0.160 across all declared classes, including two without test support. The constant-label rows are retrospective accuracy checks, not validated policies. These results do not support autonomous retention or a claim of general six-type classification.

The training tools support optional class balancing, per-class diagnostics, training-majority baselines, and separate reports for human, teacher and synthetic labels. An October 22 development comparison recovered some minority types but left durable-memory recall poor. The default remains unweighted and shadow-only. This experiment reuses previously examined data and supplements the frozen paper; it is not a new independent benchmark. These tools are included in v1.5.0; trained weights remain private.

The replay study used the source filters and connected session/repository components available when its protocol was frozen. The expanded audit finds further training overlap and overlooked automated or mixed-provenance records in both training and evaluation. Its primary cohorts are historical regression diagnostics. It compares ordinary mixed training, repeated examples, paraphrases, and recombinations across three seeds, with three pooled ordinary references. The primary development cohorts contain only 24 older and 18 newer candidates. The generated conditions share source and label schedules with the repeated-example control; all conditions match update counts and padded training dimensions. Generation and review use additional resources. These measurements concern classification agreement, not retention of factual knowledge or unsupported-memory creation. All private training data, provider responses, and trained weights remain outside Git. Neither generated condition met the joint development improvement criteria. A separate 32-candidate API check reproduced saved probabilities and passed twelve invalid-request and source-lifecycle checks without writing memories.

Corrected-source development results

After excluding detected automation and mixed-provenance records, the expanded study uses 5,548 training candidates and 424 development candidates with provisional model labels. Twenty-two pairs of frozen-encoder heads compare source counts and class balancing. The training data form one connected source component; development contains thirty. No independent human labels are available.

Full-source classifier Unweighted Class-balanced
Retention macro-F1 0.393 0.372
Type macro-F1 across six classes 0.256 0.255
Durable examples recovered 0/14 5/14
Joint acceptance coverage 151/424 (35.6%) 28/424 (6.6%)
Disagreements among accepted predictions 14/151 (9.3%) 7/28 (25.0%)

Balanced fitting predicts durable for seventy examples, with sixty-five provisional-label disagreements. Type development data have no behavior or relationship examples and only one routine. These scores do not support an automatic retention policy. Calibration uses the same development set and is optimistic. The aggregate results include class supports, confusion matrices, and source-subset ranges.

Thirty fictional memory episodes show that retrieving original observations can conceal losses from learned source selection. A separate assertion study retains 19/20 required phase-level claims with 0/28 forbidden claims detected. Eight fictional historical-ingestion episodes retain 16/16 required claims with 0/12 forbidden claims detected. These use model judgments, repeated fixtures, and no independent human review; they do not establish safety on natural conversations. The paper records the failures and qualifications.

Comparative benchmark plan

No matched comparison with Mem0, Zep, or Hindsight has been run. Their published scores use different systems and protocols and are reported separately in the paper. A credible comparison needs:

  1. A frozen full 500-question LongMemEval-S run, reporting the 79 previously examined cases separately from the remaining 421.
  2. The same reader and evidence-token budget for retrieval comparisons, with complete-product comparisons reported as a separate track.
  3. Raw-source, consolidated-memory-only, and combined retrieval conditions; repeated answers, case-level failure analysis, cost, and latency measurements.
  4. Independently reviewed classifier labels, class-specific metrics, and fixed acceptance criteria before enabling learned memory mutations.

The replay development study does not complete this benchmark plan. Independent human judgments, fresh component-level confirmation, and downstream memory tests remain necessary. The paper's final protocol specifies the evidence needed for comparative claims.

Papers

The current manuscript is Cortex: Sleep-Inspired Memory Consolidation for Language Agents, paper revision 8. It includes the biological motivation, conditional mathematical proofs, corrected-source learning curves, replay and fictional-memory diagnostics, platform context, and the comparative benchmark protocol.

The proofs concern the stated abstract state machine, not formal verification of the implementation or proof that model-generated memories are true. Only aggregate experimental results are public. Actual conversations, annotations, per-example outputs, model weights, and database exports remain private.

Checks

From the repository root:

go test -race ./...
go vet ./...
go build ./...
python3 -m unittest discover -s tools/classifier -p 'test_*.py'
python3 -m unittest discover -s tools/embeddings -p 'test_*.py'

Database regression tests are skipped unless CORTEX_TEST_DATABASE_URL is set. Use a dedicated disposable PostgreSQL database with schema and extension permissions, never the application's DATABASE_URL:

CORTEX_TEST_DATABASE_URL='postgres://user:pass@localhost/cortex_test?sslmode=disable' \
  go test -race -count=1 ./...

Tests create an isolated schema and remove that schema on completion. Unit and database tests use a fake inference boundary; they do not call a live model. Live model quality is evaluated separately as described above.

GitHub checks also run vulnerability detection and a complete Git-history secret scan. See the release contract for upgrade requirements and the design note for ownership boundaries.

License

MIT. See LICENSE and THIRD_PARTY_NOTICES.md.

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 CalendarMonthsBetween added in v1.4.0

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

CalendarMonthsBetween counts complete calendar months; Jan 31 to Feb 28 is zero, not an assumed fixed number of days. Negative intervals are symmetric.

func ConsolidationPromptHash added in v1.5.0

func ConsolidationPromptHash(model string, messages []llm.Message) (string, error)

ConsolidationPromptHash lets a host verify a queued inference payload against the exact model/messages approved by its guard.

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 AnswerOptions added in v1.4.0

type AnswerOptions struct {
	AsOf        time.Time `json:"as_of"`
	Timezone    string    `json:"timezone"`
	LexicalOnly bool      `json:"lexical_only"`
}

AnswerOptions makes the date anchor and transfer of raw evidence explicit. Calling AnswerEvidence sends selected raw source excerpts to the configured model. It does not consolidate, index, or mutate any memory.

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 ConsolidationGuard added in v1.5.0

type ConsolidationGuard func(context.Context, pgx.Tx, ConsolidationReview) error

ConsolidationGuard must check the host's current source permissions and lock its policy rows until tx ends. It must not commit, roll back, or retain tx. The commit check and memory changes share one PostgreSQL transaction; host policy tables must be reachable from this database connection.

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 ConsolidationReview added in v1.5.0

type ConsolidationReview struct {
	RunID          string
	UserID         string
	Phase          string
	ObservationIDs []string
	MemoryIDs      []string
	PromptHash     string
}

ConsolidationReview identifies the frozen input without exposing source text. Phase is either "inference" or "commit". PromptHash covers the model and the exact serialized messages passed to Model.Complete.

type ConsolidationSelection added in v1.5.0

type ConsolidationSelection struct {
	ObservationIDs []string
	MemoryIDs      []string
}

ConsolidationSelection is an exact allowlist supplied by an authenticated host. Empty MemoryIDs means no existing memory context, never every memory.

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) AnswerEvidence added in v1.4.0

func (e *Engine) AnswerEvidence(ctx context.Context, user, question string, opts AnswerOptions) (out EvidenceAnswer, err error)

AnswerEvidence is an optional bounded reader: plan, retrieve, extract exact quotations, calculate supported date differences/counts, then compose. One malformed successful response may be repaired (at most four model calls). Model interpretations and event identity are not proven by quotation validation.

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) ConsolidateSelected added in v1.5.0

func (e *Engine) ConsolidateSelected(ctx context.Context, userID string, selection ConsolidationSelection, guard ConsolidationGuard) (ConsolidationResult, error)

ConsolidateSelected makes one model call for at most 200 observations and 500 explicitly selected memories. It never splits, truncates, repairs, or retries provider work. Rejected/changed sources leave all observations pending. Guard is required; this library does not authenticate the supplied namespace.

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 EvidenceAnswer added in v1.4.0

type EvidenceAnswer struct {
	Answer            string              `json:"answer"`
	Status            string              `json:"status"`
	Facts             []EvidenceFact      `json:"facts"`
	Citations         []string            `json:"citations"`
	Assumptions       []string            `json:"assumptions,omitempty"`
	Calculation       EvidenceCalculation `json:"calculation"`
	Coverage          string              `json:"coverage"`
	Truncated         bool                `json:"truncated"`
	IndexIncomplete   bool                `json:"index_incomplete"`
	ModelCalls        int                 `json:"model_calls"`
	FormatRepairs     int                 `json:"format_repairs"`
	QueryPlanFallback bool                `json:"query_plan_fallback"`
	Model             string              `json:"model"`
	Tokens            int                 `json:"tokens"`
	EvidenceBytes     int                 `json:"evidence_bytes"`
}

type EvidenceCalculation added in v1.4.0

type EvidenceCalculation struct {
	Operation  string   `json:"operation"`
	FromFact   string   `json:"from_fact,omitempty"`
	ToFact     string   `json:"to_fact,omitempty"`
	ToAsOf     bool     `json:"to_as_of,omitempty"`
	EventFacts []string `json:"event_facts,omitempty"`
	Value      int      `json:"value"`
}

type EvidenceFact added in v1.4.0

type EvidenceFact struct {
	ID             string    `json:"id"`
	SourceID       string    `json:"source_id"`
	Quote          string    `json:"quote"`
	Claim          string    `json:"claim"`
	DateExpression string    `json:"date_expression,omitempty"`
	DateAssumption string    `json:"date_assumption,omitempty"`
	StartRune      int       `json:"start_rune"`
	EndRune        int       `json:"end_rune"`
	ContentHash    string    `json:"content_hash"`
	ObservedAt     time.Time `json:"observed_at"`
	Date           string    `json:"date,omitempty"`
	DateRule       string    `json:"date_rule,omitempty"`
}

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) Consolidation added in v1.5.0

func (s *Store) Consolidation(ctx context.Context, userID, id string) (Consolidation, error)

Consolidation reads one retained outcome in its trusted host-derived scope. A host can reconcile an uncertain response without invoking the model again.

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