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