memory

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2026 License: MIT Imports: 24 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 memory is the verb layer of mnemos: one place that owns the behavior behind every memory operation (search, read, context, list, remember, okfy, forget, move). The CLI commands and the MCP tools are thin adapters over it — they parse arguments or JSON, call a Service method, and format the result — so the two surfaces cannot drift in semantics, gating, or option construction.

A Service is built from the same primitives an *app.App exposes (the open database, the loaded config, the OKF tree root, a secret scanner, and a logger). It deliberately does not build a search retriever: the CLI selects a retriever per command (lexical or hybrid via --semantic) while the MCP server builds one for its lifetime, so the retriever is passed in to Search/Context.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrAmbiguousRead = errors.New("provide exactly one of uri or chunk_id, not both")
	ErrEmptyRead     = errors.New("provide exactly one of uri or chunk_id")
)

ErrAmbiguousRead and ErrEmptyRead document the two invalid read selectors a surface may pass; surfaces validate their own input shape, but ReadOne lets a surface delegate the choice too.

View Source
var ErrNotEditable = errors.New("edit: frontmatter is not editable in place")

ErrNotEditable reports frontmatter this codebase declines to rewrite (missing, malformed, or using a shape whose source bytes cannot be patched in place).

View Source
var ErrOriginReadOnly = errors.New("memory: registered origin is read-only")

ErrOriginReadOnly means the path names a document in a registered external origin. Those trees are indexed in place and stay canonical under their own tooling, so mnemos never writes to them (ADR-0013).

View Source
var ErrReindexAfterWrite = errors.New("edit: write ok, reindex failed")

ErrReindexAfterWrite tags a reindex failure that followed a successful write. It separates two outcomes a caller must not conflate: the edit is durable on disk and only the index is stale, versus the edit was lost.

Functions

This section is empty.

Types

type Citation

type Citation struct {
	URI         string
	HeadingPath string
	StartLine   int
	EndLine     int
}

Citation locates a chunk for an agent: the owning document uri, the heading path, and the 1-based inclusive line range.

type ContextBlock

type ContextBlock struct {
	Source     string
	Title      string
	Collection string
	ModifiedAt string
	Content    string
	Truncated  bool
	// Neighbors is the block document's 1-hop link neighborhood, populated only
	// when ContextOptions.FollowLinks is set.
	Neighbors []RelatedNeighbor
}

ContextBlock is one retrieved passage ready to inject into an LLM prompt: Source cites it as "uri:start-end", Content is the chunk text, and Title / ModifiedAt label its owning document (empty when the document stored neither). Truncated reports that a size budget clipped Content.

type ContextOptions added in v0.3.0

type ContextOptions struct {
	GroupByDocument bool
	Cliff           bool
	MaxChars        int
	MaxTokens       int
	// FollowLinks, when set, attaches each block document's 1-hop link
	// neighborhood to the block (best-effort). Neighbors are computed once per
	// document across the result set.
	FollowLinks bool
	// LinkLimit caps neighbors per direction when FollowLinks is set (0 = default).
	LinkLimit int
	// LinkDirection selects which edges to follow (empty = both).
	LinkDirection Direction
}

ContextOptions shape a Context call. The zero value reproduces the original flat, unbounded behavior; the MCP context tool opts into grouping and the relevance cliff by default (see tools_context.go). GroupByDocument collapses hits to the best chunk per document, widening recall breadth for a fixed limit; Cliff trims the low-relevance tail; MaxChars/MaxTokens cap each block's content.

type Direction added in v0.3.0

type Direction string

Direction selects which link edges Related traverses.

const (
	// DirectionOutbound follows links the document contains.
	DirectionOutbound Direction = "outbound"
	// DirectionInbound follows backlinks that point at the document.
	DirectionInbound Direction = "inbound"
	// DirectionBoth follows both; it is also the zero-value default.
	DirectionBoth Direction = "both"
)

type EditFrontmatterInput added in v0.3.0

type EditFrontmatterInput struct {
	URI    string
	Fields []FieldEdit
	Body   *string
}

EditFrontmatterInput is a single atomic edit of the document at URI: any number of frontmatter field patches plus, when Body is non-nil, a replacement body. Batching them is deliberate — an editor session that changed both a field and the body saves once, so the two can never be written from stale copies of each other.

type EditResult added in v0.3.0

type EditResult struct {
	URI        string
	DocumentID string
	Chunks     int
}

EditResult reports the edited document's uri, its document id and the number of chunks the reindex wrote.

type EditSource added in v0.3.0

