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, backend_invoked_passage): (Vec<f32>, Option<&str>) = if chunks_info.len() == 1 {
645 crate::embedder::embed_passage_with_choice(&paths.models, &raw_body, Some(llm_backend))
649 .map(|(v, k)| (v, Some(k.as_str())))?
650 } else {
651 let chunk_texts: Vec<String> = chunks_info
652 .iter()
653 .map(|c| chunking::chunk_text(&raw_body, c).to_string())
654 .collect();
655 output::emit_progress_i18n(
661 &format!(
662 "Embedding {} chunks in parallel batches (parallelism {})...",
663 chunks_info.len(),
664 args.llm_parallelism
665 ),
666 &format!(
667 "Embedding {} chunks em lotes paralelos (paralelismo {})...",
668 chunks_info.len(),
669 args.llm_parallelism
670 ),
671 );
672 if let Some(rss) = crate::memory_guard::current_process_memory_mb() {
673 if rss > args.max_rss_mb {
674 tracing::error!(target: "remember",
675 rss_mb = rss,
676 max_rss_mb = args.max_rss_mb,
677 "RSS exceeded --max-rss-mb threshold; aborting to prevent system instability"
678 );
679 return Err(AppError::LowMemory {
680 available_mb: crate::memory_guard::available_memory_mb(),
681 required_mb: args.max_rss_mb,
682 });
683 }
684 }
685 let chunk_embeddings = crate::embedder::embed_passages_parallel_local(
686 &paths.models,
687 &chunk_texts,
688 args.llm_parallelism as usize,
689 crate::embedder::chunk_embed_batch_size(),
690 )?;
691 output::emit_progress_i18n(
692 &format!(
693 "Remember stage: chunk embeddings complete; process RSS {} MB",
694 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
695 ),
696 &format!(
697 "Stage remember: chunk embeddings completed; process RSS {} MB",
698 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
699 ),
700 );
701 let aggregated = chunking::aggregate_embeddings(&chunk_embeddings);
702 chunk_embeddings_cache = Some(chunk_embeddings);
703 (aggregated, None)
709 };
710 let body_for_storage = raw_body;
711
712 let memory_type = resolved_type.as_str();
713 let new_memory = NewMemory {
714 namespace: namespace.clone(),
715 name: normalized_name.clone(),
716 memory_type: memory_type.to_string(),
717 description: resolved_description.clone(),
718 body: body_for_storage,
719 body_hash: body_hash.clone(),
720 session_id: args.session_id.clone(),
721 source: "agent".to_string(),
722 metadata,
723 };
724
725 let mut warnings = Vec::with_capacity(4);
726 let mut entities_persisted = 0usize;
727 let mut relationships_persisted = 0usize;
728
729 let entity_texts: Vec<String> = graph
734 .entities
735 .iter()
736 .map(|entity| match &entity.description {
737 Some(desc) => format!("{} {}", entity.name, desc),
738 None => entity.name.clone(),
739 })
740 .collect();
741 let (graph_entity_embeddings, embed_cache_stats) = crate::embedder::embed_entity_texts_cached(
749 &paths.models,
750 &entity_texts,
751 args.llm_parallelism as usize,
752 )?;
753 if embed_cache_stats.hits > 0 {
754 tracing::debug!(
755 hits = embed_cache_stats.hits,
756 misses = embed_cache_stats.misses,
757 requested = embed_cache_stats.requested,
758 "G56: entity embed cache hit (remember)"
759 );
760 }
761
762 let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
763
764 let mut skip_reindex = false;
765 let (memory_id, action, version) = match existing_memory {
766 Some((existing_id, _updated_at, _current_version)) => {
767 if let Some(hash_id) = duplicate_hash_id {
768 if hash_id != existing_id {
769 warnings.push(format!(
770 "identical body already exists as memory id {hash_id}"
771 ));
772 }
773 }
774
775 let (old_fts_name, old_fts_desc, old_fts_body): (String, String, String) = tx
777 .query_row(
778 "SELECT name, description, body FROM memories WHERE id = ?1",
779 rusqlite::params![existing_id],
780 |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
781 )?;
782
783 let existing_body_hash: Option<String> = tx
785 .query_row(
786 "SELECT body_hash FROM memories WHERE id = ?1",
787 rusqlite::params![existing_id],
788 |r| r.get(0),
789 )
790 .ok();
791 let body_unchanged = existing_body_hash.as_deref() == Some(&body_hash);
792 skip_reindex = body_unchanged;
793 if !body_unchanged {
794 storage_chunks::delete_chunks(&tx, existing_id)?;
795 }
796
797 let next_v = versions::next_version(&tx, existing_id)?;
798 memories::update(&tx, existing_id, &new_memory, args.expected_updated_at)?;
799
800 memories::sync_fts_after_update(
803 &tx,
804 existing_id,
805 &old_fts_name,
806 &old_fts_desc,
807 &old_fts_body,
808 &normalized_name,
809 &resolved_description,
810 &new_memory.body,
811 )?;
812
813 versions::insert_version(
814 &tx,
815 existing_id,
816 next_v,
817 &normalized_name,
818 memory_type,
819 &resolved_description,
820 &new_memory.body,
821 &serde_json::to_string(&new_memory.metadata)?,
822 None,
823 "edit",
824 )?;
825 if !body_unchanged {
826 memories::upsert_vec(
827 &tx,
828 existing_id,
829 &namespace,
830 memory_type,
831 &embedding,
832 &normalized_name,
833 &snippet,
834 )?;
835 }
836 (existing_id, "updated".to_string(), next_v)
837 }
838 None => {
839 if let Some(hash_id) = duplicate_hash_id {
840 warnings.push(format!(
841 "identical body already exists as memory id {hash_id}"
842 ));
843 }
844 let id = memories::insert(&tx, &new_memory)?;
845 versions::insert_version(
846 &tx,
847 id,
848 1,
849 &normalized_name,
850 memory_type,
851 &resolved_description,
852 &new_memory.body,
853 &serde_json::to_string(&new_memory.metadata)?,
854 None,
855 "create",
856 )?;
857 memories::upsert_vec(
858 &tx,
859 id,
860 &namespace,
861 memory_type,
862 &embedding,
863 &normalized_name,
864 &snippet,
865 )?;
866 (id, "created".to_string(), 1)
867 }
868 };
869
870 if chunks_info.len() > 1 && !skip_reindex {
871 storage_chunks::insert_chunk_slices(&tx, memory_id, &new_memory.body, &chunks_info)?;
872
873 let chunk_embeddings = chunk_embeddings_cache.take().ok_or_else(|| {
874 AppError::Internal(anyhow::anyhow!(
875 "chunk embeddings cache missing in multi-chunk remember path"
876 ))
877 })?;
878
879 for (i, emb) in chunk_embeddings.iter().enumerate() {
880 storage_chunks::upsert_chunk_vec(&tx, i as i64, memory_id, i as i32, emb)?;
881 }
882 output::emit_progress_i18n(
883 &format!(
884 "Remember stage: persisted chunk vectors; process RSS {} MB",
885 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
886 ),
887 &format!(
888 "Etapa remember: vetores de chunks persistidos; RSS do processo {} MB",
889 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
890 ),
891 );
892 }
893
894 if !graph.entities.is_empty() || !graph.relationships.is_empty() {
895 for entity in &graph.entities {
896 let entity_id = entities::upsert_entity(&tx, &namespace, entity)?;
897 let entity_embedding = &graph_entity_embeddings[entities_persisted];
898 entities::upsert_entity_vec(
899 &tx,
900 entity_id,
901 &namespace,
902 entity.entity_type,
903 entity_embedding,
904 &entity.name,
905 )?;
906 entities::link_memory_entity(&tx, memory_id, entity_id)?;
907 entities::increment_degree(&tx, entity_id)?;
908 if args.max_entity_degree > 0 {
910 let cap = args.max_entity_degree as i64;
911 let degree: i64 = tx.query_row(
912 "SELECT degree FROM entities WHERE id = ?1",
913 rusqlite::params![entity_id],
914 |r| r.get(0),
915 )?;
916 if degree > cap {
917 tracing::warn!(target: "remember",
918 entity = %entity.name,
919 degree = degree,
920 cap = cap,
921 "entity degree cap exceeded"
922 );
923 }
924 }
925 entities_persisted += 1;
926 }
927 let entity_types: std::collections::HashMap<&str, EntityType> = graph
928 .entities
929 .iter()
930 .map(|entity| (entity.name.as_str(), entity.entity_type))
931 .collect();
932
933 for rel in &graph.relationships {
934 let source_entity = NewEntity {
935 name: rel.source.clone(),
936 entity_type: entity_types
937 .get(rel.source.as_str())
938 .copied()
939 .unwrap_or(EntityType::Concept),
940 description: None,
941 };
942 let target_entity = NewEntity {
943 name: rel.target.clone(),
944 entity_type: entity_types
945 .get(rel.target.as_str())
946 .copied()
947 .unwrap_or(EntityType::Concept),
948 description: None,
949 };
950 let source_id = entities::upsert_entity(&tx, &namespace, &source_entity)?;
951 let target_id = entities::upsert_entity(&tx, &namespace, &target_entity)?;
952 let rel_id = entities::upsert_relationship(&tx, &namespace, source_id, target_id, rel)?;
953 entities::link_memory_relationship(&tx, memory_id, rel_id)?;
954 relationships_persisted += 1;
955 }
956 }
957 tx.commit()?;
958
959 let urls_persisted = if !extracted_urls.is_empty() {
962 let url_entries: Vec<storage_urls::MemoryUrl> = extracted_urls
963 .into_iter()
964 .map(|u| storage_urls::MemoryUrl {
965 url: u.url,
966 offset: Some(u.start as i64),
967 })
968 .collect();
969 storage_urls::insert_urls(&conn, memory_id, &url_entries)
970 } else {
971 0
972 };
973
974 conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
975
976 let created_at_epoch = chrono::Utc::now().timestamp();
977 let created_at_iso = crate::tz::format_iso(chrono::Utc::now());
978
979 output::emit_json(&RememberResponse {
980 memory_id,
981 name: normalized_name.clone(),
985 namespace,
986 action: action.clone(),
987 operation: action,
988 version,
989 entities_persisted,
990 relationships_persisted,
991 relationships_truncated,
992 chunks_created,
993 chunks_persisted,
994 urls_persisted,
995 extraction_method,
996 merged_into_memory_id: None,
997 warnings,
998 created_at: created_at_epoch,
999 created_at_iso,
1000 elapsed_ms: inicio.elapsed().as_millis() as u64,
1001 name_was_normalized,
1002 original_name: name_was_normalized.then_some(original_name),
1003 backend_invoked: backend_invoked_passage,
1004 })?;
1005
1006 Ok(())
1007}
1008
1009#[cfg(test)]
1010mod tests {
1011 use super::compute_chunks_persisted;
1012 use crate::output::RememberResponse;
1013
1014 #[test]
1016 fn chunks_persisted_zero_for_zero_chunks() {
1017 assert_eq!(compute_chunks_persisted(0), 0);
1018 }
1019
1020 #[test]
1021 fn chunks_persisted_zero_for_single_chunk_body() {
1022 assert_eq!(compute_chunks_persisted(1), 0);
1025 }
1026
1027 #[test]
1028 fn chunks_persisted_equals_count_for_multi_chunk_body() {
1029 assert_eq!(compute_chunks_persisted(2), 2);
1031 assert_eq!(compute_chunks_persisted(7), 7);
1032 assert_eq!(compute_chunks_persisted(64), 64);
1033 }
1034
1035 #[test]
1036 fn remember_response_serializes_required_fields() {
1037 let resp = RememberResponse {
1038 memory_id: 42,
1039 name: "minha-mem".to_string(),
1040 namespace: "global".to_string(),
1041 action: "created".to_string(),
1042 operation: "created".to_string(),
1043 version: 1,
1044 entities_persisted: 0,
1045 relationships_persisted: 0,
1046 relationships_truncated: false,
1047 chunks_created: 1,
1048 chunks_persisted: 0,
1049 urls_persisted: 0,
1050 extraction_method: None,
1051 merged_into_memory_id: None,
1052 warnings: vec![],
1053 created_at: 1_705_320_000,
1054 created_at_iso: "2024-01-15T12:00:00Z".to_string(),
1055 elapsed_ms: 55,
1056 name_was_normalized: false,
1057 original_name: None,
1058 backend_invoked: None,
1059 };
1060
1061 let json = serde_json::to_value(&resp).expect("serialization failed");
1062 assert_eq!(json["memory_id"], 42);
1063 assert_eq!(json["action"], "created");
1064 assert_eq!(json["operation"], "created");
1065 assert_eq!(json["version"], 1);
1066 assert_eq!(json["elapsed_ms"], 55u64);
1067 assert!(json["warnings"].is_array());
1068 assert!(json["merged_into_memory_id"].is_null());
1069 }
1070
1071 #[test]
1072 fn remember_response_action_e_operation_sao_aliases() {
1073 let resp = RememberResponse {
1074 memory_id: 1,
1075 name: "mem".to_string(),
1076 namespace: "global".to_string(),
1077 action: "updated".to_string(),
1078 operation: "updated".to_string(),
1079 version: 2,
1080 entities_persisted: 3,
1081 relationships_persisted: 1,
1082 relationships_truncated: false,
1083 extraction_method: None,
1084 chunks_created: 2,
1085 chunks_persisted: 2,
1086 urls_persisted: 0,
1087 merged_into_memory_id: None,
1088 warnings: vec![],
1089 created_at: 0,
1090 created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1091 elapsed_ms: 0,
1092 name_was_normalized: false,
1093 original_name: None,
1094 backend_invoked: None,
1095 };
1096
1097 let json = serde_json::to_value(&resp).expect("serialization failed");
1098 assert_eq!(
1099 json["action"], json["operation"],
1100 "action e operation devem ser iguais"
1101 );
1102 assert_eq!(json["entities_persisted"], 3);
1103 assert_eq!(json["relationships_persisted"], 1);
1104 assert_eq!(json["chunks_created"], 2);
1105 }
1106
1107 #[test]
1108 fn remember_response_warnings_lista_mensagens() {
1109 let resp = RememberResponse {
1110 memory_id: 5,
1111 name: "dup-mem".to_string(),
1112 namespace: "global".to_string(),
1113 action: "created".to_string(),
1114 operation: "created".to_string(),
1115 version: 1,
1116 entities_persisted: 0,
1117 extraction_method: None,
1118 relationships_persisted: 0,
1119 relationships_truncated: false,
1120 chunks_created: 1,
1121 chunks_persisted: 0,
1122 urls_persisted: 0,
1123 merged_into_memory_id: None,
1124 warnings: vec!["identical body already exists as memory id 3".to_string()],
1125 created_at: 0,
1126 created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1127 elapsed_ms: 10,
1128 name_was_normalized: false,
1129 original_name: None,
1130 backend_invoked: None,
1131 };
1132
1133 let json = serde_json::to_value(&resp).expect("serialization failed");
1134 let warnings = json["warnings"]
1135 .as_array()
1136 .expect("warnings deve ser array");
1137 assert_eq!(warnings.len(), 1);
1138 assert!(warnings[0].as_str().unwrap().contains("identical body"));
1139 }
1140
1141 #[test]
1142 fn invalid_name_reserved_prefix_returns_validation_error() {
1143 use crate::errors::AppError;
1144 let nome = "__reservado";
1146 let resultado: Result<(), AppError> = if nome.starts_with("__") {
1147 Err(AppError::Validation(
1148 crate::i18n::validation::reserved_name(),
1149 ))
1150 } else {
1151 Ok(())
1152 };
1153 assert!(resultado.is_err());
1154 if let Err(AppError::Validation(msg)) = resultado {
1155 assert!(!msg.is_empty());
1156 }
1157 }
1158
1159 #[test]
1160 fn name_too_long_returns_validation_error() {
1161 use crate::errors::AppError;
1162 let nome_longo = "a".repeat(crate::constants::MAX_MEMORY_NAME_LEN + 1);
1163 let resultado: Result<(), AppError> =
1164 if nome_longo.is_empty() || nome_longo.len() > crate::constants::MAX_MEMORY_NAME_LEN {
1165 Err(AppError::Validation(crate::i18n::validation::name_length(
1166 crate::constants::MAX_MEMORY_NAME_LEN,
1167 )))
1168 } else {
1169 Ok(())
1170 };
1171 assert!(resultado.is_err());
1172 }
1173
1174 #[test]
1175 fn remember_response_merged_into_memory_id_some_serializes_integer() {
1176 let resp = RememberResponse {
1177 memory_id: 10,
1178 name: "mem-mergeada".to_string(),
1179 namespace: "global".to_string(),
1180 action: "updated".to_string(),
1181 operation: "updated".to_string(),
1182 version: 3,
1183 extraction_method: None,
1184 entities_persisted: 0,
1185 relationships_persisted: 0,
1186 relationships_truncated: false,
1187 chunks_created: 1,
1188 chunks_persisted: 0,
1189 urls_persisted: 0,
1190 merged_into_memory_id: Some(7),
1191 warnings: vec![],
1192 created_at: 0,
1193 created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1194 elapsed_ms: 0,
1195 name_was_normalized: false,
1196 original_name: None,
1197 backend_invoked: None,
1198 };
1199
1200 let json = serde_json::to_value(&resp).expect("serialization failed");
1201 assert_eq!(json["merged_into_memory_id"], 7);
1202 }
1203
1204 #[test]
1205 fn remember_response_urls_persisted_serializes_field() {
1206 let resp = RememberResponse {
1208 memory_id: 3,
1209 name: "mem-com-urls".to_string(),
1210 namespace: "global".to_string(),
1211 action: "created".to_string(),
1212 operation: "created".to_string(),
1213 version: 1,
1214 entities_persisted: 0,
1215 relationships_persisted: 0,
1216 relationships_truncated: false,
1217 chunks_created: 1,
1218 chunks_persisted: 0,
1219 urls_persisted: 3,
1220 extraction_method: Some("regex-only".to_string()),
1221 merged_into_memory_id: None,
1222 warnings: vec![],
1223 created_at: 0,
1224 created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1225 elapsed_ms: 0,
1226 name_was_normalized: false,
1227 original_name: None,
1228 backend_invoked: None,
1229 };
1230 let json = serde_json::to_value(&resp).expect("serialization failed");
1231 assert_eq!(json["urls_persisted"], 3);
1232 }
1233
1234 #[test]
1235 fn empty_name_after_normalization_returns_specific_message() {
1236 use crate::errors::AppError;
1239 let normalized = "---".to_lowercase().replace(['_', ' '], "-");
1240 let normalized = normalized.trim_matches('-').to_string();
1241 let resultado: Result<(), AppError> = if normalized.is_empty() {
1242 Err(AppError::Validation(
1243 "name cannot be empty after normalization (input was blank or contained only hyphens/underscores/spaces)".to_string(),
1244 ))
1245 } else {
1246 Ok(())
1247 };
1248 assert!(resultado.is_err());
1249 if let Err(AppError::Validation(msg)) = resultado {
1250 assert!(
1251 msg.contains("empty after normalization"),
1252 "mensagem deve mencionar 'empty after normalization', obteve: {msg}"
1253 );
1254 }
1255 }
1256
1257 #[test]
1258 fn name_only_underscores_after_normalization_returns_specific_message() {
1259 use crate::errors::AppError;
1261 let normalized = "___".to_lowercase().replace(['_', ' '], "-");
1262 let normalized = normalized.trim_matches('-').to_string();
1263 assert!(
1264 normalized.is_empty(),
1265 "underscores devem normalizar para string vazia"
1266 );
1267 let resultado: Result<(), AppError> = if normalized.is_empty() {
1268 Err(AppError::Validation(
1269 "name cannot be empty after normalization (input was blank or contained only hyphens/underscores/spaces)".to_string(),
1270 ))
1271 } else {
1272 Ok(())
1273 };
1274 assert!(resultado.is_err());
1275 if let Err(AppError::Validation(msg)) = resultado {
1276 assert!(
1277 msg.contains("empty after normalization"),
1278 "mensagem deve mencionar 'empty after normalization', obteve: {msg}"
1279 );
1280 }
1281 }
1282
1283 #[test]
1284 fn remember_response_relationships_truncated_serializes_field() {
1285 let resp_false = RememberResponse {
1287 memory_id: 1,
1288 name: "test".to_string(),
1289 namespace: "global".to_string(),
1290 action: "created".to_string(),
1291 operation: "created".to_string(),
1292 version: 1,
1293 entities_persisted: 2,
1294 relationships_persisted: 1,
1295 relationships_truncated: false,
1296 chunks_created: 1,
1297 chunks_persisted: 0,
1298 urls_persisted: 0,
1299 extraction_method: None,
1300 merged_into_memory_id: None,
1301 warnings: vec![],
1302 created_at: 0,
1303 created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1304 elapsed_ms: 0,
1305 name_was_normalized: false,
1306 original_name: None,
1307 backend_invoked: None,
1308 };
1309 let json_false = serde_json::to_value(&resp_false).expect("serialization failed");
1310 assert_eq!(json_false["relationships_truncated"], false);
1311
1312 let resp_true = RememberResponse {
1313 relationships_truncated: true,
1314 ..resp_false
1315 };
1316 let json_true = serde_json::to_value(&resp_true).expect("serialization failed");
1317 assert_eq!(json_true["relationships_truncated"], true);
1318 }
1319
1320 fn should_preserve_body(force_merge: bool, raw_body_is_empty: bool, clear_body: bool) -> bool {
1329 force_merge && raw_body_is_empty && !clear_body
1330 }
1331
1332 #[test]
1333 fn gap08_empty_body_force_merge_no_clear_body_preserves() {
1334 assert!(
1337 should_preserve_body(true, true, false),
1338 "empty body + force-merge + no clear-body should trigger preservation"
1339 );
1340 }
1341
1342 #[test]
1343 fn gap08_empty_body_force_merge_with_clear_body_does_not_preserve() {
1344 assert!(
1346 !should_preserve_body(true, true, true),
1347 "--clear-body must bypass preservation"
1348 );
1349 }
1350
1351 #[test]
1352 fn gap08_non_empty_body_force_merge_does_not_preserve() {
1353 assert!(
1355 !should_preserve_body(true, false, false),
1356 "non-empty body must overwrite, not preserve"
1357 );
1358 }
1359
1360 #[test]
1361 fn gap08_empty_body_no_force_merge_does_not_preserve() {
1362 assert!(
1364 !should_preserve_body(false, true, false),
1365 "no --force-merge means no preservation logic applies"
1366 );
1367 }
1368}