sqlite-graphrag 1.0.43

Local GraphRAG memory for LLMs in a single SQLite file
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
#![cfg(feature = "slow-tests")]

//! CLI integration tests for M2 (forget deleted_at_iso) and M3 (ingest truncated/original_name).

use assert_cmd::Command;
use serde_json::Value;
use serial_test::serial;
use tempfile::TempDir;

fn cmd(tmp: &TempDir) -> Command {
    let mut c = Command::cargo_bin("sqlite-graphrag").unwrap();
    c.env("SQLITE_GRAPHRAG_DB_PATH", tmp.path().join("test.sqlite"));
    c.env("SQLITE_GRAPHRAG_CACHE_DIR", tmp.path().join("cache"));
    c.env("SQLITE_GRAPHRAG_LOG_LEVEL", "error");
    c.arg("--skip-memory-guard");
    c
}

fn init_db(tmp: &TempDir) {
    cmd(tmp).arg("init").assert().success();
}

#[test]
#[serial]
fn forget_response_emits_deleted_at_iso_when_soft_deleted() {
    let tmp = TempDir::new().unwrap();
    init_db(&tmp);

    cmd(&tmp)
        .args([
            "remember",
            "--name",
            "test-mem",
            "--type",
            "user",
            "--description",
            "a test memory",
            "--body",
            "body text",
        ])
        .assert()
        .success();

    let output = cmd(&tmp)
        .args(["forget", "--name", "test-mem"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let json: Value = serde_json::from_slice(&output).expect("stdout must be valid JSON");

    assert_eq!(json["action"], "soft_deleted");
    assert_eq!(json["forgotten"], true);

    let deleted_at = json.get("deleted_at");
    assert!(
        deleted_at.is_some() && deleted_at.unwrap().is_number(),
        "deleted_at must be a number; got: {json}"
    );

    let deleted_at_iso = json.get("deleted_at_iso");
    assert!(
        deleted_at_iso.is_some() && deleted_at_iso.unwrap().is_string(),
        "deleted_at_iso must be a string; got: {json}"
    );

    // Validate RFC 3339 format: must contain 'T' separator and timezone offset
    let iso_str = deleted_at_iso.unwrap().as_str().unwrap();
    assert!(
        iso_str.contains('T')
            && (iso_str.ends_with('Z')
                || iso_str.contains('+')
                || iso_str.contains("-0")
                || iso_str.contains(":00")),
        "deleted_at_iso must be RFC 3339; got: {iso_str}"
    );
}

#[test]
#[serial]
fn ingest_event_emits_truncated_when_filename_exceeds_60_chars() {
    let tmp = TempDir::new().unwrap();
    init_db(&tmp);

    // Create a file with a basename of 80 chars (will exceed DERIVED_NAME_MAX_LEN=60)
    let long_name = format!("{}.md", "a".repeat(80));
    let file_path = tmp.path().join(&long_name);
    std::fs::write(&file_path, "content for truncation test").expect("write file must succeed");

    let output = cmd(&tmp)
        .args([
            "ingest",
            tmp.path().to_str().unwrap(),
            "--type",
            "document",
            "--pattern",
            &long_name,
        ])
        .output()
        .expect("ingest command must run");

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Find the file event line (not the summary line)
    let file_event: Value = stdout
        .lines()
        .filter_map(|line| serde_json::from_str::<Value>(line).ok())
        .find(|v| v.get("summary").is_none())
        .expect("must find a file event JSON line");

    assert_eq!(
        file_event["truncated"], true,
        "truncated must be true for long filename; got: {file_event}"
    );

    let original_name = file_event.get("original_name");
    assert!(
        original_name.is_some() && original_name.unwrap().is_string(),
        "original_name must be present and a string when truncated=true; got: {file_event}"
    );

    let original = original_name.unwrap().as_str().unwrap();
    assert!(
        original.len() > 60,
        "original_name must be longer than 60 chars; got len={} value={original}",
        original.len()
    );
}

#[test]
#[serial]
fn recall_with_autostart_daemon_false_does_not_spawn_daemon() {
    let tmp = TempDir::new().unwrap();
    init_db(&tmp);

    cmd(&tmp)
        .args([
            "remember",
            "--name",
            "autostart-test-mem",
            "--type",
            "user",
            "--description",
            "autostart test memory",
            "--body",
            "daemon autostart test body",
        ])
        .assert()
        .success();

    // Run recall with --autostart-daemon=false; the daemon should NOT be spawned.
    // We verify absence of the daemon spawn lock file in the control dir.
    cmd(&tmp)
        .args([
            "recall",
            "daemon autostart test",
            "--autostart-daemon=false",
        ])
        .env("SQLITE_GRAPHRAG_DAEMON_DISABLE_AUTOSTART", "1")
        .assert()
        .success();

    // Daemon spawn lock file must not exist when autostart was disabled.
    let cache_dir = tmp.path().join("cache");
    let spawn_lock = cache_dir.join("daemon-spawn.lock");
    assert!(
        !spawn_lock.exists(),
        "daemon-spawn.lock must NOT exist when --autostart-daemon=false; found at: {}",
        spawn_lock.display()
    );
}

#[test]
#[serial]
fn recall_default_autostart_daemon_true_remains_compatible() {
    let tmp = TempDir::new().unwrap();
    init_db(&tmp);

    cmd(&tmp)
        .args([
            "remember",
            "--name",
            "compat-test-mem",
            "--type",
            "user",
            "--description",
            "compatibility test memory",
            "--body",
            "regression guard body text",
        ])
        .assert()
        .success();

    // Default flag value (true) must not break the recall command.
    // Env var disables actual daemon spawn so the test stays fast and isolated.
    cmd(&tmp)
        .args(["recall", "regression guard"])
        .env("SQLITE_GRAPHRAG_DAEMON_DISABLE_AUTOSTART", "1")
        .assert()
        .success();
}

#[test]
#[serial]
fn list_include_deleted_emits_deleted_at_and_deleted_at_iso() {
    let tmp = TempDir::new().unwrap();
    init_db(&tmp);

    cmd(&tmp)
        .args([
            "remember",
            "--name",
            "h1-regression-mem",
            "--type",
            "user",
            "--description",
            "H1 regression memory",
            "--body",
            "body for list include-deleted regression",
        ])
        .assert()
        .success();

    cmd(&tmp)
        .args(["forget", "--name", "h1-regression-mem"])
        .assert()
        .success();

    let output = cmd(&tmp)
        .args(["list", "--include-deleted", "--json"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let json: Value =
        serde_json::from_slice(&output).expect("list --include-deleted output must be valid JSON");

    let items = json["items"].as_array().expect("items must be an array");
    let item = items
        .iter()
        .find(|v| v["name"] == "h1-regression-mem")
        .expect("soft-deleted memory must appear in list --include-deleted");

    let deleted_at = item.get("deleted_at");
    assert!(
        deleted_at.is_some() && deleted_at.unwrap().is_number(),
        "deleted_at must be a number in list --include-deleted output; got: {item}"
    );

    let deleted_at_iso = item.get("deleted_at_iso");
    assert!(
        deleted_at_iso.is_some() && deleted_at_iso.unwrap().is_string(),
        "deleted_at_iso must be a string in list --include-deleted output; got: {item}"
    );

    let iso_str = deleted_at_iso.unwrap().as_str().unwrap();
    assert!(
        iso_str.contains('T'),
        "deleted_at_iso must be RFC 3339 (contains 'T'); got: {iso_str}"
    );
}

// ---------------------------------------------------------------------------
// Wave 2 logic bug regressions (v1.0.40)
// ---------------------------------------------------------------------------

// Bug M-A6: history JSON populates a non-null `action` field for the
// initial memory version, mapped from the underlying `change_reason`.
#[test]
#[serial]
fn history_initial_version_emits_action_created() {
    let tmp = TempDir::new().unwrap();
    init_db(&tmp);

    cmd(&tmp)
        .args([
            "remember",
            "--name",
            "wave2-history-action",
            "--type",
            "note",
            "--description",
            "test note",
            "--body",
            "Hello world. This is a note about Rust.",
        ])
        .assert()
        .success();

    let output = cmd(&tmp)
        .args(["history", "--name", "wave2-history-action"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let json: Value = serde_json::from_slice(&output).expect("stdout must be valid JSON");
    let versions = json["versions"]
        .as_array()
        .expect("versions must be an array");
    assert!(!versions.is_empty(), "versions must not be empty");

    let v0 = &versions[0];
    let action = v0
        .get("action")
        .expect("history version must expose `action`");
    assert!(
        action.is_string(),
        "action must be a string, got: {action:?}"
    );
    assert_eq!(
        action.as_str().unwrap(),
        "created",
        "first version action must be `created`"
    );
}

// Bug M-A5: recall populates a non-null `score` in [0, 1] for every direct match.
#[test]
#[serial]
fn recall_results_carry_score_in_unit_range() {
    let tmp = TempDir::new().unwrap();
    init_db(&tmp);

    cmd(&tmp)
        .args([
            "remember",
            "--name",
            "wave2-recall-score",
            "--type",
            "note",
            "--description",
            "rust adapter mechanism",
            "--body",
            "The rust adapter mechanism uses traits and generics to provide flexible type conversions.",
        ])
        .assert()
        .success();

    let output = cmd(&tmp)
        .args(["recall", "rust adapter mechanism", "--k", "5", "--no-graph"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let json: Value = serde_json::from_slice(&output).expect("stdout must be valid JSON");
    let results = json["results"]
        .as_array()
        .expect("results must be an array");
    assert!(!results.is_empty(), "recall must return at least one match");

    for item in results {
        let score = item
            .get("score")
            .expect("every recall item must expose `score`");
        let s = score.as_f64().unwrap_or_else(|| {
            panic!("score must be a number, got {score:?}");
        });
        assert!((0.0..=1.0).contains(&s), "score must be in [0, 1], got {s}");
    }
}

// Bug M-A3: ingest derives kebab names that preserve the base ASCII letters
// of accented and emoji-bearing filenames instead of collapsing them to
// stray characters. Validates via `list` after ingest.
#[test]
#[serial]
fn ingest_unicode_filenames_yield_meaningful_names() {
    let tmp = TempDir::new().unwrap();
    init_db(&tmp);

    let corpus = tmp.path().join("corpus");
    std::fs::create_dir(&corpus).unwrap();
    std::fs::write(corpus.join("açaí.md"), "acai berry content").unwrap();
    std::fs::write(corpus.join("naïve-test.md"), "naive test content").unwrap();
    std::fs::write(corpus.join("🚀-rocket.md"), "rocket content").unwrap();

    cmd(&tmp)
        .args([
            "ingest",
            corpus.to_str().unwrap(),
            "--type",
            "note",
            "--pattern",
            "*.md",
            "--skip-extraction",
        ])
        .assert()
        .success();

    let output = cmd(&tmp)
        .args(["list", "--json"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let json: Value = serde_json::from_slice(&output).expect("stdout must be valid JSON");
    let items = json["items"]
        .as_array()
        .or_else(|| json["memories"].as_array())
        .expect("list must return items or memories array");

    let names: Vec<String> = items
        .iter()
        .filter_map(|i| i.get("name").and_then(|n| n.as_str()).map(String::from))
        .collect();

    assert!(
        names.iter().any(|n| n == "acai"),
        "expected an entry named `acai`, got: {names:?}"
    );
    assert!(
        names.iter().any(|n| n == "naive-test"),
        "expected an entry named `naive-test`, got: {names:?}"
    );
    assert!(
        names.iter().any(|n| n == "rocket"),
        "expected an entry named `rocket`, got: {names:?}"
    );
}

// Bug H-M8: chunks_persisted contract for single-chunk vs multi-chunk bodies.
// Single-chunk bodies live in the memories row directly so chunks_persisted=0.
// Multi-chunk bodies persist every chunk so chunks_persisted=chunks_created.
#[test]
#[serial]
fn remember_single_chunk_body_reports_zero_persisted_chunks() {
    let tmp = TempDir::new().unwrap();
    init_db(&tmp);

    let output = cmd(&tmp)
        .args([
            "remember",
            "--name",
            "wave2-single-chunk",
            "--type",
            "note",
            "--description",
            "short body",
            "--body",
            "Tiny body fits in one chunk.",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let json: Value = serde_json::from_slice(&output).expect("stdout must be valid JSON");
    assert_eq!(
        json["chunks_created"].as_u64().unwrap(),
        1,
        "single-chunk body must report chunks_created=1"
    );
    assert_eq!(
        json["chunks_persisted"].as_u64().unwrap(),
        0,
        "single-chunk body MUST report chunks_persisted=0 \
         because the memories row itself acts as the chunk \
         (no row in memory_chunks)"
    );
}