Skip to main content

aidaemon_memory/
lib.rs

1//! # aidaemon-memory (experimental)
2//!
3//! Long-term memory for agents built on `aidaemon-core`, ported from the
4//! daemon's memory system: durable **facts** keyed by
5//! `(scope, category, key)` with supersession instead of overwrite,
6//! **episodes** summarizing past sessions, hybrid retrieval (semantic +
7//! lexical + freshness + confidence + provenance), recall decay and
8//! retention.
9//!
10//! Writing is model-driven: [`FactExtractor`] and [`EpisodeSummarizer`] ask
11//! any `aidaemon_core::Provider` for a typed JSON payload. Nothing decides
12//! what to remember from phrase lists, and retrieval is scoring with
13//! relevance thresholds, not keyword gates.
14//!
15//! ## Integration
16//!
17//! The rest of the SDK never depends on this crate. It plugs in through
18//! public traits only:
19//!
20//! | Piece | Plugs in as |
21//! |---|---|
22//! | [`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 |
23//! | [`ScopedMemory`] | `aidaemon_policies::MemorySystem`: a small scope-keyed memory over any [`MemoryStore`] |
24//! | [`MemoryRecall`] | `aidaemon_policies::Recall`, for `MemoryInjection` (`before_model`) |
25//! | [`MemoryWriter`] | `aidaemon_core::Hook` (`on_run_end`, background extraction) |
26//! | [`RememberTool`], [`RecallTool`] | `aidaemon_core::Tool` |
27//! | [`Memory::ingest_run`] | explicit call with a `RunOutcome` |
28//!
29//! ## Example
30//!
31//! ```no_run
32//! # async fn demo() -> Result<(), aidaemon_memory::MemoryError> {
33//! use aidaemon_memory::{HashEmbedder, Memory, MemoryRecall, NewFact, SqliteMemoryStore};
34//!
35//! let store = SqliteMemoryStore::open("memory.db").await?;
36//! let memory = Memory::new(store, HashEmbedder::default());
37//!
38//! let scope = "telegram:synthetic-user-1";
39//! memory
40//!     .remember(NewFact::new(scope, "person", "daughters", "Mia and Zoe"))
41//!     .await?;
42//! for hit in memory.recall_facts(scope, "what are my daughters called", 5).await? {
43//!     println!("{:.2} {}", hit.score, hit.fact.value);
44//! }
45//!
46//! // Automatic injection into every model request:
47//! let injection = aidaemon_policies::MemoryInjection::new(MemoryRecall::new(memory.clone()));
48//! # let _ = injection;
49//! # Ok(()) }
50//! ```
51//!
52//! ## Bring your own memory
53//!
54//! [`Memory`] holds only trait objects, so every part is swappable without
55//! touching this crate:
56//!
57//! - [`MemoryStore`]: storage (pgvector, Qdrant, a document DB, ...). Only
58//!   row storage is required; lexical scoring has a default, and overriding
59//!   [`MemoryStore::search_facts`] / [`MemoryStore::search_episodes`] lets a
60//!   backend rank natively and bypass the scorer. Access levels, the graph
61//!   signal and vector refresh are optional methods with safe defaults: a
62//!   store without them hides its records from shared channels, scores with
63//!   a graph signal of 0, and keeps old-model rows lexical-only.
64//! - [`Embedder`]: an embedding API or local model ([`HashEmbedder`] for
65//!   tests and offline use, `FastEmbedder` behind the `fastembed` feature).
66//! - [`Scorer`]: ranking ([`HybridScorer`], the daemon's weights, by
67//!   default).
68//! - Any `aidaemon_core::Provider` for [`FactExtractor`] and
69//!   [`EpisodeSummarizer`].
70//!
71//! Or replace this crate entirely: implement `aidaemon_policies::MemorySystem`
72//! (the hooks and tools memory adds to a turn) or just
73//! `aidaemon_policies::Recall` (snippets for injection) in your own crate.
74//! The SDK only ever sees those traits.
75
76// Feature unification only (cargo-hakari); keeps the unused-dependency lint quiet.
77use workspace_hack as _;
78
79#[cfg(feature = "conformance")]
80pub mod conformance;
81pub mod consolidation;
82pub mod dates;
83mod embed;
84pub mod embedding_index;
85/// The daemon's local embedder (fastembed), or deterministic
86/// offline vectors: the caller picks one by constructor.
87#[cfg(feature = "fastembed")]
88pub mod embeddings;
89pub mod episodes;
90mod error;
91mod extract;
92pub mod full;
93pub mod history;
94pub mod hygiene;
95mod learning;
96mod memory;
97pub mod neighborhood;
98pub mod people_intelligence;
99pub mod policy;
100pub mod profile;
101pub mod progressive;
102pub mod project;
103mod recall;
104pub mod records;
105pub mod render;
106pub mod retrieval_eval;
107mod scoring;
108pub mod search;
109#[cfg(test)]
110mod search_fixture;
111pub mod skills;
112pub mod sqlite;
113mod store;
114pub mod stores;
115mod system;
116pub mod task_learning;
117pub mod text;
118mod tools;
119pub mod trajectory;
120mod types;
121mod writer;
122
123#[cfg(feature = "fastembed")]
124pub use embed::{DEFAULT_FASTEMBED_MODEL, FastEmbedder};
125pub use embed::{
126    Embedder, HashEmbedder, cosine, decode_embedding, decode_embedding_with_dim, encode_embedding,
127};
128pub use error::{MemoryError, Result};
129pub use extract::{
130    EpisodeDraft, EpisodeSummarizer, ExtractedFact, Extraction, FactExtractor, parse_facts,
131};
132pub use learning::{
133    BehaviorPattern, ErrorSolution, Expertise, LearningStore, Procedure, UserProfile,
134    backfill_learning_embeddings, detect_domains, error_pattern, expertise_level,
135    extract_trigger_pattern, generalize_procedure, new_error_solution, new_procedure,
136    procedure_base_name, procedure_keyed_name, record_tool_sequence_patterns, summarize_solution,
137    tool_sequence_patterns, update_communication_profile, verbosity_from_messages,
138};
139pub use memory::{
140    AudienceResolver, IngestReport, MAX_REEMBED_BATCH, Memory, MemoryBuilder, ScopeResolver,
141};
142pub use recall::MemoryRecall;
143pub use records::FactPrivacy;
144pub use scoring::{
145    HybridScorer, HybridWeights, Scorer, ScoringConfig, episode_importance, episode_recall_boost,
146    term_overlap, text_similarity, tokens, turn_importance, word_overlap,
147};
148pub use store::{
149    InMemoryMemoryStore, MIGRATIONS, MemoryStore, Migration, SqliteMemoryStore, latest_version,
150    related_fact_scores,
151};
152pub use stores::OverlapReviewVerdict;
153pub use system::ScopedMemory;
154pub use tools::{RecallTool, RememberTool};
155pub use types::{
156    DecayReport, Episode, EpisodeRecord, Fact, FactAccess, FactRecord, MAX_FACT_VALUE_CHARS,
157    MemoryStats, MergeConfig, NewEpisode, NewFact, Provenance, RecallAudience, RecordKind,
158    ReembedCursor, ReembedReport, RetentionConfig, Score, ScoredEpisode, ScoredFact, Signals,
159    StaleEmbedding, StoredEmbedding, UpsertOutcome, episode_search_text, fact_search_text,
160    normalize_category, normalize_key, same_value,
161};
162pub use writer::{MemoryWriter, WriterReport};