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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
//! Episode completion and pattern learning
use crate::error::{Error, Result};
use crate::pattern::Pattern;
use crate::types::TaskOutcome;
use std::sync::Arc;
use tracing::{debug, info, instrument, warn};
use uuid::Uuid;
use super::SelfLearningMemory;
impl SelfLearningMemory {
pub(super) async fn extract_patterns_sync(&self, episode_id: Uuid) -> Result<()> {
// Get the episode Arc and clone it to work with Episode directly
let episode_arc = {
let episodes = self.episodes_fallback.read().await;
episodes
.get(&episode_id)
.cloned()
.ok_or(Error::NotFound(episode_id))?
};
let mut episode = (*episode_arc).clone();
// Extract patterns
let extracted_patterns = self.pattern_extractor.extract(&episode);
debug!(
pattern_count = extracted_patterns.len(),
"Extracted patterns synchronously"
);
// Store patterns and link to episode
let mut patterns = self.patterns_fallback.write().await;
let mut pattern_ids = Vec::new();
for pattern in extracted_patterns {
let pattern_id = pattern.id();
pattern_ids.push(pattern_id);
// Store in backends
if let Some(cache) = &self.cache_storage {
if let Err(e) = cache.store_pattern(&pattern).await {
warn!("Failed to store pattern in cache: {}", e);
}
}
if let Some(turso) = &self.turso_storage {
if let Err(e) = turso.store_pattern(&pattern).await {
warn!("Failed to store pattern in Turso: {}", e);
}
}
patterns.insert(pattern_id, pattern);
}
episode.patterns = pattern_ids;
// Extract heuristics
match self.heuristic_extractor.extract(&episode).await {
Ok(extracted_heuristics) => {
debug!(
heuristic_count = extracted_heuristics.len(),
"Extracted heuristics synchronously"
);
// Store heuristics and link to episode
let mut heuristic_ids = Vec::new();
let mut heuristics_map = self.heuristics_fallback.write().await;
for heuristic in &extracted_heuristics {
heuristic_ids.push(heuristic.heuristic_id);
// Store in backends
if let Some(cache) = &self.cache_storage {
#[allow(clippy::excessive_nesting)]
if let Err(e) = cache.store_heuristic(heuristic).await {
warn!("Failed to store heuristic in cache: {}", e);
}
}
if let Some(turso) = &self.turso_storage {
#[allow(clippy::excessive_nesting)]
if let Err(e) = turso.store_heuristic(heuristic).await {
warn!("Failed to store heuristic in Turso: {}", e);
}
}
// Store in in-memory fallback
heuristics_map.insert(heuristic.heuristic_id, heuristic.clone());
}
episode.heuristics = heuristic_ids;
}
Err(e) => {
warn!("Failed to extract heuristics: {}", e);
episode.heuristics = Vec::new();
}
}
// Update episode with pattern and heuristic IDs in storage backends
if let Some(cache) = &self.cache_storage {
if let Err(e) = cache.store_episode(&episode).await {
warn!(
"Failed to update episode with patterns and heuristics in cache: {}",
e
);
}
}
if let Some(turso) = &self.turso_storage {
if let Err(e) = turso.store_episode(&episode).await {
warn!(
"Failed to update episode with patterns and heuristics in Turso: {}",
e
);
}
}
// Re-insert the updated episode into the in-memory cache
let mut episodes = self.episodes_fallback.write().await;
episodes.insert(episode_id, Arc::new(episode));
Ok(())
}
/// Store patterns (for use by async extraction workers)
///
/// Links patterns to an episode. This is public so the queue workers
/// can call it after extracting patterns asynchronously.
///
/// # Arguments
///
/// * `episode_id` - Episode these patterns came from
/// * `patterns` - Patterns to store
///
/// # Errors
///
/// Returns error if episode not found
pub async fn store_patterns(
&self,
episode_id: Uuid,
extracted_patterns: Vec<Pattern>,
) -> Result<()> {
// Get the episode Arc and clone it to work with Episode directly
let episode_arc = {
let episodes = self.episodes_fallback.read().await;
episodes
.get(&episode_id)
.cloned()
.ok_or(Error::NotFound(episode_id))?
};
let mut episode = (*episode_arc).clone(); // Deref Arc<Episode> to Episode, then clone
let mut patterns = self.patterns_fallback.write().await;
let mut pattern_ids = Vec::new();
for pattern in extracted_patterns {
let pattern_id = pattern.id();
pattern_ids.push(pattern_id);
// Store in backends
if let Some(cache) = &self.cache_storage {
if let Err(e) = cache.store_pattern(&pattern).await {
warn!("Failed to store pattern in cache: {}", e);
}
}
if let Some(turso) = &self.turso_storage {
if let Err(e) = turso.store_pattern(&pattern).await {
warn!("Failed to store pattern in Turso: {}", e);
}
}
patterns.insert(pattern_id, pattern);
}
episode.patterns = pattern_ids;
// Update episode with pattern IDs in storage backends
if let Some(cache) = &self.cache_storage {
if let Err(e) = cache.store_episode(&episode).await {
warn!("Failed to update episode with patterns in cache: {}", e);
}
}
if let Some(turso) = &self.turso_storage {
if let Err(e) = turso.store_episode(&episode).await {
warn!("Failed to update episode with patterns in Turso: {}", e);
}
}
// Re-insert the updated episode into the in-memory cache
let mut episodes = self.episodes_fallback.write().await;
episodes.insert(episode_id, Arc::new(episode));
Ok(())
}
/// Get queue statistics (if async extraction enabled)
///
/// Returns statistics about the pattern extraction queue,
/// or None if async extraction is not enabled.
pub async fn get_queue_stats(&self) -> Option<crate::learning::queue::QueueStats> {
if let Some(queue) = &self.pattern_queue {
Some(queue.get_stats().await)
} else {
None
}
}
/// Update heuristic confidence based on new episode outcome
///
/// Updates a heuristic's confidence score by incorporating evidence from
/// a new episode. The heuristic is retrieved from storage, updated with
/// the new evidence, and persisted back to all storage backends.
///
/// # Algorithm
///
/// 1. Retrieve heuristic from in-memory fallback (or storage if needed)
/// 2. Call `heuristic.update_evidence(episode_id, is_success)`
/// 3. Recalculate confidence: `success_rate` × √`sample_size`
/// 4. Store updated heuristic to both Turso and redb
/// 5. Update in-memory fallback
///
/// # Arguments
///
/// * `heuristic_id` - ID of the heuristic to update
/// * `episode_id` - ID of the episode providing new evidence
/// * `outcome` - Outcome of the episode
///
/// # Returns
///
/// `Ok(())` on success, or an error if the heuristic doesn't exist.
///
/// # Errors
///
/// Returns [`Error::NotFound`] if the heuristic ID doesn't exist.
///
/// # Examples
///
/// ```
/// use do_memory_core::{SelfLearningMemory, TaskOutcome};
/// use uuid::Uuid;
///
/// # async fn example() -> anyhow::Result<()> {
/// let memory = SelfLearningMemory::new();
///
/// let heuristic_id = Uuid::new_v4(); // From previous heuristic extraction
/// let episode_id = Uuid::new_v4(); // From current episode
///
/// // Update with successful outcome
/// memory.update_heuristic_confidence(
/// heuristic_id,
/// episode_id,
/// TaskOutcome::Success {
/// verdict: "Applied heuristic successfully".to_string(),
/// artifacts: vec![],
/// },
/// ).await?;
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self, outcome), fields(heuristic_id = %heuristic_id, episode_id = %episode_id))]
pub async fn update_heuristic_confidence(
&self,
heuristic_id: Uuid,
episode_id: Uuid,
outcome: TaskOutcome,
) -> Result<()> {
let mut heuristics = self.heuristics_fallback.write().await;
let heuristic = heuristics
.get_mut(&heuristic_id)
.ok_or(Error::NotFound(heuristic_id))?;
// Determine if the outcome was successful
let is_success = matches!(
outcome,
TaskOutcome::Success { .. } | TaskOutcome::PartialSuccess { .. }
);
debug!(
heuristic_id = %heuristic_id,
episode_id = %episode_id,
is_success = is_success,
old_confidence = heuristic.confidence,
old_success_rate = heuristic.evidence.success_rate,
old_sample_size = heuristic.evidence.sample_size,
"Updating heuristic confidence"
);
// Update evidence
heuristic.update_evidence(episode_id, is_success);
// Recalculate confidence: success_rate × √sample_size
let new_confidence =
heuristic.evidence.success_rate * (heuristic.evidence.sample_size as f32).sqrt();
heuristic.confidence = new_confidence;
info!(
heuristic_id = %heuristic_id,
new_confidence = new_confidence,
new_success_rate = heuristic.evidence.success_rate,
new_sample_size = heuristic.evidence.sample_size,
"Updated heuristic confidence"
);
// Store updated heuristic in backends
if let Some(cache) = &self.cache_storage {
if let Err(e) = cache.store_heuristic(heuristic).await {
warn!("Failed to store updated heuristic in cache: {}", e);
}
}
if let Some(turso) = &self.turso_storage {
if let Err(e) = turso.store_heuristic(heuristic).await {
warn!("Failed to store updated heuristic in Turso: {}", e);
}
}
Ok(())
}
}