memstore

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 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

memstore

CI Docker Go Report Card License Go Version codecov

Persistent memory system for AI agents with hybrid semantic search, cross-encoder reranking, fact supersession, and cross-session task tracking.

Multi-user isolation (v0.4.0). Memstore enforces per-user isolation end to end. Every read and write -- facts, links, sessions, hints, and feedback -- is filtered by the user the bearer token belongs to; two tokens for two users never see each other's data. A fresh PostgreSQL deployment runs memstore admin tier3-init --default-user <name> once to seed identity; an existing single-user deployment upgrades automatically (the default user is inferred from your token names). See docs/MIGRATING.md for the upgrade path.

Quick Start

# Install binaries
go install github.com/matthewjhunter/memstore/cmd/memstore@latest
go install github.com/matthewjhunter/memstore/cmd/memstore-mcp@latest

# Pull an embedding model. Any Ollama or OpenAI-compatible embedding model
# works (nomic-embed-text, embeddinggemma, mxbai-embed-large, etc.). The
# chosen model and its vector dimension are locked on first use, so pick
# one and stick with it. See "Installation" for the env vars.
ollama pull nomic-embed-text

# Set up everything: hooks, MCP registration, config
memstore setup

memstore setup detects your environment, installs Claude Code hooks, registers the MCP server, and creates a config file. Run it again after updating to deploy the latest hooks. See docs/installation.md for manual setup and troubleshooting.

Other harnesses. memstore-mcp is a standard MCP stdio server and works in any host that speaks MCP. The Taskfile has per-harness installers:

task install:claude     # Claude Code: hooks + MCP (calls memstore setup)
task install:cursor     # Cursor: writes ~/.cursor/mcp.json
task install:zed        # Zed: prints settings.json snippet (manual paste)
task install:codex      # Codex: installs experimental notify shim + prints config.toml snippet
task install:harnesses  # run all of the above

Only Claude Code has a full hook lifecycle; the others get tools-only or an experimental adapter (Codex). See examples/codex/README.md for the Codex caveats.

What It Does

Memstore gives AI agents durable memory that persists across sessions. It stores facts with automatic vector embeddings, enabling hybrid full-text and semantic search with an optional cross-encoder rerank pass. Facts form supersession chains -- when knowledge evolves, the old version is preserved in history while the new version takes precedence. An integrated task system with startup surfacing ensures pending work survives session boundaries.

