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
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
//! Architecture validation tests for CODEX-ARCH-001
//!
//! These tests validate that the documented architecture in ARCHITECTURE.md
//! matches the actual implementation and ensures architectural consistency.
//!
//! NOTE: These tests are currently disabled as they validate v2.x architecture
//! but ARCHITECTURE.md has been updated to v3.0.0 specifications.

#![cfg(feature = "architecture_tests")] // Disable by default

use codex_memory::{Config, MCPServer, Storage};
use sqlx::Row;
use std::sync::Arc;

mod common;
use common::test_db_manager::TestDatabaseManager;

#[tokio::test]
async fn test_mcp_tools_match_documented_count() -> Result<(), Box<dyn std::error::Error>> {
    // ARCHITECTURE.md documents exactly 5 MCP tools
    let tools = codex_memory::mcp_server::tools::MCPTools::get_tools_list();

    let tools_array = tools.as_array().ok_or("Tools should be an array")?;

    assert_eq!(
        tools_array.len(),
        5,
        "ARCHITECTURE.md documents 5 MCP tools, found {}",
        tools_array.len()
    );

    // Validate documented tool names exist
    let documented_tools = vec![
        "store_memory",
        "get_memory",
        "delete_memory",
        "get_statistics",
        "store_file",
    ];

    for expected_tool in documented_tools {
        let tool_exists = tools_array
            .iter()
            .any(|tool| tool["name"].as_str() == Some(expected_tool));

        assert!(
            tool_exists,
            "Documented tool '{}' not found in implementation",
            expected_tool
        );
    }

    Ok(())
}

#[tokio::test]
async fn test_no_phantom_feature_flags() -> Result<(), Box<dyn std::error::Error>> {
    // ARCHITECTURE.md states: "No feature flags currently implemented"
    // Previous CLAUDE.md falsely referenced --features codex-dreams

    // Read Cargo.toml to verify no features are defined
    let cargo_toml = tokio::fs::read_to_string("Cargo.toml").await?;

    // Should only contain minimal features section as documented
    if cargo_toml.contains("[features]") {
        // Only architecture_tests feature should exist
        assert!(
            cargo_toml.contains("architecture_tests = []"),
            "Features section should only contain architecture_tests feature"
        );
    }

    // Should not contain codex-dreams references
    assert!(
        !cargo_toml.contains("codex-dreams"),
        "Found phantom 'codex-dreams' feature reference in Cargo.toml"
    );

    Ok(())
}

#[tokio::test]
async fn test_database_schema_matches_documented() -> Result<(), Box<dyn std::error::Error>> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;

    // Test that memories table structure matches ARCHITECTURE.md documentation
    let table_info = sqlx::query(
        r#"
        SELECT column_name, data_type, is_nullable
        FROM information_schema.columns 
        WHERE table_name = 'memories'
        ORDER BY ordinal_position
        "#,
    )
    .fetch_all(&pool)
    .await?;

    // Verify core columns documented in ARCHITECTURE.md exist
    let required_columns = vec![
        "id",
        "content",
        "content_hash",
        "context",
        "summary",
        "tags",
        "chunk_index",
        "total_chunks",
        "parent_id",
        "created_at",
        "updated_at",
    ];

    for required_col in required_columns {
        let column_exists = table_info.iter().any(|row: &sqlx::postgres::PgRow| {
            let col_name: String = row.get("column_name");
            col_name == required_col
        });

        assert!(
            column_exists,
            "Required column '{}' documented in ARCHITECTURE.md not found in database schema",
            required_col
        );
    }

    // Verify tier column is NOT present (removed in migration 004)
    let tier_exists = table_info.iter().any(|row: &sqlx::postgres::PgRow| {
        let col_name: String = row.get("column_name");
        col_name == "tier"
    });

    assert!(
        !tier_exists,
        "ARCHITECTURE.md documents tier system removal, but 'tier' column still exists"
    );

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

#[tokio::test]
async fn test_memory_model_matches_documented_structure() -> Result<(), Box<dyn std::error::Error>>
{
    // Test that the Memory struct has all fields documented in ARCHITECTURE.md
    use codex_memory::models::Memory;

    let memory = Memory::new(
        "test content".to_string(),
        "test context".to_string(),
        "test summary".to_string(),
        Some(vec!["test".to_string()]),
    );

    // Verify all documented fields are accessible
    let _ = memory.id;
    let _ = memory.content;
    let _ = memory.content_hash;
    let _ = memory.tags;
    let _ = memory.context;
    let _ = memory.summary;
    let _ = memory.chunk_index;
    let _ = memory.total_chunks;
    let _ = memory.parent_id;
    let _ = memory.created_at;
    let _ = memory.updated_at;

    // Verify memory has required metadata fields as documented
    assert!(
        !memory.context.is_empty(),
        "Context is required per ARCHITECTURE.md"
    );
    assert!(
        !memory.summary.is_empty(),
        "Summary is required per ARCHITECTURE.md"
    );
    assert!(
        !memory.tags.is_empty(),
        "Tags are required per ARCHITECTURE.md"
    );

    Ok(())
}

