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 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\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 GLiNER NER entity/relationship extraction from body"
147 )]
148 pub enable_ner: bool,
149 #[arg(
150 long,
151 env = "SQLITE_GRAPHRAG_GLINER_VARIANT",
152 default_value = "fp32",
153 help = "GLiNER model variant: fp32 (1.1GB, best quality), fp16 (580MB), int8 (349MB, fastest but may miss entities on short texts), q4, q4f16"
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}
192
193#[derive(Deserialize, Default)]
194#[serde(deny_unknown_fields)]
195struct GraphInput {
196 #[serde(default)]
197 body: Option<String>,
198 #[serde(default)]
199 entities: Vec<NewEntity>,
200 #[serde(default)]
201 relationships: Vec<NewRelationship>,
202}
203
204fn normalize_and_validate_graph_input(graph: &mut GraphInput) -> Result<(), AppError> {
205 for rel in &mut graph.relationships {
206 rel.relation = crate::parsers::normalize_relation(&rel.relation);
207 if let Err(e) = crate::parsers::validate_relation_format(&rel.relation) {
208 return Err(AppError::Validation(format!(
209 "{e} for relationship '{}' -> '{}'",
210 rel.source, rel.target
211 )));
212 }
213 crate::parsers::warn_if_non_canonical(&rel.relation);
214 if !(0.0..=1.0).contains(&rel.strength) {
215 return Err(AppError::Validation(format!(
216 "invalid strength {} for relationship '{}' -> '{}'; expected value in [0.0, 1.0]",
217 rel.strength, rel.source, rel.target
218 )));
219 }
220 }
221
222 Ok(())
223}
224
225#[tracing::instrument(skip_all, level = "debug", name = "remember")]
226pub fn run(args: RememberArgs) -> Result<(), AppError> {
227 use crate::constants::*;
228
229 let inicio = std::time::Instant::now();
230 let _ = args.format;
231 tracing::debug!(target: "remember", name = %args.name, "persisting memory");
232 let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
233
234 let original_name = args.name.clone();
238
239 let normalized_name = {
243 let lower = args.name.to_lowercase().replace(['_', ' '], "-");
244 let trimmed = lower.trim_matches('-').to_string();
245 if trimmed != args.name {
246 tracing::warn!(target: "remember",
247 original = %args.name,
248 normalized = %trimmed,
249 "name auto-normalized to kebab-case"
250 );
251 }
252 trimmed
253 };
254 let name_was_normalized = normalized_name != original_name;
255
256 if normalized_name.is_empty() {
257 return Err(AppError::Validation(
258 "name cannot be empty after normalization (input was blank or contained only hyphens/underscores/spaces)".to_string(),
259 ));
260 }
261 if normalized_name.len() > MAX_MEMORY_NAME_LEN {
262 return Err(AppError::LimitExceeded(
263 crate::i18n::validation::name_length(MAX_MEMORY_NAME_LEN),
264 ));
265 }
266
267 if normalized_name.starts_with("__") {
268 return Err(AppError::Validation(
269 crate::i18n::validation::reserved_name(),
270 ));
271 }
272
273 {
274 let slug_re = crate::constants::name_slug_regex();
275 if !slug_re.is_match(&normalized_name) {
276 return Err(AppError::Validation(crate::i18n::validation::name_kebab(
277 &normalized_name,
278 )));
279 }
280 }
281
282 if let Some(ref desc) = args.description {
283 if desc.len() > MAX_MEMORY_DESCRIPTION_LEN {
284 return Err(AppError::Validation(
285 crate::i18n::validation::description_exceeds(MAX_MEMORY_DESCRIPTION_LEN),
286 ));
287 }
288 }
289
290 let mut raw_body = if let Some(b) = args.body {
291 b
292 } else if let Some(ref path) = args.body_file {
293 let file_size = std::fs::metadata(path).map_err(AppError::Io)?.len();
294 if file_size > MAX_MEMORY_BODY_LEN as u64 {
295 return Err(AppError::LimitExceeded(
296 crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
297 ));
298 }
299 match std::fs::read_to_string(path) {
300 Ok(s) => s,
301 Err(e) if e.kind() == std::io::ErrorKind::InvalidData => {
302 let bytes = std::fs::read(path).map_err(AppError::Io)?;
303 tracing::warn!(target: "remember", "body file contains invalid UTF-8; replacing invalid sequences");
304 String::from_utf8_lossy(&bytes).into_owned()
305 }
306 Err(e) => return Err(AppError::Io(e)),
307 }
308 } else if args.body_stdin || args.graph_stdin {
309 crate::stdin_helper::read_stdin_with_timeout(60)?
310 } else {
311 String::new()
312 };
313
314 let mut entities_provided_externally =
315 args.entities_file.is_some() || args.relationships_file.is_some();
316
317 let mut graph = GraphInput::default();
318 if let Some(path) = args.entities_file {
319 let file_size = std::fs::metadata(&path).map_err(AppError::Io)?.len();
320 if file_size > MAX_MEMORY_BODY_LEN as u64 {
321 return Err(AppError::LimitExceeded(
322 crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
323 ));
324 }
325 let content = std::fs::read_to_string(&path).map_err(AppError::Io)?;
326 graph.entities = serde_json::from_str(&content)?;
327 }
328 if let Some(path) = args.relationships_file {
329 let file_size = std::fs::metadata(&path).map_err(AppError::Io)?.len();
330 if file_size > MAX_MEMORY_BODY_LEN as u64 {
331 return Err(AppError::LimitExceeded(
332 crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
333 ));
334 }
335 let content = std::fs::read_to_string(&path).map_err(AppError::Io)?;
336 graph.relationships = serde_json::from_str(&content)?;
337 }
338 if args.graph_stdin {
339 graph = serde_json::from_str::<GraphInput>(&raw_body).map_err(|e| {
340 AppError::Validation(format!("invalid JSON payload on --graph-stdin: {e}"))
341 })?;
342 raw_body = graph.body.take().unwrap_or_default();
343 }
344 if args.graph_stdin && !graph.entities.is_empty() {
345 entities_provided_externally = true;
346 }
347
348 if graph.entities.len() > max_entities_per_memory() {
349 return Err(AppError::LimitExceeded(errors_msg::entity_limit_exceeded(
350 max_entities_per_memory(),
351 )));
352 }
353 let mut relationships_truncated = false;
354 let rel_cap = max_relationships_per_memory();
355 if graph.relationships.len() > rel_cap {
356 tracing::warn!(target: "remember",
357 count = graph.relationships.len(),
358 cap = rel_cap,
359 "truncating relationships to cap"
360 );
361 graph.relationships.truncate(rel_cap);
362 relationships_truncated = true;
363 }
364 normalize_and_validate_graph_input(&mut graph)?;
365
366 if raw_body.len() > MAX_MEMORY_BODY_LEN {
367 return Err(AppError::LimitExceeded(
368 crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
369 ));
370 }
371
372 let body_will_be_preserved = args.force_merge && raw_body.trim().is_empty() && !args.clear_body;
377 if !entities_provided_externally
378 && graph.entities.is_empty()
379 && raw_body.trim().is_empty()
380 && !body_will_be_preserved
381 && !args.clear_body
382 {
383 return Err(AppError::Validation(crate::i18n::validation::empty_body()));
384 }
385
386 let metadata: serde_json::Value = if let Some(m) = args.metadata {
387 serde_json::from_str(&m)?
388 } else if let Some(path) = args.metadata_file {
389 let file_size = std::fs::metadata(&path).map_err(AppError::Io)?.len();
390 if file_size > MAX_MEMORY_BODY_LEN as u64 {
391 return Err(AppError::LimitExceeded(
392 crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
393 ));
394 }
395 let content = std::fs::read_to_string(&path).map_err(AppError::Io)?;
396 serde_json::from_str(&content)?
397 } else {
398 serde_json::json!({})
399 };
400
401 let mut body_hash = blake3::hash(raw_body.as_bytes()).to_hex().to_string();
402 let mut snippet: String = raw_body.chars().take(200).collect();
403
404 let paths = AppPaths::resolve(args.db.as_deref())?;
405 paths.ensure_dirs()?;
406
407 let mut extraction_method: Option<String> = None;
409 let mut extracted_urls: Vec<crate::extraction::ExtractedUrl> = Vec::with_capacity(4);
410 if args.enable_ner && args.skip_extraction {
411 return Err(AppError::Validation(
412 "--enable-ner and --skip-extraction are mutually exclusive; remove one".to_string(),
413 ));
414 }
415 if args.skip_extraction && !args.enable_ner {
416 return Err(AppError::Validation(
417 "--skip-extraction is deprecated since v1.0.45 and has no effect; remove this flag"
418 .to_string(),
419 ));
420 }
421 let gliner_variant: crate::extraction::GlinerVariant =
422 args.gliner_variant.parse().unwrap_or_else(|e| {
423 tracing::warn!(target: "remember", error = %e, "invalid --gliner-variant, defaulting to fp32");
424 crate::extraction::GlinerVariant::Fp32
425 });
426 if args.enable_ner && graph.entities.is_empty() && !raw_body.trim().is_empty() {
427 match crate::extraction::extract_graph_auto(&raw_body, &paths, gliner_variant) {
428 Ok(extracted) => {
429 extraction_method = Some(extracted.extraction_method.clone());
430 extracted_urls = extracted.urls;
431 graph.entities = extracted.entities;
432 graph.relationships = extracted.relationships;
433 relationships_truncated = extracted.relationships_truncated;
434
435 if graph.entities.len() > max_entities_per_memory() {
436 graph.entities.truncate(max_entities_per_memory());
437 }
438 if graph.relationships.len() > max_relationships_per_memory() {
439 relationships_truncated = true;
440 graph.relationships.truncate(max_relationships_per_memory());
441 }
442 normalize_and_validate_graph_input(&mut graph)?;
443 }
444 Err(e) => {
445 tracing::warn!(target: "remember", error = %e, "auto-extraction failed, graceful degradation");
446 extraction_method = Some("none:extraction-failed".to_string());
447 }
448 }
449 }
450
451 let mut conn = open_rw(&paths.db)?;
452 ensure_schema(&mut conn)?;
453
454 if args.dry_run {
456 let existing = memories::find_by_name(&conn, &namespace, &normalized_name)?;
457 let planned_action = if existing.is_some() && args.force_merge {
458 "would_update"
459 } else {
460 "would_create"
461 };
462 output::emit_json(&serde_json::json!({
463 "dry_run": true,
464 "name": normalized_name,
465 "namespace": namespace,
466 "planned_action": planned_action,
467 }))?;
468 return Ok(());
469 }
470
471 {
472 use crate::constants::MAX_NAMESPACES_ACTIVE;
473 let active_count: u32 = conn.query_row(
474 "SELECT COUNT(DISTINCT namespace) FROM memories WHERE deleted_at IS NULL",
475 [],
476 |r| r.get::<_, i64>(0).map(|v| v as u32),
477 )?;
478 let ns_exists: bool = conn.query_row(
479 "SELECT EXISTS(SELECT 1 FROM memories WHERE namespace = ?1 AND deleted_at IS NULL)",
480 rusqlite::params![namespace],
481 |r| r.get::<_, i64>(0).map(|v| v > 0),
482 )?;
483 if !ns_exists && active_count >= MAX_NAMESPACES_ACTIVE {
484 return Err(AppError::NamespaceError(format!(
485 "active namespace limit of {MAX_NAMESPACES_ACTIVE} reached while trying to create '{namespace}'"
486 )));
487 }
488 }
489
490 if let Some((sd_id, true)) =
492 memories::find_by_name_any_state(&conn, &namespace, &normalized_name)?
493 {
494 if args.force_merge {
495 memories::clear_deleted_at(&conn, sd_id)?;
496 } else {
497 return Err(AppError::Duplicate(
498 errors_msg::duplicate_memory_soft_deleted(&normalized_name, &namespace),
499 ));
500 }
501 }
502
503 let existing_memory = memories::find_by_name(&conn, &namespace, &normalized_name)?;
504 if existing_memory.is_some() && !args.force_merge {
505 return Err(AppError::Duplicate(errors_msg::duplicate_memory(
506 &normalized_name,
507 &namespace,
508 )));
509 }
510
511 let (resolved_type, resolved_description) = if existing_memory.is_none() {
515 let t = args.r#type.ok_or_else(|| {
517 AppError::Validation(
518 "--type and --description are required when creating a new memory".to_string(),
519 )
520 })?;
521 let d = args.description.clone().ok_or_else(|| {
522 AppError::Validation(
523 "--type and --description are required when creating a new memory".to_string(),
524 )
525 })?;
526 (t.as_str().to_string(), d)
527 } else {
528 let existing_row = memories::read_by_name(&conn, &namespace, &normalized_name)?
530 .ok_or_else(|| {
531 AppError::NotFound(format!(
532 "memory '{normalized_name}' not found in namespace '{namespace}'"
533 ))
534 })?;
535 let t = args
536 .r#type
537 .map(|v| v.as_str().to_string())
538 .unwrap_or_else(|| existing_row.memory_type.clone());
539 let d = args
540 .description
541 .clone()
542 .unwrap_or_else(|| existing_row.description.clone());
543 (t, d)
544 };
545
546 if body_will_be_preserved {
551 if let Some(existing_row) = memories::read_by_name(&conn, &namespace, &normalized_name)? {
552 if !existing_row.body.is_empty() {
553 tracing::debug!(target: "remember",
554 name = %normalized_name,
555 "GAP-08: empty body with --force-merge and no --clear-body; preserving existing body"
556 );
557 raw_body = existing_row.body;
558 body_hash = blake3::hash(raw_body.as_bytes()).to_hex().to_string();
559 snippet = raw_body.chars().take(200).collect();
560 }
561 }
562 }
563
564 let duplicate_hash_id = memories::find_by_hash(&conn, &namespace, &body_hash)?;
565
566 output::emit_progress_i18n(
567 &format!(
568 "Remember stage: validated input; available memory {} MB",
569 crate::memory_guard::available_memory_mb()
570 ),
571 &format!(
572 "Stage remember: input validated; available memory {} MB",
573 crate::memory_guard::available_memory_mb()
574 ),
575 );
576
577 let tokenizer = crate::tokenizer::get_tokenizer(&paths.models)?;
578 let model_max_length = crate::tokenizer::get_model_max_length(&paths.models)?;
579 let total_passage_tokens = crate::tokenizer::count_passage_tokens(tokenizer, &raw_body)?;
580 let chunks_info = chunking::split_into_chunks_hierarchical(&raw_body, tokenizer);
581 let chunks_created = chunks_info.len();
582 let chunks_persisted = compute_chunks_persisted(chunks_info.len());
586
587 output::emit_progress_i18n(
588 &format!(
589 "Remember stage: tokenizer counted {total_passage_tokens} passage tokens (model max {model_max_length}); chunking produced {} chunks; process RSS {} MB",
590 chunks_created,
591 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
592 ),
593 &format!(
594 "Stage remember: tokenizer counted {total_passage_tokens} passage tokens (model max {model_max_length}); chunking produced {} chunks; process RSS {} MB",
595 chunks_created,
596 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
597 ),
598 );
599
600 if chunks_created > crate::constants::REMEMBER_MAX_SAFE_MULTI_CHUNKS {
601 return Err(AppError::LimitExceeded(format!(
602 "document produces {chunks_created} chunks; current safe operational limit is {} chunks; split the document before using remember",
603 crate::constants::REMEMBER_MAX_SAFE_MULTI_CHUNKS
604 )));
605 }
606
607 output::emit_progress_i18n("Computing embedding...", "Calculando embedding...");
608 let mut chunk_embeddings_cache: Option<Vec<Vec<f32>>> = None;
609
610 let embedding = if chunks_info.len() == 1 {
611 crate::daemon::embed_passage_or_local(&paths.models, &raw_body)?
612 } else {
613 let chunk_texts: Vec<&str> = chunks_info
614 .iter()
615 .map(|c| chunking::chunk_text(&raw_body, c))
616 .collect();
617 output::emit_progress_i18n(
618 &format!(
619 "Embedding {} chunks serially to keep memory bounded...",
620 chunks_info.len()
621 ),
622 &format!(
623 "Embedding {} chunks serially to keep memory bounded...",
624 chunks_info.len()
625 ),
626 );
627 let embed_cap = chunk_texts.len();
628 let mut chunk_embeddings = Vec::new();
629 chunk_embeddings.try_reserve(embed_cap).map_err(|_| {
630 AppError::LimitExceeded(format!(
631 "allocation of {embed_cap} chunk embeddings would exceed available memory"
632 ))
633 })?;
634 for chunk_text in &chunk_texts {
635 if let Some(rss) = crate::memory_guard::current_process_memory_mb() {
636 if rss > args.max_rss_mb {
637 tracing::error!(target: "remember",
638 rss_mb = rss,
639 max_rss_mb = args.max_rss_mb,
640 "RSS exceeded --max-rss-mb threshold; aborting to prevent system instability"
641 );
642 return Err(AppError::LowMemory {
643 available_mb: crate::memory_guard::available_memory_mb(),
644 required_mb: args.max_rss_mb,
645 });
646 }
647 }
648 chunk_embeddings.push(crate::daemon::embed_passage_or_local(
649 &paths.models,
650 chunk_text,
651 )?);
652 }
653 output::emit_progress_i18n(
654 &format!(
655 "Remember stage: chunk embeddings complete; process RSS {} MB",
656 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
657 ),
658 &format!(
659 "Stage remember: chunk embeddings completed; process RSS {} MB",
660 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
661 ),
662 );
663 let aggregated = chunking::aggregate_embeddings(&chunk_embeddings);
664 chunk_embeddings_cache = Some(chunk_embeddings);
665 aggregated
666 };
667 let body_for_storage = raw_body;
668
669 let memory_type = resolved_type.as_str();
670 let new_memory = NewMemory {
671 namespace: namespace.clone(),
672 name: normalized_name.clone(),
673 memory_type: memory_type.to_string(),
674 description: resolved_description.clone(),
675 body: body_for_storage,
676 body_hash: body_hash.clone(),
677 session_id: args.session_id.clone(),
678 source: "agent".to_string(),
679 metadata,
680 };
681
682 let mut warnings = Vec::with_capacity(4);
683 let mut entities_persisted = 0usize;
684 let mut relationships_persisted = 0usize;
685
686 let graph_entity_embeddings = graph
687 .entities
688 .iter()
689 .map(|entity| {
690 let entity_text = match &entity.description {
691 Some(desc) => format!("{} {}", entity.name, desc),
692 None => entity.name.clone(),
693 };
694 crate::daemon::embed_passage_or_local(&paths.models, &entity_text)
695 })
696 .collect::<Result<Vec<_>, _>>()?;
697
698 let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
699
700 let mut skip_reindex = false;
701 let (memory_id, action, version) = match existing_memory {
702 Some((existing_id, _updated_at, _current_version)) => {
703 if let Some(hash_id) = duplicate_hash_id {
704 if hash_id != existing_id {
705 warnings.push(format!(
706 "identical body already exists as memory id {hash_id}"
707 ));
708 }
709 }
710
711 let (old_fts_name, old_fts_desc, old_fts_body): (String, String, String) = tx
713 .query_row(
714 "SELECT name, description, body FROM memories WHERE id = ?1",
715 rusqlite::params![existing_id],
716 |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
717 )?;
718
719 let existing_body_hash: Option<String> = tx
721 .query_row(
722 "SELECT body_hash FROM memories WHERE id = ?1",
723 rusqlite::params![existing_id],
724 |r| r.get(0),
725 )
726 .ok();
727 let body_unchanged = existing_body_hash.as_deref() == Some(&body_hash);
728 skip_reindex = body_unchanged;
729 if !body_unchanged {
730 storage_chunks::delete_chunks(&tx, existing_id)?;
731 }
732
733 let next_v = versions::next_version(&tx, existing_id)?;
734 memories::update(&tx, existing_id, &new_memory, args.expected_updated_at)?;
735
736 memories::sync_fts_after_update(
739 &tx,
740 existing_id,
741 &old_fts_name,
742 &old_fts_desc,
743 &old_fts_body,
744 &normalized_name,
745 &resolved_description,
746 &new_memory.body,
747 )?;
748
749 versions::insert_version(
750 &tx,
751 existing_id,
752 next_v,
753 &normalized_name,
754 memory_type,
755 &resolved_description,
756 &new_memory.body,
757 &serde_json::to_string(&new_memory.metadata)?,
758 None,
759 "edit",
760 )?;
761 if !body_unchanged {
762 memories::upsert_vec(
763 &tx,
764 existing_id,
765 &namespace,
766 memory_type,
767 &embedding,
768 &normalized_name,
769 &snippet,
770 )?;
771 }
772 (existing_id, "updated".to_string(), next_v)
773 }
774 None => {
775 if let Some(hash_id) = duplicate_hash_id {
776 warnings.push(format!(
777 "identical body already exists as memory id {hash_id}"
778 ));
779 }
780 let id = memories::insert(&tx, &new_memory)?;
781 versions::insert_version(
782 &tx,
783 id,
784 1,
785 &normalized_name,
786 memory_type,
787 &resolved_description,
788 &new_memory.body,
789 &serde_json::to_string(&new_memory.metadata)?,
790 None,
791 "create",
792 )?;
793 memories::upsert_vec(
794 &tx,
795 id,
796 &namespace,
797 memory_type,
798 &embedding,
799 &normalized_name,
800 &snippet,
801 )?;
802 (id, "created".to_string(), 1)
803 }
804 };
805
806 if chunks_info.len() > 1 && !skip_reindex {
807 storage_chunks::insert_chunk_slices(&tx, memory_id, &new_memory.body, &chunks_info)?;
808
809 let chunk_embeddings = chunk_embeddings_cache.take().ok_or_else(|| {
810 AppError::Internal(anyhow::anyhow!(
811 "chunk embeddings cache missing in multi-chunk remember path"
812 ))
813 })?;
814
815 for (i, emb) in chunk_embeddings.iter().enumerate() {
816 storage_chunks::upsert_chunk_vec(&tx, i as i64, memory_id, i as i32, emb)?;
817 }
818 output::emit_progress_i18n(
819 &format!(
820 "Remember stage: persisted chunk vectors; process RSS {} MB",
821 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
822 ),
823 &format!(
824 "Etapa remember: vetores de chunks persistidos; RSS do processo {} MB",
825 crate::memory_guard::current_process_memory_mb().unwrap_or(0)
826 ),
827 );
828 }
829
830 if !graph.entities.is_empty() || !graph.relationships.is_empty() {
831 for entity in &graph.entities {
832 let entity_id = entities::upsert_entity(&tx, &namespace, entity)?;
833 let entity_embedding = &graph_entity_embeddings[entities_persisted];
834 entities::upsert_entity_vec(
835 &tx,
836 entity_id,
837 &namespace,
838 entity.entity_type,
839 entity_embedding,
840 &entity.name,
841 )?;
842 entities::link_memory_entity(&tx, memory_id, entity_id)?;
843 entities::increment_degree(&tx, entity_id)?;
844 if args.max_entity_degree > 0 {
846 let cap = args.max_entity_degree as i64;
847 let degree: i64 = tx.query_row(
848 "SELECT degree FROM entities WHERE id = ?1",
849 rusqlite::params![entity_id],
850 |r| r.get(0),
851 )?;
852 if degree > cap {
853 tracing::warn!(target: "remember",
854 entity = %entity.name,
855 degree = degree,
856 cap = cap,
857 "entity degree cap exceeded"
858 );
859 }
860 }
861 entities_persisted += 1;
862 }
863 let entity_types: std::collections::HashMap<&str, EntityType> = graph
864 .entities
865 .iter()
866 .map(|entity| (entity.name.as_str(), entity.entity_type))
867 .collect();
868
869 for rel in &graph.relationships {
870 let source_entity = NewEntity {
871 name: rel.source.clone(),
872 entity_type: entity_types
873 .get(rel.source.as_str())
874 .copied()
875 .unwrap_or(EntityType::Concept),
876 description: None,
877 };
878 let target_entity = NewEntity {
879 name: rel.target.clone(),
880 entity_type: entity_types
881 .get(rel.target.as_str())
882 .copied()
883 .unwrap_or(EntityType::Concept),
884 description: None,
885 };
886 let source_id = entities::upsert_entity(&tx, &namespace, &source_entity)?;
887 let target_id = entities::upsert_entity(&tx, &namespace, &target_entity)?;
888 let rel_id = entities::upsert_relationship(&tx, &namespace, source_id, target_id, rel)?;
889 entities::link_memory_relationship(&tx, memory_id, rel_id)?;
890 relationships_persisted += 1;
891 }
892 }
893 tx.commit()?;
894
895 let urls_persisted = if !extracted_urls.is_empty() {
898 let url_entries: Vec<storage_urls::MemoryUrl> = extracted_urls
899 .into_iter()
900 .map(|u| storage_urls::MemoryUrl {
901 url: u.url,
902 offset: Some(u.offset as i64),
903 })
904 .collect();
905 storage_urls::insert_urls(&conn, memory_id, &url_entries)
906 } else {
907 0
908 };
909
910 conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
911
912 let created_at_epoch = chrono::Utc::now().timestamp();
913 let created_at_iso = crate::tz::format_iso(chrono::Utc::now());
914
915 output::emit_json(&RememberResponse {
916 memory_id,
917 name: normalized_name.clone(),
921 namespace,
922 action: action.clone(),
923 operation: action,
924 version,
925 entities_persisted,
926 relationships_persisted,
927 relationships_truncated,
928 chunks_created,
929 chunks_persisted,
930 urls_persisted,
931 extraction_method,
932 merged_into_memory_id: None,
933 warnings,
934 created_at: created_at_epoch,
935 created_at_iso,
936 elapsed_ms: inicio.elapsed().as_millis() as u64,
937 name_was_normalized,
938 original_name: name_was_normalized.then_some(original_name),
939 })?;
940
941 Ok(())
942}
943
944#[cfg(test)]
945mod tests {
946 use super::compute_chunks_persisted;
947 use crate::output::RememberResponse;
948
949 #[test]
951 fn chunks_persisted_zero_for_zero_chunks() {
952 assert_eq!(compute_chunks_persisted(0), 0);
953 }
954
955 #[test]
956 fn chunks_persisted_zero_for_single_chunk_body() {
957 assert_eq!(compute_chunks_persisted(1), 0);
960 }
961
962 #[test]
963 fn chunks_persisted_equals_count_for_multi_chunk_body() {
964 assert_eq!(compute_chunks_persisted(2), 2);
966 assert_eq!(compute_chunks_persisted(7), 7);
967 assert_eq!(compute_chunks_persisted(64), 64);
968 }
969
970 #[test]
971 fn remember_response_serializes_required_fields() {
972 let resp = RememberResponse {
973 memory_id: 42,
974 name: "minha-mem".to_string(),
975 namespace: "global".to_string(),
976 action: "created".to_string(),
977 operation: "created".to_string(),
978 version: 1,
979 entities_persisted: 0,
980 relationships_persisted: 0,
981 relationships_truncated: false,
982 chunks_created: 1,
983 chunks_persisted: 0,
984 urls_persisted: 0,
985 extraction_method: None,
986 merged_into_memory_id: None,
987 warnings: vec![],
988 created_at: 1_705_320_000,
989 created_at_iso: "2024-01-15T12:00:00Z".to_string(),
990 elapsed_ms: 55,
991 name_was_normalized: false,
992 original_name: None,
993 };
994
995 let json = serde_json::to_value(&resp).expect("serialization failed");
996 assert_eq!(json["memory_id"], 42);
997 assert_eq!(json["action"], "created");
998 assert_eq!(json["operation"], "created");
999 assert_eq!(json["version"], 1);
1000 assert_eq!(json["elapsed_ms"], 55u64);
1001 assert!(json["warnings"].is_array());
1002 assert!(json["merged_into_memory_id"].is_null());
1003 }
1004
1005 #[test]
1006 fn remember_response_action_e_operation_sao_aliases() {
1007 let resp = RememberResponse {
1008 memory_id: 1,
1009 name: "mem".to_string(),
1010 namespace: "global".to_string(),
1011 action: "updated".to_string(),
1012 operation: "updated".to_string(),
1013 version: 2,
1014 entities_persisted: 3,
1015 relationships_persisted: 1,
1016 relationships_truncated: false,
1017 extraction_method: None,
1018 chunks_created: 2,
1019 chunks_persisted: 2,
1020 urls_persisted: 0,
1021 merged_into_memory_id: None,
1022 warnings: vec![],
1023 created_at: 0,
1024 created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1025 elapsed_ms: 0,
1026 name_was_normalized: false,
1027 original_name: None,
1028 };
1029
1030 let json = serde_json::to_value(&resp).expect("serialization failed");
1031 assert_eq!(
1032 json["action"], json["operation"],
1033 "action e operation devem ser iguais"
1034 );
1035 assert_eq!(json["entities_persisted"], 3);
1036 assert_eq!(json["relationships_persisted"], 1);
1037 assert_eq!(json["chunks_created"], 2);
1038 }
1039
1040 #[test]
1041 fn remember_response_warnings_lista_mensagens() {
1042 let resp = RememberResponse {
1043 memory_id: 5,
1044 name: "dup-mem".to_string(),
1045 namespace: "global".to_string(),
1046 action: "created".to_string(),
1047 operation: "created".to_string(),
1048 version: 1,
1049 entities_persisted: 0,
1050 extraction_method: None,
1051 relationships_persisted: 0,
1052 relationships_truncated: false,
1053 chunks_created: 1,
1054 chunks_persisted: 0,
1055 urls_persisted: 0,
1056 merged_into_memory_id: None,
1057 warnings: vec!["identical body already exists as memory id 3".to_string()],
1058 created_at: 0,
1059 created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1060 elapsed_ms: 10,
1061 name_was_normalized: false,
1062 original_name: None,
1063 };
1064
1065 let json = serde_json::to_value(&resp).expect("serialization failed");
1066 let warnings = json["warnings"]
1067 .as_array()
1068 .expect("warnings deve ser array");
1069 assert_eq!(warnings.len(), 1);
1070 assert!(warnings[0].as_str().unwrap().contains("identical body"));
1071 }
1072
1073 #[test]
1074 fn invalid_name_reserved_prefix_returns_validation_error() {
1075 use crate::errors::AppError;
1076 let nome = "__reservado";
1078 let resultado: Result<(), AppError> = if nome.starts_with("__") {
1079 Err(AppError::Validation(
1080 crate::i18n::validation::reserved_name(),
1081 ))
1082 } else {
1083 Ok(())
1084 };
1085 assert!(resultado.is_err());
1086 if let Err(AppError::Validation(msg)) = resultado {
1087 assert!(!msg.is_empty());
1088 }
1089 }
1090
1091 #[test]
1092 fn name_too_long_returns_validation_error() {
1093 use crate::errors::AppError;
1094 let nome_longo = "a".repeat(crate::constants::MAX_MEMORY_NAME_LEN + 1);
1095 let resultado: Result<(), AppError> =
1096 if nome_longo.is_empty() || nome_longo.len() > crate::constants::MAX_MEMORY_NAME_LEN {
1097 Err(AppError::Validation(crate::i18n::validation::name_length(
1098 crate::constants::MAX_MEMORY_NAME_LEN,
1099 )))
1100 } else {
1101 Ok(())
1102 };
1103 assert!(resultado.is_err());
1104 }
1105
1106 #[test]
1107 fn remember_response_merged_into_memory_id_some_serializes_integer() {
1108 let resp = RememberResponse {
1109 memory_id: 10,
1110 name: "mem-mergeada".to_string(),
1111 namespace: "global".to_string(),
1112 action: "updated".to_string(),
1113 operation: "updated".to_string(),
1114 version: 3,
1115 extraction_method: None,
1116 entities_persisted: 0,
1117 relationships_persisted: 0,
1118 relationships_truncated: false,
1119 chunks_created: 1,
1120 chunks_persisted: 0,
1121 urls_persisted: 0,
1122 merged_into_memory_id: Some(7),
1123 warnings: vec![],
1124 created_at: 0,
1125 created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1126 elapsed_ms: 0,
1127 name_was_normalized: false,
1128 original_name: None,
1129 };
1130
1131 let json = serde_json::to_value(&resp).expect("serialization failed");
1132 assert_eq!(json["merged_into_memory_id"], 7);
1133 }
1134
1135 #[test]
1136 fn remember_response_urls_persisted_serializes_field() {
1137 let resp = RememberResponse {
1139 memory_id: 3,
1140 name: "mem-com-urls".to_string(),
1141 namespace: "global".to_string(),
1142 action: "created".to_string(),
1143 operation: "created".to_string(),
1144 version: 1,
1145 entities_persisted: 0,
1146 relationships_persisted: 0,
1147 relationships_truncated: false,
1148 chunks_created: 1,
1149 chunks_persisted: 0,
1150 urls_persisted: 3,
1151 extraction_method: Some("regex-only".to_string()),
1152 merged_into_memory_id: None,
1153 warnings: vec![],
1154 created_at: 0,
1155 created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1156 elapsed_ms: 0,
1157 name_was_normalized: false,
1158 original_name: None,
1159 };
1160 let json = serde_json::to_value(&resp).expect("serialization failed");
1161 assert_eq!(json["urls_persisted"], 3);
1162 }
1163
1164 #[test]
1165 fn empty_name_after_normalization_returns_specific_message() {
1166 use crate::errors::AppError;
1169 let normalized = "---".to_lowercase().replace(['_', ' '], "-");
1170 let normalized = normalized.trim_matches('-').to_string();
1171 let resultado: Result<(), AppError> = if normalized.is_empty() {
1172 Err(AppError::Validation(
1173 "name cannot be empty after normalization (input was blank or contained only hyphens/underscores/spaces)".to_string(),
1174 ))
1175 } else {
1176 Ok(())
1177 };
1178 assert!(resultado.is_err());
1179 if let Err(AppError::Validation(msg)) = resultado {
1180 assert!(
1181 msg.contains("empty after normalization"),
1182 "mensagem deve mencionar 'empty after normalization', obteve: {msg}"
1183 );
1184 }
1185 }
1186
1187 #[test]
1188 fn name_only_underscores_after_normalization_returns_specific_message() {
1189 use crate::errors::AppError;
1191 let normalized = "___".to_lowercase().replace(['_', ' '], "-");
1192 let normalized = normalized.trim_matches('-').to_string();
1193 assert!(
1194 normalized.is_empty(),
1195 "underscores devem normalizar para string vazia"
1196 );
1197 let resultado: Result<(), AppError> = if normalized.is_empty() {
1198 Err(AppError::Validation(
1199 "name cannot be empty after normalization (input was blank or contained only hyphens/underscores/spaces)".to_string(),
1200 ))
1201 } else {
1202 Ok(())
1203 };
1204 assert!(resultado.is_err());
1205 if let Err(AppError::Validation(msg)) = resultado {
1206 assert!(
1207 msg.contains("empty after normalization"),
1208 "mensagem deve mencionar 'empty after normalization', obteve: {msg}"
1209 );
1210 }
1211 }
1212
1213 #[test]
1214 fn remember_response_relationships_truncated_serializes_field() {
1215 let resp_false = RememberResponse {
1217 memory_id: 1,
1218 name: "test".to_string(),
1219 namespace: "global".to_string(),
1220 action: "created".to_string(),
1221 operation: "created".to_string(),
1222 version: 1,
1223 entities_persisted: 2,
1224 relationships_persisted: 1,
1225 relationships_truncated: false,
1226 chunks_created: 1,
1227 chunks_persisted: 0,
1228 urls_persisted: 0,
1229 extraction_method: None,
1230 merged_into_memory_id: None,
1231 warnings: vec![],
1232 created_at: 0,
1233 created_at_iso: "1970-01-01T00:00:00Z".to_string(),
1234 elapsed_ms: 0,
1235 name_was_normalized: false,
1236 original_name: None,
1237 };
1238 let json_false = serde_json::to_value(&resp_false).expect("serialization failed");
1239 assert_eq!(json_false["relationships_truncated"], false);
1240
1241 let resp_true = RememberResponse {
1242 relationships_truncated: true,
1243 ..resp_false
1244 };
1245 let json_true = serde_json::to_value(&resp_true).expect("serialization failed");
1246 assert_eq!(json_true["relationships_truncated"], true);
1247 }
1248
1249 fn should_preserve_body(force_merge: bool, raw_body_is_empty: bool, clear_body: bool) -> bool {
1258 force_merge && raw_body_is_empty && !clear_body
1259 }
1260
1261 #[test]
1262 fn gap08_empty_body_force_merge_no_clear_body_preserves() {
1263 assert!(
1266 should_preserve_body(true, true, false),
1267 "empty body + force-merge + no clear-body should trigger preservation"
1268 );
1269 }
1270
1271 #[test]
1272 fn gap08_empty_body_force_merge_with_clear_body_does_not_preserve() {
1273 assert!(
1275 !should_preserve_body(true, true, true),
1276 "--clear-body must bypass preservation"
1277 );
1278 }
1279
1280 #[test]
1281 fn gap08_non_empty_body_force_merge_does_not_preserve() {
1282 assert!(
1284 !should_preserve_body(true, false, false),
1285 "non-empty body must overwrite, not preserve"
1286 );
1287 }
1288
1289 #[test]
1290 fn gap08_empty_body_no_force_merge_does_not_preserve() {
1291 assert!(
1293 !should_preserve_body(false, true, false),
1294 "no --force-merge means no preservation logic applies"
1295 );
1296 }
1297}