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