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 #[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 #[arg(long)]
29 pub description: String,
30 #[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 #[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 #[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 #[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 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 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 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 let chunks_persisted = if chunks_info.len() > 1 {
385 chunks_info.len()
386 } else {
387 0
388 };
389
390 output::emit_progress_i18n(
391 &format!(
392 "Remember stage: tokenizer counted {total_passage_tokens} passage tokens (model max {model_max_length}); chunking produced {} chunks; process RSS {} MB",
393 chunks_created,
394 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
395 ),
396 &format!(
397 "Etapa remember: tokenizer contou {total_passage_tokens} tokens de passagem (máximo do modelo {model_max_length}); chunking gerou {} chunks; RSS do processo {} MB",
398 chunks_created,
399 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
400 ),
401 );
402
403 if chunks_created > crate::constants::REMEMBER_MAX_SAFE_MULTI_CHUNKS {
404 return Err(AppError::LimitExceeded(format!(
405 "documento gera {chunks_created} chunks; limite operacional seguro atual é {} chunks; divida o documento antes de usar remember",
406 crate::constants::REMEMBER_MAX_SAFE_MULTI_CHUNKS
407 )));
408 }
409
410 output::emit_progress_i18n("Computing embedding...", "Calculando embedding...");
411 let mut chunk_embeddings_cache: Option<Vec<Vec<f32>>> = None;
412
413 let embedding = if chunks_info.len() == 1 {
414 crate::daemon::embed_passage_or_local(&paths.models, &raw_body)?
415 } else {
416 let chunk_texts: Vec<&str> = chunks_info
417 .iter()
418 .map(|c| chunking::chunk_text(&raw_body, c))
419 .collect();
420 output::emit_progress_i18n(
421 &format!(
422 "Embedding {} chunks serially to keep memory bounded...",
423 chunks_info.len()
424 ),
425 &format!(
426 "Embedando {} chunks serialmente para manter memória limitada...",
427 chunks_info.len()
428 ),
429 );
430 let mut chunk_embeddings = Vec::with_capacity(chunk_texts.len());
431 for chunk_text in &chunk_texts {
432 chunk_embeddings.push(crate::daemon::embed_passage_or_local(
433 &paths.models,
434 chunk_text,
435 )?);
436 }
437 output::emit_progress_i18n(
438 &format!(
439 "Remember stage: chunk embeddings complete; process RSS {} MB",
440 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
441 ),
442 &format!(
443 "Etapa remember: embeddings dos chunks concluídos; RSS do processo {} MB",
444 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
445 ),
446 );
447 let aggregated = chunking::aggregate_embeddings(&chunk_embeddings);
448 chunk_embeddings_cache = Some(chunk_embeddings);
449 aggregated
450 };
451 let body_for_storage = raw_body;
452
453 let memory_type = args.r#type.as_str();
454 let new_memory = NewMemory {
455 namespace: namespace.clone(),
456 name: normalized_name.clone(),
457 memory_type: memory_type.to_string(),
458 description: args.description.clone(),
459 body: body_for_storage,
460 body_hash: body_hash.clone(),
461 session_id: args.session_id.clone(),
462 source: "agent".to_string(),
463 metadata,
464 };
465
466 let mut warnings = Vec::new();
467 let mut entities_persisted = 0usize;
468 let mut relationships_persisted = 0usize;
469
470 let graph_entity_embeddings = graph
471 .entities
472 .iter()
473 .map(|entity| {
474 let entity_text = match &entity.description {
475 Some(desc) => format!("{} {}", entity.name, desc),
476 None => entity.name.clone(),
477 };
478 crate::daemon::embed_passage_or_local(&paths.models, &entity_text)
479 })
480 .collect::<Result<Vec<_>, _>>()?;
481
482 let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
483
484 let (memory_id, action, version) = match existing_memory {
485 Some((existing_id, _updated_at, _current_version)) => {
486 if let Some(hash_id) = duplicate_hash_id {
487 if hash_id != existing_id {
488 warnings.push(format!(
489 "identical body already exists as memory id {hash_id}"
490 ));
491 }
492 }
493
494 storage_chunks::delete_chunks(&tx, existing_id)?;
495
496 let next_v = versions::next_version(&tx, existing_id)?;
497 memories::update(&tx, existing_id, &new_memory, args.expected_updated_at)?;
498 versions::insert_version(
499 &tx,
500 existing_id,
501 next_v,
502 &normalized_name,
503 memory_type,
504 &args.description,
505 &new_memory.body,
506 &serde_json::to_string(&new_memory.metadata)?,
507 None,
508 "edit",
509 )?;
510 memories::upsert_vec(
511 &tx,
512 existing_id,
513 &namespace,
514 memory_type,
515 &embedding,
516 &normalized_name,
517 &snippet,
518 )?;
519 (existing_id, "updated".to_string(), next_v)
520 }
521 None => {
522 if let Some(hash_id) = duplicate_hash_id {
523 warnings.push(format!(
524 "identical body already exists as memory id {hash_id}"
525 ));
526 }
527 let id = memories::insert(&tx, &new_memory)?;
528 versions::insert_version(
529 &tx,
530 id,
531 1,
532 &normalized_name,
533 memory_type,
534 &args.description,
535 &new_memory.body,
536 &serde_json::to_string(&new_memory.metadata)?,
537 None,
538 "create",
539 )?;
540 memories::upsert_vec(
541 &tx,
542 id,
543 &namespace,
544 memory_type,
545 &embedding,
546 &normalized_name,
547 &snippet,
548 )?;
549 (id, "created".to_string(), 1)
550 }
551 };
552
553 if chunks_info.len() > 1 {
554 storage_chunks::insert_chunk_slices(&tx, memory_id, &new_memory.body, &chunks_info)?;
555
556 let chunk_embeddings = chunk_embeddings_cache.take().ok_or_else(|| {
557 AppError::Internal(anyhow::anyhow!(
558 "cache de embeddings de chunks ausente no caminho multi-chunk do remember"
559 ))
560 })?;
561
562 for (i, emb) in chunk_embeddings.iter().enumerate() {
563 storage_chunks::upsert_chunk_vec(&tx, i as i64, memory_id, i as i32, emb)?;
564 }
565 output::emit_progress_i18n(
566 &format!(
567 "Remember stage: persisted chunk vectors; process RSS {} MB",
568 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
569 ),
570 &format!(
571 "Etapa remember: vetores de chunks persistidos; RSS do processo {} MB",
572 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
573 ),
574 );
575 }
576
577 if !graph.entities.is_empty() || !graph.relationships.is_empty() {
578 for entity in &graph.entities {
579 let entity_id = entities::upsert_entity(&tx, &namespace, entity)?;
580 let entity_embedding = &graph_entity_embeddings[entities_persisted];
581 entities::upsert_entity_vec(
582 &tx,
583 entity_id,
584 &namespace,
585 &entity.entity_type,
586 entity_embedding,
587 &entity.name,
588 )?;
589 entities::link_memory_entity(&tx, memory_id, entity_id)?;
590 entities::increment_degree(&tx, entity_id)?;
591 entities_persisted += 1;
592 }
593 let entity_types: std::collections::HashMap<&str, &str> = graph
594 .entities
595 .iter()
596 .map(|entity| (entity.name.as_str(), entity.entity_type.as_str()))
597 .collect();
598
599 for rel in &graph.relationships {
600 let source_entity = NewEntity {
601 name: rel.source.clone(),
602 entity_type: entity_types
603 .get(rel.source.as_str())
604 .copied()
605 .unwrap_or("concept")
606 .to_string(),
607 description: None,
608 };
609 let target_entity = NewEntity {
610 name: rel.target.clone(),
611 entity_type: entity_types
612 .get(rel.target.as_str())
613 .copied()
614 .unwrap_or("concept")
615 .to_string(),
616 description: None,
617 };
618 let source_id = entities::upsert_entity(&tx, &namespace, &source_entity)?;
619 let target_id = entities::upsert_entity(&tx, &namespace, &target_entity)?;
620 let rel_id = entities::upsert_relationship(&tx, &namespace, source_id, target_id, rel)?;
621 entities::link_memory_relationship(&tx, memory_id, rel_id)?;
622 relationships_persisted += 1;
623 }
624 }
625 tx.commit()?;
626
627 let created_at_epoch = chrono::Utc::now().timestamp();
628 let created_at_iso = crate::tz::formatar_iso(chrono::Utc::now());
629
630 output::emit_json(&RememberResponse {
631 memory_id,
632 name: args.name,
633 namespace,
634 action: action.clone(),
635 operation: action,
636 version,
637 entities_persisted,
638 relationships_persisted,
639 chunks_created,
640 chunks_persisted,
641 extraction_method,
642 merged_into_memory_id: None,
643 warnings,
644 created_at: created_at_epoch,
645 created_at_iso,
646 elapsed_ms: inicio.elapsed().as_millis() as u64,
647 })?;
648
649 Ok(())
650}
651
652#[cfg(test)]
653mod testes {
654 use crate::output::RememberResponse;
655
656 #[test]
657 fn remember_response_serializa_campos_obrigatorios() {
658 let resp = RememberResponse {
659 memory_id: 42,
660 name: "minha-mem".to_string(),
661 namespace: "global".to_string(),
662 action: "created".to_string(),
663 operation: "created".to_string(),
664 version: 1,
665 entities_persisted: 0,
666 relationships_persisted: 0,
667 chunks_created: 1,
668 chunks_persisted: 0,
669 extraction_method: None,
670 merged_into_memory_id: None,
671 warnings: vec![],
672 created_at: 1_705_320_000,
673 created_at_iso: "2024-01-15T12:00:00Z".to_string(),
674 elapsed_ms: 55,
675 };
676
677 let json = serde_json::to_value(&resp).expect("serialização falhou");
678 assert_eq!(json["memory_id"], 42);
679 assert_eq!(json["action"], "created");
680 assert_eq!(json["operation"], "created");
681 assert_eq!(json["version"], 1);
682 assert_eq!(json["elapsed_ms"], 55u64);
683 assert!(json["warnings"].is_array());
684 assert!(json["merged_into_memory_id"].is_null());
685 }
686
687 #[test]
688 fn remember_response_action_e_operation_sao_aliases() {
689 let resp = RememberResponse {
690 memory_id: 1,
691 name: "mem".to_string(),
692 namespace: "global".to_string(),
693 action: "updated".to_string(),
694 operation: "updated".to_string(),
695 version: 2,
696 entities_persisted: 3,
697 relationships_persisted: 1,
698 extraction_method: None,
699 chunks_created: 2,
700 chunks_persisted: 2,
701 merged_into_memory_id: None,
702 warnings: vec![],
703 created_at: 0,
704 created_at_iso: "1970-01-01T00:00:00Z".to_string(),
705 elapsed_ms: 0,
706 };
707
708 let json = serde_json::to_value(&resp).expect("serialização falhou");
709 assert_eq!(
710 json["action"], json["operation"],
711 "action e operation devem ser iguais"
712 );
713 assert_eq!(json["entities_persisted"], 3);
714 assert_eq!(json["relationships_persisted"], 1);
715 assert_eq!(json["chunks_created"], 2);
716 }
717
718 #[test]
719 fn remember_response_warnings_lista_mensagens() {
720 let resp = RememberResponse {
721 memory_id: 5,
722 name: "dup-mem".to_string(),
723 namespace: "global".to_string(),
724 action: "created".to_string(),
725 operation: "created".to_string(),
726 version: 1,
727 entities_persisted: 0,
728 extraction_method: None,
729 relationships_persisted: 0,
730 chunks_created: 1,
731 chunks_persisted: 0,
732 merged_into_memory_id: None,
733 warnings: vec!["identical body already exists as memory id 3".to_string()],
734 created_at: 0,
735 created_at_iso: "1970-01-01T00:00:00Z".to_string(),
736 elapsed_ms: 10,
737 };
738
739 let json = serde_json::to_value(&resp).expect("serialização falhou");
740 let warnings = json["warnings"]
741 .as_array()
742 .expect("warnings deve ser array");
743 assert_eq!(warnings.len(), 1);
744 assert!(warnings[0].as_str().unwrap().contains("identical body"));
745 }
746
747 #[test]
748 fn nome_invalido_prefixo_reservado_retorna_validation_error() {
749 use crate::errors::AppError;
750 let nome = "__reservado";
752 let resultado: Result<(), AppError> = if nome.starts_with("__") {
753 Err(AppError::Validation(
754 crate::i18n::validacao::nome_reservado(),
755 ))
756 } else {
757 Ok(())
758 };
759 assert!(resultado.is_err());
760 if let Err(AppError::Validation(msg)) = resultado {
761 assert!(!msg.is_empty());
762 }
763 }
764
765 #[test]
766 fn nome_muito_longo_retorna_validation_error() {
767 use crate::errors::AppError;
768 let nome_longo = "a".repeat(crate::constants::MAX_MEMORY_NAME_LEN + 1);
769 let resultado: Result<(), AppError> =
770 if nome_longo.is_empty() || nome_longo.len() > crate::constants::MAX_MEMORY_NAME_LEN {
771 Err(AppError::Validation(
772 crate::i18n::validacao::nome_comprimento(crate::constants::MAX_MEMORY_NAME_LEN),
773 ))
774 } else {
775 Ok(())
776 };
777 assert!(resultado.is_err());
778 }
779
780 #[test]
781 fn remember_response_merged_into_memory_id_some_serializa_inteiro() {
782 let resp = RememberResponse {
783 memory_id: 10,
784 name: "mem-mergeada".to_string(),
785 namespace: "global".to_string(),
786 action: "updated".to_string(),
787 operation: "updated".to_string(),
788 version: 3,
789 extraction_method: None,
790 entities_persisted: 0,
791 relationships_persisted: 0,
792 chunks_created: 1,
793 chunks_persisted: 0,
794 merged_into_memory_id: Some(7),
795 warnings: vec![],
796 created_at: 0,
797 created_at_iso: "1970-01-01T00:00:00Z".to_string(),
798 elapsed_ms: 0,
799 };
800
801 let json = serde_json::to_value(&resp).expect("serialização falhou");
802 assert_eq!(json["merged_into_memory_id"], 7);
803 }
804}