sqlite-graphrag 1.2.5

Persistent GraphRAG memory for Claude Code, Codex, Cursor, and 27 AI agents — one self-contained ~19 MiB Rust binary, zero daemon. Never re-explain your codebase again. Hybrid retrieval (FTS5 BM25 + cosine similarity + multi-hop graph traversal) surfaces the right memory in milliseconds. Embedding and entity enrichment run as parallel REST calls against your cloud LLM — no fragile headless subprocesses, no ONNX runtime, no model downloads. Soft-delete with full version history, transactional atomic writes, BLAKE3-tracked mutations. OAuth-only: raw API keys ABORT the spawn.
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
//! PRD compliance: purge retention, optimize, vacuum, permissions, path traversal, stats, list, rename, restore, cleanup-orphans, sync-safe-copy and the high-degree hub write (clauses 21-32).
//!
//! Part of the PRD-compliance suite split by GAP-SG-208. Covers the MUST/DEVE
//! clauses of the sqlite-graphrag PRD. The shared harness lives in
//! `tests/prd_support/`.

#[path = "prd_support/mod.rs"]
mod support;

use rusqlite::Connection;
use serial_test::serial;
use support::{cmd_base, db_path, init_db, remember_ok, sgr_cmd};
use tempfile::TempDir;
// ---------------------------------------------------------------------------
// 21 — purge with retention=1 removes soft-deleted memories older than 1 day
// ---------------------------------------------------------------------------

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

    remember_ok(&tmp, "mem-purge-alvo", "corpo para purge test");

    // Direct soft-delete via SQL with timestamp in the past (2 days ago)
    let conn = Connection::open(db_path(&tmp)).unwrap();
    conn.execute(
        "UPDATE memories SET deleted_at = strftime('%s','now') - 172800 WHERE name='mem-purge-alvo'",
        [],
    )
    .unwrap();
    drop(conn);

    // Purge with retention of 1 day — should remove the 2-day-old memory
    cmd_base(&tmp)
        .args(["purge", "--retention-days", "1", "--yes"])
        .assert()
        .success();

    // Verifica que foi removida permanentemente
    let conn2 = Connection::open(db_path(&tmp)).unwrap();
    let count: i64 = conn2
        .query_row(
            "SELECT COUNT(*) FROM memories WHERE name='mem-purge-alvo'",
            [],
            |r| r.get(0),
        )
        .unwrap();
    assert_eq!(
        count, 0,
        "purge deve remover permanentemente memórias com deleted_at > retention"
    );
}

// ---------------------------------------------------------------------------
// 22 — optimize executa sem erros e retorna status ok
// ---------------------------------------------------------------------------

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

    let output = cmd_base(&tmp)
        .arg("optimize")
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let json: serde_json::Value = serde_json::from_slice(&output).unwrap();
    assert_eq!(json["status"], "ok", "optimize deve retornar status 'ok'");
}

// ---------------------------------------------------------------------------
// 23 — vacuum retorna size_before_bytes e size_after_bytes
// ---------------------------------------------------------------------------

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

    let output = cmd_base(&tmp)
        .arg("vacuum")
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let json: serde_json::Value = serde_json::from_slice(&output).unwrap();
    assert!(
        json.get("size_before_bytes").is_some(),
        "vacuum deve emitir size_before_bytes"
    );
    assert!(
        json.get("size_after_bytes").is_some(),
        "vacuum deve emitir size_after_bytes"
    );
}

// ---------------------------------------------------------------------------
// 24 — chmod 600 applied on Unix after init
// ---------------------------------------------------------------------------

#[test]
#[cfg(unix)]
fn prd_chmod_600_aplicado_apos_init() {
    use std::os::unix::fs::PermissionsExt;

    let tmp = TempDir::new().unwrap();
    init_db(&tmp);

    let db = db_path(&tmp);
    let perms = std::fs::metadata(&db).unwrap().permissions();
    let mode = perms.mode() & 0o777;
    assert_eq!(
        mode, 0o600,
        "database deve ter permissão 600 após init, atual: {mode:o}"
    );
}

