store

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: Apache-2.0 Imports: 20 Imported by: 0 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.

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

View Source
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.

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

View Source
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.

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

ErrNotFound is returned for a missing row.

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

func ParseKey

func ParseKey(s string) ([]byte, error)

ParseKey decodes a key from the configuration: base64, standard or URL alphabet, padded or raw. Empty input is no key.

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

func NewBox(key []byte) (*Box, error)

NewBox builds a Box over a 32-byte key. A nil or empty key means plaintext: the returned Box is nil.

func (*Box) Enabled

func (b *Box) Enabled() bool

Enabled tells whether content is sealed.

func (*Box) KeyID

func (b *Box) KeyID() string

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

func (b *Box) Open(sealed, aad string) (string, error)

Open decrypts a sealed value; a value without the prefix is returned as is (written before the key existed).

func (*Box) OpenJSON

func (b *Box) OpenJSON(raw []byte, aad string) ([]byte, error)

OpenJSON reads a jsonb column written by SealJSON: a JSON string holding a sealed value is opened, anything else is returned as is.

func (*Box) Seal

func (b *Box) Seal(plain, aad string) (string, error)

Seal encrypts plain with the associated data aad (the row and column the value belongs to, so a ciphertext cannot be moved to another row). A nil Box returns plain unchanged.

func (*Box) SealJSON

func (b *Box) SealJSON(raw []byte, aad string) (string, error)

SealJSON seals a value stored in a jsonb column: the sealed text is wrapped as a JSON string literal, which jsonb accepts as a document.

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

type BundleWithCount struct {
	Bundle
	Concepts int64 `db:"concepts"`
}

BundleWithCount is a bundle with its number of concepts.

type ChunkInput

type ChunkInput struct {
	Ord     int
	Heading string
	Text    string
}

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

type ContentCounts struct {
	Sealed int
	Plain  int
}

ContentCounts is how many stored content values are sealed and how many are still in plaintext, over every content column of every table.

type EdgeInput

type EdgeInput struct {
	Src  string
	Dst  string
	Kind string
}

EdgeInput is a bundle-graph edge between two concepts, by path.

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 Neighbor

type Neighbor struct {
	Path string `db:"path"`
	Kind string `db:"kind"`
	Out  bool   `db:"out"`
}

Neighbor is a concept one edge away.

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 New

func New(db *pgxpool.Pool) *Repo

New returns a repository over the service's pool, in plaintext mode.

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

func (r *Repo) CountPendingChunks(ctx context.Context, bundleID string) (int, error)

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

func (r *Repo) DecryptAll(ctx context.Context) (int, error)

DecryptAll is EncryptAll's inverse: every sealed value goes back to plaintext. A rollback, or the step before a key change.

func (*Repo) DeleteBundle

func (r *Repo) DeleteBundle(ctx context.Context, slug string) error

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

func (r *Repo) Enabled() bool

Enabled reports whether content is sealed at rest.

func (*Repo) EncryptAll

func (r *Repo) EncryptAll(ctx context.Context) (int, error)

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

func (r *Repo) GetBundle(ctx context.Context, slug string) (*Bundle, error)

GetBundle returns the bundle by slug.

func (*Repo) GetConcept

func (r *Repo) GetConcept(ctx context.Context, bundleID, path string) (*Concept, error)

GetConcept returns the concept by bundle and path.

func (*Repo) GetToken

func (r *Repo) GetToken(ctx context.Context, id string) (*Token, error)

GetToken returns the token by id.

func (*Repo) GetTokenByHash

func (r *Repo) GetTokenByHash(ctx context.Context, hash string) (*Token, error)

GetTokenByHash resolves a plaintext token's hash.

func (*Repo) GetTokenByName

func (r *Repo) GetTokenByName(ctx context.Context, name string) (*Token, error)

GetTokenByName returns the token by its name.

func (*Repo) InsertEpisode

func (r *Repo) InsertEpisode(ctx context.Context, bundleID, content, actor string) (int64, error)

InsertEpisode stores a raw memory.

func (*Repo) KeyID

func (r *Repo) KeyID() string

KeyID is the fingerprint of the content key, "" when content is plaintext.

func (*Repo) ListBundles

func (r *Repo) ListBundles(ctx context.Context) ([]BundleWithCount, error)

ListBundles returns every bundle with its concept count.

func (*Repo) ListConceptContents

func (r *Repo) ListConceptContents(ctx context.Context, bundleID string) ([]ConceptContent, error)

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

func (r *Repo) ListEpisodes(ctx context.Context, bundleID string, limit int) ([]Episode, error)

ListEpisodes returns the newest episodes of a bundle.

func (*Repo) ListNeighbors

func (r *Repo) ListNeighbors(ctx context.Context, conceptID int64) ([]Neighbor, error)

ListNeighbors returns the concepts linked to and from a concept.

func (*Repo) ListPendingChunks

func (r *Repo) ListPendingChunks(ctx context.Context, limit int) ([]PendingChunk, error)

ListPendingChunks returns up to limit chunks that still have no embedding, oldest concept first.

func (*Repo) ListTokens

func (r *Repo) ListTokens(ctx context.Context) ([]Token, error)

ListTokens returns every token, newest first.

func (*Repo) ListVersions

func (r *Repo) ListVersions(ctx context.Context, conceptID int64) ([]Version, error)

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

func (r *Repo) RecentAudit(ctx context.Context, limit int) ([]AuditEntry, error)

RecentAudit returns the newest audit rows.

func (*Repo) RecentQueries

func (r *Repo) RecentQueries(ctx context.Context, limit int) ([]QueryLogEntry, error)

RecentQueries returns the newest logged searches.

func (*Repo) ReplaceChunks

func (r *Repo) ReplaceChunks(ctx context.Context, conceptID int64, chunks []ChunkInput) error

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

func (r *Repo) ReplaceEdges(ctx context.Context, bundleID string, edges []EdgeInput) error

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

func (r *Repo) RevokeToken(ctx context.Context, id string) error

RevokeToken revokes a token; revoking twice is not an error.

func (*Repo) SearchFTS

func (r *Repo) SearchFTS(ctx context.Context, terms []string, f *Filter, limit int) ([]Hit, error)

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

func (r *Repo) SetBox(b *Box)

SetBox turns content sealing on. nil keeps plaintext.

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

func (r *Repo) TouchToken(ctx context.Context, id string) error

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

func (t *Token) Active() bool

Active reports whether the token may be used.

func (*Token) AllowsBundle

func (t *Token) AllowsBundle(bundleID string) bool

AllowsBundle reports whether the token may touch the bundle.

func (*Token) HasScope

func (t *Token) HasScope(scope string) bool

HasScope reports whether the token carries the scope.

type UpsertConceptResult

type UpsertConceptResult struct {
	ID      int64
	Changed bool
	Version int
}

UpsertConceptResult tells what UpsertConcept did.

type Version

type Version struct {
	Version     int       `db:"version"`
	Content     string    `db:"content"`
	ContentHash string    `db:"content_hash"`
	Actor       string    `db:"actor"`
	CreatedAt   time.Time `db:"created_at"`
}

Version is one stored version of a concept.

Jump to

Keyboard shortcuts

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