Documentation
¶
Overview ¶
Package ingest implements the V0 ingestion pipeline: discover files, hash them, skip unchanged ones, parse, chunk, and write documents/chunks/links and an event in a single transaction per document. Parse and chunk run in a bounded worker pool; all writes are funneled through one writer goroutine because SQLite admits a single writer under WAL, so concurrent write transactions would serialize on the file lock (or fail on busy) rather than proceed. Reads are not funneled: the storage pool serves them concurrently.
Index ¶
- Variables
- func File(ctx context.Context, db *sql.DB, logger *slog.Logger, ...) (docID string, chunks int, err error)
- func ForgetPath(ctx context.Context, db *sql.DB, logger *slog.Logger, abs, uri string) (bool, error)
- func Match(relPath string, include, exclude, securityExclude []string) bool
- func PrepareOKF(in CaptureInput, hasPath bool) (filename string, content []byte)
- func RegisterOrigin(ctx context.Context, db *sql.DB, kbRoot, prefix, path, collection string) (storage.Origin, error)
- func ReindexOne(ctx context.Context, db *sql.DB, logger *slog.Logger, ...) (docID string, chunks int, err error)
- func RemoveOrigin(ctx context.Context, db *sql.DB, prefix string) (int, error)
- func RenderOKF(in CaptureInput) (filename string, content []byte)
- func ValidateOriginPrefix(prefix string) error
- func WriteCapture(dir, filename string, content []byte) (string, error)
- func WriteFileAtomic(absPath string, content []byte) (string, error)
- type CaptureInput
- type EncodingRule
- type MoveEntry
- type MoveResult
- type OkfyOptions
- type OkfyResult
- type Option
- type Options
- type OriginReindexSummary
- type Pipeline
- func (p *Pipeline) IngestPath(ctx context.Context, absPath, uri, collection string, cfg chunk.Config) (docID string, chunks int, err error)
- func (p *Pipeline) ReindexContent(ctx context.Context, kbRoot string, cfg chunk.Config) (ReindexContentSummary, error)
- func (p *Pipeline) ReindexOne(ctx context.Context, absPath, uri, collection string, cfg chunk.Config) (docID string, chunks int, err error)
- func (p *Pipeline) ReindexOrigin(ctx context.Context, o storage.Origin, rules Rules, cfg chunk.Config) (OriginReindexSummary, error)
- func (p *Pipeline) Run(ctx context.Context, opts Options) (Summary, error)
- type ReconcileSummary
- type ReindexContentSummary
- type Rules
- type Summary
- type WatchConfig
- type Watcher
Constants ¶
This section is empty.
Variables ¶
var ( // ErrOriginPathNotDir means the path is not an existing directory. ErrOriginPathNotDir = errors.New("origin: path is not a directory") // ErrOriginPrefixInvalid means the prefix is not a single usable uri segment. ErrOriginPrefixInvalid = errors.New("origin: invalid prefix") // ErrOriginPrefixTaken means the prefix collides with existing kb content, so // registering it would put two different files under one uri namespace. ErrOriginPrefixTaken = errors.New("origin: prefix collides with kb content") // ErrOriginInsideKB means the path is inside the kb, where content is already // indexed and writable; registering it would create a second, read-only view // of the same bytes under a different uri. ErrOriginInsideKB = errors.New("origin: path is inside the kb") )
Origin registration errors. They are distinguished so a CLI can explain what to change rather than printing a generic failure.
var ErrReconcileRootMissing = errors.New("ingest: reconcile root is missing or unreadable")
ErrReconcileRootMissing means the scan root itself is unreadable, so absence of a file below it proves nothing. Callers must not treat it as "everything was deleted": an unmounted volume and an emptied directory are indistinguishable from inside the walk, and evicting a namespace is not recoverable by a reindex.
Functions ¶
func File ¶
func File(ctx context.Context, db *sql.DB, logger *slog.Logger, absPath, uri, collection string, cfg chunk.Config) (docID string, chunks int, err error)
File performs a one-shot ingest of a single explicit file, reusing the existing parse→chunk→write path via Pipeline.IngestPath. It does not scan a directory and changes no pipeline behavior. uri is the stable, project-root- relative identifier stored as documents.uri (the captured file's path relative to the project root, e.g. ".mnemos/capture/idea-20260625-ab12cd34.md"), which is what mnemos.search and mnemos.read cite.
One-shot ingest is the default: remember both writes and ingests, and the call is intentionally retained. Setting defer_to_watcher=true makes remember write-only, leaving capture_dir ingestion to a running watcher (the watcher then owns capture). The two modes stay safe together because Phase 1 hash-skip turns the watcher's re-sighting of an already-ingested file into a no-op, so there is no double index either way.
func ForgetPath ¶
func ForgetPath(ctx context.Context, db *sql.DB, logger *slog.Logger, abs, uri string) (bool, error)
ForgetPath deletes a file from the OKF tree: it removes the document from the index and the backing file from disk, returning whether a file was actually removed. It is idempotent — forgetting a path whose file is already gone is not an error and reports deleted=false. Both the CLI `forget` command and the mnemos.forget MCP tool route through it, so the two surfaces cannot drift in behavior or crash semantics.
The index is cleared BEFORE the file is removed. A DB failure before any disk mutation leaves the system coherent: the file and its index entry both still exist, so a re-run completes cleanly. The reverse order risks a ghost document — indexed but missing on disk — that survives until the next reconcile. The opposite residue, an orphaned file present on disk but not indexed, is benign: the next ingest or watcher reconcile re-indexes or re-removes it automatically.
func Match ¶
Match reports whether the file at root-relative path relPath is selected by the include/exclude glob sets, using the exact same predicate the directory scanner applies. relPath is matched after slash-normalization, so callers may pass an OS-native relative path. The watcher uses this to decide, per live event, whether a file should be ingested — sharing one predicate guarantees the watcher and the batch pipeline never disagree about what is indexable.
func PrepareOKF ¶ added in v0.3.0
func PrepareOKF(in CaptureInput, hasPath bool) (filename string, content []byte)
PrepareOKF turns a capture into the bytes to write, choosing between preserving an authored document and generating a frontmatter wrapper.
When the caller targets an explicit path (hasPath) AND the body already opens with a frontmatter block, the body is preserved verbatim (only a trailing newline is ensured). This is the read-modify-write case for a stateful document — a task state file, status.md, a decision — where the caller's frontmatter (status, priority, title, …) is authoritative. Wrapping it in a second block would shadow those fields behind a generated one that carries only type/tags/timestamp/collection, which is why a remembered task never grouped in `mnemos task list`.
Otherwise (an inbox capture with no path, or a path target whose body carries no frontmatter yet) the body is wrapped by RenderOKF. Gating passthrough on hasPath keeps raw inbox notes that merely begin with a `---` thematic break from being mistaken for frontmatter. The returned filename is empty in the passthrough case: it is only consumed for auto-naming, which never happens when a path is targeted.
func RegisterOrigin ¶ added in v0.3.0
func RegisterOrigin(ctx context.Context, db *sql.DB, kbRoot, prefix, path, collection string) (storage.Origin, error)
RegisterOrigin validates and records an external origin (ADR-0013). It does not index anything: registration and indexing are separate so a mistyped path fails before any content is written.
The path is resolved (symlinks evaluated) before storage, so a later swap of an intermediate symlink cannot silently redirect the origin somewhere else.
func ReindexOne ¶ added in v0.3.0
func ReindexOne(ctx context.Context, db *sql.DB, logger *slog.Logger, absPath, uri, collection string, cfg chunk.Config) (docID string, chunks int, err error)
ReindexOne performs a one-shot forced reindex of a single explicit file, mirroring File's wrapper shape over the pipeline. absPath is the file to read; uri is the stable, tree-root-relative identifier stored as documents.uri.
func RemoveOrigin ¶ added in v0.3.0
RemoveOrigin unregisters an origin and evicts every document in its namespace, so a removed origin stops being citable. The files themselves are never touched: they are canonical under their own tooling, which is the whole point of a read-only origin.
func RenderOKF ¶
func RenderOKF(in CaptureInput) (filename string, content []byte)
RenderOKF serializes a capture into an OKF markdown document: a YAML frontmatter block (type, tags, timestamp in RFC3339, collection) followed by a blank line and the body. The returned filename is collision-safe and readable — "<type>-<YYYYMMDD>-<shorthash>.md" — where the short hash is derived from the body so identical notes captured the same day reuse a filename (idempotent re-ingest) while distinct notes diverge.
func ValidateOriginPrefix ¶ added in v0.3.0
ValidateOriginPrefix accepts a single, plain uri segment. A multi-segment or dotted prefix would make the namespace ambiguous against real subdirectories and against the "." / ".." the confinement guard rejects everywhere else.
func WriteCapture ¶
WriteCapture writes content to dir/filename atomically. It is the auto-named capture wrapper: it joins filename under dir and delegates the atomic write to WriteFileAtomic. It returns the absolute path of the written file.
func WriteFileAtomic ¶
WriteFileAtomic writes content to absPath atomically: it creates the parent directory if missing, writes to a temp file in the same directory, then renames it over the destination. The same-directory temp file guarantees the rename is atomic (no cross-device copy). It returns absPath on success.
Types ¶
type CaptureInput ¶
type CaptureInput struct {
Type string
Body string
Tags []string
Collection string
// Timestamp is the capture time. The program may use time.Now(); only the
// eval/workflow scripts are forbidden wall-clock access, not the server.
Timestamp time.Time
}
CaptureInput is the content an agent hands to mnemos.remember, normalized for serialization. Type is the OKF document type ("idea" or "document"), Body the note text, Tags the optional frontmatter tags, and Collection the logical space the captured note belongs to.
type EncodingRule ¶ added in v0.3.0
EncodingRule binds a charset to the root-relative globs it applies to. It mirrors config's [[indexing.encoding]] without importing it, keeping the pipeline free of config types as Rules already does for the selection globs.
type MoveEntry ¶
MoveEntry records one file relocated by MovePath: its old and new uris and the document id it was re-indexed under (the id derives from collection + uri, so it changes on every move).
type MoveResult ¶
MoveResult is the outcome of a MovePath call. IsDir reports whether the source was a directory (a subtree move). DanglingLinks is the total number of inbound markdown links left pointing at the old uris — not rewritten in V0.
func MovePath ¶
func MovePath(ctx context.Context, db *sql.DB, logger *slog.Logger, absFrom, absTo, oldURI, newURI string, cfg chunk.Config) (MoveResult, error)
MovePath moves a file or directory within the OKF tree: it renames the path on disk and re-indexes every affected indexed document under its new uri, preserving each document's collection. For a directory it relocates the whole subtree and re-indexes each document that was indexed under the old prefix (files present on disk but never indexed simply move with the subtree). Both the CLI `mv` command and the mnemos.move MCP tool route through it, so the two surfaces cannot drift.
Inbound markdown links to moved uris are not rewritten (a V0 limitation); their total is returned in MoveResult.DanglingLinks and logged as a warning.
type OkfyOptions ¶
type OkfyOptions struct {
// TreeRoot is the writable OKF tree root used to confine Source and Out.
TreeRoot string
// Exclude is the [security].exclude glob set applied to Source and Out.
Exclude []string
// Source is the tree-root-relative (or absolute, within the tree) path of the
// plain file to convert. It must resolve to a .txt or .md file.
Source string
// Out is the output path within the tree. When empty it defaults to Source
// with a .md extension. It must resolve to a .md file and must not equal Source.
Out string
// Collection is the collection the OKF document is indexed under. Empty means
// "default".
Collection string
// Type is the OKF note type recorded in the frontmatter (e.g. "document").
Type string
// Tags are the optional frontmatter tags.
Tags []string
// Force overwrites the output file when it already exists.
Force bool
// Chunking is the token budget applied to the ingest.
Chunking chunk.Config
// Scanner screens the source body for secrets before anything is written.
Scanner security.SecretScanner
}
OkfyOptions configures Okfy: the shared core that turns a plain .txt or .md file into an OKF document and indexes it, leaving the source intact. It is called by both the `okfy` CLI command and the mnemos.okfy MCP tool so the two surfaces share one implementation.
type OkfyResult ¶
type OkfyResult struct {
URI string
SourceURI string
Collection string
DocumentID string
Chunks int
}
OkfyResult reports the outcome of Okfy: the output document's tree-root- relative URI (an immediate citation), the source URI, the resolved collection, the document id, and the number of chunks indexed.
func Okfy ¶
func Okfy(ctx context.Context, db *sql.DB, logger *slog.Logger, opts OkfyOptions) (OkfyResult, error)
Okfy validates Source within the tree, derives and validates the output path, secret-scans the source body, renders an OKF document, writes it atomically, indexes it, and keeps the source. The source file is never overwritten: an output equal to the source is rejected, and an existing output requires Force.
type Option ¶
type Option func(*Pipeline)
Option customizes a Pipeline at construction.
func WithEncodings ¶ added in v0.3.0
func WithEncodings(rules []EncodingRule) Option
WithEncodings declares the charsets of legacy, non-UTF-8 source files so they are decoded at ingest instead of skipped as binary (see EncodingRule). An unresolvable charset is reported by New. Passing no rules, the default, keeps ingest UTF-8-only.
func WithMaxFileBytes ¶
WithMaxFileBytes sets the per-file size cap. A file larger than n is skipped (with a warning) instead of being read into memory. n <= 0 disables the cap.
func WithSecretScanner ¶ added in v0.3.0
func WithSecretScanner(s security.SecretScanner) Option
WithSecretScanner screens every file's content for credentials before it is indexed, skipping a matching file with a warning naming the matched rules (not the matched values). It exists because the index is served to an LLM: an unscanned ingest would surface a credential verbatim in a search snippet. A nil scanner, the default, disables screening.
The skip is deliberate rather than a hard failure: one bad file must not abort a tree ingest, matching the oversize and binary skips.
type Options ¶
type Options struct {
Root string
// URIBase is the directory document URIs are made relative to. Leave empty to
// use Root (scan-root-relative URIs); set it to the knowledge-base root so a
// subtree ingest still mints kb-relative URIs.
URIBase string
Collection string
Rules Rules
Chunking chunk.Config
// Force bypasses the content-hash skip so an unchanged file is re-parsed and
// rewritten anyway. It is how a parser or schema change is propagated to
// already-indexed documents; the oversize, binary, and unparseable skips still
// apply. Off for normal ingest/watch, which stay hash-skip-fast.
Force bool
// URIPrefix namespaces every minted uri as "<URIPrefix>/<path under Root>".
// Empty, the default, means uris stay relative to URIBase, which is every
// in-kb scan. A registered external origin sets it so its documents get
// stable URIs that cannot collide with another tree's identical relative
// paths (ADR-0013). With it set, URIBase is Root: the origin root is what its
// paths are relative to.
URIPrefix string
// Reconcile evicts indexed documents under Root whose backing file no longer
// exists, so the run converges the index onto the filesystem instead of only
// adding to it (#42). Off by default because a run over a single file, or one
// whose caller reconciles separately (the watcher), must not prune anything.
Reconcile bool
// contains filtered or unexported fields
}
Options configures a single ingest run.
type OriginReindexSummary ¶ added in v0.3.0
type OriginReindexSummary struct {
Prefix string
Scanned int
Indexed int
Skipped int
Removed int
Chunks int
}
OriginReindexSummary reports one origin's reindex.
type Pipeline ¶
type Pipeline struct {
// contains filtered or unexported fields
}
Pipeline ingests files into the store. It holds the dependencies the run needs; construct one per command invocation.
func New ¶
New builds a Pipeline over db using the default offline token estimator and the default file-size cap. Pass WithMaxFileBytes to override the cap.
func (*Pipeline) IngestPath ¶
func (p *Pipeline) IngestPath(ctx context.Context, absPath, uri, collection string, cfg chunk.Config) (docID string, chunks int, err error)
IngestPath ingests a single explicit file using the same prepare→write path the directory pipeline uses, then returns the document id and the number of chunks written. absPath is the file to read; uri is the stable, project-root- relative identifier stored as documents.uri (capture passes the path relative to the project root so the captured note is a stable citation). A file whose content hash is unchanged is a no-op: it returns the existing document id with zero chunks. This is the one-shot ingest seam used by mnemos.remember; it adds no scan and no pipeline behavior of its own beyond reusing prepare/write.
func (*Pipeline) ReindexContent ¶ added in v0.3.0
func (p *Pipeline) ReindexContent(ctx context.Context, kbRoot string, cfg chunk.Config) (ReindexContentSummary, error)
ReindexContent re-parses and rewrites every already-indexed document from its on-disk file, bypassing the content-hash skip, so a parser or schema change (e.g. a corrected title derivation) propagates to the whole index without editing files. It walks the documents table rather than the filesystem, so each document keeps its stored collection and only indexed documents are touched.
Documents belonging to a registered external origin are left alone: their files live outside the kb, and `mnemos origin reindex` refreshes them.
A document whose file no longer exists is evicted, so a reindex converges the index onto what is on disk instead of leaving a deleted file citable (#42). An unreadable-but-present file is left in place with a warning. If kbRoot itself is unreadable the whole pass fails without evicting anything, because absence below an unreadable root proves nothing.
Rewriting a document's chunks cascades away its stored embeddings (they key on chunk id); callers that use semantic search should run `reindex --embeddings` afterwards.
func (*Pipeline) ReindexOne ¶ added in v0.3.0
func (p *Pipeline) ReindexOne(ctx context.Context, absPath, uri, collection string, cfg chunk.Config) (docID string, chunks int, err error)
ReindexOne re-parses and rewrites a single file, always forcing, and returns its document id and chunk count. Unlike IngestPath it never short-circuits on an unchanged content hash: it backs an editor's save, where "the index now reflects this file" must hold even when the saved bytes happen to match what was already indexed. A file prepare declines (binary, oversize, unparseable) is an error here rather than a silent skip, because the caller asked for this one file by name.
func (*Pipeline) ReindexOrigin ¶ added in v0.3.0
func (p *Pipeline) ReindexOrigin(ctx context.Context, o storage.Origin, rules Rules, cfg chunk.Config) (OriginReindexSummary, error)
ReindexOrigin indexes a registered origin in place, under its namespace, and evicts documents in that namespace whose file is gone. It never writes to the origin tree.
A missing or unreadable origin root fails with ErrReconcileRootMissing and evicts nothing: an unmounted volume and an emptied tree look identical from inside the walk, and losing a namespace is not recoverable by re-running.
func (*Pipeline) Run ¶
Run executes the pipeline and returns a Summary. Discovery and hashing run on the calling goroutine; parse+chunk run in a bounded worker pool; every result flows through one writer goroutine that owns all DB writes and all tallying, so the counters are race-free by construction.
type ReconcileSummary ¶ added in v0.3.0
type ReconcileSummary struct {
// Considered is how many indexed documents were in scope.
Considered int
// Removed is how many were evicted because their backing file is gone.
Removed int
// URIs are the evicted URIs, in the order they were removed.
URIs []string
}
ReconcileSummary reports what a reconcile pass removed.
func Reconcile ¶ added in v0.3.0
func Reconcile(ctx context.Context, db *sql.DB, root, uriBase, uriPrefix string, stripPrefix bool, exclude ...string) (ReconcileSummary, error)
Reconcile evicts every indexed document under uriPrefix whose backing file no longer exists on disk. It is the deletion half of indexing: Run and ReindexContent are additive, so without this pass a deleted file keeps being returned by search and cited with line ranges into a file that is gone (#42).
uriBase is the directory URIs are relative to (the kb root). uriPrefix scopes the pass to a subtree, slash-separated and matched at segment boundaries, so "adr" covers "adr/0001.md" but never "adr-archive/x.md"; empty means the whole store. root is the directory whose readability gates the pass.
stripPrefix distinguishes the two shapes a prefix can have. For an in-kb subtree the prefix is part of the path under uriBase, so it stays in the join. For a registered origin (ADR-0013) it is a namespace that exists only in the uri: the file lives at "<origin root>/<path after the prefix>", so the prefix must come off before resolving. Getting this backwards would stat the wrong path and evict every document in the namespace.
exclude names namespaces to skip entirely, so a kb-anchored pass never judges a registered origin's documents by a path they do not have.
It returns ErrReconcileRootMissing without evicting anything when root cannot be read. Every eviction commits in one transaction, so an interrupted run leaves the index either fully reconciled or untouched, never half-pruned.
type ReindexContentSummary ¶ added in v0.3.0
type ReindexContentSummary struct {
// Documents is how many indexed documents were considered.
Documents int
// Reindexed is how many were re-parsed and rewritten.
Reindexed int
// Skipped is how many prepare declined (binary/oversize/unparseable on disk).
Skipped int
// Missing is how many had no readable backing file (unreadable, e.g. a
// permission error). A file that is simply gone is evicted by the reconcile
// pass instead and counted in Removed.
Missing int
// Removed is how many documents were evicted because their backing file no
// longer exists on disk.
Removed int
// Chunks is the total chunks rewritten across reindexed documents.
Chunks int
}
ReindexContentSummary reports the outcome of a content reindex.
type Summary ¶
type Summary struct {
FilesScanned int
FilesIngested int
FilesSkipped int
ChunksWritten int
// FilesRemoved is how many indexed documents were evicted because their
// backing file is gone. Always zero unless Options.Reconcile is set.
FilesRemoved int
}
Summary reports the outcome of an ingest run.
type WatchConfig ¶
type WatchConfig struct {
// Include/Exclude/SecurityExclude are the same glob sets the scanner uses;
// the watcher applies them through the shared Match predicate so a live event
// and a batch scan agree on what is indexable.
Include []string
Exclude []string
SecurityExclude []string
// Chunking is the token budget for reindexing a changed file.
Chunking chunk.Config
// Encoding declares legacy source charsets, so a live edit to a non-UTF-8
// file is decoded exactly as a batch ingest would decode it.
Encoding []EncodingRule
// StorageDir is the directory holding the SQLite database (e.g. ".mnemos").
// Events under it are ignored so the watcher does not churn on WAL/SHM writes
// it triggers itself.
StorageDir string
// URIBase is the directory document URIs are made relative to (the kb root).
// Empty means use the watched root, reproducing root-relative URIs.
URIBase string
// MaxFileBytes caps the size of a single file read into memory; a larger file
// is skipped with a warning. A value <= 0 disables the cap, matching the
// [indexing].max_file_bytes config contract.
MaxFileBytes int64
// ScanSecrets screens a changed file for credentials before indexing it, so a
// live edit is held to the same bar as a batch ingest. Mirrors
// [security].exclude_secrets.
ScanSecrets bool
}
WatchConfig carries the selection and chunking settings the watcher reuses from the batch pipeline, plus the storage directory to ignore so the watcher never reacts to its own database writes.
type Watcher ¶
type Watcher struct {
// contains filtered or unexported fields
}
Watcher incrementally keeps a collection in sync with a directory tree. It performs a startup reconcile (full hash-skip scan plus removal of vanished documents) and then watches for live changes, reindexing modified files and deleting removed ones. It reuses the Phase 1 pipeline for all ingestion, so it adds no parsing or chunking logic of its own.
func NewWatcher ¶
func NewWatcher(db *sql.DB, logger *slog.Logger, root, collection string, cfg WatchConfig) (*Watcher, error)
NewWatcher builds a Watcher over db. root is the directory to watch (relative or absolute; it is resolved to an absolute path), collection the logical space reindexed files belong to, and cfg the shared selection/chunking settings.
func (*Watcher) Ready ¶
func (w *Watcher) Ready() <-chan struct{}
Ready returns a channel that is closed once Run has completed its startup reconcile and registered the live filesystem watch. Until then, file changes may not yet be observed; after it is closed, they are. Callers that mutate the watched tree and expect the watcher to react (notably tests, but also any orchestrator that wants to know the watcher is live) can block on it. If Run returns before going live (a reconcile or watch-setup error), the channel is never closed; select on it together with the Run error or a timeout.