engram-core 0.21.1

AI Memory Infrastructure - Persistent memory for AI agents with semantic search
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
//! Search tool handlers.

use std::collections::HashMap;

use serde_json::{json, Value};

use crate::intelligence::memory_policy::{
    blend_retrieval_priority, extract_features, score_policy, PolicyFeatureInput,
};
use crate::search::{hybrid_search, RerankConfig, RerankStrategy, Reranker};
use crate::storage::queries::get_policy_record;
use crate::types::*;

use super::HandlerContext;

#[derive(Clone)]
struct PolicyRerankInfo {
    score: f32,
    blended_score: f32,
    reason: String,
    version: String,
    source: &'static str,
}

impl PolicyRerankInfo {
    fn to_json(&self) -> Value {
        json!({
            "score": self.score,
            "blended_score": self.blended_score,
            "reason": self.reason,
            "version": self.version,
            "source": self.source
        })
    }
}

pub fn memory_search(ctx: &HandlerContext, params: Value) -> Value {
    use crate::search::result_cache::CacheFilterParams;

    let query = params.get("query").and_then(|v| v.as_str()).unwrap_or("");
    let mut options: SearchOptions = serde_json::from_value(params.clone()).unwrap_or_default();
    let policy_rerank = params
        .get("policy_rerank")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let policy_explain = params
        .get("policy_explain")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);

    // Global search opt-in: when `global` is true, ignore workspace filters.
    let global = params
        .get("global")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    if global {
        options.global = true;
        options.workspace = None;
        options.workspaces = None;
    }

    let rerank_enabled = params
        .get("rerank")
        .and_then(|v| v.as_bool())
        .unwrap_or(true);
    let rerank_strategy = match params.get("rerank_strategy").and_then(|v| v.as_str()) {
        Some("none") => RerankStrategy::None,
        Some("multi_signal") => RerankStrategy::MultiSignal,
        _ => RerankStrategy::Heuristic,
    };

    let query_embedding = ctx.embedder.embed(query).ok();
    let embedding_ref = query_embedding.as_deref();

    let cache_filters = CacheFilterParams {
        workspace: options.workspace.clone(),
        tier: options.tier.map(|t| t.as_str().to_string()),
        memory_types: options.memory_type.map(|t| vec![t]),
        include_archived: options.include_archived,
        include_transcripts: options.include_transcripts,
        tags: options.tags.clone(),
        global,
    };

    let skip_cache = params
        .get("skip_cache")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);

    if !skip_cache && !rerank_enabled && !policy_rerank {
        if let Some(cached_results) = ctx.search_cache.get(query, embedding_ref, &cache_filters) {
            if global {
                let results_with_ws: Vec<Value> = cached_results
                    .iter()
                    .map(|r| {
                        json!({
                            "memory": r.memory,
                            "score": r.score,
                            "match_info": r.match_info,
                            "workspace": r.memory.workspace
                        })
                    })
                    .collect();
                return json!({"results": results_with_ws, "cached": true});
            }
            return json!({"results": cached_results, "cached": true});
        }
    }

    let mut search_config = ctx.search_config.clone();
    if let Ok(cwd) = std::env::current_dir() {
        if let Ok(canonical) = cwd.canonicalize() {
            search_config.project_context_path = Some(canonical.to_string_lossy().to_string());
        }
    }

    ctx.storage
        .with_connection(|conn| {
            let mut results = hybrid_search(conn, query, embedding_ref, &options, &search_config)?;

            if !rerank_enabled && !skip_cache && !policy_rerank {
                ctx.search_cache.put(
                    query,
                    query_embedding.clone(),
                    cache_filters.clone(),
                    results.clone(),
                );
            }

            let mut policy_info_by_memory_id = HashMap::new();
            if policy_rerank {
                for result in &mut results {
                    let hybrid_score = result.score;
                    let stored_policy = get_policy_record(conn, result.memory.id)?;
                    let (policy_score, source) = if let Some(policy) = stored_policy.as_ref() {
                        (
                            crate::intelligence::memory_policy::PolicyScore {
                                salience_score: policy.salience_score,
                                retention_score: policy.retention_score,
                                retrieval_priority: policy.retrieval_priority,
                                policy_version: policy.policy_version.clone(),
                                policy_reason: policy.policy_reason.clone(),
                            },
                            "stored",
                        )
                    } else {
                        let features = extract_features(PolicyFeatureInput {
                            memory: &result.memory,
                            existing_policy: None,
                            event: None,
                            hybrid_search_score: Some(hybrid_score),
                            session_relevance: None,
                        });
                        (score_policy(&features), "heuristic-v1")
                    };
                    let blended_score =
                        blend_retrieval_priority(hybrid_score, policy_score.retrieval_priority);

                    result.score = blended_score;
                    policy_info_by_memory_id.insert(
                        result.memory.id,
                        PolicyRerankInfo {
                            score: policy_score.retrieval_priority,
                            blended_score,
                            reason: policy_score.policy_reason,
                            version: policy_score.policy_version,
                            source,
                        },
                    );
                }

                results.sort_by(|a, b| {
                    b.score
                        .partial_cmp(&a.score)
                        .unwrap_or(std::cmp::Ordering::Equal)
                });
            }

            if rerank_enabled && rerank_strategy != RerankStrategy::None {
                let config = RerankConfig {
                    enabled: true,
                    strategy: rerank_strategy,
                    ..Default::default()
                };
                let reranker = Reranker::with_config(config);
                let reranked = reranker.rerank(results, query, Some(conn));

                if options.explain {
                    Ok(json!({
                        "results": reranked.iter().map(|r| {
                            let mut obj = json!({
                                "memory": r.result.memory,
                                "score": r.rerank_info.final_score,
                                "match_info": r.result.match_info,
                                "rerank_info": r.rerank_info
                            });
                            if global {
                                obj["workspace"] = json!(r.result.memory.workspace);
                            }
                            if policy_rerank && policy_explain {
                                if let Some(policy) = policy_info_by_memory_id.get(&r.result.memory.id) {
                                    obj["policy"] = policy.to_json();
                                }
                            }
                            obj
                        }).collect::<Vec<_>>(),
                        "reranked": true,
                        "strategy": format!("{:?}", rerank_strategy)
                    }))
                } else {
                    Ok(json!(reranked
                        .iter()
                        .map(|r| {
                            let mut obj = json!({
                                "memory": r.result.memory,
                                "score": r.rerank_info.final_score,
                                "match_info": r.result.match_info
                            });
                            if global {
                                obj["workspace"] = json!(r.result.memory.workspace);
                            }
                            if policy_rerank && policy_explain {
                                if let Some(policy) = policy_info_by_memory_id.get(&r.result.memory.id) {
                                    obj["policy"] = policy.to_json();
                                }
                            }
                            obj
                        })
                        .collect::<Vec<_>>()))
                }
            } else if global {
                // For global search without reranking, add top-level workspace field
                Ok(json!(results
                    .iter()
                    .map(|r| {
                        let mut obj = json!({
                            "memory": r.memory,
                            "score": r.score,
                            "match_info": r.match_info,
                            "workspace": r.memory.workspace
                        });
                        if policy_rerank && policy_explain {
                            if let Some(policy) = policy_info_by_memory_id.get(&r.memory.id) {
                                obj["policy"] = policy.to_json();
                            }
                        }
                        obj
                    })
                    .collect::<Vec<_>>()))
            } else {
                Ok(json!(results
                    .iter()
                    .map(|r| {
                        let mut obj = json!({
                            "memory": r.memory,
                            "score": r.score,
                            "match_info": r.match_info
                        });
                        if policy_rerank && policy_explain {
                            if let Some(policy) = policy_info_by_memory_id.get(&r.memory.id) {
                                obj["policy"] = policy.to_json();
                            }
                        }
                        obj
                    })
                    .collect::<Vec<_>>()))
            }
        })
        .unwrap_or_else(|e| json!({"error": e.to_string()}))
}

