do-memory-core 0.1.31

Core episodic learning system for AI agents with pattern extraction, reward scoring, and dual storage backend
Documentation
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! Phase 2 (GENESIS) Integration Tests
//!
//! End-to-end tests for capacity management and semantic summarization integration
//! with `SelfLearningMemory`.

use do_memory_core::{
    EvictionPolicy, ExecutionResult, ExecutionStep, MemoryConfig, SelfLearningMemory, TaskContext,
    TaskOutcome, TaskType,
};

/// Helper to create a test episode with sufficient steps to pass quality threshold
async fn create_test_episode(
    memory: &SelfLearningMemory,
    task_desc: &str,
    num_steps: usize,
) -> uuid::Uuid {
    let episode_id = memory
        .start_episode(
            task_desc.to_string(),
            TaskContext::default(),
            TaskType::Testing,
        )
        .await;

    // Add steps to meet quality threshold
    for i in 0..num_steps {
        let mut step =
            ExecutionStep::new(i + 1, format!("tool_{}", i % 6), format!("Test step {i}"));
        step.result = Some(ExecutionResult::Success {
            output: format!("Step {i} completed successfully"),
        });
        memory.log_step(episode_id, step).await;
    }

    episode_id
}

#[tokio::test]
async fn test_complete_episode_with_summary() {
    // Test that episodes are summarized when summarization is enabled

    let config = MemoryConfig {
        quality_threshold: 0.3, // Lower threshold for faster test
        enable_summarization: true,
        summary_min_length: 50,
        summary_max_length: 150,
        ..Default::default()
    };

    let memory = SelfLearningMemory::with_config(config);

    // Create and complete an episode (reduced steps for faster test)
    let episode_id = create_test_episode(&memory, "Implement authentication feature", 10).await;

    let outcome = TaskOutcome::Success {
        verdict: "Authentication implemented successfully with tests".to_string(),
        artifacts: vec!["auth.rs".to_string(), "auth_test.rs".to_string()],
    };

    let result = memory.complete_episode(episode_id, outcome).await;
    assert!(result.is_ok(), "Episode completion should succeed");

    // Verify episode was completed
    let episode = memory.get_episode(episode_id).await.unwrap();
    assert!(episode.is_complete(), "Episode should be marked complete");
    assert!(episode.reward.is_some(), "Episode should have reward");
    assert!(
        episode.reflection.is_some(),
        "Episode should have reflection"
    );

    // Note: Summary storage verification will be added in Phase 2.4
    // when storage backends implement store_episode_summary()
}

#[tokio::test]
async fn test_complete_episode_with_capacity() {
    // Test that capacity limits are enforced during episode completion

    let config = MemoryConfig {
        quality_threshold: 0.3, // Lower threshold for faster test
        max_episodes: Some(5),  // Limit to 5 episodes
        eviction_policy: Some(EvictionPolicy::LRU),
        enable_summarization: false, // Disable to focus on capacity
        ..Default::default()
    };

    let memory = SelfLearningMemory::with_config(config);

    // Create and complete 7 episodes (should evict 2) - reduced steps for speed
    for i in 0..7 {
        let episode_id = create_test_episode(
            &memory,
            &format!("Task {i}"),
            8, // Reduced steps but still enough for quality threshold
        )
        .await;

        let outcome = TaskOutcome::Success {
            verdict: format!("Task {i} completed"),
            artifacts: vec![],
        };

        memory
            .complete_episode(episode_id, outcome)
            .await
            .expect("Episode completion should succeed");
    }

    // Verify we have at most 5 episodes
    let (total, completed, _) = memory.get_stats().await;
    assert!(total <= 5, "Should have at most 5 episodes, found {total}");
    assert_eq!(completed, total, "All stored episodes should be completed");
}

