1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
//! Layered memory trait definitions.
//!
//! This module defines the five trait contracts that make up the **layered
//! memory architecture**: [`ConversationMemory`], [`UserProfileMemory`],
//! [`ProjectMemory`], [`FactMemory`], and [`SummaryMemory`].
//!
//! Each trait represents a distinct *memory layer* with its own access
//! patterns, retention policies, and lifecycle — from short-lived
//! conversational windows to durable, searchable facts.
//!
//! # Design principles
//!
//! - **Separation of concerns**: each layer has a single responsibility and
//! can be backed by a different storage engine.
//! - **Async-first**: every operation is `async` so backends can use
//! remote stores, vector databases, or batched I/O without blocking.
//! - **Swappable backends**: implementing a trait is the only contract;
//! the layered engine composes them without coupling to any concrete type.
//! - **`Send + Sync`**: all traits require `Send + Sync` so they can be
//! shared across `tokio` tasks safely.
use async_trait;
use HashMap;
use StoreError;
// ---------------------------------------------------------------------------
// ConversationMemory
// ---------------------------------------------------------------------------
/// Short-term conversational memory.
///
/// Models the sliding window of a single conversation session — messages are
/// appended in chronological order, the most recent `n` can be retrieved,
/// and the oldest messages can be evicted to bound memory usage.
///
/// # Typical backends
///
/// - In-memory ring buffer (fast, bounded).
/// - Redis list with `LPUSH` / `LRANGE` / `LTRIM`.
/// - SQLite table ordered by `recorded_at`.
///
/// # Examples
///
/// ```ignore
/// use xz_memory_engine::layered::traits::ConversationMemory;
/// use xz_memory_core::StoreError;
///
/// async fn example(store: &dyn ConversationMemory) -> Result<(), StoreError> {
/// store.append("sess-1", "Hello, how can I help?").await?;
/// store.append("sess-1", "What is the weather?").await?;
/// let recent = store.recent("sess-1", 2).await?;
/// assert_eq!(recent.len(), 2);
/// let evicted = store.evict("sess-1", 1).await?;
/// assert_eq!(evicted, 1);
/// Ok(())
/// }
/// ```
// ---------------------------------------------------------------------------
// UserProfileMemory
// ---------------------------------------------------------------------------
/// Per-user profile / preference memory.
///
/// Stores key-value preference pairs keyed by `(user_id, key)`. This layer
/// is designed for stable, low-volume data that persists across sessions:
/// language preferences, notification settings, display name, etc.
///
/// # Typical backends
///
/// - SQLite `user_prefs` table.
/// - Redis hash per user (`HSET` / `HGETALL` / `HDEL`).
/// - Embedded key-value store (e.g. RocksDB, Sled).
///
/// # Examples
///
/// ```ignore
/// use xz_memory_engine::layered::traits::UserProfileMemory;
/// use xz_memory_core::StoreError;
///
/// async fn example(store: &dyn UserProfileMemory) -> Result<(), StoreError> {
/// store.set_preference("user-42", "language", "zh-CN").await?;
/// store.set_preference("user-42", "theme", "dark").await?;
/// let prefs = store.get_preferences("user-42").await?;
/// assert!(prefs.contains_key("language"));
/// store.remove_preference("user-42", "theme").await?;
/// Ok(())
/// }
/// ```
// ---------------------------------------------------------------------------
// ProjectMemory
// ---------------------------------------------------------------------------
/// Project-scoped key-value memory with fuzzy search.
///
/// Unlike [`UserProfileMemory`], this layer is designed for larger,
/// project-associated datasets that benefit from content-based retrieval.
/// Values are opaque strings and the `search` method enables approximate
/// matching (e.g. for notes, code snippets, or documentation fragments).
///
/// # Typical backends
///
/// - Full-text search index (Tantivy, Meilisearch) backed by a document store.
/// - Vector database (Qdrant, Milvus) with semantic search via embedding.
/// - SQLite with FTS5 extension.
///
/// # Examples
///
/// ```ignore
/// use xz_memory_engine::layered::traits::ProjectMemory;
/// use xz_memory_core::StoreError;
///
/// async fn example(store: &dyn ProjectMemory) -> Result<(), StoreError> {
/// store.put("proj-1", "note-1", "Remember to update deps").await?;
/// let val = store.get("proj-1", "note-1").await?;
/// assert_eq!(val, Some("Remember to update deps".into()));
/// let results = store.search("proj-1", "update deps").await?;
/// assert!(!results.is_empty());
/// Ok(())
/// }
/// ```
// ---------------------------------------------------------------------------
// FactMemory
// ---------------------------------------------------------------------------
/// Semantic / tagged fact memory.
///
/// Stores discrete facts with optional tags and supports fuzzy retrieval
/// by semantic similarity or keyword match. Designed for knowledge that
/// is ingested, queried, and occasionally pruned — the agent's long-term
/// general knowledge.
///
/// # Typical backends
///
/// - Vector database with embedding-based retrieval.
/// - Hybrid index combining BM25 keyword search and dense embeddings.
/// - Graph database with tag-based traversal.
///
/// # Examples
///
/// ```ignore
/// use xz_memory_engine::layered::traits::FactMemory;
/// use xz_memory_core::StoreError;
///
/// async fn example(store: &dyn FactMemory) -> Result<(), StoreError> {
/// let id = store.remember("Tokyo is the capital of Japan", &["geography".into()]).await?;
/// let results = store.recall("capital of Japan", 5).await?;
/// assert!(!results.is_empty());
/// store.forget(&id).await?;
/// Ok(())
/// }
/// ```
// ---------------------------------------------------------------------------
// SummaryMemory
// ---------------------------------------------------------------------------
/// Compressed / summary memory.
///
/// Stores timestamped summaries of conversations, projects, or other scopes.
/// Each summary is associated with a `source` (e.g. the raw conversation ID
/// that was summarised) and a monotonic timestamp. The latest summary can
/// be retrieved quickly, and the full history can be inspected.
///
/// # Typical backends
///
/// - SQLite table with `(scope, summary, source, created_at)`.
/// - Document database (MongoDB, CouchDB) with scope-based indexing.
/// - Append-only log file.
///
/// # Examples
///
/// ```ignore
/// use xz_memory_engine::layered::traits::SummaryMemory;
/// use xz_memory_core::StoreError;
///
/// async fn example(store: &dyn SummaryMemory) -> Result<(), StoreError> {
/// store.store("sess-1", "User asked about weather and travel.",
/// "raw-sess-1").await?;
/// let latest = store.get_latest("sess-1").await?;
/// assert!(latest.is_some());
/// let history = store.history("sess-1", 10).await?;
/// assert!(!history.is_empty());
/// Ok(())
/// }
/// ```