Documentation
¶
Overview ¶
Package pgstore implements the memstore.Store interface backed by PostgreSQL with pgvector for vector search and tsvector/GIN for full-text search.
Index ¶
- Variables
- func EnsureUser(ctx context.Context, pool *pgxpool.Pool, namespace, name string) (int64, error)
- func InitIdentity(ctx context.Context, pool *pgxpool.Pool, namespace, defaultUser string) error
- func IsMemstoreToken(s string) bool
- func LookupUserID(ctx context.Context, pool *pgxpool.Pool, namespace, name string) (int64, error)
- func ResetEmbeddings(ctx context.Context, pool *pgxpool.Pool) (int64, error)
- type IssueOpts
- type OAuthUserStore
- func (u *OAuthUserStore) Create(ctx context.Context, id rpuser.Identity) (rpuser.User, error)
- func (u *OAuthUserStore) LookupBySubject(ctx context.Context, issuer, subject string) (rpuser.User, error)
- func (u *OAuthUserStore) SyncEmail(ctx context.Context, userKey, email string, verified bool) error
- type PostgresStore
- func (s *PostgresStore) Abandon(ctx context.Context, id int64, reason string) error
- func (s *PostgresStore) ActiveCount(ctx context.Context) (int64, error)
- func (s *PostgresStore) BackfillDetectScores(ctx context.Context, limit int) (int, error)
- func (s *PostgresStore) BlockedFacts(ctx context.Context, limit int) ([]memstore.BlockedFact, error)
- func (s *PostgresStore) Breakdown(ctx context.Context) (memstore.FactBreakdown, error)
- func (s *PostgresStore) BySubject(ctx context.Context, subject string, onlyActive bool) ([]memstore.Fact, error)
- func (s *PostgresStore) Close() error
- func (s *PostgresStore) Confirm(ctx context.Context, id int64) error
- func (s *PostgresStore) Defer(ctx context.Context, id int64, reason string) error
- func (s *PostgresStore) Delete(ctx context.Context, id int64) error
- func (s *PostgresStore) DeleteDocuments(ctx context.Context, repoURL string, paths []string) (int64, error)
- func (s *PostgresStore) DeleteLink(ctx context.Context, linkID int64) error
- func (s *PostgresStore) DetectWithheldCount(ctx context.Context) (int, error)
- func (s *PostgresStore) EmbedFacts(ctx context.Context, batchSize int) (int, error)
- func (s *PostgresStore) Exists(ctx context.Context, content, subject string) (bool, error)
- func (s *PostgresStore) FactChunks(ctx context.Context, id int64) ([]memstore.FactChunk, error)
- func (s *PostgresStore) ForUser(userID int64) (memstore.Store, error)
- func (s *PostgresStore) Get(ctx context.Context, id int64) (*memstore.Fact, error)
- func (s *PostgresStore) GetDocument(ctx context.Context, id int64) (*memstore.Document, error)
- func (s *PostgresStore) GetDocumentChunks(ctx context.Context, documentID int64) ([]memstore.DocumentChunk, error)
- func (s *PostgresStore) GetLink(ctx context.Context, linkID int64) (*memstore.Link, error)
- func (s *PostgresStore) GetLinks(ctx context.Context, factID int64, direction memstore.LinkDirection, ...) ([]memstore.Link, error)
- func (s *PostgresStore) History(ctx context.Context, id int64, subject string) ([]memstore.HistoryEntry, error)
- func (s *PostgresStore) Insert(ctx context.Context, f memstore.Fact) (int64, error)
- func (s *PostgresStore) InsertBatch(ctx context.Context, facts []memstore.Fact) error
- func (s *PostgresStore) LinkFacts(ctx context.Context, sourceID, targetID int64, linkType string, ...) (int64, error)
- func (s *PostgresStore) List(ctx context.Context, opts memstore.QueryOpts) ([]memstore.Fact, error)
- func (s *PostgresStore) ListDocuments(ctx context.Context, repoURL string) ([]memstore.DocumentInfo, error)
- func (s *PostgresStore) ListSubsystems(ctx context.Context, subject string) ([]string, error)
- func (s *PostgresStore) MarkEmbedFailed(ctx context.Context, id int64, reason string) error
- func (s *PostgresStore) NeedingEmbedding(ctx context.Context, limit int) ([]memstore.Fact, error)
- func (s *PostgresStore) PendingFacts(ctx context.Context, limit int) ([]screening.PendingFact, error)
- func (s *PostgresStore) ReadableFor(p memstore.Principal) (memstore.ReadableStore, error)
- func (s *PostgresStore) RecordInjection(ctx context.Context, ids []int64) error
- func (s *PostgresStore) ReleaseFact(ctx context.Context, id int64) error
- func (s *PostgresStore) Resolve(ctx context.Context, id int64, d screening.Decision) error
- func (s *PostgresStore) ScreenCounts(ctx context.Context) (map[memstore.ScreenState]int, error)
- func (s *PostgresStore) Search(ctx context.Context, query string, opts memstore.SearchOpts) ([]memstore.SearchResult, error)
- func (s *PostgresStore) SearchBatch(ctx context.Context, queries []string, opts memstore.SearchOpts) ([][]memstore.SearchResult, error)
- func (s *PostgresStore) SearchDocumentChunks(ctx context.Context, query string, opts memstore.DocumentSearchOpts) ([]memstore.DocumentSearchResult, error)
- func (s *PostgresStore) SearchFTS(ctx context.Context, query string, opts memstore.SearchOpts) ([]memstore.SearchResult, error)
- func (s *PostgresStore) ServiceScope() *PostgresStore
- func (s *PostgresStore) SetDetectModes(write, read memstore.ScreenDetectMode)
- func (s *PostgresStore) SetDetectReadScore(n int)
- func (s *PostgresStore) SetDetectScoreForTest(ctx context.Context, id int64, score int) error
- func (s *PostgresStore) SetEmbedCeiling(n int)
- func (s *PostgresStore) SetEmbedding(ctx context.Context, id int64, emb []float32) error
- func (s *PostgresStore) SetFactVectors(ctx context.Context, id int64, v memstore.FactVectors) error
- func (s *PostgresStore) SetInlineRejectScore(score int)
- func (s *PostgresStore) SetReranker(rr embedding.Reranker)
- func (s *PostgresStore) SetScreenMode(m memstore.ScreenMode)
- func (s *PostgresStore) Supersede(ctx context.Context, oldID, newID int64) error
- func (s *PostgresStore) TermDocCounts(ctx context.Context, terms []string) (map[string]int, int, error)
- func (s *PostgresStore) Touch(ctx context.Context, ids []int64) error
- func (s *PostgresStore) UpdateLink(ctx context.Context, linkID int64, label string, metadata map[string]any) error
- func (s *PostgresStore) UpdateMetadata(ctx context.Context, id int64, patch map[string]any) error
- func (s *PostgresStore) UpsertDocument(ctx context.Context, doc memstore.Document, chunks []memstore.DocumentChunk) (int64, error)
- func (s *PostgresStore) WritableFor(p memstore.Principal) (memstore.WritableStore, error)
- type QueryEmbedFunc
- type SessionStore
- func (s *SessionStore) FeedbackScore(ctx context.Context, refID, refType string) (float64, error)
- func (s *SessionStore) FeedbackScores(ctx context.Context, refIDs []string, refType string) (map[string]memstore.FeedbackStat, error)
- func (s *SessionStore) ForUser(userID int64) (memstore.SessionStore, error)
- func (s *SessionStore) GetInjectedFactIDs(ctx context.Context, sessionID string) ([]int64, error)
- func (s *SessionStore) GetInjectedHints(ctx context.Context, sessionID string) ([]memstore.ContextHint, error)
- func (s *SessionStore) GetPendingHints(ctx context.Context, sessionID, cwd string) ([]memstore.ContextHint, error)
- func (s *SessionStore) GetSessionTurns(ctx context.Context, sessionID string) ([]memstore.SessionTurn, error)
- func (s *SessionStore) MarkHintConsumed(ctx context.Context, hintID int64) error
- func (s *SessionStore) RecordFeedback(ctx context.Context, fb memstore.ContextFeedback) error
- func (s *SessionStore) RecordInjection(ctx context.Context, sessionID, refID, refType string, rank int) error
- func (s *SessionStore) SaveHook(ctx context.Context, payload []byte) error
- func (s *SessionStore) SaveTurns(ctx context.Context, sessionID string, turns []memstore.SessionTurn) error
- func (s *SessionStore) ServiceScope() *SessionStore
- func (s *SessionStore) StoreHint(ctx context.Context, hint memstore.ContextHint) (int64, error)
- func (s *SessionStore) UnratedFactSessions(ctx context.Context) ([]string, error)
- func (s *SessionStore) UserID() int64
- func (s *SessionStore) WasInjected(ctx context.Context, sessionID, refID, refType string) (bool, error)
- type SimilarityPair
- type SimilaritySample
- type TokenInfo
- type TokenStore
- func (s *TokenStore) EnsureLegacyToken(ctx context.Context, key string) (bool, error)
- func (s *TokenStore) Issue(ctx context.Context, name string, opts IssueOpts) (string, error)
- func (s *TokenStore) List(ctx context.Context) ([]TokenInfo, error)
- func (s *TokenStore) Revoke(ctx context.Context, name string) (int, error)
- func (s *TokenStore) RevokeByUser(ctx context.Context, userID int64) (int, error)
- func (s *TokenStore) Rotate(ctx context.Context, name string) (string, error)
- func (s *TokenStore) Verify(ctx context.Context, token string) (VerifyResult, error)
- type VerifyResult
Constants ¶
This section is empty.
Variables ¶
var ErrNoDefaultUser = errors.New("no default user recorded -- run 'memstore admin tier3-init --default-user <name>' before starting memstored")
ErrNoDefaultUser is returned when the database has a schema but no owner recorded in memstore_meta. It is the one startup failure a deployment can resolve by naming a user -- `memstore admin tier3-init --default-user`, or memstored's --default-user on first start -- so callers match on it.
var ErrTokenInvalid = errors.New("token invalid")
ErrTokenInvalid is returned by Verify for any reason a token doesn't authenticate (not found, revoked, expired). Callers must not distinguish between these reasons in error messages — they all collapse to 401.
var ErrUserNotFound = errors.New("user not found")
ErrUserNotFound reports that no user of that name exists in any namespace. Callers may safely suggest creating one.
var ErrUserWrongNamespace = errors.New("user found in a different namespace")
ErrUserWrongNamespace reports that the user exists, but under a different namespace than the caller asked for. It is deliberately NOT an ErrUserNotFound: creating the user would produce a duplicate in the wrong namespace rather than fix anything. The caller passed the wrong --namespace.
Functions ¶
func EnsureUser ¶
EnsureUser resolves or creates the user row for name in namespace and returns its id. Idempotent. Intended for admin tooling (user provisioning) and tests; it does not touch memstore_meta['default_user'].
func InitIdentity ¶
InitIdentity seeds the identity schema with an operator-supplied default user. This is the implementation behind 'memstore admin tier3-init --default-user <name>'.
Two cases:
- Schema already at V4 (fresh DB whose migration took the no-user path): ensure the user row and the default_user meta key exist. Idempotent.
- Schema below V4 (typically because migrateV4's inference failed and the whole transaction rolled back): run the full V4 work -- shared with migrateV4 via migrateV4As so the two paths cannot drift -- with the explicit user, and record schema version 4.
func IsMemstoreToken ¶
IsMemstoreToken reports whether the given string looks like a token issued by this package (i.e. carries the mst_ prefix). Useful when operators paste a legacy key and you want to warn them it's not in the new format.
func LookupUserID ¶
LookupUserID returns the id of an existing user in the namespace. Unlike EnsureUser it never creates a row -- it returns a not-found error when the user does not exist, so callers (e.g. disable-user) cannot accidentally create the principal they meant to act on.
When the name exists in some other namespace, the error names those namespaces and wraps ErrUserWrongNamespace.
func ResetEmbeddings ¶ added in v0.5.1
ResetEmbeddings drops every stored vector and forgets the recorded embedder fingerprint, so the daemon can be started under a different embedding model. It returns how many fact vectors were cleared.
This is the operator-side half of reconcileEmbedder: a model or dimension change is refused at open because vectors from two models do not compare, and silently discarding them would hide a configuration drift. Running this deliberately, then starting the daemon with the new model, records the new fingerprint and lets the embed queue rebuild every vector.
The reset is deployment-wide, not namespace-scoped: the fingerprint is one row per database and the embedder is one per daemon.
Types ¶
type IssueOpts ¶
type IssueOpts struct {
UserID int64 // required; Issue returns an error if zero
Scopes []string // optional, e.g. {"read","write","admin"}
Expires time.Duration // 0 = no expiry
}
IssueOpts configures a new token.
type OAuthUserStore ¶
type OAuthUserStore struct {
// contains filtered or unexported fields
}
OAuthUserStore implements rpuser.UserStore over memstore_users, scoped to one namespace. Construct it with NewOAuthUserStore.
func NewOAuthUserStore ¶
func NewOAuthUserStore(s *PostgresStore) *OAuthUserStore
NewOAuthUserStore returns a user store backed by s, for the namespace s was constructed with.
func (*OAuthUserStore) LookupBySubject ¶
func (u *OAuthUserStore) LookupBySubject(ctx context.Context, issuer, subject string) (rpuser.User, error)
LookupBySubject returns the user for (issuer, subject), or rpuser.ErrNotFound. It runs on every authenticated request and never writes.
type PostgresStore ¶
type PostgresStore struct {
// contains filtered or unexported fields
}
PostgresStore implements memstore.Store backed by PostgreSQL. It uses pgvector for vector similarity search and tsvector with GIN indexing for full-text search. No mutex is needed -- Postgres handles concurrency natively via MVCC.
func New ¶
func New(ctx context.Context, pool *pgxpool.Pool, embedder embedding.Embedder, namespace string, vecDim, cacheSize int) (*PostgresStore, error)
New creates a new PostgresStore using the given connection pool. It creates memstore_* tables if needed and runs any pending migrations.
The namespace parameter partitions facts for multi-tenant isolation. vecDim is the embedding vector dimension (e.g. 768 for embeddinggemma). If vecDim is 0, embedding columns are created without a dimension constraint.
cacheSize bounds the in-process LRU that caches query embeddings on the search path; a value <= 0 disables it.
func (*PostgresStore) Abandon ¶
Abandon stops the worker retrying a fact.
Abandoning never changes whether a fact is readable: a gate-mode fact was being held, so it stays unreadable as 'abandoned'; an observe-mode fact was already readable, so it settles at 'regex-clean', which is exactly what it passed on the way in. See the SQLiteStore method for why.
func (*PostgresStore) ActiveCount ¶
func (s *PostgresStore) ActiveCount(ctx context.Context) (int64, error)
ActiveCount returns the number of non-superseded facts.
func (*PostgresStore) BackfillDetectScores ¶
BackfillDetectScores scores facts that have none, so the read filter can act on content written before the score was recorded. Returns how many it scored.
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. Mirrors SQLiteStore.BackfillDetectScores.
func (*PostgresStore) BlockedFacts ¶
func (s *PostgresStore) BlockedFacts(ctx context.Context, limit int) ([]memstore.BlockedFact, error)
BlockedFacts returns writes screening rejected, newest first.
Content is included deliberately: an operator judging whether a block was a false positive has to see what was blocked, and a blocked write exists nowhere else. Callers rendering it to a model must fence it like any stored content.
func (*PostgresStore) Breakdown ¶
func (s *PostgresStore) Breakdown(ctx context.Context) (memstore.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 (*PostgresStore) BySubject ¶
func (s *PostgresStore) BySubject(ctx context.Context, subject string, onlyActive bool) ([]memstore.Fact, error)
BySubject returns facts for a given subject.
func (*PostgresStore) Close ¶
func (s *PostgresStore) Close() error
Close is a no-op; the caller owns the connection pool.
func (*PostgresStore) Confirm ¶
func (s *PostgresStore) Confirm(ctx context.Context, id int64) error
Confirm increments a fact's confirmed_count and updates last_confirmed_at.
func (*PostgresStore) Delete ¶
func (s *PostgresStore) Delete(ctx context.Context, id int64) error
Delete removes a fact by ID.
func (*PostgresStore) DeleteDocuments ¶
func (s *PostgresStore) DeleteDocuments(ctx context.Context, repoURL string, paths []string) (int64, error)
DeleteDocuments removes the named documents for a repo identity; chunks cascade. Returns the number of documents actually deleted -- paths that were never stored (or belong to another user) simply do not count.
func (*PostgresStore) DeleteLink ¶
func (s *PostgresStore) DeleteLink(ctx context.Context, linkID int64) error
DeleteLink removes a link by ID.
func (*PostgresStore) DetectWithheldCount ¶
func (s *PostgresStore) DetectWithheldCount(ctx context.Context) (int, error)
DetectWithheldCount reports how many facts the read filter is currently hiding. A blocked read is the silent edge, so the number has to stay answerable.
func (*PostgresStore) EmbedFacts ¶
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 (*PostgresStore) Exists ¶
Exists checks whether a fact with the same content and subject exists.
func (*PostgresStore) FactChunks ¶
FactChunks returns a fact's chunk vectors in ordinal order.
func (*PostgresStore) ForUser ¶
func (s *PostgresStore) ForUser(userID int64) (memstore.Store, error)
func (*PostgresStore) GetDocument ¶
GetDocument returns a document by id, or (nil, nil) when no document with that id is visible in the caller's scope.
func (*PostgresStore) GetDocumentChunks ¶
func (s *PostgresStore) GetDocumentChunks(ctx context.Context, documentID int64) ([]memstore.DocumentChunk, error)
GetDocumentChunks returns a document's chunks ordered by ordinal. A document outside the caller's scope yields no chunks, matching GetDocument's not-found contract.
func (*PostgresStore) GetLink ¶
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.
func (*PostgresStore) GetLinks ¶
func (s *PostgresStore) GetLinks(ctx context.Context, factID int64, direction memstore.LinkDirection, linkTypes ...string) ([]memstore.Link, error)
GetLinks returns edges touching factID filtered by direction.
func (*PostgresStore) History ¶
func (s *PostgresStore) History(ctx context.Context, id int64, subject string) ([]memstore.HistoryEntry, error)
History returns the supersession chain for a fact.
func (*PostgresStore) InsertBatch ¶
InsertBatch inserts multiple facts in a single transaction.
func (*PostgresStore) LinkFacts ¶
func (s *PostgresStore) 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 (*PostgresStore) ListDocuments ¶
func (s *PostgresStore) ListDocuments(ctx context.Context, repoURL string) ([]memstore.DocumentInfo, error)
ListDocuments returns the manifest view of every stored document for a repo identity, ordered by path. repoURL "" selects loose files (repo_url IS NULL) -- unlike search, where "" means unfiltered, a manifest is always scoped to one identity.
func (*PostgresStore) ListSubsystems ¶
ListSubsystems returns all distinct non-empty subsystem values.
func (*PostgresStore) MarkEmbedFailed ¶
MarkEmbedFailed quarantines a fact whose embedding failed permanently, so NeedingEmbedding no longer returns it. reason is stored for diagnostics. Clearing the embedding (e.g. on a content edit) re-queues the fact only if the caller also resets embed_failed_at; superseding replaces the fact with a fresh row that starts unquarantined.
func (*PostgresStore) NeedingEmbedding ¶
NeedingEmbedding returns facts that don't have embeddings yet.
func (*PostgresStore) PendingFacts ¶
func (s *PostgresStore) PendingFacts(ctx context.Context, limit int) ([]screening.PendingFact, error)
PendingFacts returns writes awaiting screening, oldest first.
The claim is not locked. Ticks within one worker do not overlap, and two daemons against one database would at worst screen the same fact twice -- which is wasteful but harmless, because Resolve only applies to a row still pending and so the second verdict lands as a no-op rather than a second finding.
func (*PostgresStore) ReadableFor ¶
func (s *PostgresStore) ReadableFor(p memstore.Principal) (memstore.ReadableStore, error)
ForUser returns a cheap clone of the store scoped to the given user: every read and write the clone performs carries the owner predicate for userID. The clone shares the pool, embedder, query cache, and reranker with the receiver and runs no migrations. userID must be positive. ReadableFor and WritableFor implement memstore.StoreScoper, narrowing what ForUser already returns. ForUser has always bound the identity into the handle; these decide how much authority the handle carries, so the one place a writable store can come from is also the one place the decision is made.
func (*PostgresStore) RecordInjection ¶
func (s *PostgresStore) RecordInjection(ctx context.Context, ids []int64) error
RecordInjection increments inject_count and updates last_injected_at for the given fact IDs.
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. See SQLite RecordInjection.
func (*PostgresStore) ReleaseFact ¶
func (s *PostgresStore) ReleaseFact(ctx context.Context, id int64) error
ReleaseFact overrides a block, making the fact readable.
The false-positive escape hatch, and why blocked rows are retained rather than deleted. It is a human decision: nothing in the pipeline calls it. The fact becomes grandfathered, not clean -- it was admitted by override, not by passing a screen.
func (*PostgresStore) Resolve ¶
Resolve applies a terminal screening decision and records the finding atomically.
func (*PostgresStore) ScreenCounts ¶
func (s *PostgresStore) ScreenCounts(ctx context.Context) (map[memstore.ScreenState]int, error)
ScreenCounts returns how many facts sit in each screening state.
func (*PostgresStore) Search ¶
func (s *PostgresStore) Search(ctx context.Context, query string, opts memstore.SearchOpts) ([]memstore.SearchResult, error)
Search performs hybrid tsvector + pgvector search, merging and deduplicating results.
func (*PostgresStore) SearchBatch ¶
func (s *PostgresStore) SearchBatch(ctx context.Context, queries []string, opts memstore.SearchOpts) ([][]memstore.SearchResult, error)
SearchBatch performs hybrid search for multiple queries with shared embedding.
func (*PostgresStore) SearchDocumentChunks ¶
func (s *PostgresStore) SearchDocumentChunks(ctx context.Context, query string, opts memstore.DocumentSearchOpts) ([]memstore.DocumentSearchResult, error)
SearchDocumentChunks is FTS over chunk content, per the measured design in docs/embedding-model-routing.md: an exact english pass first; then, only when the exact pass leaves room below MaxResults, a decomposed-identifier pass against the 'simple' weight-D lexemes, appended after the exact hits and marked Fallback. Appending rather than blending is the measured property: the fallback can only fill space an exact match was not using, so queries that already work keep their ranking.
func (*PostgresStore) SearchFTS ¶
func (s *PostgresStore) SearchFTS(ctx context.Context, query string, opts memstore.SearchOpts) ([]memstore.SearchResult, error)
SearchFTS performs tsvector-only search without requiring an embedder.
func (*PostgresStore) ServiceScope ¶
func (s *PostgresStore) ServiceScope() *PostgresStore
ServiceScope returns a clone of the store with NO user predicate: it sees and can touch every user's facts and links in the namespace.
This scope is PRIVILEGED. It exists only for daemon-internal workers (embedding backfill, curation) that must operate across users; never hand it to anything serving an end-user request.
func (*PostgresStore) SetDetectModes ¶
func (s *PostgresStore) SetDetectModes(write, read memstore.ScreenDetectMode)
SetDetectModes selects what the regex screen does on each edge. Empty values restore the block default. See memstore.ScreenDetectMode for why the two edges are configured separately.
func (*PostgresStore) SetDetectReadScore ¶
func (s *PostgresStore) SetDetectReadScore(n int)
SetDetectReadScore sets the score at which a read is withheld. Zero restores memstore.DefaultDetectReadScore.
func (*PostgresStore) SetDetectScoreForTest ¶
SetDetectScoreForTest overrides a fact's recorded score. A negative score clears it, reproducing a fact written before the column existed.
func (*PostgresStore) SetEmbedCeiling ¶
func (s *PostgresStore) 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 (*PostgresStore) SetEmbedding ¶
SetEmbedding stores a computed embedding for a fact.
func (*PostgresStore) SetFactVectors ¶
func (s *PostgresStore) SetFactVectors(ctx context.Context, id int64, v memstore.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 (*PostgresStore) SetInlineRejectScore ¶
func (s *PostgresStore) SetInlineRejectScore(score int)
SetInlineRejectScore sets the detect score at which the inline regex screen rejects a write. Zero restores memstore.InlineRejectScore. See the SQLiteStore method.
func (*PostgresStore) SetReranker ¶
func (s *PostgresStore) 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 (*PostgresStore) SetScreenMode ¶
func (s *PostgresStore) SetScreenMode(m memstore.ScreenMode)
SetScreenMode selects how the model half of screening participates in writes. See the SQLiteStore method of the same name; the two backends must agree, since a deployment can move between them.
func (*PostgresStore) Supersede ¶
func (s *PostgresStore) Supersede(ctx context.Context, oldID, newID int64) error
Supersede marks an old fact as superseded by a new fact.
func (*PostgresStore) TermDocCounts ¶
func (s *PostgresStore) 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 ts_stat for efficient term frequency lookup.
func (*PostgresStore) Touch ¶
func (s *PostgresStore) Touch(ctx context.Context, ids []int64) error
Touch increments use_count and updates last_used_at for the given fact IDs.
func (*PostgresStore) UpdateLink ¶
func (s *PostgresStore) UpdateLink(ctx context.Context, linkID int64, label string, metadata map[string]any) error
UpdateLink patches the label and/or metadata of an existing link.
func (*PostgresStore) UpdateMetadata ¶
UpdateMetadata merges a patch into the metadata JSON for a fact.
func (*PostgresStore) UpsertDocument ¶
func (s *PostgresStore) UpsertDocument(ctx context.Context, doc memstore.Document, chunks []memstore.DocumentChunk) (int64, error)
UpsertDocument stores or replaces a document and its chunks atomically. Replacement is keyed on (namespace, user, repo_url, path) -- commit is deliberately outside the key, so re-ingesting at a new commit replaces the row. The previous chunk set is deleted, never merged.
func (*PostgresStore) WritableFor ¶
func (s *PostgresStore) WritableFor(p memstore.Principal) (memstore.WritableStore, error)
type QueryEmbedFunc ¶ added in v0.5.1
QueryEmbedFunc embeds a fact's content the way the search path embeds a query. The auto-link gate compares a query-side embedding of the new fact's content against document-side stored vectors, and on models with task prefixes those two sides are not symmetric: a document-to-document cosine overstates what the gate sees. SampleSimilarity uses this for the link side when given one, and falls back to the stored vector otherwise.
type SessionStore ¶
type SessionStore struct {
// contains filtered or unexported fields
}
SessionStore persists Claude Code session events to PostgreSQL. It is independent of PostgresStore -- it manages its own tables.
Every instance carries a userID resolved at construction from memstore_meta['default_user']. ForUser returns a cheap clone scoped to a different user; ServiceScope returns a clone with userID 0 that omits the user predicate on reads and is intended for cross-user maintenance operations only (writes would violate NOT NULL on user_id).
func NewSessionStore ¶
NewSessionStore creates a SessionStore, runs its migrations, and resolves the default user from memstore_meta. The default user must already exist (recorded by the facts-layer migration or 'memstore admin tier3-init') unless all session tables are empty, in which case userID stays 0 until ForUser is called.
func (*SessionStore) FeedbackScore ¶
FeedbackScore returns the average feedback score for a ref across all sessions. Returns 0 if no feedback exists. Scoped-read: filters AND user_id = s.userID when userID != 0.
func (*SessionStore) FeedbackScores ¶
func (s *SessionStore) FeedbackScores(ctx context.Context, refIDs []string, refType string) (map[string]memstore.FeedbackStat, error)
FeedbackScores returns the average feedback score and rating count for each ref across all sessions. Only refs with feedback data are included. Scoped-read: filters AND user_id = s.userID when userID != 0. Service-conditional: at userID 0 (service scope) spans all users.
func (*SessionStore) ForUser ¶
func (s *SessionStore) ForUser(userID int64) (memstore.SessionStore, error)
ForUser returns a cheap clone of the session store scoped to the given user. Every read and write the clone performs carries the owner predicate for userID. userID must be positive.
func (*SessionStore) GetInjectedFactIDs ¶
GetInjectedFactIDs returns the IDs of facts injected into the given session via recall. Used for auto-rating at session end. Scoped-read: filters AND user_id = s.userID when userID != 0.
func (*SessionStore) GetInjectedHints ¶
func (s *SessionStore) GetInjectedHints(ctx context.Context, sessionID string) ([]memstore.ContextHint, error)
GetInjectedHints returns hints injected into the given session via recall. Used for auto-rating at session end. Scoped-read: filters on ci.user_id when userID != 0.
func (*SessionStore) GetPendingHints ¶
func (s *SessionStore) GetPendingHints(ctx context.Context, sessionID, cwd string) ([]memstore.ContextHint, error)
GetPendingHints returns unconsumed hints matching sessionID or cwd (OR semantics), ordered by relevance*desirability desc. Either parameter may be empty. Scoped-read: filters AND user_id = s.userID when userID != 0.
func (*SessionStore) GetSessionTurns ¶
func (s *SessionStore) GetSessionTurns(ctx context.Context, sessionID string) ([]memstore.SessionTurn, error)
GetSessionTurns returns all turns for a given session, ordered by turn index. Scoped-read: filters AND user_id = s.userID when userID != 0.
func (*SessionStore) MarkHintConsumed ¶
func (s *SessionStore) MarkHintConsumed(ctx context.Context, hintID int64) error
MarkHintConsumed marks a hint as consumed. Scoped-read/mutation: filters AND user_id = s.userID so a user cannot consume another user's hint.
func (*SessionStore) RecordFeedback ¶
func (s *SessionStore) RecordFeedback(ctx context.Context, fb memstore.ContextFeedback) error
RecordFeedback stores Claude's rating of an injected context item. Stamped-write: stamps user_id = s.userID. One rating per (user_id, ref_id, ref_type, session_id) -- silently ignores duplicates.
func (*SessionStore) RecordInjection ¶
func (s *SessionStore) RecordInjection(ctx context.Context, sessionID, refID, refType string, rank int) error
RecordInjection records that a ref was injected into a session. rank is the 0-based position of the item in the candidate list; -1 if unknown. Stamped-write: stamps user_id = s.userID. Ignores conflicts (idempotent).
func (*SessionStore) SaveHook ¶
func (s *SessionStore) SaveHook(ctx context.Context, payload []byte) error
SaveHook appends a raw Stop hook payload. Stamped-write: stamps user_id = s.userID. session_id is extracted from the JSON payload (best-effort); user_id is stamped from the store's scope, not the payload, since hooks do not carry an owner identity.
func (*SessionStore) SaveTurns ¶
func (s *SessionStore) SaveTurns(ctx context.Context, sessionID string, turns []memstore.SessionTurn) error
SaveTurns upserts session turns using a single batched round-trip. Stamped-write: stamps user_id = s.userID.
func (*SessionStore) ServiceScope ¶
func (s *SessionStore) ServiceScope() *SessionStore
ServiceScope returns a clone of the session store with NO user predicate. Reads span all users; writes are invalid (user_id NOT NULL would fire). Intended for cross-user maintenance (BackfillFeedback, UnratedFactSessions).
func (*SessionStore) StoreHint ¶
func (s *SessionStore) StoreHint(ctx context.Context, hint memstore.ContextHint) (int64, error)
StoreHint stores a context hint produced by the Ollama pipeline. Stamped-write: stamps user_id = s.userID.
func (*SessionStore) UnratedFactSessions ¶
func (s *SessionStore) UnratedFactSessions(ctx context.Context) ([]string, error)
UnratedFactSessions returns session IDs that have fact injections with no corresponding feedback. Used by the backfill-feedback command. Scoped-read: filters AND ci.user_id = s.userID when userID != 0. Service-conditional: at userID 0 (service scope) spans all users.
func (*SessionStore) UserID ¶
func (s *SessionStore) UserID() int64
UserID returns the user ID this store is scoped to. 0 means service scope (no user predicate). Exposed so tests and admin tooling can pass the resolved default-user ID to ForUser.
func (*SessionStore) WasInjected ¶
func (s *SessionStore) WasInjected(ctx context.Context, sessionID, refID, refType string) (bool, error)
WasInjected returns true if refID+refType was already injected this session. Scoped-read: filters AND user_id = s.userID when userID != 0.
type SimilarityPair ¶ added in v0.5.1
type SimilarityPair struct {
SourceID, TargetID int64
// Cosine is the similarity between the two facts' stored vectors.
Cosine float64
// Floor is the similarity between the source and its floorRank-th nearest
// active neighbour -- the background level a gate has to sit above. Only
// filled for linked pairs.
Floor float64
}
SimilarityPair is one measured pair for calibrating the similarity gates.
type SimilaritySample ¶ added in v0.5.1
type SimilaritySample struct {
Model string
// LinkedQuerySide is true when the linked pairs were scored from a
// query-side embedding of the source (the gate's view) rather than the
// source's stored vector.
LinkedQuerySide bool
Linked []SimilarityPair
Superseded []SimilarityPair
}
SimilaritySample is what SampleSimilarity measures: the pairs the auto-link gate is meant to admit (existing "related" links between active facts) and the pairs the auto-supersede gate is meant to admit (a superseded fact and its successor), both scored on the vectors as stored, plus the model that produced those vectors.
func SampleSimilarity ¶ added in v0.5.1
func SampleSimilarity(ctx context.Context, pool *pgxpool.Pool, namespace string, n, floorRank int, queryEmbed QueryEmbedFunc) (SimilaritySample, error)
SampleSimilarity reads up to n linked pairs and n supersession pairs from namespace and scores each with pgvector, so the gates in memstore.SimilarityPolicy can be set from the corpus rather than carried over from a previous model. Run it after a re-embed has finished.
Linked pairs are scored as the auto-link gate scores them when queryEmbed is given: the source's content embedded as a query against the target's stored vector, and the floor is the floorRank-th nearest active fact to that query vector. With a nil queryEmbed both use the source's stored vector, which is a document-to-document comparison and, on a prefixed model, runs higher than the gate's view. Supersession pairs are always stored-to-stored, which is how the supersede gate compares them. The linked sample is pseudo-random (ordered by a hash of the link id); the supersession sample is the most recent n.
type TokenInfo ¶
type TokenInfo struct {
ID int64
Name string
UserID int64
Scopes []string
CreatedAt time.Time
LastUsedAt *time.Time
ExpiresAt *time.Time
RevokedAt *time.Time
}
TokenInfo describes a token row without revealing the token value.
type TokenStore ¶
type TokenStore struct {
// contains filtered or unexported fields
}
TokenStore manages API tokens used by memstored for bearer-token auth. It is independent of PostgresStore — its tables are isolated.
Tokens are stored as SHA-256 of the token string. The plaintext token is returned exactly once (from Issue) and never retrievable afterwards.
func NewTokenStore ¶
NewTokenStore creates a TokenStore and runs its migrations.
func (*TokenStore) EnsureLegacyToken ¶
EnsureLegacyToken bootstraps the table with a row for the given plaintext key under name "legacy" if no row for that key already exists. Used by the daemon at startup to keep MEMSTORE_API_KEY-style deployments working without operator action. Returns true if a row was inserted.
func (*TokenStore) Issue ¶
Issue mints a new token, stores its hash, and returns the plaintext token. The plaintext is returned exactly once -- it cannot be retrieved later. Callers must surface it to the operator immediately and refuse to log it.
Token names must match the <user>@<host> shape. opts.UserID is required.
func (*TokenStore) List ¶
func (s *TokenStore) List(ctx context.Context) ([]TokenInfo, error)
List returns metadata for all non-revoked tokens, ordered by creation time. The plaintext token is never returned (it's not stored).
func (*TokenStore) Revoke ¶
Revoke marks all active tokens with the given name as revoked. Returns the number of tokens revoked.
func (*TokenStore) RevokeByUser ¶
RevokeByUser revokes every active token owned by userID and returns the number revoked. This is the mechanism behind 'memstore admin disable-user': a user with no active token cannot authenticate to the daemon.
func (*TokenStore) Rotate ¶
Rotate issues a new token with the same name, scopes, and owner as the existing active token, then revokes the old one(s). Returns the new plaintext token. If multiple active tokens share the name, all are revoked and one new token is issued.
func (*TokenStore) Verify ¶
func (s *TokenStore) Verify(ctx context.Context, token string) (VerifyResult, error)
Verify resolves a presented bearer token to a name + scopes. Returns ErrTokenInvalid for any failure mode (not found, revoked, expired) so the caller can't accidentally distinguish.
Side effect: bumps last_used_at on success. Failures do not write.
type VerifyResult ¶
VerifyResult is what Verify returns for a valid token: enough to populate httpapi.Identity (kept here as primitives so this package doesn't import httpapi).