storage

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: MIT Imports: 14 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 storage provides SQLite persistence for mnemos: opening the database with sane PRAGMAs and running embedded goose migrations.

Index

Constants

View Source
const (
	DirOutbound = "outbound"
	DirInbound  = "inbound"
)

Direction values for a Neighbor.

View Source
const CapturedAtKey = "captured_at"

CapturedAtKey is the frontmatter key holding when the entry was captured. It is distinct from the document's modified_at, which a later edit or a re-ingest moves: the capture instant must not drift.

View Source
const JournalDocType = "journal"

JournalDocType is the OKF `type` a document declares to be a journal entry. Matching is case-insensitive, like every other type comparison in the index, so `Journal`, `journal` and `JOURNAL` are one type.

View Source
const PromotedToKey = "promoted_to"

PromotedToKey is the frontmatter key a journal entry carries once its content has been promoted into the knowledge base, naming the kb document that now holds it. Its presence is what stops a second consolidation pass from re-promoting the same material (ADR-0011).

Variables

View Source
var ErrOriginExists = errors.New("storage: origin already registered")

ErrOriginExists means the prefix, or the path, is already registered. Both are unique: one prefix per namespace, and one namespace per tree, so the same content is never indexed twice under two citations.

View Source
var ErrOriginNotFound = errors.New("storage: origin not found")

ErrOriginNotFound means no origin is registered under that prefix.

Functions

func AnyEmbeddingModel added in v0.3.0

func AnyEmbeddingModel(ctx context.Context, db *sql.DB) (model string, found bool, err error)

AnyEmbeddingModel returns the model name of an arbitrary stored embedding, or found=false when the table is empty. It lets a caller cheaply decide whether vector features are available at all without constructing an embedder (which would load an ONNX model just to read its name).

func AppendEvent

func AppendEvent(ctx context.Context, tx *sql.Tx, id, documentID, eventType, payloadJSON, createdAt string) error

AppendEvent inserts one events row within tx. id must be unique (the pipeline derives it from the document id and timestamp); documentID ties the event to its document so it is cascaded away when the document is deleted (empty maps to NULL for document-less events); payloadJSON is opaque JSON; createdAt is RFC3339.

func CollectionByURI

func CollectionByURI(ctx context.Context, db *sql.DB, uri string) (string, bool, error)

CollectionByURI returns the stored collection for a uri, or ("", false) when no document with that uri exists. move uses it to preserve a document's collection when re-ingesting it under a new uri (the document id is derived from collection + uri, so a move is a delete-old + ingest-new).

func CountEmbeddings

func CountEmbeddings(ctx context.Context, db *sql.DB, model string) (int, error)

CountEmbeddings returns the number of stored vectors for model. It backs the reindex summary and status reporting, and lets cross-package tests assert that the reindex path actually persisted vectors.

func CountInboundLinks(ctx context.Context, db *sql.DB, dstURI string) (int, error)

CountInboundLinks returns how many link edges point at dstURI (links.dst_doc is a plain uri string with no foreign key). move reports this as the number of inbound markdown links left dangling after a rename (a V0 limitation).

func CountJournal added in v0.3.0

func CountJournal(ctx context.Context, db *sql.DB) (int, error)

CountJournal returns how many journal documents are indexed. It exists for the doctor/stats surfaces, which want the size of the tier without paging every row through memory.

func DeleteByURI

func DeleteByURI(ctx context.Context, db *sql.DB, uri string) error

DeleteByURI removes the document with the given uri. Its chunks and links are removed by the ON DELETE CASCADE foreign keys, and the chunks delete trigger (chunks_ad) cleans the FTS external-content index — so a single DELETE on documents fully evicts the document from every searchable surface. Deleting a uri that does not exist is a no-op (no error). The watcher calls this when a tracked file vanishes from disk.

func DeleteByURITx

func DeleteByURITx(ctx context.Context, tx *sql.Tx, uri string) error