#[tokio::test]
async fn test_performance_targets_documented() -> Result<(), Box<dyn std::error::Error>> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Storage::new(pool);

    // Test documented performance targets from ARCHITECTURE.md
    let start = std::time::Instant::now();

    // Storage should be <10ms (documented target), actual ~5ms
    let id = storage
        .store(
            "performance test content",
            "Performance testing".to_string(),
            "Testing documented latency targets".to_string(),
            Some(vec!["performance".to_string()]),
        )
        .await?;

    let storage_duration = start.elapsed();

    // Retrieval should be <5ms (documented target), actual ~2ms
    let retrieve_start = std::time::Instant::now();
    let retrieved = storage.get(id).await?;
    let retrieval_duration = retrieve_start.elapsed();

    // Validate performance meets documented targets
    assert!(
        storage_duration.as_millis() < 50, // Generous 50ms limit vs 10ms target
        "Storage operation took {}ms, exceeds documented 10ms target by significant margin",
        storage_duration.as_millis()
    );

    assert!(
        retrieval_duration.as_millis() < 25, // Generous 25ms limit vs 5ms target
        "Retrieval operation took {}ms, exceeds documented 5ms target by significant margin",
        retrieval_duration.as_millis()
    );

    assert!(retrieved.is_some(), "Retrieved memory should exist");

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

#[tokio::test]
async fn test_connection_pool_configuration_matches_documented(
) -> Result<(), Box<dyn std::error::Error>> {
    // ARCHITECTURE.md documents specific connection pool configuration
    let config = Config::from_env()?;
    let pool = codex_memory::database::create_pool(&config.database_url).await?;

    // Verify documented pool configuration
    let options = pool.options();

    assert_eq!(
        options.get_max_connections(),
        50,
        "Connection pool optimized for production MCP workload (50 connections), found {}",
        options.get_max_connections()
    );

    // Note: Pool health monitoring functions have been simplified
    // Advanced monitoring features moved to codex-dreams project

    pool.close().await;
    Ok(())
}

