sqlite-graphrag 1.0.99

Persistent GraphRAG memory for Claude Code, Codex, Cursor, and 24+ AI agents in a single 19 MiB Rust binary. LLM-only and one-shot in v1.0.78: every `remember` / `ingest` spawns a headless claude code or codex subprocess (OAuth, no MCP, no hooks). v1.0.93: optional OpenRouter API embedding backend (~100-500ms vs 20-60s subprocess). No daemon. No ONNX runtime. No model download. Graph-native retrieval with FTS5 + cosine + multi-hop traversal. OAuth-only enforcement for LLM backends: 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
//! Handler for the `unlink` CLI subcommand.

use crate::errors::AppError;
use crate::i18n::errors_msg;
use crate::output::{self, OutputFormat};
use crate::paths::AppPaths;
use crate::storage::connection::open_rw;
use crate::storage::entities;
use serde::Serialize;

#[derive(clap::Args)]
#[command(after_long_help = "EXAMPLES:\n  \
    # Remove a specific relationship between two entities\n  \
    sqlite-graphrag unlink --from oauth-flow --to refresh-tokens --relation related\n\n  \
    # Remove ALL relationships between two entities (any relation type)\n  \
    sqlite-graphrag unlink --from oauth-flow --to refresh-tokens\n\n  \
    # Remove ALL relationships where an entity is source or target\n  \
    sqlite-graphrag unlink --entity oauth-flow --all\n\n  \
NOTE:\n  \
    --from and --to expect ENTITY names (graph nodes), not memory names.\n  \
    To inspect current entities and relationships, run: sqlite-graphrag graph --format json")]
pub struct UnlinkArgs {
    /// Source ENTITY name (graph node, not memory). Also accepts the aliases `--source` and `--name`.
    /// To list current entities run `graph --format json | jaq '.nodes[].name'`.
    #[arg(long, alias = "source", alias = "name", conflicts_with = "entity")]
    pub from: Option<String>,
    /// Target ENTITY name (graph node, not memory). Also accepts the alias `--target`.
    #[arg(long, alias = "target", conflicts_with = "entity")]
    pub to: Option<String>,
    /// Relation type to remove. When omitted with --from/--to, ALL relationships between
    /// those two entities are deleted. Accepts canonical values (e.g. uses, depends-on)
    /// or any custom snake_case/kebab-case string.
    #[arg(long, value_parser = crate::parsers::parse_relation, value_name = "RELATION")]
    pub relation: Option<String>,
    /// Entity name. Combine with --all to remove every relationship of that
    /// entity, or with --memory to remove the curated memory↔entity binding.
    #[arg(long, conflicts_with_all = ["from", "to"])]
    pub entity: Option<String>,
    /// When combined with --entity, removes ALL relationships where that entity is source or target.
    #[arg(long, requires = "entity")]
    pub all: bool,
    /// GAP-SG-52: memory name. Combine with --entity to surgically remove the
    /// curated `memory_entities` binding for that (memory, entity) pair —
    /// covering bindings created via `remember --graph-stdin` that `prune-ner`
    /// would not target selectively.
    #[arg(long, requires = "entity", conflicts_with_all = ["from", "to", "all"], value_name = "NAME")]
    pub memory: Option<String>,
    #[arg(long)]
    pub namespace: Option<String>,
    #[arg(long, value_enum, default_value = "json")]
    pub format: OutputFormat,
    #[arg(long, hide = true, help = "No-op; JSON is always emitted on stdout")]
    pub json: bool,
    #[arg(long, env = "SQLITE_GRAPHRAG_DB_PATH")]
    pub db: Option<String>,
}

#[derive(Serialize)]
struct UnlinkResponse {
    action: String,
    from_name: String,
    to_name: String,
    relation: String,
    relationships_removed: u64,
    namespace: String,
    /// Total execution time in milliseconds from handler start to serialisation.
    elapsed_ms: u64,
}

