zeroclaw 0.1.7

Zero overhead. Zero compromise. 100% Rust. The fastest, smallest AI assistant.
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
//! Head-to-head comparison: SQLite vs Markdown memory backends
//!
//! Run with: cargo test --test memory_comparison -- --nocapture

use std::time::Instant;
use tempfile::TempDir;

// We test both backends through the public memory module
use zeroclaw::memory::{markdown::MarkdownMemory, sqlite::SqliteMemory, Memory, MemoryCategory};

// ── Helpers ────────────────────────────────────────────────────

fn sqlite_backend(dir: &std::path::Path) -> SqliteMemory {
    SqliteMemory::new(dir).expect("SQLite init failed")
}

fn markdown_backend(dir: &std::path::Path) -> MarkdownMemory {
    MarkdownMemory::new(dir)
}

// ── Test 1: Store performance ──────────────────────────────────

#[tokio::test]
async fn compare_store_speed() {
    let tmp_sq = TempDir::new().unwrap();
    let tmp_md = TempDir::new().unwrap();
    let sq = sqlite_backend(tmp_sq.path());
    let md = markdown_backend(tmp_md.path());

    let n = 100;

    // SQLite: 100 stores
    let start = Instant::now();
    for i in 0..n {
        sq.store(
            &format!("key_{i}"),
            &format!("Memory entry number {i} about Rust programming"),
            MemoryCategory::Core,
            None,
        )
        .await
        .unwrap();
    }
    let sq_dur = start.elapsed();

    // Markdown: 100 stores
    let start = Instant::now();
    for i in 0..n {
        md.store(
            &format!("key_{i}"),
            &format!("Memory entry number {i} about Rust programming"),
            MemoryCategory::Core,
            None,
        )
        .await
        .unwrap();
    }
    let md_dur = start.elapsed();

    println!("\n============================================================");
    println!("STORE {n} entries:");
    println!("  SQLite:   {:?}", sq_dur);
    println!("  Markdown: {:?}", md_dur);

    // Both should succeed
    assert_eq!(sq.count().await.unwrap(), n);
    // Markdown count parses lines, may differ slightly from n
    let md_count = md.count().await.unwrap();
    assert!(md_count >= n, "Markdown stored {md_count}, expected >= {n}");
}

// ── Test 2: Recall / search quality ────────────────────────────

#[tokio::test]
async fn compare_recall_quality() {
    let tmp_sq = TempDir::new().unwrap();
    let tmp_md = TempDir::new().unwrap();
    let sq = sqlite_backend(tmp_sq.path());
    let md = markdown_backend(tmp_md.path());

    // Seed both with identical data
    let entries = vec![
        (
            "lang_pref",
            "User prefers Rust over Python",
            MemoryCategory::Core,
        ),
        (
            "editor",
            "Uses VS Code with rust-analyzer",
            MemoryCategory::Core,
        ),
        ("tz", "Timezone is EST, works 9-5", MemoryCategory::Core),
        (
            "proj1",
            "Working on ZeroClaw AI assistant",
            MemoryCategory::Daily,
        ),
        (
            "proj2",
            "Previous project was a web scraper in Python",
            MemoryCategory::Daily,
        ),
        (
            "deploy",
            "Deploys to Hetzner VPS via Docker",
            MemoryCategory::Core,
        ),
        (
            "model",
            "Prefers Claude Sonnet for coding tasks",
            MemoryCategory::Core,
        ),
        (
            "style",
            "Likes concise responses, no fluff",
            MemoryCategory::Core,
        ),
        (
            "rust_note",
            "Rust's ownership model prevents memory bugs",
            MemoryCategory::Daily,
        ),
        (
            "perf",
            "Cares about binary size and startup time",
            MemoryCategory::Core,
        ),
    ];

    for (key, content, cat) in &entries {
        sq.store(key, content, cat.clone(), None).await.unwrap();
        md.store(key, content, cat.clone(), None).await.unwrap();
    }

    // Test queries and compare results
    let queries = vec![
        ("Rust", "Should find Rust-related entries"),
        ("Python", "Should find Python references"),
        ("deploy Docker", "Multi-keyword search"),
        ("Claude", "Specific tool reference"),
        ("javascript", "No matches expected"),
        ("binary size startup", "Multi-keyword partial match"),
    ];

    println!("\n============================================================");
    println!("RECALL QUALITY (10 entries seeded):\n");

    for (query, desc) in &queries {
        let sq_results = sq.recall(query, 10, None).await.unwrap();
        let md_results = md.recall(query, 10, None).await.unwrap();

        println!("  Query: \"{query}\"{desc}");
        println!("    SQLite:   {} results", sq_results.len());
        for r in &sq_results {
            println!(
                "      [{:.2}] {}: {}",
                r.score.unwrap_or(0.0),
                r.key,
                &r.content[..r.content.len().min(50)]
            );
        }
        println!("    Markdown: {} results", md_results.len());
        for r in &md_results {
            println!(
                "      [{:.2}] {}: {}",
                r.score.unwrap_or(0.0),
                r.key,
                &r.content[..r.content.len().min(50)]
            );
        }
        println!();
    }
}

