Skip to main content

sqlite_graphrag/commands/
remember.rs

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