sqlite_graphrag/lib.rs
1//! # sqlite-graphrag
2//!
3//! Local GraphRAG memory for LLMs in a single SQLite file — zero external
4//! services required.
5//!
6//! `sqlite-graphrag` is a CLI-first library that persists memories, entities and
7//! typed relationships inside a single SQLite database. It combines FTS5
8//! full-text search with `sqlite-vec` KNN over locally-generated embeddings to
9//! expose a hybrid retrieval ranker tailored for LLM agents.
10//!
11//! ## CLI usage
12//!
13//! Install and initialize once, then save and recall memories:
14//!
15//! ```bash
16//! cargo install sqlite-graphrag
17//! sqlite-graphrag init
18//! sqlite-graphrag remember \
19//! --name onboarding-note \
20//! --type user \
21//! --description "first memory" \
22//! --body "hello graphrag"
23//! sqlite-graphrag recall "graphrag" --k 5
24//! ```
25//!
26//! ## Crate layout
27//!
28//! The public modules group the CLI, the SQLite storage layer and the
29//! supporting primitives (embedder, chunking, graph, namespace detection,
30//! output, paths and pragmas). The CLI binary wires them together through the
31//! commands in [`commands`].
32//!
33//! ## Exit codes
34//!
35//! Errors returned from [`errors::AppError`] map to deterministic exit codes
36//! suitable for orchestration by shell scripts and LLM agents. Consult the
37//! README for the full contract.
38
39use std::sync::atomic::{AtomicBool, Ordering};
40
41/// Sinaliza que um sinal de encerramento (SIGINT / SIGTERM / SIGHUP) foi recebido.
42///
43/// Definido em `main` via `ctrlc::set_handler`. Subcomandos de longa duração podem
44/// consultar [`shutdown_requested`] para encerrar gracefully antes do timeout.
45pub static SHUTDOWN: AtomicBool = AtomicBool::new(false);
46
47/// Retorna `true` se um sinal de encerramento foi recebido desde o início do processo.
48///
49/// O valor reflete o estado de [`SHUTDOWN`]. Sem chamada a `ctrlc::set_handler`,
50/// o estado inicial é sempre `false`.
51///
52/// # Examples
53///
54/// ```
55/// use sqlite_graphrag::shutdown_requested;
56///
57/// // Em condições normais de inicialização o sinal não foi recebido.
58/// assert!(!shutdown_requested());
59/// ```
60///
61/// ```
62/// use std::sync::atomic::Ordering;
63/// use sqlite_graphrag::{SHUTDOWN, shutdown_requested};
64///
65/// // Simula recebimento de sinal e verifica que a função reflete o estado.
66/// SHUTDOWN.store(true, Ordering::SeqCst);
67/// assert!(shutdown_requested());
68/// // Restaura para não contaminar outros testes.
69/// SHUTDOWN.store(false, Ordering::SeqCst);
70/// ```
71pub fn shutdown_requested() -> bool {
72 SHUTDOWN.load(Ordering::SeqCst)
73}
74
75/// Token-aware chunking utilities for bodies that exceed the embedding window.
76pub mod chunking;
77
78/// `clap` definitions for the top-level `sqlite-graphrag` binary.
79pub mod cli;
80
81/// Subcommand handlers wired into the `clap` tree from [`cli`].
82pub mod commands;
83
84/// Compile-time constants: embedding dimensions, limits and thresholds.
85pub mod constants;
86
87/// Local embedding generation backed by `fastembed`.
88pub mod embedder;
89
90/// Library-wide error type and the mapping to process exit codes (see [`errors::AppError`]).
91pub mod errors;
92
93/// Graph traversal helpers over the entities and relationships tables.
94pub mod graph;
95
96/// Bilingual message layer for human-facing stderr progress (`--lang en|pt`, `SQLITE_GRAPHRAG_LANG`).
97pub mod i18n;
98
99/// Semáforo de contagem via lock files para limitar invocações paralelas (veja [`lock::acquire_cli_slot`]).
100pub mod lock;
101
102/// Guarda de memória: verifica disponibilidade de RAM antes de carregar o modelo ONNX.
103pub mod memory_guard;
104
105/// Namespace resolution with precedence between flag, environment and markers.
106pub mod namespace;
107
108/// Centralized stdout/stderr emitters for CLI output formatting.
109pub mod output;
110
111/// Parser de argumentos dual-format: aceita Unix epoch e RFC 3339.
112pub mod parsers;
113
114/// Filesystem paths for the project-local database and app support directories.
115pub mod paths;
116
117/// SQLite pragma helpers applied on every connection.
118pub mod pragmas;
119
120/// Persistence layer: memories, entities, chunks and version history.
121pub mod storage;
122
123/// Fuso horário de exibição para campos `*_iso` (flag `--tz`, env `SQLITE_GRAPHRAG_DISPLAY_TZ`, fallback UTC).
124pub mod tz;
125
126mod embedded_migrations {
127 use refinery::embed_migrations;
128 embed_migrations!("migrations");
129}
130
131pub use embedded_migrations::migrations;