// ---------------------------------------------------------------------------
// 25 — path traversal (..) rejected in --db (product env is not a channel)
// ---------------------------------------------------------------------------

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

    // GAP-SG-101: SQLITE_GRAPHRAG_DB_PATH is not read. Validate --db instead.
    let mut c = sgr_cmd();
    support::common::wire_assert_cmd(&tmp, &mut c, "unused.sqlite");
    c.arg("--skip-memory-guard");
    c.args(["init", "--db", "../../../etc/passwd"]);

    c.assert().failure();
}

// ---------------------------------------------------------------------------
// 26 — stats inclui memories, entities, relationships (e aliases _total)
// ---------------------------------------------------------------------------

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

    remember_ok(&tmp, "mem-stats-check", "corpo para stats test");

    let output = cmd_base(&tmp)
        .arg("stats")
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let json: serde_json::Value = serde_json::from_slice(&output).unwrap();
    assert!(
        json.get("memories").is_some(),
        "stats deve ter campo 'memories'"
    );
    assert!(
        json.get("entities").is_some(),
        "stats deve ter campo 'entities'"
    );
    assert!(
        json.get("relationships").is_some(),
        "stats deve ter campo 'relationships'"
    );
    assert!(
        json.get("memories_total").is_some() || json.get("memories").is_some(),
        "stats deve ter memories_total ou memories"
    );
}

// ---------------------------------------------------------------------------
// 27 — list respeita --limit
// ---------------------------------------------------------------------------

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

    // Create 5 memories
    for i in 0..5 {
        remember_ok(&tmp, &format!("mem-limit-{i}"), &format!("corpo {i}"));
    }

    let output = cmd_base(&tmp)
        .args(["list", "--namespace", "global", "--limit", "2"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let json: serde_json::Value = serde_json::from_slice(&output).unwrap();
    let items = json["items"].as_array().unwrap();
    assert_eq!(
        items.len(),
        2,
        "list com --limit 2 deve retornar exatamente 2 itens"
    );
}

// ---------------------------------------------------------------------------
// 28 — rename updates memory version
// ---------------------------------------------------------------------------

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

    remember_ok(&tmp, "mem-rename-orig", "corpo para rename test");

    // Verify initial version via memory_versions
    let conn = Connection::open(db_path(&tmp)).unwrap();
    let version_antes: i64 = conn
        .query_row(
            "SELECT MAX(version) FROM memory_versions mv \
             JOIN memories m ON m.id = mv.memory_id WHERE m.name='mem-rename-orig'",
            [],
            |r| r.get(0),
        )
        .unwrap_or(0);
    drop(conn);

    // Rename
    cmd_base(&tmp)
        .args([
            "rename",
            "--name",
            "mem-rename-orig",
            "--new-name",
            "mem-rename-novo",
            "--namespace",
            "global",
        ])
        .assert()
        .success();

    // Verify the memory exists with the new name
    let conn2 = Connection::open(db_path(&tmp)).unwrap();
    let count: i64 = conn2
        .query_row(
            "SELECT COUNT(*) FROM memories WHERE name='mem-rename-novo'",
            [],
            |r| r.get(0),
        )
        .unwrap();
    assert_eq!(count, 1, "memória deve existir com novo nome após rename");

    // Version may have incremented after rename (we check it exists in memory_versions)
    let versions_count: i64 = conn2
        .query_row(
            "SELECT COUNT(*) FROM memory_versions WHERE name='mem-rename-novo' OR name='mem-rename-orig'",
            [],
            |r| r.get(0),
        )
        .unwrap();
    assert!(
        versions_count >= 1,
        "rename deve registrar versão em memory_versions"
    );
    let _ = version_antes; // usado para documentar intenção do teste
}

