Skip to main content

sqlite_graphrag/commands/
remember.rs

1//! Handler for the `remember` CLI subcommand.
2
3use crate::chunking;
4use crate::cli::MemoryType;
5use crate::entity_type::EntityType;
6use crate::errors::AppError;
7use crate::i18n::errors_msg;
8use crate::output::{self, JsonOutputFormat, RememberResponse};
9use crate::paths::AppPaths;
10use crate::storage::chunks as storage_chunks;
11use crate::storage::connection::{ensure_schema, open_rw};
12use crate::storage::entities::{NewEntity, NewRelationship};
13use crate::storage::memories::NewMemory;
14use crate::storage::{entities, memories, urls as storage_urls, versions};
15use serde::Deserialize;
16
17/// Returns the number of rows that will be written to `memory_chunks` for the
18/// given chunk count. Single-chunk bodies are stored directly in the
19/// `memories` row, so no chunk row is appended (returns `0`). Multi-chunk
20/// bodies persist every chunk and the count equals `chunks_created`.
21///
22/// Centralized as a function so the H-M8 invariant is unit-testable without
23/// running the full handler. The schema for `chunks_persisted` documents this
24/// contract explicitly (see `docs/schemas/remember.schema.json`).
25fn compute_chunks_persisted(chunks_created: usize) -> usize {
26    if chunks_created > 1 {
27        chunks_created
28    } else {
29        0
30    }
31}
32
33#[derive(clap::Args)]
34#[command(after_long_help = "EXAMPLES:\n  \
35    # Create a memory with inline body\n  \
36    sqlite-graphrag remember --name design-auth --type decision \\\n    \
37    --description \"auth design\" --body \"JWT for stateless auth\"\n\n  \
38    # Create with curated graph via --graph-stdin\n  \
39    echo '{\"body\":\"...\",\"entities\":[],\"relationships\":[]}' | \\\n    \
40    sqlite-graphrag remember --name my-mem --type note --description \"desc\" --graph-stdin\n\n  \
41    # Enable automatic URL extraction with --graph-stdin (URL-regex only since v1.0.79)\n  \
42    echo '{\"body\":\"See https://docs.rs ...\",\"entities\":[],\"relationships\":[]}' | \\\n    \
43    sqlite-graphrag remember --name url-test --type note --description \"test\" \\\n    \
44    --graph-stdin --enable-ner\n\n  \
45    # Idempotent upsert with --force-merge\n  \
46    sqlite-graphrag remember --name my-mem --type note --description \"updated\" \\\n    \
47    --body \"new content\" --force-merge\n\n\
48NOTE:\n  \
49    remember does NOT accept positional arguments.\n  \
50    Use --body \"text\" for inline content\n  \
51    Use --body-file path for file content\n  \
52    Use --body-stdin for piped content\n  \
53    Use --graph-stdin for JSON with entities and relationships\n\n\
54ENTITY TYPES (for --graph-stdin entities, NOT memory --type):\n  \
55    concept, tool, person, file, project, decision, incident,\n  \
56    organization, location, date, dashboard, issue_tracker, memory\n  \
57    WARNING: reference, skill, document, note, user, feedback are\n  \
58    MEMORY types only — NOT valid for entities.\n  \
59    Mapping: reference→concept, document→file, user→person")]
60pub struct RememberArgs {
61    /// Memory name in kebab-case (lowercase letters, digits, hyphens).
62    /// Acts as unique key within the namespace; collisions trigger merge or rejection.
63    #[arg(long)]
64    pub name: String,
65    #[arg(
66        long,
67        value_enum,
68        long_help = "Memory kind stored in `memories.type`. Required when creating a new memory. Optional with --force-merge: if omitted the existing memory type is inherited. This is NOT the graph `entity_type` used in `--entities-file`. Valid values: user, feedback, project, reference, decision, incident, skill, document, note."
69    )]
70    pub r#type: Option<MemoryType>,
71    /// Short description (≤500 chars) summarizing the memory for use in `list` and `recall` snippets.
72    /// Required when creating a new memory. Optional with --force-merge: if omitted the existing description is inherited.
73    #[arg(long)]
74    pub description: Option<String>,
75    /// Inline body content. Mutually exclusive with --body-file, --body-stdin, --graph-stdin.
76    /// Maximum 512000 bytes; rejected if empty without an external graph.
77    #[arg(
78        long,
79        help = "Inline body content (max 500 KB / 512000 bytes; for larger inputs split into multiple memories or use --body-file)",
80        conflicts_with_all = ["body_file", "body_stdin", "graph_stdin"]
81    )]
82    pub body: Option<String>,
83    #[arg(
84        long,
85        help = "Read body from a file instead of --body",
86        conflicts_with_all = ["body", "body_stdin", "graph_stdin"]
87    )]
88    pub body_file: Option<std::path::PathBuf>,
89    /// Read body from stdin until EOF. Useful in pipes (echo "..." | sqlite-graphrag remember ...).
90    /// Mutually exclusive with --body, --body-file, --graph-stdin.
91    #[arg(
92        long,
93        conflicts_with_all = ["body", "body_file", "graph_stdin"]
94    )]
95    pub body_stdin: bool,
96    #[arg(
97        long,
98        help = "JSON file containing entities to associate with this memory"
99    )]
100    pub entities_file: Option<std::path::PathBuf>,
101    #[arg(
102        long,
103        help = "JSON file containing relationships to associate with this memory"
104    )]
105    pub relationships_file: Option<std::path::PathBuf>,
106    #[arg(
107        long,
108        help = "Read graph JSON (body + entities + relationships) from stdin",
109        conflicts_with_all = [
110            "body",
111            "body_file",
112            "body_stdin",
113            "entities_file",
114            "relationships_file"
115        ]
116    )]
117    pub graph_stdin: bool,
118    #[arg(
119        long,
120        help = "Namespace (env: SQLITE_GRAPHRAG_NAMESPACE, default: global)"
121    )]
122    pub namespace: Option<String>,
123    /// Inline JSON object with arbitrary metadata key-value pairs. Mutually exclusive with --metadata-file.
124    #[arg(long)]
125    pub metadata: Option<String>,
126    #[arg(long, help = "JSON file containing metadata key-value pairs")]
127    pub metadata_file: Option<std::path::PathBuf>,
128    #[arg(long)]
129    pub force_merge: bool,
130    #[arg(
131        long,
132        value_name = "EPOCH_OR_RFC3339",
133        value_parser = crate::parsers::parse_expected_updated_at,
134        long_help = "Optimistic lock: reject if updated_at does not match. \
135Accepts Unix epoch (e.g. 1700000000) or RFC 3339 (e.g. 2026-04-19T12:00:00Z)."
136    )]
137    pub expected_updated_at: Option<i64>,
138    #[arg(
139        long,
140        env = "SQLITE_GRAPHRAG_ENABLE_NER",
141        value_parser = crate::parsers::parse_bool_flexible,
142        action = clap::ArgAction::Set,
143        num_args = 0..=1,
144        default_missing_value = "true",
145        default_value = "false",
146        help = "Enable automatic URL-regex extraction from body (the GLiNER NER pipeline was removed in v1.0.79)"
147    )]
148    pub enable_ner: bool,
149    #[arg(
150        long,
151        env = "SQLITE_GRAPHRAG_GLINER_VARIANT",
152        default_value = "fp32",
153        help = "DEPRECATED: no effect since v1.0.79 (the GLiNER pipeline was removed); accepted for compatibility only"
154    )]
155    pub gliner_variant: String,
156    #[arg(long, hide = true)]
157    pub skip_extraction: bool,
158    /// Explicitly clear the body content (set to empty string). Required to distinguish
159    /// intentional body clearing from accidental omission during --force-merge.
160    /// Without this flag, an empty body passed to --force-merge preserves the existing body.
161    #[arg(
162        long,
163        default_value_t = false,
164        help = "Explicitly clear body content during --force-merge (without this flag, an empty body is ignored and the existing body is kept)"
165    )]
166    pub clear_body: bool,
167    /// Validate input and report planned actions without persisting.
168    #[arg(
169        long,
170        default_value_t = false,
171        help = "Validate input and report planned actions without persisting"
172    )]
173    pub dry_run: bool,
174    /// Optional opaque session identifier for tracing memory provenance across multi-agent runs.
175    #[arg(long)]
176    pub session_id: Option<String>,
177    #[arg(long, value_enum, default_value_t = JsonOutputFormat::Json)]
178    pub format: JsonOutputFormat,
179    #[arg(long, hide = true, help = "No-op; JSON is always emitted on stdout")]
180    pub json: bool,
181    #[arg(long, env = "SQLITE_GRAPHRAG_DB_PATH")]
182    pub db: Option<String>,
183    /// Maximum process RSS in MiB; abort if exceeded during embedding.
184    #[arg(long, default_value_t = crate::constants::DEFAULT_MAX_RSS_MB,
185          help = "Maximum process RSS in MiB; abort if exceeded during embedding (default: 8192)")]
186    pub max_rss_mb: u64,
187    /// Emit a warning (but do not reject) when persisting an entity whose degree would
188    /// exceed this value after the upsert. Default 50. Set 0 to disable the check.
189    #[arg(long, default_value_t = 50, value_name = "N")]
190    pub max_entity_degree: u32,
191    /// G42/S3 (v1.0.79): maximum simultaneous LLM embedding subprocesses.
192    /// The effective value is further bounded by CPU count and available
193    /// RAM (permits = min(N, cpus, ram_livre*0.5/350MB), clamp [1, 32]).
194    #[arg(long, default_value_t = 4, value_name = "N",
195          value_parser = clap::value_parser!(u64).range(1..=32),
196          help = "Maximum simultaneous LLM embedding subprocesses (default: 4, clamp [1,32])")]
197    pub llm_parallelism: u64,
198}
199
200#[derive(Deserialize, Default)]
201#[serde(deny_unknown_fields)]
202struct GraphInput {
203    #[serde(default)]
204    body: Option<String>,
205    #[serde(default)]
206    entities: Vec<NewEntity>,
207    #[serde(default)]
208    relationships: Vec<NewRelationship>,
209}
210
211fn normalize_and_validate_graph_input(graph: &mut GraphInput) -> Result<(), AppError> {
212    for rel in &mut graph.relationships {
213        rel.relation = crate::parsers::normalize_relation(&rel.relation);
214        if let Err(e) = crate::parsers::validate_relation_format(&rel.relation) {
215            return Err(AppError::Validation(format!(
216                "{e} for relationship '{}' -> '{}'",
217                rel.source, rel.target
218            )));
219        }
220        crate::parsers::warn_if_non_canonical(&rel.relation);
221        if !(0.0..=1.0).contains(&rel.strength) {
222            return Err(AppError::Validation(format!(
223                "invalid strength {} for relationship '{}' -> '{}'; expected value in [0.0, 1.0]",
224                rel.strength, rel.source, rel.target
225            )));
226        }
227    }
228
229    Ok(())
230}
231
232#[tracing::instrument(skip_all, level = "debug", name = "remember")]
233pub fn run(args: RememberArgs) -> Result<(), AppError> {
234    use crate::constants::*;
235
236    let inicio = std::time::Instant::now();
237    let _ = args.format;
238    tracing::debug!(target: "remember", name = %args.name, "persisting memory");
239    let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
240
241    // Capture the original `--name` before normalization so the JSON response can
242    // surface `name_was_normalized` + `original_name` (B_4 in v1.0.32). Stored as
243    // an owned String because `args.name` is moved into the response below.
244    let original_name = args.name.clone();
245
246    // Auto-normalize to kebab-case before validation (P2-H).
247    // v1.0.20: also trims hyphens at the boundary (including trailing) to avoid rejection
248    // after truncation by a long filename ending in a hyphen.
249    let normalized_name = {
250        let lower = args.name.to_lowercase().replace(['_', ' '], "-");
251        let trimmed = lower.trim_matches('-').to_string();
252        if trimmed != args.name {
253            tracing::warn!(target: "remember",
254                original = %args.name,
255                normalized = %trimmed,
256                "name auto-normalized to kebab-case"
257            );
258        }
259        trimmed
260    };
261    let name_was_normalized = normalized_name != original_name;
262
263    if normalized_name.is_empty() {
264        return Err(AppError::Validation(
265            "name cannot be empty after normalization (input was blank or contained only hyphens/underscores/spaces)".to_string(),
266        ));
267    }
268    if normalized_name.len() > MAX_MEMORY_NAME_LEN {
269        return Err(AppError::LimitExceeded(
270            crate::i18n::validation::name_length(MAX_MEMORY_NAME_LEN),
271        ));
272    }
273
274    if normalized_name.starts_with("__") {
275        return Err(AppError::Validation(
276            crate::i18n::validation::reserved_name(),
277        ));
278    }
279
280    {
281        let slug_re = crate::constants::name_slug_regex();
282        if !slug_re.is_match(&normalized_name) {
283            return Err(AppError::Validation(crate::i18n::validation::name_kebab(
284                &normalized_name,
285            )));
286        }
287    }
288
289    if let Some(ref desc) = args.description {
290        if desc.len() > MAX_MEMORY_DESCRIPTION_LEN {
291            return Err(AppError::Validation(
292                crate::i18n::validation::description_exceeds(MAX_MEMORY_DESCRIPTION_LEN),
293            ));
294        }
295    }
296
297    let mut raw_body = if let Some(b) = args.body {
298        b
299    } else if let Some(ref path) = args.body_file {
300        let file_size = std::fs::metadata(path).map_err(AppError::Io)?.len();
301        if file_size > MAX_MEMORY_BODY_LEN as u64 {
302            return Err(AppError::LimitExceeded(
303                crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
304            ));
305        }
306        match std::fs::read_to_string(path) {
307            Ok(s) => s,
308            Err(e) if e.kind() == std::io::ErrorKind::InvalidData => {
309                let bytes = std::fs::read(path).map_err(AppError::Io)?;
310                tracing::warn!(target: "remember", "body file contains invalid UTF-8; replacing invalid sequences");
311                String::from_utf8_lossy(&bytes).into_owned()
312            }
313            Err(e) => return Err(AppError::Io(e)),
314        }
315    } else if args.body_stdin || args.graph_stdin {
316        crate::stdin_helper::read_stdin_with_timeout(60)?
317    } else {
318        String::new()
319    };
320
321    let mut entities_provided_externally =
322        args.entities_file.is_some() || args.relationships_file.is_some();
323
324    let mut graph = GraphInput::default();
325    if let Some(path) = args.entities_file {
326        let file_size = std::fs::metadata(&path).map_err(AppError::Io)?.len();
327        if file_size > MAX_MEMORY_BODY_LEN as u64 {
328            return Err(AppError::LimitExceeded(
329                crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
330            ));
331        }
332        let content = std::fs::read_to_string(&path).map_err(AppError::Io)?;
333        graph.entities = serde_json::from_str(&content)?;
334    }
335    if let Some(path) = args.relationships_file {
336        let file_size = std::fs::metadata(&path).map_err(AppError::Io)?.len();
337        if file_size > MAX_MEMORY_BODY_LEN as u64 {
338            return Err(AppError::LimitExceeded(
339                crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
340            ));
341        }
342        let content = std::fs::read_to_string(&path).map_err(AppError::Io)?;
343        graph.relationships = serde_json::from_str(&content)?;
344    }
345    if args.graph_stdin {
346        graph = serde_json::from_str::<GraphInput>(&raw_body).map_err(|e| {
347            AppError::Validation(format!("invalid JSON payload on --graph-stdin: {e}"))
348        })?;
349        raw_body = graph.body.take().unwrap_or_default();
350    }
351    if args.graph_stdin && !graph.entities.is_empty() {
352        entities_provided_externally = true;
353    }
354
355    if graph.entities.len() > max_entities_per_memory() {
356        return Err(AppError::LimitExceeded(errors_msg::entity_limit_exceeded(
357            max_entities_per_memory(),
358        )));
359    }
360    let mut relationships_truncated = false;
361    let rel_cap = max_relationships_per_memory();
362    if graph.relationships.len() > rel_cap {
363        tracing::warn!(target: "remember",
364            count = graph.relationships.len(),
365            cap = rel_cap,
366            "truncating relationships to cap"
367        );
368        graph.relationships.truncate(rel_cap);
369        relationships_truncated = true;
370    }
371    normalize_and_validate_graph_input(&mut graph)?;
372
373    if raw_body.len() > MAX_MEMORY_BODY_LEN {
374        return Err(AppError::LimitExceeded(
375            crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
376        ));
377    }
378
379    // v1.0.22 P1: reject empty or whitespace-only body when no external graph is provided.
380    // Without this check, empty embeddings would be persisted, breaking recall semantics.
381    // GAP-08: skip this guard when --force-merge without --clear-body; the existing body
382    // will be preserved from the database, so the effective body will not be empty.
383    let body_will_be_preserved = args.force_merge && raw_body.trim().is_empty() && !args.clear_body;
384    if !entities_provided_externally
385        && graph.entities.is_empty()
386        && raw_body.trim().is_empty()
387        && !body_will_be_preserved
388        && !args.clear_body
389    {
390        return Err(AppError::Validation(crate::i18n::validation::empty_body()));
391    }
392
393    let metadata: serde_json::Value = if let Some(m) = args.metadata {
394        serde_json::from_str(&m)?
395    } else if let Some(path) = args.metadata_file {
396        let file_size = std::fs::metadata(&path).map_err(AppError::Io)?.len();
397        if file_size > MAX_MEMORY_BODY_LEN as u64 {
398            return Err(AppError::LimitExceeded(
399                crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
400            ));
401        }
402        let content = std::fs::read_to_string(&path).map_err(AppError::Io)?;
403        serde_json::from_str(&content)?
404    } else {
405        serde_json::json!({})
406    };
407
408    let mut body_hash = blake3::hash(raw_body.as_bytes()).to_hex().to_string();
409    let mut snippet: String = raw_body.chars().take(200).collect();
410
411    let paths = AppPaths::resolve(args.db.as_deref())?;
412    paths.ensure_dirs()?;
413
414    // v1.0.20: use .trim().is_empty() to reject bodies that are only whitespace.
415    let mut extraction_method: Option<String> = None;
416    let mut extracted_urls: Vec<crate::extraction::ExtractedUrl> = Vec::with_capacity(4);
417    if args.enable_ner && args.skip_extraction {
418        return Err(AppError::Validation(
419            "--enable-ner and --skip-extraction are mutually exclusive; remove one".to_string(),
420        ));
421    }
422    if args.skip_extraction && !args.enable_ner {
423        // v1.0.74: revert to v1.0.45 hidden no-op behavior. The v1.0.67
424        // commit (9ddb17b) promoted this to a hard validation error, which
425        // broke the "kept as a hidden no-op for backwards compatibility"
426        // promise documented in CHANGELOG v1.0.45 and started failing
427        // 5+ CI jobs whose E2E tests use this flag to skip the
428        // GLiNER-ONNX model download in CI environments.
429        tracing::warn!(
430            "--skip-extraction is deprecated since v1.0.45 and has no effect (NER is disabled by default); remove this flag to silence the warning"
431        );
432    }
433    // v1.0.79: --gliner-variant is a no-op kept for compatibility; a
434    // non-default value signals the caller still expects the removed
435    // GLiNER pipeline, so warn explicitly.
436    if args.gliner_variant != "fp32" {
437        tracing::warn!(
438            "--gliner-variant is deprecated and has no effect since v1.0.79 (the GLiNER pipeline was removed); --enable-ner performs URL-regex extraction only"
439        );
440    }
441    let gliner_variant: crate::extraction::GlinerVariant = match args.gliner_variant.as_str() {
442        "int8" => crate::extraction::GlinerVariant::Int8,
443        _ => crate::extraction::GlinerVariant::Fp32,
444    };
445    if args.enable_ner && graph.entities.is_empty() && !raw_body.trim().is_empty() {
446        match crate::extraction::extract_graph_auto(&raw_body, &paths, gliner_variant) {
447            Ok(extracted) => {
448                // v1.0.76: ExtractionResult is URL + entity + elapsed_ms;
449                // the LLM ExtractionBackend returns typed relationships
450                // separately. The default build is URL-only extraction.
451                extraction_method = Some("url-regex".to_string());
452                extracted_urls = extracted.urls;
453                // Convert ExtractedEntity → NewEntity (no offsets,
454                // type defaults to Concept).
455                graph.entities = extracted
456                    .entities
457                    .into_iter()
458                    .map(|e| NewEntity {
459                        name: e.name,
460                        entity_type: crate::entity_type::EntityType::Concept,
461                        description: None,
462                    })
463                    .collect();
464                graph.relationships.clear();
465                relationships_truncated = false;
466
467                if graph.entities.len() > max_entities_per_memory() {
468                    graph.entities.truncate(max_entities_per_memory());
469                }
470                if graph.relationships.len() > max_relationships_per_memory() {
471                    relationships_truncated = true;
472                    graph.relationships.truncate(max_relationships_per_memory());
473                }
474                normalize_and_validate_graph_input(&mut graph)?;
475            }
476            Err(e) => {
477                tracing::warn!(target: "remember", error = %e, "auto-extraction failed, graceful degradation");
478                extraction_method = Some("none:extraction-failed".to_string());
479            }
480        }
481    }
482
483    let mut conn = open_rw(&paths.db)?;
484    ensure_schema(&mut conn)?;
485
486    // --dry-run: emit planned action without any DB writes and return.
487    if args.dry_run {
488        let existing = memories::find_by_name(&conn, &namespace, &normalized_name)?;
489        let planned_action = if existing.is_some() && args.force_merge {
490            "would_update"
491        } else {
492            "would_create"
493        };
494        output::emit_json(&serde_json::json!({
495            "dry_run": true,
496            "name": normalized_name,
497            "namespace": namespace,
498            "planned_action": planned_action,
499        }))?;
500        return Ok(());
501    }
502
503    {
504        use crate::constants::MAX_NAMESPACES_ACTIVE;
505        let active_count: u32 = conn.query_row(
506            "SELECT COUNT(DISTINCT namespace) FROM memories WHERE deleted_at IS NULL",
507            [],
508            |r| r.get::<_, i64>(0).map(|v| v as u32),
509        )?;
510        let ns_exists: bool = conn.query_row(
511            "SELECT EXISTS(SELECT 1 FROM memories WHERE namespace = ?1 AND deleted_at IS NULL)",
512            rusqlite::params![namespace],
513            |r| r.get::<_, i64>(0).map(|v| v > 0),
514        )?;
515        if !ns_exists && active_count >= MAX_NAMESPACES_ACTIVE {
516            return Err(AppError::NamespaceError(format!(
517                "active namespace limit of {MAX_NAMESPACES_ACTIVE} reached while trying to create '{namespace}'"
518            )));
519        }
520    }
521
522    // M7: detect soft-deleted memory before the standard duplicate check.
523    if let Some((sd_id, true)) =
524        memories::find_by_name_any_state(&conn, &namespace, &normalized_name)?
525    {
526        if args.force_merge {
527            memories::clear_deleted_at(&conn, sd_id)?;
528        } else {
529            return Err(AppError::Duplicate(
530                errors_msg::duplicate_memory_soft_deleted(&normalized_name, &namespace),
531            ));
532        }
533    }
534
535    let existing_memory = memories::find_by_name(&conn, &namespace, &normalized_name)?;
536    if existing_memory.is_some() && !args.force_merge {
537        return Err(AppError::Duplicate(errors_msg::duplicate_memory(
538            &normalized_name,
539            &namespace,
540        )));
541    }
542
543    // GAP-10: resolve type and description.
544    // For CREATE path (new memory): both are required.
545    // For UPDATE path (--force-merge on existing memory): inherit from existing row when omitted.
546    let (resolved_type, resolved_description) = if existing_memory.is_none() {
547        // CREATE path — both fields are mandatory.
548        let t = args.r#type.ok_or_else(|| {
549            AppError::Validation(
550                "--type and --description are required when creating a new memory".to_string(),
551            )
552        })?;
553        let d = args.description.clone().ok_or_else(|| {
554            AppError::Validation(
555                "--type and --description are required when creating a new memory".to_string(),
556            )
557        })?;
558        (t.as_str().to_string(), d)
559    } else {
560        // UPDATE path (--force-merge) — inherit missing fields from stored row.
561        let existing_row = memories::read_by_name(&conn, &namespace, &normalized_name)?
562            .ok_or_else(|| {
563                AppError::NotFound(format!(
564                    "memory '{normalized_name}' not found in namespace '{namespace}'"
565                ))
566            })?;
567        let t = args
568            .r#type
569            .map(|v| v.as_str().to_string())
570            .unwrap_or_else(|| existing_row.memory_type.clone());
571        let d = args
572            .description
573            .clone()
574            .unwrap_or_else(|| existing_row.description.clone());
575        (t, d)
576    };
577
578    // GAP-08/GAP-09: protect existing body from accidental destruction during --force-merge.
579    // When the caller omits a body (or passes an empty one) without --clear-body, silently
580    // preserve the existing body from the database.  This prevents a common scripting mistake
581    // where a cron job updates metadata fields and inadvertently wipes the stored content.
582    if body_will_be_preserved {
583        if let Some(existing_row) = memories::read_by_name(&conn, &namespace, &normalized_name)? {
584            if !existing_row.body.is_empty() {
585                tracing::debug!(target: "remember",
586                    name = %normalized_name,
587                    "GAP-08: empty body with --force-merge and no --clear-body; preserving existing body"
588                );
589                raw_body = existing_row.body;
590                body_hash = blake3::hash(raw_body.as_bytes()).to_hex().to_string();
591                snippet = raw_body.chars().take(200).collect();
592            }
593        }
594    }
595
596    let duplicate_hash_id = memories::find_by_hash(&conn, &namespace, &body_hash)?;
597
598    output::emit_progress_i18n(
599        &format!(
600            "Remember stage: validated input; available memory {} MB",
601            crate::memory_guard::available_memory_mb()
602        ),
603        &format!(
604            "Stage remember: input validated; available memory {} MB",
605            crate::memory_guard::available_memory_mb()
606        ),
607    );
608
609    let model_max_length = crate::tokenizer::get_model_max_length();
610    let total_passage_tokens = crate::tokenizer::count_passage_tokens(&raw_body)?;
611    let chunks_info = chunking::split_into_chunks_hierarchical(&raw_body);
612    let chunks_created = chunks_info.len();
613    // For single-chunk bodies the memory row itself stores the content and no
614    // entry is appended to `memory_chunks` (see line ~545). For multi-chunk
615    // bodies every chunk is persisted via `insert_chunk_slices`.
616    let chunks_persisted = compute_chunks_persisted(chunks_info.len());
617
618    output::emit_progress_i18n(
619        &format!(
620            "Remember stage: tokenizer counted {total_passage_tokens} passage tokens (model max {model_max_length}); chunking produced {} chunks; process RSS {} MB",
621            chunks_created,
622            crate::memory_guard::current_process_memory_mb().unwrap_or(0)
623        ),
624        &format!(
625            "Stage remember: tokenizer counted {total_passage_tokens} passage tokens (model max {model_max_length}); chunking produced {} chunks; process RSS {} MB",
626            chunks_created,
627            crate::memory_guard::current_process_memory_mb().unwrap_or(0)
628        ),
629    );
630
631    if chunks_created > crate::constants::REMEMBER_MAX_SAFE_MULTI_CHUNKS {
632        return Err(AppError::LimitExceeded(format!(
633            "document produces {chunks_created} chunks; current safe operational limit is {} chunks; split the document before using remember",
634            crate::constants::REMEMBER_MAX_SAFE_MULTI_CHUNKS
635        )));
636    }
637
638    output::emit_progress_i18n("Computing embedding...", "Calculando embedding...");
639    let mut chunk_embeddings_cache: Option<Vec<Vec<f32>>> = None;
640
641    let embedding = if chunks_info.len() == 1 {
642        crate::embedder::embed_passage_local(&paths.models, &raw_body)?
643    } else {
644        let chunk_texts: Vec<String> = chunks_info
645            .iter()
646            .map(|c| chunking::chunk_text(&raw_body, c).to_string())
647            .collect();
648        // G42/S2+S3 (v1.0.79): chunks are embedded in dim-adaptive
649        // batches per LLM call (G44: clamp(base*64/dim, 1, base)), with up to
650        // --llm-parallelism bounded subprocesses in flight. The old
651        // serial loop spent SUM(items) wall time; the fan-out spends
652        // roughly MAX(batch).
653        output::emit_progress_i18n(
654            &format!(
655                "Embedding {} chunks in parallel batches (parallelism {})...",
656                chunks_info.len(),
657                args.llm_parallelism
658            ),
659            &format!(
660                "Embedding {} chunks em lotes paralelos (paralelismo {})...",
661                chunks_info.len(),
662                args.llm_parallelism
663            ),
664        );
665        if let Some(rss) = crate::memory_guard::current_process_memory_mb() {
666            if rss > args.max_rss_mb {
667                tracing::error!(target: "remember",
668                    rss_mb = rss,
669                    max_rss_mb = args.max_rss_mb,
670                    "RSS exceeded --max-rss-mb threshold; aborting to prevent system instability"
671                );
672                return Err(AppError::LowMemory {
673                    available_mb: crate::memory_guard::available_memory_mb(),
674                    required_mb: args.max_rss_mb,
675                });
676            }
677        }
678        let chunk_embeddings = crate::embedder::embed_passages_parallel_local(
679            &paths.models,
680            &chunk_texts,
681            args.llm_parallelism as usize,
682            crate::embedder::chunk_embed_batch_size(),
683        )?;
684        output::emit_progress_i18n(
685            &format!(
686                "Remember stage: chunk embeddings complete; process RSS {} MB",
687                crate::memory_guard::current_process_memory_mb().unwrap_or(0)
688            ),
689            &format!(
690                "Stage remember: chunk embeddings completed; process RSS {} MB",
691                crate::memory_guard::current_process_memory_mb().unwrap_or(0)
692            ),
693        );
694        let aggregated = chunking::aggregate_embeddings(&chunk_embeddings);
695        chunk_embeddings_cache = Some(chunk_embeddings);
696        aggregated
697    };
698    let body_for_storage = raw_body;
699
700    let memory_type = resolved_type.as_str();
701    let new_memory = NewMemory {
702        namespace: namespace.clone(),
703        name: normalized_name.clone(),
704        memory_type: memory_type.to_string(),
705        description: resolved_description.clone(),
706        body: body_for_storage,
707        body_hash: body_hash.clone(),
708        session_id: args.session_id.clone(),
709        source: "agent".to_string(),
710        metadata,
711    };
712
713    let mut warnings = Vec::with_capacity(4);
714    let mut entities_persisted = 0usize;
715    let mut relationships_persisted = 0usize;
716
717    // G42/S2+A4 (v1.0.79): entity names are SHORT texts — they get their
718    // own batch profile (25 per LLM call) instead of one subprocess per
719    // 3-15 byte name (21 names used to cost ~12 minutes, 46% of the
720    // measured remember total).
721    let entity_texts: Vec<String> = graph
722        .entities
723        .iter()
724        .map(|entity| match &entity.description {
725            Some(desc) => format!("{} {}", entity.name, desc),
726            None => entity.name.clone(),
727        })
728        .collect();
729    let graph_entity_embeddings = crate::embedder::embed_passages_parallel_local(
730        &paths.models,
731        &entity_texts,
732        args.llm_parallelism as usize,
733        crate::embedder::entity_embed_batch_size(),
734    )?;
735
736    let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
737
738    let mut skip_reindex = false;
739    let (memory_id, action, version) = match existing_memory {
740        Some((existing_id, _updated_at, _current_version)) => {
741            if let Some(hash_id) = duplicate_hash_id {
742                if hash_id != existing_id {
743                    warnings.push(format!(
744                        "identical body already exists as memory id {hash_id}"
745                    ));
746                }
747            }
748
749            // C1 fix: capture old values for FTS5 sync before update
750            let (old_fts_name, old_fts_desc, old_fts_body): (String, String, String) = tx
751                .query_row(
752                    "SELECT name, description, body FROM memories WHERE id = ?1",
753                    rusqlite::params![existing_id],
754                    |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
755                )?;
756
757            // G15: skip re-indexing when body hash matches (common in --force-merge loops)
758            let existing_body_hash: Option<String> = tx
759                .query_row(
760                    "SELECT body_hash FROM memories WHERE id = ?1",
761                    rusqlite::params![existing_id],
762                    |r| r.get(0),
763                )
764                .ok();
765            let body_unchanged = existing_body_hash.as_deref() == Some(&body_hash);
766            skip_reindex = body_unchanged;
767            if !body_unchanged {
768                storage_chunks::delete_chunks(&tx, existing_id)?;
769            }
770
771            let next_v = versions::next_version(&tx, existing_id)?;
772            memories::update(&tx, existing_id, &new_memory, args.expected_updated_at)?;
773
774            // C1 fix: sync FTS5 external-content index after update
775            // (trg_fts_au trigger is absent by design due to sqlite-vec conflict)
776            memories::sync_fts_after_update(
777                &tx,
778                existing_id,
779                &old_fts_name,
780                &old_fts_desc,
781                &old_fts_body,
782                &normalized_name,
783                &resolved_description,
784                &new_memory.body,
785            )?;
786
787            versions::insert_version(
788                &tx,
789                existing_id,
790                next_v,
791                &normalized_name,
792                memory_type,
793                &resolved_description,
794                &new_memory.body,
795                &serde_json::to_string(&new_memory.metadata)?,
796                None,
797                "edit",
798            )?;
799            if !body_unchanged {
800                memories::upsert_vec(
801                    &tx,
802                    existing_id,
803                    &namespace,
804                    memory_type,
805                    &embedding,
806                    &normalized_name,
807                    &snippet,
808                )?;
809            }
810            (existing_id, "updated".to_string(), next_v)
811        }
812        None => {
813            if let Some(hash_id) = duplicate_hash_id {
814                warnings.push(format!(
815                    "identical body already exists as memory id {hash_id}"
816                ));
817            }
818            let id = memories::insert(&tx, &new_memory)?;
819            versions::insert_version(
820                &tx,
821                id,
822                1,
823                &normalized_name,
824                memory_type,
825                &resolved_description,
826                &new_memory.body,
827                &serde_json::to_string(&new_memory.metadata)?,
828                None,
829                "create",
830            )?;
831            memories::upsert_vec(
832                &tx,
833                id,
834                &namespace,
835                memory_type,
836                &embedding,
837                &normalized_name,
838                &snippet,
839            )?;
840            (id, "created".to_string(), 1)
841        }
842    };
843
844    if chunks_info.len() > 1 && !skip_reindex {
845        storage_chunks::insert_chunk_slices(&tx, memory_id, &new_memory.body, &chunks_info)?;
846
847        let chunk_embeddings = chunk_embeddings_cache.take().ok_or_else(|| {
848            AppError::Internal(anyhow::anyhow!(
849                "chunk embeddings cache missing in multi-chunk remember path"
850            ))
851        })?;
852
853        for (i, emb) in chunk_embeddings.iter().enumerate() {
854            storage_chunks::upsert_chunk_vec(&tx, i as i64, memory_id, i as i32, emb)?;
855        }
856        output::emit_progress_i18n(
857            &format!(
858                "Remember stage: persisted chunk vectors; process RSS {} MB",
859                crate::memory_guard::current_process_memory_mb().unwrap_or(0)
860            ),
861            &format!(
862                "Etapa remember: vetores de chunks persistidos; RSS do processo {} MB",
863                crate::memory_guard::current_process_memory_mb().unwrap_or(0)
864            ),
865        );
866    }
867
868    if !graph.entities.is_empty() || !graph.relationships.is_empty() {
869        for entity in &graph.entities {
870            let entity_id = entities::upsert_entity(&tx, &namespace, entity)?;
871            let entity_embedding = &graph_entity_embeddings[entities_persisted];
872            entities::upsert_entity_vec(
873                &tx,
874                entity_id,
875                &namespace,
876                entity.entity_type,
877                entity_embedding,
878                &entity.name,
879            )?;
880            entities::link_memory_entity(&tx, memory_id, entity_id)?;
881            entities::increment_degree(&tx, entity_id)?;
882            // GAP-17: warn when entity degree exceeds the configured cap.
883            if args.max_entity_degree > 0 {
884                let cap = args.max_entity_degree as i64;
885                let degree: i64 = tx.query_row(
886                    "SELECT degree FROM entities WHERE id = ?1",
887                    rusqlite::params![entity_id],
888                    |r| r.get(0),
889                )?;
890                if degree > cap {
891                    tracing::warn!(target: "remember",
892                        entity = %entity.name,
893                        degree = degree,
894                        cap = cap,
895                        "entity degree cap exceeded"
896                    );
897                }
898            }
899            entities_persisted += 1;
900        }
901        let entity_types: std::collections::HashMap<&str, EntityType> = graph
902            .entities
903            .iter()
904            .map(|entity| (entity.name.as_str(), entity.entity_type))
905            .collect();
906
907        for rel in &graph.relationships {
908            let source_entity = NewEntity {
909                name: rel.source.clone(),
910                entity_type: entity_types
911                    .get(rel.source.as_str())
912                    .copied()
913                    .unwrap_or(EntityType::Concept),
914                description: None,
915            };
916            let target_entity = NewEntity {
917                name: rel.target.clone(),
918                entity_type: entity_types
919                    .get(rel.target.as_str())
920                    .copied()
921                    .unwrap_or(EntityType::Concept),
922                description: None,
923            };
924            let source_id = entities::upsert_entity(&tx, &namespace, &source_entity)?;
925            let target_id = entities::upsert_entity(&tx, &namespace, &target_entity)?;
926            let rel_id = entities::upsert_relationship(&tx, &namespace, source_id, target_id, rel)?;
927            entities::link_memory_relationship(&tx, memory_id, rel_id)?;
928            relationships_persisted += 1;
929        }
930    }
931    tx.commit()?;
932
933    // v1.0.24 P0-2: persist URLs in a dedicated table, outside the main transaction.
934    // Failures do not propagate — non-critical path with graceful degradation.
935    let urls_persisted = if !extracted_urls.is_empty() {
936        let url_entries: Vec<storage_urls::MemoryUrl> = extracted_urls
937            .into_iter()
938            .map(|u| storage_urls::MemoryUrl {
939                url: u.url,
940                offset: Some(u.start as i64),
941            })
942            .collect();
943        storage_urls::insert_urls(&conn, memory_id, &url_entries)
944    } else {
945        0
946    };
947
948    conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
949
950    let created_at_epoch = chrono::Utc::now().timestamp();
951    let created_at_iso = crate::tz::format_iso(chrono::Utc::now());
952
953    output::emit_json(&RememberResponse {
954        memory_id,
955        // Persist the normalized (kebab-case) slug as `name` since that is the
956        // storage key. The original input is exposed via `original_name` only
957        // when normalization actually changed something (B_4 in v1.0.32).
958        name: normalized_name.clone(),
959        namespace,
960        action: action.clone(),
961        operation: action,
962        version,
963        entities_persisted,
964        relationships_persisted,
965        relationships_truncated,
966        chunks_created,
967        chunks_persisted,
968        urls_persisted,
969        extraction_method,
970        merged_into_memory_id: None,
971        warnings,
972        created_at: created_at_epoch,
973        created_at_iso,
974        elapsed_ms: inicio.elapsed().as_millis() as u64,
975        name_was_normalized,
976        original_name: name_was_normalized.then_some(original_name),
977    })?;
978
979    Ok(())
980}
981
982#[cfg(test)]
983mod tests {
984    use super::compute_chunks_persisted;
985    use crate::output::RememberResponse;
986
987    // Bug H-M8: chunks_persisted contract is unit-testable and matches schema.
988    #[test]
989    fn chunks_persisted_zero_for_zero_chunks() {
990        assert_eq!(compute_chunks_persisted(0), 0);
991    }
992
993    #[test]
994    fn chunks_persisted_zero_for_single_chunk_body() {
995        // Single-chunk bodies live in the memories row itself; no row is
996        // appended to memory_chunks. This is the documented contract.
997        assert_eq!(compute_chunks_persisted(1), 0);
998    }
999
1000    #[test]
1001    fn chunks_persisted_equals_count_for_multi_chunk_body() {
1002        // Every chunk above the first triggers a row in memory_chunks.
1003        assert_eq!(compute_chunks_persisted(2), 2);
1004        assert_eq!(compute_chunks_persisted(7), 7);
1005        assert_eq!(compute_chunks_persisted(64), 64);
1006    }
1007
1008    #[test]
1009    fn remember_response_serializes_required_fields() {
1010        let resp = RememberResponse {
1011            memory_id: 42,
1012            name: "minha-mem".to_string(),
1013            namespace: "global".to_string(),
1014            action: "created".to_string(),
1015            operation: "created".to_string(),
1016            version: 1,
1017            entities_persisted: 0,
1018            relationships_persisted: 0,
1019            relationships_truncated: false,
1020            chunks_created: 1,
1021            chunks_persisted: 0,
1022            urls_persisted: 0,
1023            extraction_method: None,
1024            merged_into_memory_id: None,
1025            warnings: vec![],
1026            created_at: 1_705_320_000,
1027            created_at_iso: "2024-01-15T12:00:00Z".to_string(),
1028            elapsed_ms: 55,
1029            name_was_normalized: false,
1030            original_name: None,
1031        };
1032
1033        let json = serde_json::to_value(&resp).expect("serialization failed");
1034        assert_eq!(json["memory_id"], 42);
1035        assert_eq!(json["action"], "created");
1036        assert_eq!(json["operation"], "created");
1037        assert_eq!(json["version"], 1);
1038        assert_eq!(json["elapsed_ms"], 55u64);
1039        assert!(json["warnings"].is_array());
1040        assert!(json["merged_into_memory_id"].is_null());
1041    }
1042
1043    #[test]
1044    fn remember_response_action_e_operation_sao_aliases() {
1045        let resp = RememberResponse {
1046            memory_id: 1,
1047            name: "mem".to_string(),
1048            namespace: "global".to_string(),
1049            action: "updated".to_string(),
1050            operation: "updated".to_string(),
1051            version: 2,
1052            entities_persisted: 3,
1053            relationships_persisted: 1,
1054            relationships_truncated: false,
1055            extraction_method: None,
1056            chunks_created: 2,
1057            chunks_persisted: 2,
1058            urls_persisted: 0,
1059            merged_into_memory_id: None,
1060            warnings: vec![],
1061            created_at: 0,
1062            created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1063            elapsed_ms: 0,
1064            name_was_normalized: false,
1065            original_name: None,
1066        };
1067
1068        let json = serde_json::to_value(&resp).expect("serialization failed");
1069        assert_eq!(
1070            json["action"], json["operation"],
1071            "action e operation devem ser iguais"
1072        );
1073        assert_eq!(json["entities_persisted"], 3);
1074        assert_eq!(json["relationships_persisted"], 1);
1075        assert_eq!(json["chunks_created"], 2);
1076    }
1077
1078    #[test]
1079    fn remember_response_warnings_lista_mensagens() {
1080        let resp = RememberResponse {
1081            memory_id: 5,
1082            name: "dup-mem".to_string(),
1083            namespace: "global".to_string(),
1084            action: "created".to_string(),
1085            operation: "created".to_string(),
1086            version: 1,
1087            entities_persisted: 0,
1088            extraction_method: None,
1089            relationships_persisted: 0,
1090            relationships_truncated: false,
1091            chunks_created: 1,
1092            chunks_persisted: 0,
1093            urls_persisted: 0,
1094            merged_into_memory_id: None,
1095            warnings: vec!["identical body already exists as memory id 3".to_string()],
1096            created_at: 0,
1097            created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1098            elapsed_ms: 10,
1099            name_was_normalized: false,
1100            original_name: None,
1101        };
1102
1103        let json = serde_json::to_value(&resp).expect("serialization failed");
1104        let warnings = json["warnings"]
1105            .as_array()
1106            .expect("warnings deve ser array");
1107        assert_eq!(warnings.len(), 1);
1108        assert!(warnings[0].as_str().unwrap().contains("identical body"));
1109    }
1110
1111    #[test]
1112    fn invalid_name_reserved_prefix_returns_validation_error() {
1113        use crate::errors::AppError;
1114        // Validates the rejection logic for names with the "__" prefix directly
1115        let nome = "__reservado";
1116        let resultado: Result<(), AppError> = if nome.starts_with("__") {
1117            Err(AppError::Validation(
1118                crate::i18n::validation::reserved_name(),
1119            ))
1120        } else {
1121            Ok(())
1122        };
1123        assert!(resultado.is_err());
1124        if let Err(AppError::Validation(msg)) = resultado {
1125            assert!(!msg.is_empty());
1126        }
1127    }
1128
1129    #[test]
1130    fn name_too_long_returns_validation_error() {
1131        use crate::errors::AppError;
1132        let nome_longo = "a".repeat(crate::constants::MAX_MEMORY_NAME_LEN + 1);
1133        let resultado: Result<(), AppError> =
1134            if nome_longo.is_empty() || nome_longo.len() > crate::constants::MAX_MEMORY_NAME_LEN {
1135                Err(AppError::Validation(crate::i18n::validation::name_length(
1136                    crate::constants::MAX_MEMORY_NAME_LEN,
1137                )))
1138            } else {
1139                Ok(())
1140            };
1141        assert!(resultado.is_err());
1142    }
1143
1144    #[test]
1145    fn remember_response_merged_into_memory_id_some_serializes_integer() {
1146        let resp = RememberResponse {
1147            memory_id: 10,
1148            name: "mem-mergeada".to_string(),
1149            namespace: "global".to_string(),
1150            action: "updated".to_string(),
1151            operation: "updated".to_string(),
1152            version: 3,
1153            extraction_method: None,
1154            entities_persisted: 0,
1155            relationships_persisted: 0,
1156            relationships_truncated: false,
1157            chunks_created: 1,
1158            chunks_persisted: 0,
1159            urls_persisted: 0,
1160            merged_into_memory_id: Some(7),
1161            warnings: vec![],
1162            created_at: 0,
1163            created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1164            elapsed_ms: 0,
1165            name_was_normalized: false,
1166            original_name: None,
1167        };
1168
1169        let json = serde_json::to_value(&resp).expect("serialization failed");
1170        assert_eq!(json["merged_into_memory_id"], 7);
1171    }
1172
1173    #[test]
1174    fn remember_response_urls_persisted_serializes_field() {
1175        // v1.0.24 P0-2: garante que urls_persisted aparece no JSON e aceita valor > 0.
1176        let resp = RememberResponse {
1177            memory_id: 3,
1178            name: "mem-com-urls".to_string(),
1179            namespace: "global".to_string(),
1180            action: "created".to_string(),
1181            operation: "created".to_string(),
1182            version: 1,
1183            entities_persisted: 0,
1184            relationships_persisted: 0,
1185            relationships_truncated: false,
1186            chunks_created: 1,
1187            chunks_persisted: 0,
1188            urls_persisted: 3,
1189            extraction_method: Some("regex-only".to_string()),
1190            merged_into_memory_id: None,
1191            warnings: vec![],
1192            created_at: 0,
1193            created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1194            elapsed_ms: 0,
1195            name_was_normalized: false,
1196            original_name: None,
1197        };
1198        let json = serde_json::to_value(&resp).expect("serialization failed");
1199        assert_eq!(json["urls_persisted"], 3);
1200    }
1201
1202    #[test]
1203    fn empty_name_after_normalization_returns_specific_message() {
1204        // P0-4 regression: name consisting only of hyphens normalizes to empty string;
1205        // must produce a distinct error message, not the "too long" message.
1206        use crate::errors::AppError;
1207        let normalized = "---".to_lowercase().replace(['_', ' '], "-");
1208        let normalized = normalized.trim_matches('-').to_string();
1209        let resultado: Result<(), AppError> = if normalized.is_empty() {
1210            Err(AppError::Validation(
1211                "name cannot be empty after normalization (input was blank or contained only hyphens/underscores/spaces)".to_string(),
1212            ))
1213        } else {
1214            Ok(())
1215        };
1216        assert!(resultado.is_err());
1217        if let Err(AppError::Validation(msg)) = resultado {
1218            assert!(
1219                msg.contains("empty after normalization"),
1220                "mensagem deve mencionar 'empty after normalization', obteve: {msg}"
1221            );
1222        }
1223    }
1224
1225    #[test]
1226    fn name_only_underscores_after_normalization_returns_specific_message() {
1227        // P0-4 regression: name consisting only of underscores normalizes to empty string.
1228        use crate::errors::AppError;
1229        let normalized = "___".to_lowercase().replace(['_', ' '], "-");
1230        let normalized = normalized.trim_matches('-').to_string();
1231        assert!(
1232            normalized.is_empty(),
1233            "underscores devem normalizar para string vazia"
1234        );
1235        let resultado: Result<(), AppError> = if normalized.is_empty() {
1236            Err(AppError::Validation(
1237                "name cannot be empty after normalization (input was blank or contained only hyphens/underscores/spaces)".to_string(),
1238            ))
1239        } else {
1240            Ok(())
1241        };
1242        assert!(resultado.is_err());
1243        if let Err(AppError::Validation(msg)) = resultado {
1244            assert!(
1245                msg.contains("empty after normalization"),
1246                "mensagem deve mencionar 'empty after normalization', obteve: {msg}"
1247            );
1248        }
1249    }
1250
1251    #[test]
1252    fn remember_response_relationships_truncated_serializes_field() {
1253        // P1-D: garante que relationships_truncated aparece no JSON como bool.
1254        let resp_false = RememberResponse {
1255            memory_id: 1,
1256            name: "test".to_string(),
1257            namespace: "global".to_string(),
1258            action: "created".to_string(),
1259            operation: "created".to_string(),
1260            version: 1,
1261            entities_persisted: 2,
1262            relationships_persisted: 1,
1263            relationships_truncated: false,
1264            chunks_created: 1,
1265            chunks_persisted: 0,
1266            urls_persisted: 0,
1267            extraction_method: None,
1268            merged_into_memory_id: None,
1269            warnings: vec![],
1270            created_at: 0,
1271            created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1272            elapsed_ms: 0,
1273            name_was_normalized: false,
1274            original_name: None,
1275        };
1276        let json_false = serde_json::to_value(&resp_false).expect("serialization failed");
1277        assert_eq!(json_false["relationships_truncated"], false);
1278
1279        let resp_true = RememberResponse {
1280            relationships_truncated: true,
1281            ..resp_false
1282        };
1283        let json_true = serde_json::to_value(&resp_true).expect("serialization failed");
1284        assert_eq!(json_true["relationships_truncated"], true);
1285    }
1286
1287    // GAP-08: body-preservation predicate tests.
1288    // Verifies the decision logic that determines whether an existing body should
1289    // be kept instead of overwritten with an empty incoming body during --force-merge.
1290
1291    /// Returns `true` when the existing body should be preserved.
1292    ///
1293    /// Mirrors the `body_will_be_preserved` expression in `run()` so the logic
1294    /// is testable without a real database connection.
1295    fn should_preserve_body(force_merge: bool, raw_body_is_empty: bool, clear_body: bool) -> bool {
1296        force_merge && raw_body_is_empty && !clear_body
1297    }
1298
1299    #[test]
1300    fn gap08_empty_body_force_merge_no_clear_body_preserves() {
1301        // Caller passes no body with --force-merge but without --clear-body.
1302        // The existing body in the DB must be kept.
1303        assert!(
1304            should_preserve_body(true, true, false),
1305            "empty body + force-merge + no clear-body should trigger preservation"
1306        );
1307    }
1308
1309    #[test]
1310    fn gap08_empty_body_force_merge_with_clear_body_does_not_preserve() {
1311        // Caller explicitly passes --clear-body; intentional wipe is honoured.
1312        assert!(
1313            !should_preserve_body(true, true, true),
1314            "--clear-body must bypass preservation"
1315        );
1316    }
1317
1318    #[test]
1319    fn gap08_non_empty_body_force_merge_does_not_preserve() {
1320        // Caller provides a real body; it must overwrite the existing one.
1321        assert!(
1322            !should_preserve_body(true, false, false),
1323            "non-empty body must overwrite, not preserve"
1324        );
1325    }
1326
1327    #[test]
1328    fn gap08_empty_body_no_force_merge_does_not_preserve() {
1329        // Without --force-merge the path is a fresh create; no preservation needed.
1330        assert!(
1331            !should_preserve_body(false, true, false),
1332            "no --force-merge means no preservation logic applies"
1333        );
1334    }
1335}