pub fn search_suggest(ctx: &HandlerContext, params: Value) -> Value {
    let query = params.get("query").and_then(|v| v.as_str()).unwrap_or("");
    let fuzzy = ctx.fuzzy_engine.lock();
    let result = fuzzy.correct_query(query);
    json!(result)
}

pub fn memory_search_by_identity(ctx: &HandlerContext, params: Value) -> Value {
    use crate::storage::search_by_identity;

    let identity = match params.get("identity").and_then(|v| v.as_str()) {
        Some(i) => i,
        None => return json!({"error": "identity is required"}),
    };

    let workspace = params.get("workspace").and_then(|v| v.as_str());
    let limit = params
        .get("limit")
        .and_then(|v| v.as_u64())
        .map(|v| v as usize);

    ctx.storage
        .with_connection(|conn| {
            let memories = search_by_identity(conn, identity, workspace, limit)?;
            Ok(json!({"memories": memories}))
        })
        .unwrap_or_else(|e| json!({"error": e.to_string()}))
}

pub fn memory_session_search(ctx: &HandlerContext, params: Value) -> Value {
    use crate::storage::search_sessions;

    let query = match params.get("query").and_then(|v| v.as_str()) {
        Some(q) => q,
        None => return json!({"error": "query is required"}),
    };

    let session_id = params.get("session_id").and_then(|v| v.as_str());
    let workspace = params.get("workspace").and_then(|v| v.as_str());
    let limit = params
        .get("limit")
        .and_then(|v| v.as_u64())
        .map(|v| v as usize);

    ctx.storage
        .with_connection(|conn| {
            let memories = search_sessions(conn, query, session_id, workspace, limit)?;
            Ok(json!({"memories": memories}))
        })
        .unwrap_or_else(|e| json!({"error": e.to_string()}))
}

