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(
234    args: RememberArgs,
235    llm_backend: crate::cli::LlmBackendChoice,
236    embedding_backend: crate::cli::EmbeddingBackendChoice,
237) -> Result<(), AppError> {
238    use crate::constants::*;
239
240    let inicio = std::time::Instant::now();
241    let _ = args.format;
242    tracing::debug!(target: "remember", name = %args.name, "persisting memory");
243    let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
244
245    // Capture the original `--name` before normalization so the JSON response can
246    // surface `name_was_normalized` + `original_name` (B_4 in v1.0.32). Stored as
247    // an owned String because `args.name` is moved into the response below.
248    let original_name = args.name.clone();
249
250    // Auto-normalize to kebab-case before validation (P2-H).
251    // v1.0.20: also trims hyphens at the boundary (including trailing) to avoid rejection
252    // after truncation by a long filename ending in a hyphen.
253    let normalized_name = {
254        let lower = args.name.to_lowercase().replace(['_', ' '], "-");
255        let trimmed = lower.trim_matches('-').to_string();
256        if trimmed != args.name {
257            tracing::warn!(target: "remember",
258                original = %args.name,
259                normalized = %trimmed,
260                "name auto-normalized to kebab-case"
261            );
262        }
263        trimmed
264    };
265    let name_was_normalized = normalized_name != original_name;
266
267    if normalized_name.is_empty() {
268        return Err(AppError::Validation(
269            "name cannot be empty after normalization (input was blank or contained only hyphens/underscores/spaces)".to_string(),
270        ));
271    }
272    if normalized_name.len() > MAX_MEMORY_NAME_LEN {
273        return Err(AppError::LimitExceeded(
274            crate::i18n::validation::name_length(MAX_MEMORY_NAME_LEN),
275        ));
276    }
277
278    if normalized_name.starts_with("__") {
279        return Err(AppError::Validation(
280            crate::i18n::validation::reserved_name(),
281        ));
282    }
283
284    {
285        let slug_re = crate::constants::name_slug_regex();
286        if !slug_re.is_match(&normalized_name) {
287            return Err(AppError::Validation(crate::i18n::validation::name_kebab(
288                &normalized_name,
289            )));
290        }
291    }
292
293    if let Some(ref desc) = args.description {
294        if desc.len() > MAX_MEMORY_DESCRIPTION_LEN {
295            return Err(AppError::Validation(
296                crate::i18n::validation::description_exceeds(MAX_MEMORY_DESCRIPTION_LEN),
297            ));
298        }
299    }
300
301    let mut raw_body = if let Some(b) = args.body {
302        b
303    } else if let Some(ref path) = args.body_file {
304        let file_size = std::fs::metadata(path).map_err(AppError::Io)?.len();
305        if file_size > MAX_MEMORY_BODY_LEN as u64 {
306            return Err(AppError::LimitExceeded(
307                crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
308            ));
309        }
310        match std::fs::read_to_string(path) {
311            Ok(s) => s,
312            Err(e) if e.kind() == std::io::ErrorKind::InvalidData => {
313                let bytes = std::fs::read(path).map_err(AppError::Io)?;
314                tracing::warn!(target: "remember", "body file contains invalid UTF-8; replacing invalid sequences");
315                String::from_utf8_lossy(&bytes).into_owned()
316            }
317            Err(e) => return Err(AppError::Io(e)),
318        }
319    } else if args.body_stdin || args.graph_stdin {
320        crate::stdin_helper::read_stdin_with_timeout(60)?
321    } else {
322        String::new()
323    };
324
325    let mut entities_provided_externally =
326        args.entities_file.is_some() || args.relationships_file.is_some();
327
328    let mut graph = GraphInput::default();
329    if let Some(path) = args.entities_file {
330        let file_size = std::fs::metadata(&path).map_err(AppError::Io)?.len();
331        if file_size > MAX_MEMORY_BODY_LEN as u64 {
332            return Err(AppError::LimitExceeded(
333                crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
334            ));
335        }
336        let content = std::fs::read_to_string(&path).map_err(AppError::Io)?;
337        graph.entities = serde_json::from_str(&content)?;
338    }
339    if let Some(path) = args.relationships_file {
340        let file_size = std::fs::metadata(&path).map_err(AppError::Io)?.len();
341        if file_size > MAX_MEMORY_BODY_LEN as u64 {
342            return Err(AppError::LimitExceeded(
343                crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
344            ));
345        }
346        let content = std::fs::read_to_string(&path).map_err(AppError::Io)?;
347        graph.relationships = serde_json::from_str(&content)?;
348    }
349    if args.graph_stdin {
350        graph = serde_json::from_str::<GraphInput>(&raw_body).map_err(|e| {
351            AppError::Validation(format!("invalid JSON payload on --graph-stdin: {e}"))
352        })?;
353        raw_body = graph.body.take().unwrap_or_default();
354    }
355    if args.graph_stdin && !graph.entities.is_empty() {
356        entities_provided_externally = true;
357    }
358
359    if graph.entities.len() > max_entities_per_memory() {
360        return Err(AppError::LimitExceeded(errors_msg::entity_limit_exceeded(
361            max_entities_per_memory(),
362        )));
363    }
364    let mut relationships_truncated = false;
365    let rel_cap = max_relationships_per_memory();
366    if graph.relationships.len() > rel_cap {
367        tracing::warn!(target: "remember",
368            count = graph.relationships.len(),
369            cap = rel_cap,
370            "truncating relationships to cap"
371        );
372        graph.relationships.truncate(rel_cap);
373        relationships_truncated = true;
374    }
375    normalize_and_validate_graph_input(&mut graph)?;
376
377    if raw_body.len() > MAX_MEMORY_BODY_LEN {
378        return Err(AppError::LimitExceeded(
379            crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
380        ));
381    }
382
383    // v1.0.22 P1: reject empty or whitespace-only body when no external graph is provided.
384    // Without this check, empty embeddings would be persisted, breaking recall semantics.
385    // GAP-08: skip this guard when --force-merge without --clear-body; the existing body
386    // will be preserved from the database, so the effective body will not be empty.
387    let body_will_be_preserved = args.force_merge && raw_body.trim().is_empty() && !args.clear_body;
388    if !entities_provided_externally
389        && graph.entities.is_empty()
390        && raw_body.trim().is_empty()
391        && !body_will_be_preserved
392        && !args.clear_body
393    {
394        return Err(AppError::Validation(crate::i18n::validation::empty_body()));
395    }
396
397    let metadata: serde_json::Value = if let Some(m) = args.metadata {
398        serde_json::from_str(&m)?
399    } else if let Some(path) = args.metadata_file {
400        let file_size = std::fs::metadata(&path).map_err(AppError::Io)?.len();
401        if file_size > MAX_MEMORY_BODY_LEN as u64 {
402            return Err(AppError::LimitExceeded(
403                crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
404            ));
405        }
406        let content = std::fs::read_to_string(&path).map_err(AppError::Io)?;
407        serde_json::from_str(&content)?
408    } else {
409        serde_json::json!({})
410    };
411
412    let mut body_hash = blake3::hash(raw_body.as_bytes()).to_hex().to_string();
413    let mut snippet: String = raw_body.chars().take(200).collect();
414
415    let paths = AppPaths::resolve(args.db.as_deref())?;
416    paths.ensure_dirs()?;
417
418    // v1.0.20: use .trim().is_empty() to reject bodies that are only whitespace.
419    let mut extraction_method: Option<String> = None;
420    let mut extracted_urls: Vec<crate::extraction::ExtractedUrl> = Vec::with_capacity(4);
421    if args.enable_ner && args.skip_extraction {
422        return Err(AppError::Validation(
423            "--enable-ner and --skip-extraction are mutually exclusive; remove one".to_string(),
424        ));
425    }
426    if args.skip_extraction && !args.enable_ner {
427        // v1.0.74: revert to v1.0.45 hidden no-op behavior. The v1.0.67
428        // commit (9ddb17b) promoted this to a hard validation error, which
429        // broke the "kept as a hidden no-op for backwards compatibility"
430        // promise documented in CHANGELOG v1.0.45 and started failing
431        // 5+ CI jobs whose E2E tests use this flag to skip the
432        // GLiNER-ONNX model download in CI environments.
433        tracing::warn!(
434            "--skip-extraction is deprecated since v1.0.45 and has no effect (NER is disabled by default); remove this flag to silence the warning"
435        );
436    }
437    // v1.0.79: --gliner-variant is a no-op kept for compatibility; a
438    // non-default value signals the caller still expects the removed
439    // GLiNER pipeline, so warn explicitly.
440    if args.gliner_variant != "fp32" {
441        tracing::warn!(
442            "--gliner-variant is deprecated and has no effect since v1.0.79 (the GLiNER pipeline was removed); --enable-ner performs URL-regex extraction only"
443        );
444    }
445    let gliner_variant: crate::extraction::GlinerVariant = match args.gliner_variant.as_str() {
446        "int8" => crate::extraction::GlinerVariant::Int8,
447        _ => crate::extraction::GlinerVariant::Fp32,
448    };
449    if args.enable_ner && graph.entities.is_empty() && !raw_body.trim().is_empty() {
450        match crate::extraction::extract_graph_auto(&raw_body, &paths, gliner_variant) {
451            Ok(extracted) => {
452                // v1.0.76: ExtractionResult is URL + entity + elapsed_ms;
453                // the LLM ExtractionBackend returns typed relationships
454                // separately. The default build is URL-only extraction.
455                extraction_method = Some("url-regex".to_string());
456                extracted_urls = extracted.urls;
457                // Convert ExtractedEntity → NewEntity (no offsets,
458                // type defaults to Concept).
459                graph.entities = extracted
460                    .entities
461                    .into_iter()
462                    .map(|e| NewEntity {
463                        name: e.name,
464                        entity_type: crate::entity_type::EntityType::Concept,
465                        description: None,
466                    })
467                    .collect();
468                graph.relationships.clear();
469                relationships_truncated = false;
470
471                if graph.entities.len() > max_entities_per_memory() {
472                    graph.entities.truncate(max_entities_per_memory());
473                }
474                if graph.relationships.len() > max_relationships_per_memory() {
475                    relationships_truncated = true;
476                    graph.relationships.truncate(max_relationships_per_memory());
477                }
478                normalize_and_validate_graph_input(&mut graph)?;
479            }
480            Err(e) => {
481                tracing::warn!(target: "remember", error = %e, "auto-extraction failed, graceful degradation");
482                extraction_method = Some("none:extraction-failed".to_string());
483            }
484        }
485    }
486
487    let mut conn = open_rw(&paths.db)?;
488    ensure_schema(&mut conn)?;
489
490    // --dry-run: emit planned action without any DB writes and return.
491    if args.dry_run {
492        let existing = memories::find_by_name(&conn, &namespace, &normalized_name)?;
493        let planned_action = if existing.is_some() && args.force_merge {
494            "would_update"
495        } else {
496            "would_create"
497        };
498        output::emit_json(&serde_json::json!({
499            "dry_run": true,
500            "name": normalized_name,
501            "namespace": namespace,
502            "planned_action": planned_action,
503        }))?;
504        return Ok(());
505    }
506
507    {
508        use crate::constants::MAX_NAMESPACES_ACTIVE;
509        let active_count: u32 = conn.query_row(
510            "SELECT COUNT(DISTINCT namespace) FROM memories WHERE deleted_at IS NULL",
511            [],
512            |r| r.get::<_, i64>(0).map(|v| v as u32),
513        )?;
514        let ns_exists: bool = conn.query_row(
515            "SELECT EXISTS(SELECT 1 FROM memories WHERE namespace = ?1 AND deleted_at IS NULL)",
516            rusqlite::params![namespace],
517            |r| r.get::<_, i64>(0).map(|v| v > 0),
518        )?;
519        if !ns_exists && active_count >= MAX_NAMESPACES_ACTIVE {
520            return Err(AppError::NamespaceError(format!(
521                "active namespace limit of {MAX_NAMESPACES_ACTIVE} reached while trying to create '{namespace}'"
522            )));
523        }
524    }
525
526    // M7: detect soft-deleted memory before the standard duplicate check.
527    if let Some((sd_id, true)) =
528        memories::find_by_name_any_state(&conn, &namespace, &normalized_name)?
529    {
530        if args.force_merge {
531            memories::clear_deleted_at(&conn, sd_id)?;
532        } else {
533            return Err(AppError::Duplicate(
534                errors_msg::duplicate_memory_soft_deleted(&normalized_name, &namespace),
535            ));
536        }
537    }
538
539    let existing_memory = memories::find_by_name(&conn, &namespace, &normalized_name)?;
540    if existing_memory.is_some() && !args.force_merge {
541        return Err(AppError::Duplicate(errors_msg::duplicate_memory(
542            &normalized_name,
543            &namespace,
544        )));
545    }
546
547    // GAP-10: resolve type and description.
548    // For CREATE path (new memory): both are required.
549    // For UPDATE path (--force-merge on existing memory): inherit from existing row when omitted.
550    let (resolved_type, resolved_description) = if existing_memory.is_none() {
551        // CREATE path — both fields are mandatory.
552        let t = args.r#type.ok_or_else(|| {
553            AppError::Validation(
554                "--type and --description are required when creating a new memory".to_string(),
555            )
556        })?;
557        let d = args.description.clone().ok_or_else(|| {
558            AppError::Validation(
559                "--type and --description are required when creating a new memory".to_string(),
560            )
561        })?;
562        (t.as_str().to_string(), d)
563    } else {
564        // UPDATE path (--force-merge) — inherit missing fields from stored row.
565        let existing_row = memories::read_by_name(&conn, &namespace, &normalized_name)?
566            .ok_or_else(|| {
567                AppError::NotFound(format!(
568                    "memory '{normalized_name}' not found in namespace '{namespace}'"
569                ))
570            })?;
571        let t = args
572            .r#type
573            .map(|v| v.as_str().to_string())
574            .unwrap_or_else(|| existing_row.memory_type.clone());
575        let d = args
576            .description
577            .clone()
578            .unwrap_or_else(|| existing_row.description.clone());
579        (t, d)
580    };
581
582    // GAP-08/GAP-09: protect existing body from accidental destruction during --force-merge.
583    // When the caller omits a body (or passes an empty one) without --clear-body, silently
584    // preserve the existing body from the database.  This prevents a common scripting mistake
585    // where a cron job updates metadata fields and inadvertently wipes the stored content.
586    if body_will_be_preserved {
587        if let Some(existing_row) = memories::read_by_name(&conn, &namespace, &normalized_name)? {
588            if !existing_row.body.is_empty() {
589                tracing::debug!(target: "remember",
590                    name = %normalized_name,
591                    "GAP-08: empty body with --force-merge and no --clear-body; preserving existing body"
592                );
593                raw_body = existing_row.body;
594                body_hash = blake3::hash(raw_body.as_bytes()).to_hex().to_string();
595                snippet = raw_body.chars().take(200).collect();
596            }
597        }
598    }
599
600    let duplicate_hash_id = memories::find_by_hash(&conn, &namespace, &body_hash)?;
601
602    output::emit_progress_i18n(
603        &format!(
604            "Remember stage: validated input; available memory {} MB",
605            crate::memory_guard::available_memory_mb()
606        ),
607        &format!(
608            "Stage remember: input validated; available memory {} MB",
609            crate::memory_guard::available_memory_mb()
610        ),
611    );
612
613    let model_max_length = crate::tokenizer::get_model_max_length();
614    let total_passage_tokens = crate::tokenizer::count_passage_tokens(&raw_body)?;
615    let chunks_info = chunking::split_into_chunks_hierarchical(&raw_body);
616    let chunks_created = chunks_info.len();
617    // For single-chunk bodies the memory row itself stores the content and no
618    // entry is appended to `memory_chunks` (see line ~545). For multi-chunk
619    // bodies every chunk is persisted via `insert_chunk_slices`.
620    let chunks_persisted = compute_chunks_persisted(chunks_info.len());
621
622    output::emit_progress_i18n(
623        &format!(
624            "Remember stage: tokenizer counted {total_passage_tokens} passage tokens (model max {model_max_length}); chunking produced {} chunks; process RSS {} MB",
625            chunks_created,
626            crate::memory_guard::current_process_memory_mb().unwrap_or(0)
627        ),
628        &format!(
629            "Stage remember: tokenizer counted {total_passage_tokens} passage tokens (model max {model_max_length}); chunking produced {} chunks; process RSS {} MB",
630            chunks_created,
631            crate::memory_guard::current_process_memory_mb().unwrap_or(0)
632        ),
633    );
634
635    if chunks_created > crate::constants::REMEMBER_MAX_SAFE_MULTI_CHUNKS {
636        return Err(AppError::LimitExceeded(format!(
637            "document produces {chunks_created} chunks; current safe operational limit is {} chunks; split the document before using remember",
638            crate::constants::REMEMBER_MAX_SAFE_MULTI_CHUNKS
639        )));
640    }
641
642    output::emit_progress_i18n("Computing embedding...", "Calculando embedding...");
643    let mut chunk_embeddings_cache: Option<Vec<Vec<f32>>> = None;
644
645    // v1.0.84 (ADR-0042): extrai o backend que efetivamente executou o
646    // embedding da passagem (ou do batch em chunks) para popular
647    // `backend_invoked` no envelope de resposta.
648    let skip_embed = crate::embedder::should_skip_embedding_on_failure();
649    let (embedding, backend_invoked_passage): (Option<Vec<f32>>, Option<&str>) = if chunks_info
650        .len()
651        == 1
652    {
653        match crate::embedder::embed_passage_with_embedding_choice(
654            &paths.models,
655            &raw_body,
656            embedding_backend,
657            llm_backend,
658        ) {
659            Ok((v, k)) => (Some(v), Some(k.as_str())),
660            Err(AppError::Validation(msg)) => return Err(AppError::Validation(msg)),
661            Err(e) if skip_embed => {
662                tracing::warn!(error = %e, "embedding failed; --skip-embedding-on-failure active, persisting without embedding");
663                (None, None)
664            }
665            Err(e) => return Err(e),
666        }
667    } else {
668        let chunk_texts: Vec<String> = chunks_info
669            .iter()
670            .map(|c| chunking::chunk_text(&raw_body, c).to_string())
671            .collect();
672        // G42/S2+S3 (v1.0.79): chunks are embedded in dim-adaptive
673        // batches per LLM call (G44: clamp(base*64/dim, 1, base)), with up to
674        // --llm-parallelism bounded subprocesses in flight. The old
675        // serial loop spent SUM(items) wall time; the fan-out spends
676        // roughly MAX(batch).
677        output::emit_progress_i18n(
678            &format!(
679                "Embedding {} chunks in parallel batches (parallelism {})...",
680                chunks_info.len(),
681                args.llm_parallelism
682            ),
683            &format!(
684                "Embedding {} chunks em lotes paralelos (paralelismo {})...",
685                chunks_info.len(),
686                args.llm_parallelism
687            ),
688        );
689        if let Some(rss) = crate::memory_guard::current_process_memory_mb() {
690            if rss > args.max_rss_mb {
691                tracing::error!(target: "remember",
692                    rss_mb = rss,
693                    max_rss_mb = args.max_rss_mb,
694                    "RSS exceeded --max-rss-mb threshold; aborting to prevent system instability"
695                );
696                return Err(AppError::LowMemory {
697                    available_mb: crate::memory_guard::available_memory_mb(),
698                    required_mb: args.max_rss_mb,
699                });
700            }
701        }
702        match crate::embedder::embed_passages_parallel_with_embedding_choice(
703            &paths.models,
704            &chunk_texts,
705            args.llm_parallelism as usize,
706            crate::embedder::chunk_embed_batch_size(),
707            embedding_backend,
708            llm_backend,
709        ) {
710            Ok(chunk_embeddings) => {
711                output::emit_progress_i18n(
712                    &format!(
713                        "Remember stage: chunk embeddings complete; process RSS {} MB",
714                        crate::memory_guard::current_process_memory_mb().unwrap_or(0)
715                    ),
716                    &format!(
717                        "Stage remember: chunk embeddings completed; process RSS {} MB",
718                        crate::memory_guard::current_process_memory_mb().unwrap_or(0)
719                    ),
720                );
721                let aggregated = chunking::aggregate_embeddings(&chunk_embeddings);
722                chunk_embeddings_cache = Some(chunk_embeddings);
723                (Some(aggregated), None)
724            }
725            Err(e) if skip_embed => {
726                tracing::warn!(error = %e, "chunk embedding failed; --skip-embedding-on-failure active, persisting without embedding");
727                (None, None)
728            }
729            Err(e) => return Err(e),
730        }
731    };
732    let body_for_storage = raw_body;
733
734    let memory_type = resolved_type.as_str();
735    let new_memory = NewMemory {
736        namespace: namespace.clone(),
737        name: normalized_name.clone(),
738        memory_type: memory_type.to_string(),
739        description: resolved_description.clone(),
740        body: body_for_storage,
741        body_hash: body_hash.clone(),
742        session_id: args.session_id.clone(),
743        source: "agent".to_string(),
744        metadata,
745    };
746
747    let mut warnings = Vec::with_capacity(4);
748    let mut entities_persisted = 0usize;
749    let mut relationships_persisted = 0usize;
750
751    // G42/S2+A4 (v1.0.79): entity names are SHORT texts — they get their
752    // own batch profile (25 per LLM call) instead of one subprocess per
753    // 3-15 byte name (21 names used to cost ~12 minutes, 46% of the
754    // measured remember total).
755    let entity_texts: Vec<String> = graph
756        .entities
757        .iter()
758        .map(|entity| match &entity.description {
759            Some(desc) => format!("{} {}", entity.name, desc),
760            None => entity.name.clone(),
761        })
762        .collect();
763    // G56 (v1.0.80): route entity-name embedding through the in-process
764    // cache. Repeated `remember` invocations within one CLI process — and
765    // re-embedded entities inside a single batch — skip the LLM call
766    // entirely when the (model, text) pair was already produced. The
767    // chunk body embedding below still uses `embed_passages_parallel_local`
768    // because chunks are unique per memory and the cache hit rate is
769    // effectively zero.
770    let (graph_entity_embeddings, embed_cache_stats) =
771        match crate::embedder::embed_entity_texts_cached(
772            &paths.models,
773            &entity_texts,
774            args.llm_parallelism as usize,
775        ) {
776            Ok(r) => r,
777            Err(e) if skip_embed => {
778                tracing::warn!(error = %e, "entity embedding failed; --skip-embedding-on-failure active");
779                let empty: Vec<Vec<f32>> = entity_texts.iter().map(|_| vec![]).collect();
780                (empty, crate::embedder::EmbedCacheStats::default())
781            }
782            Err(e) => return Err(e),
783        };
784    if embed_cache_stats.hits > 0 {
785        tracing::debug!(
786            hits = embed_cache_stats.hits,
787            misses = embed_cache_stats.misses,
788            requested = embed_cache_stats.requested,
789            "G56: entity embed cache hit (remember)"
790        );
791    }
792
793    let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
794
795    let mut skip_reindex = false;
796    let (memory_id, action, version) = match existing_memory {
797        Some((existing_id, _updated_at, _current_version)) => {
798            if let Some(hash_id) = duplicate_hash_id {
799                if hash_id != existing_id {
800                    warnings.push(format!(
801                        "identical body already exists as memory id {hash_id}"
802                    ));
803                }
804            }
805
806            // C1 fix: capture old values for FTS5 sync before update
807            let (old_fts_name, old_fts_desc, old_fts_body): (String, String, String) = tx
808                .query_row(
809                    "SELECT name, description, body FROM memories WHERE id = ?1",
810                    rusqlite::params![existing_id],
811                    |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
812                )?;
813
814            // G15: skip re-indexing when body hash matches (common in --force-merge loops)
815            let existing_body_hash: Option<String> = tx
816                .query_row(
817                    "SELECT body_hash FROM memories WHERE id = ?1",
818                    rusqlite::params![existing_id],
819                    |r| r.get(0),
820                )
821                .ok();
822            let body_unchanged = existing_body_hash.as_deref() == Some(&body_hash);
823            skip_reindex = body_unchanged;
824            if !body_unchanged {
825                storage_chunks::delete_chunks(&tx, existing_id)?;
826            }
827
828            let next_v = versions::next_version(&tx, existing_id)?;
829            memories::update(&tx, existing_id, &new_memory, args.expected_updated_at)?;
830
831            // C1 fix: sync FTS5 external-content index after update
832            // (trg_fts_au trigger is absent by design due to sqlite-vec conflict)
833            memories::sync_fts_after_update(
834                &tx,
835                existing_id,
836                &old_fts_name,
837                &old_fts_desc,
838                &old_fts_body,
839                &normalized_name,
840                &resolved_description,
841                &new_memory.body,
842            )?;
843
844            versions::insert_version(
845                &tx,
846                existing_id,
847                next_v,
848                &normalized_name,
849                memory_type,
850                &resolved_description,
851                &new_memory.body,
852                &serde_json::to_string(&new_memory.metadata)?,
853                None,
854                "edit",
855            )?;
856            if !body_unchanged {
857                if let Some(ref emb) = embedding {
858                    memories::upsert_vec(
859                        &tx,
860                        existing_id,
861                        &namespace,
862                        memory_type,
863                        emb,
864                        &normalized_name,
865                        &snippet,
866                    )?;
867                }
868            }
869            (existing_id, "updated".to_string(), next_v)
870        }
871        None => {
872            if let Some(hash_id) = duplicate_hash_id {
873                warnings.push(format!(
874                    "identical body already exists as memory id {hash_id}"
875                ));
876            }
877            let id = memories::insert(&tx, &new_memory)?;
878            versions::insert_version(
879                &tx,
880                id,
881                1,
882                &normalized_name,
883                memory_type,
884                &resolved_description,
885                &new_memory.body,
886                &serde_json::to_string(&new_memory.metadata)?,
887                None,
888                "create",
889            )?;
890            if let Some(ref emb) = embedding {
891                memories::upsert_vec(
892                    &tx,
893                    id,
894                    &namespace,
895                    memory_type,
896                    emb,
897                    &normalized_name,
898                    &snippet,
899                )?;
900            }
901            (id, "created".to_string(), 1)
902        }
903    };
904
905    if chunks_info.len() > 1 && !skip_reindex {
906        storage_chunks::insert_chunk_slices(&tx, memory_id, &new_memory.body, &chunks_info)?;
907
908        if let Some(chunk_embeddings) = chunk_embeddings_cache.take() {
909            for (i, emb) in chunk_embeddings.iter().enumerate() {
910                storage_chunks::upsert_chunk_vec(&tx, i as i64, memory_id, i as i32, emb)?;
911            }
912        }
913        output::emit_progress_i18n(
914            &format!(
915                "Remember stage: persisted chunk vectors; process RSS {} MB",
916                crate::memory_guard::current_process_memory_mb().unwrap_or(0)
917            ),
918            &format!(
919                "Etapa remember: vetores de chunks persistidos; RSS do processo {} MB",
920                crate::memory_guard::current_process_memory_mb().unwrap_or(0)
921            ),
922        );
923    }
924
925    if !graph.entities.is_empty() || !graph.relationships.is_empty() {
926        for entity in &graph.entities {
927            let entity_id = entities::upsert_entity(&tx, &namespace, entity)?;
928            let entity_embedding = &graph_entity_embeddings[entities_persisted];
929            entities::upsert_entity_vec(
930                &tx,
931                entity_id,
932                &namespace,
933                entity.entity_type,
934                entity_embedding,
935                &entity.name,
936            )?;
937            entities::link_memory_entity(&tx, memory_id, entity_id)?;
938            entities_persisted += 1;
939        }
940        let entity_types: std::collections::HashMap<&str, EntityType> = graph
941            .entities
942            .iter()
943            .map(|entity| (entity.name.as_str(), entity.entity_type))
944            .collect();
945
946        let mut affected_entity_ids: std::collections::HashSet<i64> =
947            std::collections::HashSet::new();
948        for entity in &graph.entities {
949            if let Some(eid) = entities::find_entity_id(&tx, &namespace, &entity.name)? {
950                affected_entity_ids.insert(eid);
951            }
952        }
953
954        for rel in &graph.relationships {
955            let source_entity = NewEntity {
956                name: rel.source.clone(),
957                entity_type: entity_types
958                    .get(rel.source.as_str())
959                    .copied()
960                    .unwrap_or(EntityType::Concept),
961                description: None,
962            };
963            let target_entity = NewEntity {
964                name: rel.target.clone(),
965                entity_type: entity_types
966                    .get(rel.target.as_str())
967                    .copied()
968                    .unwrap_or(EntityType::Concept),
969                description: None,
970            };
971            let source_id = entities::upsert_entity(&tx, &namespace, &source_entity)?;
972            let target_id = entities::upsert_entity(&tx, &namespace, &target_entity)?;
973            let rel_id = entities::upsert_relationship(&tx, &namespace, source_id, target_id, rel)?;
974            entities::link_memory_relationship(&tx, memory_id, rel_id)?;
975            affected_entity_ids.insert(source_id);
976            affected_entity_ids.insert(target_id);
977            relationships_persisted += 1;
978        }
979
980        for &eid in &affected_entity_ids {
981            entities::recalculate_degree(&tx, eid)?;
982        }
983        // GAP-17: warn when entity degree exceeds the configured cap.
984        if args.max_entity_degree > 0 {
985            let cap = args.max_entity_degree as i64;
986            for &eid in &affected_entity_ids {
987                let degree: i64 = tx.query_row(
988                    "SELECT degree FROM entities WHERE id = ?1",
989                    rusqlite::params![eid],
990                    |r| r.get(0),
991                )?;
992                if degree > cap {
993                    let name: String = tx.query_row(
994                        "SELECT name FROM entities WHERE id = ?1",
995                        rusqlite::params![eid],
996                        |r| r.get(0),
997                    )?;
998                    tracing::warn!(target: "remember",
999                        entity = %name,
1000                        degree = degree,
1001                        cap = cap,
1002                        "entity degree cap exceeded"
1003                    );
1004                }
1005            }
1006        }
1007    }
1008    tx.commit()?;
1009
1010    // v1.0.24 P0-2: persist URLs in a dedicated table, outside the main transaction.
1011    // Failures do not propagate — non-critical path with graceful degradation.
1012    let urls_persisted = if !extracted_urls.is_empty() {
1013        let url_entries: Vec<storage_urls::MemoryUrl> = extracted_urls
1014            .into_iter()
1015            .map(|u| storage_urls::MemoryUrl {
1016                url: u.url,
1017                offset: Some(u.start as i64),
1018            })
1019            .collect();
1020        storage_urls::insert_urls(&conn, memory_id, &url_entries)
1021    } else {
1022        0
1023    };
1024
1025    conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
1026
1027    let created_at_epoch = chrono::Utc::now().timestamp();
1028    let created_at_iso = crate::tz::format_iso(chrono::Utc::now());
1029
1030    output::emit_json(&RememberResponse {
1031        memory_id,
1032        // Persist the normalized (kebab-case) slug as `name` since that is the
1033        // storage key. The original input is exposed via `original_name` only
1034        // when normalization actually changed something (B_4 in v1.0.32).
1035        name: normalized_name.clone(),
1036        namespace,
1037        action: action.clone(),
1038        operation: action,
1039        version,
1040        entities_persisted,
1041        relationships_persisted,
1042        relationships_truncated,
1043        chunks_created,
1044        chunks_persisted,
1045        urls_persisted,
1046        extraction_method,
1047        merged_into_memory_id: None,
1048        warnings,
1049        created_at: created_at_epoch,
1050        created_at_iso,
1051        elapsed_ms: inicio.elapsed().as_millis() as u64,
1052        name_was_normalized,
1053        original_name: name_was_normalized.then_some(original_name),
1054        backend_invoked: backend_invoked_passage,
1055    })?;
1056
1057    Ok(())
1058}
1059
1060#[cfg(test)]
1061mod tests {
1062    use super::compute_chunks_persisted;
1063    use crate::output::RememberResponse;
1064
1065    // Bug H-M8: chunks_persisted contract is unit-testable and matches schema.
1066    #[test]
1067    fn chunks_persisted_zero_for_zero_chunks() {
1068        assert_eq!(compute_chunks_persisted(0), 0);
1069    }
1070
1071    #[test]
1072    fn chunks_persisted_zero_for_single_chunk_body() {
1073        // Single-chunk bodies live in the memories row itself; no row is
1074        // appended to memory_chunks. This is the documented contract.
1075        assert_eq!(compute_chunks_persisted(1), 0);
1076    }
1077
1078    #[test]
1079    fn chunks_persisted_equals_count_for_multi_chunk_body() {
1080        // Every chunk above the first triggers a row in memory_chunks.
1081        assert_eq!(compute_chunks_persisted(2), 2);
1082        assert_eq!(compute_chunks_persisted(7), 7);
1083        assert_eq!(compute_chunks_persisted(64), 64);
1084    }
1085
1086    #[test]
1087    fn remember_response_serializes_required_fields() {
1088        let resp = RememberResponse {
1089            memory_id: 42,
1090            name: "minha-mem".to_string(),
1091            namespace: "global".to_string(),
1092            action: "created".to_string(),
1093            operation: "created".to_string(),
1094            version: 1,
1095            entities_persisted: 0,
1096            relationships_persisted: 0,
1097            relationships_truncated: false,
1098            chunks_created: 1,
1099            chunks_persisted: 0,
1100            urls_persisted: 0,
1101            extraction_method: None,
1102            merged_into_memory_id: None,
1103            warnings: vec![],
1104            created_at: 1_705_320_000,
1105            created_at_iso: "2024-01-15T12:00:00Z".to_string(),
1106            elapsed_ms: 55,
1107            name_was_normalized: false,
1108            original_name: None,
1109            backend_invoked: None,
1110        };
1111
1112        let json = serde_json::to_value(&resp).expect("serialization failed");
1113        assert_eq!(json["memory_id"], 42);
1114        assert_eq!(json["action"], "created");
1115        assert_eq!(json["operation"], "created");
1116        assert_eq!(json["version"], 1);
1117        assert_eq!(json["elapsed_ms"], 55u64);
1118        assert!(json["warnings"].is_array());
1119        assert!(json["merged_into_memory_id"].is_null());
1120    }
1121
1122    #[test]
1123    fn remember_response_action_e_operation_sao_aliases() {
1124        let resp = RememberResponse {
1125            memory_id: 1,
1126            name: "mem".to_string(),
1127            namespace: "global".to_string(),
1128            action: "updated".to_string(),
1129            operation: "updated".to_string(),
1130            version: 2,
1131            entities_persisted: 3,
1132            relationships_persisted: 1,
1133            relationships_truncated: false,
1134            extraction_method: None,
1135            chunks_created: 2,
1136            chunks_persisted: 2,
1137            urls_persisted: 0,
1138            merged_into_memory_id: None,
1139            warnings: vec![],
1140            created_at: 0,
1141            created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1142            elapsed_ms: 0,
1143            name_was_normalized: false,
1144            original_name: None,
1145            backend_invoked: None,
1146        };
1147
1148        let json = serde_json::to_value(&resp).expect("serialization failed");
1149        assert_eq!(
1150            json["action"], json["operation"],
1151            "action e operation devem ser iguais"
1152        );
1153        assert_eq!(json["entities_persisted"], 3);
1154        assert_eq!(json["relationships_persisted"], 1);
1155        assert_eq!(json["chunks_created"], 2);
1156    }
1157
1158    #[test]
1159    fn remember_response_warnings_lista_mensagens() {
1160        let resp = RememberResponse {
1161            memory_id: 5,
1162            name: "dup-mem".to_string(),
1163            namespace: "global".to_string(),
1164            action: "created".to_string(),
1165            operation: "created".to_string(),
1166            version: 1,
1167            entities_persisted: 0,
1168            extraction_method: None,
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: None,
1175            warnings: vec!["identical body already exists as memory id 3".to_string()],
1176            created_at: 0,
1177            created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1178            elapsed_ms: 10,
1179            name_was_normalized: false,
1180            original_name: None,
1181            backend_invoked: None,
1182        };
1183
1184        let json = serde_json::to_value(&resp).expect("serialization failed");
1185        let warnings = json["warnings"]
1186            .as_array()
1187            .expect("warnings deve ser array");
1188        assert_eq!(warnings.len(), 1);
1189        assert!(warnings[0].as_str().unwrap().contains("identical body"));
1190    }
1191
1192    #[test]
1193    fn invalid_name_reserved_prefix_returns_validation_error() {
1194        use crate::errors::AppError;
1195        // Validates the rejection logic for names with the "__" prefix directly
1196        let nome = "__reservado";
1197        let resultado: Result<(), AppError> = if nome.starts_with("__") {
1198            Err(AppError::Validation(
1199                crate::i18n::validation::reserved_name(),
1200            ))
1201        } else {
1202            Ok(())
1203        };
1204        assert!(resultado.is_err());
1205        if let Err(AppError::Validation(msg)) = resultado {
1206            assert!(!msg.is_empty());
1207        }
1208    }
1209
1210    #[test]
1211    fn name_too_long_returns_validation_error() {
1212        use crate::errors::AppError;
1213        let nome_longo = "a".repeat(crate::constants::MAX_MEMORY_NAME_LEN + 1);
1214        let resultado: Result<(), AppError> =
1215            if nome_longo.is_empty() || nome_longo.len() > crate::constants::MAX_MEMORY_NAME_LEN {
1216                Err(AppError::Validation(crate::i18n::validation::name_length(
1217                    crate::constants::MAX_MEMORY_NAME_LEN,
1218                )))
1219            } else {
1220                Ok(())
1221            };
1222        assert!(resultado.is_err());
1223    }
1224
1225    #[test]
1226    fn remember_response_merged_into_memory_id_some_serializes_integer() {
1227        let resp = RememberResponse {
1228            memory_id: 10,
1229            name: "mem-mergeada".to_string(),
1230            namespace: "global".to_string(),
1231            action: "updated".to_string(),
1232            operation: "updated".to_string(),
1233            version: 3,
1234            extraction_method: None,
1235            entities_persisted: 0,
1236            relationships_persisted: 0,
1237            relationships_truncated: false,
1238            chunks_created: 1,
1239            chunks_persisted: 0,
1240            urls_persisted: 0,
1241            merged_into_memory_id: Some(7),
1242            warnings: vec![],
1243            created_at: 0,
1244            created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1245            elapsed_ms: 0,
1246            name_was_normalized: false,
1247            original_name: None,
1248            backend_invoked: None,
1249        };
1250
1251        let json = serde_json::to_value(&resp).expect("serialization failed");
1252        assert_eq!(json["merged_into_memory_id"], 7);
1253    }
1254
1255    #[test]
1256    fn remember_response_urls_persisted_serializes_field() {
1257        // v1.0.24 P0-2: garante que urls_persisted aparece no JSON e aceita valor > 0.
1258        let resp = RememberResponse {
1259            memory_id: 3,
1260            name: "mem-com-urls".to_string(),
1261            namespace: "global".to_string(),
1262            action: "created".to_string(),
1263            operation: "created".to_string(),
1264            version: 1,
1265            entities_persisted: 0,
1266            relationships_persisted: 0,
1267            relationships_truncated: false,
1268            chunks_created: 1,
1269            chunks_persisted: 0,
1270            urls_persisted: 3,
1271            extraction_method: Some("regex-only".to_string()),
1272            merged_into_memory_id: None,
1273            warnings: vec![],
1274            created_at: 0,
1275            created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1276            elapsed_ms: 0,
1277            name_was_normalized: false,
1278            original_name: None,
1279            backend_invoked: None,
1280        };
1281        let json = serde_json::to_value(&resp).expect("serialization failed");
1282        assert_eq!(json["urls_persisted"], 3);
1283    }
1284
1285    #[test]
1286    fn empty_name_after_normalization_returns_specific_message() {
1287        // P0-4 regression: name consisting only of hyphens normalizes to empty string;
1288        // must produce a distinct error message, not the "too long" message.
1289        use crate::errors::AppError;
1290        let normalized = "---".to_lowercase().replace(['_', ' '], "-");
1291        let normalized = normalized.trim_matches('-').to_string();
1292        let resultado: Result<(), AppError> = if normalized.is_empty() {
1293            Err(AppError::Validation(
1294                "name cannot be empty after normalization (input was blank or contained only hyphens/underscores/spaces)".to_string(),
1295            ))
1296        } else {
1297            Ok(())
1298        };
1299        assert!(resultado.is_err());
1300        if let Err(AppError::Validation(msg)) = resultado {
1301            assert!(
1302                msg.contains("empty after normalization"),
1303                "mensagem deve mencionar 'empty after normalization', obteve: {msg}"
1304            );
1305        }
1306    }
1307
1308    #[test]
1309    fn name_only_underscores_after_normalization_returns_specific_message() {
1310        // P0-4 regression: name consisting only of underscores normalizes to empty string.
1311        use crate::errors::AppError;
1312        let normalized = "___".to_lowercase().replace(['_', ' '], "-");
1313        let normalized = normalized.trim_matches('-').to_string();
1314        assert!(
1315            normalized.is_empty(),
1316            "underscores devem normalizar para string vazia"
1317        );
1318        let resultado: Result<(), AppError> = if normalized.is_empty() {
1319            Err(AppError::Validation(
1320                "name cannot be empty after normalization (input was blank or contained only hyphens/underscores/spaces)".to_string(),
1321            ))
1322        } else {
1323            Ok(())
1324        };
1325        assert!(resultado.is_err());
1326        if let Err(AppError::Validation(msg)) = resultado {
1327            assert!(
1328                msg.contains("empty after normalization"),
1329                "mensagem deve mencionar 'empty after normalization', obteve: {msg}"
1330            );
1331        }
1332    }
1333
1334    #[test]
1335    fn remember_response_relationships_truncated_serializes_field() {
1336        // P1-D: garante que relationships_truncated aparece no JSON como bool.
1337        let resp_false = RememberResponse {
1338            memory_id: 1,
1339            name: "test".to_string(),
1340            namespace: "global".to_string(),
1341            action: "created".to_string(),
1342            operation: "created".to_string(),
1343            version: 1,
1344            entities_persisted: 2,
1345            relationships_persisted: 1,
1346            relationships_truncated: false,
1347            chunks_created: 1,
1348            chunks_persisted: 0,
1349            urls_persisted: 0,
1350            extraction_method: None,
1351            merged_into_memory_id: None,
1352            warnings: vec![],
1353            created_at: 0,
1354            created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1355            elapsed_ms: 0,
1356            name_was_normalized: false,
1357            original_name: None,
1358            backend_invoked: None,
1359        };
1360        let json_false = serde_json::to_value(&resp_false).expect("serialization failed");
1361        assert_eq!(json_false["relationships_truncated"], false);
1362
1363        let resp_true = RememberResponse {
1364            relationships_truncated: true,
1365            ..resp_false
1366        };
1367        let json_true = serde_json::to_value(&resp_true).expect("serialization failed");
1368        assert_eq!(json_true["relationships_truncated"], true);
1369    }
1370
1371    // GAP-08: body-preservation predicate tests.
1372    // Verifies the decision logic that determines whether an existing body should
1373    // be kept instead of overwritten with an empty incoming body during --force-merge.
1374
1375    /// Returns `true` when the existing body should be preserved.
1376    ///
1377    /// Mirrors the `body_will_be_preserved` expression in `run()` so the logic
1378    /// is testable without a real database connection.
1379    fn should_preserve_body(force_merge: bool, raw_body_is_empty: bool, clear_body: bool) -> bool {
1380        force_merge && raw_body_is_empty && !clear_body
1381    }
1382
1383    #[test]
1384    fn gap08_empty_body_force_merge_no_clear_body_preserves() {
1385        // Caller passes no body with --force-merge but without --clear-body.
1386        // The existing body in the DB must be kept.
1387        assert!(
1388            should_preserve_body(true, true, false),
1389            "empty body + force-merge + no clear-body should trigger preservation"
1390        );
1391    }
1392
1393    #[test]
1394    fn gap08_empty_body_force_merge_with_clear_body_does_not_preserve() {
1395        // Caller explicitly passes --clear-body; intentional wipe is honoured.
1396        assert!(
1397            !should_preserve_body(true, true, true),
1398            "--clear-body must bypass preservation"
1399        );
1400    }
1401
1402    #[test]
1403    fn gap08_non_empty_body_force_merge_does_not_preserve() {
1404        // Caller provides a real body; it must overwrite the existing one.
1405        assert!(
1406            !should_preserve_body(true, false, false),
1407            "non-empty body must overwrite, not preserve"
1408        );
1409    }
1410
1411    #[test]
1412    fn gap08_empty_body_no_force_merge_does_not_preserve() {
1413        // Without --force-merge the path is a fresh create; no preservation needed.
1414        assert!(
1415            !should_preserve_body(false, true, false),
1416            "no --force-merge means no preservation logic applies"
1417        );
1418    }
1419}