pub fn run(args: UnlinkArgs) -> Result<(), AppError> {
    let inicio = std::time::Instant::now();
    let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
    let paths = AppPaths::resolve(args.db.as_deref())?;

    crate::storage::connection::ensure_db_ready(&paths)?;

    if let Some(relation_str) = &args.relation {
        crate::parsers::warn_if_non_canonical(relation_str);
    }

    let mut conn = open_rw(&paths.db)?;

    // GAP-SG-52: --memory <name> --entity <name> → remove the curated
    // memory↔entity binding for that pair (the `memory_entities` junction row).
    if let Some(memory_name) = args.memory.as_deref() {
        let entity_name = args.entity.as_deref().ok_or_else(|| {
            AppError::Validation("--entity is required when --memory is used".to_string())
        })?;
        let memory_id = crate::storage::memories::find_by_name(&conn, &namespace, memory_name)?
            .map(|(id, _, _)| id)
            .ok_or_else(|| AppError::MemoryNotFound {
                name: memory_name.to_string(),
                namespace: namespace.clone(),
            })?;
        let entity_id =
            entities::find_entity_id(&conn, &namespace, entity_name)?.ok_or_else(|| {
                AppError::NotFound(errors_msg::entity_not_found(entity_name, &namespace))
            })?;

        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
        let removed = entities::unlink_memory_entity(&tx, memory_id, entity_id)?;
        entities::recalculate_degree(&tx, entity_id)?;
        tx.commit()?;

        conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;

        let response = UnlinkResponse {
            action: if removed > 0 {
                "deleted".to_string()
            } else {
                "noop".to_string()
            },
            from_name: memory_name.to_string(),
            to_name: entity_name.to_string(),
            relation: "memory-entity".to_string(),
            relationships_removed: removed,
            namespace: namespace.clone(),
            elapsed_ms: inicio.elapsed().as_millis() as u64,
        };

        match args.format {
            OutputFormat::Json => output::emit_json(&response)?,
            OutputFormat::Text | OutputFormat::Markdown => {
                output::emit_text(&format!(
                    "{}: memory '{}' --[memory-entity]--> entity '{}' removed {} binding(s) [{}]",
                    response.action,
                    response.from_name,
                    response.to_name,
                    response.relationships_removed,
                    response.namespace
                ));
            }
        }
        return Ok(());
    }

    // --entity without --all or --memory is ambiguous: reject loudly.
    if args.entity.is_some() && !args.all {
        return Err(AppError::Validation(
            "--entity must be combined with --all (remove all relationships) or --memory <name> (remove a memory↔entity binding)"
                .to_string(),
        ));
    }

    // Mode: --entity --all → delete every relationship for that entity.
    if args.all {
        let entity_name = args.entity.as_deref().unwrap_or("");
        let entity_id =
            entities::find_entity_id(&conn, &namespace, entity_name)?.ok_or_else(|| {
                AppError::NotFound(errors_msg::entity_not_found(entity_name, &namespace))
            })?;

        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
        let removed = delete_all_entity_relationships(&tx, entity_id)?;
        entities::recalculate_degree(&tx, entity_id)?;
        tx.commit()?;

        conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;

        let response = UnlinkResponse {
            action: "deleted".to_string(),
            from_name: entity_name.to_string(),
            to_name: "*".to_string(),
            relation: "*".to_string(),
            relationships_removed: removed,
            namespace: namespace.clone(),
            elapsed_ms: inicio.elapsed().as_millis() as u64,
        };

        match args.format {
            OutputFormat::Json => output::emit_json(&response)?,
            OutputFormat::Text | OutputFormat::Markdown => {
                output::emit_text(&format!(
                    "deleted: {} --[*]--> * removed {} relationship(s) [{}]",
                    response.from_name, response.relationships_removed, response.namespace
                ));
            }
        }
        return Ok(());
    }

    // Mode: --from/--to (with optional --relation).
    let from_name = args.from.as_deref().ok_or_else(|| {
        AppError::Validation("--from is required when --entity/--all is not used".to_string())
    })?;
    let to_name = args.to.as_deref().ok_or_else(|| {
        AppError::Validation("--to is required when --entity/--all is not used".to_string())
    })?;

    let source_id = entities::find_entity_id(&conn, &namespace, from_name)?
        .ok_or_else(|| AppError::NotFound(errors_msg::entity_not_found(from_name, &namespace)))?;
    let target_id = entities::find_entity_id(&conn, &namespace, to_name)?
        .ok_or_else(|| AppError::NotFound(errors_msg::entity_not_found(to_name, &namespace)))?;

    let (removed, relation_display) = if let Some(rel) = args.relation.as_deref() {
        // Single-relation mode: exact match required.
        let row =
            entities::find_relationship(&conn, source_id, target_id, rel)?.ok_or_else(|| {
                AppError::NotFound(errors_msg::relationship_not_found(
                    from_name, rel, to_name, &namespace,
                ))
            })?;

        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
        entities::delete_relationship_by_id(&tx, row.id)?;
        entities::recalculate_degree(&tx, source_id)?;
        entities::recalculate_degree(&tx, target_id)?;
        tx.commit()?;

        (1u64, rel.to_string())
    } else {
        // Bulk mode: delete all relationships between from and to.
        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
        let count = delete_relationships_between(&tx, source_id, target_id)?;
        entities::recalculate_degree(&tx, source_id)?;
        entities::recalculate_degree(&tx, target_id)?;
        tx.commit()?;

        (count, "*".to_string())
    };

    conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;

    let response = UnlinkResponse {
        action: "deleted".to_string(),
        from_name: from_name.to_string(),
        to_name: to_name.to_string(),
        relation: relation_display.clone(),
        relationships_removed: removed,
        namespace: namespace.clone(),
        elapsed_ms: inicio.elapsed().as_millis() as u64,
    };

    match args.format {
        OutputFormat::Json => output::emit_json(&response)?,
        OutputFormat::Text | OutputFormat::Markdown => {
            output::emit_text(&format!(
                "deleted: {} --[{}]--> {} removed {} relationship(s) [{}]",
                response.from_name,
                response.relation,
                response.to_name,
                response.relationships_removed,
                response.namespace
            ));
        }
    }

    Ok(())
}

