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
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
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
//! BDD-style performance tests for non-functional requirements NFR1-NFR5
//!
//! Tests verify that the memory system meets performance, scalability,
//! and reliability targets from plans/04-review.md.
//!
//! ## Test Coverage
//! - NFR1: Retrieval latency (<100ms P95) with 100-10K episodes
//! - NFR2: Storage capacity (1K-10K episodes without degradation)
//! - NFR3: Pattern recognition accuracy (>70%)
//! - NFR4: Test coverage (>90%)
//! - NFR5: Memory leak prevention under continuous operation
//! - Concurrent performance (episode creation, completion, retrieval)
//! - Step logging and completion performance
//!
//! All tests follow the Given-When-Then pattern for clarity.

use do_memory_core::memory::SelfLearningMemory;
use do_memory_core::{
    ComplexityLevel, ExecutionResult, ExecutionStep, MemoryConfig, TaskContext, TaskOutcome,
    TaskType,
};
use std::sync::Arc;
use std::time::{Duration, Instant};

// ============================================================================
// Test Utilities
// ============================================================================

/// Create a test memory instance with zero quality threshold
fn setup_test_memory() -> SelfLearningMemory {
    let config = MemoryConfig {
        quality_threshold: 0.0, // Zero threshold for test episodes
        ..Default::default()
    };
    SelfLearningMemory::with_config(config)
}

/// Create memory with custom config
fn setup_memory_with_config(config: MemoryConfig) -> SelfLearningMemory {
    SelfLearningMemory::with_config(config)
}

