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