Skip to main content

sqlite_graphrag/commands/
remember.rs

1use crate::chunking;
2use crate::cli::MemoryType;
3use crate::errors::AppError;
4use crate::i18n::erros;
5use crate::output::{self, JsonOutputFormat, RememberResponse};
6use crate::paths::AppPaths;
7use crate::storage::chunks as storage_chunks;
8use crate::storage::connection::{ensure_schema, open_rw};
9use crate::storage::entities::{NewEntity, NewRelationship};
10use crate::storage::memories::NewMemory;
11use crate::storage::{entities, memories, versions};
12use serde::Deserialize;
13use std::io::Read as _;
14
15#[derive(clap::Args)]
16pub struct RememberArgs {
17    /// Memory name in kebab-case (lowercase letters, digits, hyphens).
18    /// Acts as unique key within the namespace; collisions trigger merge or rejection.
19    #[arg(long)]
20    pub name: String,
21    #[arg(
22        long,
23        value_enum,
24        long_help = "Memory kind stored in `memories.type`. This is NOT the graph `entity_type` used in `--entities-file`. Valid values: user, feedback, project, reference, decision, incident, skill."
25    )]
26    pub r#type: MemoryType,
27    /// Short description (≤500 chars) summarizing the memory for use in `list` and `recall` snippets.
28    #[arg(long)]
29    pub description: String,
30    /// Inline body content. Mutually exclusive with --body-file, --body-stdin, --graph-stdin.
31    /// Maximum 512000 bytes; rejected if empty without an external graph.
32    #[arg(
33        long,
34        conflicts_with_all = ["body_file", "body_stdin", "graph_stdin"]
35    )]
36    pub body: Option<String>,
37    #[arg(
38        long,
39        help = "Read body from a file instead of --body",
40        conflicts_with_all = ["body", "body_stdin", "graph_stdin"]
41    )]
42    pub body_file: Option<std::path::PathBuf>,
43    /// Read body from stdin until EOF. Useful in pipes (echo "..." | sqlite-graphrag remember ...).
44    /// Mutually exclusive with --body, --body-file, --graph-stdin.
45    #[arg(
46        long,
47        conflicts_with_all = ["body", "body_file", "graph_stdin"]
48    )]
49    pub body_stdin: bool,
50    #[arg(
51        long,
52        help = "JSON file containing entities to associate with this memory"
53    )]
54    pub entities_file: Option<std::path::PathBuf>,
55    #[arg(
56        long,
57        help = "JSON file containing relationships to associate with this memory"
58    )]
59    pub relationships_file: Option<std::path::PathBuf>,
60    #[arg(
61        long,
62        help = "Read graph JSON (body + entities + relationships) from stdin",
63        conflicts_with_all = [
64            "body",
65            "body_file",
66            "body_stdin",
67            "entities_file",
68            "relationships_file"
69        ]
70    )]
71    pub graph_stdin: bool,
72    #[arg(long, default_value = "global")]
73    pub namespace: Option<String>,
74    /// Inline JSON object with arbitrary metadata key-value pairs. Mutually exclusive with --metadata-file.
75    #[arg(long)]
76    pub metadata: Option<String>,
77    #[arg(long, help = "JSON file containing metadata key-value pairs")]
78    pub metadata_file: Option<std::path::PathBuf>,
79    #[arg(long)]
80    pub force_merge: bool,
81    #[arg(
82        long,
83        value_name = "EPOCH_OR_RFC3339",
84        value_parser = crate::parsers::parse_expected_updated_at,
85        long_help = "Optimistic lock: reject if updated_at does not match. \
86Accepts Unix epoch (e.g. 1700000000) or RFC 3339 (e.g. 2026-04-19T12:00:00Z)."
87    )]
88    pub expected_updated_at: Option<i64>,
89    #[arg(
90        long,
91        help = "Disable automatic entity/relationship extraction from body"
92    )]
93    pub skip_extraction: bool,
94    /// Optional opaque session identifier for tracing memory provenance across multi-agent runs.
95    #[arg(long)]
96    pub session_id: Option<String>,
97    #[arg(long, value_enum, default_value_t = JsonOutputFormat::Json)]
98    pub format: JsonOutputFormat,
99    #[arg(long, help = "No-op; JSON is always emitted on stdout")]
100    pub json: bool,
101    #[arg(long, env = "SQLITE_GRAPHRAG_DB_PATH")]
102    pub db: Option<String>,
103}
104
105#[derive(Deserialize, Default)]
106#[serde(deny_unknown_fields)]
107struct GraphInput {
108    #[serde(default)]
109    body: Option<String>,
110    #[serde(default)]
111    entities: Vec<NewEntity>,
112    #[serde(default)]
113    relationships: Vec<NewRelationship>,
114}
115
116fn normalize_and_validate_graph_input(graph: &mut GraphInput) -> Result<(), AppError> {
117    for entity in &graph.entities {
118        if !is_valid_entity_type(&entity.entity_type) {
119            return Err(AppError::Validation(format!(
120                "entity_type '{}' inválido para entidade '{}'",
121                entity.entity_type, entity.name
122            )));
123        }
124    }
125
126    for rel in &mut graph.relationships {
127        rel.relation = rel.relation.replace('-', "_");
128        if !is_valid_relation(&rel.relation) {
129            return Err(AppError::Validation(format!(
130                "relation '{}' inválida para relacionamento '{}' -> '{}'",
131                rel.relation, rel.source, rel.target
132            )));
133        }
134        if !(0.0..=1.0).contains(&rel.strength) {
135            return Err(AppError::Validation(format!(
136                "strength {} inválido para relacionamento '{}' -> '{}'; esperado valor em [0.0, 1.0]",
137                rel.strength, rel.source, rel.target
138            )));
139        }
140    }
141
142    Ok(())
143}
144
145fn is_valid_entity_type(entity_type: &str) -> bool {
146    matches!(
147        entity_type,
148        "project"
149            | "tool"
150            | "person"
151            | "file"
152            | "concept"
153            | "incident"
154            | "decision"
155            | "memory"
156            | "dashboard"
157            | "issue_tracker"
158    )
159}
160
161fn is_valid_relation(relation: &str) -> bool {
162    matches!(
163        relation,
164        "applies_to"
165            | "uses"
166            | "depends_on"
167            | "causes"
168            | "fixes"
169            | "contradicts"
170            | "supports"
171            | "follows"
172            | "related"
173            | "mentions"
174            | "replaces"
175            | "tracked_in"
176    )
177}
178
179pub fn run(args: RememberArgs) -> Result<(), AppError> {
180    use crate::constants::*;
181
182    let inicio = std::time::Instant::now();
183    let _ = args.format;
184    let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
185
186    // Auto-normalizar para kebab-case antes de validar (P2-H).
187    // v1.0.20: também faz trim de hífens em borda (incluindo trailing) para evitar rejeição
188    // após truncamento por filename longo terminando em hífen.
189    let normalized_name = {
190        let lower = args.name.to_lowercase().replace(['_', ' '], "-");
191        let trimmed = lower.trim_matches('-').to_string();
192        if trimmed != args.name {
193            tracing::warn!(
194                original = %args.name,
195                normalized = %trimmed,
196                "name auto-normalized to kebab-case"
197            );
198        }
199        trimmed
200    };
201
202    if normalized_name.is_empty() || normalized_name.len() > MAX_MEMORY_NAME_LEN {
203        return Err(AppError::Validation(
204            crate::i18n::validacao::nome_comprimento(MAX_MEMORY_NAME_LEN),
205        ));
206    }
207
208    if normalized_name.starts_with("__") {
209        return Err(AppError::Validation(
210            crate::i18n::validacao::nome_reservado(),
211        ));
212    }
213
214    {
215        let slug_re = regex::Regex::new(crate::constants::NAME_SLUG_REGEX)
216            .map_err(|e| AppError::Internal(anyhow::anyhow!("regex: {e}")))?;
217        if !slug_re.is_match(&normalized_name) {
218            return Err(AppError::Validation(crate::i18n::validacao::nome_kebab(
219                &normalized_name,
220            )));
221        }
222    }
223
224    if args.description.len() > MAX_MEMORY_DESCRIPTION_LEN {
225        return Err(AppError::Validation(
226            crate::i18n::validacao::descricao_excede(MAX_MEMORY_DESCRIPTION_LEN),
227        ));
228    }
229
230    let mut raw_body = if let Some(b) = args.body {
231        b
232    } else if let Some(path) = args.body_file {
233        std::fs::read_to_string(&path).map_err(AppError::Io)?
234    } else if args.body_stdin || args.graph_stdin {
235        let mut buf = String::new();
236        std::io::stdin()
237            .read_to_string(&mut buf)
238            .map_err(AppError::Io)?;
239        buf
240    } else {
241        String::new()
242    };
243
244    let entities_provided_externally =
245        args.entities_file.is_some() || args.relationships_file.is_some() || args.graph_stdin;
246
247    let mut graph = GraphInput::default();
248    if let Some(path) = args.entities_file {
249        let content = std::fs::read_to_string(&path).map_err(AppError::Io)?;
250        graph.entities = serde_json::from_str(&content)?;
251    }
252    if let Some(path) = args.relationships_file {
253        let content = std::fs::read_to_string(&path).map_err(AppError::Io)?;
254        graph.relationships = serde_json::from_str(&content)?;
255    }
256    if args.graph_stdin {
257        graph = serde_json::from_str::<GraphInput>(&raw_body).map_err(|e| {
258            AppError::Validation(format!("payload JSON inválido em --graph-stdin: {e}"))
259        })?;
260        raw_body = graph.body.take().unwrap_or_default();
261    }
262
263    if graph.entities.len() > MAX_ENTITIES_PER_MEMORY {
264        return Err(AppError::LimitExceeded(erros::limite_entidades(
265            MAX_ENTITIES_PER_MEMORY,
266        )));
267    }
268    if graph.relationships.len() > MAX_RELATIONSHIPS_PER_MEMORY {
269        return Err(AppError::LimitExceeded(erros::limite_relacionamentos(
270            MAX_RELATIONSHIPS_PER_MEMORY,
271        )));
272    }
273    normalize_and_validate_graph_input(&mut graph)?;
274
275    if raw_body.len() > MAX_MEMORY_BODY_LEN {
276        return Err(AppError::LimitExceeded(
277            crate::i18n::validacao::body_excede(MAX_MEMORY_BODY_LEN),
278        ));
279    }
280
281    // v1.0.22 P1: rejeitar body vazio ou whitespace-only quando não há grafo externo.
282    // Sem este check, embeddings vazios eram persistidos quebrando a semântica de recall.
283    if !entities_provided_externally && graph.entities.is_empty() && raw_body.trim().is_empty() {
284        return Err(AppError::Validation(
285            "body não pode estar vazio: forneça --body, --body-file, --body-stdin com conteúdo, \
286             ou um grafo via --entities-file/--graph-stdin"
287                .to_string(),
288        ));
289    }
290
291    let metadata: serde_json::Value = if let Some(m) = args.metadata {
292        serde_json::from_str(&m)?
293    } else if let Some(path) = args.metadata_file {
294        let content = std::fs::read_to_string(&path).map_err(AppError::Io)?;
295        serde_json::from_str(&content)?
296    } else {
297        serde_json::json!({})
298    };
299
300    let body_hash = blake3::hash(raw_body.as_bytes()).to_hex().to_string();
301    let snippet: String = raw_body.chars().take(200).collect();
302
303    let paths = AppPaths::resolve(args.db.as_deref())?;
304    paths.ensure_dirs()?;
305
306    // v1.0.20: usar .trim().is_empty() para rejeitar bodies que são apenas whitespace.
307    let mut extraction_method: Option<String> = None;
308    if !args.skip_extraction
309        && !entities_provided_externally
310        && graph.entities.is_empty()
311        && !raw_body.trim().is_empty()
312    {
313        match crate::extraction::extract_graph_auto(&raw_body, &paths) {
314            Ok(extracted) => {
315                extraction_method = Some(extracted.extraction_method.clone());
316                graph.entities = extracted.entities;
317                graph.relationships = extracted.relationships;
318
319                if graph.entities.len() > MAX_ENTITIES_PER_MEMORY {
320                    graph.entities.truncate(MAX_ENTITIES_PER_MEMORY);
321                }
322                if graph.relationships.len() > MAX_RELATIONSHIPS_PER_MEMORY {
323                    graph.relationships.truncate(MAX_RELATIONSHIPS_PER_MEMORY);
324                }
325                normalize_and_validate_graph_input(&mut graph)?;
326            }
327            Err(e) => {
328                tracing::warn!("auto-extraction falhou (graceful degradation): {e:#}");
329            }
330        }
331    }
332
333    let mut conn = open_rw(&paths.db)?;
334    ensure_schema(&mut conn)?;
335
336    {
337        use crate::constants::MAX_NAMESPACES_ACTIVE;
338        let active_count: u32 = conn.query_row(
339            "SELECT COUNT(DISTINCT namespace) FROM memories WHERE deleted_at IS NULL",
340            [],
341            |r| r.get::<_, i64>(0).map(|v| v as u32),
342        )?;
343        let ns_exists: bool = conn.query_row(
344            "SELECT EXISTS(SELECT 1 FROM memories WHERE namespace = ?1 AND deleted_at IS NULL)",
345            rusqlite::params![namespace],
346            |r| r.get::<_, i64>(0).map(|v| v > 0),
347        )?;
348        if !ns_exists && active_count >= MAX_NAMESPACES_ACTIVE {
349            return Err(AppError::NamespaceError(format!(
350                "limite de {MAX_NAMESPACES_ACTIVE} namespaces ativos excedido ao tentar criar '{namespace}'"
351            )));
352        }
353    }
354
355    let existing_memory = memories::find_by_name(&conn, &namespace, &normalized_name)?;
356    if existing_memory.is_some() && !args.force_merge {
357        return Err(AppError::Duplicate(erros::memoria_duplicada(
358            &normalized_name,
359            &namespace,
360        )));
361    }
362
363    let duplicate_hash_id = memories::find_by_hash(&conn, &namespace, &body_hash)?;
364
365    output::emit_progress_i18n(
366        &format!(
367            "Remember stage: validated input; available memory {} MB",
368            crate::memory_guard::available_memory_mb()
369        ),
370        &format!(
371            "Etapa remember: entrada validada; memória disponível {} MB",
372            crate::memory_guard::available_memory_mb()
373        ),
374    );
375
376    let tokenizer = crate::tokenizer::get_tokenizer(&paths.models)?;
377    let model_max_length = crate::tokenizer::get_model_max_length(&paths.models)?;
378    let total_passage_tokens = crate::tokenizer::count_passage_tokens(tokenizer, &raw_body)?;
379    let chunks_info = chunking::split_into_chunks_hierarchical(&raw_body, tokenizer);
380    let chunks_created = chunks_info.len();
381
382    output::emit_progress_i18n(
383        &format!(
384            "Remember stage: tokenizer counted {total_passage_tokens} passage tokens (model max {model_max_length}); chunking produced {} chunks; process RSS {} MB",
385            chunks_created,
386            crate::memory_guard::current_process_memory_mb().unwrap_or(0)
387        ),
388        &format!(
389            "Etapa remember: tokenizer contou {total_passage_tokens} tokens de passagem (máximo do modelo {model_max_length}); chunking gerou {} chunks; RSS do processo {} MB",
390            chunks_created,
391            crate::memory_guard::current_process_memory_mb().unwrap_or(0)
392        ),
393    );
394
395    if chunks_created > crate::constants::REMEMBER_MAX_SAFE_MULTI_CHUNKS {
396        return Err(AppError::LimitExceeded(format!(
397            "documento gera {chunks_created} chunks; limite operacional seguro atual é {} chunks; divida o documento antes de usar remember",
398            crate::constants::REMEMBER_MAX_SAFE_MULTI_CHUNKS
399        )));
400    }
401
402    output::emit_progress_i18n("Computing embedding...", "Calculando embedding...");
403    let mut chunk_embeddings_cache: Option<Vec<Vec<f32>>> = None;
404
405    let embedding = if chunks_info.len() == 1 {
406        crate::daemon::embed_passage_or_local(&paths.models, &raw_body)?
407    } else {
408        let chunk_texts: Vec<&str> = chunks_info
409            .iter()
410            .map(|c| chunking::chunk_text(&raw_body, c))
411            .collect();
412        output::emit_progress_i18n(
413            &format!(
414                "Embedding {} chunks serially to keep memory bounded...",
415                chunks_info.len()
416            ),
417            &format!(
418                "Embedando {} chunks serialmente para manter memória limitada...",
419                chunks_info.len()
420            ),
421        );
422        let mut chunk_embeddings = Vec::with_capacity(chunk_texts.len());
423        for chunk_text in &chunk_texts {
424            chunk_embeddings.push(crate::daemon::embed_passage_or_local(
425                &paths.models,
426                chunk_text,
427            )?);
428        }
429        output::emit_progress_i18n(
430            &format!(
431                "Remember stage: chunk embeddings complete; process RSS {} MB",
432                crate::memory_guard::current_process_memory_mb().unwrap_or(0)
433            ),
434            &format!(
435                "Etapa remember: embeddings dos chunks concluídos; RSS do processo {} MB",
436                crate::memory_guard::current_process_memory_mb().unwrap_or(0)
437            ),
438        );
439        let aggregated = chunking::aggregate_embeddings(&chunk_embeddings);
440        chunk_embeddings_cache = Some(chunk_embeddings);
441        aggregated
442    };
443    let body_for_storage = raw_body;
444
445    let memory_type = args.r#type.as_str();
446    let new_memory = NewMemory {
447        namespace: namespace.clone(),
448        name: normalized_name.clone(),
449        memory_type: memory_type.to_string(),
450        description: args.description.clone(),
451        body: body_for_storage,
452        body_hash: body_hash.clone(),
453        session_id: args.session_id.clone(),
454        source: "agent".to_string(),
455        metadata,
456    };
457
458    let mut warnings = Vec::new();
459    let mut entities_persisted = 0usize;
460    let mut relationships_persisted = 0usize;
461
462    let graph_entity_embeddings = graph
463        .entities
464        .iter()
465        .map(|entity| {
466            let entity_text = match &entity.description {
467                Some(desc) => format!("{} {}", entity.name, desc),
468                None => entity.name.clone(),
469            };
470            crate::daemon::embed_passage_or_local(&paths.models, &entity_text)
471        })
472        .collect::<Result<Vec<_>, _>>()?;
473
474    let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
475
476    let (memory_id, action, version) = match existing_memory {
477        Some((existing_id, _updated_at, _current_version)) => {
478            if let Some(hash_id) = duplicate_hash_id {
479                if hash_id != existing_id {
480                    warnings.push(format!(
481                        "identical body already exists as memory id {hash_id}"
482                    ));
483                }
484            }
485
486            storage_chunks::delete_chunks(&tx, existing_id)?;
487
488            let next_v = versions::next_version(&tx, existing_id)?;
489            memories::update(&tx, existing_id, &new_memory, args.expected_updated_at)?;
490            versions::insert_version(
491                &tx,
492                existing_id,
493                next_v,
494                &normalized_name,
495                memory_type,
496                &args.description,
497                &new_memory.body,
498                &serde_json::to_string(&new_memory.metadata)?,
499                None,
500                "edit",
501            )?;
502            memories::upsert_vec(
503                &tx,
504                existing_id,
505                &namespace,
506                memory_type,
507                &embedding,
508                &normalized_name,
509                &snippet,
510            )?;
511            (existing_id, "updated".to_string(), next_v)
512        }
513        None => {
514            if let Some(hash_id) = duplicate_hash_id {
515                warnings.push(format!(
516                    "identical body already exists as memory id {hash_id}"
517                ));
518            }
519            let id = memories::insert(&tx, &new_memory)?;
520            versions::insert_version(
521                &tx,
522                id,
523                1,
524                &normalized_name,
525                memory_type,
526                &args.description,
527                &new_memory.body,
528                &serde_json::to_string(&new_memory.metadata)?,
529                None,
530                "create",
531            )?;
532            memories::upsert_vec(
533                &tx,
534                id,
535                &namespace,
536                memory_type,
537                &embedding,
538                &normalized_name,
539                &snippet,
540            )?;
541            (id, "created".to_string(), 1)
542        }
543    };
544
545    if chunks_info.len() > 1 {
546        storage_chunks::insert_chunk_slices(&tx, memory_id, &new_memory.body, &chunks_info)?;
547
548        let chunk_embeddings = chunk_embeddings_cache.take().ok_or_else(|| {
549            AppError::Internal(anyhow::anyhow!(
550                "cache de embeddings de chunks ausente no caminho multi-chunk do remember"
551            ))
552        })?;
553
554        for (i, emb) in chunk_embeddings.iter().enumerate() {
555            storage_chunks::upsert_chunk_vec(&tx, i as i64, memory_id, i as i32, emb)?;
556        }
557        output::emit_progress_i18n(
558            &format!(
559                "Remember stage: persisted chunk vectors; process RSS {} MB",
560                crate::memory_guard::current_process_memory_mb().unwrap_or(0)
561            ),
562            &format!(
563                "Etapa remember: vetores de chunks persistidos; RSS do processo {} MB",
564                crate::memory_guard::current_process_memory_mb().unwrap_or(0)
565            ),
566        );
567    }
568
569    if !graph.entities.is_empty() || !graph.relationships.is_empty() {
570        for entity in &graph.entities {
571            let entity_id = entities::upsert_entity(&tx, &namespace, entity)?;
572            let entity_embedding = &graph_entity_embeddings[entities_persisted];
573            entities::upsert_entity_vec(
574                &tx,
575                entity_id,
576                &namespace,
577                &entity.entity_type,
578                entity_embedding,
579                &entity.name,
580            )?;
581            entities::link_memory_entity(&tx, memory_id, entity_id)?;
582            entities::increment_degree(&tx, entity_id)?;
583            entities_persisted += 1;
584        }
585        let entity_types: std::collections::HashMap<&str, &str> = graph
586            .entities
587            .iter()
588            .map(|entity| (entity.name.as_str(), entity.entity_type.as_str()))
589            .collect();
590
591        for rel in &graph.relationships {
592            let source_entity = NewEntity {
593                name: rel.source.clone(),
594                entity_type: entity_types
595                    .get(rel.source.as_str())
596                    .copied()
597                    .unwrap_or("concept")
598                    .to_string(),
599                description: None,
600            };
601            let target_entity = NewEntity {
602                name: rel.target.clone(),
603                entity_type: entity_types
604                    .get(rel.target.as_str())
605                    .copied()
606                    .unwrap_or("concept")
607                    .to_string(),
608                description: None,
609            };
610            let source_id = entities::upsert_entity(&tx, &namespace, &source_entity)?;
611            let target_id = entities::upsert_entity(&tx, &namespace, &target_entity)?;
612            let rel_id = entities::upsert_relationship(&tx, &namespace, source_id, target_id, rel)?;
613            entities::link_memory_relationship(&tx, memory_id, rel_id)?;
614            relationships_persisted += 1;
615        }
616    }
617    tx.commit()?;
618
619    let created_at_epoch = chrono::Utc::now().timestamp();
620    let created_at_iso = crate::tz::formatar_iso(chrono::Utc::now());
621
622    output::emit_json(&RememberResponse {
623        memory_id,
624        name: args.name,
625        namespace,
626        action: action.clone(),
627        operation: action,
628        version,
629        entities_persisted,
630        relationships_persisted,
631        chunks_created,
632        extraction_method,
633        merged_into_memory_id: None,
634        warnings,
635        created_at: created_at_epoch,
636        created_at_iso,
637        elapsed_ms: inicio.elapsed().as_millis() as u64,
638    })?;
639
640    Ok(())
641}
642
643#[cfg(test)]
644mod testes {
645    use crate::output::RememberResponse;
646
647    #[test]
648    fn remember_response_serializa_campos_obrigatorios() {
649        let resp = RememberResponse {
650            memory_id: 42,
651            name: "minha-mem".to_string(),
652            namespace: "global".to_string(),
653            action: "created".to_string(),
654            operation: "created".to_string(),
655            version: 1,
656            entities_persisted: 0,
657            relationships_persisted: 0,
658            chunks_created: 1,
659            extraction_method: None,
660            merged_into_memory_id: None,
661            warnings: vec![],
662            created_at: 1_705_320_000,
663            created_at_iso: "2024-01-15T12:00:00Z".to_string(),
664            elapsed_ms: 55,
665        };
666
667        let json = serde_json::to_value(&resp).expect("serialização falhou");
668        assert_eq!(json["memory_id"], 42);
669        assert_eq!(json["action"], "created");
670        assert_eq!(json["operation"], "created");
671        assert_eq!(json["version"], 1);
672        assert_eq!(json["elapsed_ms"], 55u64);
673        assert!(json["warnings"].is_array());
674        assert!(json["merged_into_memory_id"].is_null());
675    }
676
677    #[test]
678    fn remember_response_action_e_operation_sao_aliases() {
679        let resp = RememberResponse {
680            memory_id: 1,
681            name: "mem".to_string(),
682            namespace: "global".to_string(),
683            action: "updated".to_string(),
684            operation: "updated".to_string(),
685            version: 2,
686            entities_persisted: 3,
687            relationships_persisted: 1,
688            extraction_method: None,
689            chunks_created: 2,
690            merged_into_memory_id: None,
691            warnings: vec![],
692            created_at: 0,
693            created_at_iso: "1970-01-01T00:00:00Z".to_string(),
694            elapsed_ms: 0,
695        };
696
697        let json = serde_json::to_value(&resp).expect("serialização falhou");
698        assert_eq!(
699            json["action"], json["operation"],
700            "action e operation devem ser iguais"
701        );
702        assert_eq!(json["entities_persisted"], 3);
703        assert_eq!(json["relationships_persisted"], 1);
704        assert_eq!(json["chunks_created"], 2);
705    }
706
707    #[test]
708    fn remember_response_warnings_lista_mensagens() {
709        let resp = RememberResponse {
710            memory_id: 5,
711            name: "dup-mem".to_string(),
712            namespace: "global".to_string(),
713            action: "created".to_string(),
714            operation: "created".to_string(),
715            version: 1,
716            entities_persisted: 0,
717            extraction_method: None,
718            relationships_persisted: 0,
719            chunks_created: 1,
720            merged_into_memory_id: None,
721            warnings: vec!["identical body already exists as memory id 3".to_string()],
722            created_at: 0,
723            created_at_iso: "1970-01-01T00:00:00Z".to_string(),
724            elapsed_ms: 10,
725        };
726
727        let json = serde_json::to_value(&resp).expect("serialização falhou");
728        let warnings = json["warnings"]
729            .as_array()
730            .expect("warnings deve ser array");
731        assert_eq!(warnings.len(), 1);
732        assert!(warnings[0].as_str().unwrap().contains("identical body"));
733    }
734
735    #[test]
736    fn nome_invalido_prefixo_reservado_retorna_validation_error() {
737        use crate::errors::AppError;
738        // Valida a lógica de rejeição de nomes com prefixo "__" diretamente
739        let nome = "__reservado";
740        let resultado: Result<(), AppError> = if nome.starts_with("__") {
741            Err(AppError::Validation(
742                crate::i18n::validacao::nome_reservado(),
743            ))
744        } else {
745            Ok(())
746        };
747        assert!(resultado.is_err());
748        if let Err(AppError::Validation(msg)) = resultado {
749            assert!(!msg.is_empty());
750        }
751    }
752
753    #[test]
754    fn nome_muito_longo_retorna_validation_error() {
755        use crate::errors::AppError;
756        let nome_longo = "a".repeat(crate::constants::MAX_MEMORY_NAME_LEN + 1);
757        let resultado: Result<(), AppError> =
758            if nome_longo.is_empty() || nome_longo.len() > crate::constants::MAX_MEMORY_NAME_LEN {
759                Err(AppError::Validation(
760                    crate::i18n::validacao::nome_comprimento(crate::constants::MAX_MEMORY_NAME_LEN),
761                ))
762            } else {
763                Ok(())
764            };
765        assert!(resultado.is_err());
766    }
767
768    #[test]
769    fn remember_response_merged_into_memory_id_some_serializa_inteiro() {
770        let resp = RememberResponse {
771            memory_id: 10,
772            name: "mem-mergeada".to_string(),
773            namespace: "global".to_string(),
774            action: "updated".to_string(),
775            operation: "updated".to_string(),
776            version: 3,
777            extraction_method: None,
778            entities_persisted: 0,
779            relationships_persisted: 0,
780            chunks_created: 1,
781            merged_into_memory_id: Some(7),
782            warnings: vec![],
783            created_at: 0,
784            created_at_iso: "1970-01-01T00:00:00Z".to_string(),
785            elapsed_ms: 0,
786        };
787
788        let json = serde_json::to_value(&resp).expect("serialização falhou");
789        assert_eq!(json["merged_into_memory_id"], 7);
790    }
791}