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    // G56 (v1.0.80): route entity-name embedding through the in-process
730    // cache. Repeated `remember` invocations within one CLI process — and
731    // re-embedded entities inside a single batch — skip the LLM call
732    // entirely when the (model, text) pair was already produced. The
733    // chunk body embedding below still uses `embed_passages_parallel_local`
734    // because chunks are unique per memory and the cache hit rate is
735    // effectively zero.
736    let (graph_entity_embeddings, embed_cache_stats) = crate::embedder::embed_entity_texts_cached(
737        &paths.models,
738        &entity_texts,
739        args.llm_parallelism as usize,
740    )?;
741    if embed_cache_stats.hits > 0 {
742        tracing::debug!(
743            hits = embed_cache_stats.hits,
744            misses = embed_cache_stats.misses,
745            requested = embed_cache_stats.requested,
746            "G56: entity embed cache hit (remember)"
747        );
748    }
749
750    let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
751
752    let mut skip_reindex = false;
753    let (memory_id, action, version) = match existing_memory {
754        Some((existing_id, _updated_at, _current_version)) => {
755            if let Some(hash_id) = duplicate_hash_id {
756                if hash_id != existing_id {
757                    warnings.push(format!(
758                        "identical body already exists as memory id {hash_id}"
759                    ));
760                }
761            }
762
763            // C1 fix: capture old values for FTS5 sync before update
764            let (old_fts_name, old_fts_desc, old_fts_body): (String, String, String) = tx
765                .query_row(
766                    "SELECT name, description, body FROM memories WHERE id = ?1",
767                    rusqlite::params![existing_id],
768                    |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
769                )?;
770
771            // G15: skip re-indexing when body hash matches (common in --force-merge loops)
772            let existing_body_hash: Option<String> = tx
773                .query_row(
774                    "SELECT body_hash FROM memories WHERE id = ?1",
775                    rusqlite::params![existing_id],
776                    |r| r.get(0),
777                )
778                .ok();
779            let body_unchanged = existing_body_hash.as_deref() == Some(&body_hash);
780            skip_reindex = body_unchanged;
781            if !body_unchanged {
782                storage_chunks::delete_chunks(&tx, existing_id)?;
783            }
784
785            let next_v = versions::next_version(&tx, existing_id)?;
786            memories::update(&tx, existing_id, &new_memory, args.expected_updated_at)?;
787
788            // C1 fix: sync FTS5 external-content index after update
789            // (trg_fts_au trigger is absent by design due to sqlite-vec conflict)
790            memories::sync_fts_after_update(
791                &tx,
792                existing_id,
793                &old_fts_name,
794                &old_fts_desc,
795                &old_fts_body,
796                &normalized_name,
797                &resolved_description,
798                &new_memory.body,
799            )?;
800
801            versions::insert_version(
802                &tx,
803                existing_id,
804                next_v,
805                &normalized_name,
806                memory_type,
807                &resolved_description,
808                &new_memory.body,
809                &serde_json::to_string(&new_memory.metadata)?,
810                None,
811                "edit",
812            )?;
813            if !body_unchanged {
814                memories::upsert_vec(
815                    &tx,
816                    existing_id,
817                    &namespace,
818                    memory_type,
819                    &embedding,
820                    &normalized_name,
821                    &snippet,
822                )?;
823            }
824            (existing_id, "updated".to_string(), next_v)
825        }
826        None => {
827            if let Some(hash_id) = duplicate_hash_id {
828                warnings.push(format!(
829                    "identical body already exists as memory id {hash_id}"
830                ));
831            }
832            let id = memories::insert(&tx, &new_memory)?;
833            versions::insert_version(
834                &tx,
835                id,
836                1,
837                &normalized_name,
838                memory_type,
839                &resolved_description,
840                &new_memory.body,
841                &serde_json::to_string(&new_memory.metadata)?,
842                None,
843                "create",
844            )?;
845            memories::upsert_vec(
846                &tx,
847                id,
848                &namespace,
849                memory_type,
850                &embedding,
851                &normalized_name,
852                &snippet,
853            )?;
854            (id, "created".to_string(), 1)
855        }
856    };
857
858    if chunks_info.len() > 1 && !skip_reindex {
859        storage_chunks::insert_chunk_slices(&tx, memory_id, &new_memory.body, &chunks_info)?;
860
861        let chunk_embeddings = chunk_embeddings_cache.take().ok_or_else(|| {
862            AppError::Internal(anyhow::anyhow!(
863                "chunk embeddings cache missing in multi-chunk remember path"
864            ))
865        })?;
866
867        for (i, emb) in chunk_embeddings.iter().enumerate() {
868            storage_chunks::upsert_chunk_vec(&tx, i as i64, memory_id, i as i32, emb)?;
869        }
870        output::emit_progress_i18n(
871            &format!(
872                "Remember stage: persisted chunk vectors; process RSS {} MB",
873                crate::memory_guard::current_process_memory_mb().unwrap_or(0)
874            ),
875            &format!(
876                "Etapa remember: vetores de chunks persistidos; RSS do processo {} MB",
877                crate::memory_guard::current_process_memory_mb().unwrap_or(0)
878            ),
879        );
880    }
881
882    if !graph.entities.is_empty() || !graph.relationships.is_empty() {
883        for entity in &graph.entities {
884            let entity_id = entities::upsert_entity(&tx, &namespace, entity)?;
885            let entity_embedding = &graph_entity_embeddings[entities_persisted];
886            entities::upsert_entity_vec(
887                &tx,
888                entity_id,
889                &namespace,
890                entity.entity_type,
891                entity_embedding,
892                &entity.name,
893            )?;
894            entities::link_memory_entity(&tx, memory_id, entity_id)?;
895            entities::increment_degree(&tx, entity_id)?;
896            // GAP-17: warn when entity degree exceeds the configured cap.
897            if args.max_entity_degree > 0 {
898                let cap = args.max_entity_degree as i64;
899                let degree: i64 = tx.query_row(
900                    "SELECT degree FROM entities WHERE id = ?1",
901                    rusqlite::params![entity_id],
902                    |r| r.get(0),
903                )?;
904                if degree > cap {
905                    tracing::warn!(target: "remember",
906                        entity = %entity.name,
907                        degree = degree,
908                        cap = cap,
909                        "entity degree cap exceeded"
910                    );
911                }
912            }
913            entities_persisted += 1;
914        }
915        let entity_types: std::collections::HashMap<&str, EntityType> = graph
916            .entities
917            .iter()
918            .map(|entity| (entity.name.as_str(), entity.entity_type))
919            .collect();
920
921        for rel in &graph.relationships {
922            let source_entity = NewEntity {
923                name: rel.source.clone(),
924                entity_type: entity_types
925                    .get(rel.source.as_str())
926                    .copied()
927                    .unwrap_or(EntityType::Concept),
928                description: None,
929            };
930            let target_entity = NewEntity {
931                name: rel.target.clone(),
932                entity_type: entity_types
933                    .get(rel.target.as_str())
934                    .copied()
935                    .unwrap_or(EntityType::Concept),
936                description: None,
937            };
938            let source_id = entities::upsert_entity(&tx, &namespace, &source_entity)?;
939            let target_id = entities::upsert_entity(&tx, &namespace, &target_entity)?;
940            let rel_id = entities::upsert_relationship(&tx, &namespace, source_id, target_id, rel)?;
941            entities::link_memory_relationship(&tx, memory_id, rel_id)?;
942            relationships_persisted += 1;
943        }
944    }
945    tx.commit()?;
946
947    // v1.0.24 P0-2: persist URLs in a dedicated table, outside the main transaction.
948    // Failures do not propagate — non-critical path with graceful degradation.
949    let urls_persisted = if !extracted_urls.is_empty() {
950        let url_entries: Vec<storage_urls::MemoryUrl> = extracted_urls
951            .into_iter()
952            .map(|u| storage_urls::MemoryUrl {
953                url: u.url,
954                offset: Some(u.start as i64),
955            })
956            .collect();
957        storage_urls::insert_urls(&conn, memory_id, &url_entries)
958    } else {
959        0
960    };
961
962    conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
963
964    let created_at_epoch = chrono::Utc::now().timestamp();
965    let created_at_iso = crate::tz::format_iso(chrono::Utc::now());
966
967    output::emit_json(&RememberResponse {
968        memory_id,
969        // Persist the normalized (kebab-case) slug as `name` since that is the
970        // storage key. The original input is exposed via `original_name` only
971        // when normalization actually changed something (B_4 in v1.0.32).
972        name: normalized_name.clone(),
973        namespace,
974        action: action.clone(),
975        operation: action,
976        version,
977        entities_persisted,
978        relationships_persisted,
979        relationships_truncated,
980        chunks_created,
981        chunks_persisted,
982        urls_persisted,
983        extraction_method,
984        merged_into_memory_id: None,
985        warnings,
986        created_at: created_at_epoch,
987        created_at_iso,
988        elapsed_ms: inicio.elapsed().as_millis() as u64,
989        name_was_normalized,
990        original_name: name_was_normalized.then_some(original_name),
991    })?;
992
993    Ok(())
994}
995
996#[cfg(test)]
997mod tests {
998    use super::compute_chunks_persisted;
999    use crate::output::RememberResponse;
1000
1001    // Bug H-M8: chunks_persisted contract is unit-testable and matches schema.
1002    #[test]
1003    fn chunks_persisted_zero_for_zero_chunks() {
1004        assert_eq!(compute_chunks_persisted(0), 0);
1005    }
1006
1007    #[test]
1008    fn chunks_persisted_zero_for_single_chunk_body() {
1009        // Single-chunk bodies live in the memories row itself; no row is
1010        // appended to memory_chunks. This is the documented contract.
1011        assert_eq!(compute_chunks_persisted(1), 0);
1012    }
1013
1014    #[test]
1015    fn chunks_persisted_equals_count_for_multi_chunk_body() {
1016        // Every chunk above the first triggers a row in memory_chunks.
1017        assert_eq!(compute_chunks_persisted(2), 2);
1018        assert_eq!(compute_chunks_persisted(7), 7);
1019        assert_eq!(compute_chunks_persisted(64), 64);
1020    }
1021
1022    #[test]
1023    fn remember_response_serializes_required_fields() {
1024        let resp = RememberResponse {
1025            memory_id: 42,
1026            name: "minha-mem".to_string(),
1027            namespace: "global".to_string(),
1028            action: "created".to_string(),
1029            operation: "created".to_string(),
1030            version: 1,
1031            entities_persisted: 0,
1032            relationships_persisted: 0,
1033            relationships_truncated: false,
1034            chunks_created: 1,
1035            chunks_persisted: 0,
1036            urls_persisted: 0,
1037            extraction_method: None,
1038            merged_into_memory_id: None,
1039            warnings: vec![],
1040            created_at: 1_705_320_000,
1041            created_at_iso: "2024-01-15T12:00:00Z".to_string(),
1042            elapsed_ms: 55,
1043            name_was_normalized: false,
1044            original_name: None,
1045        };
1046
1047        let json = serde_json::to_value(&resp).expect("serialization failed");
1048        assert_eq!(json["memory_id"], 42);
1049        assert_eq!(json["action"], "created");
1050        assert_eq!(json["operation"], "created");
1051        assert_eq!(json["version"], 1);
1052        assert_eq!(json["elapsed_ms"], 55u64);
1053        assert!(json["warnings"].is_array());
1054        assert!(json["merged_into_memory_id"].is_null());
1055    }
1056
1057    #[test]
1058    fn remember_response_action_e_operation_sao_aliases() {
1059        let resp = RememberResponse {
1060            memory_id: 1,
1061            name: "mem".to_string(),
1062            namespace: "global".to_string(),
1063            action: "updated".to_string(),
1064            operation: "updated".to_string(),
1065            version: 2,
1066            entities_persisted: 3,
1067            relationships_persisted: 1,
1068            relationships_truncated: false,
1069            extraction_method: None,
1070            chunks_created: 2,
1071            chunks_persisted: 2,
1072            urls_persisted: 0,
1073            merged_into_memory_id: None,
1074            warnings: vec![],
1075            created_at: 0,
1076            created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1077            elapsed_ms: 0,
1078            name_was_normalized: false,
1079            original_name: None,
1080        };
1081
1082        let json = serde_json::to_value(&resp).expect("serialization failed");
1083        assert_eq!(
1084            json["action"], json["operation"],
1085            "action e operation devem ser iguais"
1086        );
1087        assert_eq!(json["entities_persisted"], 3);
1088        assert_eq!(json["relationships_persisted"], 1);
1089        assert_eq!(json["chunks_created"], 2);
1090    }
1091
1092    #[test]
1093    fn remember_response_warnings_lista_mensagens() {
1094        let resp = RememberResponse {
1095            memory_id: 5,
1096            name: "dup-mem".to_string(),
1097            namespace: "global".to_string(),
1098            action: "created".to_string(),
1099            operation: "created".to_string(),
1100            version: 1,
1101            entities_persisted: 0,
1102            extraction_method: None,
1103            relationships_persisted: 0,
1104            relationships_truncated: false,
1105            chunks_created: 1,
1106            chunks_persisted: 0,
1107            urls_persisted: 0,
1108            merged_into_memory_id: None,
1109            warnings: vec!["identical body already exists as memory id 3".to_string()],
1110            created_at: 0,
1111            created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1112            elapsed_ms: 10,
1113            name_was_normalized: false,
1114            original_name: None,
1115        };
1116
1117        let json = serde_json::to_value(&resp).expect("serialization failed");
1118        let warnings = json["warnings"]
1119            .as_array()
1120            .expect("warnings deve ser array");
1121        assert_eq!(warnings.len(), 1);
1122        assert!(warnings[0].as_str().unwrap().contains("identical body"));
1123    }
1124
1125    #[test]
1126    fn invalid_name_reserved_prefix_returns_validation_error() {
1127        use crate::errors::AppError;
1128        // Validates the rejection logic for names with the "__" prefix directly
1129        let nome = "__reservado";
1130        let resultado: Result<(), AppError> = if nome.starts_with("__") {
1131            Err(AppError::Validation(
1132                crate::i18n::validation::reserved_name(),
1133            ))
1134        } else {
1135            Ok(())
1136        };
1137        assert!(resultado.is_err());
1138        if let Err(AppError::Validation(msg)) = resultado {
1139            assert!(!msg.is_empty());
1140        }
1141    }
1142
1143    #[test]
1144    fn name_too_long_returns_validation_error() {
1145        use crate::errors::AppError;
1146        let nome_longo = "a".repeat(crate::constants::MAX_MEMORY_NAME_LEN + 1);
1147        let resultado: Result<(), AppError> =
1148            if nome_longo.is_empty() || nome_longo.len() > crate::constants::MAX_MEMORY_NAME_LEN {
1149                Err(AppError::Validation(crate::i18n::validation::name_length(
1150                    crate::constants::MAX_MEMORY_NAME_LEN,
1151                )))
1152            } else {
1153                Ok(())
1154            };
1155        assert!(resultado.is_err());
1156    }
1157
1158    #[test]
1159    fn remember_response_merged_into_memory_id_some_serializes_integer() {
1160        let resp = RememberResponse {
1161            memory_id: 10,
1162            name: "mem-mergeada".to_string(),
1163            namespace: "global".to_string(),
1164            action: "updated".to_string(),
1165            operation: "updated".to_string(),
1166            version: 3,
1167            extraction_method: None,
1168            entities_persisted: 0,
1169            relationships_persisted: 0,
1170            relationships_truncated: false,
1171            chunks_created: 1,
1172            chunks_persisted: 0,
1173            urls_persisted: 0,
1174            merged_into_memory_id: Some(7),
1175            warnings: vec![],
1176            created_at: 0,
1177            created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1178            elapsed_ms: 0,
1179            name_was_normalized: false,
1180            original_name: None,
1181        };
1182
1183        let json = serde_json::to_value(&resp).expect("serialization failed");
1184        assert_eq!(json["merged_into_memory_id"], 7);
1185    }
1186
1187    #[test]
1188    fn remember_response_urls_persisted_serializes_field() {
1189        // v1.0.24 P0-2: garante que urls_persisted aparece no JSON e aceita valor > 0.
1190        let resp = RememberResponse {
1191            memory_id: 3,
1192            name: "mem-com-urls".to_string(),
1193            namespace: "global".to_string(),
1194            action: "created".to_string(),
1195            operation: "created".to_string(),
1196            version: 1,
1197            entities_persisted: 0,
1198            relationships_persisted: 0,
1199            relationships_truncated: false,
1200            chunks_created: 1,
1201            chunks_persisted: 0,
1202            urls_persisted: 3,
1203            extraction_method: Some("regex-only".to_string()),
1204            merged_into_memory_id: None,
1205            warnings: vec![],
1206            created_at: 0,
1207            created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1208            elapsed_ms: 0,
1209            name_was_normalized: false,
1210            original_name: None,
1211        };
1212        let json = serde_json::to_value(&resp).expect("serialization failed");
1213        assert_eq!(json["urls_persisted"], 3);
1214    }
1215
1216    #[test]
1217    fn empty_name_after_normalization_returns_specific_message() {
1218        // P0-4 regression: name consisting only of hyphens normalizes to empty string;
1219        // must produce a distinct error message, not the "too long" message.
1220        use crate::errors::AppError;
1221        let normalized = "---".to_lowercase().replace(['_', ' '], "-");
1222        let normalized = normalized.trim_matches('-').to_string();
1223        let resultado: Result<(), AppError> = if normalized.is_empty() {
1224            Err(AppError::Validation(
1225                "name cannot be empty after normalization (input was blank or contained only hyphens/underscores/spaces)".to_string(),
1226            ))
1227        } else {
1228            Ok(())
1229        };
1230        assert!(resultado.is_err());
1231        if let Err(AppError::Validation(msg)) = resultado {
1232            assert!(
1233                msg.contains("empty after normalization"),
1234                "mensagem deve mencionar 'empty after normalization', obteve: {msg}"
1235            );
1236        }
1237    }
1238
1239    #[test]
1240    fn name_only_underscores_after_normalization_returns_specific_message() {
1241        // P0-4 regression: name consisting only of underscores normalizes to empty string.
1242        use crate::errors::AppError;
1243        let normalized = "___".to_lowercase().replace(['_', ' '], "-");
1244        let normalized = normalized.trim_matches('-').to_string();
1245        assert!(
1246            normalized.is_empty(),
1247            "underscores devem normalizar para string vazia"
1248        );
1249        let resultado: Result<(), AppError> = if normalized.is_empty() {
1250            Err(AppError::Validation(
1251                "name cannot be empty after normalization (input was blank or contained only hyphens/underscores/spaces)".to_string(),
1252            ))
1253        } else {
1254            Ok(())
1255        };
1256        assert!(resultado.is_err());
1257        if let Err(AppError::Validation(msg)) = resultado {
1258            assert!(
1259                msg.contains("empty after normalization"),
1260                "mensagem deve mencionar 'empty after normalization', obteve: {msg}"
1261            );
1262        }
1263    }
1264
1265    #[test]
1266    fn remember_response_relationships_truncated_serializes_field() {
1267        // P1-D: garante que relationships_truncated aparece no JSON como bool.
1268        let resp_false = RememberResponse {
1269            memory_id: 1,
1270            name: "test".to_string(),
1271            namespace: "global".to_string(),
1272            action: "created".to_string(),
1273            operation: "created".to_string(),
1274            version: 1,
1275            entities_persisted: 2,
1276            relationships_persisted: 1,
1277            relationships_truncated: false,
1278            chunks_created: 1,
1279            chunks_persisted: 0,
1280            urls_persisted: 0,
1281            extraction_method: None,
1282            merged_into_memory_id: None,
1283            warnings: vec![],
1284            created_at: 0,
1285            created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1286            elapsed_ms: 0,
1287            name_was_normalized: false,
1288            original_name: None,
1289        };
1290        let json_false = serde_json::to_value(&resp_false).expect("serialization failed");
1291        assert_eq!(json_false["relationships_truncated"], false);
1292
1293        let resp_true = RememberResponse {
1294            relationships_truncated: true,
1295            ..resp_false
1296        };
1297        let json_true = serde_json::to_value(&resp_true).expect("serialization failed");
1298        assert_eq!(json_true["relationships_truncated"], true);
1299    }
1300
1301    // GAP-08: body-preservation predicate tests.
1302    // Verifies the decision logic that determines whether an existing body should
1303    // be kept instead of overwritten with an empty incoming body during --force-merge.
1304
1305    /// Returns `true` when the existing body should be preserved.
1306    ///
1307    /// Mirrors the `body_will_be_preserved` expression in `run()` so the logic
1308    /// is testable without a real database connection.
1309    fn should_preserve_body(force_merge: bool, raw_body_is_empty: bool, clear_body: bool) -> bool {
1310        force_merge && raw_body_is_empty && !clear_body
1311    }
1312
1313    #[test]
1314    fn gap08_empty_body_force_merge_no_clear_body_preserves() {
1315        // Caller passes no body with --force-merge but without --clear-body.
1316        // The existing body in the DB must be kept.
1317        assert!(
1318            should_preserve_body(true, true, false),
1319            "empty body + force-merge + no clear-body should trigger preservation"
1320        );
1321    }
1322
1323    #[test]
1324    fn gap08_empty_body_force_merge_with_clear_body_does_not_preserve() {
1325        // Caller explicitly passes --clear-body; intentional wipe is honoured.
1326        assert!(
1327            !should_preserve_body(true, true, true),
1328            "--clear-body must bypass preservation"
1329        );
1330    }
1331
1332    #[test]
1333    fn gap08_non_empty_body_force_merge_does_not_preserve() {
1334        // Caller provides a real body; it must overwrite the existing one.
1335        assert!(
1336            !should_preserve_body(true, false, false),
1337            "non-empty body must overwrite, not preserve"
1338        );
1339    }
1340
1341    #[test]
1342    fn gap08_empty_body_no_force_merge_does_not_preserve() {
1343        // Without --force-merge the path is a fresh create; no preservation needed.
1344        assert!(
1345            !should_preserve_body(false, true, false),
1346            "no --force-merge means no preservation logic applies"
1347        );
1348    }
1349}