sqlite-graphrag 1.2.8

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
//! Integration tests for v1.0.44 features:
//! - H3: `related` falls back to bare entity when no memory matches the seed name
//! - H4: `rename` accepts `<NEW>` as a second positional argument (mv-style)
//! - M6: `cache list` emits structured JSON with `schema_version = 1`
//! - B1 regression: README bash blocks contain no inline `# comment` after a CLI command

use assert_cmd::Command;
use predicates::prelude::*;
use serial_test::serial;
use tempfile::TempDir;

/// Builds a fresh `Command` with the mock LLM PATH prepended.
///
/// v1.0.76 spawns `claude` or `codex` on every `remember` / `ingest` /
/// `edit`. The bundled mocks under `tests/mock-llm/` return a fixed
/// 64-dim zero vector so the binary finishes without a real OAuth
/// login. The mock directory is leaked (no TempDir cleanup) so the
/// spawned subprocess always finds the mocks.
fn sgr_cmd() -> Command {
    let mock_dir = common::mock_llm_path();
    let mut c = Command::cargo_bin("sqlite-graphrag").expect("sqlite-graphrag binary not found");
    c.env("PATH", common::prepend_path(&mock_dir));
    c
}

#[path = "common/mod.rs"]
mod common;

// ---------------------------------------------------------------------------
// Helper: build a Command with a fully isolated environment.
// ---------------------------------------------------------------------------

fn system_cache_dir() -> std::path::PathBuf {
    // `ProjectDirs` already honours `XDG_CACHE_HOME` on Linux AND appends the
    // application subdirectory. Reading the env by hand here would return the
    // parent and silently miss `<root>/sqlite-graphrag`.
    directories::ProjectDirs::from("", "", "sqlite-graphrag")
        .map(|p| p.cache_dir().to_path_buf())
        .unwrap_or_else(|| std::path::PathBuf::from(".cache"))
}

fn cmd(temp: &TempDir) -> Command {
    let cache = system_cache_dir();
    let mut c = sgr_cmd();
    let mock_dir = common::mock_llm_path();
    c.env_clear()
        .env("HOME", temp.path())
        .env("HOME", temp.path())
        .env("XDG_CACHE_HOME", &cache)
        .arg("--lang")
        .arg("en")
        // GAP-SG-207: this sandbox isolates HOME precisely so the XDG default
        // IS the intended target, which is a deliberate choice rather than an
        // inherited one. Declaring it keeps the mutating verbs below running
        // without pinning `--db` on every single invocation.
        .arg("--use-active")
        .current_dir(temp.path());
    for var in &["LOCALAPPDATA", "APPDATA", "USERPROFILE", "SystemRoot"] {
        if let Ok(v) = std::env::var(var) {
            c.env(var, v);
        }
    }
    // PATH is composed (not just inherited) so the mock-llm directory is
    // always prepended. The v1.0.76 binary spawns `claude` or `codex`
    // for every `remember` / `ingest` / `edit`; without the mock in
    // PATH the spawn calls the real CLI on the host which fails.
    c.env("PATH", common::prepend_path(&mock_dir));
    // Offline OpenRouter stub: `env_clear` leaves HOME as the only config
    // channel, so the sandbox config lands under $HOME/.config.
    common::write_sandbox_config(&temp.path().join(".config").join("sqlite-graphrag"), None);
    c.arg("--embedding-model")
        .arg(common::openrouter_mock::STUB_MODEL);
    c
}

// ---------------------------------------------------------------------------
// H3 — `related` entity-fallback
// ---------------------------------------------------------------------------

