Expand description
§aidaemon-memory (experimental)
Long-term memory for agents built on aidaemon-core, ported from the
daemon’s memory system: durable facts keyed by
(scope, category, key) with supersession instead of overwrite,
episodes summarizing past sessions, hybrid retrieval (semantic +
lexical + freshness + confidence + provenance), recall decay and
retention.
Writing is model-driven: FactExtractor and EpisodeSummarizer ask
any aidaemon_core::Provider for a typed JSON payload. Nothing decides
what to remember from phrase lists, and retrieval is scoring with
relevance thresholds, not keyword gates.
§Integration
The rest of the SDK never depends on this crate. It plugs in through public traits only:
| Piece | Plugs in as |
|---|---|
full::FullMemory | aidaemon_policies::MemorySystem: aidaemon’s own memory (facts, episodes, procedures, people, profile) over sqlite::SqliteMemory, with its tools and run-end writer; the SDK preset’s default |
ScopedMemory | aidaemon_policies::MemorySystem: a small scope-keyed memory over any MemoryStore |
MemoryRecall | aidaemon_policies::Recall, for MemoryInjection (before_model) |
MemoryWriter | aidaemon_core::Hook (on_run_end, background extraction) |
RememberTool, RecallTool | aidaemon_core::Tool |
Memory::ingest_run | explicit call with a RunOutcome |
§Example
use aidaemon_memory::{HashEmbedder, Memory, MemoryRecall, NewFact, SqliteMemoryStore};
let store = SqliteMemoryStore::open("memory.db").await?;
let memory = Memory::new(store, HashEmbedder::default());
let scope = "telegram:synthetic-user-1";
memory
.remember(NewFact::new(scope, "person", "daughters", "Mia and Zoe"))
.await?;
for hit in memory.recall_facts(scope, "what are my daughters called", 5).await? {
println!("{:.2} {}", hit.score, hit.fact.value);
}
// Automatic injection into every model request:
let injection = aidaemon_policies::MemoryInjection::new(MemoryRecall::new(memory.clone()));§Bring your own memory
Memory holds only trait objects, so every part is swappable without
touching this crate:
MemoryStore: storage (pgvector, Qdrant, a document DB, …). Only row storage is required; lexical scoring has a default, and overridingMemoryStore::search_facts/MemoryStore::search_episodeslets a backend rank natively and bypass the scorer. Access levels, the graph signal and vector refresh are optional methods with safe defaults: a store without them hides its records from shared channels, scores with a graph signal of 0, and keeps old-model rows lexical-only.Embedder: an embedding API or local model (HashEmbedderfor tests and offline use,FastEmbedderbehind thefastembedfeature).Scorer: ranking (HybridScorer, the daemon’s weights, by default).- Any
aidaemon_core::ProviderforFactExtractorandEpisodeSummarizer.
Or replace this crate entirely: implement aidaemon_policies::MemorySystem
(the hooks and tools memory adds to a turn) or just
aidaemon_policies::Recall (snippets for injection) in your own crate.
The SDK only ever sees those traits.
Re-exports§
pub use records::FactPrivacy;
Modules§
- consolidation
- Fact consolidation: a background pass over owner conversation history that asks a model for durable facts the turn-by-turn extraction missed.
- dates
- Dates the people store keeps (birthdays, important dates). They are
machine dates the model fills: ISO 8601
YYYY-MM-DD, or--MM-DDwhen the year is unknown. Nothing else is read: a month name or a05/03-style date is locale prose (May 3 or March 5?), and a wrong reading sends a reminder on the wrong day. - embedding_
index - Backend-neutral storage contract for derived memory embeddings.
- episodes
- Episodes: a model summarizes a finished stretch of conversation into a recallable episode (summary, topics, tone, outcome, importance).
- full
- The full memory system: aidaemon’s own long-term memory over
SqliteMemory. It recalls facts, episodes, procedures, people and a core profile into each turn, scoped by the turn’s audience. A host supplies what is its own (goals, settings, diagnostics) through small traits. - history
- What memory consolidation reads: a host’s conversation history, as a typed contract. The host implements it over its own event log; memory never parses the host’s storage.
- neighborhood
- Pure expansion over already-loaded flat facts.
- people_
intelligence - People intelligence: daily upkeep of the people memory.
- policy
- The automatic-memory policy of one task, compiled once from typed facts. Prompt retrieval, message-span projection and post-task learning all read this one value; none of them reinterprets the user’s wording.
- profile
- progressive
- Progressive extraction: after each owner exchange, a fast model proposes durable facts, and the ones that are new, evidenced and not already stored are written.
- project
- Project memory: what the agent learns about one project, kept as plain Markdown files in a directory of that project’s own, apart from the owner’s personal memory.
- records
- The records of the daemon-shaped memory contract (
crate::stores): facts with privacy and channel provenance, extraction results, episodes, people, and exact conversation history. - render
- The daemon memory’s prompt block: the pinned critical facts and the memory section (communication preferences, the memory tool guide, query-ranked recall, people privacy rules, the current speaker). Pure rendering over records the recall read.
- retrieval_
eval - Small deterministic metrics used by memory retrieval benchmarks.
- search
- Explicit fact search ranking, pure and database-free.
- skills
- Skills a host keeps in its database: drafts promoted from successful procedures, pending the owner’s review, and the deprecated dynamic skills kept for migration compatibility.
- sqlite
- The SQLite implementation of the
crate::storescontract: facts with privacy and channel provenance, episodes, the claim graph, structured personal memory, people and learned habits. - stores
- The daemon-shaped memory storage contract: facts (with privacy, channel provenance and the extraction graph), episodes, exact history and people. A store implements the slices it supports; every method has a conservative default.
- task_
learning - Learning from finished tasks: a model reads what a task did and how it ended, and the procedures and error solutions it finds are stored for future tasks.
- trajectory
- Learning from what tasks did: a host’s task history as typed trace events, and the procedures, error solutions and expertise memory learns from them.
Structs§
- Behavior
Pattern - A detected behavior pattern.
- Decay
Report - What one
crate::Memory::decaypass changed. - Episode
- A summary of a finished run or session.
- Episode
Draft - A summary ready to become an
crate::Episode. - Episode
Record - An episode as a store hands it back.
- Episode
Summarizer - Summarizes a finished run or session into an episode. Importance is computed from typed features: message count, failed receipts or error tool results, and the model’s structured decisions, goals and intensity.
- Error
Solution - A learned error-solution pair.
- Expertise
- Expertise level in a domain.
- Extracted
Fact - One fact proposed by the model, before validation.
- Extraction
- The parsed result of one extraction call.
- Fact
- A durable piece of knowledge, keyed by
(scope, category, key). - Fact
Access - Who may see a stored fact or episode. The default is the narrowest level,
FactPrivacy::Private, so a record nobody classified stays out of shared channels. - Fact
Extractor - Asks a model for durable facts in a transcript slice.
- Fact
Record - A fact as a store hands it back, with its embedding if it has one.
- Hash
Embedder - Deterministic hashed bag-of-words embedder. No model, no network, same output on every machine (FNV-1a hashing). Similarity reflects shared words only, so it suits tests and offline use, not production recall.
- Hybrid
Scorer - The daemon’s hybrid ranking: weighted semantic + lexical + graph + freshness + confidence + provenance, gated on relevance thresholds.
- Hybrid
Weights - Weights of the fused score. Defaults are the daemon’s calibrated values and sum to 1.0.
- InMemory
Memory Store - A process-local
MemoryStore. Same semantics as the SQLite store, nothing persisted. Lexical scores use word overlap. - Ingest
Report - What
Memory::ingest_turn/Memory::ingest_rundid. - Memory
- Long-term memory. Depends only on traits (
MemoryStore,Embedder,Scorer), so every piece is swappable. Cheap to clone; clones share everything. - Memory
Builder - Builder for
Memory. - Memory
Recall - An
aidaemon_policies::Recallbacked byMemory: top facts first, then relevant episodes, as one-line snippets. Errors are logged and yield no snippets, so a memory outage never breaks a run. - Memory
Stats - Counts reported by
crate::MemoryStore::stats. - Memory
Writer - Extracts durable facts from the latest user turn once a run completes. Failed, cancelled and interrupted runs write nothing. The extraction runs on a spawned task and can neither block nor change the run, and because it fires at run end, hook order does not matter: an answer another hook rejected is never extracted.
- Merge
Config - When a new fact counts as a near duplicate of an active one under another
key. A threshold above 1.0 never matches; see
MergeConfig::disabled. - Migration
- One schema step.
- NewEpisode
- An episode to write.
- NewFact
- A fact to write. Normalized and validated by
NewFact::normalizedbefore it reaches a store. - Procedure
- A learned procedure (procedural memory).
- Provenance
- Where a fact came from. Every field is optional so manual imports work, but writers in this crate fill in what they know.
- Recall
Audience - Who a recall is for, as the host knows it. Uses the same visibility rule as the daemon’s own store.
- Recall
Tool - Lets the model search memory. Read-only.
- Reembed
Cursor - Where a re-embedding pass stands. Plain data, so a host can persist it.
- Reembed
Report - What one
crate::Memory::reembed_batchdid. - Remember
Tool - Lets the model store a fact. Not read-only, not destructive, and idempotent: the same arguments reinforce instead of duplicating.
- Retention
Config - Decay and retention windows (ports of the daemon’s
decay_memoriesandRetentionConfigdefaults).Nonedisables a step. - Scoped
Memory Memoryas a pluggable memory system: per turn, injected recall and therecalltool when the turn may read, theremembertool when it may write, and run-end fact extraction unless writes are explicit only.- Score
- A scorer’s verdict on one candidate.
- Scored
Episode - A recalled episode with its score.
- Scored
Fact - A recalled fact with its score.
- Scoring
Config - Tunables for
HybridScorer. - Signals
- The independently bounded retrieval signals behind a score (port of
the daemon’s
HybridSignals). All 0.0-1.0. - Sqlite
Memory Store - SQLite-backed
MemoryStore: versioned migrations, embeddings as little-endian f32 BLOBs, and FTS5 indexes (BM25) over active facts and episodes, kept in sync inside each write transaction. Cheap to clone. - Stale
Embedding - A record whose vector is missing or came from another model.
- Stored
Embedding - A stored vector plus the model that produced it. Vectors from a different model are ignored at recall time instead of being compared.
- User
Profile - User communication style preferences.
- Writer
Report - Result of one background extraction.
Enums§
- Memory
Error - Errors from this crate.
- Record
Kind - Which table of records an embedding refresh is working through.
- Upsert
Outcome - What an upsert did.
Constants§
- MAX_
FACT_ VALUE_ CHARS - Longest fact value accepted, in characters.
- MAX_
REEMBED_ BATCH - The most records one
Memory::reembed_batchwill embed. - MIGRATIONS
- Every migration this build knows, in order.
Traits§
- Embedder
- Turns text into vectors. Implement this to use an embedding API or
another local model;
crate::Memoryonly seesArc<dyn Embedder>. - Learning
Store - Learning system: procedures, expertise, behavior patterns, and error solutions.
- Memory
Store - Persistence for facts and episodes. This is the extension point for
bringing your own backend (pgvector, Qdrant, a document store, …).
crate::Memoryholds anArc<dyn MemoryStore>; the trait is object-safe. - Scorer
- Turns retrieval signals into a ranking score, or drops the candidate.
Functions§
- backfill_
learning_ embeddings - Embed the procedures and error solutions that have no current embedding, one batch of each. Returns whether there was anything to do.
- cosine
- Cosine similarity; 0.0 for mismatched lengths or zero vectors.
- decode_
embedding - Inverse of
encode_embedding;Nonefor a malformed blob. - decode_
embedding_ with_ dim - Decode a stored vector that must have
dimsdimensions. Besides the binary format ofencode_embedding, this reads the legacy format a JSON array of numbers (older daemon databases stored vectors that way). Any other blob, including binary of the wrong length, is an error. - detect_
domains - Detect domains from explicit classifier hints only.
- encode_
embedding - Little-endian f32 bytes, the BLOB format used by
SqliteMemoryStore. - episode_
importance - Episode importance from typed session features (port of the daemon’s
calculate_episode_importance). Base 0.5, clamped to 0.1..=1.0. - episode_
recall_ boost - Bounded reinforcement for often-recalled episodes: at most +16%.
- episode_
search_ text - error_
pattern - An error message reduced to a pattern that matches recurrences: line and
column numbers become
:<line>, paths become<path>, cut to 200 bytes. - expertise_
level - Calculate expertise level based on success/failure counts.
- extract_
trigger_ pattern - The trigger a procedure is recalled by: the task’s first sentence, cut to 100 bytes at a character boundary.
- fact_
search_ text "{category} {key words}: {value}", shared by every store so lexical and semantic signals see the same text.- generalize_
procedure - Replace specific paths and URLs in recorded actions with
<path>and<url>, so a learned procedure applies beyond the task it came from. - latest_
version - The newest schema version this build understands.
- new_
error_ solution - A new error solution, recorded as having worked once. The store assigns the id.
- new_
procedure - A new procedure recording its first outcome. The store assigns the id.
- normalize_
category - Lowercase and trim.
- normalize_
key - Lowercase snake_case: runs of whitespace,
-and.become_. - parse_
facts - Parse a fact-extraction reply: the
record_factstool call if present, otherwise JSON in the text ({"facts": [...]}or a bare array, code fences allowed). - procedure_
base_ name - A readable procedure name from its steps: the distinct tools it used, in
order (at most three), such as
terminal-edit_file. Steps are recorded astool(arguments)(ortool: ...); the name never depends on the wording of the request. - procedure_
keyed_ name - A stable, collision-resistant procedure name: the readable
base_nameplus a short hash of the normalized steps, so different workflows under a generic name (“deploy”) do not overwrite each other. - record_
tool_ sequence_ patterns - Record the habitual tool sequences in
toolsas behavior patterns. - related_
fact_ scores - Key-namespace and co-mention links from each seed to the other active facts, by fact id: the graph a store gets without keeping edges. Purely structural (keys and whole-word mentions), so stores can share it.
- same_
value - True when two values state the same thing modulo case and whitespace. Used to tell a restatement (reinforce) from a correction (supersede).
- summarize_
solution - A one-line summary of the tools a solution used (
name(...)actions). - term_
overlap - Fraction of distinct query tokens that occur as words in
text(0.0-1.0). The in-memory store’s lexical signal. - text_
similarity - Distinct words two texts share over the words they have between them (0.0-1.0), stopwords removed.
- tokens
- Lowercase alphanumeric words, stopwords removed. Splits on
_too, sofavorite_coloryieldsfavoriteandcolor. - tool_
sequence_ patterns - Tool sequences seen often enough to be a habit: each pair “after A, B”
that occurs at least three times in
tools(calls in order), with a confidence from its share of all calls (capped at 0.9). - turn_
importance - A conversation turn’s importance (0.1-1.0) from structure only: its role (system prompts are not memories; tool output counts less than what the user says) and its length. Nothing is inferred from the words used; deciding what is durable is the extraction model’s job.
- update_
communication_ profile - Update the stored profile’s verbosity from the owner’s recent messages. Tone and explanation preferences are not inferred from wording, so they keep their stored values.
- verbosity_
from_ messages - Communication verbosity from the average length of the user’s
messages:
briefup to 50 bytes,mediumup to 200,detailedabove.Nonewhen there are no messages. - word_
overlap - Fraction of distinct query words that occur as words in
text(0.0-1.0), counting every word, stopwords included. Unliketerm_overlap, a short query such as “who is she” keeps all its words: the signal for ranking when no embedder is available.
Type Aliases§
- Audience
Resolver - Maps a session id to who that conversation reaches, which decides what recall may return and how new memories are classified.
- Result
- Scope
Resolver - Maps a session id (from
ToolContext/HookContext) to a memory scope. The default is the identity: one memory per session id.