type EditSource struct {
	URI        string
	Collection string
	Type       string
	Content    []byte
	Body       string
	Fields     []okfyaml.Field
	Editable   bool
}

EditSource is a document as an editor opens it: the bytes on disk, the frontmatter split out for display, and whether those fields can be patched in place. Editable is false for a document whose frontmatter this codebase declines to rewrite, so an editor shows it read-only instead of risking a corrupting save.

type FieldEdit added in v0.3.0

type FieldEdit struct {
	Key   string
	Value string
	Items []string
	List  bool
}

FieldEdit is one frontmatter key to rewrite. Items applies when List is set (the whole list is retyped); otherwise Value replaces the scalar.

type ForgetResult

type ForgetResult struct {
	URI     string
	Deleted bool
}

ForgetResult reports the removed file's uri and whether a file was actually deleted from disk (false when it was already absent — forget is idempotent).

type MoveResult

type MoveResult struct {
	From   string
	To     string
	Result ingest.MoveResult
}

MoveResult reports the old and new uris and the underlying ingest outcome (the re-indexed entries, whether the source was a directory, and any inbound links left dangling).

type OkfyInput

type OkfyInput struct {
	Source     string
	Out        string
	Collection string
	Type       string
	Tags       []string
	Force      bool
}

OkfyInput is a request to convert an existing plain .txt or .md file into an OKF document at Out and index it, leaving the source intact. Source and Out are tree-root-relative paths confined to the tree.

type ReadOptions added in v0.3.0

type ReadOptions struct {
	// Section keeps only chunks whose heading path contains this text
	// (case-insensitive), e.g. "Definition of done".
	Section string
	// Lines keeps only chunks overlapping this 1-based inclusive source-line span,
	// written "start-end" or a bare "start".
	Lines     string
	MaxChars  int
	MaxTokens int
	// FollowLinks, when set, attaches the read document's 1-hop link neighborhood
	// to the result (best-effort: it never fails an otherwise-successful read).
	FollowLinks bool
	// LinkLimit caps neighbors per direction when FollowLinks is set (0 = default).
	LinkLimit int
	// LinkDirection selects which edges to follow (empty = both).
	LinkDirection Direction
}

ReadOptions narrows and bounds a read. Section and Lines scope a document read to a subset of its chunks (both empty reads the whole document); they are ignored for a single-chunk read, which is already a fragment. MaxChars and MaxTokens cap the returned Content (see charBudget); the zero value of every field reproduces the unbounded whole-document/whole-chunk read.

type ReadResult

type ReadResult struct {
	URI        string
	Collection string
	Title      string
	Content    string
	Truncated  bool
	Citation   *Citation
	// Neighbors is the document's 1-hop link neighborhood, populated only when
	// ReadOptions.FollowLinks is set. Empty when the document has no visible
	// neighbors.
	Neighbors []RelatedNeighbor
}

ReadResult is the outcome of reading a document or a single chunk. Content is the chunk text or the reconstructed document body; the metadata fields locate it. Citation is set only for a chunk read. Truncated reports that a size budget clipped Content, signalling the caller to read deeper if it needs the rest.

type RelatedNeighbor added in v0.3.0

type RelatedNeighbor struct {
	URI        string `json:"uri"`
	Title      string `json:"title,omitempty"`
	Collection string `json:"collection,omitempty"`
	Direction  string `json:"direction"`
	Resolved   bool   `json:"resolved"`
}

RelatedNeighbor is one 1-hop link-graph neighbor of a document. Resolved is false for a dangling outbound link (the target uri is not an ingested document), in which case Title and Collection are empty. Inbound neighbors are always resolved.

type RelatedResult added in v0.3.0

type RelatedResult struct {
	URI      string            `json:"uri"`
	Outbound []RelatedNeighbor `json:"outbound"`
	Inbound  []RelatedNeighbor `json:"inbound"`
}

RelatedResult is the link-graph neighborhood of a document: the outbound links it contains and the inbound backlinks that point at it, one hop out. A direction not requested is nil.

type RememberInput

type RememberInput struct {
	Type       string
	Text       string
	Collection string
	Tags       []string
	Path       string
}

RememberInput is a request to capture a note. Type is a free-form OKF type (e.g. idea, document, Task); Text is the note body; Collection defaults to "default"; Tags are optional frontmatter signals; Path, when set, is a tree-root-relative target ending in .md (else the note is auto-named under the capture directory).

type RememberResult

type RememberResult struct {
	URI        string
	DocumentID string
	Chunks     int
	Type       string
	Deferred   bool
}