#[tokio::test]
async fn test_eviction_during_completion() {
    // Test that eviction occurs correctly when completing episodes at capacity

    let config = MemoryConfig {
        quality_threshold: 0.3, // Lower threshold for faster test
        max_episodes: Some(3),
        eviction_policy: Some(EvictionPolicy::RelevanceWeighted),
        enable_summarization: false,
        ..Default::default()
    };

    let memory = SelfLearningMemory::with_config(config);

    // Create 3 low-quality episodes (reduced steps for speed)
    for i in 0..3 {
        let episode_id = create_test_episode(
            &memory,
            &format!("Low quality task {i}"),
            6, // Fewer steps = lower quality
        )
        .await;

        memory
            .complete_episode(
                episode_id,
                TaskOutcome::Success {
                    verdict: "Completed".to_string(),
                    artifacts: vec![],
                },
            )
            .await
            .unwrap();
    }

    // Verify we have 3 episodes
    let (total_before, _, _) = memory.get_stats().await;
    assert_eq!(total_before, 3, "Should have 3 episodes before eviction");

    // Now create a high-quality episode (should trigger eviction of lowest quality)
    let high_quality_id = create_test_episode(
        &memory,
        "High quality complex task",
        15, // More steps = higher quality (reduced for speed)
    )
    .await;

    memory
        .complete_episode(
            high_quality_id,
            TaskOutcome::Success {
                verdict: "High quality implementation with comprehensive testing".to_string(),
                artifacts: vec!["impl.rs".to_string(), "tests.rs".to_string()],
            },
        )
        .await
        .unwrap();

    // Verify we still have at most 3 episodes (one was evicted)
    let (total_after, _, _) = memory.get_stats().await;
    assert!(
        total_after <= 3,
        "Should have at most 3 episodes after eviction, found {total_after}"
    );

    // Verify high-quality episode is still present
    assert!(
        memory.get_episode(high_quality_id).await.is_ok(),
        "High-quality episode should not be evicted"
    );
}

#[tokio::test]
async fn test_capacity_performance_overhead() {
    // Test that capacity enforcement doesn't add significant overhead

    use std::time::Instant;

    // Test without capacity limits (reduced iterations and steps for speed)
    let config_unlimited = MemoryConfig {
        quality_threshold: 0.3, // Lower threshold for faster test
        max_episodes: None,     // No limits
        enable_summarization: false,
        ..Default::default()
    };

    let memory_unlimited = SelfLearningMemory::with_config(config_unlimited);

    let start_unlimited = Instant::now();
    for i in 0..5 {
        let episode_id = create_test_episode(&memory_unlimited, &format!("Task {i}"), 8).await;
        memory_unlimited
            .complete_episode(
                episode_id,
                TaskOutcome::Success {
                    verdict: "Done".to_string(),
                    artifacts: vec![],
                },
            )
            .await
            .unwrap();
    }
    let duration_unlimited = start_unlimited.elapsed();

    // Test with capacity limits
    let config_limited = MemoryConfig {
        quality_threshold: 0.3,  // Lower threshold for faster test
        max_episodes: Some(100), // High enough to not trigger eviction in this test
        eviction_policy: Some(EvictionPolicy::RelevanceWeighted),
        enable_summarization: false,
        ..Default::default()
    };

    let memory_limited = SelfLearningMemory::with_config(config_limited);

    let start_limited = Instant::now();
    for i in 0..5 {
        let episode_id = create_test_episode(&memory_limited, &format!("Task {i}"), 8).await;
        memory_limited
            .complete_episode(
                episode_id,
                TaskOutcome::Success {
                    verdict: "Done".to_string(),
                    artifacts: vec![],
                },
            )
            .await
            .unwrap();
    }
    let duration_limited = start_limited.elapsed();

    // Calculate overhead
    // Clippy: Precision loss acceptable for test overhead calculation
    #[allow(clippy::cast_precision_loss)]
    let overhead_ms = duration_limited
        .saturating_sub(duration_unlimited)
        .as_millis() as f64
        / 5.0;

    println!("Unlimited: {duration_unlimited:?}");
    println!("Limited: {duration_limited:?}");
    println!("Average overhead per episode: {overhead_ms:.2} ms");

    // Overhead should be minimal (≤ 50ms average per episode)
    // Note: This is a soft check as CI environments can be unpredictable
    assert!(
        overhead_ms <= 50.0,
        "Capacity check overhead should be minimal, found {overhead_ms:.2} ms"
    );
}

