do-memory-core 0.1.30

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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
//! Comprehensive integration tests for heuristic learning cycle
//!
//! Tests the complete workflow of heuristic extraction, storage, retrieval, and updates.
//! Verifies end-to-end functionality from episode completion through heuristic application.

mod common;

use common::{ContextBuilder, setup_test_memory};
use do_memory_core::{
    ComplexityLevel, ExecutionResult, ExecutionStep, SelfLearningMemory, TaskContext, TaskOutcome,
    TaskType,
};
use uuid::Uuid;

/// Helper: Create an episode with decision points
async fn create_episode_with_decision_points(
    memory: &SelfLearningMemory,
    domain: &str,
    num_decisions: usize,
) -> Uuid {
    let context = ContextBuilder::new(domain)
        .language("rust")
        .framework("tokio")
        .complexity(ComplexityLevel::Moderate)
        .tag("decisions")
        .build();

    let episode_id = memory
        .start_episode(
            format!("Task with {num_decisions} decision points"),
            context,
            TaskType::CodeGeneration,
        )
        .await;

    // Add decision points with the same decision pattern
    for i in 0..num_decisions {
        // Decision step (contains decision keyword)
        let mut decision_step = ExecutionStep::new(
            (i * 2) + 1,
            "validator".to_string(),
            "Check if input is valid".to_string(), // Same decision text
        );
        decision_step.result = Some(ExecutionResult::Success {
            output: "Input is valid".to_string(),
        });
        memory.log_step(episode_id, decision_step).await;

        // Action step (what happens after the decision) - MUST be identical for grouping
        let mut action_step = ExecutionStep::new(
            (i * 2) + 2,
            "processor".to_string(),
            "Process the data".to_string(), // Same action for all
        );
        action_step.result = Some(ExecutionResult::Success {
            output: "Processed".to_string(),
        });
        memory.log_step(episode_id, action_step).await;
    }

    episode_id
}

#[tokio::test]
#[ignore = "slow integration test - run with --ignored or in release CI"]
async fn test_heuristic_extraction_from_episode() {
    // Given: A memory system
    let memory = setup_test_memory();

    // When: We create an episode with decision points
    let context = ContextBuilder::new("data-validation")
        .language("rust")
        .complexity(ComplexityLevel::Moderate)
        .build();

    let episode_id = memory
        .start_episode(
            "Validate and process data".to_string(),
            context.clone(),
            TaskType::CodeGeneration,
        )
        .await;

    // Add multiple similar decision points (needed for extraction threshold)
    for i in 0..3 {
        let mut decision_step = ExecutionStep::new(
            (i * 2) + 1,
            "validator".to_string(),
            "Check data integrity".to_string(), // Same condition
        );
        decision_step.result = Some(ExecutionResult::Success {
            output: "Data valid".to_string(),
        });
        memory.log_step(episode_id, decision_step).await;

        let mut action_step = ExecutionStep::new(
            (i * 2) + 2,
            "sanitizer".to_string(),
            "Sanitize input".to_string(), // Same action
        );
        action_step.result = Some(ExecutionResult::Success {
            output: "Sanitized".to_string(),
        });
        memory.log_step(episode_id, action_step).await;
    }

    // When: We complete the episode
    memory
        .complete_episode(
            episode_id,
            TaskOutcome::Success {
                verdict: "Data validated and processed".to_string(),
                artifacts: vec![],
            },
        )
        .await
        .unwrap();

    // Then: Heuristics should be extracted
    let episode = memory.get_episode(episode_id).await.unwrap();

    // Verify episode has heuristics linked
    assert!(
        !episode.heuristics.is_empty(),
        "Episode should have extracted heuristics. Got {} heuristics",
        episode.heuristics.len()
    );

    // Retrieve and verify heuristic fields
    let heuristics = memory.retrieve_relevant_heuristics(&context, 10).await;

    assert!(
        !heuristics.is_empty(),
        "Should retrieve extracted heuristics"
    );

    for heuristic in &heuristics {
        // Verify condition is not empty
        assert!(
            !heuristic.condition.is_empty(),
            "Heuristic condition should not be empty"
        );

        // Verify action is not empty
        assert!(
            !heuristic.action.is_empty(),
            "Heuristic action should not be empty"
        );

        // Verify confidence is in valid range (can exceed 1.0 due to sqrt formula)
        assert!(
            heuristic.confidence >= 0.0,
            "Confidence should be non-negative, got {}",
            heuristic.confidence
        );

        // Verify evidence
        assert!(
            heuristic.evidence.sample_size >= 2,
            "Sample size should meet minimum threshold of 2, got {}",
            heuristic.evidence.sample_size
        );
        assert!(
            heuristic.evidence.success_rate > 0.0,
            "Success rate should be positive for successful episode, got {}",
            heuristic.evidence.success_rate
        );
        assert!(
            !heuristic.evidence.episode_ids.is_empty(),
            "Evidence should contain episode IDs"
        );
    }
}