DeleteByURITx is DeleteByURI within a caller-managed transaction, so a batch of deletes (e.g. the watcher's vanished-file reconcile) commits atomically.

func DeleteOrigin added in v0.3.0

func DeleteOrigin(ctx context.Context, db *sql.DB, prefix string) error

DeleteOrigin removes a registration. It does not touch the documents indexed under that prefix: eviction is the caller's explicit step, so an accidental unregister never silently discards indexed content.

func DocumentHashByURI

func DocumentHashByURI(ctx context.Context, db *sql.DB, uri string) (string, bool, error)

DocumentHashByURI returns the stored content_hash for a uri, or ("", false) when no document with that uri exists. The ingest pipeline uses it to skip unchanged files before parsing.

func EncodeVector

func EncodeVector(vec []float32) []byte

EncodeVector serializes an embedding to a little-endian float32 BLOB (4 bytes per dimension). It is the inverse of decodeVector. Storing the raw float32 bytes keeps vectors compact and lets the linear scan decode them directly.

func EscapeLike

func EscapeLike(s string) string

EscapeLike escapes the LIKE wildcards (% and _) and the escape character in a literal so a path prefix/extension is matched verbatim rather than as a pattern. Use it together with `ESCAPE '\'` in a LIKE clause. Shared by the document lister and the search filter so both treat user-supplied path/type values literally.

func FirstChunkByDocURI added in v0.3.0

func FirstChunkByDocURI(ctx context.Context, db *sql.DB, uri string) (*model.Chunk, error)

FirstChunkByDocURI returns the lowest-ordinal chunk of the document at uri, or (nil, nil) when the document has no chunks. It is the representative chunk that graph expansion cites for a neighbor document which did not match the query lexically, so the injected result still carries a real citation.

func GetChunkByID

func GetChunkByID(ctx context.Context, db *sql.DB, id string) (*model.Chunk, error)

GetChunkByID returns the chunk with the given id, or (nil, nil) when no such chunk exists. It is a read-only accessor used by the MCP read tool.

func GetChunkContentsByIDs

func GetChunkContentsByIDs(ctx context.Context, db *sql.DB, ids []string) (map[string]string, error)

GetChunkContentsByIDs fetches the content of many chunks in a single query, returning a map from chunk id to content. Missing ids are simply absent from the map. An empty ids slice short-circuits to an empty map with no query. It is the batch accessor used by mnemos.context to avoid a per-result round-trip (the N+1 the single-id GetChunkByID would cause in a loop). The id count is bounded by the search limit, well under SQLite's bound-parameter cap.

func GetChunksByDocURI

func GetChunksByDocURI(ctx context.Context, db *sql.DB, uri string) ([]model.Chunk, error)

GetChunksByDocURI returns every chunk owned by the document with the given uri, ordered by ordinal. The chunks table is the source of truth for document content (the file on disk may have moved); reconstructing a document means reassembling these chunks. An empty slice means the uri matched no chunks.

func GetDocumentByID

func GetDocumentByID(ctx context.Context, db *sql.DB, id string) (*model.Document, error)

GetDocumentByID returns the document with the given id, or (nil, nil) when no such document exists. It is a read-only accessor used by the MCP read tool to resolve a chunk's owning document.

func GetDocumentByURI

func GetDocumentByURI(ctx context.Context, db *sql.DB, uri string) (*model.Document, error)

GetDocumentByURI returns the document with the given uri, or (nil, nil) when no such document exists. It is a read-only accessor used by the MCP read tool.

func InsertOrigin added in v0.3.0

func InsertOrigin(ctx context.Context, db *sql.DB, o Origin) error

InsertOrigin registers an origin. It returns ErrOriginExists if the prefix or the path is taken, so a caller can report the conflict rather than silently rebinding a namespace that existing document URIs depend on.

func IsJournalType added in v0.3.0

func IsJournalType(docType string) bool

IsJournalType reports whether an OKF document type names the journal tier. It is the single place the spelling is decided, so ingest, promotion and any future surface cannot disagree about what counts as a journal entry.

func IsJournalURI added in v0.3.0

func IsJournalURI(ctx context.Context, db *sql.DB, uri string) (bool, error)

IsJournalURI reports whether the document at uri is a journal entry. A uri with no document returns false: absent is not journal.

func JournalCapturedAt added in v0.4.0

func JournalCapturedAt(d model.Document) string

JournalCapturedAt returns the entry's CapturedAtKey value, or "" when the frontmatter does not carry one.

func JournalPromotedTo added in v0.4.0

func JournalPromotedTo(ctx context.Context, db *sql.DB, uri string) (string, error)

JournalPromotedTo returns the promoted_to value of the indexed document at uri, read with the same expression ListPendingJournal filters on: the kb document that now holds the entry's content, "none" when nothing was worth promoting, or "" when the entry is pending. A uri with no document returns "".

func ListDocsWithoutChunks added in v0.3.0

func ListDocsWithoutChunks(ctx context.Context, db *sql.DB, excludeCollections []string) ([]string, error)

ListDocsWithoutChunks returns the uris of documents that have no chunk rows — an indexed document with no extractable body (empty or whitespace-only). Used by the doctor structural-gap check. Ordered by uri. excludeCollections drops documents in hidden collections so a doctor run cannot disclose their uris.

func ListURIs added in v0.3.0

func ListURIs(ctx context.Context, db *sql.DB) ([]string, error)

ListURIs returns every documents.uri in the store, unordered. Reconcile uses it to find documents whose backing file has disappeared from disk; it filters by path prefix in Go rather than SQL because a LIKE prefix is not segment-aware ("adr" would match "adr-archive/x.md").

func Migrate

func Migrate(db *sql.DB) error

Migrate runs all pending goose migrations against db using the embedded SQL files. It is idempotent: applying it to an already-migrated database is a no-op. The "sqlite3" dialect name is goose's identifier for the SQLite dialect and is independent of the underlying driver.

func Open

func Open(ctx context.Context, path string) (*sql.DB, error)

Open opens (creating if needed) the SQLite database at path with the standard PRAGMAs applied to every pooled connection. The returned *sql.DB is ready for migrations and queries, and is safe for concurrent use.

func ReplaceChunks

func ReplaceChunks(ctx context.Context, tx *sql.Tx, documentID string, chunks []model.Chunk) error

ReplaceChunks deletes the existing chunks for documentID and inserts the provided set within tx. Deleting first lets the FTS triggers cascade-clean the external-content index; the inserts then repopulate it. tags and doc_type are stored denormalized on each chunk so FTS5 external content stays correct.

func ReplaceLinks(ctx context.Context, tx *sql.Tx, srcDoc string, links []model.Link) error

ReplaceLinks deletes the outbound edges for srcDoc and inserts the provided set within tx. dst_doc is a plain URI string with no foreign key, so link targets need not be ingested yet.

func TouchOriginIndexed added in v0.3.0

func TouchOriginIndexed(ctx context.Context, db *sql.DB, prefix, at string) error

TouchOriginIndexed records when an origin was last indexed, so a stale registration is diagnosable without walking its tree.

func UpsertDocument

func UpsertDocument(ctx context.Context, tx *sql.Tx, d model.Document) error

UpsertDocument inserts or updates a document by uri within tx. On conflict it refreshes the mutable fields (hash, title, sizes, timestamps, frontmatter) and re-stamps indexed_at.

The id travels with the row: document ids are derived from collection + uri, so re-ingesting a uri under a different collection mints a new id. The stored row must adopt it, otherwise the caller's chunk, link, and event writes reference an id no documents row carries and fail the foreign key. Adopting it means dropping the superseded row first, which cascades its chunks, links, and events away, so the caller must write the new ones in the same tx (ingest does: upsert, then ReplaceChunks/ReplaceLinks/AppendEvent).

func UpsertEmbedding

func UpsertEmbedding(ctx context.Context, tx *sql.Tx, chunkID, model string, dim int, vector []byte) error

UpsertEmbedding inserts or replaces the vector for chunkID within tx. The vector is stored as the encoded BLOB; dim and model are stored alongside so a later model change can be detected. The reindex path batches many upserts in a single transaction.

Types

type BrokenLink struct {
	DstURI string
	SrcURI string
}

BrokenLink is one link edge whose target uri (links.dst_doc) has no matching document — i.e. an inbound reference left dangling (e.g. after a move, since V0 does not rewrite inbound links). SrcURI is the document that contains the link.

func ListBrokenLinks(ctx context.Context, db *sql.DB, excludeCollections []string) ([]BrokenLink, error)

ListBrokenLinks returns every link edge whose dst_doc uri does not resolve to a document, joined back to the source document's uri. links.dst_doc is a plain uri with no foreign key, so a LEFT JOIN onto documents.uri finds the misses. Ordered by (src, dst) for stable output.

excludeCollections drops edges whose source document is in a hidden collection, so a doctor run cannot disclose the uris of a denied collection.

type ChunkRef

type ChunkRef struct {
	ID      string
	Content string
}

ChunkRef is a minimal chunk projection (id + content) used by the reindex path to embed every stored chunk without loading the full chunk rows.

func AllChunkRefs

func AllChunkRefs(ctx context.Context, db *sql.DB) ([]ChunkRef, error)

AllChunkRefs returns the id and content of every chunk, ordered by id for deterministic batching. The reindex path embeds these and stores one vector per chunk. The count is bounded by the corpus size (tens of thousands for the personal-use target), so materializing id+content is acceptable.

type ChunkVector added in v0.3.0

type ChunkVector struct {
	ChunkID string
	Vector  []float32
}

ChunkVector pairs a chunk id with its decoded embedding.

func DocChunkVectors added in v0.3.0

func DocChunkVectors(ctx context.Context, db *sql.DB, docID, model string) ([]ChunkVector, error)

DocChunkVectors returns the stored vectors of one document's chunks for model, ordered by chunk id. It backs "documents similar to this one", which pools a document's own already-computed vectors instead of re-embedding it. A document with no embeddings yields an empty slice, not an error: that is the ordinary state before `reindex --embeddings` has run.

type DocumentDigest added in v0.3.0

type DocumentDigest struct {
	URI             string
	Collection      string
	ContentHash     string
	FrontmatterJSON string
	SizeBytes       int64
}

DocumentDigest is the subset of a document the doctor detectors need: the content_hash (for exact-duplicate grouping, not carried by DocumentRow), the byte size (oversized check), and the raw frontmatter JSON (tag hygiene and the missing-frontmatter check). Kept separate from DocumentRow so the browse/list path is unaffected.

func ListDocumentDigests added in v0.3.0

func ListDocumentDigests(ctx context.Context, db *sql.DB, f ListFilter) ([]DocumentDigest, error)

ListDocumentDigests returns a digest per document, narrowed by the same ListFilter as ListDocuments so `doctor --path/--collection` scoping reuses one filter vocabulary. frontmatter_json may be NULL, so it is scanned through sql.NullString.

type DocumentRow

type DocumentRow struct {
	URI             string
	Collection      string
	Title           string
	ModifiedAt      string
	IndexedAt       string
	FrontmatterJSON string
	SizeBytes       int64
}

DocumentRow is a document's stored metadata as returned by ListDocuments. The type/tags a caller may want live inside FrontmatterJSON (the raw YAML re-encoded as JSON); decode it on the caller side rather than joining chunks.

func ListDocuments

func ListDocuments(ctx context.Context, db *sql.DB, f ListFilter) ([]DocumentRow, error)

ListDocuments returns document metadata rows ordered by uri, narrowed by the filter. It backs the browse/list feature and directory move (which lists every document under a uri prefix to re-index it). title/modified_at may be NULL in the schema, so they are scanned through sql.NullString.

type JournalDoc added in v0.4.0

type JournalDoc struct {
	model.Document

	PromotedTo string
}

JournalDoc is a journal row with its review state read by the index: PromotedTo is the promoted_to value, "" while the entry is pending.

func ListJournal added in v0.3.0

func ListJournal(ctx context.Context, db *sql.DB, limit int) ([]JournalDoc, error)

ListJournal returns journal documents ordered newest first, capped at limit (a limit <= 0 returns all of them). It reads the stored journal flag rather than matching a uri prefix, so an entry stays listed after a move or a rename (ADR-0011).

Entries are returned whether or not they have been promoted; PromotedTo on each says which. Consolidation filters on it so a second pass does not re-promote the same material (ADR-0011).

func ListPendingJournal added in v0.4.0

func ListPendingJournal(ctx context.Context, db *sql.DB, hidden []string, limit int) ([]JournalDoc, error)

ListPendingJournal returns the journal entries not yet reviewed (PromotedTo is ""), leaving out those whose collection is in hidden. An entry with empty or invalid frontmatter has nothing to say it was handled, so it is pending. Entries come oldest first, the order consolidation works through them, capped at limit (a limit <= 0 returns all of them). The cap applies after the hidden filter, so hidden rows never eat into the page. Like ListJournal it keys on the stored journal flag, never a uri prefix (ADR-0011).

type ListFilter

type ListFilter struct {
	Collection string // exact collection match
	PathPrefix string // documents.uri starts with this slash-relative prefix
	FileType   string // file extension without the dot (e.g. "md")
	// DocType filters on the OKF document type in frontmatter (json_extract
	// $.type), case-insensitive. Applied in SQL so callers do not scan every row
	// and JSON-decode it in Go. Documents with absent or malformed frontmatter
	// never match.
	DocType string
	// Status filters on the OKF status field in frontmatter (json_extract
	// $.status), case-insensitive, with the same SQL/JSON semantics as DocType.
	Status string
	// ExcludeCollections drops rows whose collection is in the list — the
	// server-side visibility boundary ([security].visibility.deny). Callers set it
	// from config so a hidden collection never surfaces in list/task output.
	ExcludeCollections []string
	Limit              int
}

ListFilter narrows ListDocuments. Empty string fields are ignored; Limit <= 0 returns all matching rows.

type Neighbor added in v0.3.0

type Neighbor struct {
	URI        string
	Title      string
	Collection string
	Direction  string
	Resolved   bool
}

Neighbor is one 1-hop link-graph neighbor of a document: the connected document plus the edge direction that reached it. For an outbound edge Resolved is false when the target uri has no ingested document (a dangling link), in which case Title and Collection are empty. Inbound neighbors are always resolved, because the source of a link is a stored document.

func InboundNeighbors added in v0.3.0

func InboundNeighbors(ctx context.Context, db *sql.DB, dstURI string) ([]Neighbor, error)

InboundNeighbors returns the documents that link to dstURI (its backlinks), joined to their source document for title/collection. Always Resolved (a link source is a stored document). Ordered by source uri. Relies on idx_links_dst_doc (migration 0004) to avoid a full links scan.

func OutboundNeighbors added in v0.3.0

func OutboundNeighbors(ctx context.Context, db *sql.DB, srcURI string) ([]Neighbor, error)

OutboundNeighbors returns the documents srcURI links to (its outbound edges), left-joined to documents so a dangling target still surfaces with Resolved false and empty title/collection. Ordered by target uri for stable output. An unknown srcURI simply has no outbound edges and yields an empty slice.

type Origin added in v0.3.0

type Origin struct {
	Prefix        string
	Path          string
	Collection    string
	RegisteredAt  string
	LastIndexedAt string
}

Origin is a registered external tree indexed in place, read-only (ADR-0013). Prefix is the URI namespace its documents are stored under; Path is the resolved absolute directory on disk. Collection is the fallback label for documents that do not declare a `collection:` frontmatter.

func GetOrigin added in v0.3.0

func GetOrigin(ctx context.Context, db *sql.DB, prefix string) (Origin, error)

GetOrigin returns the origin registered under prefix, or ErrOriginNotFound.

func ListOrigins added in v0.3.0

func ListOrigins(ctx context.Context, db *sql.DB) ([]Origin, error)

ListOrigins returns every registered origin, ordered by prefix so listings and JSON exports are diffable.

Jump to

Keyboard shortcuts

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