#![cfg(feature = "architecture_tests")]
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>> {
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()
);
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>> {
let cargo_toml = tokio::fs::read_to_string("Cargo.toml").await?;
if cargo_toml.contains("[features]") {
assert!(
cargo_toml.contains("architecture_tests = []"),
"Features section should only contain architecture_tests feature"
);
}
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?;
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?;
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
);
}
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>>
{
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()]),
);
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;
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);
let start = std::time::Instant::now();
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();
let retrieve_start = std::time::Instant::now();
let retrieved = storage.get(id).await?;
let retrieval_duration = retrieve_start.elapsed();
assert!(
storage_duration.as_millis() < 50, "Storage operation took {}ms, exceeds documented 10ms target by significant margin",
storage_duration.as_millis()
);
assert!(
retrieval_duration.as_millis() < 25, "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>> {
let config = Config::from_env()?;
let pool = codex_memory::database::create_pool(&config.database_url).await?;
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()
);
pool.close().await;
Ok(())
}
#[tokio::test]
async fn test_file_chunking_matches_documented_defaults() -> Result<(), Box<dyn std::error::Error>>
{
let mut manager = TestDatabaseManager::new()?;
let pool = manager.setup_test_database().await?;
let storage = Storage::new(pool);
let large_content = "x".repeat(10000); let temp_file = std::env::temp_dir().join("test_chunking.txt");
tokio::fs::write(&temp_file, &large_content).await?;
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, "overlap": 200, "tags": ["test"]
});
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>> {
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"
);
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>> {
let mut manager = TestDatabaseManager::new()?;
let pool = manager.setup_test_database().await?;
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
);
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
);
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);
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?;
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"
);
let stats = storage.stats().await?;
assert!(stats.total_memories > 0, "Stats should show stored memory");
let deleted = storage.delete(id).await?;
assert!(
deleted,
"Delete operation should return true for existing memory"
);
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);
let content = "duplicate content test";
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?;
assert_eq!(
id1, id2,
"ARCHITECTURE.md documents content deduplication, but different IDs returned: {} vs {}",
id1, id2
);
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>> {
let mut manager = TestDatabaseManager::new()?;
let pool = manager.setup_test_database().await?;
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?;
let custom_vector_functions: Vec<_> = vector_functions
.iter()
.filter(|row: &&sqlx::postgres::PgRow| {
let name: String = row.get("proname");
!name.starts_with("vector_") })
.collect();
assert!(
custom_vector_functions.is_empty(),
"ARCHITECTURE.md states no vector search, but custom vector functions found: {:?}",
custom_vector_functions
);
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>> {
let config = Config::from_env()?;
let mut manager = TestDatabaseManager::new()?;
let pool = manager.setup_test_database().await?;
let storage = Arc::new(Storage::new(pool));
let _server = MCPServer::new(config, storage);
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?;
let documented_indexes = vec![
"idx_content_hash", "idx_created_at", "idx_tags", "idx_parent_id", "idx_parent_chunk", "idx_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>> {
let mut manager = TestDatabaseManager::new()?;
let pool = manager.setup_test_database().await?;
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
);
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>> {
let mut manager = TestDatabaseManager::new()?;
let pool = manager.setup_test_database().await?;
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"
);
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"
);
let functions = sqlx::query(
"SELECT proname FROM pg_proc WHERE pronamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public')"
)
.fetch_all(&pool)
.await?;
let custom_functions: Vec<_> = functions
.iter()
.filter(|row| {
let name: &str = row.try_get("proname").unwrap_or("");
!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(())
}