Documentation
¶
Overview ¶
Package mnemos exposes a small, framework-neutral Go API for the Mnemos evidence layer. It is intended to be consumed by agent runtimes (Claude Code, Codex, Hermes, Nomi, OpenClaw, NanoClaw, and similar), programmatic systems, and tests.
Three modes ¶
Mnemos supports three modes, selected at construction time:
- Passive — no language model required. Rule-based claim extraction and token-overlap query ranking. Works with zero environment configuration. Use WithPassiveMode.
- Shared — the agent runtime hands Mnemos its model provider so enrichment shares the same key, model, and budget. Use WithSharedProvider.
- Enhanced — Mnemos uses its own dedicated provider configuration, typically a different (smaller/cheaper) model for background enrichment. Use WithEnhancedMode.
Zero-config ¶
The default constructor does the right thing without any options:
mem, err := mnemos.New()
if err != nil { panic(err) }
defer mem.Close()
This boots Mnemos in WithPassiveMode against the default storage (XDG-resolved SQLite at ~/.local/share/mnemos/mnemos.db) with an embedded Chronos for temporal queries.
Storage backends ¶
Mnemos talks to its storage layer through a URL-scheme registry. The providers a binary supports are determined by blank-imports in the consuming program:
import (
_ "github.com/felixgeelhaar/mnemos/internal/store/memory"
_ "github.com/felixgeelhaar/mnemos/internal/store/sqlite"
_ "github.com/felixgeelhaar/mnemos/internal/store/postgres"
)
Without at least one provider blank-imported, New cannot open the default storage and will return an error. For most callers, importing the sqlite provider is sufficient.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ClaimItem ¶
type ClaimItem struct {
// Text is the claim content. Required.
Text string
// Type classifies the claim. Mnemos recognises "fact",
// "hypothesis", "decision", and "test_result" natively. Defaults
// to "fact" when empty.
Type string
// Confidence is the agent's confidence in [0, 1]. Defaults to 1.0
// when zero (the agent is asserting the claim with full
// confidence). Mnemos will recompute the trust score from this
// confidence × corroboration × freshness at query time.
Confidence float64
// EventIDs links the claim back to source events. Optional but
// strongly recommended: claims without evidence cannot be ranked
// by corroboration and skip the freshness factor. Each id must
// already exist in the event store (use [Memory.RememberEvent] to
// add them first).
EventIDs []string
// ValidFrom is when the claim's content first became true. Zero
// value means "valid since before the system started tracking";
// for fresh claims, set this to time.Now() or the time the agent
// observed the fact.
ValidFrom time.Time
// ValidUntil is when the claim stopped being true (a successor
// claim took its place). Zero value means "currently valid".
ValidUntil time.Time
// RunID groups related claims together for scoped recall.
// Optional; matches the RunID used on the linked events when
// present.
RunID string
}
ClaimItem is a pre-built claim an agent runtime can hand to Mnemos directly, bypassing the extraction pipeline. Use this when the agent has already derived structured assertions (with its own model, from parsed structured data, or through any other path) and wants Mnemos to persist them as-is.
This is the third of Mnemos's three input modes:
- Item + Memory.Remember → rule-based extraction (passive mode) or LLM-driven extraction (shared / enhanced mode).
- Same Item path with WithSharedProvider / WithEnhancedMode → extraction uses the configured language model.
- ClaimItem + Memory.RememberClaim → no extraction at all; Mnemos stores the supplied claim verbatim and (optionally) links it to source events the caller has already persisted via Memory.RememberEvent.
type Event ¶
type Event struct {
// ID, when non-empty, sets the stable identifier; otherwise Mnemos
// generates a UUID.
ID string
// At is the wall-clock time the event occurred. Required.
At time.Time
// Type classifies the event. Examples: "deployment", "incident",
// "decision", "release", "alert". Used by [TimelineQuery.Types]
// for filtering.
Type string
// Content is the human-readable description.
Content string
// Metadata is free-form key/value context.
Metadata map[string]string
// RunID groups related events. Optional; empty means default run.
RunID string
}
Event is a temporal entry to remember. Unlike an Item, an Event is always anchored to a wall-clock time and is intended for the timeline (incident timelines, audit trails, deployment history, decision logs).
Events are stored both as Mnemos events (immutable knowledge) and fed to the bundled Chronos engine for temporal pattern detection.
type Item ¶
type Item struct {
// Type classifies the knowledge. Mnemos recognises "fact",
// "hypothesis", and "decision" natively; other strings are stored
// verbatim and can be filtered on later.
Type string
// Content is the human-readable text Mnemos stores and later
// retrieves. The extraction pipeline may derive multiple claims
// from a single Item when the content contains several assertions.
Content string
// Metadata is free-form key/value context attached to the source
// event. Searchable; not used for ranking by default.
Metadata map[string]string
// Source is an optional human-readable label for where the
// knowledge came from (a file path, a URL, a person's name). Stored
// as a Mnemos Input so downstream queries can group by origin.
Source string
// RunID groups related items together for scoped recall. Optional;
// when empty, the item is associated with the implicit default run.
RunID string
}
Item is a single piece of knowledge to remember. Type and Content are the only required fields; everything else is optional.
type Memory ¶
type Memory interface {
// Remember stores an item of knowledge. Extraction runs the item
// through the configured pipeline (rule-based in passive mode,
// LLM-augmented when a [TextGenerator] is configured) and persists
// any derived claims with full evidence links back to the source
// event.
Remember(ctx context.Context, item Item) error
// RememberClaim stores a pre-built claim directly, without running
// extraction. Use this when an agent runtime has already derived a
// structured assertion (with its own model, parsed structured data,
// etc.) and wants Mnemos to persist it verbatim. Linked source
// events (referenced via [ClaimItem.EventIDs]) must already exist
// in the event store — add them with [Memory.RememberEvent] first
// when they're new.
//
// Returns the generated claim ID so the caller can reference the
// claim in future relationship edges or evidence links.
RememberClaim(ctx context.Context, claim ClaimItem) (string, error)
// Recall answers a query against the stored knowledge. The result
// is ranked by trust score (or token overlap in passive mode when
// no embeddings are configured) and may include claims reached by
// graph expansion when [Query.Hops] > 0.
Recall(ctx context.Context, q Query) ([]Result, error)
// RememberEvent stores a temporal event. The event is appended to
// the Mnemos event log and forwarded to the bundled Chronos engine
// for pattern detection. Events with the same ID are idempotent.
RememberEvent(ctx context.Context, e Event) error
// Timeline returns events matching the query in chronological order.
// Source events live in Mnemos; signals derived by Chronos are
// surfaced as additional events with [Event.Type] reflecting the
// detected pattern.
Timeline(ctx context.Context, q TimelineQuery) ([]Event, error)
// Close releases the underlying storage handle. Safe to call more
// than once. Returns the first error encountered.
Close() error
}
Memory is the public API of the Mnemos evidence layer. Implementations are returned by New; all methods are safe for concurrent use.
Example (RememberClaim) ¶
ExampleMemory_rememberClaim shows the third input mode: an agent runtime hands a pre-built claim to Mnemos directly, bypassing the extraction pipeline. Useful when the agent has already derived a structured assertion with its own model or from parsed structured data.
package main
import (
"context"
"time"
"github.com/felixgeelhaar/mnemos"
// Tests use the in-memory storage provider.
_ "github.com/felixgeelhaar/mnemos/internal/store/memory"
)
func main() {
mem, _ := mnemos.New(
mnemos.WithStorage("memory://?namespace=example_remember_claim"),
mnemos.WithPassiveMode(),
)
defer func() { _ = mem.Close() }()
ctx := context.Background()
// Step 1: anchor the claim to a source event the agent observed.
_ = mem.RememberEvent(ctx, mnemos.Event{
ID: "evt-obs-1",
At: time.Now(),
Type: "observation",
Content: "User said: I prefer Go for backend.",
RunID: "session-A",
})
// Step 2: the agent has already extracted a structured claim from
// the event using its own reasoning. Hand it to Mnemos verbatim.
claimID, _ := mem.RememberClaim(ctx, mnemos.ClaimItem{
Text: "User prefers Go for backend work.",
Type: "fact",
Confidence: 0.95,
EventIDs: []string{"evt-obs-1"},
RunID: "session-A",
})
_ = claimID
}
Output:
func New ¶
New constructs a Memory from the supplied options. When no mode option is supplied, WithPassiveMode is assumed; when no storage option is supplied, the DSN is resolved from MNEMOS_DB_URL > a project-local .mnemos/mnemos.db (walked up from the working directory like .git) > the XDG default ~/.local/share/mnemos/mnemos.db.
The caller is responsible for blank-importing the storage providers it needs. The simplest pattern:
import _ "github.com/felixgeelhaar/mnemos/internal/store/sqlite"
will let the default DSN resolve. For Postgres, MySQL, libSQL, or in-memory storage, blank-import the corresponding sub-package.
Returned Memory holds an open storage handle; the caller MUST call Memory.Close when finished.
Example ¶
ExampleNew demonstrates the simplest possible Mnemos usage: zero options, in-memory storage for the doc-example sandbox, and a single Remember + Recall roundtrip.
package main
import (
"context"
"fmt"
"github.com/felixgeelhaar/mnemos"
// Tests use the in-memory storage provider.
_ "github.com/felixgeelhaar/mnemos/internal/store/memory"
)
func main() {
mem, err := mnemos.New(
mnemos.WithStorage("memory://?namespace=example_new"),
mnemos.WithPassiveMode(),
)
if err != nil {
fmt.Println("setup:", err)
return
}
defer func() { _ = mem.Close() }()
ctx := context.Background()
if err := mem.Remember(ctx, mnemos.Item{
Type: "fact",
Content: "The user prefers Go for backend work.",
}); err != nil {
fmt.Println("remember:", err)
return
}
results, err := mem.Recall(ctx, mnemos.Query{Text: "user Go work"})
if err != nil {
fmt.Println("recall:", err)
return
}
fmt.Println("results:", len(results) > 0)
}
Output: results: true
Example (Passive) ¶
ExampleNew_passive shows the passive (no-LLM) mode explicitly. This is the default; the With option is shown for clarity.
package main
import (
"context"
"github.com/felixgeelhaar/mnemos"
// Tests use the in-memory storage provider.
_ "github.com/felixgeelhaar/mnemos/internal/store/memory"
)
func main() {
mem, _ := mnemos.New(
mnemos.WithStorage("memory://?namespace=example_passive"),
mnemos.WithPassiveMode(),
)
defer func() { _ = mem.Close() }()
_ = mem.Remember(context.Background(), mnemos.Item{
Type: "decision",
Content: "Adopt SQLite for local-first storage.",
})
}
Output:
Example (WithChronos) ¶
ExampleNew_withChronos shows supplying a custom Chronos engine for durable temporal storage. The default mnemos.New() boots an in-memory Chronos automatically; pass WithChronos when you want shared state with another consumer or non-default detector config.
package main
import (
"context"
"time"
"github.com/felixgeelhaar/chronos/embed"
"github.com/felixgeelhaar/mnemos"
// Tests use the in-memory storage provider.
_ "github.com/felixgeelhaar/mnemos/internal/store/memory"
)
func main() {
eng, _ := embed.New(embed.WithStorage("memory://?namespace=example_chronos"))
defer func() { _ = eng.Close() }()
mem, _ := mnemos.New(
mnemos.WithStorage("memory://?namespace=example_chronos_mem"),
mnemos.WithChronos(eng),
)
defer func() { _ = mem.Close() }()
_ = mem.RememberEvent(context.Background(), mnemos.Event{
At: time.Now(),
Type: "deployment",
Content: "shipped v2.3.0",
RunID: "release-cycle",
})
}
Output:
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
Option configures New. Options are constructed by the With* helpers in this package. The interface is intentionally sealed (its method is unexported) so the option set can grow without breaking existing callers.
func WithActor ¶
WithActor sets the user/agent id Mnemos stamps onto every write. Use this when you need attribution different from the MNEMOS_USER_ID env var (which is the default). Passing an empty string is a no-op.
func WithChronos ¶
WithChronos supplies an existing embed.Engine for Mnemos to use as its temporal backend instead of booting a default one. Useful when:
- The host already runs Chronos for other purposes and wants to share the same engine + storage.
- You need a non-default Chronos configuration (custom detector set, parallel detection, dedicated SQL storage).
Ownership of the supplied engine stays with the caller; Memory.Close will NOT call embed.Engine.Close on it. When this option is not used, New constructs a default in-memory engine and owns it.
func WithEnhancedMode ¶
func WithEnhancedMode(cfg ProviderConfig) Option
WithEnhancedMode configures Mnemos to use its own dedicated language-model + embedding provider, separate from any host agent's configuration. Useful when you want background enrichment on a cheaper or specialised model, or when separating billing.
func WithPassiveMode ¶
func WithPassiveMode() Option
WithPassiveMode selects the no-LLM mode. Claim extraction uses the built-in rule-based engine; query ranking falls back to token overlap when no embeddings exist. This is the default if no mode option is supplied.
Use this mode when:
- You don't have a language-model provider configured.
- You want zero per-call cost.
- You're embedding Mnemos in a test or smoke-demo environment.
func WithSharedProvider ¶
func WithSharedProvider(tg providers.TextGenerator, embedder providers.Embedder) Option
WithSharedProvider configures Mnemos to use a providers.TextGenerator and optional providers.Embedder supplied by the caller. Use this mode when an agent runtime already has a model client configured and wants Mnemos to share the same key, model, and budget.
embedder may be nil; Mnemos falls back to token-overlap ranking when embeddings are not supplied. Pairing a TextGenerator with no Embedder is supported and useful when the consumer's provider doesn't expose an embedding API (e.g. Anthropic) and the consumer doesn't want to configure a second provider just for embeddings.
func WithStorage ¶
WithStorage overrides the storage DSN. The DSN selects the provider by URL scheme (e.g. "sqlite://", "memory://", "postgres://", "mysql://", "libsql://"). The corresponding provider package must be blank-imported by the consuming program for the scheme to be registered.
When unset, New resolves the DSN the same way the mnemos CLI does: MNEMOS_DB_URL env > project-local ./.mnemos/mnemos.db (walked up like .git) > XDG default ~/.local/share/mnemos/mnemos.db.
type ProviderConfig ¶
type ProviderConfig struct {
LLMProvider string
LLMAPIKey string
LLMModel string
LLMBaseURL string
EmbedProvider string
EmbedAPIKey string
EmbedModel string
EmbedBaseURL string
}
ProviderConfig describes a dedicated language-model + embedding provider configuration. Used with WithEnhancedMode when Mnemos should run its own model for background enrichment (typically a smaller/cheaper model than the host agent uses).
LLMProvider names the family: "anthropic", "openai", "gemini", "ollama", or "openai-compat". LLMAPIKey, LLMModel, and LLMBaseURL fill in the connection details; the defaults match the corresponding MNEMOS_LLM_* environment variables.
EmbedProvider, EmbedAPIKey, EmbedModel, and EmbedBaseURL configure the embedding side. When EmbedProvider is empty, the embedding side falls back to the LLM-side fields (mirroring the env-var behaviour). Note that Anthropic does not offer an embedding API; pair it with a separate embedding provider (Voyage, OpenAI, Ollama, ...).
type Query ¶
type Query struct {
// Text is the natural-language question or keyword.
Text string
// RunID, when set, narrows the answer to items remembered under
// that run. Empty means "across all runs".
RunID string
// Hops controls graph expansion. 0 (the default) returns directly
// retrieved claims. 1 follows one supports/contradicts edge and
// brings the connected claims in. Higher values expand further.
Hops int
// Limit caps the number of [Result]s returned. 0 means "use the
// engine default" (typically 10).
Limit int
// AsOf, when set, returns the answer as it would have been at that
// instant in time. Useful for incident timelines and audits. Zero
// value disables the filter (the common case).
AsOf time.Time
// IncludeHistory makes the engine also return superseded claim
// versions for the items that match. False by default.
IncludeHistory bool
}
Query describes what to recall.
type Result ¶
type Result struct {
// ClaimID is the stable identifier of the underlying claim.
ClaimID string
// Text is the claim's content.
Text string
// Type is the claim's classification ("fact", "hypothesis",
// "decision", or a custom string).
Type string
// Confidence is the [0, 1] confidence score the extractor assigned
// when the claim was created.
Confidence float64
// TrustScore is the [0, 1] composite score combining confidence,
// corroboration, and freshness. Computed by Mnemos at query time.
TrustScore float64
// HopDistance is how many supports/contradicts edges Mnemos walked
// from the directly-retrieved set to reach this claim. 0 means
// the claim was a direct hit; 1+ means it was reached via graph
// expansion (see [Query.Hops]).
HopDistance int
// Provenance is a human-readable origin label: "local" for claims
// sourced from this project's events, or a registry URL for claims
// imported via federation. Empty when unknown.
Provenance string
}
Result is one item Mnemos returned for a Query.
type TimelineQuery ¶
type TimelineQuery struct {
// From bounds the range below. Zero means "no lower bound".
From time.Time
// To bounds the range above. Zero means "no upper bound".
To time.Time
// Types, when non-empty, restricts the result to events whose
// [Event.Type] is in the list.
Types []string
// RunID, when set, narrows the timeline to a single run.
RunID string
// Limit caps the result size. 0 means "use the engine default".
Limit int
}
TimelineQuery selects a slice of [Event]s from the timeline.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package client is a typed Go client for the Mnemos registry HTTP API (the surface served by `mnemos serve`).
|
Package client is a typed Go client for the Mnemos registry HTTP API (the surface served by `mnemos serve`). |
|
tools
Package tools exposes Mnemos's agent-memory primitives as canonical LLM tool-call schemas.
|
Package tools exposes Mnemos's agent-memory primitives as canonical LLM tool-call schemas. |
|
cmd
|
|
|
mnemos
command
|
|
|
internal
|
|
|
adapters/outcomes
Package outcomes contains pull adapters that turn external metric or log sources into Mnemos Outcomes.
|
Package outcomes contains pull adapters that turn external metric or log sources into Mnemos Outcomes. |
|
auth
Package auth implements the Mnemos identity primitives: JWT issuance, validation, and revocation.
|
Package auth implements the Mnemos identity primitives: JWT issuance, validation, and revocation. |
|
autoedge
Package autoedge wires the implicit relationships that fall out of recording outcomes and attaching them to decisions.
|
Package autoedge wires the implicit relationships that fall out of recording outcomes and attaching them to decisions. |
|
bias
Package bias surfaces simple, explainable bias indicators on the evidence layer.
|
Package bias surfaces simple, explainable bias indicators on the evidence layer. |
|
embedding
Package embedding provides a provider-agnostic interface for text embeddings.
|
Package embedding provides a provider-agnostic interface for text embeddings. |
|
llm
Package llm provides a provider-agnostic interface for LLM completions.
|
Package llm provides a provider-agnostic interface for LLM completions. |
|
markdown
Package markdown round-trips Mnemos lessons and playbooks to and from a Git-friendly markdown format.
|
Package markdown round-trips Mnemos lessons and playbooks to and from a Git-friendly markdown format. |
|
pipeline
Package pipeline provides shared orchestration logic used by both the CLI and MCP server entrypoints: extraction engine setup, artifact persistence, and embedding generation.
|
Package pipeline provides shared orchestration logic used by both the CLI and MCP server entrypoints: extraction engine setup, artifact persistence, and embedding generation. |
|
server/grpc
Package grpc implements the gRPC API surface for Mnemos.
|
Package grpc implements the gRPC API surface for Mnemos. |
|
store
Package store wires Mnemos's persistence backends behind a single scheme-dispatched factory.
|
Package store wires Mnemos's persistence backends behind a single scheme-dispatched factory. |
|
store/libsql
Package libsql implements a store provider backed by libSQL — the SQLite-compatible engine behind Turso.
|
Package libsql implements a store provider backed by libSQL — the SQLite-compatible engine behind Turso. |
|
store/memory
Package memory implements an in-process store provider whose repositories live entirely in Go maps guarded by a single sync.RWMutex.
|
Package memory implements an in-process store provider whose repositories live entirely in Go maps guarded by a single sync.RWMutex. |
|
store/mysql
Package mysql implements a store provider backed by MySQL or MariaDB (the wire protocol is identical and the SQL dialect we rely on is the common subset).
|
Package mysql implements a store provider backed by MySQL or MariaDB (the wire protocol is identical and the SQL dialect we rely on is the common subset). |
|
store/postgres
Package postgres implements a store provider backed by Postgres.
|
Package postgres implements a store provider backed by Postgres. |
|
synthesize
Package synthesize derives Lessons from Action -> Outcome chains.
|
Package synthesize derives Lessons from Action -> Outcome chains. |
|
trust
Package trust derives a single, comparable trust_score for each claim from three independent signals: the LLM-assigned confidence, the number of distinct events that corroborate the claim, and the freshness of the most recent corroborating evidence.
|
Package trust derives a single, comparable trust_score for each claim from three independent signals: the LLM-assigned confidence, the number of distinct events that corroborate the claim, and the freshness of the most recent corroborating evidence. |
|
proto
|
|
|
Package providers exposes framework-neutral interfaces for language model and embedding providers.
|
Package providers exposes framework-neutral interfaces for language model and embedding providers. |
|
tools
|
|
|
mutate
command
Command mutate runs an in-tree mutation testing harness.
|
Command mutate runs an in-tree mutation testing harness. |