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, urls as storage_urls, 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 | "organization"
159 | "location"
160 | "date"
161 )
162}
163
164fn is_valid_relation(relation: &str) -> bool {
165 matches!(
166 relation,
167 "applies_to"
168 | "uses"
169 | "depends_on"
170 | "causes"
171 | "fixes"
172 | "contradicts"
173 | "supports"
174 | "follows"
175 | "related"
176 | "mentions"
177 | "replaces"
178 | "tracked_in"
179 )
180}
181
182pub fn run(args: RememberArgs) -> Result<(), AppError> {
183 use crate::constants::*;
184
185 let inicio = std::time::Instant::now();
186 let _ = args.format;
187 let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
188
189 let normalized_name = {
193 let lower = args.name.to_lowercase().replace(['_', ' '], "-");
194 let trimmed = lower.trim_matches('-').to_string();
195 if trimmed != args.name {
196 tracing::warn!(
197 original = %args.name,
198 normalized = %trimmed,
199 "name auto-normalized to kebab-case"
200 );
201 }
202 trimmed
203 };
204
205 if normalized_name.is_empty() {
206 return Err(AppError::Validation(
207 "name cannot be empty after normalization (input was blank or contained only hyphens/underscores/spaces)".to_string(),
208 ));
209 }
210 if normalized_name.len() > MAX_MEMORY_NAME_LEN {
211 return Err(AppError::LimitExceeded(
212 crate::i18n::validacao::nome_comprimento(MAX_MEMORY_NAME_LEN),
213 ));
214 }
215
216 if normalized_name.starts_with("__") {
217 return Err(AppError::Validation(
218 crate::i18n::validacao::nome_reservado(),
219 ));
220 }
221
222 {
223 let slug_re = regex::Regex::new(crate::constants::NAME_SLUG_REGEX)
224 .map_err(|e| AppError::Internal(anyhow::anyhow!("regex: {e}")))?;
225 if !slug_re.is_match(&normalized_name) {
226 return Err(AppError::Validation(crate::i18n::validacao::nome_kebab(
227 &normalized_name,
228 )));
229 }
230 }
231
232 if args.description.len() > MAX_MEMORY_DESCRIPTION_LEN {
233 return Err(AppError::Validation(
234 crate::i18n::validacao::descricao_excede(MAX_MEMORY_DESCRIPTION_LEN),
235 ));
236 }
237
238 let mut raw_body = if let Some(b) = args.body {
239 b
240 } else if let Some(path) = args.body_file {
241 std::fs::read_to_string(&path).map_err(AppError::Io)?
242 } else if args.body_stdin || args.graph_stdin {
243 let mut buf = String::new();
244 std::io::stdin()
245 .read_to_string(&mut buf)
246 .map_err(AppError::Io)?;
247 buf
248 } else {
249 String::new()
250 };
251
252 let entities_provided_externally =
253 args.entities_file.is_some() || args.relationships_file.is_some() || args.graph_stdin;
254
255 let mut graph = GraphInput::default();
256 if let Some(path) = args.entities_file {
257 let content = std::fs::read_to_string(&path).map_err(AppError::Io)?;
258 graph.entities = serde_json::from_str(&content)?;
259 }
260 if let Some(path) = args.relationships_file {
261 let content = std::fs::read_to_string(&path).map_err(AppError::Io)?;
262 graph.relationships = serde_json::from_str(&content)?;
263 }
264 if args.graph_stdin {
265 graph = serde_json::from_str::<GraphInput>(&raw_body).map_err(|e| {
266 AppError::Validation(format!("payload JSON inválido em --graph-stdin: {e}"))
267 })?;
268 raw_body = graph.body.take().unwrap_or_default();
269 }
270
271 if graph.entities.len() > MAX_ENTITIES_PER_MEMORY {
272 return Err(AppError::LimitExceeded(erros::limite_entidades(
273 MAX_ENTITIES_PER_MEMORY,
274 )));
275 }
276 if graph.relationships.len() > MAX_RELATIONSHIPS_PER_MEMORY {
277 return Err(AppError::LimitExceeded(erros::limite_relacionamentos(
278 MAX_RELATIONSHIPS_PER_MEMORY,
279 )));
280 }
281 normalize_and_validate_graph_input(&mut graph)?;
282
283 if raw_body.len() > MAX_MEMORY_BODY_LEN {
284 return Err(AppError::LimitExceeded(
285 crate::i18n::validacao::body_excede(MAX_MEMORY_BODY_LEN),
286 ));
287 }
288
289 if !entities_provided_externally && graph.entities.is_empty() && raw_body.trim().is_empty() {
292 return Err(AppError::Validation(
293 "body não pode estar vazio: forneça --body, --body-file, --body-stdin com conteúdo, \
294 ou um grafo via --entities-file/--graph-stdin"
295 .to_string(),
296 ));
297 }
298
299 let metadata: serde_json::Value = if let Some(m) = args.metadata {
300 serde_json::from_str(&m)?
301 } else if let Some(path) = args.metadata_file {
302 let content = std::fs::read_to_string(&path).map_err(AppError::Io)?;
303 serde_json::from_str(&content)?
304 } else {
305 serde_json::json!({})
306 };
307
308 let body_hash = blake3::hash(raw_body.as_bytes()).to_hex().to_string();
309 let snippet: String = raw_body.chars().take(200).collect();
310
311 let paths = AppPaths::resolve(args.db.as_deref())?;
312 paths.ensure_dirs()?;
313
314 let mut extraction_method: Option<String> = None;
316 let mut extracted_urls: Vec<crate::extraction::ExtractedUrl> = Vec::new();
317 let mut relationships_truncated = false;
318 if !args.skip_extraction
319 && !entities_provided_externally
320 && graph.entities.is_empty()
321 && !raw_body.trim().is_empty()
322 {
323 match crate::extraction::extract_graph_auto(&raw_body, &paths) {
324 Ok(extracted) => {
325 extraction_method = Some(extracted.extraction_method.clone());
326 extracted_urls = extracted.urls;
327 graph.entities = extracted.entities;
328 graph.relationships = extracted.relationships;
329 relationships_truncated = extracted.relationships_truncated;
330
331 if graph.entities.len() > MAX_ENTITIES_PER_MEMORY {
332 graph.entities.truncate(MAX_ENTITIES_PER_MEMORY);
333 }
334 if graph.relationships.len() > MAX_RELATIONSHIPS_PER_MEMORY {
335 relationships_truncated = true;
336 graph.relationships.truncate(MAX_RELATIONSHIPS_PER_MEMORY);
337 }
338 normalize_and_validate_graph_input(&mut graph)?;
339 }
340 Err(e) => {
341 tracing::warn!("auto-extraction falhou (graceful degradation): {e:#}");
342 }
343 }
344 }
345
346 let mut conn = open_rw(&paths.db)?;
347 ensure_schema(&mut conn)?;
348
349 {
350 use crate::constants::MAX_NAMESPACES_ACTIVE;
351 let active_count: u32 = conn.query_row(
352 "SELECT COUNT(DISTINCT namespace) FROM memories WHERE deleted_at IS NULL",
353 [],
354 |r| r.get::<_, i64>(0).map(|v| v as u32),
355 )?;
356 let ns_exists: bool = conn.query_row(
357 "SELECT EXISTS(SELECT 1 FROM memories WHERE namespace = ?1 AND deleted_at IS NULL)",
358 rusqlite::params![namespace],
359 |r| r.get::<_, i64>(0).map(|v| v > 0),
360 )?;
361 if !ns_exists && active_count >= MAX_NAMESPACES_ACTIVE {
362 return Err(AppError::NamespaceError(format!(
363 "limite de {MAX_NAMESPACES_ACTIVE} namespaces ativos excedido ao tentar criar '{namespace}'"
364 )));
365 }
366 }
367
368 let existing_memory = memories::find_by_name(&conn, &namespace, &normalized_name)?;
369 if existing_memory.is_some() && !args.force_merge {
370 return Err(AppError::Duplicate(erros::memoria_duplicada(
371 &normalized_name,
372 &namespace,
373 )));
374 }
375
376 let duplicate_hash_id = memories::find_by_hash(&conn, &namespace, &body_hash)?;
377
378 output::emit_progress_i18n(
379 &format!(
380 "Remember stage: validated input; available memory {} MB",
381 crate::memory_guard::available_memory_mb()
382 ),
383 &format!(
384 "Etapa remember: entrada validada; memória disponível {} MB",
385 crate::memory_guard::available_memory_mb()
386 ),
387 );
388
389 let tokenizer = crate::tokenizer::get_tokenizer(&paths.models)?;
390 let model_max_length = crate::tokenizer::get_model_max_length(&paths.models)?;
391 let total_passage_tokens = crate::tokenizer::count_passage_tokens(tokenizer, &raw_body)?;
392 let chunks_info = chunking::split_into_chunks_hierarchical(&raw_body, tokenizer);
393 let chunks_created = chunks_info.len();
394 let chunks_persisted = if chunks_info.len() > 1 {
398 chunks_info.len()
399 } else {
400 0
401 };
402
403 output::emit_progress_i18n(
404 &format!(
405 "Remember stage: tokenizer counted {total_passage_tokens} passage tokens (model max {model_max_length}); chunking produced {} chunks; process RSS {} MB",
406 chunks_created,
407 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
408 ),
409 &format!(
410 "Etapa remember: tokenizer contou {total_passage_tokens} tokens de passagem (máximo do modelo {model_max_length}); chunking gerou {} chunks; RSS do processo {} MB",
411 chunks_created,
412 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
413 ),
414 );
415
416 if chunks_created > crate::constants::REMEMBER_MAX_SAFE_MULTI_CHUNKS {
417 return Err(AppError::LimitExceeded(format!(
418 "documento gera {chunks_created} chunks; limite operacional seguro atual é {} chunks; divida o documento antes de usar remember",
419 crate::constants::REMEMBER_MAX_SAFE_MULTI_CHUNKS
420 )));
421 }
422
423 output::emit_progress_i18n("Computing embedding...", "Calculando embedding...");
424 let mut chunk_embeddings_cache: Option<Vec<Vec<f32>>> = None;
425
426 let embedding = if chunks_info.len() == 1 {
427 crate::daemon::embed_passage_or_local(&paths.models, &raw_body)?
428 } else {
429 let chunk_texts: Vec<&str> = chunks_info
430 .iter()
431 .map(|c| chunking::chunk_text(&raw_body, c))
432 .collect();
433 output::emit_progress_i18n(
434 &format!(
435 "Embedding {} chunks serially to keep memory bounded...",
436 chunks_info.len()
437 ),
438 &format!(
439 "Embedando {} chunks serialmente para manter memória limitada...",
440 chunks_info.len()
441 ),
442 );
443 let mut chunk_embeddings = Vec::with_capacity(chunk_texts.len());
444 for chunk_text in &chunk_texts {
445 chunk_embeddings.push(crate::daemon::embed_passage_or_local(
446 &paths.models,
447 chunk_text,
448 )?);
449 }
450 output::emit_progress_i18n(
451 &format!(
452 "Remember stage: chunk embeddings complete; process RSS {} MB",
453 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
454 ),
455 &format!(
456 "Etapa remember: embeddings dos chunks concluídos; RSS do processo {} MB",
457 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
458 ),
459 );
460 let aggregated = chunking::aggregate_embeddings(&chunk_embeddings);
461 chunk_embeddings_cache = Some(chunk_embeddings);
462 aggregated
463 };
464 let body_for_storage = raw_body;
465
466 let memory_type = args.r#type.as_str();
467 let new_memory = NewMemory {
468 namespace: namespace.clone(),
469 name: normalized_name.clone(),
470 memory_type: memory_type.to_string(),
471 description: args.description.clone(),
472 body: body_for_storage,
473 body_hash: body_hash.clone(),
474 session_id: args.session_id.clone(),
475 source: "agent".to_string(),
476 metadata,
477 };
478
479 let mut warnings = Vec::new();
480 let mut entities_persisted = 0usize;
481 let mut relationships_persisted = 0usize;
482
483 let graph_entity_embeddings = graph
484 .entities
485 .iter()
486 .map(|entity| {
487 let entity_text = match &entity.description {
488 Some(desc) => format!("{} {}", entity.name, desc),
489 None => entity.name.clone(),
490 };
491 crate::daemon::embed_passage_or_local(&paths.models, &entity_text)
492 })
493 .collect::<Result<Vec<_>, _>>()?;
494
495 let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
496
497 let (memory_id, action, version) = match existing_memory {
498 Some((existing_id, _updated_at, _current_version)) => {
499 if let Some(hash_id) = duplicate_hash_id {
500 if hash_id != existing_id {
501 warnings.push(format!(
502 "identical body already exists as memory id {hash_id}"
503 ));
504 }
505 }
506
507 storage_chunks::delete_chunks(&tx, existing_id)?;
508
509 let next_v = versions::next_version(&tx, existing_id)?;
510 memories::update(&tx, existing_id, &new_memory, args.expected_updated_at)?;
511 versions::insert_version(
512 &tx,
513 existing_id,
514 next_v,
515 &normalized_name,
516 memory_type,
517 &args.description,
518 &new_memory.body,
519 &serde_json::to_string(&new_memory.metadata)?,
520 None,
521 "edit",
522 )?;
523 memories::upsert_vec(
524 &tx,
525 existing_id,
526 &namespace,
527 memory_type,
528 &embedding,
529 &normalized_name,
530 &snippet,
531 )?;
532 (existing_id, "updated".to_string(), next_v)
533 }
534 None => {
535 if let Some(hash_id) = duplicate_hash_id {
536 warnings.push(format!(
537 "identical body already exists as memory id {hash_id}"
538 ));
539 }
540 let id = memories::insert(&tx, &new_memory)?;
541 versions::insert_version(
542 &tx,
543 id,
544 1,
545 &normalized_name,
546 memory_type,
547 &args.description,
548 &new_memory.body,
549 &serde_json::to_string(&new_memory.metadata)?,
550 None,
551 "create",
552 )?;
553 memories::upsert_vec(
554 &tx,
555 id,
556 &namespace,
557 memory_type,
558 &embedding,
559 &normalized_name,
560 &snippet,
561 )?;
562 (id, "created".to_string(), 1)
563 }
564 };
565
566 if chunks_info.len() > 1 {
567 storage_chunks::insert_chunk_slices(&tx, memory_id, &new_memory.body, &chunks_info)?;
568
569 let chunk_embeddings = chunk_embeddings_cache.take().ok_or_else(|| {
570 AppError::Internal(anyhow::anyhow!(
571 "cache de embeddings de chunks ausente no caminho multi-chunk do remember"
572 ))
573 })?;
574
575 for (i, emb) in chunk_embeddings.iter().enumerate() {
576 storage_chunks::upsert_chunk_vec(&tx, i as i64, memory_id, i as i32, emb)?;
577 }
578 output::emit_progress_i18n(
579 &format!(
580 "Remember stage: persisted chunk vectors; process RSS {} MB",
581 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
582 ),
583 &format!(
584 "Etapa remember: vetores de chunks persistidos; RSS do processo {} MB",
585 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
586 ),
587 );
588 }
589
590 if !graph.entities.is_empty() || !graph.relationships.is_empty() {
591 for entity in &graph.entities {
592 let entity_id = entities::upsert_entity(&tx, &namespace, entity)?;
593 let entity_embedding = &graph_entity_embeddings[entities_persisted];
594 entities::upsert_entity_vec(
595 &tx,
596 entity_id,
597 &namespace,
598 &entity.entity_type,
599 entity_embedding,
600 &entity.name,
601 )?;
602 entities::link_memory_entity(&tx, memory_id, entity_id)?;
603 entities::increment_degree(&tx, entity_id)?;
604 entities_persisted += 1;
605 }
606 let entity_types: std::collections::HashMap<&str, &str> = graph
607 .entities
608 .iter()
609 .map(|entity| (entity.name.as_str(), entity.entity_type.as_str()))
610 .collect();
611
612 for rel in &graph.relationships {
613 let source_entity = NewEntity {
614 name: rel.source.clone(),
615 entity_type: entity_types
616 .get(rel.source.as_str())
617 .copied()
618 .unwrap_or("concept")
619 .to_string(),
620 description: None,
621 };
622 let target_entity = NewEntity {
623 name: rel.target.clone(),
624 entity_type: entity_types
625 .get(rel.target.as_str())
626 .copied()
627 .unwrap_or("concept")
628 .to_string(),
629 description: None,
630 };
631 let source_id = entities::upsert_entity(&tx, &namespace, &source_entity)?;
632 let target_id = entities::upsert_entity(&tx, &namespace, &target_entity)?;
633 let rel_id = entities::upsert_relationship(&tx, &namespace, source_id, target_id, rel)?;
634 entities::link_memory_relationship(&tx, memory_id, rel_id)?;
635 relationships_persisted += 1;
636 }
637 }
638 tx.commit()?;
639
640 let urls_persisted = if !extracted_urls.is_empty() {
643 let url_entries: Vec<storage_urls::MemoryUrl> = extracted_urls
644 .into_iter()
645 .map(|u| storage_urls::MemoryUrl {
646 url: u.url,
647 offset: Some(u.offset as i64),
648 })
649 .collect();
650 storage_urls::insert_urls(&conn, memory_id, &url_entries)
651 } else {
652 0
653 };
654
655 let created_at_epoch = chrono::Utc::now().timestamp();
656 let created_at_iso = crate::tz::formatar_iso(chrono::Utc::now());
657
658 output::emit_json(&RememberResponse {
659 memory_id,
660 name: args.name,
661 namespace,
662 action: action.clone(),
663 operation: action,
664 version,
665 entities_persisted,
666 relationships_persisted,
667 relationships_truncated,
668 chunks_created,
669 chunks_persisted,
670 urls_persisted,
671 extraction_method,
672 merged_into_memory_id: None,
673 warnings,
674 created_at: created_at_epoch,
675 created_at_iso,
676 elapsed_ms: inicio.elapsed().as_millis() as u64,
677 })?;
678
679 Ok(())
680}
681
682#[cfg(test)]
683mod testes {
684 use crate::output::RememberResponse;
685
686 #[test]
687 fn remember_response_serializa_campos_obrigatorios() {
688 let resp = RememberResponse {
689 memory_id: 42,
690 name: "minha-mem".to_string(),
691 namespace: "global".to_string(),
692 action: "created".to_string(),
693 operation: "created".to_string(),
694 version: 1,
695 entities_persisted: 0,
696 relationships_persisted: 0,
697 relationships_truncated: false,
698 chunks_created: 1,
699 chunks_persisted: 0,
700 urls_persisted: 0,
701 extraction_method: None,
702 merged_into_memory_id: None,
703 warnings: vec![],
704 created_at: 1_705_320_000,
705 created_at_iso: "2024-01-15T12:00:00Z".to_string(),
706 elapsed_ms: 55,
707 };
708
709 let json = serde_json::to_value(&resp).expect("serialização falhou");
710 assert_eq!(json["memory_id"], 42);
711 assert_eq!(json["action"], "created");
712 assert_eq!(json["operation"], "created");
713 assert_eq!(json["version"], 1);
714 assert_eq!(json["elapsed_ms"], 55u64);
715 assert!(json["warnings"].is_array());
716 assert!(json["merged_into_memory_id"].is_null());
717 }
718
719 #[test]
720 fn remember_response_action_e_operation_sao_aliases() {
721 let resp = RememberResponse {
722 memory_id: 1,
723 name: "mem".to_string(),
724 namespace: "global".to_string(),
725 action: "updated".to_string(),
726 operation: "updated".to_string(),
727 version: 2,
728 entities_persisted: 3,
729 relationships_persisted: 1,
730 relationships_truncated: false,
731 extraction_method: None,
732 chunks_created: 2,
733 chunks_persisted: 2,
734 urls_persisted: 0,
735 merged_into_memory_id: None,
736 warnings: vec![],
737 created_at: 0,
738 created_at_iso: "1970-01-01T00:00:00Z".to_string(),
739 elapsed_ms: 0,
740 };
741
742 let json = serde_json::to_value(&resp).expect("serialização falhou");
743 assert_eq!(
744 json["action"], json["operation"],
745 "action e operation devem ser iguais"
746 );
747 assert_eq!(json["entities_persisted"], 3);
748 assert_eq!(json["relationships_persisted"], 1);
749 assert_eq!(json["chunks_created"], 2);
750 }
751
752 #[test]
753 fn remember_response_warnings_lista_mensagens() {
754 let resp = RememberResponse {
755 memory_id: 5,
756 name: "dup-mem".to_string(),
757 namespace: "global".to_string(),
758 action: "created".to_string(),
759 operation: "created".to_string(),
760 version: 1,
761 entities_persisted: 0,
762 extraction_method: None,
763 relationships_persisted: 0,
764 relationships_truncated: false,
765 chunks_created: 1,
766 chunks_persisted: 0,
767 urls_persisted: 0,
768 merged_into_memory_id: None,
769 warnings: vec!["identical body already exists as memory id 3".to_string()],
770 created_at: 0,
771 created_at_iso: "1970-01-01T00:00:00Z".to_string(),
772 elapsed_ms: 10,
773 };
774
775 let json = serde_json::to_value(&resp).expect("serialização falhou");
776 let warnings = json["warnings"]
777 .as_array()
778 .expect("warnings deve ser array");
779 assert_eq!(warnings.len(), 1);
780 assert!(warnings[0].as_str().unwrap().contains("identical body"));
781 }
782
783 #[test]
784 fn nome_invalido_prefixo_reservado_retorna_validation_error() {
785 use crate::errors::AppError;
786 let nome = "__reservado";
788 let resultado: Result<(), AppError> = if nome.starts_with("__") {
789 Err(AppError::Validation(
790 crate::i18n::validacao::nome_reservado(),
791 ))
792 } else {
793 Ok(())
794 };
795 assert!(resultado.is_err());
796 if let Err(AppError::Validation(msg)) = resultado {
797 assert!(!msg.is_empty());
798 }
799 }
800
801 #[test]
802 fn nome_muito_longo_retorna_validation_error() {
803 use crate::errors::AppError;
804 let nome_longo = "a".repeat(crate::constants::MAX_MEMORY_NAME_LEN + 1);
805 let resultado: Result<(), AppError> =
806 if nome_longo.is_empty() || nome_longo.len() > crate::constants::MAX_MEMORY_NAME_LEN {
807 Err(AppError::Validation(
808 crate::i18n::validacao::nome_comprimento(crate::constants::MAX_MEMORY_NAME_LEN),
809 ))
810 } else {
811 Ok(())
812 };
813 assert!(resultado.is_err());
814 }
815
816 #[test]
817 fn remember_response_merged_into_memory_id_some_serializa_inteiro() {
818 let resp = RememberResponse {
819 memory_id: 10,
820 name: "mem-mergeada".to_string(),
821 namespace: "global".to_string(),
822 action: "updated".to_string(),
823 operation: "updated".to_string(),
824 version: 3,
825 extraction_method: None,
826 entities_persisted: 0,
827 relationships_persisted: 0,
828 relationships_truncated: false,
829 chunks_created: 1,
830 chunks_persisted: 0,
831 urls_persisted: 0,
832 merged_into_memory_id: Some(7),
833 warnings: vec![],
834 created_at: 0,
835 created_at_iso: "1970-01-01T00:00:00Z".to_string(),
836 elapsed_ms: 0,
837 };
838
839 let json = serde_json::to_value(&resp).expect("serialização falhou");
840 assert_eq!(json["merged_into_memory_id"], 7);
841 }
842
843 #[test]
844 fn remember_response_urls_persisted_serializa_campo() {
845 let resp = RememberResponse {
847 memory_id: 3,
848 name: "mem-com-urls".to_string(),
849 namespace: "global".to_string(),
850 action: "created".to_string(),
851 operation: "created".to_string(),
852 version: 1,
853 entities_persisted: 0,
854 relationships_persisted: 0,
855 relationships_truncated: false,
856 chunks_created: 1,
857 chunks_persisted: 0,
858 urls_persisted: 3,
859 extraction_method: Some("regex-only".to_string()),
860 merged_into_memory_id: None,
861 warnings: vec![],
862 created_at: 0,
863 created_at_iso: "1970-01-01T00:00:00Z".to_string(),
864 elapsed_ms: 0,
865 };
866 let json = serde_json::to_value(&resp).expect("serialização falhou");
867 assert_eq!(json["urls_persisted"], 3);
868 }
869
870 #[test]
871 fn nome_vazio_apos_normalizacao_retorna_mensagem_especifica() {
872 use crate::errors::AppError;
875 let normalized = "---".to_lowercase().replace(['_', ' '], "-");
876 let normalized = normalized.trim_matches('-').to_string();
877 let resultado: Result<(), AppError> = if normalized.is_empty() {
878 Err(AppError::Validation(
879 "name cannot be empty after normalization (input was blank or contained only hyphens/underscores/spaces)".to_string(),
880 ))
881 } else {
882 Ok(())
883 };
884 assert!(resultado.is_err());
885 if let Err(AppError::Validation(msg)) = resultado {
886 assert!(
887 msg.contains("empty after normalization"),
888 "mensagem deve mencionar 'empty after normalization', obteve: {msg}"
889 );
890 }
891 }
892
893 #[test]
894 fn nome_so_underscores_apos_normalizacao_retorna_mensagem_especifica() {
895 use crate::errors::AppError;
897 let normalized = "___".to_lowercase().replace(['_', ' '], "-");
898 let normalized = normalized.trim_matches('-').to_string();
899 assert!(
900 normalized.is_empty(),
901 "underscores devem normalizar para string vazia"
902 );
903 let resultado: Result<(), AppError> = if normalized.is_empty() {
904 Err(AppError::Validation(
905 "name cannot be empty after normalization (input was blank or contained only hyphens/underscores/spaces)".to_string(),
906 ))
907 } else {
908 Ok(())
909 };
910 assert!(resultado.is_err());
911 if let Err(AppError::Validation(msg)) = resultado {
912 assert!(
913 msg.contains("empty after normalization"),
914 "mensagem deve mencionar 'empty after normalization', obteve: {msg}"
915 );
916 }
917 }
918
919 #[test]
920 fn remember_response_relationships_truncated_serializa_campo() {
921 let resp_false = RememberResponse {
923 memory_id: 1,
924 name: "test".to_string(),
925 namespace: "global".to_string(),
926 action: "created".to_string(),
927 operation: "created".to_string(),
928 version: 1,
929 entities_persisted: 2,
930 relationships_persisted: 1,
931 relationships_truncated: false,
932 chunks_created: 1,
933 chunks_persisted: 0,
934 urls_persisted: 0,
935 extraction_method: None,
936 merged_into_memory_id: None,
937 warnings: vec![],
938 created_at: 0,
939 created_at_iso: "1970-01-01T00:00:00Z".to_string(),
940 elapsed_ms: 0,
941 };
942 let json_false = serde_json::to_value(&resp_false).expect("serialização falhou");
943 assert_eq!(json_false["relationships_truncated"], false);
944
945 let resp_true = RememberResponse {
946 relationships_truncated: true,
947 ..resp_false
948 };
949 let json_true = serde_json::to_value(&resp_true).expect("serialização falhou");
950 assert_eq!(json_true["relationships_truncated"], true);
951 }
952
953 #[test]
954 fn is_valid_entity_type_accepts_v008_types() {
955 assert!(super::is_valid_entity_type("organization"));
957 assert!(super::is_valid_entity_type("location"));
958 assert!(super::is_valid_entity_type("date"));
959 assert!(!super::is_valid_entity_type("unknown_type_xyz"));
960 }
961}