/// Setup memory pre-populated with N episodes
async fn setup_memory_with_n_episodes(n: usize) -> SelfLearningMemory {
    let memory = setup_test_memory();

    for i in 0..n {
        let context = TaskContext {
            language: Some("rust".to_string()),
            domain: format!("domain_{}", i % 10),
            complexity: match i % 3 {
                0 => ComplexityLevel::Simple,
                1 => ComplexityLevel::Moderate,
                _ => ComplexityLevel::Complex,
            },
            tags: vec![format!("tag_{}", i % 5)],
            ..Default::default()
        };

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

        // Add 3-5 steps per episode
        let step_count = 3 + (i % 3);
        for j in 0..step_count {
            let mut step = ExecutionStep::new(j + 1, format!("tool_{j}"), format!("Action {j}"));
            step.latency_ms = 10 + (j as u64 * 5);
            step.tokens_used = Some(50 + (j * 10));
            step.result = Some(ExecutionResult::Success {
                output: format!("Step {j} done"),
            });
            memory.log_step(episode_id, step).await;
        }

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

    memory
}

/// Standard test context
fn test_context() -> TaskContext {
    TaskContext {
        language: Some("rust".to_string()),
        framework: Some("tokio".to_string()),
        complexity: ComplexityLevel::Moderate,
        domain: "testing".to_string(),
        tags: vec!["performance".to_string()],
    }
}

/// Create a test step
fn create_test_step(step_number: usize) -> ExecutionStep {
    let mut step = ExecutionStep::new(
        step_number,
        format!("tool_{step_number}"),
        format!("Action {step_number}"),
    );
    step.latency_ms = 10;
    step.tokens_used = Some(50);
    step.result = Some(ExecutionResult::Success {
        output: "Done".to_string(),
    });
    step
}

/// Get current process memory usage in bytes
#[cfg(target_os = "linux")]
fn get_current_memory_usage() -> usize {
    use std::fs;

    let status = fs::read_to_string("/proc/self/status").unwrap_or_default();
    for line in status.lines() {
        if line.starts_with("VmRSS:") {
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() >= 2 {
                if let Ok(kb) = parts[1].parse::<usize>() {
                    return kb * 1024; // Convert to bytes
                }
            }
        }
    }
    0
}

#[cfg(not(target_os = "linux"))]
fn get_current_memory_usage() -> usize {
    // Fallback for non-Linux systems
    // Use a rough estimate based on allocated memory
    0
}

// ============================================================================
// NFR1: Retrieval Latency
// ============================================================================

#[tokio::test]
async fn should_retrieve_episodes_under_100ms_p95_with_100_episodes() {
    // Given: Memory system with 100 episodes
    let memory = setup_memory_with_n_episodes(100).await;
    let mut latencies = Vec::new();

    // When: Running 100 retrieval queries across different domains
    for i in 0..100 {
        let context = TaskContext {
            domain: format!("domain_{}", i % 10),
            ..Default::default()
        };

        let start = Instant::now();
        let _ = memory
            .retrieve_relevant_context(format!("test query {i}"), context.clone(), 10)
            .await;
        latencies.push(start.elapsed());
    }

    // Then: P95 latency should be under 100ms (NFR1)
    latencies.sort();
    // Clippy: Cast is safe for percentile index calculation in test context
    #[allow(clippy::cast_possible_truncation)]
    #[allow(clippy::cast_precision_loss)]
    #[allow(clippy::cast_sign_loss)]
    let p95_index = ((latencies.len() as f32 * 0.95) as usize).min(latencies.len() - 1);
    let p95 = latencies[p95_index];

    println!("P95 latency with 100 episodes: {p95:?}");

    assert!(
        p95.as_millis() < 100,
        "P95 retrieval latency {}ms exceeds 100ms target",
        p95.as_millis()
    );
}

#[tokio::test]
#[ignore = "Long-running test - run with --include-ignored for full validation"]
async fn should_retrieve_episodes_under_100ms_p95_with_10k_episodes() {
    // Given: Memory system with 10K episodes
    let memory = setup_memory_with_n_episodes(10000).await;
    let mut latencies = Vec::new();

    // When: Running 100 retrieval queries across different domains
    for i in 0..100 {
        let context = TaskContext {
            domain: format!("domain_{}", i % 10),
            ..Default::default()
        };

        let start = Instant::now();
        let _ = memory
            .retrieve_relevant_context(format!("test query {i}"), context.clone(), 10)
            .await;
        latencies.push(start.elapsed());
    }

    // Then: P95 latency should remain under 100ms even with large dataset (NFR1)
    latencies.sort();
    // Clippy: Cast is safe for percentile index calculation in test context
    #[allow(clippy::cast_possible_truncation)]
    #[allow(clippy::cast_precision_loss)]
    #[allow(clippy::cast_sign_loss)]
    let p95_index = ((latencies.len() as f32 * 0.95) as usize).min(latencies.len() - 1);
    let p95 = latencies[p95_index];

    println!("P95 latency with 10K episodes: {p95:?}");

    assert!(
        p95.as_millis() < 100,
        "P95 retrieval latency {}ms exceeds 100ms target with 10K episodes",
        p95.as_millis()
    );
}

#[tokio::test]
async fn should_maintain_consistent_retrieval_latency_across_percentiles() {
    // Given: Memory system with 500 episodes
    let memory = setup_memory_with_n_episodes(500).await;
    let mut latencies = Vec::new();

    // When: Running 100 retrieval queries
    for _ in 0..100 {
        let start = Instant::now();
        memory
            .retrieve_relevant_context("query".to_string(), test_context(), 10)
            .await;
        latencies.push(start.elapsed());
    }

    // Then: All percentiles should show acceptable performance
    latencies.sort();
    let p50 = latencies[50];
    let p90 = latencies[90];
    let p95 = latencies[95];
    let p99 = latencies[99];

    println!("Retrieval latency percentiles:");
    println!("  P50: {p50:?}");
    println!("  P90: {p90:?}");
    println!("  P95: {p95:?}");
    println!("  P99: {p99:?}");

    assert!(p95.as_millis() < 100, "P95 should be under 100ms");
}

// ============================================================================
// NFR2: Storage Capacity
// ============================================================================

#[tokio::test]
async fn should_store_1000_episodes_without_performance_degradation() {
    // Given: Memory system
    let memory = setup_test_memory();
    let start = Instant::now();

    // When: Storing 1,000 episodes (NFR2 capacity target)
    for i in 0..1000 {
        let episode_id = memory
            .start_episode(
                format!("Task {i}"),
                test_context(),
                TaskType::CodeGeneration,
            )
            .await;

        let step = create_test_step(1);
        memory.log_step(episode_id, step).await;

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

    let storage_time = start.elapsed();
    println!("Stored 1K episodes in {storage_time:?}");

    // Then: Retrieval should remain fast despite large dataset
    let retrieval_start = Instant::now();
    let results = memory
        .retrieve_relevant_context("test".to_string(), test_context(), 10)
        .await;
    let retrieval_time = retrieval_start.elapsed();

    assert!(!results.is_empty());
    assert!(
        retrieval_time.as_millis() < 100,
        "Retrieval degraded to {}ms with 1K episodes",
        retrieval_time.as_millis()
    );
}

#[tokio::test]
#[ignore = "Long-running test - run with --include-ignored for full validation"]
async fn should_store_10000_episodes_without_performance_degradation() {
    // Given: Memory system
    let memory = setup_test_memory();
    let start = Instant::now();

    // When: Storing 10,000 episodes (NFR2 extended capacity test)
    for i in 0..10000 {
        if i % 1000 == 0 {
            println!("Progress: {i}/10000 episodes");
        }

        let episode_id = memory
            .start_episode(
                format!("Task {i}"),
                test_context(),
                TaskType::CodeGeneration,
            )
            .await;

        let step = create_test_step(1);
        memory.log_step(episode_id, step).await;

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

    let storage_time = start.elapsed();
    println!("Stored 10K episodes in {storage_time:?}");

    // Then: Retrieval should remain fast even with very large dataset
    let retrieval_start = Instant::now();
    let results = memory
        .retrieve_relevant_context("test".to_string(), test_context(), 10)
        .await;
    let retrieval_time = retrieval_start.elapsed();

    assert!(!results.is_empty());
    assert!(
        retrieval_time.as_millis() < 100,
        "Retrieval degraded to {}ms with 10K episodes",
        retrieval_time.as_millis()
    );
}

#[tokio::test]
async fn should_create_episodes_very_quickly() {
    // Given: Memory system
    let memory = setup_test_memory();
    let mut creation_times = Vec::new();

    // When: Creating 100 episodes
    for i in 0..100 {
        let start = Instant::now();
        memory
            .start_episode(
                format!("Task {i}"),
                test_context(),
                TaskType::CodeGeneration,
            )
            .await;
        creation_times.push(start.elapsed());
    }

    // Then: Average creation time should be very fast (<10ms)
    let avg_time: Duration =
        creation_times.iter().sum::<Duration>() / u32::try_from(creation_times.len()).unwrap_or(1);

    println!("Average episode creation time: {avg_time:?}");

    assert!(
        avg_time.as_millis() < 10,
        "Average creation time {}ms too slow",
        avg_time.as_millis()
    );
}

// ============================================================================
// NFR3: Pattern Accuracy (Placeholder)
// ============================================================================

#[tokio::test]
#[ignore = "Requires pattern accuracy measurement infrastructure"]
async fn should_achieve_70_percent_pattern_recognition_accuracy() {
    // NFR3: >70% pattern recognition accuracy
    // This test would:
    // Given: Episodes with known patterns
    // When: Extracting patterns automatically
    // Then: Accuracy should exceed 70%
    // 1. Create episodes with known patterns
    // 2. Extract patterns
    // 3. Compare against expected patterns
    // 4. Calculate accuracy percentage
}

// ============================================================================
// NFR4: Test Coverage (CI Validation)
// ============================================================================

#[tokio::test]
async fn should_maintain_90_percent_test_coverage() {
    // NFR4: 90%+ test coverage
    // Given: CI configuration with coverage reporting enabled
    // When: Running tests with coverage analysis
    // Then: Coverage should exceed 90%
    // This is validated by CI with cargo-llvm-cov
    // This test verifies CI configuration exists

    #[cfg(not(target_os = "windows"))]
    {
        let ci_workflow_path = std::env::current_dir()
            .unwrap()
            .parent()
            .unwrap()
            .join(".github/workflows/ci-enhanced.yml");

        if ci_workflow_path.exists() {
            let ci_workflow = std::fs::read_to_string(&ci_workflow_path).unwrap();

            assert!(
                ci_workflow.contains("cargo-llvm-cov") || ci_workflow.contains("coverage"),
                "CI workflow should include coverage reporting"
            );
        } else {
            println!("CI workflow not found at {ci_workflow_path:?}");
        }
    }
}

// ============================================================================
// NFR5: Memory Leaks
// ============================================================================

#[tokio::test]
async fn should_not_leak_memory_under_continuous_operation() {
    // Given: Memory system with initial memory baseline
    let memory = Arc::new(setup_test_memory());
    let initial_memory = get_current_memory_usage();
    println!("Initial memory: {initial_memory} bytes");

    // When: Running 100 episode creation/completion cycles
    for i in 0..100 {
        let mem = memory.clone();
        let episode_id = mem
            .start_episode(format!("Task {i}"), test_context(), TaskType::Testing)
            .await;

        for j in 0..5 {
            mem.log_step(episode_id, create_test_step(j + 1)).await;
        }

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

    // Then: Memory growth should be minimal (NFR5: no leaks)
    let final_memory = get_current_memory_usage();
    println!("Final memory: {final_memory} bytes");

    if initial_memory > 0 {
        #[allow(clippy::cast_precision_loss)]
        let growth = (final_memory as f32 - initial_memory as f32) / initial_memory as f32;
        println!("Memory growth: {:.2}%", growth * 100.0);

        // Allow some growth for caching, but flag excessive growth
        // Note: 100 episodes with 5 steps each will legitimately increase memory usage
        assert!(
            growth < 2.0, // 200% growth max to account for test data accumulation
            "Memory grew by {:.2}% - possible leak",
            growth * 100.0
        );
    }
}

#[tokio::test]
async fn should_not_leak_memory_over_iterations() {
    // Given: Memory system with initial memory baseline
    let memory = Arc::new(setup_test_memory());
    let initial_memory = get_current_memory_usage();

    // When: Running 100 episode creation/completion cycles (reduced from 1000 for CI)
    for i in 0..100 {
        let mem = memory.clone();
        let episode_id = mem
            .start_episode(format!("Task {i}"), test_context(), TaskType::Testing)
            .await;

        for j in 0..5 {
            mem.log_step(episode_id, create_test_step(j + 1)).await;
        }

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

        // Then: Check memory every 25 iterations to detect leaks early
        if i % 25 == 0 && i > 0 && initial_memory > 0 {
            let current_memory = get_current_memory_usage();
            #[allow(clippy::cast_precision_loss)]
            let growth = (current_memory as f32 - initial_memory as f32) / initial_memory as f32;

            println!("Iteration {}: Memory growth {:.2}%", i, growth * 100.0);

            assert!(
                growth < 1.0, // Allow 100% growth for 100 iterations (reasonable for test data)
                "Memory grew by {:.2}% after {} iterations - possible leak",
                growth * 100.0,
                i
            );
        }

        // Explicit cleanup of Arc references between iterations
        drop(mem);
    }

    println!("Memory leak test completed successfully over 100 iterations");
}

#[tokio::test]
#[ignore = "slow integration test - run with --ignored or in release CI"]
async fn should_cleanup_cache_when_exceeding_limits() {
    // Given: Memory system with limited cache (100 episodes max)
    let config = MemoryConfig {
        storage: do_memory_core::StorageConfig {
            max_episodes_cache: 100,
            ..Default::default()
        },
        quality_threshold: 0.0, // Zero threshold for test episodes
        ..Default::default()
    };
    let memory = setup_memory_with_config(config);

    // When: Creating 200 episodes (exceeding cache limit)
    for i in 0..200 {
        let episode_id = memory
            .start_episode(format!("Task {i}"), test_context(), TaskType::Testing)
            .await;

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

    // Then: System should function correctly without memory leaks
    let (total, completed, _) = memory.get_stats().await;
    assert_eq!(total, 200);
    assert_eq!(completed, 200);
}

// ============================================================================
// Concurrent Performance Tests
// ============================================================================

#[tokio::test]
async fn should_create_episodes_concurrently_without_conflicts() {
    // Given: Shared memory system
    let memory = Arc::new(setup_test_memory());
    let start = Instant::now();

    // When: Creating 100 episodes concurrently from multiple tasks
    let mut handles = vec![];
    for i in 0..100 {
        let mem = memory.clone();
        let handle = tokio::spawn(async move {
            mem.start_episode(
                format!("Task {i}"),
                test_context(),
                TaskType::CodeGeneration,
            )
            .await
        });
        handles.push(handle);
    }

    let mut ids = vec![];
    for handle in handles {
        ids.push(handle.await.unwrap());
    }

    let elapsed = start.elapsed();

    println!(
        "Created 100 episodes concurrently in {:?} ({:.2} eps/sec)",
        elapsed,
        100.0 / elapsed.as_secs_f32()
    );

    // Then: All episodes should be created successfully
    assert_eq!(ids.len(), 100);

    // Then: Concurrent execution should be fast (<1 second)
    assert!(
        elapsed.as_secs() < 1,
        "Concurrent creation took {}ms",
        elapsed.as_millis()
    );
}

#[tokio::test]
#[ignore = "slow integration test - run with --ignored or in release CI"]
async fn should_complete_episodes_concurrently_without_conflicts() {
    // Given: Shared memory system with 50 episodes
    let memory = Arc::new(setup_test_memory());
    let mut episode_ids = vec![];

    for i in 0..50 {
        let id = memory
            .start_episode(
                format!("Task {i}"),
                test_context(),
                TaskType::CodeGeneration,
            )
            .await;
        episode_ids.push(id);
    }

    let start = Instant::now();

    // When: Completing all episodes concurrently from multiple tasks
    let mut handles = vec![];
    for episode_id in episode_ids {
        let mem = memory.clone();
        let handle = tokio::spawn(async move {
            mem.complete_episode(
                episode_id,
                TaskOutcome::Success {
                    verdict: "Done".to_string(),
                    artifacts: vec![],
                },
            )
            .await
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.await.unwrap().unwrap();
    }

    let elapsed = start.elapsed();

    println!("Completed 50 episodes concurrently in {elapsed:?}");

    // Then: All episodes should be completed successfully
    let (_, completed, _) = memory.get_stats().await;
    assert_eq!(completed, 50);
}

#[tokio::test]
#[ignore = "slow integration test - run with --ignored or in release CI"]
async fn should_handle_concurrent_retrievals_efficiently() {
    // Given: Memory system with 100 episodes
    let memory = Arc::new(setup_memory_with_n_episodes(100).await);
    let start = Instant::now();

    // When: Running 50 concurrent retrieval queries
    let mut handles = vec![];
    for i in 0..50 {
        let mem = memory.clone();
        let handle = tokio::spawn(async move {
            mem.retrieve_relevant_context(format!("query {i}"), test_context(), 10)
                .await
        });
        handles.push(handle);
    }

    // Then: All retrievals should complete successfully
    for handle in handles {
        let results = handle.await.unwrap();
        assert!(results.len() <= 10);
    }

    let elapsed = start.elapsed();

    println!("Executed 50 concurrent retrievals in {elapsed:?}");

    // Then: Concurrent retrievals should be fast (<500ms)
    assert!(
        elapsed.as_millis() < 500,
        "Concurrent retrievals took {}ms",
        elapsed.as_millis()
    );
}

// ============================================================================
// Step Logging Performance
// ============================================================================

#[tokio::test]
async fn should_log_steps_very_quickly() {
    // Given: Memory system with an active episode
    let memory = setup_test_memory();
    let episode_id = memory
        .start_episode("Test".to_string(), test_context(), TaskType::Testing)
        .await;

    let mut step_times = vec![];

    // When: Logging 100 execution steps
    for i in 1..=100 {
        let step = create_test_step(i);
        let start = Instant::now();
        memory.log_step(episode_id, step).await;
        step_times.push(start.elapsed());
    }

    // Then: Average step logging should be very fast (<5ms)
    // Cast is safe for small test sizes (100 items)
    // Fixed: use try_into() for safe usize to u32 conversion
    let count: u32 = step_times.len().try_into().expect("Test size fits in u32");
    let avg_time: Duration = step_times.iter().sum::<Duration>() / count;

    println!("Average step logging time: {avg_time:?}");

    assert!(
        avg_time.as_millis() < 5,
        "Step logging too slow: {}ms",
        avg_time.as_millis()
    );
}

#[tokio::test]
#[ignore = "slow integration test - run with --ignored or in release CI"]
async fn should_complete_episodes_quickly_with_pattern_extraction() {
    // Given: Memory system
    let memory = setup_test_memory();
    let mut completion_times = vec![];

    // When: Creating and completing 50 episodes with steps
    for i in 0..50 {
        let episode_id = memory
            .start_episode(
                format!("Task {i}"),
                test_context(),
                TaskType::CodeGeneration,
            )
            .await;

        // Add a few steps
        for j in 1..=3 {
            memory.log_step(episode_id, create_test_step(j)).await;
        }

        let start = Instant::now();
        memory
            .complete_episode(
                episode_id,
                TaskOutcome::Success {
                    verdict: "Done".to_string(),
                    artifacts: vec![],
                },
            )
            .await
            .unwrap();
        completion_times.push(start.elapsed());
    }

    // Then: Average completion time should be fast (<100ms including pattern extraction)
    let avg_time: Duration = completion_times.iter().sum::<Duration>()
        / u32::try_from(completion_times.len()).unwrap_or(1);

    println!("Average episode completion time: {avg_time:?}");

    assert!(
        avg_time.as_millis() < 100,
        "Episode completion too slow: {}ms",
        avg_time.as_millis()
    );
}