Skip to main content

sqlite_graphrag/commands/
remember.rs

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