codex-memory 3.0.15

A simple memory storage service with MCP interface for Claude Desktop
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
//! Comprehensive search functionality tests
//! 
//! Tests all aspects of the search system including:
//! - Basic text search
//! - Tag filtering 
//! - Vector similarity search
//! - Progressive search strategy
//! - Performance requirements

use codex_memory::{
    error::Result,
    models::{SearchParams, SearchStrategy},
    storage::Storage,
};
use tests::common::test_db_manager::TestDatabaseManager;
use uuid::Uuid;

#[tokio::test]
async fn test_basic_text_search() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Storage::new(pool);

    // Store test memories
    let id1 = storage
        .store(
            "Database performance optimization techniques",
            "Technical documentation".to_string(),
            "Guide for optimizing database queries".to_string(),
            Some(vec!["database".to_string(), "performance".to_string()]),
        )
        .await?;

    let id2 = storage
        .store(
            "JavaScript performance tips",
            "Programming guide".to_string(),
            "Best practices for JavaScript optimization".to_string(),
            Some(vec!["javascript".to_string(), "performance".to_string()]),
        )
        .await?;

    // Test search with query
    let search_params = SearchParams {
        query: "database optimization".to_string(),
        similarity_threshold: 0.1, // Low threshold for fallback search
        max_results: 10,
        ..Default::default()
    };

    let results = storage.search_memories(search_params).await?;

    // Should find at least the database-related memory
    assert!(!results.is_empty(), "Search should return results");
    
    // Database memory should be ranked higher than JavaScript memory
    let database_result = results.iter().find(|r| r.memory.id == id1);
    let javascript_result = results.iter().find(|r| r.memory.id == id2);

    assert!(database_result.is_some(), "Should find database memory");
    
    // If JavaScript memory is found, database should rank higher
    if let (Some(db), Some(js)) = (database_result, javascript_result) {
        assert!(db.combined_score >= js.combined_score, 
                "Database memory should rank higher than JavaScript for 'database optimization' query");
    }

    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
async fn test_tag_filtering() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Storage::new(pool);

    // Store memories with different tags
    let _id1 = storage
        .store(
            "Content about databases",
            "Database content".to_string(),
            "Information about databases".to_string(),
            Some(vec!["database".to_string(), "sql".to_string()]),
        )
        .await?;

    let _id2 = storage
        .store(
            "Content about databases",
            "Web development content".to_string(),
            "Information about web development".to_string(),
            Some(vec!["javascript".to_string(), "web".to_string()]),
        )
        .await?;

    let _id3 = storage
        .store(
            "Content about databases and performance",
            "Performance content".to_string(),
            "Database performance information".to_string(),
            Some(vec!["database".to_string(), "performance".to_string()]),
        )
        .await?;

    // Test search with tag filter
    let search_params = SearchParams {
        query: "databases".to_string(),
        tag_filter: Some(vec!["database".to_string()]),
        similarity_threshold: 0.1,
        max_results: 10,
        ..Default::default()
    };

    let results = storage.search_memories(search_params).await?;

    // Should only return memories tagged with "database"
    assert!(!results.is_empty(), "Search should return tagged results");
    
    for result in results {
        assert!(
            result.memory.tags.contains(&"database".to_string()),
            "All results should have the 'database' tag"
        );
    }

    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
async fn test_progressive_search_strategy() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Storage::new(pool);

    // Store a test memory
    let _id = storage
        .store(
            "Machine learning algorithms for pattern recognition",
            "AI research".to_string(),
            "Overview of ML algorithms".to_string(),
            Some(vec!["machine-learning".to_string(), "ai".to_string()]),
        )
        .await?;

    // Test with high threshold (should use stage 1)
    let search_params_high = SearchParams {
        query: "machine learning".to_string(),
        similarity_threshold: 0.9, // Very high threshold
        max_results: 10,
        ..Default::default()
    };

    let results_high = storage
        .search_memories_progressive_with_metadata(search_params_high)
        .await?;

    // Test with medium threshold (might use stage 2)
    let search_params_medium = SearchParams {
        query: "pattern recognition".to_string(),
        similarity_threshold: 0.7,
        max_results: 10,
        ..Default::default()
    };

    let results_medium = storage
        .search_memories_progressive_with_metadata(search_params_medium)
        .await?;

    // Progressive search should work and provide metadata
    assert!(
        results_high.metadata.stage_used >= 1 && results_high.metadata.stage_used <= 3,
        "Stage should be between 1 and 3"
    );
    
    assert!(
        results_medium.metadata.stage_used >= 1 && results_medium.metadata.stage_used <= 3,
        "Stage should be between 1 and 3"
    );

    // Metadata should be meaningful
    assert!(!results_high.metadata.stage_description.is_empty());
    assert!(!results_medium.metadata.stage_description.is_empty());

    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