/// When the seed name matches a bare entity (not a memory name), `related`
/// must succeed via the entity fallback path added in H3.
///
/// Entities are injected via `--entities-file` to avoid needing the BERT NER
/// model in CI; then `link` creates a relationship so `related` has edges to
/// traverse.
#[test]
#[serial]
fn related_entity_seed_via_link_succeeds() {
    let temp = TempDir::new().expect("create temp dir");

    // Write a minimal entities JSON file for alice-note.
    let entities_alice = temp.path().join("entities_alice.json");
    std::fs::write(
        &entities_alice,
        r#"[{"name":"Alice","entity_type":"person"},{"name":"Acme","entity_type":"organization"}]"#,
    )
    .expect("write entities_alice.json");

    // Write a minimal entities JSON file for bob-note.
    let entities_bob = temp.path().join("entities_bob.json");
    std::fs::write(
        &entities_bob,
        r#"[{"name":"Bob","entity_type":"person"},{"name":"Acme","entity_type":"organization"}]"#,
    )
    .expect("write entities_bob.json");

    // Persist alice-note with injected entities (no BERT model needed).
    cmd(&temp)
        .args([
            "remember",
            "--name",
            "alice-note",
            "--type",
            "user",
            "--description",
            "note about alice",
            "--body",
            "Alice is a software engineer",
            "--entities-file",
            entities_alice.to_str().expect("utf-8 path"),
        ])
        .assert()
        .success();

    // Persist bob-note with injected entities.
    cmd(&temp)
        .args([
            "remember",
            "--name",
            "bob-note",
            "--type",
            "user",
            "--description",
            "note about bob",
            "--body",
            "Bob is a software engineer",
            "--entities-file",
            entities_bob.to_str().expect("utf-8 path"),
        ])
        .assert()
        .success();

    // Now "Alice" and "Bob" exist as graph entities; link them.
    cmd(&temp)
        .args([
            "link",
            "--from",
            "Alice",
            "--to",
            "Bob",
            "--relation",
            "related",
        ])
        .assert()
        .success();

    // `related Alice` — "Alice" is a bare entity, not a memory name.
    // The H3 fallback must locate it and return success.
    cmd(&temp)
        .args(["related", "Alice", "--max-hops", "2"])
        .assert()
        .success();
}