pub fn find_duplicates(ctx: &HandlerContext, params: Value) -> Value {
    use crate::storage::queries::find_duplicates;

    let threshold = params
        .get("threshold")
        .and_then(|v| v.as_f64())
        .unwrap_or(0.9);

    ctx.storage
        .with_connection(|conn| {
            let duplicates = find_duplicates(conn, threshold)?;
            Ok(json!({
                "count": duplicates.len(),
                "threshold": threshold,
                "duplicates": duplicates
            }))
        })
        .unwrap_or_else(|e| json!({"error": e.to_string()}))
}

pub fn find_semantic_duplicates(ctx: &HandlerContext, params: Value) -> Value {
    use crate::storage::queries::find_duplicates_by_embedding;

    let threshold = params
        .get("threshold")
        .and_then(|v| v.as_f64())
        .unwrap_or(0.92) as f32;
    let workspace = params.get("workspace").and_then(|v| v.as_str());
    let limit = params.get("limit").and_then(|v| v.as_i64()).unwrap_or(50) as usize;

    ctx.storage
        .with_connection(|conn| {
            let duplicates = find_duplicates_by_embedding(conn, threshold, workspace, limit)?;
            Ok(json!({
                "count": duplicates.len(),
                "threshold": threshold,
                "method": "embedding_cosine_similarity",
                "duplicates": duplicates
            }))
        })
        .unwrap_or_else(|e| json!({"error": e.to_string()}))
}

pub fn search_cache_feedback(ctx: &HandlerContext, params: Value) -> Value {
    use crate::search::CacheFilterParams;

    let query = match params.get("query").and_then(|v| v.as_str()) {
        Some(q) => q,
        None => return json!({"error": "query is required"}),
    };

    let positive = match params.get("positive").and_then(|v| v.as_bool()) {
        Some(p) => p,
        None => return json!({"error": "positive is required"}),
    };

    let workspace = params
        .get("workspace")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    let filters = CacheFilterParams {
        workspace,
        ..Default::default()
    };

    ctx.search_cache.record_feedback(query, &filters, positive);
    let new_threshold = ctx.search_cache.current_threshold();

    json!({
        "recorded": true,
        "feedback": if positive { "positive" } else { "negative" },
        "current_threshold": new_threshold
    })
}

pub fn search_cache_stats(ctx: &HandlerContext, _params: Value) -> Value {
    let stats = ctx.search_cache.stats();
    json!(stats)
}

pub fn search_cache_clear(ctx: &HandlerContext, params: Value) -> Value {
    let workspace = params.get("workspace").and_then(|v| v.as_str());

    if let Some(ws) = workspace {
        ctx.search_cache.invalidate_for_workspace(Some(ws));
        json!({"cleared": true, "scope": "workspace", "workspace": ws})
    } else {
        ctx.search_cache.clear();
        json!({"cleared": true, "scope": "all"})
    }
}

// ── Search Explainability (RML-1242) ────────────────────────────────────────