#[tokio::test]
async fn test_file_chunking_matches_documented_defaults() -> Result<(), Box<dyn std::error::Error>>
{
    // ARCHITECTURE.md documents 8KB default chunk size, 200 char overlap
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Storage::new(pool);

    // Create test content larger than 8KB
    let large_content = "x".repeat(10000); // 10KB content
    let temp_file = std::env::temp_dir().join("test_chunking.txt");
    tokio::fs::write(&temp_file, &large_content).await?;

    // Test chunking through MCP interface (simulated)
    // In real implementation, this would go through MCP handlers
    let _config = Config::from_env()?;
    let storage_arc = Arc::new(storage);
    let _handlers = codex_memory::mcp_server::handlers::MCPHandlers::new(storage_arc);

    let _chunk_params = serde_json::json!({
        "file_path": temp_file.to_string_lossy(),
        "chunk_size": 8000,  // Documented default
        "overlap": 200,      // Documented default
        "tags": ["test"]
    });

    // Test that chunking parameters are accepted
    // Note: Full chunking test would require MCP handler implementation

    // Cleanup
    tokio::fs::remove_file(&temp_file).await.ok();
    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
async fn test_binary_name_consistency() -> Result<(), Box<dyn std::error::Error>> {
    // ARCHITECTURE.md documents binary name as "codex-memory"

    // Check Cargo.toml package name
    let cargo_toml = tokio::fs::read_to_string("Cargo.toml").await?;
    assert!(
        cargo_toml.contains("name = \"codex-memory\""),
        "Cargo.toml should specify binary name as 'codex-memory' per ARCHITECTURE.md"
    );

    // Check CLI help text consistency
    let cargo_toml_lines: Vec<&str> = cargo_toml.lines().collect();
    let package_line = cargo_toml_lines
        .iter()
        .find(|line| line.contains("name = \"codex-memory\""))
        .ok_or("Package name not found")?;

    assert!(
        package_line.contains("codex-memory"),
        "Binary name should be consistent with ARCHITECTURE.md documentation"
    );

    Ok(())
}

#[tokio::test]
async fn test_no_cognitive_features_in_implementation() -> Result<(), Box<dyn std::error::Error>> {
    // ARCHITECTURE.md explicitly states no cognitive features
    // Verify implementation matches this statement

    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;

    // Verify no tier-related tables exist
    let tier_tables = sqlx::query(
        "SELECT table_name FROM information_schema.tables WHERE table_name LIKE '%tier%'",
    )
    .fetch_all(&pool)
    .await?;

    assert!(
        tier_tables.is_empty(),
        "ARCHITECTURE.md documents no cognitive features, but tier-related tables found: {:?}",
        tier_tables
    );

    // Verify no insights-related tables exist
    let insights_tables = sqlx::query(
        "SELECT table_name FROM information_schema.tables WHERE table_name LIKE '%insight%'",
    )
    .fetch_all(&pool)
    .await?;

    assert!(
        insights_tables.is_empty(),
        "ARCHITECTURE.md documents no cognitive features, but insights-related tables found: {:?}",
        insights_tables
    );

    // Verify memory_tier enum doesn't exist (removed in migration 004)
    let tier_enum_exists = sqlx::query("SELECT 1 FROM pg_type WHERE typname = 'memory_tier'")
        .fetch_optional(&pool)
        .await?;

    assert!(
        tier_enum_exists.is_none(),
        "ARCHITECTURE.md documents tier system removal, but memory_tier enum still exists"
    );

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

#[tokio::test]
async fn test_storage_operations_match_documented_api() -> Result<(), Box<dyn std::error::Error>> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Storage::new(pool);

    // Test documented API surface from ARCHITECTURE.md

    // 1. Test store operation with required metadata
    let id = storage
        .store(
            "test content",
            "Test context per ARCHITECTURE.md requirements".to_string(),
            "Test summary per ARCHITECTURE.md requirements".to_string(),
            Some(vec!["architecture".to_string(), "test".to_string()]),
        )
        .await?;

    // 2. Test get operation
    let memory = storage.get(id).await?;
    assert!(memory.is_some(), "Stored memory should be retrievable");

    let memory = memory.unwrap();
    assert_eq!(memory.content, "test content");
    assert!(
        !memory.context.is_empty(),
        "Context is required per ARCHITECTURE.md"
    );
    assert!(
        !memory.summary.is_empty(),
        "Summary is required per ARCHITECTURE.md"
    );
    assert!(
        !memory.tags.is_empty(),
        "Tags are required per ARCHITECTURE.md"
    );

    // 3. Test stats operation
    let stats = storage.stats().await?;
    assert!(stats.total_memories > 0, "Stats should show stored memory");

    // 4. Test delete operation
    let deleted = storage.delete(id).await?;
    assert!(
        deleted,
        "Delete operation should return true for existing memory"
    );

    // 5. Test list_recent operation (documented in API surface)
    let recent = storage.list_recent(10).await?;
    assert!(
        recent.len() <= 10,
        "list_recent should respect limit parameter"
    );

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

#[tokio::test]
async fn test_content_deduplication_as_documented() -> Result<(), Box<dyn std::error::Error>> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Storage::new(pool);

    // ARCHITECTURE.md documents SHA-256 content deduplication
    let content = "duplicate content test";

    // Store same content twice
    let id1 = storage
        .store(
            content,
            "First storage".to_string(),
            "Testing deduplication".to_string(),
            Some(vec!["dedup".to_string()]),
        )
        .await?;

    let id2 = storage
        .store(
            content,
            "Second storage".to_string(),
            "Testing deduplication again".to_string(),
            Some(vec!["dedup".to_string()]),
        )
        .await?;

    // Should return same ID due to content deduplication
    assert_eq!(
        id1, id2,
        "ARCHITECTURE.md documents content deduplication, but different IDs returned: {} vs {}",
        id1, id2
    );

    // Verify only one record exists
    let stats = storage.stats().await?;
    assert_eq!(
        stats.total_memories, 1,
        "Deduplication should result in single stored record, found {}",
        stats.total_memories
    );

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

#[tokio::test]
async fn test_system_boundaries_enforced() -> Result<(), Box<dyn std::error::Error>> {
    // ARCHITECTURE.md clearly defines what the system IS NOT
    // Verify these boundaries are enforced in implementation

    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;

    // 1. No vector search capabilities (despite pgvector being available)
    let vector_functions: Vec<sqlx::postgres::PgRow> = sqlx::query(
        "SELECT proname FROM pg_proc WHERE proname LIKE '%vector%' AND pronamespace != 'pg_catalog'::regnamespace"
    )
    .fetch_all(&pool)
    .await?;

    // Should be minimal - only pgvector extension functions, no custom vector functions
    let custom_vector_functions: Vec<_> = vector_functions
        .iter()
        .filter(|row: &&sqlx::postgres::PgRow| {
            let name: String = row.get("proname");
            !name.starts_with("vector_") // pgvector extension functions
        })
        .collect();

    assert!(
        custom_vector_functions.is_empty(),
        "ARCHITECTURE.md states no vector search, but custom vector functions found: {:?}",
        custom_vector_functions
    );

    // 2. No cognitive features - verify no insights/cognitive tables
    let cognitive_tables = sqlx::query(
        "SELECT table_name FROM information_schema.tables WHERE table_name ~ '(insight|cognitive|tier|working|warm|cold|frozen)'"
    )
    .fetch_all(&pool)
    .await?;

    assert!(
        cognitive_tables.is_empty(),
        "ARCHITECTURE.md states no cognitive features, but cognitive-related tables found: {:?}",
        cognitive_tables
    );

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

#[tokio::test]
async fn test_mcp_server_initialization_matches_documented(
) -> Result<(), Box<dyn std::error::Error>> {
    // Test MCP server can be initialized as documented in ARCHITECTURE.md
    let config = Config::from_env()?;
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));

    // Should be able to create MCP server as documented
    let _server = MCPServer::new(config, storage);

    // Verify server info matches documented values
    let tools = codex_memory::mcp_server::tools::MCPTools::get_tools_list();
    assert!(
        tools.is_array(),
        "Tools should be array format for MCP protocol"
    );

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

#[tokio::test]
async fn test_documented_indexes_exist() -> Result<(), Box<dyn std::error::Error>> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;

    // ARCHITECTURE.md documents specific performance indexes
    let documented_indexes = vec![
        "idx_content_hash", // Unique index for deduplication
        "idx_created_at",   // Time-based queries
        "idx_tags",         // Tag searches (actual name)
        "idx_parent_id",    // Chunk retrieval (actual name)
        "idx_parent_chunk", // Ordered chunks (actual name)
        "idx_summary",      // Full-text search on summary
    ];

    for expected_index in documented_indexes {
        let index_exists = sqlx::query("SELECT 1 FROM pg_indexes WHERE indexname = $1")
            .bind(expected_index)
            .fetch_optional(&pool)
            .await?;

        assert!(
            index_exists.is_some(),
            "Index '{}' documented in ARCHITECTURE.md not found in database",
            expected_index
        );
    }

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

#[tokio::test]
async fn test_architectural_simplicity_validated() -> Result<(), Box<dyn std::error::Error>> {
    // ARCHITECTURE.md emphasizes deliberate simplicity
    // Validate this is reflected in implementation

    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;

    // Should have exactly 1 main table (memories)
    let table_count: i64 = sqlx::query_scalar(
        "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE'"
    )
    .fetch_one(&pool)
    .await?;

    assert_eq!(
        table_count, 1,
        "ARCHITECTURE.md emphasizes simplicity with single table design, found {} tables",
        table_count
    );

    // Verify table is named 'memories' as documented
    let table_exists: i64 = sqlx::query_scalar(
        "SELECT COUNT(*) FROM information_schema.tables WHERE table_name = 'memories'",
    )
    .fetch_one(&pool)
    .await?;

    assert_eq!(
        table_exists, 1,
        "ARCHITECTURE.md documents 'memories' table, but table not found"
    );

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

#[tokio::test]
async fn test_rollback_evidence_validation() -> Result<(), Box<dyn std::error::Error>> {
    // Validate evidence of architectural rollback documented in ARCHITECTURE.md

    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;

    // 1. Migration 004 evidence - tier system should be completely removed
    let tier_remnants = sqlx::query(
        "SELECT column_name FROM information_schema.columns WHERE table_name = 'memories' AND column_name = 'tier'"
    )
    .fetch_all(&pool)
    .await?;

    assert!(
        tier_remnants.is_empty(),
        "Migration 004 should have removed tier column completely"
    );

    // 2. Enum cleanup - memory_tier enum should not exist
    let enum_exists = sqlx::query("SELECT 1 FROM pg_type WHERE typname = 'memory_tier'")
        .fetch_optional(&pool)
        .await?;

    assert!(
        enum_exists.is_none(),
        "memory_tier enum should be completely removed per migration 004"
    );

    // 3. Only basic storage functionality should remain
    let functions = sqlx::query(
        "SELECT proname FROM pg_proc WHERE pronamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public')"
    )
    .fetch_all(&pool)
    .await?;

    // Should have minimal custom functions (allow for pgcrypto and other standard extensions)
    // Filter out common extension functions
    let custom_functions: Vec<_> = functions
        .iter()
        .filter(|row| {
            let name: &str = row.try_get("proname").unwrap_or("");
            // Exclude common pgcrypto and other extension functions
            !name.starts_with("armor")
                && !name.starts_with("crypt")
                && !name.starts_with("dearmor")
                && !name.starts_with("decrypt")
                && !name.starts_with("digest")
                && !name.starts_with("encrypt")
                && !name.starts_with("gen_")
                && !name.starts_with("hmac")
                && !name.starts_with("pgp_")
        })
        .collect();

    assert!(
        custom_functions.len() < 5,
        "Simple architecture should have minimal custom database functions, found {} custom functions (excluding extensions)",
        custom_functions.len()
    );

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