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    {
333        return Err(AppError::Validation(crate::i18n::validation::empty_body()));
334    }
335
336    let metadata: serde_json::Value = if let Some(m) = args.metadata {
337        serde_json::from_str(&m)?
338    } else if let Some(path) = args.metadata_file {
339        let content = std::fs::read_to_string(&path).map_err(AppError::Io)?;
340        serde_json::from_str(&content)?
341    } else {
342        serde_json::json!({})
343    };
344
345    let mut body_hash = blake3::hash(raw_body.as_bytes()).to_hex().to_string();
346    let mut snippet: String = raw_body.chars().take(200).collect();
347
348    let paths = AppPaths::resolve(args.db.as_deref())?;
349    paths.ensure_dirs()?;
350
351    // v1.0.20: use .trim().is_empty() to reject bodies that are only whitespace.
352    let mut extraction_method: Option<String> = None;
353    let mut extracted_urls: Vec<crate::extraction::ExtractedUrl> = Vec::with_capacity(4);
354    let mut relationships_truncated = false;
355    if args.enable_ner && args.skip_extraction {
356        tracing::warn!(
357            "--enable-ner and --skip-extraction are contradictory; --enable-ner takes precedence"
358        );
359    }
360    if args.skip_extraction && !args.enable_ner {
361        tracing::warn!("--skip-extraction is deprecated and has no effect (NER is disabled by default since v1.0.45); remove this flag");
362    }
363    let gliner_variant: crate::extraction::GlinerVariant =
364        args.gliner_variant.parse().unwrap_or_else(|e| {
365            tracing::warn!("invalid --gliner-variant: {e}; using fp32");
366            crate::extraction::GlinerVariant::Fp32
367        });
368    if args.enable_ner && graph.entities.is_empty() && !raw_body.trim().is_empty() {
369        match crate::extraction::extract_graph_auto(&raw_body, &paths, gliner_variant) {
370            Ok(extracted) => {
371                extraction_method = Some(extracted.extraction_method.clone());
372                extracted_urls = extracted.urls;
373                graph.entities = extracted.entities;
374                graph.relationships = extracted.relationships;
375                relationships_truncated = extracted.relationships_truncated;
376
377                if graph.entities.len() > max_entities_per_memory() {
378                    graph.entities.truncate(max_entities_per_memory());
379                }
380                if graph.relationships.len() > MAX_RELATIONSHIPS_PER_MEMORY {
381                    relationships_truncated = true;
382                    graph.relationships.truncate(MAX_RELATIONSHIPS_PER_MEMORY);
383                }
384                normalize_and_validate_graph_input(&mut graph)?;
385            }
386            Err(e) => {
387                tracing::warn!("auto-extraction failed (graceful degradation): {e:#}");
388                extraction_method = Some("none:extraction-failed".to_string());
389            }
390        }
391    }
392
393    let mut conn = open_rw(&paths.db)?;
394    ensure_schema(&mut conn)?;
395
396    // --dry-run: emit planned action without any DB writes and return.
397    if args.dry_run {
398        let existing = memories::find_by_name(&conn, &namespace, &normalized_name)?;
399        let planned_action = if existing.is_some() && args.force_merge {
400            "would_update"
401        } else {
402            "would_create"
403        };
404        output::emit_json(&serde_json::json!({
405            "dry_run": true,
406            "name": normalized_name,
407            "namespace": namespace,
408            "planned_action": planned_action,
409        }))?;
410        return Ok(());
411    }
412
413    {
414        use crate::constants::MAX_NAMESPACES_ACTIVE;
415        let active_count: u32 = conn.query_row(
416            "SELECT COUNT(DISTINCT namespace) FROM memories WHERE deleted_at IS NULL",
417            [],
418            |r| r.get::<_, i64>(0).map(|v| v as u32),
419        )?;
420        let ns_exists: bool = conn.query_row(
421            "SELECT EXISTS(SELECT 1 FROM memories WHERE namespace = ?1 AND deleted_at IS NULL)",
422            rusqlite::params![namespace],
423            |r| r.get::<_, i64>(0).map(|v| v > 0),
424        )?;
425        if !ns_exists && active_count >= MAX_NAMESPACES_ACTIVE {
426            return Err(AppError::NamespaceError(format!(
427                "active namespace limit of {MAX_NAMESPACES_ACTIVE} reached while trying to create '{namespace}'"
428            )));
429        }
430    }
431
432    // M7: detect soft-deleted memory before the standard duplicate check.
433    if let Some((sd_id, true)) =
434        memories::find_by_name_any_state(&conn, &namespace, &normalized_name)?
435    {
436        if args.force_merge {
437            memories::clear_deleted_at(&conn, sd_id)?;
438        } else {
439            return Err(AppError::Duplicate(
440                errors_msg::duplicate_memory_soft_deleted(&normalized_name, &namespace),
441            ));
442        }
443    }
444
445    let existing_memory = memories::find_by_name(&conn, &namespace, &normalized_name)?;
446    if existing_memory.is_some() && !args.force_merge {
447        return Err(AppError::Duplicate(errors_msg::duplicate_memory(
448            &normalized_name,
449            &namespace,
450        )));
451    }
452
453    // GAP-10: resolve type and description.
454    // For CREATE path (new memory): both are required.
455    // For UPDATE path (--force-merge on existing memory): inherit from existing row when omitted.
456    let (resolved_type, resolved_description) = if existing_memory.is_none() {
457        // CREATE path — both fields are mandatory.
458        let t = args.r#type.ok_or_else(|| {
459            AppError::Validation(
460                "--type and --description are required when creating a new memory".to_string(),
461            )
462        })?;
463        let d = args.description.clone().ok_or_else(|| {
464            AppError::Validation(
465                "--type and --description are required when creating a new memory".to_string(),
466            )
467        })?;
468        (t.as_str().to_string(), d)
469    } else {
470        // UPDATE path (--force-merge) — inherit missing fields from stored row.
471        let existing_row = memories::read_by_name(&conn, &namespace, &normalized_name)?
472            .ok_or_else(|| {
473                AppError::NotFound(format!(
474                    "memory '{normalized_name}' not found in namespace '{namespace}'"
475                ))
476            })?;
477        let t = args
478            .r#type
479            .map(|v| v.as_str().to_string())
480            .unwrap_or_else(|| existing_row.memory_type.clone());
481        let d = args
482            .description
483            .clone()
484            .unwrap_or_else(|| existing_row.description.clone());
485        (t, d)
486    };
487
488    // GAP-08/GAP-09: protect existing body from accidental destruction during --force-merge.
489    // When the caller omits a body (or passes an empty one) without --clear-body, silently
490    // preserve the existing body from the database.  This prevents a common scripting mistake
491    // where a cron job updates metadata fields and inadvertently wipes the stored content.
492    if body_will_be_preserved {
493        if let Some(existing_row) = memories::read_by_name(&conn, &namespace, &normalized_name)? {
494            if !existing_row.body.is_empty() {
495                tracing::debug!(
496                    name = %normalized_name,
497                    "GAP-08: empty body with --force-merge and no --clear-body; preserving existing body"
498                );
499                raw_body = existing_row.body;
500                body_hash = blake3::hash(raw_body.as_bytes()).to_hex().to_string();
501                snippet = raw_body.chars().take(200).collect();
502            }
503        }
504    }
505
506    let duplicate_hash_id = memories::find_by_hash(&conn, &namespace, &body_hash)?;
507
508    output::emit_progress_i18n(
509        &format!(
510            "Remember stage: validated input; available memory {} MB",
511            crate::memory_guard::available_memory_mb()
512        ),
513        &format!(
514            "Stage remember: input validated; available memory {} MB",
515            crate::memory_guard::available_memory_mb()
516        ),
517    );
518
519    let tokenizer = crate::tokenizer::get_tokenizer(&paths.models)?;
520    let model_max_length = crate::tokenizer::get_model_max_length(&paths.models)?;
521    let total_passage_tokens = crate::tokenizer::count_passage_tokens(tokenizer, &raw_body)?;
522    let chunks_info = chunking::split_into_chunks_hierarchical(&raw_body, tokenizer);
523    let chunks_created = chunks_info.len();
524    // For single-chunk bodies the memory row itself stores the content and no
525    // entry is appended to `memory_chunks` (see line ~545). For multi-chunk
526    // bodies every chunk is persisted via `insert_chunk_slices`.
527    let chunks_persisted = compute_chunks_persisted(chunks_info.len());
528
529    output::emit_progress_i18n(
530        &format!(
531            "Remember stage: tokenizer counted {total_passage_tokens} passage tokens (model max {model_max_length}); chunking produced {} chunks; process RSS {} MB",
532            chunks_created,
533            crate::memory_guard::current_process_memory_mb().unwrap_or(0)
534        ),
535        &format!(
536            "Stage remember: tokenizer counted {total_passage_tokens} passage tokens (model max {model_max_length}); chunking produced {} chunks; process RSS {} MB",
537            chunks_created,
538            crate::memory_guard::current_process_memory_mb().unwrap_or(0)
539        ),
540    );
541
542    if chunks_created > crate::constants::REMEMBER_MAX_SAFE_MULTI_CHUNKS {
543        return Err(AppError::LimitExceeded(format!(
544            "document produces {chunks_created} chunks; current safe operational limit is {} chunks; split the document before using remember",
545            crate::constants::REMEMBER_MAX_SAFE_MULTI_CHUNKS
546        )));
547    }
548
549    output::emit_progress_i18n("Computing embedding...", "Calculando embedding...");
550    let mut chunk_embeddings_cache: Option<Vec<Vec<f32>>> = None;
551
552    let embedding = if chunks_info.len() == 1 {
553        crate::daemon::embed_passage_or_local(&paths.models, &raw_body)?
554    } else {
555        let chunk_texts: Vec<&str> = chunks_info
556            .iter()
557            .map(|c| chunking::chunk_text(&raw_body, c))
558            .collect();
559        output::emit_progress_i18n(
560            &format!(
561                "Embedding {} chunks serially to keep memory bounded...",
562                chunks_info.len()
563            ),
564            &format!(
565                "Embedding {} chunks serially to keep memory bounded...",
566                chunks_info.len()
567            ),
568        );
569        let mut chunk_embeddings = Vec::with_capacity(chunk_texts.len());
570        for chunk_text in &chunk_texts {
571            if let Some(rss) = crate::memory_guard::current_process_memory_mb() {
572                if rss > args.max_rss_mb {
573                    tracing::error!(
574                        rss_mb = rss,
575                        max_rss_mb = args.max_rss_mb,
576                        "RSS exceeded --max-rss-mb threshold; aborting to prevent system instability"
577                    );
578                    return Err(AppError::LowMemory {
579                        available_mb: crate::memory_guard::available_memory_mb(),
580                        required_mb: args.max_rss_mb,
581                    });
582                }
583            }
584            chunk_embeddings.push(crate::daemon::embed_passage_or_local(
585                &paths.models,
586                chunk_text,
587            )?);
588        }
589        output::emit_progress_i18n(
590            &format!(
591                "Remember stage: chunk embeddings complete; process RSS {} MB",
592                crate::memory_guard::current_process_memory_mb().unwrap_or(0)
593            ),
594            &format!(
595                "Stage remember: chunk embeddings completed; process RSS {} MB",
596                crate::memory_guard::current_process_memory_mb().unwrap_or(0)
597            ),
598        );
599        let aggregated = chunking::aggregate_embeddings(&chunk_embeddings);
600        chunk_embeddings_cache = Some(chunk_embeddings);
601        aggregated
602    };
603    let body_for_storage = raw_body;
604
605    let memory_type = resolved_type.as_str();
606    let new_memory = NewMemory {
607        namespace: namespace.clone(),
608        name: normalized_name.clone(),
609        memory_type: memory_type.to_string(),
610        description: resolved_description.clone(),
611        body: body_for_storage,
612        body_hash: body_hash.clone(),
613        session_id: args.session_id.clone(),
614        source: "agent".to_string(),
615        metadata,
616    };
617
618    let mut warnings = Vec::with_capacity(4);
619    let mut entities_persisted = 0usize;
620    let mut relationships_persisted = 0usize;
621
622    let graph_entity_embeddings = graph
623        .entities
624        .iter()
625        .map(|entity| {
626            let entity_text = match &entity.description {
627                Some(desc) => format!("{} {}", entity.name, desc),
628                None => entity.name.clone(),
629            };
630            crate::daemon::embed_passage_or_local(&paths.models, &entity_text)
631        })
632        .collect::<Result<Vec<_>, _>>()?;
633
634    let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
635
636    let (memory_id, action, version) = match existing_memory {
637        Some((existing_id, _updated_at, _current_version)) => {
638            if let Some(hash_id) = duplicate_hash_id {
639                if hash_id != existing_id {
640                    warnings.push(format!(
641                        "identical body already exists as memory id {hash_id}"
642                    ));
643                }
644            }
645
646            storage_chunks::delete_chunks(&tx, existing_id)?;
647
648            let next_v = versions::next_version(&tx, existing_id)?;
649            memories::update(&tx, existing_id, &new_memory, args.expected_updated_at)?;
650            versions::insert_version(
651                &tx,
652                existing_id,
653                next_v,
654                &normalized_name,
655                memory_type,
656                &resolved_description,
657                &new_memory.body,
658                &serde_json::to_string(&new_memory.metadata)?,
659                None,
660                "edit",
661            )?;
662            memories::upsert_vec(
663                &tx,
664                existing_id,
665                &namespace,
666                memory_type,
667                &embedding,
668                &normalized_name,
669                &snippet,
670            )?;
671            (existing_id, "updated".to_string(), next_v)
672        }
673        None => {
674            if let Some(hash_id) = duplicate_hash_id {
675                warnings.push(format!(
676                    "identical body already exists as memory id {hash_id}"
677                ));
678            }
679            let id = memories::insert(&tx, &new_memory)?;
680            versions::insert_version(
681                &tx,
682                id,
683                1,
684                &normalized_name,
685                memory_type,
686                &resolved_description,
687                &new_memory.body,
688                &serde_json::to_string(&new_memory.metadata)?,
689                None,
690                "create",
691            )?;
692            memories::upsert_vec(
693                &tx,
694                id,
695                &namespace,
696                memory_type,
697                &embedding,
698                &normalized_name,
699                &snippet,
700            )?;
701            (id, "created".to_string(), 1)
702        }
703    };
704
705    if chunks_info.len() > 1 {
706        storage_chunks::insert_chunk_slices(&tx, memory_id, &new_memory.body, &chunks_info)?;
707
708        let chunk_embeddings = chunk_embeddings_cache.take().ok_or_else(|| {
709            AppError::Internal(anyhow::anyhow!(
710                "chunk embeddings cache missing in multi-chunk remember path"
711            ))
712        })?;
713
714        for (i, emb) in chunk_embeddings.iter().enumerate() {
715            storage_chunks::upsert_chunk_vec(&tx, i as i64, memory_id, i as i32, emb)?;
716        }
717        output::emit_progress_i18n(
718            &format!(
719                "Remember stage: persisted chunk vectors; process RSS {} MB",
720                crate::memory_guard::current_process_memory_mb().unwrap_or(0)
721            ),
722            &format!(
723                "Etapa remember: vetores de chunks persistidos; RSS do processo {} MB",
724                crate::memory_guard::current_process_memory_mb().unwrap_or(0)
725            ),
726        );
727    }
728
729    if !graph.entities.is_empty() || !graph.relationships.is_empty() {
730        for entity in &graph.entities {
731            let entity_id = entities::upsert_entity(&tx, &namespace, entity)?;
732            let entity_embedding = &graph_entity_embeddings[entities_persisted];
733            entities::upsert_entity_vec(
734                &tx,
735                entity_id,
736                &namespace,
737                entity.entity_type,
738                entity_embedding,
739                &entity.name,
740            )?;
741            entities::link_memory_entity(&tx, memory_id, entity_id)?;
742            entities::increment_degree(&tx, entity_id)?;
743            entities_persisted += 1;
744        }
745        let entity_types: std::collections::HashMap<&str, EntityType> = graph
746            .entities
747            .iter()
748            .map(|entity| (entity.name.as_str(), entity.entity_type))
749            .collect();
750
751        for rel in &graph.relationships {
752            let source_entity = NewEntity {
753                name: rel.source.clone(),
754                entity_type: entity_types
755                    .get(rel.source.as_str())
756                    .copied()
757                    .unwrap_or(EntityType::Concept),
758                description: None,
759            };
760            let target_entity = NewEntity {
761                name: rel.target.clone(),
762                entity_type: entity_types
763                    .get(rel.target.as_str())
764                    .copied()
765                    .unwrap_or(EntityType::Concept),
766                description: None,
767            };
768            let source_id = entities::upsert_entity(&tx, &namespace, &source_entity)?;
769            let target_id = entities::upsert_entity(&tx, &namespace, &target_entity)?;
770            let rel_id = entities::upsert_relationship(&tx, &namespace, source_id, target_id, rel)?;
771            entities::link_memory_relationship(&tx, memory_id, rel_id)?;
772            relationships_persisted += 1;
773        }
774    }
775    tx.commit()?;
776
777    // v1.0.24 P0-2: persist URLs in a dedicated table, outside the main transaction.
778    // Failures do not propagate — non-critical path with graceful degradation.
779    let urls_persisted = if !extracted_urls.is_empty() {
780        let url_entries: Vec<storage_urls::MemoryUrl> = extracted_urls
781            .into_iter()
782            .map(|u| storage_urls::MemoryUrl {
783                url: u.url,
784                offset: Some(u.offset as i64),
785            })
786            .collect();
787        storage_urls::insert_urls(&conn, memory_id, &url_entries)
788    } else {
789        0
790    };
791
792    conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
793
794    let created_at_epoch = chrono::Utc::now().timestamp();
795    let created_at_iso = crate::tz::format_iso(chrono::Utc::now());
796
797    output::emit_json(&RememberResponse {
798        memory_id,
799        // Persist the normalized (kebab-case) slug as `name` since that is the
800        // storage key. The original input is exposed via `original_name` only
801        // when normalization actually changed something (B_4 in v1.0.32).
802        name: normalized_name.clone(),
803        namespace,
804        action: action.clone(),
805        operation: action,
806        version,
807        entities_persisted,
808        relationships_persisted,
809        relationships_truncated,
810        chunks_created,
811        chunks_persisted,
812        urls_persisted,
813        extraction_method,
814        merged_into_memory_id: None,
815        warnings,
816        created_at: created_at_epoch,
817        created_at_iso,
818        elapsed_ms: inicio.elapsed().as_millis() as u64,
819        name_was_normalized,
820        original_name: name_was_normalized.then_some(original_name),
821    })?;
822
823    Ok(())
824}
825
826#[cfg(test)]
827mod tests {
828    use super::compute_chunks_persisted;
829    use crate::output::RememberResponse;
830
831    // Bug H-M8: chunks_persisted contract is unit-testable and matches schema.
832    #[test]
833    fn chunks_persisted_zero_for_zero_chunks() {
834        assert_eq!(compute_chunks_persisted(0), 0);
835    }
836
837    #[test]
838    fn chunks_persisted_zero_for_single_chunk_body() {
839        // Single-chunk bodies live in the memories row itself; no row is
840        // appended to memory_chunks. This is the documented contract.
841        assert_eq!(compute_chunks_persisted(1), 0);
842    }
843
844    #[test]
845    fn chunks_persisted_equals_count_for_multi_chunk_body() {
846        // Every chunk above the first triggers a row in memory_chunks.
847        assert_eq!(compute_chunks_persisted(2), 2);
848        assert_eq!(compute_chunks_persisted(7), 7);
849        assert_eq!(compute_chunks_persisted(64), 64);
850    }
851
852    #[test]
853    fn remember_response_serializes_required_fields() {
854        let resp = RememberResponse {
855            memory_id: 42,
856            name: "minha-mem".to_string(),
857            namespace: "global".to_string(),
858            action: "created".to_string(),
859            operation: "created".to_string(),
860            version: 1,
861            entities_persisted: 0,
862            relationships_persisted: 0,
863            relationships_truncated: false,
864            chunks_created: 1,
865            chunks_persisted: 0,
866            urls_persisted: 0,
867            extraction_method: None,
868            merged_into_memory_id: None,
869            warnings: vec![],
870            created_at: 1_705_320_000,
871            created_at_iso: "2024-01-15T12:00:00Z".to_string(),
872            elapsed_ms: 55,
873            name_was_normalized: false,
874            original_name: None,
875        };
876
877        let json = serde_json::to_value(&resp).expect("serialization failed");
878        assert_eq!(json["memory_id"], 42);
879        assert_eq!(json["action"], "created");
880        assert_eq!(json["operation"], "created");
881        assert_eq!(json["version"], 1);
882        assert_eq!(json["elapsed_ms"], 55u64);
883        assert!(json["warnings"].is_array());
884        assert!(json["merged_into_memory_id"].is_null());
885    }
886
887    #[test]
888    fn remember_response_action_e_operation_sao_aliases() {
889        let resp = RememberResponse {
890            memory_id: 1,
891            name: "mem".to_string(),
892            namespace: "global".to_string(),
893            action: "updated".to_string(),
894            operation: "updated".to_string(),
895            version: 2,
896            entities_persisted: 3,
897            relationships_persisted: 1,
898            relationships_truncated: false,
899            extraction_method: None,
900            chunks_created: 2,
901            chunks_persisted: 2,
902            urls_persisted: 0,
903            merged_into_memory_id: None,
904            warnings: vec![],
905            created_at: 0,
906            created_at_iso: "1970-01-01T00:00:00Z".to_string(),
907            elapsed_ms: 0,
908            name_was_normalized: false,
909            original_name: None,
910        };
911
912        let json = serde_json::to_value(&resp).expect("serialization failed");
913        assert_eq!(
914            json["action"], json["operation"],
915            "action e operation devem ser iguais"
916        );
917        assert_eq!(json["entities_persisted"], 3);
918        assert_eq!(json["relationships_persisted"], 1);
919        assert_eq!(json["chunks_created"], 2);
920    }
921
922    #[test]
923    fn remember_response_warnings_lista_mensagens() {
924        let resp = RememberResponse {
925            memory_id: 5,
926            name: "dup-mem".to_string(),
927            namespace: "global".to_string(),
928            action: "created".to_string(),
929            operation: "created".to_string(),
930            version: 1,
931            entities_persisted: 0,
932            extraction_method: None,
933            relationships_persisted: 0,
934            relationships_truncated: false,
935            chunks_created: 1,
936            chunks_persisted: 0,
937            urls_persisted: 0,
938            merged_into_memory_id: None,
939            warnings: vec!["identical body already exists as memory id 3".to_string()],
940            created_at: 0,
941            created_at_iso: "1970-01-01T00:00:00Z".to_string(),
942            elapsed_ms: 10,
943            name_was_normalized: false,
944            original_name: None,
945        };
946
947        let json = serde_json::to_value(&resp).expect("serialization failed");
948        let warnings = json["warnings"]
949            .as_array()
950            .expect("warnings deve ser array");
951        assert_eq!(warnings.len(), 1);
952        assert!(warnings[0].as_str().unwrap().contains("identical body"));
953    }
954
955    #[test]
956    fn invalid_name_reserved_prefix_returns_validation_error() {
957        use crate::errors::AppError;
958        // Validates the rejection logic for names with the "__" prefix directly
959        let nome = "__reservado";
960        let resultado: Result<(), AppError> = if nome.starts_with("__") {
961            Err(AppError::Validation(
962                crate::i18n::validation::reserved_name(),
963            ))
964        } else {
965            Ok(())
966        };
967        assert!(resultado.is_err());
968        if let Err(AppError::Validation(msg)) = resultado {
969            assert!(!msg.is_empty());
970        }
971    }
972
973    #[test]
974    fn name_too_long_returns_validation_error() {
975        use crate::errors::AppError;
976        let nome_longo = "a".repeat(crate::constants::MAX_MEMORY_NAME_LEN + 1);
977        let resultado: Result<(), AppError> =
978            if nome_longo.is_empty() || nome_longo.len() > crate::constants::MAX_MEMORY_NAME_LEN {
979                Err(AppError::Validation(crate::i18n::validation::name_length(
980                    crate::constants::MAX_MEMORY_NAME_LEN,
981                )))
982            } else {
983                Ok(())
984            };
985        assert!(resultado.is_err());
986    }
987
988    #[test]
989    fn remember_response_merged_into_memory_id_some_serializes_integer() {
990        let resp = RememberResponse {
991            memory_id: 10,
992            name: "mem-mergeada".to_string(),
993            namespace: "global".to_string(),
994            action: "updated".to_string(),
995            operation: "updated".to_string(),
996            version: 3,
997            extraction_method: None,
998            entities_persisted: 0,
999            relationships_persisted: 0,
1000            relationships_truncated: false,
1001            chunks_created: 1,
1002            chunks_persisted: 0,
1003            urls_persisted: 0,
1004            merged_into_memory_id: Some(7),
1005            warnings: vec![],
1006            created_at: 0,
1007            created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1008            elapsed_ms: 0,
1009            name_was_normalized: false,
1010            original_name: None,
1011        };
1012
1013        let json = serde_json::to_value(&resp).expect("serialization failed");
1014        assert_eq!(json["merged_into_memory_id"], 7);
1015    }
1016
1017    #[test]
1018    fn remember_response_urls_persisted_serializes_field() {
1019        // v1.0.24 P0-2: garante que urls_persisted aparece no JSON e aceita valor > 0.
1020        let resp = RememberResponse {
1021            memory_id: 3,
1022            name: "mem-com-urls".to_string(),
1023            namespace: "global".to_string(),
1024            action: "created".to_string(),
1025            operation: "created".to_string(),
1026            version: 1,
1027            entities_persisted: 0,
1028            relationships_persisted: 0,
1029            relationships_truncated: false,
1030            chunks_created: 1,
1031            chunks_persisted: 0,
1032            urls_persisted: 3,
1033            extraction_method: Some("regex-only".to_string()),
1034            merged_into_memory_id: None,
1035            warnings: vec![],
1036            created_at: 0,
1037            created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1038            elapsed_ms: 0,
1039            name_was_normalized: false,
1040            original_name: None,
1041        };
1042        let json = serde_json::to_value(&resp).expect("serialization failed");
1043        assert_eq!(json["urls_persisted"], 3);
1044    }
1045
1046    #[test]
1047    fn empty_name_after_normalization_returns_specific_message() {
1048        // P0-4 regression: name consisting only of hyphens normalizes to empty string;
1049        // must produce a distinct error message, not the "too long" message.
1050        use crate::errors::AppError;
1051        let normalized = "---".to_lowercase().replace(['_', ' '], "-");
1052        let normalized = normalized.trim_matches('-').to_string();
1053        let resultado: Result<(), AppError> = if normalized.is_empty() {
1054            Err(AppError::Validation(
1055                "name cannot be empty after normalization (input was blank or contained only hyphens/underscores/spaces)".to_string(),
1056            ))
1057        } else {
1058            Ok(())
1059        };
1060        assert!(resultado.is_err());
1061        if let Err(AppError::Validation(msg)) = resultado {
1062            assert!(
1063                msg.contains("empty after normalization"),
1064                "mensagem deve mencionar 'empty after normalization', obteve: {msg}"
1065            );
1066        }
1067    }
1068
1069    #[test]
1070    fn name_only_underscores_after_normalization_returns_specific_message() {
1071        // P0-4 regression: name consisting only of underscores normalizes to empty string.
1072        use crate::errors::AppError;
1073        let normalized = "___".to_lowercase().replace(['_', ' '], "-");
1074        let normalized = normalized.trim_matches('-').to_string();
1075        assert!(
1076            normalized.is_empty(),
1077            "underscores devem normalizar para string vazia"
1078        );
1079        let resultado: Result<(), AppError> = if normalized.is_empty() {
1080            Err(AppError::Validation(
1081                "name cannot be empty after normalization (input was blank or contained only hyphens/underscores/spaces)".to_string(),
1082            ))
1083        } else {
1084            Ok(())
1085        };
1086        assert!(resultado.is_err());
1087        if let Err(AppError::Validation(msg)) = resultado {
1088            assert!(
1089                msg.contains("empty after normalization"),
1090                "mensagem deve mencionar 'empty after normalization', obteve: {msg}"
1091            );
1092        }
1093    }
1094
1095    #[test]
1096    fn remember_response_relationships_truncated_serializes_field() {
1097        // P1-D: garante que relationships_truncated aparece no JSON como bool.
1098        let resp_false = RememberResponse {
1099            memory_id: 1,
1100            name: "test".to_string(),
1101            namespace: "global".to_string(),
1102            action: "created".to_string(),
1103            operation: "created".to_string(),
1104            version: 1,
1105            entities_persisted: 2,
1106            relationships_persisted: 1,
1107            relationships_truncated: false,
1108            chunks_created: 1,
1109            chunks_persisted: 0,
1110            urls_persisted: 0,
1111            extraction_method: None,
1112            merged_into_memory_id: None,
1113            warnings: vec![],
1114            created_at: 0,
1115            created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1116            elapsed_ms: 0,
1117            name_was_normalized: false,
1118            original_name: None,
1119        };
1120        let json_false = serde_json::to_value(&resp_false).expect("serialization failed");
1121        assert_eq!(json_false["relationships_truncated"], false);
1122
1123        let resp_true = RememberResponse {
1124            relationships_truncated: true,
1125            ..resp_false
1126        };
1127        let json_true = serde_json::to_value(&resp_true).expect("serialization failed");
1128        assert_eq!(json_true["relationships_truncated"], true);
1129    }
1130
1131    // GAP-08: body-preservation predicate tests.
1132    // Verifies the decision logic that determines whether an existing body should
1133    // be kept instead of overwritten with an empty incoming body during --force-merge.
1134
1135    /// Returns `true` when the existing body should be preserved.
1136    ///
1137    /// Mirrors the `body_will_be_preserved` expression in `run()` so the logic
1138    /// is testable without a real database connection.
1139    fn should_preserve_body(force_merge: bool, raw_body_is_empty: bool, clear_body: bool) -> bool {
1140        force_merge && raw_body_is_empty && !clear_body
1141    }
1142
1143    #[test]
1144    fn gap08_empty_body_force_merge_no_clear_body_preserves() {
1145        // Caller passes no body with --force-merge but without --clear-body.
1146        // The existing body in the DB must be kept.
1147        assert!(
1148            should_preserve_body(true, true, false),
1149            "empty body + force-merge + no clear-body should trigger preservation"
1150        );
1151    }
1152
1153    #[test]
1154    fn gap08_empty_body_force_merge_with_clear_body_does_not_preserve() {
1155        // Caller explicitly passes --clear-body; intentional wipe is honoured.
1156        assert!(
1157            !should_preserve_body(true, true, true),
1158            "--clear-body must bypass preservation"
1159        );
1160    }
1161
1162    #[test]
1163    fn gap08_non_empty_body_force_merge_does_not_preserve() {
1164        // Caller provides a real body; it must overwrite the existing one.
1165        assert!(
1166            !should_preserve_body(true, false, false),
1167            "non-empty body must overwrite, not preserve"
1168        );
1169    }
1170
1171    #[test]
1172    fn gap08_empty_body_no_force_merge_does_not_preserve() {
1173        // Without --force-merge the path is a fresh create; no preservation needed.
1174        assert!(
1175            !should_preserve_body(false, true, false),
1176            "no --force-merge means no preservation logic applies"
1177        );
1178    }
1179}