// ── Test 3: Recall speed at scale ──────────────────────────────

#[tokio::test]
async fn compare_recall_speed() {
    let tmp_sq = TempDir::new().unwrap();
    let tmp_md = TempDir::new().unwrap();
    let sq = sqlite_backend(tmp_sq.path());
    let md = markdown_backend(tmp_md.path());

    // Seed 200 entries
    let n = 200;
    for i in 0..n {
        let content = if i % 3 == 0 {
            format!("Rust is great for systems programming, entry {i}")
        } else if i % 3 == 1 {
            format!("Python is popular for data science, entry {i}")
        } else {
            format!("TypeScript powers modern web apps, entry {i}")
        };
        sq.store(&format!("e{i}"), &content, MemoryCategory::Core, None)
            .await
            .unwrap();
        md.store(&format!("e{i}"), &content, MemoryCategory::Daily, None)
            .await
            .unwrap();
    }

    // Benchmark recall
    let start = Instant::now();
    let sq_results = sq.recall("Rust systems", 10, None).await.unwrap();
    let sq_dur = start.elapsed();

    let start = Instant::now();
    let md_results = md.recall("Rust systems", 10, None).await.unwrap();
    let md_dur = start.elapsed();

    println!("\n============================================================");
    println!("RECALL from {n} entries (query: \"Rust systems\", limit 10):");
    println!("  SQLite:   {:?}{} results", sq_dur, sq_results.len());
    println!("  Markdown: {:?}{} results", md_dur, md_results.len());

    // Both should find results
    assert!(!sq_results.is_empty());
    assert!(!md_results.is_empty());
}

// ── Test 4: Persistence (SQLite wins by design) ────────────────

#[tokio::test]
async fn compare_persistence() {
    let tmp_sq = TempDir::new().unwrap();
    let tmp_md = TempDir::new().unwrap();

    // Store in both, then drop and re-open
    {
        let sq = sqlite_backend(tmp_sq.path());
        sq.store(
            "persist_test",
            "I should survive",
            MemoryCategory::Core,
            None,
        )
        .await
        .unwrap();
    }
    {
        let md = markdown_backend(tmp_md.path());
        md.store(
            "persist_test",
            "I should survive",
            MemoryCategory::Core,
            None,
        )
        .await
        .unwrap();
    }

    // Re-open
    let sq2 = sqlite_backend(tmp_sq.path());
    let md2 = markdown_backend(tmp_md.path());

    let sq_entry = sq2.get("persist_test").await.unwrap();
    let md_entry = md2.get("persist_test").await.unwrap();

    println!("\n============================================================");
    println!("PERSISTENCE (store → drop → re-open → get):");
    println!(
        "  SQLite:   {}",
        if sq_entry.is_some() {
            "✅ Survived"
        } else {
            "❌ Lost"
        }
    );
    println!(
        "  Markdown: {}",
        if md_entry.is_some() {
            "✅ Survived"
        } else {
            "❌ Lost"
        }
    );

    // SQLite should always persist by key
    assert!(sq_entry.is_some());
    assert_eq!(sq_entry.unwrap().content, "I should survive");

    // Markdown persists content to files (get uses content search)
    assert!(md_entry.is_some());
}

// ── Test 5: Upsert / update behavior ──────────────────────────