RememberResult reports the stored note's tree-relative uri (an immediate citation), the document id, the number of chunks indexed, the recorded type, and whether ingestion was deferred to a watcher (Deferred true means the file is written but not yet indexed, so DocumentID is empty and Chunks is 0).

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service owns the memory verbs over an open store, the loaded configuration, the OKF tree root, and a secret scanner. The same value backs both surfaces.

func New

func New(db *sql.DB, cfg *config.Config, treeRoot string, scanner security.SecretScanner, logger *slog.Logger) *Service

New builds a Service. cfg supplies the write/capture/indexing settings and the gate flags read by the write verbs; treeRoot confines every caller-supplied path; scanner screens captured/converted text for secrets (a nil scanner defaults to a regex scanner so the write verbs are always guarded); logger writes diagnostics. The configured search.default_limit is applied by Search/Context when a caller leaves limit unset.

func (*Service) Context

func (s *Service) Context(ctx context.Context, r search.Retriever, q search.Query) ([]ContextBlock, error)

Context runs q through r with the default (flat, unbounded) shaping.

func (*Service) ContextWithOptions added in v0.3.0

func (s *Service) ContextWithOptions(ctx context.Context, r search.Retriever, q search.Query, opts ContextOptions) ([]ContextBlock, error)

ContextWithOptions runs q through r and batch-loads each hit's full chunk content, returning LLM-ready blocks in rank order. The retriever only returns a highlighted snippet, so context fetches the whole chunk in one query (avoiding the per-result N+1). A chunk that vanished between search and fetch falls back to its snippet so the block still carries something. When opts.GroupByDocument is set it over-fetches candidates, keeps the best chunk per document, and caps to the requested number of documents; opts.Cliff then trims the low-relevance tail, and the size budget clips each block.

func (*Service) Diagnose added in v0.3.0

func (s *Service) Diagnose(ctx context.Context, opts doctor.Options) ([]doctor.Finding, error)

Diagnose runs the read-only health detectors over the store and returns their findings. Like List (which wraps browse), it is a thin pass-through to the doctor package so the CLI `doctor` command and a future mnemos.doctor MCP tool share one implementation and cannot drift.

Hidden collections are excluded here rather than in doctor: findings carry document URIs and tags, so an unfiltered run would disclose the namespace of a collection the operator denied. Applying it at the verb layer is what makes the exclusion hold for every surface, including one that does not exist yet.

The tree root is supplied the same way, for the same reason: it enables the missing-file detector for every caller at once, so no surface silently runs without it.

func (*Service) EditBody added in v0.3.0

func (s *Service) EditBody(ctx context.Context, uri, newBody string) (EditResult, error)

EditBody replaces the document body at uri, leaving its frontmatter block byte for byte. It is gated by [mcp].allow_write.

func (*Service) EditFrontmatter added in v0.3.0

func (s *Service) EditFrontmatter(ctx context.Context, in EditFrontmatterInput) (EditResult, error)

EditFrontmatter applies field patches (and optionally a new body) to an existing OKF document and reindexes it. It is gated by [mcp].allow_write.

The file is written before the reindex runs, deliberately: a write that lands makes the edit durable whatever happens next, so a failing reindex costs a stale index rather than the user's work. That case returns an error wrapping ErrReindexAfterWrite so a caller can say which of the two happened.

func (*Service) Forget

func (s *Service) Forget(ctx context.Context, path string) (ForgetResult, error)

Forget removes a file from disk and the index. It de-indexes before touching disk (crash-coherent ordering, via ingest.ForgetPath). It is gated by [mcp].allow_delete. Resolve and ForgetPath errors are returned un-prefixed so each surface can add its own ("forget:" / "mcp:").

func (*Service) List

func (s *Service) List(ctx context.Context, opts browse.Options) ([]browse.Entry, error)

List walks the OKF tree on disk and annotates each file with the index metadata mnemos holds, applying opts as filters. It owns the indexed/unindexed mutual-exclusion check (formerly re-implemented on both surfaces) and the include/exclude/security-exclude wiring from config, so both surfaces narrow the tree identically. A nil result is normalized to an empty slice.

func (*Service) Move

func (s *Service) Move(ctx context.Context, from, to string) (MoveResult, error)

Move renames a file or directory within the OKF tree and re-indexes it under the new path, preserving each document's collection. It is gated by [mcp].allow_delete (the old index entries are deleted). The two resolve errors are tagged "source:" / "destination:" so a surface can prefix them ("mv: source:" / "mcp: destination:") and still tell the two apart.

func (*Service) Okfy

func (s *Service) Okfy(ctx context.Context, in OkfyInput) (ingest.OkfyResult, error)

