sqlite-graphrag 1.0.8

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
use assert_cmd::Command;
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
}

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

fn remember(tmp: &TempDir, name: &str, memory_type: &str, description: &str, body: &str) {
    cmd(tmp)
        .args([
            "remember",
            "--name",
            name,
            "--type",
            memory_type,
            "--description",
            description,
            "--body",
            body,
        ])
        .assert()
        .success();
}

// ---------------------------------------------------------------------------
// recall — DB não-inicializada
// ---------------------------------------------------------------------------

#[test]
#[serial]
fn test_recall_falha_sem_init() {
    let tmp = TempDir::new().unwrap();
    cmd(&tmp)
        .args(["recall", "qualquer-query"])
        .assert()
        .failure();
}

// ---------------------------------------------------------------------------
// recall — banco vazio retorna listas vazias
// ---------------------------------------------------------------------------

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

    let output = cmd(&tmp)
        .args(["recall", "busca-em-banco-vazio"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let json: serde_json::Value = serde_json::from_slice(&output).unwrap();
    assert_eq!(json["query"], "busca-em-banco-vazio");
    assert_eq!(json["direct_matches"].as_array().unwrap().len(), 0);
    assert_eq!(json["graph_matches"].as_array().unwrap().len(), 0);
}

// ---------------------------------------------------------------------------
// recall — query simples encontra memória existente
// ---------------------------------------------------------------------------

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

    remember(
        &tmp,
        "rust-ownership",
        "skill",
        "Conceito de ownership em Rust",
        "Ownership é o sistema de gerenciamento de memória do Rust sem garbage collector",
    );

    let output = cmd(&tmp)
        .args(["recall", "ownership Rust memória"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let json: serde_json::Value = serde_json::from_slice(&output).unwrap();
    assert_eq!(json["query"], "ownership Rust memória");
    let direct = json["direct_matches"].as_array().unwrap();
    assert!(
        !direct.is_empty(),
        "deve retornar ao menos uma correspondência direta"
    );
    assert_eq!(direct[0]["name"], "rust-ownership");
    assert_eq!(direct[0]["source"], "direct");
    assert!(direct[0]["distance"].as_f64().unwrap() >= 0.0);
}

// ---------------------------------------------------------------------------
// recall — campo snippet limitado a 300 chars
// ---------------------------------------------------------------------------

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

    let corpo_longo = "x".repeat(600);
    remember(
        &tmp,
        "memoria-longa",
        "project",
        "Memória com corpo muito longo",
        &corpo_longo,
    );

    let output = cmd(&tmp)
        .args(["recall", "memoria longa corpo"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let json: serde_json::Value = serde_json::from_slice(&output).unwrap();
    let direct = json["direct_matches"].as_array().unwrap();
    if !direct.is_empty() {
        let snippet = direct[0]["snippet"].as_str().unwrap();
        assert!(
            snippet.len() <= 300,
            "snippet deve ter no máximo 300 chars, tem {}",
            snippet.len()
        );
    }
}

// ---------------------------------------------------------------------------
// recall — -k limita número de resultados
// ---------------------------------------------------------------------------

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

    for i in 0..5 {
        remember(
            &tmp,
            &format!("memoria-k-{i}"),
            "user",
            &format!("Memória número {i} para teste de k"),
            &format!("Corpo da memória {i} com conteúdo sobre aprendizado e conhecimento"),
        );
    }

    let output = cmd(&tmp)
        .args(["recall", "memória aprendizado", "-k", "2"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let json: serde_json::Value = serde_json::from_slice(&output).unwrap();
    let direct = json["direct_matches"].as_array().unwrap();
    assert!(
        direct.len() <= 2,
        "com -k 2 deve retornar no máximo 2 diretos, retornou {}",
        direct.len()
    );
}

// ---------------------------------------------------------------------------
// recall — --no-graph desativa expansão por grafo
// ---------------------------------------------------------------------------

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

    remember(
        &tmp,
        "memoria-no-graph",
        "feedback",
        "Memória para teste de no-graph",
        "Conteúdo sobre configuração e preferências do usuário",
    );

    let output = cmd(&tmp)
        .args(["recall", "configuração preferências", "--no-graph"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let json: serde_json::Value = serde_json::from_slice(&output).unwrap();
    assert_eq!(
        json["graph_matches"].as_array().unwrap().len(),
        0,
        "--no-graph deve resultar em lista graph_matches vazia"
    );
}

// ---------------------------------------------------------------------------
// recall — --namespace filtra por namespace
// ---------------------------------------------------------------------------

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

    cmd(&tmp)
        .args([
            "remember",
            "--name",
            "mem-ns-alpha",
            "--type",
            "project",
            "--description",
            "Memória no namespace alpha",
            "--body",
            "Conteúdo do namespace alpha sobre projeto",
            "--namespace",
            "alpha",
        ])
        .assert()
        .success();

    cmd(&tmp)
        .args([
            "remember",
            "--name",
            "mem-ns-beta",
            "--type",
            "project",
            "--description",
            "Memória no namespace beta",
            "--body",
            "Conteúdo do namespace beta sobre projeto",
            "--namespace",
            "beta",
        ])
        .assert()
        .success();

    let output = cmd(&tmp)
        .args([
            "recall",
            "projeto conteúdo",
            "--namespace",
            "alpha",
            "--no-graph",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let json: serde_json::Value = serde_json::from_slice(&output).unwrap();
    let direct = json["direct_matches"].as_array().unwrap();
    for item in direct {
        assert_eq!(
            item["namespace"].as_str().unwrap(),
            "alpha",
            "todos resultados devem pertencer ao namespace alpha"
        );
    }
}

// ---------------------------------------------------------------------------
// recall — --type filtra por tipo de memória
// ---------------------------------------------------------------------------

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

    remember(
        &tmp,
        "mem-tipo-skill",
        "skill",
        "Habilidade de programação",
        "Saber programar em Rust é essencial para sistemas de alto desempenho",
    );
    remember(
        &tmp,
        "mem-tipo-user",
        "user",
        "Informação do usuário",
        "Usuário prefere Rust para desenvolvimento de sistemas",
    );

    let output = cmd(&tmp)
        .args([
            "recall",
            "Rust programação",
            "--type",
            "skill",
            "--no-graph",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let json: serde_json::Value = serde_json::from_slice(&output).unwrap();
    let direct = json["direct_matches"].as_array().unwrap();
    for item in direct {
        assert_eq!(
            item["type"].as_str().unwrap(),
            "skill",
            "com --type skill todos resultados devem ser do tipo skill"
        );
    }
}

// ---------------------------------------------------------------------------
// recall — estrutura JSON de resposta válida
// ---------------------------------------------------------------------------

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

    remember(
        &tmp,
        "mem-json-check",
        "reference",
        "Referência para validação JSON",
        "Conteúdo de referência técnica sobre estrutura de dados",
    );

    let output = cmd(&tmp)
        .args(["recall", "referência técnica", "--no-graph"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let json: serde_json::Value = serde_json::from_slice(&output).unwrap();

    assert!(json.get("query").is_some(), "resposta deve ter campo query");
    assert!(
        json.get("k").is_some(),
        "resposta deve ter campo k (v2.0.0+)"
    );
    assert!(
        json["k"].as_u64().unwrap() > 0,
        "campo k deve ser inteiro positivo"
    );
    assert!(
        json.get("direct_matches").is_some(),
        "resposta deve ter campo direct_matches"
    );
    assert!(
        json.get("graph_matches").is_some(),
        "resposta deve ter campo graph_matches"
    );

    let direct = json["direct_matches"].as_array().unwrap();
    if !direct.is_empty() {
        let item = &direct[0];
        assert!(item.get("memory_id").is_some());
        assert!(item.get("name").is_some());
        assert!(item.get("namespace").is_some());
        assert!(item.get("type").is_some(), "campo 'type' deve existir");
        assert!(item.get("snippet").is_some());
        assert!(item.get("distance").is_some());
        assert!(item.get("source").is_some());
        assert_eq!(item["source"].as_str().unwrap(), "direct");
    }
}

// ---------------------------------------------------------------------------
// recall — múltiplas memórias, query reflete todas
// ---------------------------------------------------------------------------

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

    remember(
        &tmp,
        "mem-multi-1",
        "feedback",
        "Feedback sobre testes automatizados",
        "Testes automatizados garantem qualidade do software e evitam regressões",
    );
    remember(
        &tmp,
        "mem-multi-2",
        "feedback",
        "Feedback sobre CI/CD",
        "Integração contínua melhora a entrega de software com testes automatizados",
    );
    remember(
        &tmp,
        "mem-multi-3",
        "feedback",
        "Feedback sobre code review",
        "Revisão de código com testes ajuda a manter padrão de qualidade",
    );

    let output = cmd(&tmp)
        .args(["recall", "testes qualidade software", "--no-graph"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let json: serde_json::Value = serde_json::from_slice(&output).unwrap();
    let direct = json["direct_matches"].as_array().unwrap();
    assert!(
        direct.len() >= 2,
        "deve retornar ao menos 2 das 3 memórias relacionadas, retornou {}",
        direct.len()
    );
}