/// When neither a memory nor an entity named `<seed>` exists, `related` must
/// exit with failure and surface a "not found" message in stderr.
#[test]
#[serial]
fn related_errors_when_neither_memory_nor_entity_exists() {
    let temp = TempDir::new().expect("create temp dir");

    // Warm up auto-init; --skip-extraction avoids model requirement.
    cmd(&temp)
        .args([
            "remember",
            "--name",
            "warm-up",
            "--type",
            "note",
            "--description",
            "init db",
            "--body",
            "warm up",
            "--skip-extraction",
        ])
        .assert()
        .success();

    cmd(&temp)
        .args(["related", "definitely-does-not-exist-xyz-8675309"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("not found").or(predicate::str::contains("Not Found")));
}

// ---------------------------------------------------------------------------
// H4 — `rename` positional NEW argument (mv-style)
// ---------------------------------------------------------------------------

/// `rename OLD NEW` — both arguments positional — must rename the memory and
/// leave the new name readable.
#[test]
#[serial]
fn rename_positional_new_name_works() {
    let temp = TempDir::new().expect("create temp dir");

    cmd(&temp)
        .args([
            "remember",
            "--name",
            "old-name",
            "--type",
            "note",
            "--description",
            "test",
            "--body",
            "hello rename",
            "--skip-extraction",
        ])
        .assert()
        .success();

    // mv-style: rename OLD NEW
    cmd(&temp)
        .args(["rename", "old-name", "new-name"])
        .assert()
        .success();

    // old name must be gone; new name must return the original body.
    cmd(&temp).args(["read", "old-name"]).assert().failure();

    cmd(&temp)
        .args(["read", "new-name"])
        .assert()
        .success()
        .stdout(predicate::str::contains("hello rename"));
}

/// `rename OLD --new-name NEW` (legacy flag form) must still work after the
/// positional NEW was added so existing integrations are not broken.
#[test]
#[serial]
fn rename_legacy_new_name_flag_still_works() {
    let temp = TempDir::new().expect("create temp dir");

    cmd(&temp)
        .args([
            "remember",
            "--name",
            "foo",
            "--type",
            "note",
            "--description",
            "test",
            "--body",
            "bar body",
            "--skip-extraction",
        ])
        .assert()
        .success();

    cmd(&temp)
        .args(["rename", "foo", "--new-name", "bar"])
        .assert()
        .success();

    cmd(&temp)
        .args(["read", "bar"])
        .assert()
        .success()
        .stdout(predicate::str::contains("bar body"));
}

/// Providing both the positional NEW and the `--new-name` flag simultaneously
/// must be rejected by clap (conflicts_with).
#[test]
#[serial]
fn rename_rejects_both_positional_new_and_flag() {
    let temp = TempDir::new().expect("create temp dir");

    cmd(&temp)
        .args([
            "remember",
            "--name",
            "conflict-test",
            "--type",
            "note",
            "--description",
            "test",
            "--body",
            "body",
            "--skip-extraction",
        ])
        .assert()
        .success();

    // Both positional NEW ("bar") and --new-name ("baz") provided — clap must reject.
    cmd(&temp)
        .args(["rename", "conflict-test", "bar", "--new-name", "baz"])
        .assert()
        .failure();
}

// ---------------------------------------------------------------------------
// M6 — `cache list` JSON output
// ---------------------------------------------------------------------------

/// `cache list --json` must emit valid JSON with `schema_version = 1` and a
/// `files` array regardless of whether any model files are present.
#[test]
#[serial]
fn cache_list_json_returns_schema_version_1() {
    let temp = TempDir::new().expect("create temp dir");

    let output = cmd(&temp)
        .args(["cache", "list", "--json"])
        .output()
        .expect("run cache list --json");

    assert!(
        output.status.success(),
        "cache list --json failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    let parsed: serde_json::Value =
        serde_json::from_str(&stdout).expect("cache list --json must produce valid JSON");

    assert_eq!(
        parsed["schema_version"], 1,
        "schema_version must be 1; got: {parsed}"
    );
    assert!(
        parsed["files"].is_array(),
        "files must be a JSON array; got: {parsed}"
    );
    assert!(
        parsed.get("total_bytes").is_some(),
        "total_bytes field must be present; got: {parsed}"
    );
}

/// `cache list` (text mode) must either show a TOTAL footer (when files exist)
/// or print "(empty)" when the cache directory is absent or empty.
#[test]
#[serial]
fn cache_list_text_shows_total_or_empty() {
    let temp = TempDir::new().expect("create temp dir");

    cmd(&temp)
        .args(["cache", "list"])
        .assert()
        .success()
        .stdout(predicate::str::contains("TOTAL").or(predicate::str::contains("(empty)")));
}

// ---------------------------------------------------------------------------
// B1 regression — no inline shell comments after CLI commands in README blocks
// ---------------------------------------------------------------------------

/// Every sqlite-graphrag invocation line inside an **executable** ```bash block
/// (i.e. blocks NOT preceded by `<!-- skip-test -->`) in README.md and
/// README.pt-BR.md must NOT contain an inline ` # ` comment suffix.
///
/// Such suffixes pass the comment text as a literal CLI argument, breaking
/// the readme_examples_executable.rs harness (B1 regression in v1.0.43).
/// Blocks marked `<!-- skip-test -->` are exempted because they document
/// shell pipelines or commands that need external state.
#[test]
fn readme_bash_blocks_have_no_inline_shell_comments_after_command() {
    for readme in &["README.md", "README.pt-BR.md"] {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(readme);
        let content =
            std::fs::read_to_string(&path).unwrap_or_else(|_| panic!("could not read {readme}"));

        let mut in_bash = false;
        let mut skip_block = false;
        let mut last_non_blank: Option<String> = None;

        for (i, line) in content.lines().enumerate() {
            let trimmed = line.trim_end_matches('\r');
            let trimmed_start = trimmed.trim_start();

            if !in_bash {
                if trimmed_start.starts_with("```bash") {
                    // Detect skip-test marker on the most recent non-blank line.
                    skip_block = last_non_blank
                        .as_deref()
                        .map(|s| s.contains("<!-- skip-test"))
                        .unwrap_or(false);
                    in_bash = true;
                } else if !trimmed.trim().is_empty() {
                    last_non_blank = Some(trimmed.to_string());
                }
            } else if trimmed_start.starts_with("```") {
                in_bash = false;
                skip_block = false;
                last_non_blank = Some(trimmed.to_string());
            } else if !skip_block
                && trimmed_start.starts_with("sqlite-graphrag")
                && line.contains(" # ")
            {
                panic!(
                    "inline shell comment on executable CLI line in {readme}:{}: {:?}",
                    i + 1,
                    line
                );
            }
        }
    }
}