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;
94mod learning;
95mod memory;
96pub mod neighborhood;
97pub mod people_intelligence;
98pub mod policy;
99pub mod profile;
100pub mod progressive;
101pub mod project;
102mod recall;
103pub mod records;
104pub mod render;
105pub mod retrieval_eval;
106mod scoring;
107pub mod search;
108#[cfg(test)]
109mod search_fixture;
110pub mod skills;
111pub mod sqlite;
112mod store;
113pub mod stores;
114mod system;
115pub mod task_learning;
116pub mod text;
117mod tools;
118pub mod trajectory;
119mod types;
120mod writer;
121
122#[cfg(feature = "fastembed")]
123pub use embed::{DEFAULT_FASTEMBED_MODEL, FastEmbedder};
124pub use embed::{
125 Embedder, HashEmbedder, cosine, decode_embedding, decode_embedding_with_dim, encode_embedding,
126};
127pub use error::{MemoryError, Result};
128pub use extract::{
129 EpisodeDraft, EpisodeSummarizer, ExtractedFact, Extraction, FactExtractor, parse_facts,
130};
131pub use learning::{
132 BehaviorPattern, ErrorSolution, Expertise, LearningStore, Procedure, UserProfile,
133 backfill_learning_embeddings, detect_domains, error_pattern, expertise_level,
134 extract_trigger_pattern, generalize_procedure, new_error_solution, new_procedure,
135 procedure_base_name, procedure_keyed_name, record_tool_sequence_patterns, summarize_solution,
136 tool_sequence_patterns, update_communication_profile, verbosity_from_messages,
137};
138pub use memory::{
139 AudienceResolver, IngestReport, MAX_REEMBED_BATCH, Memory, MemoryBuilder, ScopeResolver,
140};
141pub use recall::MemoryRecall;
142pub use records::FactPrivacy;
143pub use scoring::{
144 HybridScorer, HybridWeights, Scorer, ScoringConfig, episode_importance, episode_recall_boost,
145 term_overlap, text_similarity, tokens, turn_importance, word_overlap,
146};
147pub use store::{
148 InMemoryMemoryStore, MIGRATIONS, MemoryStore, Migration, SqliteMemoryStore, latest_version,
149 related_fact_scores,
150};
151pub use system::ScopedMemory;
152pub use tools::{RecallTool, RememberTool};
153pub use types::{
154 DecayReport, Episode, EpisodeRecord, Fact, FactAccess, FactRecord, MAX_FACT_VALUE_CHARS,
155 MemoryStats, MergeConfig, NewEpisode, NewFact, Provenance, RecallAudience, RecordKind,
156 ReembedCursor, ReembedReport, RetentionConfig, Score, ScoredEpisode, ScoredFact, Signals,
157 StaleEmbedding, StoredEmbedding, UpsertOutcome, episode_search_text, fact_search_text,
158 normalize_category, normalize_key, same_value,
159};
160pub use writer::{MemoryWriter, WriterReport};