Skip to main content

Crate aidaemon_memory

Crate aidaemon_memory 

Source
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:

PiecePlugs in as
full::FullMemoryaidaemon_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
ScopedMemoryaidaemon_policies::MemorySystem: a small scope-keyed memory over any MemoryStore
MemoryRecallaidaemon_policies::Recall, for MemoryInjection (before_model)
MemoryWriteraidaemon_core::Hook (on_run_end, background extraction)
RememberTool, RecallToolaidaemon_core::Tool
Memory::ingest_runexplicit 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 overriding MemoryStore::search_facts / MemoryStore::search_episodes lets 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 (HashEmbedder for tests and offline use, FastEmbedder behind the fastembed feature).
  • Scorer: ranking (HybridScorer, the daemon’s weights, by default).
  • Any aidaemon_core::Provider for FactExtractor and EpisodeSummarizer.

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-DD when the year is unknown. Nothing else is read: a month name or a 05/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::stores contract: 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§

BehaviorPattern
A detected behavior pattern.
DecayReport
What one crate::Memory::decay pass changed.
Episode
A summary of a finished run or session.
EpisodeDraft
A summary ready to become an crate::Episode.
EpisodeRecord
An episode as a store hands it back.
EpisodeSummarizer
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.
ErrorSolution
A learned error-solution pair.
Expertise
Expertise level in a domain.
ExtractedFact
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).
FactAccess
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.
FactExtractor
Asks a model for durable facts in a transcript slice.
FactRecord
A fact as a store hands it back, with its embedding if it has one.
HashEmbedder
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.
HybridScorer
The daemon’s hybrid ranking: weighted semantic + lexical + graph + freshness + confidence + provenance, gated on relevance thresholds.
HybridWeights
Weights of the fused score. Defaults are the daemon’s calibrated values and sum to 1.0.
InMemoryMemoryStore
A process-local MemoryStore. Same semantics as the SQLite store, nothing persisted. Lexical scores use word overlap.
IngestReport
What Memory::ingest_turn / Memory::ingest_run did.
Memory
Long-term memory. Depends only on traits (MemoryStore, Embedder, Scorer), so every piece is swappable. Cheap to clone; clones share everything.
MemoryBuilder
Builder for Memory.
MemoryRecall
An aidaemon_policies::Recall backed by Memory: 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.
MemoryStats
Counts reported by crate::MemoryStore::stats.
MemoryWriter
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.
MergeConfig
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::normalized before 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.
RecallAudience
Who a recall is for, as the host knows it. Uses the same visibility rule as the daemon’s own store.
RecallTool
Lets the model search memory. Read-only.
ReembedCursor
Where a re-embedding pass stands. Plain data, so a host can persist it.
ReembedReport
What one crate::Memory::reembed_batch did.
RememberTool
Lets the model store a fact. Not read-only, not destructive, and idempotent: the same arguments reinforce instead of duplicating.
RetentionConfig
Decay and retention windows (ports of the daemon’s decay_memories and RetentionConfig defaults). None disables a step.
ScopedMemory
Memory as a pluggable memory system: per turn, injected recall and the recall tool when the turn may read, the remember tool when it may write, and run-end fact extraction unless writes are explicit only.
Score
A scorer’s verdict on one candidate.
ScoredEpisode
A recalled episode with its score.
ScoredFact
A recalled fact with its score.
ScoringConfig
Tunables for HybridScorer.
Signals
The independently bounded retrieval signals behind a score (port of the daemon’s HybridSignals). All 0.0-1.0.
SqliteMemoryStore
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.
StaleEmbedding
A record whose vector is missing or came from another model.
StoredEmbedding
A stored vector plus the model that produced it. Vectors from a different model are ignored at recall time instead of being compared.
UserProfile
User communication style preferences.
WriterReport
Result of one background extraction.

Enums§

MemoryError
Errors from this crate.
RecordKind
Which table of records an embedding refresh is working through.
UpsertOutcome
What an upsert did.

Constants§

MAX_FACT_VALUE_CHARS
Longest fact value accepted, in characters.
MAX_REEMBED_BATCH
The most records one Memory::reembed_batch will 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::Memory only sees Arc<dyn Embedder>.
LearningStore
Learning system: procedures, expertise, behavior patterns, and error solutions.
MemoryStore
Persistence for facts and episodes. This is the extension point for bringing your own backend (pgvector, Qdrant, a document store, …). crate::Memory holds an Arc<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; None for a malformed blob.
decode_embedding_with_dim
Decode a stored vector that must have dims dimensions. Besides the binary format of encode_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_facts tool 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 as tool(arguments) (or tool: ...); the name never depends on the wording of the request.
procedure_keyed_name
A stable, collision-resistant procedure name: the readable base_name plus 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 tools as 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, so favorite_color yields favorite and color.
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: brief up to 50 bytes, medium up to 200, detailed above. None when 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. Unlike term_overlap, a short query such as “who is she” keeps all its words: the signal for ranking when no embedder is available.

Type Aliases§

AudienceResolver
Maps a session id to who that conversation reaches, which decides what recall may return and how new memories are classified.
Result
ScopeResolver
Maps a session id (from ToolContext / HookContext) to a memory scope. The default is the identity: one memory per session id.