async fn test_different_search_strategies() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Storage::new(pool);

    // Store test memory
    let _id = storage
        .store(
            "Database optimization techniques",
            "Technical guide".to_string(),
            "Performance tuning for databases".to_string(),
            Some(vec!["database".to_string(), "optimization".to_string()]),
        )
        .await?;

    // Test TagsFirst strategy
    let search_params_tags = SearchParams {
        query: "optimization".to_string(),
        search_strategy: SearchStrategy::TagsFirst,
        similarity_threshold: 0.1,
        max_results: 10,
        ..Default::default()
    };

    let results_tags = storage.search_memories(search_params_tags).await?;

    // Test ContentFirst strategy
    let search_params_content = SearchParams {
        query: "optimization".to_string(),
        search_strategy: SearchStrategy::ContentFirst,
        similarity_threshold: 0.1,
        max_results: 10,
        ..Default::default()
    };

    let results_content = storage.search_memories(search_params_content).await?;

    // Test Hybrid strategy
    let search_params_hybrid = SearchParams {
        query: "optimization".to_string(),
        search_strategy: SearchStrategy::Hybrid,
        similarity_threshold: 0.1,
        max_results: 10,
        ..Default::default()
    };

    let results_hybrid = storage.search_memories(search_params_hybrid).await?;

    // All strategies should return results (due to fallback)
    assert!(!results_tags.is_empty() || !results_content.is_empty() || !results_hybrid.is_empty(),
            "At least one search strategy should return results");

    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
async fn test_search_performance() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Storage::new(pool);

    // Store multiple test memories for performance testing
    for i in 0..50 {
        storage
            .store(
                &format!("Performance test content number {}", i),
                format!("Test context {}", i),
                format!("Test summary {}", i),
                Some(vec![
                    "performance".to_string(),
                    format!("test-{}", i),
                ]),
            )
            .await?;
    }

    // Test search performance
    let start = std::time::Instant::now();
    
    let search_params = SearchParams {
        query: "performance test".to_string(),
        max_results: 20,
        ..Default::default()
    };

    let results = storage.search_memories(search_params).await?;
    let duration = start.elapsed();

    // Should return results
    assert!(!results.is_empty(), "Search should return results");

    // Performance requirement from ARCHITECTURE.md: <100ms P95 for typical searches
    // Using 200ms as a reasonable limit for test environment
    assert!(
        duration.as_millis() < 200,
        "Search should complete within 200ms, took {}ms",
        duration.as_millis()
    );

    println!("Search completed in {}ms with {} results", 
             duration.as_millis(), results.len());

    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
async fn test_search_with_empty_database() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Storage::new(pool);

    // Search empty database
    let search_params = SearchParams {
        query: "nonexistent content".to_string(),
        max_results: 10,
        ..Default::default()
    };

    let results = storage.search_memories(search_params).await?;

    // Should return empty results without error
    assert!(results.is_empty(), "Empty database should return no results");

    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
async fn test_search_result_scoring() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Storage::new(pool);

    // Store memories with varying relevance
    let id1 = storage
        .store(
            "Database optimization is crucial for performance",
            "High relevance content".to_string(),
            "Database optimization techniques".to_string(),
            Some(vec!["database".to_string(), "optimization".to_string()]),
        )
        .await?;

    let id2 = storage
        .store(
            "General optimization principles",
            "Medium relevance content".to_string(),
            "General optimization guide".to_string(),
            Some(vec!["optimization".to_string()]),
        )
        .await?;

    let _id3 = storage
        .store(
            "Web development tutorials",
            "Low relevance content".to_string(),
            "Web programming guide".to_string(),
            Some(vec!["web".to_string(), "development".to_string()]),
        )
        .await?;

    let search_params = SearchParams {
        query: "database optimization".to_string(),
        similarity_threshold: 0.1,
        max_results: 10,
        ..Default::default()
    };

    let results = storage.search_memories(search_params).await?;

    assert!(!results.is_empty(), "Should return search results");

    // Results should be sorted by combined score (highest first)
    for i in 1..results.len() {
        assert!(
            results[i-1].combined_score >= results[i].combined_score,
            "Results should be sorted by score in descending order"
        );
    }

    // The most relevant memory should score highest
    let top_result = &results[0];
    assert!(
        top_result.memory.id == id1 || top_result.memory.id == id2,
        "Top result should be one of the optimization-related memories"
    );

    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
async fn test_search_with_recency_boost() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Storage::new(pool);

    // Store a test memory
    let _id = storage
        .store(
            "Recent optimization techniques",
            "Recent content".to_string(),
            "Latest optimization methods".to_string(),
            Some(vec!["optimization".to_string(), "recent".to_string()]),
        )
        .await?;

    // Test with recency boost enabled
    let search_params_with_boost = SearchParams {
        query: "optimization".to_string(),
        boost_recent: true,
        similarity_threshold: 0.1,
        max_results: 10,
        ..Default::default()
    };

    let results_with_boost = storage.search_memories(search_params_with_boost).await?;

    // Test without recency boost
    let search_params_no_boost = SearchParams {
        query: "optimization".to_string(),
        boost_recent: false,
        similarity_threshold: 0.1,
        max_results: 10,
        ..Default::default()
    };

    let results_no_boost = storage.search_memories(search_params_no_boost).await?;

    // Both should return results
    assert!(!results_with_boost.is_empty() || !results_no_boost.is_empty(),
            "At least one search configuration should return results");

    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
async fn test_search_max_results_limit() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Storage::new(pool);

    // Store more memories than we'll request
    for i in 0..20 {
        storage
            .store(
                &format!("Test content number {}", i),
                format!("Context {}", i),
                format!("Summary {}", i),
                Some(vec!["test".to_string()]),
            )
            .await?;
    }

    // Request only 5 results
    let search_params = SearchParams {
        query: "test".to_string(),
        max_results: 5,
        similarity_threshold: 0.1,
        ..Default::default()
    };

    let results = storage.search_memories(search_params).await?;

    // Should respect the limit
    assert!(
        results.len() <= 5,
        "Should return at most 5 results, got {}",
        results.len()
    );

    manager.cleanup().await?;
    Ok(())
}