pub fn memory_explain_search(_ctx: &HandlerContext, params: Value) -> Value {
    use crate::search::explain::SearchExplainer;

    let results = match params.get("results").and_then(|v| v.as_array()) {
        Some(arr) => arr,
        None => {
            return json!({"error": "results array is required (each with memory_id, bm25, vector, fuzzy, recency, importance, final_score, and optional rerank_score)"})
        }
    };

    let reranking_active = params
        .get("reranking_active")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let rrf_k = params.get("rrf_k").and_then(|v| v.as_f64()).unwrap_or(60.0) as f32;

    let explainer = SearchExplainer::new(rrf_k, reranking_active);

    let batch: Vec<_> = results
        .iter()
        .filter_map(|r| {
            let memory_id = r.get("memory_id")?.as_i64()?;
            let bm25 = r.get("bm25").and_then(|v| v.as_f64()).unwrap_or(0.0) as f32;
            let vector = r.get("vector").and_then(|v| v.as_f64()).unwrap_or(0.0) as f32;
            let fuzzy = r.get("fuzzy").and_then(|v| v.as_f64()).unwrap_or(0.0) as f32;
            let recency = r.get("recency").and_then(|v| v.as_f64()).unwrap_or(0.0) as f32;
            let importance = r.get("importance").and_then(|v| v.as_f64()).unwrap_or(0.0) as f32;
            let rerank = r
                .get("rerank_score")
                .and_then(|v| v.as_f64())
                .map(|v| v as f32);
            let final_score = r.get("final_score").and_then(|v| v.as_f64()).unwrap_or(0.0) as f32;
            Some((
                memory_id,
                bm25,
                vector,
                fuzzy,
                recency,
                importance,
                rerank,
                final_score,
            ))
        })
        .collect();

    let explanations = explainer.explain_batch(batch);
    json!({
        "count": explanations.len(),
        "explanations": explanations
    })
}

// ── Relevance Feedback (RML-1243) ───────────────────────────────────────────

pub fn memory_feedback(ctx: &HandlerContext, params: Value) -> Value {
    use crate::search::feedback::{record_feedback, FeedbackSignal};
    use crate::storage::feedback::FeedbackProcessor;

    let query = match params.get("query").and_then(|v| v.as_str()) {
        Some(q) => q,
        None => return json!({"error": "query is required"}),
    };

    let memory_id = match params.get("memory_id").and_then(|v| v.as_i64()) {
        Some(id) => id,
        None => return json!({"error": "memory_id is required"}),
    };

    // Accept both legacy aliases (helpful/not_helpful) and canonical names
    // (useful/irrelevant/outdated/conflict). All four canonical signals are
    // distinct in storage and produce different boost magnitudes downstream.
    let (feedback_signal, signal_str): (FeedbackSignal, &str) = match params
        .get("signal")
        .and_then(|v| v.as_str())
    {
        Some("useful") | Some("helpful") => (FeedbackSignal::Useful, "helpful"),
        Some("irrelevant") | Some("not_helpful") => (FeedbackSignal::Irrelevant, "not_helpful"),
        Some("outdated") => (FeedbackSignal::Outdated, "outdated"),
        Some("conflict") => (FeedbackSignal::Conflict, "conflict"),
        _ => {
            return json!({"error": "signal must be 'helpful'/'useful', 'not_helpful'/'irrelevant', 'outdated', or 'conflict'"});
        }
    };

    let rank_position = params
        .get("rank_position")
        .and_then(|v| v.as_i64())
        .map(|v| v as i32);
    let original_score = params
        .get("original_score")
        .and_then(|v| v.as_f64())
        .map(|v| v as f32);
    let workspace = params
        .get("workspace")
        .and_then(|v| v.as_str())
        .unwrap_or("default");

    ctx.storage
        .with_connection(|conn| {
            // 1. Record the feedback in the search feedback table
            let fb = record_feedback(
                conn,
                query,
                memory_id,
                feedback_signal,
                rank_position,
                original_score,
                workspace,
            )?;

            // 2. Process feedback through the feedback loop. Attach the
            // process-wide queueing consolidator so low-utility memories are
            // enqueued for the auto-consolidation scheduler to pick up.
            let consolidator =
                std::sync::Arc::new(crate::mcp::handlers::auto_consolidate::QueueingConsolidator);
            let processor = FeedbackProcessor::new().with_consolidator(consolidator);
            let (new_score, scheduled) = processor.process_feedback(memory_id, signal_str, conn)?;

            // 3. Return enriched response
            let mut result = json!(fb);
            if let Some(obj) = result.as_object_mut() {
                obj.insert("utility_score_after".to_string(), json!(new_score));
                obj.insert("scheduled_for_consolidation".to_string(), json!(scheduled));
            }

            Ok(result)
        })
        .unwrap_or_else(|e| json!({"error": e.to_string()}))
}

