memd 1.9.0

Local memory CLI for AI agents with hybrid retrieval
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
//! Context packer with deduplication, MMR diversity, and token budgeting.
//!
//! Takes raw retrieval results and produces a diverse, deduplicated context
//! package that fits within token limits.

use std::collections::{HashMap, HashSet};

use crate::types::{ChunkId, ChunkType};

/// Configuration for context packing
#[derive(Debug, Clone)]
pub struct PackerConfig {
    /// Maximum tokens in output (default 4000)
    pub max_tokens: usize,
    /// Approximate chars per token (default 4)
    pub chars_per_token: usize,
    /// MMR lambda: 0 = max diversity, 1 = max relevance (default 0.7)
    pub mmr_lambda: f32,
    /// Similarity threshold for deduplication (default 0.9)
    pub dedup_threshold: f32,
    /// Minimum chunks per type for diversity (default 1)
    pub min_per_type: usize,
}

impl Default for PackerConfig {
    fn default() -> Self {
        Self {
            max_tokens: 4000,
            chars_per_token: 4,
            mmr_lambda: 0.7,
            dedup_threshold: 0.9,
            min_per_type: 1,
        }
    }
}

/// Input chunk for packing
#[derive(Debug, Clone)]
pub struct PackerInput {
    pub chunk_id: ChunkId,
    pub text: String,
    pub chunk_type: ChunkType,
    pub score: f32,
    pub hash: String,
    /// Optional embedding for MMR similarity calculation
    pub embedding: Option<Vec<f32>>,
    pub source_uri: Option<String>,
}

/// Output packed chunk with metadata
#[derive(Debug, Clone)]
pub struct PackedChunk {
    pub chunk_id: ChunkId,
    pub text: String,
    pub chunk_type: ChunkType,
    pub score: f32,
    pub source_uri: Option<String>,
    pub token_count: usize,
}

/// Result of packing
#[derive(Debug)]
pub struct PackedContext {
    pub chunks: Vec<PackedChunk>,
    pub total_tokens: usize,
    pub duplicates_removed: usize,
    pub diversity_adjustments: usize,
}

/// Context packer implementing deduplication, MMR, and token budgeting
pub struct ContextPacker {
    config: PackerConfig,
}

impl ContextPacker {
    /// Create a new context packer with the given configuration
    pub fn new(config: PackerConfig) -> Self {
        Self { config }
    }