#[tokio::test]
async fn test_backward_compatibility_no_capacity() {
    // Test that episodes work correctly when capacity is not configured

    let config = MemoryConfig {
        quality_threshold: 0.3, // Lower threshold for faster test
        max_episodes: None,     // No capacity limits
        eviction_policy: None,
        enable_summarization: false,
        ..Default::default()
    };

    let memory = SelfLearningMemory::with_config(config);

    // Create many episodes (no eviction should occur) - reduced count and steps for speed
    for i in 0..10 {
        let episode_id = create_test_episode(&memory, &format!("Task {i}"), 8).await;

        memory
            .complete_episode(
                episode_id,
                TaskOutcome::Success {
                    verdict: format!("Task {i} completed"),
                    artifacts: vec![],
                },
            )
            .await
            .expect("Episode completion should succeed");
    }

    // Verify all 10 episodes are stored
    let (total, completed, _) = memory.get_stats().await;
    assert_eq!(total, 10, "All 10 episodes should be stored");
    assert_eq!(completed, 10, "All episodes should be completed");
}

#[tokio::test]
async fn test_summarization_with_capacity() {
    // Test that both summarization and capacity work together

    let config = MemoryConfig {
        quality_threshold: 0.3, // Lower threshold for faster test
        max_episodes: Some(5),
        eviction_policy: Some(EvictionPolicy::RelevanceWeighted),
        enable_summarization: true,
        summary_min_length: 50,
        summary_max_length: 150,
        ..Default::default()
    };

    let memory = SelfLearningMemory::with_config(config);

    // Create episodes with both features enabled (reduced steps for speed)
    for i in 0..7 {
        let episode_id =
            create_test_episode(&memory, &format!("Feature {i} implementation"), 10).await;

        memory
            .complete_episode(
                episode_id,
                TaskOutcome::Success {
                    verdict: format!("Feature {i} implemented with tests and docs"),
                    artifacts: vec![
                        format!("feature_{}.rs", i),
                        format!("feature_{}_test.rs", i),
                    ],
                },
            )
            .await
            .expect("Episode completion should succeed");
    }

    // Verify capacity is enforced
    let (total, completed, _) = memory.get_stats().await;
    assert!(
        total <= 5,
        "Capacity should be enforced, found {total} episodes"
    );
    assert_eq!(completed, total, "All stored episodes should be completed");

    // Note: Summary verification will be added in Phase 2.4
    // when storage backends implement summary retrieval
}

#[tokio::test]
async fn test_eviction_preserves_high_quality() {
    // Test that eviction correctly preserves high-quality episodes

    let config = MemoryConfig {
        quality_threshold: 0.3, // Lower threshold for faster test
        max_episodes: Some(3),
        eviction_policy: Some(EvictionPolicy::RelevanceWeighted),
        enable_summarization: false,
        ..Default::default()
    };

    let memory = SelfLearningMemory::with_config(config);

    // Create one high-quality episode (reduced steps for speed)
    let high_quality_id =
        create_test_episode(&memory, "Complex high-quality implementation", 15).await;

    memory
        .complete_episode(
            high_quality_id,
            TaskOutcome::Success {
                verdict: "Excellent implementation with comprehensive testing and documentation"
                    .to_string(),
                artifacts: vec![
                    "main.rs".to_string(),
                    "tests.rs".to_string(),
                    "docs.md".to_string(),
                ],
            },
        )
        .await
        .unwrap();

    // Create multiple low-quality episodes (reduced steps for speed)
    for i in 0..5 {
        let low_quality_id = create_test_episode(&memory, &format!("Simple task {i}"), 6).await;

        memory
            .complete_episode(
                low_quality_id,
                TaskOutcome::Success {
                    verdict: "Done".to_string(),
                    artifacts: vec![],
                },
            )
            .await
            .unwrap();
    }

    // Verify capacity is enforced
    let (total, _, _) = memory.get_stats().await;
    assert!(total <= 3, "Should have at most 3 episodes, found {total}");

    // Verify high-quality episode is still present (not evicted)
    assert!(
        memory.get_episode(high_quality_id).await.is_ok(),
        "High-quality episode should be preserved during eviction"
    );
}