pub fn memory_feedback_stats(ctx: &HandlerContext, params: Value) -> Value {
    use crate::search::feedback::feedback_stats;

    let workspace = params.get("workspace").and_then(|v| v.as_str());

    ctx.storage
        .with_connection(|conn| {
            let stats = feedback_stats(conn, workspace)?;
            Ok(json!(stats))
        })
        .unwrap_or_else(|e| json!({"error": e.to_string()}))
}

pub fn memory_explain_utility(ctx: &HandlerContext, params: Value) -> Value {
    use crate::search::utility::UtilityTracker;

    let memory_id = match params.get("memory_id").and_then(|v| v.as_i64()) {
        Some(id) => id,
        None => return json!({"error": "memory_id is required"}),
    };

    ctx.storage
        .with_connection(|conn| {
            let tracker = UtilityTracker::new();
            let explanation = tracker.explain_utility(conn, memory_id)?;
            Ok(json!(explanation))
        })
        .unwrap_or_else(|e| json!({"error": e.to_string()}))
}

// ── Compact Search + Expand ──────────────────────────────────────────────────

/// Return a compact summary of search results (id, title, created_at, tags).
///
/// Parameters:
///   - `query` (String, required)
///   - `limit` (u64, optional, default 10)
///   - `workspace` (String, optional)
///
/// The `title` field is the first 80 chars of `content`, truncated at the first
/// newline, with "..." appended if truncated.
pub fn memory_search_compact(ctx: &HandlerContext, params: Value) -> Value {
    let query = match params.get("query").and_then(|v| v.as_str()) {
        Some(q) => q,
        None => return json!({"error": "query is required"}),
    };

    let mut options: SearchOptions = serde_json::from_value(params.clone()).unwrap_or_default();

    // Global search opt-in: when `global` is true, ignore workspace filters.
    let global = params
        .get("global")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    if global {
        options.global = true;
        options.workspace = None;
        options.workspaces = None;
    }

    // Apply default limit of 10 when not supplied
    if options.limit.is_none() {
        let limit_from_param = params.get("limit").and_then(|v| v.as_i64());
        options.limit = Some(limit_from_param.unwrap_or(10));
    }

    let query_embedding = ctx.embedder.embed(query).ok();
    let embedding_ref = query_embedding.as_deref();

    let mut search_config = ctx.search_config.clone();
    if let Ok(cwd) = std::env::current_dir() {
        if let Ok(canonical) = cwd.canonicalize() {
            search_config.project_context_path = Some(canonical.to_string_lossy().to_string());
        }
    }

    ctx.storage
        .with_connection(|conn| {
            let results = hybrid_search(conn, query, embedding_ref, &options, &search_config)?;

            let compact: Vec<Value> = results
                .iter()
                .map(|r| {
                    let memory = &r.memory;
                    // Build title: first 80 chars of content, truncated at first newline,
                    // with "..." appended if the content was longer than the title shown.
                    let first_line = memory.content.lines().next().unwrap_or("");
                    let has_more_lines = memory.content.contains('\n');
                    let title_str = if first_line.len() > 80 {
                        format!("{}...", &first_line[..80])
                    } else if has_more_lines {
                        format!("{}...", first_line)
                    } else {
                        first_line.to_string()
                    };
                    let mut obj = json!({
                        "id": memory.id,
                        "title": title_str,
                        "created_at": memory.created_at,
                        "tags": memory.tags
                    });
                    if global {
                        obj["workspace"] = json!(memory.workspace);
                    }
                    obj
                })
                .collect();

            Ok(json!({
                "results": compact,
                "count": compact.len()
            }))
        })
        .unwrap_or_else(|e| json!({"error": e.to_string()}))
}