Two deployment shapes: a local-only mode where the CLI library uses SQLite directly, and a daemon mode where memstored exposes the store over HTTPS for multiple clients (typically one human's machines).

Key Features

  • Three-stage search: BM25 full-text, cosine-similarity vector search, and optional cross-encoder reranking with four fusion modes
  • Runtime-tunable retrieval via memory_rerank_settings -- the model can adjust mode, threshold, candidate pool sizes, and doc-byte budgets per session
  • Fact supersession chains with full history preservation
  • Automatic embedding via go-embedding (model + dimension locked on first use; quarantines permanent embed failures)
  • Per-prompt context injection via the UserPromptSubmit hook + /v1/recall endpoint
  • Session capture pipeline (turns, hooks, hints, injections, feedback) that feeds back into recall ranking
  • Auto-rating of injected facts at session end -- self-improving recall
  • Temporal decay with per-category half-life tuning
  • Task tracking with scoped ownership (user / agent / collaborative)
  • Startup surfacing for pending tasks across sessions
  • Namespace isolation for multi-instance deployments
  • Metadata filtering with typed operators (=, !=, <, <=, >, >=)
  • LLM-based fact extraction with auto-deduplication and auto-supersession
  • Fact linking with directed graph edges and neighbor traversal
  • Context curation and injection feedback
  • Native TLS with optional mTLS for the daemon; bearer-token auth with hashed storage and constant-time comparison
  • Export/import for backup and migration (embeddings excluded; regenerated on import)

Architecture

Claude Code
  ├── Hooks (7 scripts)              ← context injection + event capture
  │     ├── SessionStart             ← inject tasks + project facts
  │     ├── UserPromptSubmit         ← recall facts on every prompt
  │     ├── PreToolUse (Read/Edit)   ← inject file/symbol constraints
  │     ├── PostToolUse (Write/Bash) ← nudge to store decisions
  │     ├── Stop                     ← session tracking + transcript upload
  │     └── SessionEnd               ← record activity + task reminders
  │
  └── MCP Server (23 tools)          ← stdio
        │
        ├─ Local mode ──→ SQLite + embedder endpoint
        │                   ├─ Facts table
        │                   ├─ FTS5 index
        │                   ├─ Vector embeddings (sqlite-vec)
        │                   └─ Schema migrations
        │
        └─ Daemon mode ──→ memstored (HTTPS API)
                            ├─ /v1/health, /v1/recall, /v1/search, ...
                            ├─ Postgres + pgvector + tsvector
                            ├─ Async embed queue
                            ├─ Session capture pipeline
                            └─ Optional cross-encoder rerank sidecar

The MCP server exposes the store as tools over stdio. Hooks run alongside Claude Code to inject relevant context and capture session events. In daemon mode, hooks and the MCP server both talk to memstored over HTTPS with bearer-token auth.

The Store interface (store.go) separates the storage engine from the MCP layer, so memstore can also be used as a Go library directly. See docs/architecture.md for a detailed breakdown.

MCP Tools

Tool Description
memory_store Store a fact with automatic embedding and optional supersession
memory_store_batch Store multiple facts in a single call (max 20 per batch)
memory_search Hybrid full-text + semantic search with ranked results
memory_list Browse facts by subject and category without a query
memory_delete Delete a fact by ID (prefer supersession for history preservation)
memory_supersede Mark an existing fact as replaced by a newer one
memory_history Show the supersession chain for a fact or all facts for a subject
memory_confirm Increment a fact's confirmation count to signal verified accuracy
memory_update Merge a metadata patch into a fact without replacing it
memory_status Show active fact count with breakdown by subject and category
memory_task_create Create a scoped task with priority, project, and due date
memory_task_update Transition a task's status (pending / in_progress / completed / cancelled)
memory_task_list List tasks filtered by scope, status, and project
memory_link Create a directed graph edge between two facts
memory_unlink Remove a link by ID
memory_get_links Get all links touching a fact with neighbor summaries
memory_update_link Update a link's label and metadata
memory_list_subsystems List all distinct subsystem values in the store
memory_get_context Load relevant context for a task (invariants, failure modes, search)
memory_curate_context Filter candidate facts to the most relevant subset for a task
memory_suggest_agent Recommend specialist agents based on stored domain mappings
memory_rate_context Rate injected context usefulness (feeds injection ranking)
memory_rerank_settings Get/set per-session retrieval tunables (mode, threshold, candidates, doc bytes)

Hooks

Hooks wire memstore into Claude Code's session lifecycle so context surfaces automatically. They are embedded in the memstore binary and installed by memstore setup.

Hook Event Purpose
memstore-startup.mjs SessionStart Inject pending tasks and project facts
memstore-prompt.mjs UserPromptSubmit Recall relevant facts for each prompt
memstore-read.mjs PreToolUse:Read Inject file/symbol constraints before reads
memstore-edit.mjs PreToolUse:Edit Inject file/symbol constraints before edits
store-nudge.mjs PostToolUse:Write/Bash Nudge to store decisions after key actions
stop-hook.mjs Stop Track sessions, upload transcripts
memstore-session-end.mjs SessionEnd Remind about open tasks

Hooks that communicate with memstored (prompt recall, context touch, stop hook) silently no-op when the daemon is unavailable, so they are safe to install in local-only mode.

Daemon Mode

For lower-latency context injection, multi-machine access, and background processing (session capture, hint generation, feedback rating), run memstored:

go install github.com/matthewjhunter/memstore/cmd/memstored@latest

# Required: Postgres with pgvector and an embedder endpoint
export MEMSTORE_PG_SECRET='postgres://memstore:secret@host:5432/memstore?sslmode=require'
export MEMSTORE_EMBED_BACKEND=ollama
export MEMSTORE_EMBED_BASE_URL=http://localhost:11434
export MEMSTORE_EMBED_MODEL=nomic-embed-text

# Optional: TLS + mTLS
memstore tls init-ca
memstore tls issue-server --host memstored.lan
memstored --tls-cert server.crt --tls-key server.key

# Optional: cross-encoder reranker (separate sidecar)
export MEMSTORE_RERANK_BASE_URL=http://reranker:8080
export MEMSTORE_RERANK_MODEL=bge-reranker-v2-m3

Tokens for clients are issued via memstore admin issue --name <client>. Each plaintext token is shown once; the daemon stores SHA-256 hashes and verifies with constant-time comparison.

The daemon exposes:

  • /v1/health (unauthenticated liveness)
  • /v1/recall (per-prompt context injection)
  • /v1/search, /v1/facts/* (full Store interface)
  • /v1/context/hints (proactive nudges queued by background extractors)
  • /v1/sessions/turns/* (session capture pipeline)

memstore setup auto-detects a running daemon and configures hooks accordingly. Without the daemon, memstore operates in local-only mode using the CLI binary for hook operations.

Container image is published to GHCR on every push to main.

Installation

go install github.com/matthewjhunter/memstore/cmd/memstore-mcp@latest
go install github.com/matthewjhunter/memstore/cmd/memstore@latest

Prerequisites: an OpenAI-compatible or Ollama embedding endpoint. Locally, Ollama with an embedding model pulled is the simplest:

ollama pull nomic-embed-text

Embedding configuration is read from environment variables via go-embedding -- set MEMSTORE_EMBED_BACKEND, MEMSTORE_EMBED_BASE_URL, and MEMSTORE_EMBED_MODEL (or the shared EMBEDDING_* defaults) before launching memstore-mcp or memstored. A separate generator endpoint can be wired via MEMSTORE_GEN_URL and MEMSTORE_GEN_MODEL.

Then run memstore setup to configure everything, or see docs/installation.md for manual setup.

For upgrading from a previous release, see docs/MIGRATING.md.

Usage

An AI agent stores, searches, and evolves facts through the MCP tools:

# Store a fact
memory_store(
  content="Matthew prefers small, logical commits -- never bundle unrelated changes",
  subject="matthew",
  category="preference"
)
→ Stored (id=42, subject="matthew", category="preference").

# Search for related facts
memory_search(query="matthew commit style", limit=5)
→ [1] (id=42, score=0.847, rerank=0.915) matthew | preference
      Matthew prefers small, logical commits -- never bundle unrelated changes

# Correct the fact when knowledge changes
memory_store(
  content="Matthew prefers small commits and squashes fixup commits before merging",
  subject="matthew",
  category="preference",
  supersedes=42
)
→ Stored (id=43, ...). Superseded fact 42.

# Retrieve the full history
memory_history(id=43)
→ [1/2] (id=42) SUPERSEDED by 43 | 2026-01-10
      Matthew prefers small, logical commits -- never bundle unrelated changes
  [2/2] (id=43) ACTIVE | 2026-02-15
      Matthew prefers small commits and squashes fixup commits before merging

When rerank is enabled, results include a rerank=N.NNN score alongside the first-stage score. The model can adjust the rerank policy with memory_rerank_settings.

Search runs three stages: two parallel first-stage passes that get merged, then an optional cross-encoder rerank.

  1. FTS full-text search -- in SQLite, FTS5 with BM25; in Postgres, tsvector with ts_rank_cd. Each query word is individually double-quoted to prevent FTS syntax injection. Raw scores are normalized to [0, 1] per query (min-max) so they're comparable to cosine.

  2. Vector search -- the query is embedded via the configured embedder (or fetched from the in-memory cache on the daemon for repeat prompts), then cosine similarity is computed against every stored embedding. In Postgres, an HNSW index over the vector(N) column bounds the latency cost.

  3. Score merging -- facts appearing in both result sets are deduplicated. The combined first-stage score is:

    combined = (FTSWeight * fts_score) + (VecWeight * vec_score)
    

    Default weights: FTS 0.6, vector 0.4. Weights are configurable per query.

  4. Cross-encoder reranking (optional) -- the top-K candidates from the first stage are sent to a reranker sidecar (llama.cpp with --reranking, Cohere/Jina wire shape). Raw logits → sigmoid → [0, 1]. Four fusion modes:

    • off: no rerank, first-stage order
    • balanced: weighted blend of rerank + first-stage (default 0.7)
    • dominant: rerank drives order, first-stage breaks ties only
    • gate: first-stage order, rerank only filters by threshold

    A relevance threshold drops candidates below the cutoff in any enabled mode. The rerank stage gracefully degrades to first-stage order if the sidecar is unreachable.

  5. Temporal decay -- an optional exponential decay can be applied per category. The MCP server configures note facts with a 30-day half-life; preference and identity facts do not decay.

SearchBatch amortizes embedding cost across multiple queries by making a single batched embedding call instead of one per query.

Supersession

Facts form linked chains. When knowledge evolves, the old version is preserved in history and the new version becomes active:

fact 42 (SUPERSEDED → 43)  "Matthew prefers small, logical commits"
        ↓
fact 43 (ACTIVE)            "Matthew prefers small commits and squashes fixup commits before merging"

Explicit supersession -- pass supersedes=<id> to memory_store, or call memory_supersede after storing the replacement separately.

Automatic supersession -- the FactExtractor pipeline embeds each new fact immediately after insert, then searches for same-subject active facts. If cosine similarity reaches the 0.85 threshold, the closest match is automatically superseded. A metadata conflict check prevents facts from different contexts (different projects, sources, etc.) from superseding each other across context boundaries.

memory_history walks the full chain in either direction -- useful for auditing how a piece of knowledge has changed over time.

Documentation

License

MIT

Documentation

Overview

Package memstore provides a shared fact/knowledge store with FTS5 hybrid search and vector embeddings, backed by SQLite. The caller provides the *sql.DB; memstore creates its own namespaced tables (memstore_*).

Embedder

memstore relies on github.com/matthewjhunter/go-embedding for the Embedder interface and embedding helpers (Single, EmbedWithRetry, CosineSimilarity, EncodeFloat32s, DecodeFloat32s). Construct an embedder with embedding.New(cfg), taking cfg from EmbedConfigFromEnv so the strict-model default and the MEMSTORE_EMBED_* cascade apply consistently across binaries.

Conventions

Relationship facts are directional: a fact like "Alice trusts Bob" with Subject "Alice" is only indexed under Alice. Searching for "Bob" depends on FTS matching "Bob" in the content text, which is fragile.

To ensure reliable lookup from either side of a relationship, store both directions at insert time:

{Content: "Alice trusts Bob",        Subject: "Alice", Category: "relationship"}
{Content: "Bob is trusted by Alice", Subject: "Bob",   Category: "relationship"}

This gives each direction its own FTS entry and embedding, so searches from either subject work naturally. The caller controls the inverse phrasing, which varies by relationship type.

Index

Constants

View Source
const (
	// ChunkTargetTokens is the size chunks aim for, in tokens.
	//
	// Tokens rather than bytes because that is the unit chunk size is reasoned
	// about in, and the bytes-per-token ratio varies by model and by corpus.
	// go-embedding converts it through the ratio it has actually observed for
	// the model (BudgetForTokens), falling back to a conservative figure until
	// enough has been seen.
	ChunkTargetTokens = 512
	// ChunkOverlapBytes repeats the tail of each chunk at the head of the
	// next, so a boundary landing mid-argument does not strand the two halves
	// in vectors that each describe half a thought.
	ChunkOverlapBytes = 128
	// ChunkMinBytes absorbs a trailing sliver into its predecessor. A few
	// words on their own embed to a vector that matches almost nothing.
	ChunkMinBytes = 200
)

Chunk sizing for fact embeddings.

These are retrieval targets, deliberately far below the models' registered budgets (nomic-embed-text and embeddinggemma are both 6000 bytes). A vector has fixed capacity, so filling the whole context window averages away the specificity retrieval depends on; 256-512 tokens per chunk is the usual working range. go-embedding's Split defaults to the model budget because that is the only figure it knows, and documents that the caller should pass something smaller -- this is memstore passing it.

Keeping the target separate from the backend ceiling matters: the ceiling exists so a request is not rejected, and the two answer different questions. Deriving chunk size from the ceiling means raising the ceiling silently widens every chunk and quietly degrades retrieval, with nothing reporting it (see matthewjhunter/herald#297).

View Source
const (
	// ScopeRead permits reads: fetching, listing, searching, recall.
	ScopeRead = "read"
	// ScopeWrite permits mutating facts, links, sessions, and context.
	ScopeWrite = "write"
	// ScopeAdmin permits administrative operations, and implies read and write.
	ScopeAdmin = "admin"
	// ScopeIngest permits writing to the document corpus. It is implied by no
	// other scope, including admin, and must always be granted explicitly.
	ScopeIngest = "ingest"
)

Token scopes. These name the authority a credential carries, and are the canonical spelling for both ends: pgstore stores them on api_tokens rows and validates them at issuance, httpapi enforces them per route. They live here because the root package is the one both of those already depend on.

What each scope implies -- and, for ingest, what it deliberately does not -- is documented on httpapi.Identity.Allows, which is where the decision is made.

View Source
const (
	// DefaultRerankCandidates is the rerank shortlist size used when rerank is
	// enabled but SearchOpts.RerankCandidates is unset.
	DefaultRerankCandidates = 40
	// DefaultRerankWeight is rerank's fusion share used in RerankBalanced when
	// SearchOpts.RerankWeight is unset.
	DefaultRerankWeight = 0.7
	// DefaultRerankThreshold is the relevance floor applied when none is
	// configured: a reranked fact scoring below it is dropped rather than
	// padding the result set.
	//
	// Without a floor, hybrid search returns its top N no matter how badly they
	// score, and once recalled content is in the context window a weak match is
	// indistinguishable from a strong one -- there is no score attached to the
	// model's memory of having read something (#163).
	//
	// The value is calibrated against the live corpus rather than guessed.
	// Normalized rerank scores are sharply bimodal there: genuine matches scored
	// 0.38-0.88, pure nonsense 1.7e-5 to 4.3e-5. 0.05 sits roughly three orders
	// of magnitude above the noise and an order below the weakest real hit, so
	// it is not a knife-edge in either direction. The first-stage Combined score
	// separates the same two cases by only ~5x, which is why the floor keys on
	// the rerank score instead.
	DefaultRerankThreshold = 0.05
	// DefaultRerankDocBytes is the per-document truncation budget for the search
	// path when SearchOpts.RerankDocBytes is unset. Rerank cost is superlinear in
	// document length, so search caps each candidate at ~700 tokens of lead
	// content (a fact's subject and decision usually sit up front) to keep a
	// 40-candidate pass within a few seconds on CPU. The recall path sets its own
	// tighter budget for its per-prompt latency target.
	DefaultRerankDocBytes = 2800
)

Rerank knobs applied when a reranker is configured but the matching SearchOpts field is left at its zero value. RerankCandidates follows the homelab design's latency guidance (rescore a shortlist of 30-50, not the whole result set); RerankWeight defaults rerank-leaning but not absolute, so the cross-encoder dominates ordering while the first-stage score still breaks ties and hedges a noisy rerank.

View Source
const (
	RefTypeFact = "fact" // a memstore fact ID
	RefTypeTurn = "turn" // a session turn UUID
	RefTypeHint = "hint" // a context_hints row ID
)

RefType constants for ContextFeedback and RecordInjection.

View Source
const (
	RerankDroppedHeader    = "X-Memstore-Rerank-Dropped"
	RerankTopDroppedHeader = "X-Memstore-Rerank-Top-Dropped"
)

Relevance-floor telemetry headers, carried on the /v1/search response. They ride on the response rather than in it because /v1/search returns a bare JSON array and is a documented public surface: wrapping it in an envelope to carry two numbers would break every existing consumer (#170).

They live here, not in httpapi, so the client can name them without importing the server package.

View Source
const DefaultDetectReadScore = 86

DefaultDetectReadScore is the score at which a read is withheld, and it is deliberately above the write threshold.

airlock combines evidence per category as 100*(1 - product of (1 - weight)), with a high-severity hit weighted 0.80. So a score of exactly 80 is one high-severity rule and nothing else; 86 is that plus a medium-severity hit in another category, and 96 is two independent high hits. The bar here therefore means "a high-severity hit corroborated by at least a medium one".

That is not arbitrary. Scanning the live corpus -- 5,790 active facts -- found 3 scoring 80 and nothing at all between 1 and 79. All three were false positives, and two were among the most operationally valuable facts in the store: a design decision record and a debugging runbook. Blocking reads at 80 would have withheld them silently and caught nothing.

View Source
const EmbedEnvPrefix = "MEMSTORE_EMBED"

EmbedEnvPrefix is the namespace memstore reads its embedder config from. go-embedding cascades MEMSTORE_EMBED_* -> EMBEDDING_* -> defaults.

View Source
const InlineRejectScore = 80

InlineRejectScore is the detect aggregate at which an inline screen rejects a write. 80 is a single high-severity rule in airlock's corpus; corroboration across categories scores higher.

View Source
const MaxContentLength = 8000

MaxContentLength bounds Fact.Content. Enforced at the DB level by both pgstore and sqlite stores.

It used to be sized against the embedding model's context window, because a fact was one vector over its whole content and anything longer was silently truncated. Chunking removed that constraint: content past the chunk target is split rather than clipped, so length no longer costs coverage. What remains is an ordinary sanity bound on a single fact -- a fact this long is usually a document that wants the document corpus instead.

Variables

View Source
var ErrNotFound = errors.New("not found")

Store provides fact storage with hybrid FTS5+vector search. ErrNotFound is reported by id-targeted operations when no row matches the id in the caller's scope: Delete, Confirm, UpdateMetadata, DeleteLink, UpdateLink, Supersede, History by id, and LinkFacts naming an endpoint that does not exist. History is the one read in that list -- it is id-targeted, so a caller can miss with it the same way (#172).

It exists so callers can tell a caller mistake from a store failure. The MCP layer reports the two on different channels -- a bad id is invalid_input, an outage is IsError -- and without a sentinel every miss reads as an outage (#165). Wrap it with %w rather than returning it bare, so the message keeps naming the id that missed.

View Source
var ErrNotPermitted = errors.New("not permitted")

ErrNotPermitted is reported by StoreScoper when it declines to issue a handle carrying authority the principal does not have. It is deliberately distinct from ErrNotFound: nothing was looked for and nothing was missing -- the caller asked for a capability it may not hold, and was refused before any operation was attempted.

View Source
var ErrScreenRejected = errors.New("memstore: write rejected by injection screening")

ErrScreenRejected reports a write refused by injection screening. Callers should surface it to the user rather than retrying: the content will be refused again.

Functions

func ChunkFact

func ChunkFact(model, content string, ceiling int) []embedding.Chunk

ChunkFact splits a fact's content into the spans that will each become one vector. Most facts are short and come back as a single chunk; only content past the chunk target is split.

ceiling is a hard upper bound in bytes, normally the effective input budget of the configured embedder (Config.Limits().MaxBytes). It only ever makes chunks smaller: a ceiling below the target clamps it, so a backend stricter than the target still gets requests it will accept, while a ceiling above the target is ignored rather than used to inflate chunks. Pass 0 for no ceiling.

Chunk.Text is exactly content[Start:End], so a stored vector can be traced back to the span of the fact it describes.

func ConfigPath

func ConfigPath() string

ConfigPath returns the path to the config file, following the XDG Base Directory Specification: $XDG_CONFIG_HOME/memstore/config.toml (default ~/.config/memstore/config.toml).

func DetectReadableSQL

func DetectReadableSQL(prefix string, threshold int) string

DetectReadableSQL is the read filter for the regex score, ANDed onto every fact query alongside the screening-state filter.

An unrecorded score is NULL, and NULL means *not yet computed*, not hostile. Treating it as blocked would withhold the entire corpus the moment the column landed -- the same failure grandfathering exists to avoid -- so unscored facts read normally until a backfill scores them.

It is a WHERE clause rather than a filter in Go for two reasons: running detect on every fact on every read costs ~389us per fact and rescans unchanged content forever, and dropping rows after the query silently under-delivers MaxResults.

func DetectRuleIDs

func DetectRuleIDs(r detect.Result) []string

func EmbedConfigFromEnv

func EmbedConfigFromEnv() (embedding.Config, error)

EmbedConfigFromEnv reads the embedder configuration every memstore binary shares, with StrictModel defaulted on.

The default matters because model identity decides the task prefixes and the input budget, and both fail open: a registry miss yields a passthrough prompter and a zero budget with no error, so the symptom is quietly worse recall rather than a failure. Setting MEMSTORE_EMBED_STRICT_MODEL or the bare EMBEDDING_STRICT_MODEL opts out, and is never overridden.

func EmbedRecipe

func EmbedRecipe(model string) string

EmbedRecipe identifies everything besides the model and vector dimension that determines a stored fact vector: the task prefix, the chunk size, and the header layout.

It exists so a recipe change is *detected* rather than remembered. Every previous one -- chunking, then task prefixes -- needed a hand-written migration whose only content was "delete every vector so the backfill re-runs", written from whoever changed the recipe recalling that they had. That does not scale, and the symptom of forgetting is degraded ranking rather than an error.

The embed ceiling is deliberately NOT folded in, even though a ceiling below the chunk target does lower the effective chunk size and so does change the vectors.

The reason is when each is knowable. The ceiling arrives through SetEmbedCeiling after the store is constructed, so a recipe that depended on it could not be checked at store-open -- the moment that matters, before a stale vector is served. Computing it at open with the ceiling still unset and again later with it set would make the recipe differ between the two, and a deployment clamped below the target would clear its vectors on every single startup. A check that cries wolf is one that gets routed around.

The gap this leaves is narrow and worth stating: two deployments of the same model that clamp to different ceilings below the chunk target are not distinguished. Both known deployments run budgets well above it, where the ceiling has no effect on chunk size at all.

The *token* target is hashed rather than the byte budget it converts to. The byte figure moves as calibration observations accumulate, so hashing it would make the recipe drift during normal operation and clear the corpus on a restart.

func FactEmbedText

func FactEmbedText(model, subject, chunk string) string

FactEmbedText renders what is sent to the model for one chunk of a fact: the document task prefix, the subject header, then the chunk body.

The task prefix is what the model was trained to key off. nomic-embed-text expects "search_document:" on stored text and "search_query:" on the query; memstore sent neither, so every comparison crossed a boundary the model was trained to distinguish, silently. See FactQueryText for the other side.

TaskRetrievalDocument rather than TaskClustering because memstore's primary vector use is query-to-fact search, which is asymmetric. Fact-to-fact comparison still works, since both operands are document vectors and share a space.

func FactQueryText

func FactQueryText(model, query string) string

FactQueryText renders a search query under the model's query task, so it is comparable with the document vectors FactEmbedText produced.

Getting this wrong is quiet. The two sides are set in different files and nothing fails when they disagree -- results are just worse. What must not happen again is either side being changed without the other.

func FetchLimit

func FetchLimit(opts SearchOpts) int

FetchLimit is how many rows each first-stage arm should return: enough to cover the rerank candidate pool when reranking, otherwise twice MaxResults so the merge has headroom. RerankCandidates is only non-zero once a reranker is configured, so non-rerank paths keep the original MaxResults*2 behaviour. Exported for Store backends to size their first-stage queries consistently.

func FuseScore

func FuseScore(mode RerankMode, weight, rerank, firstStage float64) float64

FuseScore combines a first-stage relevance score with a normalized [0,1] rerank score according to mode. It is the single place the mode arithmetic lives, shared by ScoreResults and the recall pipeline so both rank identically. weight is rerank's share in RerankBalanced (defaulted upstream).

  • RerankBalanced: weight*rerank + (1-weight)*firstStage
  • RerankDominant: rerank, with a tie-break sliver of firstStage
  • RerankGate: firstStage unchanged (gate only filters, never reorders)
  • RerankOff/other: firstStage unchanged

func LoadIngestToken

func LoadIngestToken() string

LoadIngestToken returns the dedicated ingest credential: the ingest_token config key, overridden by MEMSTORE_INGEST_TOKEN. It is deliberately NOT a field on AppConfig and NOT read by LoadConfig: memstore-mcp loads AppConfig, and if the ingest token rode along there, the model's process would hold the exact credential the ingest scope split exists to withhold (docs/document-ingest.md). Only `memstore ingest` calls this.

func LogEmbedModel

func LogEmbedModel(cfg embedding.Config)

LogEmbedModel records what the configured model name actually resolved to, so the prefixes and budget in force are visible at startup rather than inferred from bad results later.

func MatchFilePattern

func MatchFilePattern(pattern, filePath string) bool

MatchFilePattern checks if filePath matches a trigger's glob pattern. Patterns are relative (e.g. "internal/feeds/**"). The function tries matching against successive suffixes of the absolute file path. Supports ** as "match any path segments".

func MetadataConflicts

func MetadataConflicts(a, b json.RawMessage) bool

MetadataConflicts returns true if both metadata values are non-empty JSON objects and any shared top-level keys have different values. This prevents auto-supersession across different contexts (different projects, sources, etc.). Returns false if either is nil/empty or if they have no conflicting keys.

func ProjectNameFromCWD

func ProjectNameFromCWD(cwd string) string

ProjectNameFromCWD walks up from cwd looking for a .git directory and returns the base name of that directory. Falls back to filepath.Base(cwd) when no .git is found, and "unknown" for empty input.

Used by both the daemon (to attribute extracted summaries) and clients (Claude Code hooks, in particular) to derive a stable project subject from a session's working directory.

func RedactDSN

func RedactDSN(dsn string) string

RedactDSN masks the password in a PostgreSQL DSN while leaving the parts an operator actually debugs -- scheme, user, host, database, options -- intact. Blanket-redacting the whole string would hide "am I pointed at the right host?", which is the usual question, and so would invite people to print the raw DSN instead.

It is exported because the DSN is passed around outside AppConfig (flags, admin commands), and every one of those paths needs the same treatment. A DSN that will not parse is redacted whole: an unparseable string is not proof there is no password in it.

func RerankerFromEnv

func RerankerFromEnv(prefix string) (embedding.Reranker, embedding.RerankConfig, error)

RerankerFromEnv builds a second-stage Reranker from the {prefix}_* env namespace, cascading to RERANK_* (see embedding.RerankConfigFromEnvPrefix). It returns (nil, cfg, nil) when no endpoint and model are configured, meaning rerank is disabled — the common case, so callers can attach the result unconditionally via Store.SetReranker.

The returned cfg lets the caller log what was configured (and warn if NormalizeScores is off for a raw-logit backend, which would break score fusion). A parse error in the env namespace is returned; a missing endpoint/model is not an error, just disabled.

func ScreenNotRejectedSQL

func ScreenNotRejectedSQL(prefix string) string

ScreenNotRejectedSQL matches facts that have not been rejected -- readable ones and those still awaiting a verdict, but not blocked or abandoned.

This is for the internal paths that should act on a fact before it is readable: embedding it so it is searchable the moment it clears, and the duplicate check, which must see a pending write to avoid queueing the same content twice. Neither returns content to a caller.

func ScreenReadableSQL

func ScreenReadableSQL(prefix string) string

ScreenReadableSQL returns the predicate restricting a query to readable facts. prefix is the table alias including its dot ("f." in joined queries), or "".

This is appended unconditionally wherever facts are selected, next to the namespace filter. Pairing it with namespace is deliberate: namespace is the one predicate every fact query already has, so "did you filter the namespace?" and "did you filter unscreened content?" become the same question, and a new query cannot quietly acquire one without the other.

The states are inlined rather than parameterized because this string is concatenated into queries built with positional placeholders, where injecting extra arguments would renumber everything after it. They are compile-time constants, not input.

func ScreenableText

func ScreenableText(content, metadata string) string

ScreenableText composes what the screener actually judges: the fact's content plus every metadata string value.

Metadata has to be in here. It is rendered to models alongside content, it is writable through a second path (UpdateMetadata), and it is where an attacker would go the moment content alone is screened.

Every string value, with no length floor. An earlier version skipped values under 80 runes on the theory that short values are enum-ish and cannot say much -- which is false, and the tests said so immediately: "ignore all previous instructions" is 32 characters and a complete attack, so the floor was a documented hole exactly the size of the most common payload. The renderer has a length threshold because inline-versus-fenced is a layout question; screening has no equivalent excuse, and scanning a few extra short strings costs nothing.

Values are walked recursively, so a payload nested inside an object or array is found rather than skipped for not being a top-level string.

func ValidScopes

func ValidScopes() []string

ValidScopes returns every recognised scope, in a stable order suitable for error messages and help text.

func ValidateScopes

func ValidateScopes(scopes []string) error

ValidateScopes reports whether every scope in the set is recognised. An empty set is valid: it is how an unscoped token is represented, and such a token receives the legacy read+write grant.

This exists because an unrecognised scope fails closed and silently. Scope matching is exact and case-sensitive, so "Ingest" or a typo like "ingset" produces a credential that authenticates successfully and is refused by every route, with nothing at issue time to say why. Worse, a non-empty scope set forfeits the empty-set grant, so a misspelled scope is strictly worse than passing no scopes at all. Rejecting it at the point of issue is the only place the mistake is still cheap.

Types

type AdminStore

type AdminStore interface {
	WritableStore
	StoreScoper
}

AdminStore is a handle that may act for principals other than its own. It is the typed replacement for today's service scope, which is a store carrying user id 0 and a convention about what that means -- a magic value that has already produced one real bug, where the service-scope branch of LinkFacts stamped user_id 0 onto a row whose foreign key required a real user.

It embeds StoreScoper rather than adding cross-user methods because that is precisely the extra authority: an admin does not read other users' facts directly, it mints a handle for the user it is acting on behalf of, and every row that handle writes names that user.

type AppConfig

type AppConfig struct {
	DB        string
	Namespace string
	Ollama    string // chat LLM base URL (used by OpenAIGenerator)
	GenModel  string
	GenURL    string // separate LLM URL for generation (defaults to Ollama if empty)
	Remote    string // memstored URL; if set, use daemon mode instead of local SQLite
	APIKey    string // API key for memstored auth
	LLMAPIKey string // API key for the chat LLM provider (LiteLLM, OpenAI, etc.)
	Addr      string // listen address for memstored daemon
	// PG is the PostgreSQL connection string; if set, use Postgres instead of
	// SQLite. It is a SECRET: the DSN embeds the database password. It is named
	// pg_secret / MEMSTORE_PG_SECRET so that the ordinary secret-filtering
	// habit -- grep -v for pass|key|secret|token over an env dump -- catches it.
	// The old name, plain "pg" / MEMSTORE_PG, matched none of those and so read
	// as inert config; it leaked into a terminal that way. Both names still
	// load (see LoadConfig), but only the new one is documented.
	PG     string
	VecDim int // embedding vector dimension for Postgres (e.g. 768)

	// TLS configuration for memstored (server side). The daemon requires TLS
	// by default; TLSDisabled is the explicit opt-out for proxy-fronted
	// deployments.
	TLSCertFile     string // PEM-encoded server certificate
	TLSKeyFile      string // PEM-encoded server private key
	TLSClientCAFile string // PEM bundle of CAs trusted for client certs; presence enables mTLS
	TLSDisabled     bool   // listen plaintext (insecure)
	// InsecurePlaintext affirms that a plaintext listener is reachable only
	// over a trusted path. Required alongside TLSDisabled: the daemon cannot
	// tell a private container network from a routable one, so it asks once
	// rather than guessing. See checkTransport in cmd/memstored.
	InsecurePlaintext bool

	// Injection screening. Every write is screened by regex regardless of these;
	// they configure the model pass and the thresholds.
	//
	// ScreenMode is off | observe | gate, and defaults to off. Anything else requires
	// a deployment that actually runs the screening worker -- the daemon. See
	// ScreenMode for what each mode costs.
	ScreenMode        string // off | observe | gate
	ScreenThreat      int    // model threat score (0-10) at which a write is blocked (gate mode)
	ScreenDetectScore int    // detect score (0-100) at which the inline regex screen rejects

	// ScreenDetectWrite and ScreenDetectRead are allow | warn | block, defaulting to
	// block. They are separate because the two edges fail differently: a blocked
	// write returns an error the writer can act on by rephrasing, while a blocked
	// read simply withholds the memory. See ScreenDetectMode.
	ScreenDetectWrite string
	ScreenDetectRead  string

	// ScreenDetectReadScore is the score at which a read is withheld, defaulting to
	// DefaultDetectReadScore. Deliberately above ScreenDetectScore: a blocked read is
	// silent, so it should demand corroboration rather than a single rule.
	ScreenDetectReadScore int
	ScreenConcurrency     int // simultaneous model screens
	ScreenBatch           int // pending facts claimed per tick
	ScreenIntervalSec     int // seconds between worker ticks
	ScreenMaxAttempts     int // failed screens before a fact is abandoned

	// TLS configuration for memstore CLI / MCP (client side).
	TLSCAFile         string // PEM bundle to trust for the server cert (in addition to system roots)
	TLSClientCertFile string // PEM cert presented to memstored when mTLS is required
	TLSClientKeyFile  string // matching private key
}

AppConfig holds persistent defaults for the memstore CLI and MCP server. Values are loaded from the config file and can be overridden by CLI flags.

Embedding configuration is NOT in this struct — it is read from the MEMSTORE_EMBED_* / EMBEDDING_* environment variables by go-embedding.

func DefaultConfig

func DefaultConfig() AppConfig

DefaultConfig returns the built-in defaults used when no config file exists.

func LoadConfig

func LoadConfig() AppConfig

LoadConfig reads the config file and merges it with defaults. Missing keys retain their default values. If the config file does not exist or cannot be read, the defaults are returned without error.

func (AppConfig) String

func (c AppConfig) String() string

String implements fmt.Stringer so that printing a config -- in a log line, a test failure, a debug dump -- cannot leak its secrets. fmt routes %v and %+v through String, so this covers the accidental prints, which are the ones that matter: nobody deliberately writes an API key to a terminal.

type BlockedFact

type BlockedFact struct {
	ID        int64
	Subject   string
	Content   string
	Threat    int
	Category  string
	Reason    string
	CreatedAt time.Time
}

BlockedFact is a rejected write, surfaced for review.

Content is included: an operator deciding whether a block was a false positive has to see what was blocked, and this content exists nowhere else -- a blocked write never becomes a readable fact. Callers rendering it to a model must fence it, the same as any stored content.

type ContextFeedback

type ContextFeedback struct {
	RefID     string // fact ID or session_turn UUID
	RefType   string // RefTypeFact, RefTypeTurn, or RefTypeHint
	SessionID string
	Score     int // +1 or -1
	Reason    string
}

ContextFeedback is a rating from Claude on a piece of injected context. Score is +1 (useful) or -1 (not useful). One rating per ref per session.

type ContextHint

type ContextHint struct {
	ID              int64              `json:"id"`
	SessionID       string             `json:"session_id"`
	CWD             string             `json:"cwd"` // working directory of the generating session, for cross-session lookup
	TurnIndex       int                `json:"turn_index"`
	HintText        string             `json:"hint_text"`
	RefIDs          []string           `json:"ref_ids"`          // selected candidate fact IDs (positives)
	RetrievedIDs    []string           `json:"retrieved_ids"`    // all candidate fact IDs before selection (positives + negatives)
	CandidateScores map[string]float64 `json:"candidate_scores"` // {fact_id_str: vec_score} for all candidates
	SearchQuery     string             `json:"search_query"`     // query used for the Searcher stage
	RankerVersion   string             `json:"ranker_version"`   // pipeline version at generation time
	Relevance       float64            `json:"relevance"`
	Desirability    float64            `json:"desirability"`
	CreatedAt       time.Time          `json:"created_at"`
	ConsumedAt      *time.Time         `json:"consumed_at,omitempty"`
}

ContextHint is a proactively retrieved context suggestion produced by the Ollama pipeline and consumed by the next UserPromptSubmit hook injection.

type Curator

type Curator interface {
	// Curate returns up to maxOutput facts from candidates that are most relevant
	// to the task, along with a brief rationale. If maxOutput <= 0 or >= len(candidates),
	// all candidates may be returned. On error the caller should fall back to the
	// full candidate list.
	Curate(ctx context.Context, task string, candidates []Fact, maxOutput int) (selected []Fact, rationale string, err error)
}

Curator selects the most relevant subset of candidate facts for a given task. It is intended to sit between broad retrieval and context injection, reducing noise before facts are sent to the primary model.

type Document

type Document struct {
	ID        int64  `json:"id"`
	Namespace string `json:"namespace,omitempty"` // set automatically by the store on upsert
	UserID    int64  `json:"user_id,omitempty"`   // owning user; resolved by the store, see ownerFor
	RepoURL   string `json:"repo_url,omitempty"`  // canonical remote; "" = loose file (stored as NULL)
	Commit    string `json:"commit,omitempty"`    // asserted by the ingesting client
	Path      string `json:"path"`                // repo-relative (or ingest-root-relative) path
	Basename  string `json:"basename"`            // derived from Path by the store
	Lang      string `json:"lang,omitempty"`      // set by the daemon's extension routing

	FileSHA256 []byte     `json:"file_sha256"` // hash of the exact bytes the chunks were cut from
	Mtime      *time.Time `json:"mtime,omitempty"`
	Dirty      bool       `json:"dirty"`               // file was modified/untracked in the working tree at ingest
	Trusted    bool       `json:"trusted"`             // resolved from repo policy at ingest; not consulted live
	Generated  bool       `json:"generated,omitempty"` // file carries a "Code generated" header
	IsTest     bool       `json:"is_test,omitempty"`   // _test.go and equivalents

	ChunkerVersion int             `json:"chunker_version"`
	ChunkStrategy  string          `json:"chunk_strategy,omitempty"` // which chunker cut this file (e.g. "markdown", "go", "line-window" for parse fallback)
	Title          string          `json:"title,omitempty"`          // from front matter when present
	FrontMatter    json.RawMessage `json:"front_matter,omitempty"`   // parsed front matter; rigid provenance, not model-writable

	IngestedAt time.Time `json:"ingested_at"`
}

Document is the file-level identity and rigid provenance for one ingested file, per docs/document-corpus.md. Every field is written by the ingest path, never by a model: this is the typed-column provenance system, distinct from the flexible model-written metadata facts carry.

The uniqueness key is (namespace, user_id, repo_url, path); Commit is deliberately outside it -- re-ingesting at a new commit replaces the row, because git already stores history.

type DocumentChunk

type DocumentChunk struct {
	ID         int64 `json:"id"`
	DocumentID int64 `json:"document_id"`
	Ordinal    int   `json:"ordinal"`

	Content   string `json:"content"`
	ByteStart int    `json:"byte_start"`
	ByteEnd   int    `json:"byte_end"`
	LineStart int    `json:"line_start"`
	LineEnd   int    `json:"line_end"`

	// Markdown-derived context (docs/document-chunking.md).
	HeadingPath  string `json:"heading_path,omitempty"` // ancestors only, never the chunk's own heading
	HeadingLevel int    `json:"heading_level,omitempty"`
	Lang         string `json:"lang,omitempty"` // set on split-out fences

	// Code-derived context (docs/code-chunking.md).
	Package     string   `json:"package,omitempty"`
	ImportPath  string   `json:"import_path,omitempty"`
	Symbol      string   `json:"symbol,omitempty"`
	Receiver    string   `json:"receiver,omitempty"`
	DeclKind    string   `json:"decl_kind,omitempty"` // func | method | type | const | var | import | package_doc
	Exported    bool     `json:"exported,omitempty"`
	Signature   string   `json:"signature,omitempty"`
	ScopePath   string   `json:"scope_path,omitempty"` // package > receiver > symbol
	ImportsUsed []string `json:"imports_used,omitempty"`

	CreatedAt time.Time `json:"created_at"`
}

DocumentChunk is one verbatim span of a document. The checkable invariant: Content equals file[ByteStart:ByteEnd] at the document's recorded FileSHA256. Spans are non-overlapping and monotonically increasing in Ordinal; they do not cover the file (front matter and inter-block whitespace are skipped by design).

The heading/scope fields are derived context assembled into embed text at embed time; they are never prepended to Content.

type DocumentInfo

type DocumentInfo struct {
	ID         int64  `json:"id"`
	Path       string `json:"path"`
	FileSHA256 []byte `json:"file_sha256"`
	Dirty      bool   `json:"dirty"`
}

DocumentInfo is the manifest-sync view of a stored document: enough to compute need/skip/orphaned against a client manifest without shipping content.

type DocumentSearchOpts

type DocumentSearchOpts struct {
	MaxResults       int
	RepoURL          string // exact match; "" = all repos including loose files
	PathPrefix       string // prefix match on document path
	Basename         string // exact match on document basename
	Lang             string // exact match on document lang
	IncludeGenerated bool
}

DocumentSearchOpts filters and sizes a document-chunk search.

Basename exists because "show me sqlite.go" is a metadata lookup, not a full-text problem (docs/document-corpus.md). Generated documents are excluded unless IncludeGenerated is set.

type DocumentSearchResult

type DocumentSearchResult struct {
	Chunk     DocumentChunk `json:"chunk"`
	RepoURL   string        `json:"repo_url,omitempty"`
	Commit    string        `json:"commit,omitempty"`
	Path      string        `json:"path"`
	Basename  string        `json:"basename"`
	DocLang   string        `json:"doc_lang,omitempty"`
	Trusted   bool          `json:"trusted"`
	Dirty     bool          `json:"dirty"`
	Generated bool          `json:"generated,omitempty"`
	IsTest    bool          `json:"is_test,omitempty"`
	Score     float64       `json:"score"`
	Fallback  bool          `json:"fallback,omitempty"` // matched via decomposed-identifier fallback; ranked below exact hits
}

DocumentSearchResult is one chunk hit with the document identity needed for its citation. Trusted travels with every result so the caller can fence untrusted content before it reaches a context window.

func (DocumentSearchResult) Citation

func (r DocumentSearchResult) Citation() string

Citation renders the mandatory traceability string for a chunk result: repo@commit path:L120-160, degrading gracefully for loose files.

type DocumentStore

type DocumentStore interface {
	// UpsertDocument stores or replaces a document and its chunks atomically.
	// Replacement is keyed on (namespace, user, repo_url, path); the previous
	// chunk set is deleted, not merged. Basename is derived from doc.Path.
	// Returns the document id.
	UpsertDocument(ctx context.Context, doc Document, chunks []DocumentChunk) (int64, error)

	// ListDocuments returns the manifest view of every stored document for a
	// repo identity. repoURL "" selects loose files (repo_url IS NULL).
	ListDocuments(ctx context.Context, repoURL string) ([]DocumentInfo, error)

	// DeleteDocuments removes the named documents (chunks cascade) for a repo
	// identity and reports how many documents were deleted. Used for orphan
	// cleanup after a manifest sync. repoURL "" selects loose files.
	DeleteDocuments(ctx context.Context, repoURL string, paths []string) (int64, error)

	// GetDocument returns a document by id, or (nil, nil) when no document
	// with that id is visible in the caller's scope -- matching Get's
	// not-found contract.
	GetDocument(ctx context.Context, id int64) (*Document, error)

	// GetDocumentChunks returns a document's chunks ordered by ordinal.
	GetDocumentChunks(ctx context.Context, documentID int64) ([]DocumentChunk, error)

	// SearchDocumentChunks is FTS over chunk content: an exact pass first,
	// then -- only if the exact pass leaves room -- a decomposed-identifier
	// fallback appended below it (docs/embedding-model-routing.md, measured:
	// fall back, do not blend).
	SearchDocumentChunks(ctx context.Context, query string, opts DocumentSearchOpts) ([]DocumentSearchResult, error)
}

DocumentStore is the document-corpus storage interface. It is separate from Store on purpose: documents are written only by the ingest path (never by model-facing tools), do not participate in Export/Import, and have no supersession -- re-ingest replaces on (repo, path). Postgres implements it; the SQLite backend does not carry the corpus.

type EmbedStore

type EmbedStore interface {
	NeedingEmbedding(ctx context.Context, limit int) ([]Fact, error)
	SetEmbedding(ctx context.Context, id int64, emb []float32) error
	SetFactVectors(ctx context.Context, id int64, v FactVectors) error
	FactChunks(ctx context.Context, id int64) ([]FactChunk, error)
	MarkEmbedFailed(ctx context.Context, id int64, reason string) error
	EmbedFacts(ctx context.Context, batchSize int) (int, error)
}

EmbedStore is the embedding pipeline's write surface, deliberately separate from WritableStore.

These are writes, but not writes about what memstore knows: they replace vectors, quarantine facts whose embedding failed, and drain the embed queue. Folding them into WritableStore would mean anything that can store a fact can also rewrite another fact's vectors or mark it permanently unembeddable -- authority the MCP surface has never needed and should not be handed by default. The embed worker holds this; request handlers do not.

type ExportData

type ExportData struct {
	Version             int            `json:"version"`
	ExportedAt          time.Time      `json:"exported_at"`
	EmbedderModel       string         `json:"embedder_model,omitempty"`
	EmbeddingDimensions int            `json:"embedding_dimensions,omitempty"`
	Facts               []ExportedFact `json:"facts"`
}

ExportData is the top-level structure for a memstore export.

func Export

func Export(ctx context.Context, db *sql.DB) (*ExportData, error)

Export reads all facts (all namespaces, including superseded) from the database and returns them as an ExportData struct. The database must have been initialized by NewSQLiteStore at least once.

type ExportedFact

type ExportedFact struct {
	ID              int64           `json:"id"`
	Namespace       string          `json:"namespace"`
	User            string          `json:"user,omitempty"` // owner name from memstore_users; empty means import uses target default
	Content         string          `json:"content"`
	Subject         string          `json:"subject"`
	Category        string          `json:"category"`
	Kind            string          `json:"kind,omitempty"`
	Subsystem       string          `json:"subsystem,omitempty"`
	Metadata        json.RawMessage `json:"metadata,omitempty"`
	SupersededBy    *int64          `json:"superseded_by,omitempty"`
	SupersededAt    *time.Time      `json:"superseded_at,omitempty"`
	ConfirmedCount  int             `json:"confirmed_count,omitempty"`
	LastConfirmedAt *time.Time      `json:"last_confirmed_at,omitempty"`
	UseCount        int             `json:"use_count,omitempty"`
	LastUsedAt      *time.Time      `json:"last_used_at,omitempty"`
	InjectCount     int             `json:"inject_count,omitempty"`
	LastInjectedAt  *time.Time      `json:"last_injected_at,omitempty"`
	CreatedAt       time.Time       `json:"created_at"`
}

ExportedFact represents a single fact in an export. Embeddings are deliberately excluded -- they're model-specific binary blobs that don't transfer portably. Re-embed after import via EmbedFacts().

type ExtractHints

type ExtractHints struct {
	Persona    string   // name/role for domain context
	Focus      []string // domains to prioritize
	Categories []string // restrict to these; empty = all defaults
}

ExtractHints provides domain context to guide fact extraction.

type ExtractOpts

type ExtractOpts struct {
	Namespace string // target namespace for inserted facts
	Subject   string // default subject when LLM omits one
	Hints     ExtractHints
	Metadata  json.RawMessage // attached to every inserted fact (e.g. {"cwd":..., "source":...})
}

ExtractOpts controls the extraction pipeline.

type ExtractResult

type ExtractResult struct {
	Inserted   []Fact
	Duplicates int     // skipped via Exists() or in-batch dedup
	Superseded int     // count of old facts auto-superseded by new ones
	Errors     []error // per-fact parse/insert failures
}

ExtractResult summarizes the outcome of an extraction run.

type Fact

type Fact struct {
	ID              int64
	Namespace       string          // partition key; set automatically by the store on insert
	UserID          int64           `json:"UserID,omitempty"` // owning user; set automatically from the store's resolved identity
	Content         string          // the factual claim
	Subject         string          // topic of the fact (not ownership -- see UserID)
	Category        string          // freeform: "character", "preference", "identity", etc.
	Kind            string          // structural type: convention | failure_mode | invariant | pattern | decision | trigger | task | ""
	Subsystem       string          // optional project subsystem (e.g. "feeds", "auth"); scopes facts within a subject
	Metadata        json.RawMessage // domain-specific extensions (nullable)
	SupersededBy    *int64          // points to replacing fact
	SupersededAt    *time.Time      // when supersession occurred
	ConfirmedCount  int             // explicit "I verified this is accurate" count
	LastConfirmedAt *time.Time      // when last confirmed
	UseCount        int             // auto-incremented when retrieved via an explicit search
	LastUsedAt      *time.Time      // when last retrieved by search
	InjectCount     int             // auto-incremented when surfaced by recall injection
	LastInjectedAt  *time.Time      // when last injected
	Embedding       []float32       // nil until computed
	CreatedAt       time.Time
}

Fact represents a single factual claim in the knowledge store.

func ExtractFacts

func ExtractFacts(ctx context.Context, gen Generator, text string, opts ExtractOpts) ([]Fact, error)

ExtractFacts uses a generator to extract structured facts from text without persisting them. Returns parsed facts with subject and category populated, ready for caller-managed insertion. The returned facts have no embeddings or IDs -- the caller handles those.

type FactBreakdown

type FactBreakdown struct {
	Subjects   map[string]int `json:"subjects"`
	Categories map[string]int `json:"categories"`
	Kinds      map[string]int `json:"kinds"`
}

FactBreakdown holds per-dimension counts of active facts. Each map is keyed by the dimension value and holds the number of active facts carrying it.

type FactChunk

type FactChunk struct {
	// Ordinal is the chunk's position within the fact, from 0.
	Ordinal int
	// Vector is the embedding of this chunk.
	Vector []float32
	// ByteStart and ByteEnd address the span of Fact.Content this chunk was
	// produced from, so a chunk hit resolves back to a passage of the fact
	// rather than only to the fact. Overlap makes these impossible to
	// recompute after the fact, so they are stored rather than derived.
	ByteStart int
	ByteEnd   int
}

FactChunk is one embeddable span of a fact's content, and the unit a vector is actually stored against.

A fact is a set of vectors rather than a point. Most facts are short enough to be a single chunk, but a long one is split so that each vector describes one passage: a vector has fixed capacity, and averaging a whole document into it dilutes exactly the specificity retrieval depends on. See ChunkFact.

type FactExtractor

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

FactExtractor distills unstructured text into structured facts using an LLM.

func NewFactExtractor

func NewFactExtractor(store Store, embedder embedding.Embedder, generator Generator) *FactExtractor

NewFactExtractor creates an extractor that uses the given store, embedder, and generator to extract and persist facts from text.

func (*FactExtractor) Extract

func (e *FactExtractor) Extract(ctx context.Context, text string, opts ExtractOpts) (*ExtractResult, error)

Extract distills text into structured facts and persists them. It runs four phases:

  1. Resolve and dedup -- skip empty content, resolve subject/category defaults, check existence, and drop in-batch duplicates.
  2. Batch embed -- one EmbedWithRetry call for all surviving candidates.
  3. Insert -- persist each candidate.
  4. Supersession -- one SearchBatch call per distinct subject to find and supersede near-duplicate existing facts.

func (*FactExtractor) SetEmbedCeiling

func (e *FactExtractor) SetEmbedCeiling(n int)

SetEmbedCeiling sets the hard byte bound on any single embed request, normally the configured embedder's effective budget (embedding.Config.Limits().MaxBytes). Zero leaves chunk sizing to the retrieval target alone.

func (*FactExtractor) SetPromptFunc

func (e *FactExtractor) SetPromptFunc(fn PromptFunc)

SetPromptFunc overrides the default prompt builder.

type FactVectors

type FactVectors struct {
	// Whole is the vector over the fact's entire content, and the one stored
	// as the fact row's marker. For a fact short enough to be a single chunk
	// it is that chunk's vector -- they are the same text.
	Whole []float32
	// Chunks holds one vector per chunk, in ordinal order.
	Chunks []FactChunk
}

FactVectors is everything embedding a fact produces: the retrieval vectors, one per chunk, and the single whole-fact vector used for comparing facts to each other.

The two are separate because they answer different questions. Retrieval wants the nearest passage, so it needs a vector per chunk. Deduplication asks whether two facts say the same thing, which is a property of the whole fact; comparing a whole-fact vector against a chunk would compare an average with an opening passage, score systematically low, and silently stop deduplicating long facts. Auto-supersession is destructive, so that asymmetry is not one to leave in place.

func EmbedFact

func EmbedFact(ctx context.Context, e embedding.Embedder, model string, f Fact, ceiling int) (FactVectors, error)

EmbedFact splits a fact's content into retrieval-sized chunks and embeds each one, plus the whole-fact vector deduplication compares against.

ceiling is a hard byte bound on the rendered text of any single chunk, normally the effective input budget of the configured embedder. The subject header is charged against it, so the body gets the remainder -- sizing the body at the full ceiling and then prepending a header would push every request over it.

The whole-fact vector is pooled from the chunk vectors rather than embedded from the whole text. Embedding the whole text is not available here: a fact that splits is by definition longer than the ceiling, so that request is the one a strict backend rejects, and clipping it back under the ceiling would discard the tail -- reintroducing the loss chunking removed. Pooling covers every chunk, costs no extra request, and is the standard answer for a whole-document vector.

Pooling is the right tool here precisely because the question is different from retrieval's. Averaging dilutes the specificity a passage lookup needs, which is why chunks are stored separately; but "do these two facts say the same thing" is a property of the whole fact, and a pooled vector is what represents it.

Either every vector embeds or none do. A partially embedded fact would look complete to the queue (its marker vector is set) and leave a permanent hole in the middle of it, so a failure returns nothing and the fact is retried whole.

type FactVectorsResult

type FactVectorsResult struct {
	Vectors FactVectors
	Err     error
}

FactVectorsResult is the outcome for one fact in a batched embed, index-aligned with the slice EmbedFactsBatch was given.

Empty Vectors with a nil Err means the fact had nothing embeddable in it -- a deterministic skip, not a failure. A non-nil Err always comes with no vectors: a fact embeds completely or not at all, so a partial set is never stored and the fact is retried whole.

func EmbedFactsBatch

func EmbedFactsBatch(ctx context.Context, e embedding.Embedder, model string, facts []Fact, ceiling, batchSize int) []FactVectorsResult

EmbedFactsBatch embeds several facts in batched requests, returning one result per fact in the same order.

This is the throughput path, for bulk work like re-embedding after an import. Sending one request per fact costs the full per-request overhead on every fact, and the backends serialise per model anyway, so batching is the only lever. batchSize counts inputs -- chunks -- rather than facts, since a long fact contributes several.

Batching goes through go-embedding's BatchEmbedResults rather than a hand-rolled loop for one reason: it falls back to embedding one at a time when a batch errors or comes back short, so a single unembeddable fact fails alone instead of taking the other batchSize-1 good ones with it.

type FeedbackScorer

type FeedbackScorer interface {
	FeedbackScores(ctx context.Context, refIDs []string, refType string) (map[string]FeedbackStat, error)
}

FeedbackScorer returns aggregate feedback stats in bulk. Used by recall scoring to boost or demote facts based on historical usefulness. Count enables confidence-weighted scoring — a single rating shouldn't carry the same weight as consistent ratings across many sessions.

type FeedbackStat

type FeedbackStat struct {
	Avg   float64 // mean of recorded scores ([-1, +1])
	Count int     // number of recorded ratings
}

FeedbackStat is the aggregate feedback signal for a single ref.

type FeedbackStore

type FeedbackStore interface {
	RecordFeedback(ctx context.Context, fb ContextFeedback) error
}

FeedbackStore is the minimal interface required to record context feedback. httpclient.Client implements this, allowing memstore-mcp to use memory_rate_context without a full SessionStore.

type Generator

type Generator interface {
	Generate(ctx context.Context, prompt string) (string, error)
	// Model returns the model identifier used for generation (e.g. "qwen2.5:7b").
	Model() string
}

Generator produces text completions from a prompt.

type HistoryEntry

type HistoryEntry struct {
	Fact        Fact
	Position    int // 0-based, oldest first
	ChainLength int
}

HistoryEntry wraps a Fact with its position in a supersession chain.

type ImportOpts

type ImportOpts struct {
	// If true, skip facts whose (content, subject, namespace) already
	// exist in the target database.
	SkipDuplicates bool
}

ImportOpts controls import behavior.

type ImportResult

type ImportResult struct {
	Imported int
	Skipped  int
}

ImportResult summarizes an import operation.

func Import

func Import(ctx context.Context, db *sql.DB, data *ExportData, opts ImportOpts) (*ImportResult, error)

Import inserts facts from an ExportData into the database. Facts are inserted with their original namespace, timestamps, and metadata. SupersededBy references are remapped to new IDs. Embeddings are not imported — call EmbedFacts() after import to regenerate them.

func StoreImport

func StoreImport(ctx context.Context, store Store, data *ExportData, opts ImportOpts) (*ImportResult, error)

StoreImport inserts facts from an ExportData into a Store. Unlike Import, which uses raw SQL, this works through the Store interface and can target any backend (SQLite, Postgres, HTTP). Supersession chains are restored via Supersede(). Use_count, confirmed_count, and timestamps other than created_at are not preserved (the Store interface doesn't expose setters).

type InjectionRecorder

type InjectionRecorder interface {
	RecordInjection(ctx context.Context, ids []int64) error
}

InjectionRecorder is implemented by stores that can record recall injections. It is deliberately NOT part of Store.

Only the daemon calls it, on its own local store, from handleRecall -- the one place that knows which facts were injected. Putting it on Store would oblige httpclient to implement it and require an endpoint no client would ever call, so it stays an optional capability that the concrete backends provide and handleRecall type-asserts for.

The reason this lives server-side at all is that every previous attempt to record usage lived in a client -- a hook, or a model-initiated tool call -- and each one silently stopped: context_injections went quiet in May 2026, context_feedback in June, and confirmed_count is zero across the corpus. A signal the daemon derives from its own work cannot drift out of use.

type JSONGenerator

type JSONGenerator interface {
	Generator
	GenerateJSON(ctx context.Context, prompt string) (string, error)
}

JSONGenerator is optionally implemented by generators that support structured JSON output mode for more reliable parsing.

type JSONSchemaGenerator

type JSONSchemaGenerator interface {
	Generator
	// GenerateJSONSchema asks the model to return JSON matching the given
	// schema. name is a short identifier passed through to the API (used by
	// some providers for caching and telemetry). schema is a JSON Schema
	// object (typically map[string]any).
	GenerateJSONSchema(ctx context.Context, prompt, name string, schema any) (string, error)
}

JSONSchemaGenerator is optionally implemented by generators that support schema-constrained JSON output (OpenAI structured outputs / json_schema). Stronger than json_object: enums, required fields, and additionalProperties constraints can be enforced server-side, eliminating whole classes of format-lapse failure. Whether the constraint is actually enforced depends on the upstream model and proxy; even when treated as a hint it tightens generation noticeably.

type Link struct {
	ID            int64
	SourceID      int64
	TargetID      int64
	LinkType      string          // e.g. "passage", "event", "entrance", "reference"
	Bidirectional bool            // if true, traversable in both directions
	Label         string          // human-readable description
	Metadata      json.RawMessage // domain-specific properties (nullable)
	CreatedAt     time.Time
}

Link is a directed graph edge between two facts.

type LinkDirection

type LinkDirection int

LinkDirection controls which edges are returned by GetLinks.

const (
	// LinkOutbound returns edges where the fact is the source, plus bidirectional
	// edges where the fact is the target (i.e. all edges traversable FROM this fact).
	LinkOutbound LinkDirection = iota
	// LinkInbound returns edges where the fact is the target, plus bidirectional
	// edges where the fact is the source (i.e. all edges that can reach this fact).
	LinkInbound
	// LinkBoth returns all edges that touch this fact regardless of directionality.
	LinkBoth
)

type MetadataFilter

type MetadataFilter struct {
	Key         string // JSON field name (e.g., "chapter", "is_draft")
	Op          string // comparison operator
	Value       any    // value to compare against
	IncludeNull bool   // if true, also match rows where Key is absent or metadata is NULL
}

MetadataFilter applies a condition on a JSON metadata field. The Key is a top-level field name in the metadata JSON object. Supported operators: "=", "!=", "<", "<=", ">", ">=". Value is compared using SQLite's json_extract(); rows with NULL metadata or missing keys are excluded by comparison semantics unless IncludeNull is set.

type NopCurator

type NopCurator struct{}

NopCurator returns candidates unchanged (up to maxOutput), with no model call. Use this as a safe default when no curation model is configured.

func (NopCurator) Curate

func (NopCurator) Curate(_ context.Context, _ string, candidates []Fact, maxOutput int) ([]Fact, string, error)

Curate returns the first maxOutput candidates unmodified.

type OpenAICurator

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

OpenAICurator uses an OpenAI-compatible chat API to curate candidate facts. Works with OpenAI, LiteLLM, or any compatible proxy.

func NewOpenAICurator

func NewOpenAICurator(baseURL, apiKey, model string) *OpenAICurator

NewOpenAICurator creates a curator backed by an OpenAI-compatible chat API. baseURL is the API base (e.g. "http://litellm:4000" or "https://api.openai.com/v1"). apiKey may be empty for local proxies that don't require auth.

func (*OpenAICurator) Curate

func (c *OpenAICurator) Curate(ctx context.Context, task string, candidates []Fact, maxOutput int) ([]Fact, string, error)

Curate calls the chat API with a curation prompt and parses the JSON response.

type OpenAIGenerator

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

OpenAIGenerator implements Generator and JSONGenerator using an OpenAI-compatible chat API.

func NewOpenAIGenerator

func NewOpenAIGenerator(baseURL, apiKey, model string) *OpenAIGenerator

NewOpenAIGenerator creates a generator backed by an OpenAI-compatible API. baseURL is the API base (e.g. "http://litellm:4000" or "https://api.openai.com/v1"). apiKey may be empty for local proxies that don't require auth.

func (*OpenAIGenerator) Generate

func (g *OpenAIGenerator) Generate(ctx context.Context, prompt string) (string, error)

Generate produces a plain text completion from the given prompt.

func (*OpenAIGenerator) GenerateBounded

func (g *OpenAIGenerator) GenerateBounded(ctx context.Context, prompt string, maxTokens int) (string, error)

GenerateBounded is Generate with a hard cap on how much the model may emit.

It exists for screening, where the expected answer is a small fixed-shape JSON object and an unbounded response is pure downside: a model that rambles or loops burns the caller's entire timeout and, with a bounded worker pool, one of its few slots. Observed on a real corpus scan -- four workers idle at zero CPU with four open connections, all waiting out generations that had nothing left to say.

A truncated verdict fails to parse and is treated as a screening failure, which is the same outcome as the timeout it replaces, reached in a fraction of the time.

func (*OpenAIGenerator) GenerateJSON

func (g *OpenAIGenerator) GenerateJSON(ctx context.Context, prompt string) (string, error)

GenerateJSON produces a JSON completion using the json_object response format.

func (*OpenAIGenerator) GenerateJSONSchema

func (g *OpenAIGenerator) GenerateJSONSchema(ctx context.Context, prompt, name string, schema any) (string, error)

GenerateJSONSchema produces a JSON completion constrained by the given schema. Uses OpenAI's structured outputs (json_schema) with strict=true. Providers and proxies vary in how strictly they enforce the schema; even when only treated as a hint, enumerated fields and required-property lists reduce format lapses materially.

func (*OpenAIGenerator) Model

func (g *OpenAIGenerator) Model() string

Model returns the configured model name.

type Principal

type Principal struct {
	// UserID is the owning user. Zero means the unscoped legacy path, which
	// the scopers treat as "no narrowing available".
	UserID int64

	// Write reports whether this caller may mutate stored content.
	Write bool
}

Principal names the caller a store handle is scoped to.

Write carries the answer to "may this caller mutate content", not the rule that produced it. The scope policy lives with the transport that authenticated the caller (httpapi.Identity.Allows, where admin implies write, an empty scope set means the legacy pre-enforcement token, and ingest is implied by nothing). Duplicating that policy here would be a second implementation to keep in step; carrying its answer is not.

Expansion point: memstore has users and no organisations -- tier 3 shipped users only, and the group/role columns it once reserved were deliberately not built rather than guess at a sharing model. When organisations exist this struct grows a field and no call site changes, which is the reason the scopers take a Principal instead of a bare user id.

type PromptFunc

type PromptFunc func(text string, hints ExtractHints) string

PromptFunc builds the extraction prompt from input text and hints.

type QueryOpts

type QueryOpts struct {
	Subject         string           // filter by subject (empty = all)
	Category        string           // filter by category (empty = all)
	Kind            string           // filter by kind (empty = all)
	Subsystem       string           // filter by subsystem (empty = all)
	OnlyActive      bool             // exclude superseded
	Namespaces      []string         // list only these namespaces; empty means the store's own namespace
	MetadataFilters []MetadataFilter // filter on metadata JSON fields
	CreatedAfter    *time.Time       // exclude facts created before this time
	CreatedBefore   *time.Time       // exclude facts created after this time
	Limit           int              // max results (0 = no limit)
	IDs             []int64          // fetch only these specific fact IDs (empty = no filter)
}

QueryOpts controls filtering for List queries.

type ReadableStore

type ReadableStore interface {
	Get(ctx context.Context, id int64) (*Fact, error)
	List(ctx context.Context, opts QueryOpts) ([]Fact, error)
	BySubject(ctx context.Context, subject string, onlyActive bool) ([]Fact, error)
	Exists(ctx context.Context, content, subject string) (bool, error)
	ActiveCount(ctx context.Context) (int64, error)
	Breakdown(ctx context.Context) (FactBreakdown, error)
	History(ctx context.Context, id int64, subject string) ([]HistoryEntry, error)
	Search(ctx context.Context, query string, opts SearchOpts) ([]SearchResult, error)
	SearchBatch(ctx context.Context, queries []string, opts SearchOpts) ([][]SearchResult, error)
	SearchFTS(ctx context.Context, query string, opts SearchOpts) ([]SearchResult, error)
	ListSubsystems(ctx context.Context, subject string) ([]string, error)
	GetLink(ctx context.Context, linkID int64) (*Link, error)
	GetLinks(ctx context.Context, factID int64, direction LinkDirection, linkTypes ...string) ([]Link, error)

	// Touch bumps use_count for facts the caller was served. See the type
	// comment for why read telemetry lives on the read handle.
	Touch(ctx context.Context, ids []int64) error
}

ReadableStore is retrieval, plus the telemetry that records it.

Touch is here rather than on WritableStore, which looks wrong until you ask who needs it: it bumps use_count for facts a caller was actually served, and a retrieval-only session has to be able to record that or its reads are invisible to every metric built on use_count -- including the prune predicate that decides what to forget. It writes a counter about a read, never content, so granting it costs a read-only caller nothing it did not already have.

It stayed a method rather than moving inside Search for a concrete reason: Search is also called by the recall pipeline (httpapi/recall.go) and by extraction's dedup query, neither of which is a use. Bumping the counter inside Search would silently count both, conflating recall injections with tool-call usage -- exactly the separation #158 was written to establish.

func ReadOnly

func ReadOnly(r ReadableStore) ReadableStore

ReadOnly narrows a handle so the narrowing survives a type assertion.

Without it the split is advisory: every backend satisfies WritableStore, so a handler holding a ReadableStore backed by a concrete store could assert its way back up to the full interface and write. Wrapping promotes only ReadableStore's method set, so that assertion fails -- the handle does not merely decline to expose the writes, it does not have them.

Scopers return wrapped handles. Callers should not unwrap; there is no exported way to, which is the point.

type RerankMode

type RerankMode string

RerankMode selects how a second-stage cross-encoder rerank score is fused into the final ranking. A threshold (SearchOpts.RerankThreshold) applies independently in every enabled mode.

const (
	// RerankOff disables reranking. The zero value, so rerank is opt-in.
	RerankOff RerankMode = ""
	// RerankBalanced fuses rerank with the first-stage score:
	// Combined = RerankWeight*rerank + (1-RerankWeight)*firstStage. The first
	// stage (FTS + vector) still votes, so a strong keyword/semantic/feedback
	// signal can outweigh a middling rerank score.
	RerankBalanced RerankMode = "balanced"
	// RerankDominant makes the cross-encoder authoritative for ordering: the
	// rerank score is the rank key, with the first-stage score only breaking
	// ties. Best when the first stage surfaces wrong facts.
	RerankDominant RerankMode = "dominant"
	// RerankGate leaves the first-stage order intact and uses rerank only to
	// filter: it reorders nothing, but RerankThreshold still drops low-relevance
	// facts. Smallest behavioral change; attacks false positives, not ordering.
	RerankGate RerankMode = "gate"
)

func ParseRerankMode

func ParseRerankMode(s string) (RerankMode, error)

ParseRerankMode validates and normalizes a mode string (case-insensitive). "" and "off" map to RerankOff; an unknown value is an error.

func (RerankMode) Enabled

func (m RerankMode) Enabled() bool

Enabled reports whether the mode triggers reranking. "off" (any case) and the empty string are disabled.

type RerankPolicy

type RerankPolicy struct {
	Mode             RerankMode
	Threshold        float64
	Candidates       int // search candidate pool
	RecallCandidates int // recall (per-prompt injection) candidate pool
	DocBytes         int // search per-document truncation budget (bytes)
	RecallDocBytes   int // recall per-document truncation budget (bytes)
}

RerankPolicy is memstore's per-deployment rerank search policy: how rerank scores are fused (Mode), the relevance floor (Threshold), and how many first-stage candidates are sent to the cross-encoder per pass. It is distinct from go-embedding's RerankConfig, which says which backend to call.

Candidates and RecallCandidates are separate because the two paths have very different latency budgets: explicit search tolerates a larger pool, while recall runs per-prompt under a tight hook timeout and needs a small one. A zero value means "use the built-in default" (DefaultRerankCandidates for search; DefaultRecallRerankPool for recall).

func RerankPolicyFromEnv

func RerankPolicyFromEnv(prefix string) (RerankPolicy, error)

RerankPolicyFromEnv reads the rerank policy from {prefix}_MODE / _THRESHOLD / _CANDIDATES / _RECALL_CANDIDATES / _DOC_BYTES / _RECALL_DOC_BYTES, cascading to the bare RERANK_* names. These are memstore search policy (how rerank scores are fused and filtered, and how big/long each candidate pass is), distinct from go-embedding's RerankConfig (which backend to call). Unset values yield zero (use built-in defaults). A malformed mode, an out-of-[0,1] threshold, or a non-positive candidate/byte count is an error.

type RerankStats

type RerankStats struct {
	// Dropped is how many reranked facts scored below the floor.
	Dropped int
	// TopDropped is the highest rerank score among them, or 0 when none were
	// dropped. It is the number that makes Dropped actionable: several facts
	// missing by a hair says the floor is too high, several missing by three
	// orders of magnitude says it is doing its job.
	TopDropped float64
}

RerankStats reports what the relevance floor removed from a search. It is filled in only when SearchOpts.RerankStats points at one.

The floor is only as trustworthy as the number behind it, and the default was calibrated from a handful of queries. Without this a floor set too high is indistinguishable from a store that holds little on the subject -- results simply do not appear, and nothing says why (#170).

type SQLiteStore

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

SQLiteStore implements Store backed by a caller-provided SQLite database. It creates memstore_* tables and uses its own version tracking table so it doesn't conflict with any other schema in the same database.

func NewSQLiteStore

func NewSQLiteStore(db *sql.DB, embedder embedding.Embedder, namespace string) (*SQLiteStore, error)

NewSQLiteStore creates a new fact store using the given database connection. It creates memstore_* tables if needed and runs any pending migrations. The caller is responsible for opening and configuring the database (WAL mode, busy timeout, connection limits, etc.).

The namespace parameter partitions facts for multi-tenant isolation. All reads and writes are scoped to this namespace. Use SearchOpts.Namespaces to search across partitions. Pass "" for single-tenant usage.

If embedder is non-nil, the store records its Model() on first embedding operation and validates that subsequent opens use the same model. Pass nil only for write-only or administrative access (Search requires an embedder).

func (*SQLiteStore) Abandon

func (s *SQLiteStore) Abandon(ctx context.Context, id int64, reason string) error

Abandon stops the worker retrying a fact.

Where it lands depends on what the fact was waiting for, and the rule is that abandoning never changes whether a fact is readable:

  • A gate-mode fact was being held pending, so it stays unreadable as 'abandoned'. The content is kept for review and never served.
  • An observe-mode fact was already readable, so it settles at 'regex-clean'. The model screen was given up on; the regex screen it passed on the way in still stands, and that is exactly what the state now claims.

Making an observe-mode fact unreadable here would turn a mode that promises no user-visible change into one that quietly deletes memories whenever the model is unavailable. Abandoning is a decision about the screening process, not the content, so the finding records the outcome without claiming a threat was found.

func (*SQLiteStore) ActiveCount

func (s *SQLiteStore) ActiveCount(ctx context.Context) (int64, error)

ActiveCount returns the number of non-superseded facts.

func (*SQLiteStore) BackfillDetectScores

func (s *SQLiteStore) BackfillDetectScores(ctx context.Context, limit int) (int, error)

BackfillDetectScores scores facts that have none, so the read filter can act on content written before the score was recorded.

Scoring needs the regex engine rather than SQL, which is why this is a pass rather than part of the migration -- and why unscored facts read normally until it runs. Returns how many it scored.

func (*SQLiteStore) BlockedFacts

func (s *SQLiteStore) BlockedFacts(ctx context.Context, limit int) ([]BlockedFact, error)

BlockedFacts returns writes screening rejected, newest first.

func (*SQLiteStore) Breakdown

func (s *SQLiteStore) Breakdown(ctx context.Context) (FactBreakdown, error)

Breakdown aggregates the active-fact histograms in SQL. See the Store interface for why this is not a List plus a loop in Go.

func (*SQLiteStore) BySubject

func (s *SQLiteStore) BySubject(ctx context.Context, subject string, onlyActive bool) ([]Fact, error)

BySubject returns facts for a given subject. If onlyActive is true, superseded facts are excluded.

func (*SQLiteStore) Close

func (s *SQLiteStore) Close() error

Close is a no-op; the caller owns the database connection.

func (*SQLiteStore) Confirm

func (s *SQLiteStore) Confirm(ctx context.Context, id int64) error

Confirm increments a fact's confirmed_count and updates last_confirmed_at.

func (*SQLiteStore) Defer

func (s *SQLiteStore) Defer(ctx context.Context, id int64, reason string) error

Defer records a failed screening attempt, leaving the fact pending for a later tick.

func (*SQLiteStore) Delete

func (s *SQLiteStore) Delete(ctx context.Context, id int64) error

Delete removes a fact by ID. Returns an error if the fact doesn't exist in this namespace.

func (s *SQLiteStore) DeleteLink(ctx context.Context, linkID int64) error

func (*SQLiteStore) DetectScore

func (s *SQLiteStore) DetectScore(ctx context.Context, id int64) (int, error)

DetectScore returns the regex detect score recorded for a fact, or -1 when none has been computed yet.

func (*SQLiteStore) DetectWithheldCount

func (s *SQLiteStore) DetectWithheldCount(ctx context.Context) (int, error)

DetectWithheldCount reports how many facts the read filter is currently hiding.

A blocked read is the silent edge: the memory simply stops appearing, and without a number an operator cannot notice it happening. This is what makes the withholding answerable -- log it at startup, or check it when recall looks thin.

It counts against the threshold in force, so lowering the bar raises the count without anything else changing.

func (*SQLiteStore) EmbedFacts

func (s *SQLiteStore) EmbedFacts(ctx context.Context, batchSize int) (int, error)

EmbedFacts generates vectors for every fact that does not have them yet, using the store's configured embedder. It is the documented re-embed path after an import (see transfer.go), where facts arrive without vectors.

It routes through memstore.EmbedFact so an imported store ends up with exactly what the embed queue and the MCP paths produce: chunked, subject on every chunk, task-prefixed, and a pooled whole-fact marker. Building its own text here is what let this path drift before -- it embedded bare content, unprefixed and unchunked, and wrote only the marker, leaving imported facts invisible to vector search.

Facts are embedded one at a time rather than batched across facts. A fact's own chunks are still batched into a single request inside EmbedFact, and per-fact isolation means one unembeddable fact fails alone instead of stalling the whole import.

func (*SQLiteStore) Exists

func (s *SQLiteStore) Exists(ctx context.Context, content, subject string) (bool, error)

Exists checks whether a fact with the same content and subject exists.

func (*SQLiteStore) FactChunks

func (s *SQLiteStore) FactChunks(ctx context.Context, id int64) ([]FactChunk, error)

FactChunks returns a fact's chunk vectors in ordinal order.

func (*SQLiteStore) Get

func (s *SQLiteStore) Get(ctx context.Context, id int64) (*Fact, error)

Get retrieves a single fact by ID. Returns nil if not found.

func (s *SQLiteStore) GetLink(ctx context.Context, linkID int64) (*Link, error)

GetLink retrieves a single link by ID. Returns (nil, nil) when no link with that ID exists in this namespace, matching Get's not-found contract.

func (s *SQLiteStore) GetLinks(ctx context.Context, factID int64, direction LinkDirection, linkTypes ...string) ([]Link, error)

GetLinks returns edges touching factID filtered by direction and optional link types. LinkOutbound: edges where factID is source, plus bidirectional edges where factID is target. LinkInbound: edges where factID is target, plus bidirectional edges where factID is source. LinkBoth: all edges touching factID.

func (*SQLiteStore) History

func (s *SQLiteStore) History(ctx context.Context, id int64, subject string) ([]HistoryEntry, error)

History returns the supersession chain for a fact. Two modes:

By ID (id > 0): walks backward (predecessors via superseded_by = id) then forward (following SupersededBy pointers) to assemble the full chain.

By subject (id == 0, subject non-empty): returns all facts for that subject including superseded ones, ordered by created_at then id.

func (*SQLiteStore) Insert

func (s *SQLiteStore) Insert(ctx context.Context, f Fact) (int64, error)

Insert adds a single fact and returns its ID. The fact's Namespace field is set to the store's namespace regardless of any value provided.

func (*SQLiteStore) InsertBatch

func (s *SQLiteStore) InsertBatch(ctx context.Context, facts []Fact) error

InsertBatch inserts multiple facts in a single transaction. Each fact's ID field is set on the slice element after insertion.

func (*SQLiteStore) LinkFacts

func (s *SQLiteStore) LinkFacts(ctx context.Context, sourceID, targetID int64, linkType string, bidirectional bool, label string, metadata map[string]any) (int64, error)

LinkFacts creates a directed edge between two facts.

func (*SQLiteStore) List

func (s *SQLiteStore) List(ctx context.Context, opts QueryOpts) ([]Fact, error)

List returns facts matching the given filters, ordered by ID.

func (*SQLiteStore) ListSubsystems

func (s *SQLiteStore) ListSubsystems(ctx context.Context, subject string) ([]string, error)

ListSubsystems returns all distinct non-empty subsystem values, optionally filtered by subject (empty = all subjects).

func (*SQLiteStore) MarkEmbedFailed

func (s *SQLiteStore) MarkEmbedFailed(ctx context.Context, id int64, reason string) error

MarkEmbedFailed quarantines a fact whose embedding failed permanently, so NeedingEmbedding no longer returns it. reason is stored for diagnostics. Superseding replaces the fact with a fresh row that starts unquarantined.

func (*SQLiteStore) NeedingEmbedding

func (s *SQLiteStore) NeedingEmbedding(ctx context.Context, limit int) ([]Fact, error)

NeedingEmbedding returns facts that don't have embeddings yet.

func (*SQLiteStore) PendingFacts

func (s *SQLiteStore) PendingFacts(ctx context.Context, limit int) ([]screening.PendingFact, error)

PendingFacts returns writes awaiting screening, oldest first.

Abandoned facts are excluded by state, which is what keeps one unscreenable fact from heading the queue forever.

func (*SQLiteStore) ReadableFor

func (s *SQLiteStore) ReadableFor(Principal) (ReadableStore, error)

Touch increments use_count and updates last_used_at for the given fact IDs. Silently ignores IDs that don't exist or belong to other namespaces. ReadableFor and WritableFor implement StoreScoper. SQLite is single-user -- there is no per-user narrowing to apply, so the principal's user id is not consulted and the only question is the permission one. Answering it here anyway means the capability split behaves identically on both backends, so a test that passes against SQLite is testing the real contract.

func (*SQLiteStore) RecordInjection

func (s *SQLiteStore) RecordInjection(ctx context.Context, ids []int64) error

RecordInjection increments inject_count and updates last_injected_at for the given fact IDs. Silently ignores IDs that don't exist or belong to other namespaces.

Separate from Touch because recall injection and an explicit search are different evidence: a fact the model went looking for is a stronger signal than one the daemon offered unprompted. Blending them would make a fact that is injected constantly indistinguishable from one that is actively sought, and #157's prune predicate has to tell those apart.

func (*SQLiteStore) ReleaseFact

func (s *SQLiteStore) ReleaseFact(ctx context.Context, id int64) error

ReleaseFact overrides a block, making the fact readable.

This is the false-positive escape hatch, and the reason blocked rows are retained rather than deleted. It is a human decision: nothing in the screening pipeline calls it. The fact becomes grandfathered rather than clean, because it was admitted by override and not by passing a screen.

func (*SQLiteStore) Resolve

func (s *SQLiteStore) Resolve(ctx context.Context, id int64, d screening.Decision) error

Resolve applies a terminal screening decision and records the finding in the same transaction.

func (*SQLiteStore) ScreenCounts

func (s *SQLiteStore) ScreenCounts(ctx context.Context) (map[ScreenState]int, error)

ScreenCounts returns how many facts sit in each screening state.

This is the visibility surface until there is a UI: it answers "is the worker keeping up", "how much of the corpus predates screening", and "has anything been blocked".

func (*SQLiteStore) Search

func (s *SQLiteStore) Search(ctx context.Context, query string, opts SearchOpts) ([]SearchResult, error)

Search performs hybrid FTS5 + vector search, merging and deduplicating results. Requires an embedder; returns an error if none is configured.

func (*SQLiteStore) SearchBatch

func (s *SQLiteStore) SearchBatch(ctx context.Context, queries []string, opts SearchOpts) ([][]SearchResult, error)

SearchBatch performs hybrid search for multiple queries, sharing a single batched embedding call across all queries to avoid N separate API calls. Unlike Search, SearchBatch requires an embedder — batched embedding is its reason to exist. Returns an error if no embedder is configured or if embedding fails after retries.

func (*SQLiteStore) SearchFTS

func (s *SQLiteStore) SearchFTS(ctx context.Context, query string, opts SearchOpts) ([]SearchResult, error)

SearchFTS performs FTS5-only search without requiring an embedder. Results are ranked by BM25 score and subject to the same filtering options as Search, but no embedding is computed or consulted.

func (*SQLiteStore) SetDetectModes

func (s *SQLiteStore) SetDetectModes(write, read ScreenDetectMode)

SetDetectModes selects what the regex screen does on each edge. Empty values restore the block default. See ScreenDetectMode for why the two are separate.

func (*SQLiteStore) SetDetectReadScore

func (s *SQLiteStore) SetDetectReadScore(n int)

SetDetectReadScore sets the score at which a read is withheld. Zero restores DefaultDetectReadScore.

func (*SQLiteStore) SetDetectScoreForTest

func (s *SQLiteStore) SetDetectScoreForTest(ctx context.Context, id int64, score int) error

SetDetectScoreForTest overrides a fact's recorded score. A negative score clears it, reproducing a fact written before the column existed.

Tests use this rather than crafting text that scores a particular number: airlock's rule set is expected to grow, so a test asserting that some phrase scores exactly 80 would fail on a rule addition that changed nothing about memstore.

func (*SQLiteStore) SetEmbedCeiling

func (s *SQLiteStore) SetEmbedCeiling(n int)

SetEmbedCeiling sets the hard byte bound on any single embed request, normally the configured embedder's effective budget (embedding.Config.Limits().MaxBytes). Zero leaves chunk sizing to the retrieval target alone.

func (*SQLiteStore) SetEmbedding

func (s *SQLiteStore) SetEmbedding(ctx context.Context, id int64, emb []float32) error

SetEmbedding stores a computed embedding for a fact.

func (*SQLiteStore) SetFactVectors

func (s *SQLiteStore) SetFactVectors(ctx context.Context, id int64, v FactVectors) error

SetFactVectors replaces a fact's vectors in one transaction.

The fact row's embedding column is written in the same transaction, holding the whole-fact vector. It serves two purposes: it is the marker the embed queue keys off (NeedingEmbedding selects embedding IS NULL), so writing chunks without it would leave the fact queued forever; and it is the vector deduplication compares facts on, which is why it is the whole fact rather than chunk 0. Writing both together is what keeps them from diverging.

func (*SQLiteStore) SetInlineRejectScore

func (s *SQLiteStore) SetInlineRejectScore(score int)

SetInlineRejectScore sets the detect score at which the inline regex screen rejects a write. Zero restores InlineRejectScore.

This is a live control worth reaching for: the inline screen runs on every write in every mode, and regex fires on any text containing a canonical phrasing. Raising it trades detection for a lower false-positive rate on a corpus full of security notes; lowering it does the reverse. Run `memstore scan` before choosing.

func (*SQLiteStore) SetReranker

func (s *SQLiteStore) SetReranker(rr embedding.Reranker)

SetReranker configures a second-stage cross-encoder reranker for Search. Pass a Reranker built with embedding.NewReranker (configured with NormalizeScores so its scores arrive on a [0,1] scale). Intended to be called once at startup before the store serves queries; nil disables reranking.

func (*SQLiteStore) SetScreenMode

func (s *SQLiteStore) SetScreenMode(m ScreenMode)

SetScreenMode selects how the model half of screening participates in writes. See ScreenMode. It does not turn screening on or off: the inline regex screen runs in every mode, so nothing enters this store unscreened.

Only a deployment that actually runs the screening worker may set anything but off. Queuing writes for a model pass that nothing performs leaves them waiting forever -- harmless in observe mode, where they are readable anyway, and a silent outage in gate mode, where they are not.

func (*SQLiteStore) Supersede

func (s *SQLiteStore) Supersede(ctx context.Context, oldID, newID int64) error

Supersede marks an old fact as superseded by a new fact and records the timestamp.

func (*SQLiteStore) TermDocCounts

func (s *SQLiteStore) TermDocCounts(ctx context.Context, terms []string) (map[string]int, int, error)

TermDocCounts returns the number of documents containing each term and the total number of active documents. Uses the fts5vocab virtual table for efficient term frequency lookup.

func (*SQLiteStore) Touch

func (s *SQLiteStore) Touch(ctx context.Context, ids []int64) error
func (s *SQLiteStore) UpdateLink(ctx context.Context, linkID int64, label string, metadata map[string]any) error

UpdateLink patches the label and/or metadata of an existing link. An empty label leaves the existing label unchanged. Metadata keys with nil values are deleted; non-nil values are set.

func (*SQLiteStore) UpdateMetadata

func (s *SQLiteStore) UpdateMetadata(ctx context.Context, id int64, patch map[string]any) error

UpdateMetadata merges a patch into the metadata JSON for a fact. Keys with non-nil values are set; keys with nil values are deleted. Returns an error if the fact doesn't exist in this namespace. Does not trigger FTS re-index or re-embedding (metadata is not indexed).

func (*SQLiteStore) WritableFor

func (s *SQLiteStore) WritableFor(p Principal) (WritableStore, error)

type ScreenDetectMode

type ScreenDetectMode string

ScreenDetectMode is what the regex screen does when a fact trips it.

The two edges fail differently, which is why read and write are configured separately rather than sharing one setting.

A blocked *write* fails loudly: the writer gets ErrScreenRejected and can rephrase. That is a cheap fix, and it leaves the corpus safer by construction rather than relying on fencing to defang the content at read time.

A blocked *read* fails silently: the memory stops appearing and nobody finds out. So reads should demand more evidence than writes -- see DefaultDetectReadScore -- and the number withheld has to stay answerable (DetectWithheldCount).

const (
	// ScreenDetectAllow lets the content through. For a deployment where the
	// false-positive cost outweighs the risk, or one relying on fencing alone.
	ScreenDetectAllow ScreenDetectMode = "allow"

	// ScreenDetectWarn lets the content through and records the score, so a rate can
	// be measured on live traffic before enforcing. On the read edge this is the
	// measurement instrument: nobody has data on how a read bar behaves over time,
	// and fencing already bounds the risk while it is gathered.
	ScreenDetectWarn ScreenDetectMode = "warn"

	// ScreenDetectBlock refuses. The default on both edges.
	ScreenDetectBlock ScreenDetectMode = "block"
)

func ParseScreenDetectMode

func ParseScreenDetectMode(s string) (ScreenDetectMode, error)

ParseScreenDetectMode validates a mode string, defaulting an empty value to block.

type ScreenMode

type ScreenMode string

ScreenMode selects how the model half of injection screening participates in writes.

The regex screen is not part of this choice: it runs inline on every write in every mode, and nothing enters the store without it.

const (
	// ScreenModeOff runs no model screen. Regex is the whole screen and a clean write
	// is readable immediately. The default, and the only sensible setting where no
	// screening worker runs.
	ScreenModeOff ScreenMode = "off"

	// ScreenModeObserve screens with the model but gates nothing. Writes are readable
	// at once and the verdict lands in the findings table.
	//
	// This is what to run before enforcing: it produces the model's opinion on real
	// traffic with no user-visible change, so a false-positive rate can be measured on
	// live writes rather than guessed at.
	ScreenModeObserve ScreenMode = "observe"

	// ScreenModeGate holds writes unreadable until the model clears them, and blocks
	// what the policy rejects.
	//
	// Note the latency this introduces: a fact is invisible from the moment it is
	// written until the worker screens it -- one tick plus one model call, so roughly
	// 30-60s at the default interval. That is harmless for a store read minutes or
	// sessions later, and will break anything that writes a fact and reads it back
	// immediately, tests especially.
	ScreenModeGate ScreenMode = "gate"
)

func ParseScreenMode

func ParseScreenMode(s string) (ScreenMode, error)

ParseScreenMode validates a mode string, defaulting an empty value to off.

type ScreenState

type ScreenState string

ScreenState is a fact's position in the injection-screening lifecycle.

Screening runs asynchronously: a write lands durable but unreadable, and a background worker decides its fate afterwards. This value is what makes "unreadable" true, and it is enforced in SQL on every fact read rather than by a caller-supplied option. Unlike OnlyActive, which callers legitimately turn off to inspect superseded history, there is no query that may see unscreened content.

const (
	// ScreenPending is a write awaiting its screen. Not readable.
	ScreenPending ScreenState = "pending"

	// ScreenClean passed screening. Readable.
	ScreenClean ScreenState = "clean"

	// ScreenBlocked failed screening. Not readable. The row is retained rather than
	// deleted so a block can be reviewed and, if it turns out to be a false
	// positive, released.
	ScreenBlocked ScreenState = "blocked"

	// ScreenAbandoned could not be screened after repeated attempts. Not readable.
	// The content is kept for review but never served and never retried -- see the
	// worker's MaxAttempts.
	ScreenAbandoned ScreenState = "abandoned"

	// ScreenScreening passed the regex screen and is readable, with a model screen
	// still outstanding. Readable.
	//
	// This is observe mode: the model verdict is recorded as a finding but gates
	// nothing, so a write is never held out of reads waiting for it. It satisfies the
	// rule that nothing enters unscreened -- regex screened it -- while producing the
	// model's opinion on live traffic at no cost to availability.
	//
	// It provides no protection FROM the model screen. A fact the model would rate 10
	// is readable the whole time. That is the trade being made deliberately: this mode
	// exists to measure, not to defend.
	ScreenScreening ScreenState = "screening"

	// ScreenRegexClean passed the regex screen with no model screen available.
	// Readable.
	//
	// This is a weaker guarantee than ScreenClean and is recorded as its own state so
	// nothing pretends otherwise: regex is defeated by paraphrase, so a regex-clean
	// fact has been checked against known phrasings and nothing more. It exists
	// because the alternative in a model-less deployment is admitting content with no
	// screen at all, and a weak screen beats none.
	ScreenRegexClean ScreenState = "regex-clean"

	// ScreenGrandfathered predates screening. Readable.
	//
	// Facts already in the store when screening was introduced are readable on
	// arrival. The alternative -- defaulting the existing corpus to pending -- would
	// make every memory disappear the moment the migration ran and stay gone for
	// hours while the backlog drained, which is a worse failure than the one
	// screening prevents. They stay distinguishable from ScreenClean precisely
	// because they have not actually been checked, and the backfill works through
	// them.
	ScreenGrandfathered ScreenState = "grandfathered"
)

type SearchOpts

type SearchOpts struct {
	MaxResults      int                      // default 20
	Subject         string                   // filter by subject (empty = all)
	Category        string                   // filter (empty = all)
	Kind            string                   // filter by kind (empty = all)
	Subsystem       string                   // filter by subsystem (empty = all)
	OnlyActive      bool                     // exclude superseded
	AllNamespaces   bool                     // search across all namespaces (ignores Namespaces field)
	Namespaces      []string                 // search only these namespaces; empty means the store's own namespace
	MetadataFilters []MetadataFilter         // filter on metadata JSON fields
	CreatedAfter    *time.Time               // exclude facts created before this time
	CreatedBefore   *time.Time               // exclude facts created after this time
	DecayHalfLife   time.Duration            // if >0, default exponential time decay for combined scores
	CategoryDecay   map[string]time.Duration // per-category half-life overrides; 0 = no decay for that category
	FTSWeight       float64                  // default 0.6
	VecWeight       float64                  // default 0.4
	// RerankMode selects the second-stage rerank fusion algorithm. Empty (or
	// RerankOff) disables rerank entirely — the engine never calls the reranker
	// unless a mode is set, so callers that don't want rerank (e.g. background
	// extraction) simply leave it off. Requires a reranker on the store.
	RerankMode RerankMode
	// RerankCandidates is how many top first-stage results are sent to the
	// reranker for rescoring; 0 uses the default (40) when rerank is enabled.
	// Larger pools improve recall at the cost of per-query rerank latency.
	RerankCandidates int
	// RerankWeight is rerank's share of the fused score in RerankBalanced mode,
	// in [0,1]: Combined = RerankWeight*rerankScore + (1-RerankWeight)*firstStage.
	// 0 uses the default (0.7). Ignored by RerankDominant and RerankGate.
	RerankWeight float64
	// RerankDocBytes, when > 0, truncates each candidate document to this many
	// bytes before the cross-encoder scores it (passed through as the reranker's
	// MaxDocumentBytes). Rerank latency is superlinear in document length, so
	// this is the per-call latency lever; 0 falls back to the reranker model's
	// registered budget. Truncation ranks on each document's lead content.
	RerankDocBytes int
	// RerankThreshold is the relevance floor: a reranked fact whose normalized
	// [0,1] rerank score falls below it is dropped — the "don't surface wrong
	// context" filter. It applies in every rerank mode and only when rerank
	// actually ran (a degraded backend never filters, so an outage cannot empty
	// the result set). Facts outside the reranked pool are excluded when a
	// threshold is set, since the reranker never vouched for them.
	//
	// It is a pointer because nil and 0 mean different things. nil is "the
	// caller expressed no opinion", and the receiving side supplies its own
	// configured floor; 0 is "no floor", which is what memory_rerank_settings
	// documents threshold 0 to mean. While this was a plain float64 the two were
	// the same value, which was harmless only as long as the default was also
	// zero — the moment a default floor existed, no caller could turn it off
	// (#163).
	RerankThreshold *float64
	// RerankStats, when non-nil, receives what the floor dropped. It is an
	// out-parameter rather than a return value so that reporting costs no change
	// to the Store interface: SearchOpts is copied by value, but the pointer
	// survives the copy, so every backend routing through ScoreResults fills it
	// in without knowing it exists.
	RerankStats *RerankStats
}

SearchOpts controls search behavior.

type SearchResult

type SearchResult struct {
	Fact     Fact
	FTSScore float64
	VecScore float64
	// RerankScore is the reranker's normalized [0,1] relevance for this fact,
	// set only when a reranker rescored it; 0 otherwise.
	RerankScore float64
	Combined    float64
}

SearchResult holds a fact with its relevance scores.

func ScoreResults

func ScoreResults(ctx context.Context, rr embedding.Reranker, query string, fts, vec []SearchResult, opts SearchOpts) ([]SearchResult, error)

ScoreResults builds the final ranked result set from first-stage FTS and vector hits. It deduplicates by fact ID, computes the weighted first-stage relevance, optionally reranks the top opts.RerankCandidates with rr and fuses that relevance in, then applies the confirmation trust boost and recency decay before sorting and truncating to opts.MaxResults.

It is shared by every backend (SQLite and Postgres) so the scoring policy lives in one place. Rerank runs only when rr is non-nil AND opts.RerankMode is enabled — so callers that don't want rerank (e.g. background extraction) just leave the mode off, and it reduces to the first-stage weighted sum. When the reranker is unreachable it degrades to that first-stage ordering (see embedding.IsRerankAvailable) and never applies the threshold, so an outage cannot empty the result set; only a non-availability rerank error — e.g. a 4xx caller bug such as an unknown model — surfaces.

type SessionStore

type SessionStore interface {
	// SaveTurns upserts session turns (idempotent on session_id+uuid).
	SaveTurns(ctx context.Context, sessionID string, turns []SessionTurn) error
	// SaveHook appends a raw Stop hook payload.
	SaveHook(ctx context.Context, payload []byte) error

	// StoreHint stores a context hint produced by the Ollama pipeline.
	StoreHint(ctx context.Context, hint ContextHint) (int64, error)
	// GetPendingHints returns unconsumed hints matching sessionID or cwd (OR semantics).
	// Either may be empty; at least one should be non-empty. Results are ordered by
	// relevance×desirability descending.
	GetPendingHints(ctx context.Context, sessionID, cwd string) ([]ContextHint, error)
	// MarkHintConsumed marks a hint as consumed so it is not re-injected.
	MarkHintConsumed(ctx context.Context, hintID int64) error

	// RecordInjection records that a ref was injected into a session (dedup log).
	// rank is the 0-based position of the item in the candidate list; -1 if unknown.
	RecordInjection(ctx context.Context, sessionID, refID, refType string, rank int) error
	// WasInjected returns true if refID+refType was already injected this session.
	WasInjected(ctx context.Context, sessionID, refID, refType string) (bool, error)

	// RecordFeedback stores Claude's rating of an injected context item.
	RecordFeedback(ctx context.Context, fb ContextFeedback) error
}

SessionStore persists Claude Code session data: turns, hints, injections, and feedback.

type SessionTurn

type SessionTurn struct {
	SessionID string
	UUID      string
	TurnIndex int
	Role      string // "user" or "assistant"
	Content   string
	CWD       string
	CreatedAt time.Time
}

SessionTurn is a single user or assistant text turn extracted from a Claude Code JSONL transcript.

type SessionUserScoper

type SessionUserScoper interface {
	ForUser(userID int64) (SessionStore, error)
}

SessionUserScoper is implemented by session stores that support per-user scoping. ForUser returns a session store whose reads and writes are scoped to the given user. userID must be positive.

type Store

type Store interface {
	// Writes
	Insert(ctx context.Context, f Fact) (int64, error)
	InsertBatch(ctx context.Context, facts []Fact) error
	Supersede(ctx context.Context, oldID, newID int64) error
	Confirm(ctx context.Context, id int64) error
	Touch(ctx context.Context, ids []int64) error // bump use_count for retrieved facts
	Delete(ctx context.Context, id int64) error
	// UpdateMetadata merges a patch into the fact's existing metadata JSON.
	// Keys with non-nil values are set; keys with nil values are deleted.
	// Does not trigger FTS re-index or re-embedding.
	UpdateMetadata(ctx context.Context, id int64, patch map[string]any) error

	// Reads
	Get(ctx context.Context, id int64) (*Fact, error)
	List(ctx context.Context, opts QueryOpts) ([]Fact, error)
	BySubject(ctx context.Context, subject string, onlyActive bool) ([]Fact, error)
	Exists(ctx context.Context, content, subject string) (bool, error)
	ActiveCount(ctx context.Context) (int64, error)
	// Breakdown returns per-subject, per-category, and per-kind counts of
	// active facts, aggregated in the database. Callers that only need the
	// histogram must not pull whole rows to build it: memory_status did, and
	// on a 5,791-fact store that shipped every content field and embedding
	// across the wire to produce three small maps (#150). Facts with an empty
	// kind are omitted from Kinds.
	Breakdown(ctx context.Context) (FactBreakdown, error)
	// History returns the supersession chain for a fact. If id > 0, it walks
	// the chain containing that fact. If subject is non-empty (and id == 0),
	// it returns all facts for that subject ordered by creation time.
	History(ctx context.Context, id int64, subject string) ([]HistoryEntry, error)

	// Hybrid search (FTS5 + vector); requires an embedder.
	Search(ctx context.Context, query string, opts SearchOpts) ([]SearchResult, error)
	// SearchBatch shares a single batched embedding call across queries.
	SearchBatch(ctx context.Context, queries []string, opts SearchOpts) ([][]SearchResult, error)
	// SearchFTS performs FTS5-only search without requiring an embedder.
	// Results are ranked by BM25 score. Useful when Ollama is unavailable
	// or when low-latency retrieval is required (e.g. hook contexts).
	SearchFTS(ctx context.Context, query string, opts SearchOpts) ([]SearchResult, error)

	// ListSubsystems returns all distinct non-empty subsystem values,
	// optionally filtered by subject (empty = all subjects).
	ListSubsystems(ctx context.Context, subject string) ([]string, error)

	// Embedding pipeline
	NeedingEmbedding(ctx context.Context, limit int) ([]Fact, error)
	SetEmbedding(ctx context.Context, id int64, emb []float32) error
	// SetFactVectors replaces a fact's vectors, and is the write path for a
	// chunked embedding. It is atomic: the chunk rows and the fact row's
	// whole-fact marker are written together, so the two cannot diverge.
	// Passing no chunks clears the fact's vectors entirely.
	SetFactVectors(ctx context.Context, id int64, v FactVectors) error
	// FactChunks returns a fact's chunk vectors in ordinal order.
	FactChunks(ctx context.Context, id int64) ([]FactChunk, error)
	// MarkEmbedFailed quarantines a fact whose embedding failed permanently
	// so NeedingEmbedding stops returning it. reason is stored for diagnostics.
	MarkEmbedFailed(ctx context.Context, id int64, reason string) error
	EmbedFacts(ctx context.Context, batchSize int) (int, error)

	// Links — explicit graph edges between facts.
	// LinkFacts creates a directed edge from sourceID to targetID.
	// If bidirectional is true, the edge is traversable in both directions.
	// linkType is a short discriminator string (e.g. "passage", "event").
	// label is a human-readable description of the edge (may be empty).
	// metadata holds domain-specific properties (may be nil).
	LinkFacts(ctx context.Context, sourceID, targetID int64, linkType string, bidirectional bool, label string, metadata map[string]any) (int64, error)
	// GetLink retrieves a single link by ID. Returns (nil, nil) when no link
	// with that ID is visible in the caller's scope (absent, or owned by another
	// user) -- matching Get's not-found contract. A non-nil error signals a real
	// failure (query/scan), never a plain miss.
	GetLink(ctx context.Context, linkID int64) (*Link, error)
	// GetLinks returns edges touching factID filtered by direction.
	// If linkTypes is non-empty, only edges with a matching link_type are returned.
	GetLinks(ctx context.Context, factID int64, direction LinkDirection, linkTypes ...string) ([]Link, error)
	// UpdateLink patches the label and/or metadata of an existing link.
	// Pass an empty label to leave it unchanged. Metadata keys with nil values are deleted.
	UpdateLink(ctx context.Context, linkID int64, label string, metadata map[string]any) error
	// DeleteLink removes a link by ID.
	DeleteLink(ctx context.Context, linkID int64) error

	Close() error
}

type StoreScoper

type StoreScoper interface {
	ReadableFor(p Principal) (ReadableStore, error)
	WritableFor(p Principal) (WritableStore, error)
}

StoreScoper mints capability-typed handles for a principal. It is the single place a writable handle can come from, which is what makes the split worth having: one admission decision, in one function, instead of an authorization check at every call site that might mutate something.

WritableFor returns ErrNotPermitted when the principal may not write. That is a refusal to issue authority, not a failed operation -- the caller never gets far enough to attempt one.

type TermCounter

type TermCounter interface {
	TermDocCounts(ctx context.Context, terms []string) (counts map[string]int, totalDocs int, err error)
}

TermCounter is optionally implemented by stores that support IDF-based keyword extraction. TermDocCounts returns the document frequency for each term and the total number of active documents in the store's namespace.

type UserScoper

type UserScoper interface {
	ForUser(userID int64) (Store, error)
}

UserScoper is implemented by backends that support per-user scoping. ForUser returns a store whose every read and write is scoped to the given user. Backends without multi-user support (SQLite) do not implement it.

type WhoAmIResponse

type WhoAmIResponse struct {
	// Name and Source identify the credential: the token row's name, and how
	// it was established ("bearer", "mtls", "legacy").
	Name   string `json:"name,omitempty"`
	Source string `json:"source,omitempty"`

	// Authenticated is false when the deployment has no auth configured at
	// all. Such a deployment permits every route, which is what Allows then
	// reports -- a client must not read "no credential" as "no permissions".
	Authenticated bool `json:"authenticated"`

	// Scopes is what the token literally carries. Empty is meaningful: it is
	// how pre-enforcement tokens are represented, and they hold read+write.
	Scopes []string `json:"scopes"`

	// Allows is every scope this credential may exercise.
	Allows []string `json:"allows"`
}

WhoAmIResponse describes what the calling credential may do.

Allows is the field callers should shape themselves from. It is the effective set, computed by the daemon, rather than the raw Scopes the token carries. Returning only the raw scopes would push the implication rules (admin implies read+write, an empty set means read+write, ingest is implied by nothing) into every client, giving the rules a second implementation that can drift from this one. Scopes is included for display and audit, not for deciding anything.

type WritableStore

type WritableStore interface {
	ReadableStore

	Insert(ctx context.Context, f Fact) (int64, error)
	InsertBatch(ctx context.Context, facts []Fact) error
	Supersede(ctx context.Context, oldID, newID int64) error
	Confirm(ctx context.Context, id int64) error
	Delete(ctx context.Context, id int64) error
	UpdateMetadata(ctx context.Context, id int64, patch map[string]any) error
	LinkFacts(ctx context.Context, sourceID, targetID int64, linkType string, bidirectional bool, label string, metadata map[string]any) (int64, error)
	UpdateLink(ctx context.Context, linkID int64, label string, metadata map[string]any) error
	DeleteLink(ctx context.Context, linkID int64) error
}

WritableStore adds the content mutations to ReadableStore. Everything on it changes what memstore knows; nothing on it is maintenance.

Directories

Path Synopsis
Package chunk defines the chunker contract for the document corpus and the line-window fallback chunker.
Package chunk defines the chunker contract for the document corpus and the line-window fallback chunker.
gosrc
Package gosrc implements the Go source chunker from docs/code-chunking.md: cAST-style split-then-merge over the stdlib AST.
Package gosrc implements the Go source chunker from docs/code-chunking.md: cAST-style split-then-merge over the stdlib AST.
markdown
Package markdown implements the markdown chunker from docs/document-chunking.md: front matter parsed into document fields, sections segmented at headings, oversized sections split at top-level block boundaries, undersized sibling sections merged, fences and tables never split.
Package markdown implements the markdown chunker from docs/document-chunking.md: front matter parsed into document fields, sections segmented at headings, oversized sections split at top-level block boundaries, undersized sibling sections merged, fences and tables never split.
cmd
memstore command
Command memstore provides CLI access to a memstore database.
Command memstore provides CLI access to a memstore database.
memstore-mcp command
Command memstore-mcp is an MCP server that gives Claude (or any MCP client) persistent, searchable memory backed by SQLite with hybrid FTS5 + vector search.
Command memstore-mcp is an MCP server that gives Claude (or any MCP client) persistent, searchable memory backed by SQLite with hybrid FTS5 + vector search.
memstored command
memstored is the memstore network daemon.
memstored is the memstore network daemon.
Package httpapi provides an HTTP/JSON API handler that wraps a memstore.Store.
Package httpapi provides an HTTP/JSON API handler that wraps a memstore.Store.
Package httpclient provides a memstore.Store implementation that talks to a memstored daemon over HTTP.
Package httpclient provides a memstore.Store implementation that talks to a memstored daemon over HTTP.
internal
caetl
Package caetl ("cert ETL") provides a small, opinionated wrapper around crypto/x509 for generating a self-signed CA and issuing server / client leaf certificates from it.
Package caetl ("cert ETL") provides a small, opinionated wrapper around crypto/x509 for generating a self-signed CA and issuing server / client leaf certificates from it.
conformance
Package conformance provides a shared Store contract test suite that can be wired against any memstore.Store implementation.
Package conformance provides a shared Store contract test suite that can be wired against any memstore.Store implementation.
fence
Package fence marks the boundary between memstore's own voice and the stored content it returns to a model.
Package fence marks the boundary between memstore's own voice and the stored content it returns to a model.
hookcapture
Package hookcapture implements the Claude Code Stop hook: it archives the hook payload, tracks per-session state, emits the "store your decisions" nudge, and drains the session-transcript upload backlog one entry per event.
Package hookcapture implements the Claude Code Stop hook: it archives the hook payload, tracks per-session state, emits the "store your decisions" nudge, and drains the session-transcript upload backlog one entry per event.
screening
Package screening decides whether a write may enter the store.
Package screening decides whether a write may enter the store.
Package mcpserver's session instructions and the read-only decision behind them.
Package mcpserver's session instructions and the read-only decision behind them.
Package pgstore implements the memstore.Store interface backed by PostgreSQL with pgvector for vector search and tsvector/GIN for full-text search.
Package pgstore implements the memstore.Store interface backed by PostgreSQL with pgvector for vector search and tsvector/GIN for full-text search.

Jump to

Keyboard shortcuts

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