Skip to main content

sqlite_graphrag/i18n/validation/
app_error_pt.rs

1/// Localized `validation` message wrapping `msg`.
2pub fn validation(msg: &str) -> String {
3    format!("erro de validação: {msg}")
4}
5
6/// Localized `duplicate` message wrapping `msg`.
7pub fn duplicate(msg: &str) -> String {
8    let translated = msg
9        .replace("already exists in namespace", "já existe no namespace")
10        .replace(
11            "exists but is soft-deleted in namespace",
12            "existe mas está excluída temporariamente no namespace",
13        )
14        .replace(
15            "Use --force-merge to update.",
16            "Use --force-merge para atualizar.",
17        )
18        .replace(
19            "use --force-merge to restore and update, or `restore` to revive it",
20            "use --force-merge para restaurar e atualizar, ou `restore` para revivê-la",
21        )
22        .replace("memory", "memória");
23    format!("duplicata detectada: {translated}")
24}
25
26/// Localized `conflict` message wrapping `msg`.
27pub fn conflict(msg: &str) -> String {
28    let translated = msg
29        .replace("optimistic lock conflict", "conflito de lock otimista")
30        .replace("but current is", "mas atual é")
31        .replace(
32            "was modified by another process",
33            "foi modificada por outro processo",
34        );
35    format!("conflito: {translated}")
36}
37
38/// Localized `not_found` message wrapping `msg`.
39pub fn not_found(msg: &str) -> String {
40    // G55 T3: add replacements for the read.rs format produced by the
41    // T1 fix: `memory not found: name='X' in namespace 'Y'`.
42    // The existing chain did not catch ` in namespace '` when broken
43    // by the name label, leaving a bilingual hybrid. New patterns
44    // must run BEFORE the catch-all `memory` → `memória` to avoid
45    // being shadowed.
46    let translated = msg
47        .replace("memory not found:", "memória não encontrada:")
48        .replace("not found in namespace", "não encontrada no namespace")
49        .replace("not found for memory", "não encontrada para memória")
50        .replace("does not exist in namespace", "não existe no namespace")
51        .replace("memory or entity", "memória ou entidade")
52        .replace("name='", "nome='")
53        .replace("memory", "memória")
54        .replace("entity", "entidade")
55        .replace(" in namespace '", " no namespace '")
56        .replace("version", "versão")
57        .replace("soft-deleted", "excluída temporariamente");
58    format!("não encontrado: {translated}")
59}
60
61// G55 S2 (v1.0.80): structured variant helpers. They synthesize the
62// canonical English message and feed it through the `not_found`
63// replace-chain so the pt-BR translation stays in one place.
64/// Localized message for `memory_not_found`.
65pub fn memory_not_found(name: &str, namespace: &str) -> String {
66    not_found(&format!(
67        "memory not found: name='{name}' in namespace '{namespace}'"
68    ))
69}
70
71/// Localized message for `memory_not_found_by_id`.
72pub fn memory_not_found_by_id(id: i64) -> String {
73    not_found(&format!("memory not found: id={id}"))
74}
75
76// GAP-SG-78: transitory entity absence (materialized on a later enrich
77// pass). Own pt-BR string, distinct from the terminal not-found chain.
78/// Localized message for `entity_not_yet_materialized`.
79pub fn entity_not_yet_materialized(name: &str, namespace: &str) -> String {
80    format!("entidade '{name}' ainda não materializada no namespace '{namespace}'")
81}
82
83/// Localized message for `namespace_error`.
84pub fn namespace_error(msg: &str) -> String {
85    format!("namespace não resolvido: {msg}")
86}
87
88/// Localized message for `limit_exceeded`.
89pub fn limit_exceeded(msg: &str) -> String {
90    let translated = msg
91        .replace("exceeds limit of", "excede limite de")
92        .replace("body exceeds", "corpo excede")
93        .replace("entities exceed limit", "entidades excedem limite")
94        .replace(
95            "relationships exceed limit",
96            "relacionamentos excedem limite",
97        );
98    format!("limite excedido: {translated}")
99}
100
101// v1.1.1 (P11): typed ceiling variants. Own pt-BR strings mirroring
102// the English `#[error]` text of `BodyTooLarge`/`TooManyChunks`,
103// naming the constant so the operator knows WHICH cap fired.
104/// Localized message for `body_too_large`.
105pub fn body_too_large(bytes: u64, limit: u64) -> String {
106    format!(
107        "limite excedido: corpo tem {bytes} bytes, acima do teto de {limit} bytes \
108         (MAX_MEMORY_BODY_LEN); divida o conteúdo em múltiplas memórias"
109    )
110}
111
112/// Too many chunks.
113pub fn too_many_chunks(chunks: usize, limit: usize) -> String {
114    format!(
115        "limite excedido: documento produz {chunks} chunks, acima do teto de {limit} \
116         chunks (REMEMBER_MAX_SAFE_MULTI_CHUNKS); divida o documento antes da escrita"
117    )
118}
119
120// v1.1.2 (Gap 2): third typed payload ceiling — token cap, mirroring
121// the English `#[error]` text of `TooManyTokens`.
122/// Too many tokens.
123pub fn too_many_tokens(tokens: u64, limit: u64) -> String {
124    format!(
125        "limite excedido: corpo tem {tokens} tokens (estimado), acima do teto de \
126         {limit} tokens (EMBEDDING_REQUEST_MAX_TOKENS); divida o conteúdo em \
127         múltiplas memórias"
128    )
129}
130
131/// Database.
132pub fn database(err: &str) -> String {
133    format!("erro de banco de dados: {err}")
134}
135
136/// Embedding.
137pub fn embedding(msg: &str) -> String {
138    format!("erro de embedding: {msg}")
139}
140
141/// VEC extension.
142pub fn vec_extension(msg: &str) -> String {
143    format!("extensão sqlite-vec falhou: {msg}")
144}
145
146/// Provider error.
147pub fn provider_error(code: &str, message: &str) -> String {
148    format!("erro do provedor (código {code}): {message}")
149}
150
151/// DB busy.
152pub fn db_busy(msg: &str) -> String {
153    format!("banco ocupado: {msg}")
154}
155
156/// Batch partial failure.
157pub fn batch_partial_failure(total: usize, failed: usize) -> String {
158    format!("falha parcial em batch: {failed} de {total} itens falharam")
159}
160
161/// IO.
162pub fn io(err: &str) -> String {
163    format!("erro de I/O: {err}")
164}
165
166/// Internal.
167pub fn internal(err: &str) -> String {
168    format!("erro interno: {err}")
169}
170
171/// JSON.
172pub fn json(err: &str) -> String {
173    format!("erro de JSON: {err}")
174}
175
176/// Lock busy.
177pub fn lock_busy(msg: &str) -> String {
178    format!("lock ocupado: {msg}")
179}
180
181/// All slots full.
182pub fn all_slots_full(max: usize, waited_secs: u64) -> String {
183    format!(
184        "todos os {max} slots de concorrência ocupados após aguardar {waited_secs}s \
185         (exit 75); use --max-concurrency ou aguarde outras invocações terminarem"
186    )
187}
188
189/// Job singleton locked.
190pub fn job_singleton_locked(job_type: &str, namespace: &str) -> String {
191    format!(
192        "job {job_type} para o namespace '{namespace}' já está em execução (exit 75); \
193         aguarde a conclusão ou passe --wait-job-singleton <SEGUNDOS>"
194    )
195}
196
197/// Embedding singleton locked.
198pub fn embedding_singleton_locked(namespace: &str) -> String {
199    format!(
200        "singleton de embedding para o namespace '{namespace}' já está retido (exit 75); \
201         outra CLI está chamando o LLM neste banco; passe --wait-embed-singleton <SEGUNDOS> para aguardar"
202    )
203}
204
205/// Low memory.
206pub fn low_memory(available_mb: u64, required_mb: u64) -> String {
207    format!(
208        "memória disponível ({available_mb}MB) abaixo do mínimo requerido ({required_mb}MB) \
209         para carregar o modelo; aborte outras cargas ou use --skip-memory-guard (exit 77)"
210    )
211}
212
213/// Shutdown.
214pub fn shutdown(signal: &str) -> String {
215    format!("sinal de desligamento recebido: {signal}; operação cancelada pelo usuário (exit 19)")
216}
217
218/// Preflight failed.
219pub fn preflight_failed(detail: &str) -> String {
220    format!(
221        "validação pré-execução falhou (exit 16): {detail}; corrija a condição e tente novamente (config set spawn.skip_preflight=1 desabilita em emergências)"
222    )
223}
224
225/// Localized message for `binary_not_found`.
226pub fn binary_not_found(name: &str) -> String {
227    format!("binário não encontrado: {name} — instale e adicione ao PATH")
228}
229
230/// Rate limited.
231pub fn rate_limited(detail: &str) -> String {
232    format!("taxa de requisição excedida: {detail}")
233}
234
235/// Timeout.
236pub fn timeout(operation: &str, secs: u64) -> String {
237    format!("timeout após {secs}s: {operation}")
238}