/// Return recently created or updated memories for discovery.
///
/// Params:
/// - `workspace` (string, optional) — filter by workspace
/// - `timeframe` (string, optional) — "1h", "24h", "7d", "30d" (default: "24h")
/// - `limit` (integer, optional, default 20, max 100)
/// - `include_types` (array of strings, optional) — filter by memory type
pub fn recent_activity(ctx: &HandlerContext, params: Value) -> Value {
    let workspace = params.get("workspace").and_then(|v| v.as_str());
    let timeframe = params
        .get("timeframe")
        .and_then(|v| v.as_str())
        .unwrap_or("24h");
    let limit = params
        .get("limit")
        .and_then(|v| v.as_u64())
        .unwrap_or(20)
        .min(100) as i64;
    let include_types: Option<Vec<String>> = params
        .get("include_types")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        });

    let time_clause = match timeframe {
        "1h" => "AND created_at > datetime('now', '-1 hours')",
        "24h" => "AND created_at > datetime('now', '-24 hours')",
        "7d" => "AND created_at > datetime('now', '-7 days')",
        "30d" => "AND created_at > datetime('now', '-30 days')",
        _ => "AND created_at > datetime('now', '-24 hours')",
    };

    let workspace_owned = workspace.map(String::from);
    let timeframe_owned = timeframe.to_string();

    ctx.storage
        .with_connection(|conn| {
            let mut sql = format!(
                "SELECT m.id, m.content, m.memory_type, m.importance, m.workspace, \
                 m.created_at, m.updated_at, \
                 (SELECT GROUP_CONCAT(t.name, ',') FROM memory_tags mt \
                  JOIN tags t ON mt.tag_id = t.id WHERE mt.memory_id = m.id) AS tags \
                 FROM memories m WHERE m.valid_to IS NULL {} ",
                time_clause
            );

            let mut param_values: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();

            if let Some(ref ws) = workspace_owned {
                sql.push_str(&format!("AND m.workspace = ?{} ", param_values.len() + 1));
                param_values.push(Box::new(ws.clone()));
            }

            if let Some(ref types) = include_types {
                if !types.is_empty() {
                    let placeholders: Vec<String> = types
                        .iter()
                        .enumerate()
                        .map(|(i, _)| format!("?{}", param_values.len() + i + 1))
                        .collect();
                    sql.push_str(&format!(
                        "AND m.memory_type IN ({}) ",
                        placeholders.join(",")
                    ));
                    for t in types {
                        param_values.push(Box::new(t.clone()));
                    }
                }
            }

            sql.push_str(&format!(
                "ORDER BY COALESCE(m.updated_at, m.created_at) DESC LIMIT ?{}",
                param_values.len() + 1
            ));
            param_values.push(Box::new(limit));

            let mut stmt = conn.prepare(&sql)?;

            let rows = stmt.query_map(
                rusqlite::params_from_iter(param_values.iter().map(|p| p.as_ref())),
                |row| {
                    let content: String = row.get(1)?;
                    let char_count = content.chars().count();
                    let preview: String = content.chars().take(100).collect();
                    let preview = if char_count > 100 {
                        format!("{}...", preview)
                    } else {
                        preview
                    };

                    Ok(json!({
                        "id": row.get::<_, i64>(0)?,
                        "preview": preview,
                        "memory_type": row.get::<_, String>(2)?,
                        "importance": row.get::<_, f64>(3)?,
                        "workspace": row.get::<_, String>(4)?,
                        "created_at": row.get::<_, String>(5)?,
                        "updated_at": row.get::<_, String>(6)?,
                        "tags": row.get::<_, Option<String>>(7)?
                    }))
                },
            )?;

            let activities: Vec<Value> = rows.filter_map(|r| r.ok()).collect();
            let count = activities.len();

            Ok(json!({
                "activities": activities,
                "count": count,
                "timeframe": timeframe_owned,
                "workspace": workspace_owned
            }))
        })
        .unwrap_or_else(|e| json!({"error": e.to_string()}))
}

/// Fetch full Memory objects for a list of IDs.
///
/// Parameters:
///   - `ids` (array of integers, required)
///
/// IDs that do not exist are silently skipped.
/// Returns `{memories: [...], found: N, requested: N}`.
pub fn memory_expand(ctx: &HandlerContext, params: Value) -> Value {
    use crate::error::EngramError;
    use crate::storage::queries::get_memory;

    let ids: Vec<i64> = match params.get("ids").and_then(|v| v.as_array()) {
        Some(arr) => arr.iter().filter_map(|v| v.as_i64()).collect(),
        None => return json!({"error": "ids array is required"}),
    };

    let requested = ids.len();

    ctx.storage
        .with_connection(|conn| {
            let mut memories: Vec<Value> = Vec::with_capacity(ids.len());
            for id in &ids {
                match get_memory(conn, *id) {
                    Ok(memory) => memories.push(json!(memory)),
                    Err(EngramError::NotFound(_)) => {
                        // Skip silently
                    }
                    Err(e) => return Err(e),
                }
            }
            let found = memories.len();
            Ok(json!({
                "memories": memories,
                "found": found,
                "requested": requested
            }))
        })
        .unwrap_or_else(|e| json!({"error": e.to_string()}))
}