#[tokio::test]
async fn compare_upsert() {
    let tmp_sq = TempDir::new().unwrap();
    let tmp_md = TempDir::new().unwrap();
    let sq = sqlite_backend(tmp_sq.path());
    let md = markdown_backend(tmp_md.path());

    // Store twice with same key, different content
    sq.store("pref", "likes Rust", MemoryCategory::Core, None)
        .await
        .unwrap();
    sq.store("pref", "loves Rust", MemoryCategory::Core, None)
        .await
        .unwrap();

    md.store("pref", "likes Rust", MemoryCategory::Core, None)
        .await
        .unwrap();
    md.store("pref", "loves Rust", MemoryCategory::Core, None)
        .await
        .unwrap();

    let sq_count = sq.count().await.unwrap();
    let md_count = md.count().await.unwrap();

    let sq_entry = sq.get("pref").await.unwrap();
    let md_results = md.recall("loves Rust", 5, None).await.unwrap();

    println!("\n============================================================");
    println!("UPSERT (store same key twice):");
    println!(
        "  SQLite:   count={sq_count}, latest=\"{}\"",
        sq_entry.as_ref().map_or("none", |e| &e.content)
    );
    println!("  Markdown: count={md_count} (append-only, both entries kept)");
    println!("    Can still find latest: {}", !md_results.is_empty());

    // SQLite: upsert replaces, count stays at 1
    assert_eq!(sq_count, 1);
    assert_eq!(sq_entry.unwrap().content, "loves Rust");

    // Markdown: append-only, count increases
    assert!(md_count >= 2, "Markdown should keep both entries");
}

// ── Test 6: Forget / delete capability ─────────────────────────

#[tokio::test]
async fn compare_forget() {
    let tmp_sq = TempDir::new().unwrap();
    let tmp_md = TempDir::new().unwrap();
    let sq = sqlite_backend(tmp_sq.path());
    let md = markdown_backend(tmp_md.path());

    sq.store("secret", "API key: sk-1234", MemoryCategory::Core, None)
        .await
        .unwrap();
    md.store("secret", "API key: sk-1234", MemoryCategory::Core, None)
        .await
        .unwrap();

    let sq_forgot = sq.forget("secret").await.unwrap();
    let md_forgot = md.forget("secret").await.unwrap();

    println!("\n============================================================");
    println!("FORGET (delete sensitive data):");
    println!(
        "  SQLite:   {} (count={})",
        if sq_forgot { "✅ Deleted" } else { "❌ Kept" },
        sq.count().await.unwrap()
    );
    println!(
        "  Markdown: {} (append-only by design)",
        if md_forgot {
            "✅ Deleted"
        } else {
            "⚠️  Cannot delete (audit trail)"
        },
    );

    // SQLite can delete
    assert!(sq_forgot);
    assert_eq!(sq.count().await.unwrap(), 0);

    // Markdown cannot delete (by design)
    assert!(!md_forgot);
}

// ── Test 7: Category filtering ─────────────────────────────────

#[tokio::test]
async fn compare_category_filter() {
    let tmp_sq = TempDir::new().unwrap();
    let tmp_md = TempDir::new().unwrap();
    let sq = sqlite_backend(tmp_sq.path());
    let md = markdown_backend(tmp_md.path());

    // Mix of categories
    sq.store("a", "core fact 1", MemoryCategory::Core, None)
        .await
        .unwrap();
    sq.store("b", "core fact 2", MemoryCategory::Core, None)
        .await
        .unwrap();
    sq.store("c", "daily note", MemoryCategory::Daily, None)
        .await
        .unwrap();
    sq.store("d", "convo msg", MemoryCategory::Conversation, None)
        .await
        .unwrap();

    md.store("a", "core fact 1", MemoryCategory::Core, None)
        .await
        .unwrap();
    md.store("b", "core fact 2", MemoryCategory::Core, None)
        .await
        .unwrap();
    md.store("c", "daily note", MemoryCategory::Daily, None)
        .await
        .unwrap();

    let sq_core = sq.list(Some(&MemoryCategory::Core), None).await.unwrap();
    let sq_daily = sq.list(Some(&MemoryCategory::Daily), None).await.unwrap();
    let sq_conv = sq
        .list(Some(&MemoryCategory::Conversation), None)
        .await
        .unwrap();
    let sq_all = sq.list(None, None).await.unwrap();

    let md_core = md.list(Some(&MemoryCategory::Core), None).await.unwrap();
    let md_daily = md.list(Some(&MemoryCategory::Daily), None).await.unwrap();
    let md_all = md.list(None, None).await.unwrap();

    println!("\n============================================================");
    println!("CATEGORY FILTERING:");
    println!(
        "  SQLite:   core={}, daily={}, conv={}, all={}",
        sq_core.len(),
        sq_daily.len(),
        sq_conv.len(),
        sq_all.len()
    );
    println!(
        "  Markdown: core={}, daily={}, all={}",
        md_core.len(),
        md_daily.len(),
        md_all.len()
    );

    // SQLite: precise category filtering via SQL WHERE
    assert_eq!(sq_core.len(), 2);
    assert_eq!(sq_daily.len(), 1);
    assert_eq!(sq_conv.len(), 1);
    assert_eq!(sq_all.len(), 4);

    // Markdown: categories determined by file location
    assert!(!md_core.is_empty());
    assert!(!md_all.is_empty());
}