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
use crate::commands::*;
use crate::i18n::{current, Language};
use clap::{Parser, Subcommand};
/// Retorna o número máximo de invocações simultâneas permitidas pela heurística de CPU.
fn max_concurrency_ceiling() -> usize {
std::thread::available_parallelism()
.map(|n| n.get() * 2)
.unwrap_or(8)
}
#[derive(Copy, Clone, Debug, clap::ValueEnum)]
pub enum RelationKind {
AppliesTo,
Uses,
DependsOn,
Causes,
Fixes,
Contradicts,
Supports,
Follows,
Related,
Mentions,
Replaces,
TrackedIn,
}
impl RelationKind {
pub fn as_str(&self) -> &'static str {
match self {
Self::AppliesTo => "applies_to",
Self::Uses => "uses",
Self::DependsOn => "depends_on",
Self::Causes => "causes",
Self::Fixes => "fixes",
Self::Contradicts => "contradicts",
Self::Supports => "supports",
Self::Follows => "follows",
Self::Related => "related",
Self::Mentions => "mentions",
Self::Replaces => "replaces",
Self::TrackedIn => "tracked_in",
}
}
}
#[derive(Copy, Clone, Debug, clap::ValueEnum)]
pub enum GraphExportFormat {
Json,
Dot,
Mermaid,
}
#[derive(Parser)]
#[command(name = "sqlite-graphrag")]
#[command(version)]
#[command(about = "Local GraphRAG memory for LLMs in a single SQLite file")]
#[command(arg_required_else_help = true)]
pub struct Cli {
/// Número máximo de invocações CLI simultâneas permitidas (default: 4).
///
/// Limita o semáforo de contagem de slots de concorrência. O valor é restrito
/// ao intervalo [1, 2×nCPUs]. Valores acima do teto são rejeitados com exit 2.
#[arg(long, global = true, value_name = "N")]
pub max_concurrency: Option<usize>,
/// Aguardar até SECONDS por um slot livre antes de desistir (exit 75).
///
/// Útil em pipelines de agentes que fazem retry: a instância faz polling a
/// cada 500 ms até o timeout ou um slot abrir. Default: 300s (5 minutos).
#[arg(long, global = true, value_name = "SECONDS")]
pub wait_lock: Option<u64>,
/// Pular a verificação de memória disponível antes de carregar o modelo.
///
/// Uso exclusivo em testes automatizados onde a alocação real não ocorre.
#[arg(long, global = true, hide = true, default_value_t = false)]
pub skip_memory_guard: bool,
/// Idioma das mensagens humanas (stderr). Aceita `en` ou `pt`.
///
/// Sem a flag, detecta via env `SQLITE_GRAPHRAG_LANG` e depois `LC_ALL`/`LANG`.
/// JSON de stdout é determinístico e idêntico entre idiomas — apenas
/// strings destinadas a humanos são afetadas.
#[arg(long, global = true, value_enum, value_name = "LANG")]
pub lang: Option<crate::i18n::Language>,
/// Fuso horário para campos `*_iso` no JSON de saída (ex: `America/Sao_Paulo`).
///
/// Aceita qualquer nome IANA da IANA Time Zone Database. Sem a flag, usa
/// `SQLITE_GRAPHRAG_DISPLAY_TZ`; se ausente, usa UTC. Não afeta campos epoch inteiros.
#[arg(long, global = true, value_name = "IANA")]
pub tz: Option<chrono_tz::Tz>,
#[command(subcommand)]
pub command: Commands,
}
impl Cli {
/// Valida flags de concorrência e retorna erro descritivo localizado se inválidas.
///
/// Requer que `crate::i18n::init()` já tenha sido chamado (ocorre antes desta função
/// no fluxo de `main`). Em inglês emite mensagens EN; em português emite PT.
pub fn validate_flags(&self) -> Result<(), String> {
if let Some(n) = self.max_concurrency {
if n == 0 {
return Err(match current() {
Language::English => "--max-concurrency must be >= 1".to_string(),
Language::Portugues => "--max-concurrency deve ser >= 1".to_string(),
});
}
let teto = max_concurrency_ceiling();
if n > teto {
return Err(match current() {
Language::English => format!(
"--max-concurrency {n} exceeds the ceiling of {teto} (2×nCPUs) on this system"
),
Language::Portugues => format!(
"--max-concurrency {n} excede o teto de {teto} (2×nCPUs) neste sistema"
),
});
}
}
Ok(())
}
}
#[derive(Subcommand)]
pub enum Commands {
/// Initialize database and download embedding model
Init(init::InitArgs),
/// Save a memory with optional entity graph
Remember(remember::RememberArgs),
/// Search memories semantically
Recall(recall::RecallArgs),
/// Read a memory by exact name
Read(read::ReadArgs),
/// List memories with filters
List(list::ListArgs),
/// Soft-delete a memory
Forget(forget::ForgetArgs),
/// Permanently delete soft-deleted memories
Purge(purge::PurgeArgs),
/// Rename a memory preserving history
Rename(rename::RenameArgs),
/// Edit a memory's body or description
Edit(edit::EditArgs),
/// List all versions of a memory
History(history::HistoryArgs),
/// Restore a memory to a previous version
Restore(restore::RestoreArgs),
/// Search using hybrid vector + full-text search
HybridSearch(hybrid_search::HybridSearchArgs),
/// Show database health
Health(health::HealthArgs),
/// Apply pending schema migrations
Migrate(migrate::MigrateArgs),
/// Resolve namespace precedence for the current invocation
NamespaceDetect(namespace_detect::NamespaceDetectArgs),
/// Run PRAGMA optimize on the database
Optimize(optimize::OptimizeArgs),
/// Show database statistics
Stats(stats::StatsArgs),
/// Create a checkpointed copy safe for file sync
SyncSafeCopy(sync_safe_copy::SyncSafeCopyArgs),
/// Run VACUUM after checkpointing the WAL
Vacuum(vacuum::VacuumArgs),
/// Create an explicit relationship between two entities
Link(link::LinkArgs),
/// Remove a specific relationship between two entities
Unlink(unlink::UnlinkArgs),
/// List memories connected via the entity graph
Related(related::RelatedArgs),
/// Export a graph snapshot in json, dot or mermaid
Graph(graph_export::GraphArgs),
/// Remove entities that have no memories and no relationships
CleanupOrphans(cleanup_orphans::CleanupOrphansArgs),
#[command(name = "__debug_schema", hide = true)]
DebugSchema(debug_schema::DebugSchemaArgs),
}
#[derive(Copy, Clone, Debug, clap::ValueEnum)]
pub enum MemoryType {
User,
Feedback,
Project,
Reference,
Decision,
Incident,
Skill,
}
impl MemoryType {
pub fn as_str(&self) -> &'static str {
match self {
Self::User => "user",
Self::Feedback => "feedback",
Self::Project => "project",
Self::Reference => "reference",
Self::Decision => "decision",
Self::Incident => "incident",
Self::Skill => "skill",
}
}
}