#[tokio::test]
#[ignore = "slow integration test - run with --ignored or in release CI"]
async fn test_heuristic_storage_in_learning_cycle() {
    // Given: A memory system with storage backends
    let memory = setup_test_memory();

    // When: We complete an episode with decision points
    let episode_id = create_episode_with_decision_points(&memory, "api-validation", 3).await;

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

    // Then: Heuristics should be stored in the episode
    let episode = memory.get_episode(episode_id).await.unwrap();

    assert!(
        !episode.heuristics.is_empty(),
        "Episode should have heuristics stored"
    );

    // Verify data integrity: retrieve and check fields
    for heuristic_id in &episode.heuristics {
        // Try to retrieve the heuristic by context
        let context = TaskContext {
            domain: "api-validation".to_string(),
            language: Some("rust".to_string()),
            framework: Some("tokio".to_string()),
            complexity: ComplexityLevel::Moderate,
            tags: vec!["decisions".to_string()],
        };

        let heuristics = memory.retrieve_relevant_heuristics(&context, 10).await;

        // Find our heuristic
        let found = heuristics.iter().any(|h| h.heuristic_id == *heuristic_id);

        assert!(
            found,
            "Should be able to retrieve stored heuristic {heuristic_id}"
        );
    }
}

#[tokio::test]
#[ignore = "slow integration test - run with --ignored or in release CI"]
async fn test_heuristic_retrieval_by_context() {
    // Given: A memory system with heuristics in different contexts
    let memory = setup_test_memory();

    // Create episodes in different domains
    let domains = vec!["web-api", "database", "web-api"];

    for domain in &domains {
        let episode_id = create_episode_with_decision_points(&memory, domain, 3).await;

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

    // When: We retrieve heuristics for "web-api" context
    let web_api_context = ContextBuilder::new("web-api")
        .language("rust")
        .framework("tokio")
        .tag("decisions")
        .build();

    let web_api_heuristics = memory
        .retrieve_relevant_heuristics(&web_api_context, 10)
        .await;

    // Then: Should return heuristics from "web-api" domain
    assert!(
        !web_api_heuristics.is_empty(),
        "Should retrieve heuristics for web-api context"
    );

    // When: We retrieve heuristics for "database" context
    let database_context = ContextBuilder::new("database")
        .language("rust")
        .framework("tokio")
        .tag("decisions")
        .build();

    let database_heuristics = memory
        .retrieve_relevant_heuristics(&database_context, 10)
        .await;

    // Then: Should return heuristics from "database" domain
    assert!(
        !database_heuristics.is_empty(),
        "Should retrieve heuristics for database context"
    );

    // Verify ranking by confidence × relevance
    // Higher confidence heuristics should come first
    for i in 1..web_api_heuristics.len() {
        let prev = &web_api_heuristics[i - 1];
        let curr = &web_api_heuristics[i];

        // Note: ranking is by confidence × relevance, which is internal
        // We can at least verify all have valid confidence
        assert!(prev.confidence >= 0.0);
        assert!(curr.confidence >= 0.0);
    }
}

#[tokio::test]
#[allow(clippy::float_cmp)]
#[ignore = "slow integration test - run with --ignored or in release CI"]
async fn test_heuristic_confidence_updates() {
    // Given: A memory system with an initial heuristic
    let memory = setup_test_memory();

    // Create initial episode with decision points
    let episode_id = create_episode_with_decision_points(&memory, "error-handling", 3).await;

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

    // Get the extracted heuristic
    let context = ContextBuilder::new("error-handling")
        .language("rust")
        .framework("tokio")
        .tag("decisions")
        .build();

    let initial_heuristics = memory.retrieve_relevant_heuristics(&context, 1).await;

    assert!(
        !initial_heuristics.is_empty(),
        "Should have extracted initial heuristic"
    );

    let heuristic_id = initial_heuristics[0].heuristic_id;
    let initial_confidence = initial_heuristics[0].confidence;
    let initial_sample_size = initial_heuristics[0].evidence.sample_size;
    let initial_success_rate = initial_heuristics[0].evidence.success_rate;

    // When: We update with a successful outcome
    let new_episode_id = Uuid::new_v4();
    memory
        .update_heuristic_confidence(
            heuristic_id,
            new_episode_id,
            TaskOutcome::Success {
                verdict: "Applied heuristic successfully".to_string(),
                artifacts: vec![],
            },
        )
        .await
        .unwrap();

    // Then: Confidence should be updated
    let updated_heuristics = memory.retrieve_relevant_heuristics(&context, 1).await;

    let updated = updated_heuristics
        .iter()
        .find(|h| h.heuristic_id == heuristic_id)
        .expect("Should find updated heuristic");

    // Verify sample size increased
    assert_eq!(
        updated.evidence.sample_size,
        initial_sample_size + 1,
        "Sample size should increase by 1"
    );

    // Verify success rate changed (since we added a success)
    assert!(
        updated.evidence.success_rate >= initial_success_rate,
        "Success rate should increase or stay same after successful outcome"
    );

    // Verify confidence recalculated (success_rate × √sample_size)
    #[allow(clippy::cast_precision_loss)]
    let expected_confidence =
        updated.evidence.success_rate * (updated.evidence.sample_size as f32).sqrt();
    assert!(
        (updated.confidence - expected_confidence).abs() < 0.01,
        "Confidence should be recalculated correctly. Expected ~{}, got {}",
        expected_confidence,
        updated.confidence
    );

    // When: We update with a failure outcome
    let failure_episode_id = Uuid::new_v4();
    memory
        .update_heuristic_confidence(
            heuristic_id,
            failure_episode_id,
            TaskOutcome::Failure {
                reason: "Heuristic didn't work".to_string(),
                error_details: None,
            },
        )
        .await
        .unwrap();

    // Then: Confidence should decrease
    let final_heuristics = memory.retrieve_relevant_heuristics(&context, 1).await;

    let final_heuristic = final_heuristics
        .iter()
        .find(|h| h.heuristic_id == heuristic_id)
        .expect("Should find heuristic after failure update");

    // Verify sample size increased again
    assert_eq!(
        final_heuristic.evidence.sample_size,
        initial_sample_size + 2,
        "Sample size should increase by 2 after two updates"
    );

    // Verify success rate decreased (failure added)
    assert!(
        final_heuristic.evidence.success_rate < updated.evidence.success_rate,
        "Success rate should decrease after failure"
    );

    // Verify changes persisted
    assert_ne!(
        final_heuristic.confidence, initial_confidence,
        "Confidence should have changed from initial value"
    );
}

#[tokio::test]
#[ignore = "slow integration test - run with --ignored or in release CI"]
async fn test_heuristic_filtering_by_confidence() {
    // Given: A memory system configured with default thresholds
    let memory = setup_test_memory();

    // When: We create an episode with high success (should extract)
    let high_success_id = create_episode_with_decision_points(&memory, "high-confidence", 4).await;

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

    // When: We create an episode with partial success (may not extract due to threshold)
    let context = ContextBuilder::new("low-confidence")
        .language("rust")
        .complexity(ComplexityLevel::Simple)
        .build();

    let partial_id = memory
        .start_episode(
            "Partial success task".to_string(),
            context.clone(),
            TaskType::CodeGeneration,
        )
        .await;

    // Add only 1 decision point (below min_sample_size of 2)
    let mut decision_step =
        ExecutionStep::new(1, "validator".to_string(), "Check if valid".to_string());
    decision_step.result = Some(ExecutionResult::Success {
        output: "Valid".to_string(),
    });
    memory.log_step(partial_id, decision_step).await;

    memory
        .complete_episode(
            partial_id,
            TaskOutcome::PartialSuccess {
                verdict: "Partially successful".to_string(),
                completed: vec!["part1".to_string()],
                failed: vec!["part2".to_string()],
            },
        )
        .await
        .unwrap();

    // Then: High confidence heuristics should be extracted
    let high_context = ContextBuilder::new("high-confidence")
        .language("rust")
        .framework("tokio")
        .tag("decisions")
        .build();

    let high_heuristics = memory.retrieve_relevant_heuristics(&high_context, 10).await;

    // Should have extracted heuristics from successful episode with sufficient samples
    assert!(
        !high_heuristics.is_empty(),
        "Should extract heuristics from high-confidence episode"
    );

    // All extracted heuristics should meet confidence threshold (default 0.7)
    for heuristic in &high_heuristics {
        assert!(
            heuristic.confidence >= 0.7,
            "Extracted heuristic should meet minimum confidence threshold of 0.7, got {}",
            heuristic.confidence
        );
    }

    // Low confidence heuristics should be filtered out
    let low_episode = memory.get_episode(partial_id).await.unwrap();
    // Should have no heuristics due to low sample size and/or confidence
    // (1 decision point < min_sample_size of 2)
    assert!(
        low_episode.heuristics.is_empty(),
        "Low confidence episode should not have extracted heuristics"
    );
}

#[tokio::test]
#[ignore = "slow integration test - run with --ignored or in release CI"]
async fn test_end_to_end_heuristic_learning() {
    // Given: A memory system
    let memory = setup_test_memory();

    // When: We create multiple episodes with similar decision points
    for i in 0..3 {
        let episode_id = create_episode_with_decision_points(&memory, "authentication", 3).await;

        memory
            .complete_episode(
                episode_id,
                TaskOutcome::Success {
                    verdict: format!("Authentication flow {i} completed"),
                    artifacts: vec![],
                },
            )
            .await
            .unwrap();
    }

    // Then: Heuristics should be extracted and grouped
    let auth_context = ContextBuilder::new("authentication")
        .language("rust")
        .framework("tokio")
        .tag("decisions")
        .build();

    let learned_heuristics = memory.retrieve_relevant_heuristics(&auth_context, 10).await;

    assert!(
        !learned_heuristics.is_empty(),
        "Should have learned heuristics from multiple episodes"
    );

    // Verify heuristics have multiple episodes as evidence
    for heuristic in &learned_heuristics {
        assert!(
            heuristic.evidence.sample_size >= 2,
            "Heuristics should be based on multiple samples, got {}",
            heuristic.evidence.sample_size
        );

        // High success rate since all episodes succeeded
        assert!(
            heuristic.evidence.success_rate >= 0.9,
            "Success rate should be high for successful episodes, got {}",
            heuristic.evidence.success_rate
        );
    }

    // When: We retrieve heuristics for a new similar task
    let new_task_context = ContextBuilder::new("authentication")
        .language("rust")
        .framework("tokio")
        .tag("security")
        .build();

    let relevant = memory
        .retrieve_relevant_heuristics(&new_task_context, 5)
        .await;

    // Then: Learned heuristics should guide the new task
    assert!(
        !relevant.is_empty(),
        "Should retrieve relevant learned heuristics for similar task"
    );

    // Verify the heuristics are actually relevant
    for heuristic in &relevant {
        // Should have meaningful condition and action
        assert!(heuristic.condition.len() > 10);
        assert!(heuristic.action.len() > 10);

        // Should have reasonable confidence
        assert!(heuristic.confidence > 0.0);
    }

    // Verify we can access the heuristics' conditions and actions
    let first_heuristic = &relevant[0];
    assert!(
        first_heuristic.condition.contains("authentication")
            || first_heuristic.condition.contains("rust")
            || first_heuristic.condition.contains("Check")
            || first_heuristic.condition.contains("Validate"),
        "Heuristic condition should be contextually relevant: {}",
        first_heuristic.condition
    );
}

#[tokio::test]
async fn test_no_heuristic_extraction_from_incomplete_episode() {
    // Given: A memory system
    let memory = setup_test_memory();

    // When: We create an episode with decision points but don't complete it
    let context = ContextBuilder::new("incomplete-test")
        .language("rust")
        .build();

    let episode_id = memory
        .start_episode(
            "Incomplete task".to_string(),
            context.clone(),
            TaskType::CodeGeneration,
        )
        .await;

    // Add decision steps
    for i in 0..3 {
        let mut step =
            ExecutionStep::new(i + 1, "validator".to_string(), "Check validity".to_string());
        step.result = Some(ExecutionResult::Success {
            output: "Valid".to_string(),
        });
        memory.log_step(episode_id, step).await;
    }

    // Don't complete the episode!

    // Then: Episode should have no heuristics
    let episode = memory.get_episode(episode_id).await.unwrap();
    assert!(
        episode.heuristics.is_empty(),
        "Incomplete episode should have no heuristics"
    );
    assert!(!episode.is_complete());
}

#[tokio::test]
#[ignore = "slow integration test - run with --ignored or in release CI"]
async fn test_no_heuristic_extraction_from_failed_episode() {
    // Given: A memory system
    let memory = setup_test_memory();

    // When: We create an episode that fails
    let episode_id = create_episode_with_decision_points(&memory, "failed-task", 3).await;

    memory
        .complete_episode(
            episode_id,
            TaskOutcome::Failure {
                reason: "Task failed completely".to_string(),
                error_details: Some("Critical error".to_string()),
            },
        )
        .await
        .unwrap();

    // Then: Should not extract heuristics from failed episodes
    let episode = memory.get_episode(episode_id).await.unwrap();

    assert!(
        episode.heuristics.is_empty(),
        "Failed episode should not have extracted heuristics"
    );

    // Verify retrieval doesn't return heuristics from failed episode
    let context = ContextBuilder::new("failed-task")
        .language("rust")
        .framework("tokio")
        .build();

    let heuristics = memory.retrieve_relevant_heuristics(&context, 10).await;

    // Should be empty since the only episode failed
    assert!(
        heuristics.is_empty(),
        "Should not retrieve heuristics from failed episodes"
    );
}

#[tokio::test]
#[ignore = "slow integration test - run with --ignored or in release CI"]
async fn test_heuristic_edge_cases() {
    // Given: A memory system
    let memory = setup_test_memory();

    // Edge case 1: Episode with no decision points
    let context = ContextBuilder::new("no-decisions").language("rust").build();

    let no_decision_id = memory
        .start_episode(
            "Task without decisions".to_string(),
            context.clone(),
            TaskType::CodeGeneration,
        )
        .await;

    // Add regular steps (no decision keywords)
    let mut step = ExecutionStep::new(1, "reader".to_string(), "Read file".to_string());
    step.result = Some(ExecutionResult::Success {
        output: "Read".to_string(),
    });
    memory.log_step(no_decision_id, step).await;

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

    // Then: No heuristics should be extracted
    let episode = memory.get_episode(no_decision_id).await.unwrap();
    assert!(
        episode.heuristics.is_empty(),
        "Episode without decision points should have no heuristics"
    );

    // Edge case 2: Episode with all failed decision steps
    let all_failed_id = memory
        .start_episode(
            "All failures".to_string(),
            context.clone(),
            TaskType::CodeGeneration,
        )
        .await;

    for i in 0..3 {
        let mut step =
            ExecutionStep::new(i + 1, "validator".to_string(), "Check if valid".to_string());
        step.result = Some(ExecutionResult::Error {
            message: "Validation failed".to_string(),
        });
        memory.log_step(all_failed_id, step).await;
    }

    memory
        .complete_episode(
            all_failed_id,
            TaskOutcome::Failure {
                reason: "All validations failed".to_string(),
                error_details: None,
            },
        )
        .await
        .unwrap();

    // Then: No heuristics from failed episode
    let failed_episode = memory.get_episode(all_failed_id).await.unwrap();
    assert!(
        failed_episode.heuristics.is_empty(),
        "Episode with all failed steps should have no heuristics"
    );
}