Documentation
¶
Overview ¶
Package store is the memory service's PostgreSQL repository: OKF bundles and concepts with their chunks and edges, search (vector and full-text), agent tokens, and the audit and query logs.
Every statement is explicit parameterized SQL; output columns carry the `AS name` alias RowToStructByName needs. The pool is the service's own database (pgvector extension, migrations/memory).
Index ¶
- Constants
- Variables
- func ParseKey(s string) ([]byte, error)
- type AuditEntry
- type Box
- type Bundle
- type BundleWithCount
- type ChunkInput
- type Concept
- type ConceptContent
- type ConceptSummary
- type ContentCounts
- type EdgeInput
- type Episode
- type Filter
- type Hit
- type Neighbor
- type PendingChunk
- type QueryLogEntry
- type QueryStats
- type Repo
- func (r *Repo) Audit(ctx context.Context, tokenID, actor, action, bundleID, path string, ...) error
- func (r *Repo) CheckContent(ctx context.Context) (ContentCounts, error)
- func (r *Repo) CountContent(ctx context.Context) (ContentCounts, error)
- func (r *Repo) CountPendingChunks(ctx context.Context, bundleID string) (int, error)
- func (r *Repo) CreateToken(ctx context.Context, name, hash, prefix string, scopes, bundleIDs []string) (*Token, error)
- func (r *Repo) DecryptAll(ctx context.Context) (int, error)
- func (r *Repo) DeleteBundle(ctx context.Context, slug string) error
- func (r *Repo) DeleteConceptsNotIn(ctx context.Context, bundleID string, paths []string) (int64, error)
- func (r *Repo) Enabled() bool
- func (r *Repo) EncryptAll(ctx context.Context) (int, error)
- func (r *Repo) GetBundle(ctx context.Context, slug string) (*Bundle, error)
- func (r *Repo) GetConcept(ctx context.Context, bundleID, path string) (*Concept, error)
- func (r *Repo) GetToken(ctx context.Context, id string) (*Token, error)
- func (r *Repo) GetTokenByHash(ctx context.Context, hash string) (*Token, error)
- func (r *Repo) GetTokenByName(ctx context.Context, name string) (*Token, error)
- func (r *Repo) InsertEpisode(ctx context.Context, bundleID, content, actor string) (int64, error)
- func (r *Repo) KeyID() string
- func (r *Repo) ListBundles(ctx context.Context) ([]BundleWithCount, error)
- func (r *Repo) ListConceptContents(ctx context.Context, bundleID string) ([]ConceptContent, error)
- func (r *Repo) ListConcepts(ctx context.Context, bundleID, prefix string, includeNotCurrent bool) ([]ConceptSummary, error)
- func (r *Repo) ListEpisodes(ctx context.Context, bundleID string, limit int) ([]Episode, error)
- func (r *Repo) ListNeighbors(ctx context.Context, conceptID int64) ([]Neighbor, error)
- func (r *Repo) ListPendingChunks(ctx context.Context, limit int) ([]PendingChunk, error)
- func (r *Repo) ListTokens(ctx context.Context) ([]Token, error)
- func (r *Repo) ListVersions(ctx context.Context, conceptID int64) ([]Version, error)
- func (r *Repo) QueryLog(ctx context.Context, tokenID, tool, query, bundleID, mode string, ...) error
- func (r *Repo) QueryStats(ctx context.Context) ([]QueryStats, error)
- func (r *Repo) RecentAudit(ctx context.Context, limit int) ([]AuditEntry, error)
- func (r *Repo) RecentQueries(ctx context.Context, limit int) ([]QueryLogEntry, error)
- func (r *Repo) ReplaceChunks(ctx context.Context, conceptID int64, chunks []ChunkInput) error
- func (r *Repo) ReplaceEdges(ctx context.Context, bundleID string, edges []EdgeInput) error
- func (r *Repo) RevokeToken(ctx context.Context, id string) error
- func (r *Repo) SearchFTS(ctx context.Context, terms []string, f *Filter, limit int) ([]Hit, error)
- func (r *Repo) SearchVector(ctx context.Context, query []float32, f *Filter, limit int) ([]Hit, error)
- func (r *Repo) SetBox(b *Box)
- func (r *Repo) SetChunkEmbeddings(ctx context.Context, conceptID int64, ords []int, vecs [][]float32) error
- func (r *Repo) TouchToken(ctx context.Context, id string) error
- func (r *Repo) UpsertBundle(ctx context.Context, slug, title, description, version string, ...) (*Bundle, error)
- func (r *Repo) UpsertConcept(ctx context.Context, c *Concept, actor string) (UpsertConceptResult, error)
- type Token
- type UpsertConceptResult
- type Version
Constants ¶
const ( ScopeRead = "read" // memory_search, memory_get, memory_list ScopeWrite = "write" // memory_put, memory_remember, memory_deprecate ScopeAdmin = "admin" // tokens, bundles, logs (admin JWT or an admin token) )
Scopes a token can carry.
const VectorDim = 1024
VectorDim is the stored embedding size: memory_chunks.embedding is halfvec(1024). A provider with another dimension needs a migration first.
Variables ¶
var ErrKeySize = errors.New("capsa: content key must be 32 bytes (base64) after decoding")
ErrKeySize is returned for a key that is not 32 bytes.
var ErrNotFound = errors.New("capsa: not found")
ErrNotFound is returned for a missing row.
var ErrWeakKey = errors.New("capsa: content key is one repeated byte (a placeholder, not a key)")
ErrWeakKey is returned for a key that is one byte repeated: a placeholder that passed the size check, not a key.
Functions ¶
Types ¶
type AuditEntry ¶
type AuditEntry struct {
ID int64 `db:"id"`
Actor string `db:"actor"`
Action string `db:"action"`
Path string `db:"path"`
Detail []byte `db:"detail"`
CreatedAt time.Time `db:"created_at"`
}
AuditEntry is one audit row.
type Box ¶
type Box struct {
// contains filtered or unexported fields
}
Box seals content at rest: AES-256-GCM with a random nonce per value. The stored form is the text "enc1:" + <key id> + ":" + base64(nonce || ciphertext), so it fits the existing text columns without a schema change. The key id is 8 hex characters of the key's fingerprint: a value sealed with another key then reads as exactly that, not as "wrong key or moved row", and a key rotation can keep the old key alongside the new one. A nil Box stores plaintext.
Values without the prefix are read as plaintext, so rows written before a key existed stay readable; the `encrypt` subcommand converts them in place.
What is sealed: the text of concepts, chunks, versions, episodes and the query log. What stays open: the structural columns the filters and listings need (path, type, tags, status, bundle slug) and the vectors. The embedding provider still sees plaintext — a vector cannot be computed over ciphertext.
func NewBox ¶
NewBox builds a Box over a 32-byte key. A nil or empty key means plaintext: the returned Box is nil.
func (*Box) KeyID ¶
KeyID is the key's fingerprint as recorded in every value the Box seals ("" for no key). It is safe to log and to show an operator.
func (*Box) Open ¶
Open decrypts a sealed value; a value without the prefix is returned as is (written before the key existed).
func (*Box) OpenJSON ¶
OpenJSON reads a jsonb column written by SealJSON: a JSON string holding a sealed value is opened, anything else is returned as is.
type Bundle ¶
type Bundle struct {
ID string `db:"id"`
Slug string `db:"slug"`
Title string `db:"title"`
Description string `db:"description"`
OKFVersion string `db:"okf_version"`
// Settings records how the bundle is indexed (embedding provider, model).
Settings []byte `db:"settings"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
}
Bundle is a knowledge base: one OKF bundle.
type BundleWithCount ¶
BundleWithCount is a bundle with its number of concepts.
type ChunkInput ¶
ChunkInput is a chunk to store; its embedding comes later.
type Concept ¶
type Concept struct {
ID int64 `db:"id"`
BundleID string `db:"bundle_id"`
Path string `db:"path"`
Type string `db:"type"`
Title string `db:"title"`
Description string `db:"description"`
Tags []string `db:"tags"`
Status string `db:"status"`
StaleAfter *time.Time `db:"stale_after"`
StaleMalformed bool `db:"stale_malformed"`
SupersededBy string `db:"superseded_by"`
TrustTier string `db:"trust_tier"`
Frontmatter []byte `db:"frontmatter"`
Body string `db:"body"`
Content string `db:"content"`
ContentHash string `db:"content_hash"`
Version int `db:"version"`
CreatedBy string `db:"created_by"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
}
Concept is one stored OKF concept.
type ConceptContent ¶
type ConceptContent struct {
ID int64 `db:"id"`
Path string `db:"path"`
Content string `db:"content"`
}
ConceptContent is a concept's identity plus its whole file, what the service needs to recompute the links of a bundle.
type ConceptSummary ¶
type ConceptSummary struct {
BundleID string `db:"bundle_id"`
Path string `db:"path"`
Type string `db:"type"`
Title string `db:"title"`
Description string `db:"description"`
Status string `db:"status"`
Version int `db:"version"`
UpdatedAt time.Time `db:"updated_at"`
}
ConceptSummary is a listing entry.
type ContentCounts ¶
ContentCounts is how many stored content values are sealed and how many are still in plaintext, over every content column of every table.
type Episode ¶
type Episode struct {
ID int64 `db:"id"`
Content string `db:"content"`
Actor string `db:"actor"`
HappenedAt time.Time `db:"happened_at"`
}
Episode is a stored raw memory.
type Filter ¶
type Filter struct {
// BundleID limits to one bundle ("" = every bundle).
BundleID string
// Type limits to one concept type ("" = any).
Type string
// Tags limits to concepts carrying at least one of the tags.
Tags []string
// IncludeNotCurrent also returns deprecated concepts and concepts of an
// unknown status; current knowledge is draft and stable (OKF §5.4).
IncludeNotCurrent bool
// BundleIDs limits to these bundles regardless of BundleID: the bundle
// restriction of the calling token, which must hold in every search mode
// whether or not the request names a bundle. nil means no restriction.
BundleIDs []string
}
Filter narrows a search.
type Hit ¶
type Hit struct {
ConceptID int64 `db:"concept_id"`
BundleID string `db:"bundle_id"`
BundleSlug string `db:"bundle_slug"`
Path string `db:"path"`
Type string `db:"type"`
Title string `db:"title"`
Description string `db:"description"`
Status string `db:"status"`
TrustTier string `db:"trust_tier"`
StaleAfter *time.Time `db:"stale_after"`
StaleMalformed bool `db:"stale_malformed"`
Ord int `db:"ord"`
Heading string `db:"heading"`
Text string `db:"text"`
Version int `db:"version"`
// Score is the cosine similarity for a vector search and ts_rank_cd for
// a full-text one; the two are not comparable.
Score float32 `db:"score"`
}
Hit is one chunk a search returned.
type PendingChunk ¶
type PendingChunk struct {
ConceptID int64 `db:"concept_id"`
Ord int `db:"ord"`
Heading string `db:"heading"`
Text string `db:"text"`
}
PendingChunk is a stored chunk without an embedding.
type QueryLogEntry ¶
type QueryLogEntry struct {
ID int64 `db:"id"`
Tool string `db:"tool"`
Query string `db:"query"`
Mode string `db:"mode"`
LatencyMs int `db:"latency_ms"`
Results int `db:"results"`
TopScore *float32 `db:"top_score"`
CreatedAt time.Time `db:"created_at"`
}
QueryLogEntry is one logged search.
type QueryStats ¶
type QueryStats struct {
Tool string `db:"tool" json:"tool"`
Calls int64 `db:"calls" json:"calls"`
VectorCalls int64 `db:"vector_calls" json:"vector_calls"`
AvgLatencyMs float64 `db:"avg_latency_ms" json:"avg_latency_ms"`
AvgResults float64 `db:"avg_results" json:"avg_results"`
LastUsedAt *time.Time `db:"last_used_at" json:"last_used_at"`
}
QueryStats aggregates the query log: calls, vector/fts split, latency and result count averages, per tool. It answers "do the agents use it?".
type Repo ¶
type Repo struct {
// contains filtered or unexported fields
}
Repo is the PostgreSQL repository. With a content key set, every text it stores is sealed on the way in and opened on the way out (crypt.go); the service layer only ever sees plaintext.
func (*Repo) Audit ¶
func (r *Repo) Audit(ctx context.Context, tokenID, actor, action, bundleID, path string, detail json.RawMessage) error
Audit records who did what to which concept. tokenID and bundleID may be empty; detail may be nil.
func (*Repo) CheckContent ¶
func (r *Repo) CheckContent(ctx context.Context) (ContentCounts, error)
CheckContent is the startup self-check. Sealed values with no key, or a key that does not open what is stored, is an error: a service that starts that way answers every read with an error — or, without a key handed one, reads that fail one by one. The counts come back with the error, and when all is well they tell the caller how many values are still in plaintext (the rows written before the key was set: `service encrypt` seals them).
func (*Repo) CountContent ¶
func (r *Repo) CountContent(ctx context.Context) (ContentCounts, error)
CountContent counts the sealed and the plaintext content values. A sealed value starts with the prefix; in the jsonb frontmatter column the sealed form is a JSON string holding it, so there the prefix follows the quote.
func (*Repo) CountPendingChunks ¶
CountPendingChunks returns how many chunks of a bundle still have no embedding.
func (*Repo) CreateToken ¶
func (r *Repo) CreateToken(ctx context.Context, name, hash, prefix string, scopes, bundleIDs []string) (*Token, error)
CreateToken stores a token. bundleIDs is nil for all bundles.
func (*Repo) DecryptAll ¶
DecryptAll is EncryptAll's inverse: every sealed value goes back to plaintext. A rollback, or the step before a key change.
func (*Repo) DeleteBundle ¶
DeleteBundle removes a bundle and, through the foreign keys, everything in it.
func (*Repo) DeleteConceptsNotIn ¶
func (r *Repo) DeleteConceptsNotIn(ctx context.Context, bundleID string, paths []string) (int64, error)
DeleteConceptsNotIn removes the concepts of the bundle whose path is not in paths (an import of a bundle that lost files); returns how many went.
func (*Repo) EncryptAll ¶
EncryptAll seals every plaintext content value in place — the rows written before a content key was set — and returns how many values changed. It needs a key; values already sealed are left alone, so it can be re-run.
func (*Repo) GetConcept ¶
GetConcept returns the concept by bundle and path.
func (*Repo) GetTokenByHash ¶
GetTokenByHash resolves a plaintext token's hash.
func (*Repo) GetTokenByName ¶
GetTokenByName returns the token by its name.
func (*Repo) InsertEpisode ¶
InsertEpisode stores a raw memory.
func (*Repo) ListBundles ¶
func (r *Repo) ListBundles(ctx context.Context) ([]BundleWithCount, error)
ListBundles returns every bundle with its concept count.
func (*Repo) ListConceptContents ¶
ListConceptContents returns path and content of every concept of a bundle.
func (*Repo) ListConcepts ¶
func (r *Repo) ListConcepts(ctx context.Context, bundleID, prefix string, includeNotCurrent bool) ([]ConceptSummary, error)
ListConcepts lists the concepts of a bundle under a path prefix, in path order. Not-current concepts (deprecated, unknown status) are listed only on request.
func (*Repo) ListEpisodes ¶
ListEpisodes returns the newest episodes of a bundle.
func (*Repo) ListNeighbors ¶
ListNeighbors returns the concepts linked to and from a concept.
func (*Repo) ListPendingChunks ¶
ListPendingChunks returns up to limit chunks that still have no embedding, oldest concept first.
func (*Repo) ListTokens ¶
ListTokens returns every token, newest first.
func (*Repo) ListVersions ¶
ListVersions lists the versions of a concept, newest first.
func (*Repo) QueryLog ¶
func (r *Repo) QueryLog(ctx context.Context, tokenID, tool, query, bundleID, mode string, latency time.Duration, results int, topScore *float32) error
QueryLog records one search: what the experiment is measured by. topScore may be nil (no results).
func (*Repo) QueryStats ¶
func (r *Repo) QueryStats(ctx context.Context) ([]QueryStats, error)
QueryStats returns the per-tool aggregates.
func (*Repo) RecentAudit ¶
RecentAudit returns the newest audit rows.
func (*Repo) RecentQueries ¶
RecentQueries returns the newest logged searches.
func (*Repo) ReplaceChunks ¶
ReplaceChunks stores the chunks of a concept, replacing the previous ones. Their embeddings start out NULL: the concept is findable through the full-text index at once (unless content is sealed) and through the vector index once embedded.
func (*Repo) ReplaceEdges ¶
ReplaceEdges stores the bundle graph of a bundle, replacing the previous one. Edges whose ends are not both concepts of the bundle are dropped.
func (*Repo) RevokeToken ¶
RevokeToken revokes a token; revoking twice is not an error.
func (*Repo) SearchFTS ¶
SearchFTS ranks the chunks by full-text relevance: every term is stemmed with the russian configuration (which stems Latin words too) and matched as a prefix. It is the fallback when no embedding provider answered, and still beats grepping the files.
func (*Repo) SearchVector ¶
func (r *Repo) SearchVector(ctx context.Context, query []float32, f *Filter, limit int) ([]Hit, error)
SearchVector ranks the embedded chunks by cosine similarity to the query vector. It is an exact scan: at tens of thousands of chunks that is a few milliseconds, and an HNSW index only pays off beyond that.
func (*Repo) SetChunkEmbeddings ¶
func (r *Repo) SetChunkEmbeddings(ctx context.Context, conceptID int64, ords []int, vecs [][]float32) error
SetChunkEmbeddings stores the embedding of each (ord) of a concept. Every vector is checked before anything is written: pgvector refuses NaN, and one bad vector would fail the whole batch — the failure would then look like "nothing found" on every later search.
func (*Repo) TouchToken ¶
TouchToken records a use of the token.
func (*Repo) UpsertBundle ¶
func (r *Repo) UpsertBundle(ctx context.Context, slug, title, description, version string, settings json.RawMessage) (*Bundle, error)
UpsertBundle creates the bundle or refreshes its metadata; settings are replaced as a whole.
func (*Repo) UpsertConcept ¶
func (r *Repo) UpsertConcept(ctx context.Context, c *Concept, actor string) (UpsertConceptResult, error)
UpsertConcept inserts the concept, or — when its content hash changed — stores a new version of it; unchanged content is left alone. The actor is recorded on the version row.
type Token ¶
type Token struct {
ID string `db:"id" json:"id"`
Name string `db:"name" json:"name"`
// TokenHash is never serialized: it is what an attacker would need to
// forge a token, and no API has a reason to show it.
TokenHash string `db:"token_hash" json:"-"`
Prefix string `db:"prefix" json:"prefix"`
Scopes []string `db:"scopes" json:"scopes"`
// BundleIDs restricts the token to these bundles; nil means all of them.
BundleIDs []string `db:"bundle_ids" json:"bundle_ids,omitempty"`
AllBundles bool `db:"-" json:"all_bundles"`
CreatedAt time.Time `db:"created_at" json:"created_at"`
LastUsedAt *time.Time `db:"last_used_at" json:"last_used_at,omitempty"`
RevokedAt *time.Time `db:"revoked_at" json:"revoked_at,omitempty"`
}
Token is an agent's bearer token. The plaintext exists only at creation.
func (*Token) AllowsBundle ¶
AllowsBundle reports whether the token may touch the bundle.
type UpsertConceptResult ¶
UpsertConceptResult tells what UpsertConcept did.