Okfy converts a plain file into an OKF document and indexes it. It is not gated on either surface for the local operator running it directly; the MCP adapter applies the [mcp].allow_write gate at its boundary (the tool is also un-registered when write is off).

This is the one write verb whose gate lives in a surface rather than here. It is deliberate (see TestOkfyUngated) and carries no exposure today, since the MCP adapter both un-registers the tool and re-checks. It is recorded as an architectural inconsistency rather than a defect: a third surface calling this Service would inherit an unguarded write, so revisit the decision before adding one.

func (*Service) OpenForEdit added in v0.3.0

func (s *Service) OpenForEdit(ctx context.Context, uri string) (EditSource, error)

OpenForEdit reads the document at uri from disk and splits its frontmatter for display. It reads the file rather than the index because an editor edits the source of truth, not the reconstruction of it.

func (*Service) ReadChunk

func (s *Service) ReadChunk(ctx context.Context, chunkID string) (ReadResult, error)

ReadChunk returns a single chunk's content and its citation. An unknown chunk_id is a not-found error, not a crash. A chunk in a hidden collection returns the same not-found error as a missing one (see hiddenCollection).

func (*Service) ReadDocument

func (s *Service) ReadDocument(ctx context.Context, uri string) (ReadResult, error)

ReadDocument reconstructs a whole document from its stored chunks. It is the unbounded, unscoped read; ReadDocumentOpts adds section/line scoping.

func (*Service) ReadDocumentOpts added in v0.3.0

func (s *Service) ReadDocumentOpts(ctx context.Context, uri string, opts ReadOptions) (ReadResult, error)

ReadDocumentOpts reconstructs a document from its stored chunks ordered by ordinal, de-duplicating the overlapping line ranges the windowed chunker emits. When opts.Section or opts.Lines is set it first narrows to the matching chunks, so a caller can pull one heading or line span instead of the whole document. An unknown uri is a not-found error; a scope that matches no chunk is an error too, so an empty read is never silently returned. Size budgets are applied by the ReadOneOpts caller, uniformly with chunk reads.

func (*Service) ReadOne

func (s *Service) ReadOne(ctx context.Context, uri, chunkID string) (ReadResult, error)

ReadOne dispatches an unbounded read of a document or chunk. It is ReadOneOpts with the zero ReadOptions.

func (*Service) ReadOneOpts added in v0.3.0

func (s *Service) ReadOneOpts(ctx context.Context, uri, chunkID string, opts ReadOptions) (ReadResult, error)

ReadOneOpts dispatches to ReadDocumentOpts or ReadChunk based on which of uri/chunkID is set, rejecting the both-set and neither-set cases, then applies the size budget to the returned content uniformly (section/line scoping applies to document reads only; a chunk is already a fragment). It is the single entry the MCP read tool delegates to.

func (*Service) Related added in v0.3.0

func (s *Service) Related(ctx context.Context, uri string, dir Direction, limit int) (RelatedResult, error)

Related returns the 1-hop link-graph neighbors of the document at uri, honoring the server-side visibility boundary (security.visibility.deny): a neighbor in a hidden collection is dropped, and an unknown or hidden uri returns the same not-found error as a missing document (mirroring the read verbs). dir selects outbound, inbound, or both (the zero value "" is treated as both); limit caps each direction (<= 0 uses the default). Edges are document-granularity, so results locate documents; the agent reads or searches within one to get cited chunks.

func (*Service) Remember

func (s *Service) Remember(ctx context.Context, in RememberInput) (RememberResult, error)

Remember writes a note as an OKF markdown file and (unless capture is deferred to a watcher) indexes it. It validates the type/text, secret-scans the body before writing anything, confines a caller-chosen path to the tree, and appends a directory log entry. It is gated by [mcp].allow_write.

func (*Service) Search

func (s *Service) Search(ctx context.Context, r search.Retriever, q search.Query) ([]model.Result, error)

Search runs q through r, applying the configured default limit when q.Limit is unset and the server-side visibility boundary (security.visibility.deny) so a hidden collection can never surface. r is the retriever the surface chose (lexical FTS, or hybrid lexical+vector); the service does not pick one.

func (*Service) Similar added in v0.3.0

func (s *Service) Similar(ctx context.Context, uri string, limit int) ([]search.SimilarResult, error)

Similar returns the documents semantically nearest to uri, honoring the server-side visibility boundary. It returns nil (no error) when the corpus carries no embeddings or the source document has none of its own: "not embedded yet" is an expected state, not a failure.

Jump to

Keyboard shortcuts

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