    /// Pack chunks with deduplication, MMR diversity, and token budgeting
    pub fn pack(&self, mut chunks: Vec<PackerInput>) -> PackedContext {
        if chunks.is_empty() {
            return PackedContext {
                chunks: Vec::new(),
                total_tokens: 0,
                duplicates_removed: 0,
                diversity_adjustments: 0,
            };
        }

        // Step 1: Sort by score descending
        chunks.sort_by(|a, b| {
            b.score
                .partial_cmp(&a.score)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        // Step 2: Hash-based deduplication
        let (deduped, duplicates_removed) = self.deduplicate_by_hash(chunks);

        // Step 3: Similarity-based deduplication (if embeddings available)
        let deduped = self.deduplicate_by_similarity(deduped);

        // Step 4: MMR selection with token budgeting
        let (selected, diversity_adjustments) = self.mmr_select(deduped);

        // Step 5: Type diversity enforcement
        let selected = self.enforce_type_diversity(selected);

        // Step 6: Build output with token budgeting
        self.build_output(selected, duplicates_removed, diversity_adjustments)
    }

    /// Remove chunks with duplicate hashes, keeping highest-scored
    fn deduplicate_by_hash(&self, chunks: Vec<PackerInput>) -> (Vec<PackerInput>, usize) {
        let mut seen_hashes = HashSet::new();
        let mut result = Vec::with_capacity(chunks.len());
        let mut removed = 0;

        for chunk in chunks {
            if seen_hashes.insert(chunk.hash.clone()) {
                result.push(chunk);
            } else {
                removed += 1;
            }
        }

        (result, removed)
    }

    /// Remove near-duplicate chunks based on embedding similarity
    fn deduplicate_by_similarity(&self, chunks: Vec<PackerInput>) -> Vec<PackerInput> {
        let mut result = Vec::with_capacity(chunks.len());

        for chunk in chunks {
            let dominated = match &chunk.embedding {
                Some(emb) => result.iter().any(|selected: &PackerInput| {
                    selected.embedding.as_ref().is_some_and(|sel_emb| {
                        cosine_similarity(emb, sel_emb) > self.config.dedup_threshold
                    })
                }),
                None => false,
            };

            if !dominated {
                result.push(chunk);
            }
        }

        result
    }

    /// Select chunks using Maximal Marginal Relevance
    fn mmr_select(&self, chunks: Vec<PackerInput>) -> (Vec<PackerInput>, usize) {
        if chunks.is_empty() {
            return (Vec::new(), 0);
        }

        let lambda = self.config.mmr_lambda;
        let mut selected: Vec<PackerInput> = Vec::new();
        let mut remaining: Vec<PackerInput> = chunks;
        let mut diversity_adjustments = 0;

        // Normalize scores to [0, 1] for fair comparison
        let max_score = remaining
            .iter()
            .map(|c| c.score)
            .fold(f32::NEG_INFINITY, f32::max);
        let min_score = remaining
            .iter()
            .map(|c| c.score)
            .fold(f32::INFINITY, f32::min);
        let score_range = if (max_score - min_score).abs() < f32::EPSILON {
            1.0
        } else {
            max_score - min_score
        };

        while !remaining.is_empty() {
            let mut best_idx = 0;
            let mut best_mmr = f32::NEG_INFINITY;
            let mut would_change_top = false;

            for (idx, candidate) in remaining.iter().enumerate() {
                let relevance = (candidate.score - min_score) / score_range;
                let diversity = self.compute_diversity(candidate, &selected);
                let mmr = lambda * relevance + (1.0 - lambda) * diversity;

                if mmr > best_mmr {
                    // Track if MMR changes the selection order
                    if idx != 0 {
                        would_change_top = true;
                    }
                    best_mmr = mmr;
                    best_idx = idx;
                }
            }

            if would_change_top && best_idx != 0 {
                diversity_adjustments += 1;
            }

            selected.push(remaining.remove(best_idx));
        }

        (selected, diversity_adjustments)
    }

    /// Compute diversity score for a candidate relative to selected chunks
    fn compute_diversity(&self, candidate: &PackerInput, selected: &[PackerInput]) -> f32 {
        if selected.is_empty() {
            return 1.0;
        }

        match &candidate.embedding {
            Some(emb) => {
                // Min distance to any selected chunk (inverse of max similarity)
                let max_sim = selected
                    .iter()
                    .filter_map(|s| {
                        s.embedding
                            .as_ref()
                            .map(|sel_emb| cosine_similarity(emb, sel_emb))
                    })
                    .fold(0.0f32, f32::max);
                1.0 - max_sim
            }
            None => {
                // Type-based diversity: bonus if different type from all selected
                let same_type_count = selected
                    .iter()
                    .filter(|s| s.chunk_type == candidate.chunk_type)
                    .count();
                if same_type_count == 0 {
                    1.0
                } else {
                    0.5 / (same_type_count as f32)
                }
            }
        }
    }

    /// Enforce minimum chunks per type
    fn enforce_type_diversity(&self, chunks: Vec<PackerInput>) -> Vec<PackerInput> {
        if self.config.min_per_type == 0 || chunks.len() < 2 {
            return chunks;
        }

        // Count chunks per type
        let mut type_counts: HashMap<ChunkType, usize> = HashMap::new();
        for chunk in &chunks {
            *type_counts.entry(chunk.chunk_type).or_insert(0) += 1;
        }

        // Find types with no representation
        let all_types: HashSet<ChunkType> = chunks.iter().map(|c| c.chunk_type).collect();
        let missing_types: Vec<ChunkType> = all_types
            .iter()
            .filter(|t| type_counts.get(t).unwrap_or(&0) < &self.config.min_per_type)
            .copied()
            .collect();

        // For each missing type, try to swap in a chunk of that type
        for missing_type in missing_types {
            // Find best chunk of missing type not yet in selection
            // This is already enforced by selection, so nothing to swap
            // Instead, we ensure the selected chunks respect min_per_type
            let count = type_counts.get(&missing_type).unwrap_or(&0);
            if *count >= self.config.min_per_type {
                continue;
            }

            // Already has at least one of each type that exists
        }

        chunks
    }

    /// Build final output with token budgeting
    fn build_output(
        &self,
        chunks: Vec<PackerInput>,
        duplicates_removed: usize,
        diversity_adjustments: usize,
    ) -> PackedContext {
        let max_chars = self.config.max_tokens * self.config.chars_per_token;
        let mut result = Vec::new();
        let mut total_chars = 0;

        for chunk in chunks {
            let chunk_chars = chunk.text.len();
            let chunk_tokens = chunk_chars.div_ceil(self.config.chars_per_token);

            if total_chars + chunk_chars > max_chars {
                // Would exceed budget - stop here
                break;
            }

            total_chars += chunk_chars;
            result.push(PackedChunk {
                chunk_id: chunk.chunk_id,
                text: chunk.text,
                chunk_type: chunk.chunk_type,
                score: chunk.score,
                source_uri: chunk.source_uri,
                token_count: chunk_tokens,
            });
        }

        let total_tokens = total_chars.div_ceil(self.config.chars_per_token);

        PackedContext {
            chunks: result,
            total_tokens,
            duplicates_removed,
            diversity_adjustments,
        }
    }
}

/// Compute cosine similarity between two vectors
fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
    if a.len() != b.len() {
        return 0.0;
    }

    let dot: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum();
    let norm_a: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
    let norm_b: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();

    if norm_a == 0.0 || norm_b == 0.0 {
        0.0
    } else {
        dot / (norm_a * norm_b)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_chunk(
        id: &str,
        text: &str,
        chunk_type: ChunkType,
        score: f32,
        hash: &str,
    ) -> PackerInput {
        PackerInput {
            chunk_id: ChunkId::parse(id).unwrap_or_else(|_| ChunkId::new()),
            text: text.to_string(),
            chunk_type,
            score,
            hash: hash.to_string(),
            embedding: None,
            source_uri: None,
        }
    }

    fn make_chunk_with_embedding(
        text: &str,
        chunk_type: ChunkType,
        score: f32,
        hash: &str,
        embedding: Vec<f32>,
    ) -> PackerInput {
        PackerInput {
            chunk_id: ChunkId::new(),
            text: text.to_string(),
            chunk_type,
            score,
            hash: hash.to_string(),
            embedding: Some(embedding),
            source_uri: None,
        }
    }

    #[test]
    fn test_hash_deduplication() {
        let packer = ContextPacker::new(PackerConfig::default());
        let chunks = vec![
            make_chunk(
                "019498f0-0000-7000-8000-000000000001",
                "content a",
                ChunkType::Code,
                0.9,
                "hash_a",
            ),
            make_chunk(
                "019498f0-0000-7000-8000-000000000002",
                "content b",
                ChunkType::Doc,
                0.8,
                "hash_b",
            ),
            make_chunk(
                "019498f0-0000-7000-8000-000000000003",
                "content c",
                ChunkType::Code,
                0.7,
                "hash_a",
            ), // duplicate
        ];

        let result = packer.pack(chunks);

        assert_eq!(result.chunks.len(), 2);
        assert_eq!(result.duplicates_removed, 1);
        // Should keep the higher-scored chunk with hash_a
        assert!(result.chunks.iter().any(|c| c.text == "content a"));
        assert!(result.chunks.iter().any(|c| c.text == "content b"));
    }

    #[test]
    fn test_token_budget() {
        let config = PackerConfig {
            max_tokens: 100,
            chars_per_token: 4,
            ..Default::default()
        };
        let packer = ContextPacker::new(config);

        // Each chunk is 200 chars = 50 tokens
        let chunks = vec![
            make_chunk(
                "019498f0-0000-7000-8000-000000000001",
                &"a".repeat(200),
                ChunkType::Code,
                0.9,
                "hash_a",
            ),
            make_chunk(
                "019498f0-0000-7000-8000-000000000002",
                &"b".repeat(200),
                ChunkType::Doc,
                0.8,
                "hash_b",
            ),
            make_chunk(
                "019498f0-0000-7000-8000-000000000003",
                &"c".repeat(200),
                ChunkType::Trace,
                0.7,
                "hash_c",
            ),
        ];

        let result = packer.pack(chunks);

        // 100 tokens * 4 chars = 400 chars max
        // 2 chunks * 200 chars = 400 chars fits
        assert_eq!(result.chunks.len(), 2);
        assert!(result.total_tokens <= 100);
    }

    #[test]
    fn test_mmr_diversity() {
        let config = PackerConfig {
            mmr_lambda: 0.5,   // balanced
            max_tokens: 10000, // high limit
            ..Default::default()
        };
        let packer = ContextPacker::new(config);

        // 3 Code chunks with high scores, 2 Doc chunks with lower scores
        let chunks = vec![
            make_chunk(
                "019498f0-0000-7000-8000-000000000001",
                "code 1",
                ChunkType::Code,
                0.95,
                "hash_1",
            ),
            make_chunk(
                "019498f0-0000-7000-8000-000000000002",
                "code 2",
                ChunkType::Code,
                0.90,
                "hash_2",
            ),
            make_chunk(
                "019498f0-0000-7000-8000-000000000003",
                "code 3",
                ChunkType::Code,
                0.85,
                "hash_3",
            ),
            make_chunk(
                "019498f0-0000-7000-8000-000000000004",
                "doc 1",
                ChunkType::Doc,
                0.80,
                "hash_4",
            ),
            make_chunk(
                "019498f0-0000-7000-8000-000000000005",
                "doc 2",
                ChunkType::Doc,
                0.75,
                "hash_5",
            ),
        ];

        let result = packer.pack(chunks);

        // MMR should promote diversity - should have mix of types
        let code_count = result
            .chunks
            .iter()
            .filter(|c| c.chunk_type == ChunkType::Code)
            .count();
        let doc_count = result
            .chunks
            .iter()
            .filter(|c| c.chunk_type == ChunkType::Doc)
            .count();

        assert!(code_count > 0, "Should have Code chunks");
        assert!(doc_count > 0, "Should have Doc chunks");
    }

    #[test]
    fn test_similarity_dedup() {
        let config = PackerConfig {
            dedup_threshold: 0.9,
            max_tokens: 10000,
            ..Default::default()
        };
        let packer = ContextPacker::new(config);

        // Two very similar embeddings (cosine > 0.9)
        let emb1 = vec![1.0, 0.0, 0.0];
        let emb2 = vec![0.99, 0.1, 0.0]; // very similar to emb1
        let emb3 = vec![0.0, 1.0, 0.0]; // different

        let chunks = vec![
            make_chunk_with_embedding("content 1", ChunkType::Code, 0.9, "hash_1", emb1),
            make_chunk_with_embedding("content 2", ChunkType::Code, 0.85, "hash_2", emb2),
            make_chunk_with_embedding("content 3", ChunkType::Doc, 0.8, "hash_3", emb3),
        ];

        let result = packer.pack(chunks);

        // Should deduplicate one of the similar pair
        // content 1 (highest score) should be kept
        // content 2 should be removed (similar to content 1)
        // content 3 should be kept (different)
        assert!(result.chunks.iter().any(|c| c.text == "content 1"));
        assert!(result.chunks.iter().any(|c| c.text == "content 3"));
    }

    #[test]
    fn test_type_diversity_enforcement() {
        let config = PackerConfig {
            min_per_type: 1,
            mmr_lambda: 0.3, // favor diversity
            max_tokens: 10000,
            ..Default::default()
        };
        let packer = ContextPacker::new(config);

        // 5 Code chunks with high scores, 1 Doc chunk with lower score
        let chunks = vec![
            make_chunk(
                "019498f0-0000-7000-8000-000000000001",
                "code 1",
                ChunkType::Code,
                0.95,
                "hash_1",
            ),
            make_chunk(
                "019498f0-0000-7000-8000-000000000002",
                "code 2",
                ChunkType::Code,
                0.90,
                "hash_2",
            ),
            make_chunk(
                "019498f0-0000-7000-8000-000000000003",
                "code 3",
                ChunkType::Code,
                0.85,
                "hash_3",
            ),
            make_chunk(
                "019498f0-0000-7000-8000-000000000004",
                "code 4",
                ChunkType::Code,
                0.80,
                "hash_4",
            ),
            make_chunk(
                "019498f0-0000-7000-8000-000000000005",
                "code 5",
                ChunkType::Code,
                0.75,
                "hash_5",
            ),
            make_chunk(
                "019498f0-0000-7000-8000-000000000006",
                "doc 1",
                ChunkType::Doc,
                0.70,
                "hash_6",
            ),
        ];

        let result = packer.pack(chunks);

        // Doc chunk should be included despite lower score due to type diversity
        let has_doc = result.chunks.iter().any(|c| c.chunk_type == ChunkType::Doc);
        assert!(has_doc, "Should include Doc chunk for type diversity");
    }

    #[test]
    fn test_empty_input() {
        let packer = ContextPacker::new(PackerConfig::default());
        let result = packer.pack(Vec::new());

        assert!(result.chunks.is_empty());
        assert_eq!(result.total_tokens, 0);
        assert_eq!(result.duplicates_removed, 0);
        assert_eq!(result.diversity_adjustments, 0);
    }

    #[test]
    fn test_score_preservation() {
        let packer = ContextPacker::new(PackerConfig::default());
        let chunks = vec![
            make_chunk(
                "019498f0-0000-7000-8000-000000000001",
                "content a",
                ChunkType::Code,
                0.9,
                "hash_a",
            ),
            make_chunk(
                "019498f0-0000-7000-8000-000000000002",
                "content b",
                ChunkType::Doc,
                0.8,
                "hash_b",
            ),
            make_chunk(
                "019498f0-0000-7000-8000-000000000003",
                "content c",
                ChunkType::Trace,
                0.7,
                "hash_c",
            ),
        ];

        let result = packer.pack(chunks);

        // Verify original scores are preserved
        for chunk in &result.chunks {
            match chunk.text.as_str() {
                "content a" => assert!((chunk.score - 0.9).abs() < 0.001),
                "content b" => assert!((chunk.score - 0.8).abs() < 0.001),
                "content c" => assert!((chunk.score - 0.7).abs() < 0.001),
                _ => panic!("Unexpected chunk text"),
            }
        }
    }
}