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