// ---------------------------------------------------------------------------
// 29 — restore reverts memory to the state before the last soft-delete
// ---------------------------------------------------------------------------

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

    remember_ok(&tmp, "mem-restore-test", "corpo original para restore");

    // Soft-delete
    cmd_base(&tmp)
        .args([
            "forget",
            "--name",
            "mem-restore-test",
            "--namespace",
            "global",
        ])
        .assert()
        .success();

    // Verify soft-deleted and obtain the version for restore
    let conn = Connection::open(db_path(&tmp)).unwrap();
    let deleted: bool = conn
        .query_row(
            "SELECT deleted_at IS NOT NULL FROM memories WHERE name='mem-restore-test'",
            [],
            |r| r.get(0),
        )
        .unwrap();
    assert!(deleted, "memória deve estar soft-deleted após forget");
    let version: i64 = conn
        .query_row(
            "SELECT MAX(version) FROM memory_versions v JOIN memories m ON m.id=v.memory_id WHERE m.name='mem-restore-test'",
            [],
            |r| r.get(0),
        )
        .unwrap();
    drop(conn);

    // Restore passing the version obtained from history
    cmd_base(&tmp)
        .args([
            "restore",
            "--name",
            "mem-restore-test",
            "--namespace",
            "global",
            "--version",
            &version.to_string(),
        ])
        .assert()
        .success();

    // Verifica que foi restaurada (deleted_at = NULL)
    let conn2 = Connection::open(db_path(&tmp)).unwrap();
    let active: bool = conn2
        .query_row(
            "SELECT deleted_at IS NULL FROM memories WHERE name='mem-restore-test'",
            [],
            |r| r.get(0),
        )
        .unwrap();
    assert!(
        active,
        "memória deve estar ativa (deleted_at NULL) após restore"
    );
}

// ---------------------------------------------------------------------------
// 30 — cleanup-orphans removes entities without memories
// ---------------------------------------------------------------------------

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

    // Insert an orphan entity directly into the database
    let conn = Connection::open(db_path(&tmp)).unwrap();
    conn.execute(
        "INSERT INTO entities (name, type, namespace) VALUES ('entidade-orfa', 'concept', 'global')",
        [],
    )
    .unwrap();
    drop(conn);

    // Verifica que existe antes
    let conn2 = Connection::open(db_path(&tmp)).unwrap();
    let antes: i64 = conn2
        .query_row(
            "SELECT COUNT(*) FROM entities WHERE name='entidade-orfa'",
            [],
            |r| r.get(0),
        )
        .unwrap();
    assert_eq!(antes, 1, "entidade órfã deve existir antes do cleanup");
    drop(conn2);

    // Executa cleanup
    let output = cmd_base(&tmp)
        .args(["cleanup-orphans", "--yes"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let json: serde_json::Value = serde_json::from_slice(&output).unwrap();
    let deleted = json["deleted"].as_u64().unwrap_or(0);
    assert!(
        deleted >= 1,
        "cleanup-orphans deve reportar ao menos 1 deleted"
    );

    // Verifica que a entidade foi removida
    let conn3 = Connection::open(db_path(&tmp)).unwrap();
    let depois: i64 = conn3
        .query_row(
            "SELECT COUNT(*) FROM entities WHERE name='entidade-orfa'",
            [],
            |r| r.get(0),
        )
        .unwrap();
    assert_eq!(
        depois, 0,
        "entidade órfã deve ter sido removida pelo cleanup"
    );
}

// ---------------------------------------------------------------------------
// 31 — sync-safe-copy gera snapshot coerente com bytes_copied > 0
// ---------------------------------------------------------------------------

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

    remember_ok(&tmp, "mem-snapshot", "corpo para snapshot test");

    let dest = tmp.path().join("snapshot.sqlite");

    let output = cmd_base(&tmp)
        .args(["sync-safe-copy", "--dest", dest.to_str().unwrap()])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let json: serde_json::Value = serde_json::from_slice(&output).unwrap();
    assert!(
        json.get("bytes_copied").is_some(),
        "sync-safe-copy deve emitir bytes_copied"
    );
    assert!(
        json["bytes_copied"].as_u64().unwrap_or(0) > 0,
        "bytes_copied deve ser > 0"
    );
    assert_eq!(
        json["status"], "ok",
        "sync-safe-copy deve retornar status 'ok'"
    );
    assert!(dest.exists(), "arquivo de snapshot deve existir no destino");
}

