1use 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
17fn compute_chunks_persisted(chunks_created: usize) -> usize {
26 if chunks_created > 1 {
27 chunks_created
28 } else {
29 0
30 }
31}
32
33#[derive(clap::Args)]
34#[command(after_long_help = "EXAMPLES:\n \
35 # Create a memory with inline body\n \
36 sqlite-graphrag remember --name design-auth --type decision \\\n \
37 --description \"auth design\" --body \"JWT for stateless auth\"\n\n \
38 # Create with curated graph via --graph-stdin\n \
39 echo '{\"body\":\"...\",\"entities\":[],\"relationships\":[]}' | \\\n \
40 sqlite-graphrag remember --name my-mem --type note --description \"desc\" --graph-stdin\n\n \
41 # Enable automatic URL extraction with --graph-stdin (URL-regex only since v1.0.79)\n \
42 echo '{\"body\":\"See https://docs.rs ...\",\"entities\":[],\"relationships\":[]}' | \\\n \
43 sqlite-graphrag remember --name url-test --type note --description \"test\" \\\n \
44 --graph-stdin --enable-ner\n\n \
45 # Idempotent upsert with --force-merge\n \
46 sqlite-graphrag remember --name my-mem --type note --description \"updated\" \\\n \
47 --body \"new content\" --force-merge\n\n\
48NOTE:\n \
49 remember does NOT accept positional arguments.\n \
50 Use --body \"text\" for inline content\n \
51 Use --body-file path for file content\n \
52 Use --body-stdin for piped content\n \
53 Use --graph-stdin for JSON with entities and relationships\n\n\
54ENTITY TYPES (for --graph-stdin entities, NOT memory --type):\n \
55 concept, tool, person, file, project, decision, incident,\n \
56 organization, location, date, dashboard, issue_tracker, memory\n \
57 WARNING: reference, skill, document, note, user, feedback are\n \
58 MEMORY types only — NOT valid for entities.\n \
59 Mapping: reference→concept, document→file, user→person")]
60pub struct RememberArgs {
61 #[arg(long)]
64 pub name: String,
65 #[arg(
66 long,
67 value_enum,
68 long_help = "Memory kind stored in `memories.type`. Required when creating a new memory. Optional with --force-merge: if omitted the existing memory type is inherited. This is NOT the graph `entity_type` used in `--entities-file`. Valid values: user, feedback, project, reference, decision, incident, skill, document, note."
69 )]
70 pub r#type: Option<MemoryType>,
71 #[arg(long)]
74 pub description: Option<String>,
75 #[arg(
78 long,
79 help = "Inline body content (max 500 KB / 512000 bytes; for larger inputs split into multiple memories or use --body-file)",
80 conflicts_with_all = ["body_file", "body_stdin", "graph_stdin"]
81 )]
82 pub body: Option<String>,
83 #[arg(
84 long,
85 help = "Read body from a file instead of --body",
86 conflicts_with_all = ["body", "body_stdin", "graph_stdin"]
87 )]
88 pub body_file: Option<std::path::PathBuf>,
89 #[arg(
92 long,
93 conflicts_with_all = ["body", "body_file", "graph_stdin"]
94 )]
95 pub body_stdin: bool,
96 #[arg(
97 long,
98 help = "JSON file containing entities to associate with this memory"
99 )]
100 pub entities_file: Option<std::path::PathBuf>,
101 #[arg(
102 long,
103 help = "JSON file containing relationships to associate with this memory"
104 )]
105 pub relationships_file: Option<std::path::PathBuf>,
106 #[arg(
107 long,
108 help = "Read graph JSON (body + entities + relationships) from stdin",
109 conflicts_with_all = [
110 "body",
111 "body_file",
112 "body_stdin",
113 "entities_file",
114 "relationships_file"
115 ]
116 )]
117 pub graph_stdin: bool,
118 #[arg(
119 long,
120 help = "Namespace (env: SQLITE_GRAPHRAG_NAMESPACE, default: global)"
121 )]
122 pub namespace: Option<String>,
123 #[arg(long)]
125 pub metadata: Option<String>,
126 #[arg(long, help = "JSON file containing metadata key-value pairs")]
127 pub metadata_file: Option<std::path::PathBuf>,
128 #[arg(long)]
129 pub force_merge: bool,
130 #[arg(
131 long,
132 value_name = "EPOCH_OR_RFC3339",
133 value_parser = crate::parsers::parse_expected_updated_at,
134 long_help = "Optimistic lock: reject if updated_at does not match. \
135Accepts Unix epoch (e.g. 1700000000) or RFC 3339 (e.g. 2026-04-19T12:00:00Z)."
136 )]
137 pub expected_updated_at: Option<i64>,
138 #[arg(
139 long,
140 env = "SQLITE_GRAPHRAG_ENABLE_NER",
141 value_parser = crate::parsers::parse_bool_flexible,
142 action = clap::ArgAction::Set,
143 num_args = 0..=1,
144 default_missing_value = "true",
145 default_value = "false",
146 help = "Enable automatic URL-regex extraction from body (the GLiNER NER pipeline was removed in v1.0.79)"
147 )]
148 pub enable_ner: bool,
149 #[arg(
150 long,
151 env = "SQLITE_GRAPHRAG_GLINER_VARIANT",
152 default_value = "fp32",
153 help = "DEPRECATED: no effect since v1.0.79 (the GLiNER pipeline was removed); accepted for compatibility only"
154 )]
155 pub gliner_variant: String,
156 #[arg(long, hide = true)]
157 pub skip_extraction: bool,
158 #[arg(
162 long,
163 default_value_t = false,
164 help = "Explicitly clear body content during --force-merge (without this flag, an empty body is ignored and the existing body is kept)"
165 )]
166 pub clear_body: bool,
167 #[arg(
169 long,
170 default_value_t = false,
171 help = "Validate input and report planned actions without persisting"
172 )]
173 pub dry_run: bool,
174 #[arg(long)]
176 pub session_id: Option<String>,
177 #[arg(long, value_enum, default_value_t = JsonOutputFormat::Json)]
178 pub format: JsonOutputFormat,
179 #[arg(long, hide = true, help = "No-op; JSON is always emitted on stdout")]
180 pub json: bool,
181 #[arg(long, env = "SQLITE_GRAPHRAG_DB_PATH")]
182 pub db: Option<String>,
183 #[arg(long, default_value_t = crate::constants::DEFAULT_MAX_RSS_MB,
185 help = "Maximum process RSS in MiB; abort if exceeded during embedding (default: 8192)")]
186 pub max_rss_mb: u64,
187 #[arg(long, default_value_t = 50, value_name = "N")]
190 pub max_entity_degree: u32,
191 #[arg(long, default_value_t = 4, value_name = "N",
195 value_parser = clap::value_parser!(u64).range(1..=32),
196 help = "Maximum simultaneous LLM embedding subprocesses (default: 4, clamp [1,32])")]
197 pub llm_parallelism: u64,
198}
199
200#[derive(Deserialize, Default)]
201#[serde(deny_unknown_fields)]
202struct GraphInput {
203 #[serde(default)]
204 body: Option<String>,
205 #[serde(default)]
206 entities: Vec<NewEntity>,
207 #[serde(default)]
208 relationships: Vec<NewRelationship>,
209}
210
211fn normalize_and_validate_graph_input(graph: &mut GraphInput) -> Result<(), AppError> {
212 for rel in &mut graph.relationships {
213 rel.relation = crate::parsers::normalize_relation(&rel.relation);
214 if let Err(e) = crate::parsers::validate_relation_format(&rel.relation) {
215 return Err(AppError::Validation(format!(
216 "{e} for relationship '{}' -> '{}'",
217 rel.source, rel.target
218 )));
219 }
220 crate::parsers::warn_if_non_canonical(&rel.relation);
221 if !(0.0..=1.0).contains(&rel.strength) {
222 return Err(AppError::Validation(format!(
223 "invalid strength {} for relationship '{}' -> '{}'; expected value in [0.0, 1.0]",
224 rel.strength, rel.source, rel.target
225 )));
226 }
227 }
228
229 Ok(())
230}
231
232#[tracing::instrument(skip_all, level = "debug", name = "remember")]
233pub fn run(args: RememberArgs, llm_backend: crate::cli::LlmBackendChoice) -> Result<(), AppError> {
234 use crate::constants::*;
235
236 let inicio = std::time::Instant::now();
237 let _ = args.format;
238 tracing::debug!(target: "remember", name = %args.name, "persisting memory");
239 let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
240
241 let original_name = args.name.clone();
245
246 let normalized_name = {
250 let lower = args.name.to_lowercase().replace(['_', ' '], "-");
251 let trimmed = lower.trim_matches('-').to_string();
252 if trimmed != args.name {
253 tracing::warn!(target: "remember",
254 original = %args.name,
255 normalized = %trimmed,
256 "name auto-normalized to kebab-case"
257 );
258 }
259 trimmed
260 };
261 let name_was_normalized = normalized_name != original_name;
262
263 if normalized_name.is_empty() {
264 return Err(AppError::Validation(
265 "name cannot be empty after normalization (input was blank or contained only hyphens/underscores/spaces)".to_string(),
266 ));
267 }
268 if normalized_name.len() > MAX_MEMORY_NAME_LEN {
269 return Err(AppError::LimitExceeded(
270 crate::i18n::validation::name_length(MAX_MEMORY_NAME_LEN),
271 ));
272 }
273
274 if normalized_name.starts_with("__") {
275 return Err(AppError::Validation(
276 crate::i18n::validation::reserved_name(),
277 ));
278 }
279
280 {
281 let slug_re = crate::constants::name_slug_regex();
282 if !slug_re.is_match(&normalized_name) {
283 return Err(AppError::Validation(crate::i18n::validation::name_kebab(
284 &normalized_name,
285 )));
286 }
287 }
288
289 if let Some(ref desc) = args.description {
290 if desc.len() > MAX_MEMORY_DESCRIPTION_LEN {
291 return Err(AppError::Validation(
292 crate::i18n::validation::description_exceeds(MAX_MEMORY_DESCRIPTION_LEN),
293 ));
294 }
295 }
296
297 let mut raw_body = if let Some(b) = args.body {
298 b
299 } else if let Some(ref path) = args.body_file {
300 let file_size = std::fs::metadata(path).map_err(AppError::Io)?.len();
301 if file_size > MAX_MEMORY_BODY_LEN as u64 {
302 return Err(AppError::LimitExceeded(
303 crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
304 ));
305 }
306 match std::fs::read_to_string(path) {
307 Ok(s) => s,
308 Err(e) if e.kind() == std::io::ErrorKind::InvalidData => {
309 let bytes = std::fs::read(path).map_err(AppError::Io)?;
310 tracing::warn!(target: "remember", "body file contains invalid UTF-8; replacing invalid sequences");
311 String::from_utf8_lossy(&bytes).into_owned()
312 }
313 Err(e) => return Err(AppError::Io(e)),
314 }
315 } else if args.body_stdin || args.graph_stdin {
316 crate::stdin_helper::read_stdin_with_timeout(60)?
317 } else {
318 String::new()
319 };
320
321 let mut entities_provided_externally =
322 args.entities_file.is_some() || args.relationships_file.is_some();
323
324 let mut graph = GraphInput::default();
325 if let Some(path) = args.entities_file {
326 let file_size = std::fs::metadata(&path).map_err(AppError::Io)?.len();
327 if file_size > MAX_MEMORY_BODY_LEN as u64 {
328 return Err(AppError::LimitExceeded(
329 crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
330 ));
331 }
332 let content = std::fs::read_to_string(&path).map_err(AppError::Io)?;
333 graph.entities = serde_json::from_str(&content)?;
334 }
335 if let Some(path) = args.relationships_file {
336 let file_size = std::fs::metadata(&path).map_err(AppError::Io)?.len();
337 if file_size > MAX_MEMORY_BODY_LEN as u64 {
338 return Err(AppError::LimitExceeded(
339 crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
340 ));
341 }
342 let content = std::fs::read_to_string(&path).map_err(AppError::Io)?;
343 graph.relationships = serde_json::from_str(&content)?;
344 }
345 if args.graph_stdin {
346 graph = serde_json::from_str::<GraphInput>(&raw_body).map_err(|e| {
347 AppError::Validation(format!("invalid JSON payload on --graph-stdin: {e}"))
348 })?;
349 raw_body = graph.body.take().unwrap_or_default();
350 }
351 if args.graph_stdin && !graph.entities.is_empty() {
352 entities_provided_externally = true;
353 }
354
355 if graph.entities.len() > max_entities_per_memory() {
356 return Err(AppError::LimitExceeded(errors_msg::entity_limit_exceeded(
357 max_entities_per_memory(),
358 )));
359 }
360 let mut relationships_truncated = false;
361 let rel_cap = max_relationships_per_memory();
362 if graph.relationships.len() > rel_cap {
363 tracing::warn!(target: "remember",
364 count = graph.relationships.len(),
365 cap = rel_cap,
366 "truncating relationships to cap"
367 );
368 graph.relationships.truncate(rel_cap);
369 relationships_truncated = true;
370 }
371 normalize_and_validate_graph_input(&mut graph)?;
372
373 if raw_body.len() > MAX_MEMORY_BODY_LEN {
374 return Err(AppError::LimitExceeded(
375 crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
376 ));
377 }
378
379 let body_will_be_preserved = args.force_merge && raw_body.trim().is_empty() && !args.clear_body;
384 if !entities_provided_externally
385 && graph.entities.is_empty()
386 && raw_body.trim().is_empty()
387 && !body_will_be_preserved
388 && !args.clear_body
389 {
390 return Err(AppError::Validation(crate::i18n::validation::empty_body()));
391 }
392
393 let metadata: serde_json::Value = if let Some(m) = args.metadata {
394 serde_json::from_str(&m)?
395 } else if let Some(path) = args.metadata_file {
396 let file_size = std::fs::metadata(&path).map_err(AppError::Io)?.len();
397 if file_size > MAX_MEMORY_BODY_LEN as u64 {
398 return Err(AppError::LimitExceeded(
399 crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
400 ));
401 }
402 let content = std::fs::read_to_string(&path).map_err(AppError::Io)?;
403 serde_json::from_str(&content)?
404 } else {
405 serde_json::json!({})
406 };
407
408 let mut body_hash = blake3::hash(raw_body.as_bytes()).to_hex().to_string();
409 let mut snippet: String = raw_body.chars().take(200).collect();
410
411 let paths = AppPaths::resolve(args.db.as_deref())?;
412 paths.ensure_dirs()?;
413
414 let mut extraction_method: Option<String> = None;
416 let mut extracted_urls: Vec<crate::extraction::ExtractedUrl> = Vec::with_capacity(4);
417 if args.enable_ner && args.skip_extraction {
418 return Err(AppError::Validation(
419 "--enable-ner and --skip-extraction are mutually exclusive; remove one".to_string(),
420 ));
421 }
422 if args.skip_extraction && !args.enable_ner {
423 tracing::warn!(
430 "--skip-extraction is deprecated since v1.0.45 and has no effect (NER is disabled by default); remove this flag to silence the warning"
431 );
432 }
433 if args.gliner_variant != "fp32" {
437 tracing::warn!(
438 "--gliner-variant is deprecated and has no effect since v1.0.79 (the GLiNER pipeline was removed); --enable-ner performs URL-regex extraction only"
439 );
440 }
441 let gliner_variant: crate::extraction::GlinerVariant = match args.gliner_variant.as_str() {
442 "int8" => crate::extraction::GlinerVariant::Int8,
443 _ => crate::extraction::GlinerVariant::Fp32,
444 };
445 if args.enable_ner && graph.entities.is_empty() && !raw_body.trim().is_empty() {
446 match crate::extraction::extract_graph_auto(&raw_body, &paths, gliner_variant) {
447 Ok(extracted) => {
448 extraction_method = Some("url-regex".to_string());
452 extracted_urls = extracted.urls;
453 graph.entities = extracted
456 .entities
457 .into_iter()
458 .map(|e| NewEntity {
459 name: e.name,
460 entity_type: crate::entity_type::EntityType::Concept,
461 description: None,
462 })
463 .collect();
464 graph.relationships.clear();
465 relationships_truncated = false;
466
467 if graph.entities.len() > max_entities_per_memory() {
468 graph.entities.truncate(max_entities_per_memory());
469 }
470 if graph.relationships.len() > max_relationships_per_memory() {
471 relationships_truncated = true;
472 graph.relationships.truncate(max_relationships_per_memory());
473 }
474 normalize_and_validate_graph_input(&mut graph)?;
475 }
476 Err(e) => {
477 tracing::warn!(target: "remember", error = %e, "auto-extraction failed, graceful degradation");
478 extraction_method = Some("none:extraction-failed".to_string());
479 }
480 }
481 }
482
483 let mut conn = open_rw(&paths.db)?;
484 ensure_schema(&mut conn)?;
485
486 if args.dry_run {
488 let existing = memories::find_by_name(&conn, &namespace, &normalized_name)?;
489 let planned_action = if existing.is_some() && args.force_merge {
490 "would_update"
491 } else {
492 "would_create"
493 };
494 output::emit_json(&serde_json::json!({
495 "dry_run": true,
496 "name": normalized_name,
497 "namespace": namespace,
498 "planned_action": planned_action,
499 }))?;
500 return Ok(());
501 }
502
503 {
504 use crate::constants::MAX_NAMESPACES_ACTIVE;
505 let active_count: u32 = conn.query_row(
506 "SELECT COUNT(DISTINCT namespace) FROM memories WHERE deleted_at IS NULL",
507 [],
508 |r| r.get::<_, i64>(0).map(|v| v as u32),
509 )?;
510 let ns_exists: bool = conn.query_row(
511 "SELECT EXISTS(SELECT 1 FROM memories WHERE namespace = ?1 AND deleted_at IS NULL)",
512 rusqlite::params![namespace],
513 |r| r.get::<_, i64>(0).map(|v| v > 0),
514 )?;
515 if !ns_exists && active_count >= MAX_NAMESPACES_ACTIVE {
516 return Err(AppError::NamespaceError(format!(
517 "active namespace limit of {MAX_NAMESPACES_ACTIVE} reached while trying to create '{namespace}'"
518 )));
519 }
520 }
521
522 if let Some((sd_id, true)) =
524 memories::find_by_name_any_state(&conn, &namespace, &normalized_name)?
525 {
526 if args.force_merge {
527 memories::clear_deleted_at(&conn, sd_id)?;
528 } else {
529 return Err(AppError::Duplicate(
530 errors_msg::duplicate_memory_soft_deleted(&normalized_name, &namespace),
531 ));
532 }
533 }
534
535 let existing_memory = memories::find_by_name(&conn, &namespace, &normalized_name)?;
536 if existing_memory.is_some() && !args.force_merge {
537 return Err(AppError::Duplicate(errors_msg::duplicate_memory(
538 &normalized_name,
539 &namespace,
540 )));
541 }
542
543 let (resolved_type, resolved_description) = if existing_memory.is_none() {
547 let t = args.r#type.ok_or_else(|| {
549 AppError::Validation(
550 "--type and --description are required when creating a new memory".to_string(),
551 )
552 })?;
553 let d = args.description.clone().ok_or_else(|| {
554 AppError::Validation(
555 "--type and --description are required when creating a new memory".to_string(),
556 )
557 })?;
558 (t.as_str().to_string(), d)
559 } else {
560 let existing_row = memories::read_by_name(&conn, &namespace, &normalized_name)?
562 .ok_or_else(|| {
563 AppError::NotFound(format!(
564 "memory '{normalized_name}' not found in namespace '{namespace}'"
565 ))
566 })?;
567 let t = args
568 .r#type
569 .map(|v| v.as_str().to_string())
570 .unwrap_or_else(|| existing_row.memory_type.clone());
571 let d = args
572 .description
573 .clone()
574 .unwrap_or_else(|| existing_row.description.clone());
575 (t, d)
576 };
577
578 if body_will_be_preserved {
583 if let Some(existing_row) = memories::read_by_name(&conn, &namespace, &normalized_name)? {
584 if !existing_row.body.is_empty() {
585 tracing::debug!(target: "remember",
586 name = %normalized_name,
587 "GAP-08: empty body with --force-merge and no --clear-body; preserving existing body"
588 );
589 raw_body = existing_row.body;
590 body_hash = blake3::hash(raw_body.as_bytes()).to_hex().to_string();
591 snippet = raw_body.chars().take(200).collect();
592 }
593 }
594 }
595
596 let duplicate_hash_id = memories::find_by_hash(&conn, &namespace, &body_hash)?;
597
598 output::emit_progress_i18n(
599 &format!(
600 "Remember stage: validated input; available memory {} MB",
601 crate::memory_guard::available_memory_mb()
602 ),
603 &format!(
604 "Stage remember: input validated; available memory {} MB",
605 crate::memory_guard::available_memory_mb()
606 ),
607 );
608
609 let model_max_length = crate::tokenizer::get_model_max_length();
610 let total_passage_tokens = crate::tokenizer::count_passage_tokens(&raw_body)?;
611 let chunks_info = chunking::split_into_chunks_hierarchical(&raw_body);
612 let chunks_created = chunks_info.len();
613 let chunks_persisted = compute_chunks_persisted(chunks_info.len());
617
618 output::emit_progress_i18n(
619 &format!(
620 "Remember stage: tokenizer counted {total_passage_tokens} passage tokens (model max {model_max_length}); chunking produced {} chunks; process RSS {} MB",
621 chunks_created,
622 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
623 ),
624 &format!(
625 "Stage remember: tokenizer counted {total_passage_tokens} passage tokens (model max {model_max_length}); chunking produced {} chunks; process RSS {} MB",
626 chunks_created,
627 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
628 ),
629 );
630
631 if chunks_created > crate::constants::REMEMBER_MAX_SAFE_MULTI_CHUNKS {
632 return Err(AppError::LimitExceeded(format!(
633 "document produces {chunks_created} chunks; current safe operational limit is {} chunks; split the document before using remember",
634 crate::constants::REMEMBER_MAX_SAFE_MULTI_CHUNKS
635 )));
636 }
637
638 output::emit_progress_i18n("Computing embedding...", "Calculando embedding...");
639 let mut chunk_embeddings_cache: Option<Vec<Vec<f32>>> = None;
640
641 let embedding = if chunks_info.len() == 1 {
642 crate::embedder::embed_passage_with_choice(&paths.models, &raw_body, Some(llm_backend))?
644 } else {
645 let chunk_texts: Vec<String> = chunks_info
646 .iter()
647 .map(|c| chunking::chunk_text(&raw_body, c).to_string())
648 .collect();
649 output::emit_progress_i18n(
655 &format!(
656 "Embedding {} chunks in parallel batches (parallelism {})...",
657 chunks_info.len(),
658 args.llm_parallelism
659 ),
660 &format!(
661 "Embedding {} chunks em lotes paralelos (paralelismo {})...",
662 chunks_info.len(),
663 args.llm_parallelism
664 ),
665 );
666 if let Some(rss) = crate::memory_guard::current_process_memory_mb() {
667 if rss > args.max_rss_mb {
668 tracing::error!(target: "remember",
669 rss_mb = rss,
670 max_rss_mb = args.max_rss_mb,
671 "RSS exceeded --max-rss-mb threshold; aborting to prevent system instability"
672 );
673 return Err(AppError::LowMemory {
674 available_mb: crate::memory_guard::available_memory_mb(),
675 required_mb: args.max_rss_mb,
676 });
677 }
678 }
679 let chunk_embeddings = crate::embedder::embed_passages_parallel_local(
680 &paths.models,
681 &chunk_texts,
682 args.llm_parallelism as usize,
683 crate::embedder::chunk_embed_batch_size(),
684 )?;
685 output::emit_progress_i18n(
686 &format!(
687 "Remember stage: chunk embeddings complete; process RSS {} MB",
688 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
689 ),
690 &format!(
691 "Stage remember: chunk embeddings completed; process RSS {} MB",
692 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
693 ),
694 );
695 let aggregated = chunking::aggregate_embeddings(&chunk_embeddings);
696 chunk_embeddings_cache = Some(chunk_embeddings);
697 aggregated
698 };
699 let body_for_storage = raw_body;
700
701 let memory_type = resolved_type.as_str();
702 let new_memory = NewMemory {
703 namespace: namespace.clone(),
704 name: normalized_name.clone(),
705 memory_type: memory_type.to_string(),
706 description: resolved_description.clone(),
707 body: body_for_storage,
708 body_hash: body_hash.clone(),
709 session_id: args.session_id.clone(),
710 source: "agent".to_string(),
711 metadata,
712 };
713
714 let mut warnings = Vec::with_capacity(4);
715 let mut entities_persisted = 0usize;
716 let mut relationships_persisted = 0usize;
717
718 let entity_texts: Vec<String> = graph
723 .entities
724 .iter()
725 .map(|entity| match &entity.description {
726 Some(desc) => format!("{} {}", entity.name, desc),
727 None => entity.name.clone(),
728 })
729 .collect();
730 let (graph_entity_embeddings, embed_cache_stats) = crate::embedder::embed_entity_texts_cached(
738 &paths.models,
739 &entity_texts,
740 args.llm_parallelism as usize,
741 )?;
742 if embed_cache_stats.hits > 0 {
743 tracing::debug!(
744 hits = embed_cache_stats.hits,
745 misses = embed_cache_stats.misses,
746 requested = embed_cache_stats.requested,
747 "G56: entity embed cache hit (remember)"
748 );
749 }
750
751 let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
752
753 let mut skip_reindex = false;
754 let (memory_id, action, version) = match existing_memory {
755 Some((existing_id, _updated_at, _current_version)) => {
756 if let Some(hash_id) = duplicate_hash_id {
757 if hash_id != existing_id {
758 warnings.push(format!(
759 "identical body already exists as memory id {hash_id}"
760 ));
761 }
762 }
763
764 let (old_fts_name, old_fts_desc, old_fts_body): (String, String, String) = tx
766 .query_row(
767 "SELECT name, description, body FROM memories WHERE id = ?1",
768 rusqlite::params![existing_id],
769 |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
770 )?;
771
772 let existing_body_hash: Option<String> = tx
774 .query_row(
775 "SELECT body_hash FROM memories WHERE id = ?1",
776 rusqlite::params![existing_id],
777 |r| r.get(0),
778 )
779 .ok();
780 let body_unchanged = existing_body_hash.as_deref() == Some(&body_hash);
781 skip_reindex = body_unchanged;
782 if !body_unchanged {
783 storage_chunks::delete_chunks(&tx, existing_id)?;
784 }
785
786 let next_v = versions::next_version(&tx, existing_id)?;
787 memories::update(&tx, existing_id, &new_memory, args.expected_updated_at)?;
788
789 memories::sync_fts_after_update(
792 &tx,
793 existing_id,
794 &old_fts_name,
795 &old_fts_desc,
796 &old_fts_body,
797 &normalized_name,
798 &resolved_description,
799 &new_memory.body,
800 )?;
801
802 versions::insert_version(
803 &tx,
804 existing_id,
805 next_v,
806 &normalized_name,
807 memory_type,
808 &resolved_description,
809 &new_memory.body,
810 &serde_json::to_string(&new_memory.metadata)?,
811 None,
812 "edit",
813 )?;
814 if !body_unchanged {
815 memories::upsert_vec(
816 &tx,
817 existing_id,
818 &namespace,
819 memory_type,
820 &embedding,
821 &normalized_name,
822 &snippet,
823 )?;
824 }
825 (existing_id, "updated".to_string(), next_v)
826 }
827 None => {
828 if let Some(hash_id) = duplicate_hash_id {
829 warnings.push(format!(
830 "identical body already exists as memory id {hash_id}"
831 ));
832 }
833 let id = memories::insert(&tx, &new_memory)?;
834 versions::insert_version(
835 &tx,
836 id,
837 1,
838 &normalized_name,
839 memory_type,
840 &resolved_description,
841 &new_memory.body,
842 &serde_json::to_string(&new_memory.metadata)?,
843 None,
844 "create",
845 )?;
846 memories::upsert_vec(
847 &tx,
848 id,
849 &namespace,
850 memory_type,
851 &embedding,
852 &normalized_name,
853 &snippet,
854 )?;
855 (id, "created".to_string(), 1)
856 }
857 };
858
859 if chunks_info.len() > 1 && !skip_reindex {
860 storage_chunks::insert_chunk_slices(&tx, memory_id, &new_memory.body, &chunks_info)?;
861
862 let chunk_embeddings = chunk_embeddings_cache.take().ok_or_else(|| {
863 AppError::Internal(anyhow::anyhow!(
864 "chunk embeddings cache missing in multi-chunk remember path"
865 ))
866 })?;
867
868 for (i, emb) in chunk_embeddings.iter().enumerate() {
869 storage_chunks::upsert_chunk_vec(&tx, i as i64, memory_id, i as i32, emb)?;
870 }
871 output::emit_progress_i18n(
872 &format!(
873 "Remember stage: persisted chunk vectors; process RSS {} MB",
874 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
875 ),
876 &format!(
877 "Etapa remember: vetores de chunks persistidos; RSS do processo {} MB",
878 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
879 ),
880 );
881 }
882
883 if !graph.entities.is_empty() || !graph.relationships.is_empty() {
884 for entity in &graph.entities {
885 let entity_id = entities::upsert_entity(&tx, &namespace, entity)?;
886 let entity_embedding = &graph_entity_embeddings[entities_persisted];
887 entities::upsert_entity_vec(
888 &tx,
889 entity_id,
890 &namespace,
891 entity.entity_type,
892 entity_embedding,
893 &entity.name,
894 )?;
895 entities::link_memory_entity(&tx, memory_id, entity_id)?;
896 entities::increment_degree(&tx, entity_id)?;
897 if args.max_entity_degree > 0 {
899 let cap = args.max_entity_degree as i64;
900 let degree: i64 = tx.query_row(
901 "SELECT degree FROM entities WHERE id = ?1",
902 rusqlite::params![entity_id],
903 |r| r.get(0),
904 )?;
905 if degree > cap {
906 tracing::warn!(target: "remember",
907 entity = %entity.name,
908 degree = degree,
909 cap = cap,
910 "entity degree cap exceeded"
911 );
912 }
913 }
914 entities_persisted += 1;
915 }
916 let entity_types: std::collections::HashMap<&str, EntityType> = graph
917 .entities
918 .iter()
919 .map(|entity| (entity.name.as_str(), entity.entity_type))
920 .collect();
921
922 for rel in &graph.relationships {
923 let source_entity = NewEntity {
924 name: rel.source.clone(),
925 entity_type: entity_types
926 .get(rel.source.as_str())
927 .copied()
928 .unwrap_or(EntityType::Concept),
929 description: None,
930 };
931 let target_entity = NewEntity {
932 name: rel.target.clone(),
933 entity_type: entity_types
934 .get(rel.target.as_str())
935 .copied()
936 .unwrap_or(EntityType::Concept),
937 description: None,
938 };
939 let source_id = entities::upsert_entity(&tx, &namespace, &source_entity)?;
940 let target_id = entities::upsert_entity(&tx, &namespace, &target_entity)?;
941 let rel_id = entities::upsert_relationship(&tx, &namespace, source_id, target_id, rel)?;
942 entities::link_memory_relationship(&tx, memory_id, rel_id)?;
943 relationships_persisted += 1;
944 }
945 }
946 tx.commit()?;
947
948 let urls_persisted = if !extracted_urls.is_empty() {
951 let url_entries: Vec<storage_urls::MemoryUrl> = extracted_urls
952 .into_iter()
953 .map(|u| storage_urls::MemoryUrl {
954 url: u.url,
955 offset: Some(u.start as i64),
956 })
957 .collect();
958 storage_urls::insert_urls(&conn, memory_id, &url_entries)
959 } else {
960 0
961 };
962
963 conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
964
965 let created_at_epoch = chrono::Utc::now().timestamp();
966 let created_at_iso = crate::tz::format_iso(chrono::Utc::now());
967
968 output::emit_json(&RememberResponse {
969 memory_id,
970 name: normalized_name.clone(),
974 namespace,
975 action: action.clone(),
976 operation: action,
977 version,
978 entities_persisted,
979 relationships_persisted,
980 relationships_truncated,
981 chunks_created,
982 chunks_persisted,
983 urls_persisted,
984 extraction_method,
985 merged_into_memory_id: None,
986 warnings,
987 created_at: created_at_epoch,
988 created_at_iso,
989 elapsed_ms: inicio.elapsed().as_millis() as u64,
990 name_was_normalized,
991 original_name: name_was_normalized.then_some(original_name),
992 })?;
993
994 Ok(())
995}
996
997#[cfg(test)]
998mod tests {
999 use super::compute_chunks_persisted;
1000 use crate::output::RememberResponse;
1001
1002 #[test]
1004 fn chunks_persisted_zero_for_zero_chunks() {
1005 assert_eq!(compute_chunks_persisted(0), 0);
1006 }
1007
1008 #[test]
1009 fn chunks_persisted_zero_for_single_chunk_body() {
1010 assert_eq!(compute_chunks_persisted(1), 0);
1013 }
1014
1015 #[test]
1016 fn chunks_persisted_equals_count_for_multi_chunk_body() {
1017 assert_eq!(compute_chunks_persisted(2), 2);
1019 assert_eq!(compute_chunks_persisted(7), 7);
1020 assert_eq!(compute_chunks_persisted(64), 64);
1021 }
1022
1023 #[test]
1024 fn remember_response_serializes_required_fields() {
1025 let resp = RememberResponse {
1026 memory_id: 42,
1027 name: "minha-mem".to_string(),
1028 namespace: "global".to_string(),
1029 action: "created".to_string(),
1030 operation: "created".to_string(),
1031 version: 1,
1032 entities_persisted: 0,
1033 relationships_persisted: 0,
1034 relationships_truncated: false,
1035 chunks_created: 1,
1036 chunks_persisted: 0,
1037 urls_persisted: 0,
1038 extraction_method: None,
1039 merged_into_memory_id: None,
1040 warnings: vec![],
1041 created_at: 1_705_320_000,
1042 created_at_iso: "2024-01-15T12:00:00Z".to_string(),
1043 elapsed_ms: 55,
1044 name_was_normalized: false,
1045 original_name: None,
1046 };
1047
1048 let json = serde_json::to_value(&resp).expect("serialization failed");
1049 assert_eq!(json["memory_id"], 42);
1050 assert_eq!(json["action"], "created");
1051 assert_eq!(json["operation"], "created");
1052 assert_eq!(json["version"], 1);
1053 assert_eq!(json["elapsed_ms"], 55u64);
1054 assert!(json["warnings"].is_array());
1055 assert!(json["merged_into_memory_id"].is_null());
1056 }
1057
1058 #[test]
1059 fn remember_response_action_e_operation_sao_aliases() {
1060 let resp = RememberResponse {
1061 memory_id: 1,
1062 name: "mem".to_string(),
1063 namespace: "global".to_string(),
1064 action: "updated".to_string(),
1065 operation: "updated".to_string(),
1066 version: 2,
1067 entities_persisted: 3,
1068 relationships_persisted: 1,
1069 relationships_truncated: false,
1070 extraction_method: None,
1071 chunks_created: 2,
1072 chunks_persisted: 2,
1073 urls_persisted: 0,
1074 merged_into_memory_id: None,
1075 warnings: vec![],
1076 created_at: 0,
1077 created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1078 elapsed_ms: 0,
1079 name_was_normalized: false,
1080 original_name: None,
1081 };
1082
1083 let json = serde_json::to_value(&resp).expect("serialization failed");
1084 assert_eq!(
1085 json["action"], json["operation"],
1086 "action e operation devem ser iguais"
1087 );
1088 assert_eq!(json["entities_persisted"], 3);
1089 assert_eq!(json["relationships_persisted"], 1);
1090 assert_eq!(json["chunks_created"], 2);
1091 }
1092
1093 #[test]
1094 fn remember_response_warnings_lista_mensagens() {
1095 let resp = RememberResponse {
1096 memory_id: 5,
1097 name: "dup-mem".to_string(),
1098 namespace: "global".to_string(),
1099 action: "created".to_string(),
1100 operation: "created".to_string(),
1101 version: 1,
1102 entities_persisted: 0,
1103 extraction_method: None,
1104 relationships_persisted: 0,
1105 relationships_truncated: false,
1106 chunks_created: 1,
1107 chunks_persisted: 0,
1108 urls_persisted: 0,
1109 merged_into_memory_id: None,
1110 warnings: vec!["identical body already exists as memory id 3".to_string()],
1111 created_at: 0,
1112 created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1113 elapsed_ms: 10,
1114 name_was_normalized: false,
1115 original_name: None,
1116 };
1117
1118 let json = serde_json::to_value(&resp).expect("serialization failed");
1119 let warnings = json["warnings"]
1120 .as_array()
1121 .expect("warnings deve ser array");
1122 assert_eq!(warnings.len(), 1);
1123 assert!(warnings[0].as_str().unwrap().contains("identical body"));
1124 }
1125
1126 #[test]
1127 fn invalid_name_reserved_prefix_returns_validation_error() {
1128 use crate::errors::AppError;
1129 let nome = "__reservado";
1131 let resultado: Result<(), AppError> = if nome.starts_with("__") {
1132 Err(AppError::Validation(
1133 crate::i18n::validation::reserved_name(),
1134 ))
1135 } else {
1136 Ok(())
1137 };
1138 assert!(resultado.is_err());
1139 if let Err(AppError::Validation(msg)) = resultado {
1140 assert!(!msg.is_empty());
1141 }
1142 }
1143
1144 #[test]
1145 fn name_too_long_returns_validation_error() {
1146 use crate::errors::AppError;
1147 let nome_longo = "a".repeat(crate::constants::MAX_MEMORY_NAME_LEN + 1);
1148 let resultado: Result<(), AppError> =
1149 if nome_longo.is_empty() || nome_longo.len() > crate::constants::MAX_MEMORY_NAME_LEN {
1150 Err(AppError::Validation(crate::i18n::validation::name_length(
1151 crate::constants::MAX_MEMORY_NAME_LEN,
1152 )))
1153 } else {
1154 Ok(())
1155 };
1156 assert!(resultado.is_err());
1157 }
1158
1159 #[test]
1160 fn remember_response_merged_into_memory_id_some_serializes_integer() {
1161 let resp = RememberResponse {
1162 memory_id: 10,
1163 name: "mem-mergeada".to_string(),
1164 namespace: "global".to_string(),
1165 action: "updated".to_string(),
1166 operation: "updated".to_string(),
1167 version: 3,
1168 extraction_method: None,
1169 entities_persisted: 0,
1170 relationships_persisted: 0,
1171 relationships_truncated: false,
1172 chunks_created: 1,
1173 chunks_persisted: 0,
1174 urls_persisted: 0,
1175 merged_into_memory_id: Some(7),
1176 warnings: vec![],
1177 created_at: 0,
1178 created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1179 elapsed_ms: 0,
1180 name_was_normalized: false,
1181 original_name: None,
1182 };
1183
1184 let json = serde_json::to_value(&resp).expect("serialization failed");
1185 assert_eq!(json["merged_into_memory_id"], 7);
1186 }
1187
1188 #[test]
1189 fn remember_response_urls_persisted_serializes_field() {
1190 let resp = RememberResponse {
1192 memory_id: 3,
1193 name: "mem-com-urls".to_string(),
1194 namespace: "global".to_string(),
1195 action: "created".to_string(),
1196 operation: "created".to_string(),
1197 version: 1,
1198 entities_persisted: 0,
1199 relationships_persisted: 0,
1200 relationships_truncated: false,
1201 chunks_created: 1,
1202 chunks_persisted: 0,
1203 urls_persisted: 3,
1204 extraction_method: Some("regex-only".to_string()),
1205 merged_into_memory_id: None,
1206 warnings: vec![],
1207 created_at: 0,
1208 created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1209 elapsed_ms: 0,
1210 name_was_normalized: false,
1211 original_name: None,
1212 };
1213 let json = serde_json::to_value(&resp).expect("serialization failed");
1214 assert_eq!(json["urls_persisted"], 3);
1215 }
1216
1217 #[test]
1218 fn empty_name_after_normalization_returns_specific_message() {
1219 use crate::errors::AppError;
1222 let normalized = "---".to_lowercase().replace(['_', ' '], "-");
1223 let normalized = normalized.trim_matches('-').to_string();
1224 let resultado: Result<(), AppError> = if normalized.is_empty() {
1225 Err(AppError::Validation(
1226 "name cannot be empty after normalization (input was blank or contained only hyphens/underscores/spaces)".to_string(),
1227 ))
1228 } else {
1229 Ok(())
1230 };
1231 assert!(resultado.is_err());
1232 if let Err(AppError::Validation(msg)) = resultado {
1233 assert!(
1234 msg.contains("empty after normalization"),
1235 "mensagem deve mencionar 'empty after normalization', obteve: {msg}"
1236 );
1237 }
1238 }
1239
1240 #[test]
1241 fn name_only_underscores_after_normalization_returns_specific_message() {
1242 use crate::errors::AppError;
1244 let normalized = "___".to_lowercase().replace(['_', ' '], "-");
1245 let normalized = normalized.trim_matches('-').to_string();
1246 assert!(
1247 normalized.is_empty(),
1248 "underscores devem normalizar para string vazia"
1249 );
1250 let resultado: Result<(), AppError> = if normalized.is_empty() {
1251 Err(AppError::Validation(
1252 "name cannot be empty after normalization (input was blank or contained only hyphens/underscores/spaces)".to_string(),
1253 ))
1254 } else {
1255 Ok(())
1256 };
1257 assert!(resultado.is_err());
1258 if let Err(AppError::Validation(msg)) = resultado {
1259 assert!(
1260 msg.contains("empty after normalization"),
1261 "mensagem deve mencionar 'empty after normalization', obteve: {msg}"
1262 );
1263 }
1264 }
1265
1266 #[test]
1267 fn remember_response_relationships_truncated_serializes_field() {
1268 let resp_false = RememberResponse {
1270 memory_id: 1,
1271 name: "test".to_string(),
1272 namespace: "global".to_string(),
1273 action: "created".to_string(),
1274 operation: "created".to_string(),
1275 version: 1,
1276 entities_persisted: 2,
1277 relationships_persisted: 1,
1278 relationships_truncated: false,
1279 chunks_created: 1,
1280 chunks_persisted: 0,
1281 urls_persisted: 0,
1282 extraction_method: None,
1283 merged_into_memory_id: None,
1284 warnings: vec![],
1285 created_at: 0,
1286 created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1287 elapsed_ms: 0,
1288 name_was_normalized: false,
1289 original_name: None,
1290 };
1291 let json_false = serde_json::to_value(&resp_false).expect("serialization failed");
1292 assert_eq!(json_false["relationships_truncated"], false);
1293
1294 let resp_true = RememberResponse {
1295 relationships_truncated: true,
1296 ..resp_false
1297 };
1298 let json_true = serde_json::to_value(&resp_true).expect("serialization failed");
1299 assert_eq!(json_true["relationships_truncated"], true);
1300 }
1301
1302 fn should_preserve_body(force_merge: bool, raw_body_is_empty: bool, clear_body: bool) -> bool {
1311 force_merge && raw_body_is_empty && !clear_body
1312 }
1313
1314 #[test]
1315 fn gap08_empty_body_force_merge_no_clear_body_preserves() {
1316 assert!(
1319 should_preserve_body(true, true, false),
1320 "empty body + force-merge + no clear-body should trigger preservation"
1321 );
1322 }
1323
1324 #[test]
1325 fn gap08_empty_body_force_merge_with_clear_body_does_not_preserve() {
1326 assert!(
1328 !should_preserve_body(true, true, true),
1329 "--clear-body must bypass preservation"
1330 );
1331 }
1332
1333 #[test]
1334 fn gap08_non_empty_body_force_merge_does_not_preserve() {
1335 assert!(
1337 !should_preserve_body(true, false, false),
1338 "non-empty body must overwrite, not preserve"
1339 );
1340 }
1341
1342 #[test]
1343 fn gap08_empty_body_no_force_merge_does_not_preserve() {
1344 assert!(
1346 !should_preserve_body(false, true, false),
1347 "no --force-merge means no preservation logic applies"
1348 );
1349 }
1350}