/// Deletes all relationships where `entity_id` is source or target.
/// Returns the number of rows removed.
fn delete_all_entity_relationships(
    conn: &rusqlite::Connection,
    entity_id: i64,
) -> Result<u64, AppError> {
    // Collect IDs first to clean up memory_relationships junction.
    let mut stmt =
        conn.prepare_cached("SELECT id FROM relationships WHERE source_id = ?1 OR target_id = ?1")?;
    let ids: Vec<i64> = stmt
        .query_map(rusqlite::params![entity_id], |r| r.get(0))?
        .collect::<rusqlite::Result<Vec<_>>>()?;

    let count = ids.len() as u64;
    for rel_id in ids {
        conn.execute(
            "DELETE FROM memory_relationships WHERE relationship_id = ?1",
            rusqlite::params![rel_id],
        )?;
        conn.execute(
            "DELETE FROM relationships WHERE id = ?1",
            rusqlite::params![rel_id],
        )?;
    }
    Ok(count)
}

/// Deletes all relationships between `source_id` and `target_id` (any relation type).
/// Returns the number of rows removed.
fn delete_relationships_between(
    conn: &rusqlite::Connection,
    source_id: i64,
    target_id: i64,
) -> Result<u64, AppError> {
    let mut stmt = conn
        .prepare_cached("SELECT id FROM relationships WHERE source_id = ?1 AND target_id = ?2")?;
    let ids: Vec<i64> = stmt
        .query_map(rusqlite::params![source_id, target_id], |r| r.get(0))?
        .collect::<rusqlite::Result<Vec<_>>>()?;

    let count = ids.len() as u64;
    for rel_id in ids {
        conn.execute(
            "DELETE FROM memory_relationships WHERE relationship_id = ?1",
            rusqlite::params![rel_id],
        )?;
        conn.execute(
            "DELETE FROM relationships WHERE id = ?1",
            rusqlite::params![rel_id],
        )?;
    }
    Ok(count)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn unlink_response_serializes_all_fields() {
        let resp = UnlinkResponse {
            action: "deleted".to_string(),
            from_name: "entity-a".to_string(),
            to_name: "entity-b".to_string(),
            relation: "uses".to_string(),
            relationships_removed: 1,
            namespace: "global".to_string(),
            elapsed_ms: 5,
        };
        let json = serde_json::to_value(&resp).expect("serialization failed");
        assert_eq!(json["action"], "deleted");
        assert_eq!(json["from_name"], "entity-a");
        assert_eq!(json["to_name"], "entity-b");
        assert_eq!(json["relation"], "uses");
        assert_eq!(json["relationships_removed"], 1u64);
        assert_eq!(json["namespace"], "global");
        assert_eq!(json["elapsed_ms"], 5u64);
    }

    #[test]
    fn unlink_response_action_must_be_deleted() {
        let resp = UnlinkResponse {
            action: "deleted".to_string(),
            from_name: "a".to_string(),
            to_name: "b".to_string(),
            relation: "related".to_string(),
            relationships_removed: 1,
            namespace: "global".to_string(),
            elapsed_ms: 0,
        };
        let json = serde_json::to_value(&resp).expect("serialization failed");
        assert_eq!(
            json["action"], "deleted",
            "unlink action must always be 'deleted'"
        );
    }

    #[test]
    fn unlink_response_bulk_uses_wildcard_relation() {
        let resp = UnlinkResponse {
            action: "deleted".to_string(),
            from_name: "origin".to_string(),
            to_name: "destination".to_string(),
            relation: "*".to_string(),
            relationships_removed: 3,
            namespace: "project".to_string(),
            elapsed_ms: 3,
        };
        let json = serde_json::to_value(&resp).expect("serialization failed");
        assert_eq!(json["relation"], "*");
        assert_eq!(json["relationships_removed"], 3u64);
    }

    #[test]
    fn unlink_response_entity_all_uses_wildcard_to() {
        let resp = UnlinkResponse {
            action: "deleted".to_string(),
            from_name: "oauth-flow".to_string(),
            to_name: "*".to_string(),
            relation: "*".to_string(),
            relationships_removed: 5,
            namespace: "global".to_string(),
            elapsed_ms: 2,
        };
        let json = serde_json::to_value(&resp).expect("serialization failed");
        assert_eq!(json["to_name"], "*");
        assert_eq!(json["relation"], "*");
        assert_eq!(json["relationships_removed"], 5u64);
    }

    // GAP-SG-52: `unlink --memory M --entity E` parses into the binding mode.
    #[test]
    fn unlink_memory_entity_binding_mode_parses() {
        use crate::cli::{Cli, Commands};
        use clap::Parser;
        let cli = Cli::try_parse_from([
            "sqlite-graphrag",
            "unlink",
            "--memory",
            "my-mem",
            "--entity",
            "jwt-token",
        ])
        .expect("parse");
        match cli.command {
            Some(Commands::Unlink(a)) => {
                assert_eq!(a.memory.as_deref(), Some("my-mem"));
                assert_eq!(a.entity.as_deref(), Some("jwt-token"));
                assert!(!a.all);
            }
            other => panic!("expected unlink, got {other:?}"),
        }
    }

    #[test]
    fn unlink_response_relationships_removed_field_present() {
        let resp = UnlinkResponse {
            action: "deleted".to_string(),
            from_name: "a".to_string(),
            to_name: "b".to_string(),
            relation: "uses".to_string(),
            relationships_removed: 0,
            namespace: "global".to_string(),
            elapsed_ms: 0,
        };
        let json = serde_json::to_value(&resp).expect("serialization failed");
        assert!(
            json.get("relationships_removed").is_some(),
            "relationships_removed field must be present"
        );
    }
}