// ---------------------------------------------------------------------------
// 32 — GAP-SG-67: a write referencing a high-degree hub must be purely
//      additive — it must NEVER prune incident edges. Repro of the incident
//      at small scale: pre-fix, the default degree cap of 50 pruned the hub
//      back down to 50; post-fix the edge count only ever grows.
// ---------------------------------------------------------------------------

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

    // Build a HUB entity with 60 incident edges directly via SQL: well above
    // the old default degree cap of 50. Each edge targets a distinct leaf so
    // there are no UNIQUE(source_id,target_id,relation) collisions.
    let conn = Connection::open(db_path(&tmp)).unwrap();
    conn.execute(
        "INSERT INTO entities (name, type, namespace) VALUES ('hub-sg67', 'concept', 'global')",
        [],
    )
    .unwrap();
    let hub_id: i64 = conn
        .query_row("SELECT id FROM entities WHERE name='hub-sg67'", [], |r| {
            r.get(0)
        })
        .unwrap();

    const SEED_EDGES: i64 = 60;
    for i in 0..SEED_EDGES {
        let leaf = format!("leaf-sg67-{i}");
        conn.execute(
            "INSERT INTO entities (name, type, namespace) VALUES (?1, 'concept', 'global')",
            [&leaf],
        )
        .unwrap();
        let leaf_id: i64 = conn
            .query_row("SELECT id FROM entities WHERE name=?1", [&leaf], |r| {
                r.get(0)
            })
            .unwrap();
        // Ascending weights so a pruning pass would have a deterministic victim
        // order; the fix means no pruning happens at all.
        let weight = 0.1 + (i as f64) * 0.01;
        conn.execute(
            "INSERT INTO relationships (source_id, target_id, relation, weight, namespace) \
             VALUES (?1, ?2, 'related', ?3, 'global')",
            rusqlite::params![hub_id, leaf_id, weight],
        )
        .unwrap();
    }
    drop(conn);

    // One additional write: create the 61st incident edge on the hub via `link`.
    // The --max-entity-degree flag no longer exists; pre-fix it defaulted to 50
    // and this write would have pruned the 11 weakest edges back down to 50.
    cmd_base(&tmp)
        .args([
            "link",
            "--from",
            "hub-sg67",
            "--to",
            "leaf-sg67-new",
            "--relation",
            "related",
            "--create-missing",
            "--namespace",
            "global",
        ])
        .assert()
        .success();

    // ASSERT non-destructive: the edge count only grew (60 -> 61) and the hub's
    // degree stays high. A degree-cap prune would have collapsed both to 50.
    let conn = Connection::open(db_path(&tmp)).unwrap();
    let total: i64 = conn
        .query_row("SELECT COUNT(*) FROM relationships", [], |r| r.get(0))
        .unwrap();
    assert_eq!(
        total,
        SEED_EDGES + 1,
        "GAP-SG-67: write must be additive; relationships dropped (degree-cap pruning regressed)"
    );

    let hub_degree: i64 = conn
        .query_row(
            "SELECT COUNT(*) FROM relationships WHERE source_id=?1 OR target_id=?1",
            [hub_id],
            |r| r.get(0),
        )
        .unwrap();
    assert_eq!(
        hub_degree,
        SEED_EDGES + 1,
        "GAP-SG-67: hub degree must not collapse to the old cap of 50"
    );
    assert!(
        hub_degree > 50,
        "GAP-SG-67: hub must remain above the removed degree cap of 50"
    );
}