roboticus-agent 0.9.8

Agent core with ReAct loop, policy engine, injection defense, memory system, and skill loader
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
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
use roboticus_core::config::MemoryConfig;
use roboticus_db::Database;

use crate::context::{ComplexityLevel, token_budget};
use crate::memory::MemoryBudgetManager;

/// Retrieves and formats memories from all five tiers for injection into the LLM prompt.
pub struct MemoryRetriever {
    budget_manager: MemoryBudgetManager,
    hybrid_weight: f64,
    /// Half-life (in days) for episodic memory decay during retrieval re-ranking.
    /// Older episodic results have their similarity score discounted so that
    /// recent memories surface above stale ones with similar cosine proximity.
    decay_half_life_days: f64,
}

impl MemoryRetriever {
    pub fn new(config: MemoryConfig) -> Self {
        let hybrid_weight = config.hybrid_weight;
        Self {
            budget_manager: MemoryBudgetManager::new(config),
            hybrid_weight,
            decay_half_life_days: 7.0, // sensible default: 1-week half-life
        }
    }

    /// Override the episodic decay half-life (in days) used during retrieval re-ranking.
    pub fn with_decay_half_life(mut self, days: f64) -> Self {
        self.decay_half_life_days = days;
        self
    }

    /// Retrieve memories from all tiers and format them into a single string
    /// for context injection. Token budgets are respected per-tier.
    pub fn retrieve(
        &self,
        db: &Database,
        session_id: &str,
        query: &str,
        query_embedding: Option<&[f32]>,
        complexity: ComplexityLevel,
    ) -> String {
        self.retrieve_with_ann(db, session_id, query, query_embedding, complexity, None)
    }

    /// Like `retrieve`, but optionally uses an ANN index for O(log n) nearest-neighbor
    /// search instead of brute-force cosine scan.
    pub fn retrieve_with_ann(
        &self,
        db: &Database,
        session_id: &str,
        query: &str,
        query_embedding: Option<&[f32]>,
        complexity: ComplexityLevel,
        ann_index: Option<&roboticus_db::ann::AnnIndex>,
    ) -> String {
        let total_budget = token_budget(complexity);
        let budgets = self.budget_manager.allocate_budgets(total_budget);

        let mut sections = Vec::new();

        if let Some(s) = self.retrieve_working(db, session_id, budgets.working) {
            sections.push(s);
        }

        // Try ANN index first for relevant memories; fall back to brute-force hybrid search
        let relevant = if let (Some(ann), Some(emb)) = (ann_index, query_embedding) {
            ann.search(emb, 10).map(|results| {
                results
                    .into_iter()
                    .map(|r| roboticus_db::embeddings::SearchResult {
                        source_table: r.source_table,
                        source_id: r.source_id,
                        content_preview: r.content_preview,
                        similarity: r.similarity,
                    })
                    .collect::<Vec<_>>()
            })
        } else {
            None
        };
        let mut relevant = relevant.unwrap_or_else(|| {
            roboticus_db::embeddings::hybrid_search(
                db,
                query,
                query_embedding,
                10,
                self.hybrid_weight,
            )
            .unwrap_or_default()
        });

        // Decay re-ranking: discount episodic results by age so recent memories
        // surface above stale ones with similar cosine proximity.
        if self.decay_half_life_days > 0.0 {
            self.rerank_episodic_by_decay(db, &mut relevant);
        }

        if let Some(s) = self.format_relevant(&relevant, budgets.episodic + budgets.semantic) {
            sections.push(s);
        }

        if let Some(s) = self.retrieve_procedural(db, budgets.procedural) {
            sections.push(s);
        }

        if let Some(s) = self.retrieve_relationships(db, query, budgets.relationship) {
            sections.push(s);
        }

        if sections.is_empty() {
            return String::new();
        }

        format!("[Active Memory]\n{}", sections.join("\n\n"))
    }

    fn retrieve_working(
        &self,
        db: &Database,
        session_id: &str,
        budget_tokens: usize,
    ) -> Option<String> {
        if budget_tokens == 0 {
            return None;
        }

        let entries = roboticus_db::memory::retrieve_working(db, session_id)
            .inspect_err(
                |e| tracing::warn!(error = %e, session_id, "working memory retrieval failed"),
            )
            .ok()?;
        if entries.is_empty() {
            return None;
        }

        let mut text = String::from("[Working Memory]\n");
        let mut used = estimate_tokens(&text);

        for entry in &entries {
            // `turn_summary` mirrors prior assistant output and can cause
            // repetitive self-priming when injected into subsequent prompts.
            if entry.entry_type.eq_ignore_ascii_case("turn_summary") {
                continue;
            }
            let line = format!("- [{}] {}\n", entry.entry_type, entry.content);
            let line_tokens = estimate_tokens(&line);
            if used + line_tokens > budget_tokens {
                break;
            }
            text.push_str(&line);
            used += line_tokens;
        }

        if text.len() > "[Working Memory]\n".len() {
            Some(text)
        } else {
            None
        }
    }

    fn format_relevant(
        &self,
        results: &[roboticus_db::embeddings::SearchResult],
        budget_tokens: usize,
    ) -> Option<String> {
        if budget_tokens == 0 || results.is_empty() {
            return None;
        }

        let mut text = String::from("[Relevant Memories]\n");
        let mut used = estimate_tokens(&text);

        for result in results {
            let line = format!(
                "- [{} | sim={:.2}] {}\n",
                result.source_table, result.similarity, result.content_preview,
            );
            let line_tokens = estimate_tokens(&line);
            if used + line_tokens > budget_tokens {
                break;
            }
            text.push_str(&line);
            used += line_tokens;
        }

        if text.len() > "[Relevant Memories]\n".len() {
            Some(text)
        } else {
            None
        }
    }

    /// Re-rank search results by applying time-decay to episodic entries.
    ///
    /// For results from the `episodic_memory` table, look up their `created_at`
    /// timestamp and scale the similarity score by an exponential decay factor.
    /// Non-episodic results are left untouched.  The result list is re-sorted
    /// by the adjusted similarity in descending order.
    fn rerank_episodic_by_decay(
        &self,
        db: &Database,
        results: &mut [roboticus_db::embeddings::SearchResult],
    ) {
        let now = chrono::Utc::now();

        // Batch-query: collect all episodic IDs, look them up in one pass,
        // then apply decay.  This avoids N separate queries holding the DB
        // connection open in a loop.
        let episodic_ids: Vec<&str> = results
            .iter()
            .filter(|r| r.source_table == "episodic_memory")
            .map(|r| r.source_id.as_str())
            .collect();

        if episodic_ids.is_empty() {
            return;
        }

        // Build a HashMap<id, age_days> from a single DB access
        let age_map: std::collections::HashMap<String, f64> = {
            let conn = db.conn();
            let placeholders: Vec<String> =
                (1..=episodic_ids.len()).map(|i| format!("?{i}")).collect();
            let sql = format!(
                "SELECT id, created_at FROM episodic_memory WHERE id IN ({})",
                placeholders.join(", ")
            );
            let mut stmt = match conn.prepare(&sql) {
                Ok(s) => s,
                Err(_) => return,
            };
            let rows = match stmt
                .query_map(roboticus_db::params_from_iter(episodic_ids.iter()), |row| {
                    Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
                }) {
                Ok(r) => r,
                Err(_) => return,
            };
            rows.filter_map(|r| {
                r.inspect_err(|e| tracing::warn!("skipping corrupted episodic row: {e}"))
                    .ok()
            })
            .filter_map(|(id, ts)| {
                chrono::DateTime::parse_from_rfc3339(&ts)
                    .ok()
                    .map(|created| {
                        // Age in days. Future timestamps (clock skew) yield a
                        // negative chrono::Duration whose .to_std() returns Err,
                        // mapping to age=0 (fresh). This is correct: only the
                        // agent writes to episodic_memory so future-dated entries
                        // are clock-skew artifacts, not attacker-injectable.
                        let age = (now - created.with_timezone(&chrono::Utc))
                            .to_std()
                            .map(|d| d.as_secs_f64() / 86_400.0)
                            .unwrap_or(0.0);
                        (id, age)
                    })
            })
            .collect()
        }; // conn dropped here — DB connection released before mutation loop

        for result in results.iter_mut() {
            if result.source_table != "episodic_memory" {
                continue;
            }
            if result.source_id.is_empty() {
                // FTS-only results have no source_id and can't be looked up
                // in episodic_memory. Apply a conservative default penalty so
                // they don't bypass decay and outrank properly-aged results.
                result.similarity *= 0.5;
                continue;
            }
            if let Some(&age) = age_map.get(&result.source_id) {
                let decay_factor = (0.5_f64).powf(age / self.decay_half_life_days);
                // Floor at 0.05 so very old memories remain findable — they
                // rank lower but never become completely invisible.
                let clamped = decay_factor.max(0.05);
                result.similarity *= clamped;
            }
        }

        // Re-sort by adjusted similarity, descending
        results.sort_by(|a, b| {
            b.similarity
                .partial_cmp(&a.similarity)
                .unwrap_or(std::cmp::Ordering::Equal)
        });
    }

    fn retrieve_procedural(&self, db: &Database, budget_tokens: usize) -> Option<String> {
        if budget_tokens == 0 {
            return None;
        }

        // Retrieve all procedural entries and present those with meaningful history
        let conn = db.conn();
        let mut stmt = conn
            .prepare(
                "SELECT name, steps, success_count, failure_count FROM procedural_memory \
                 WHERE success_count > 0 OR failure_count > 0 \
                 ORDER BY success_count + failure_count DESC LIMIT 5",
            )
            .ok()?;

        let rows: Vec<(String, String, i64, i64)> = stmt
            .query_map([], |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, String>(1)?,
                    row.get::<_, i64>(2)?,
                    row.get::<_, i64>(3)?,
                ))
            })
            .inspect_err(|e| tracing::warn!("failed to query tool experience: {e}"))
            .ok()?
            .filter_map(|r| {
                r.inspect_err(|e| tracing::warn!("skipping corrupted tool experience row: {e}"))
                    .ok()
            })
            .collect();

        if rows.is_empty() {
            return None;
        }

        let mut text = String::from("[Tool Experience]\n");
        let mut used = estimate_tokens(&text);

        for (name, _steps, successes, failures) in &rows {
            let total = *successes + *failures;
            let rate = if total > 0 {
                (*successes as f64 / total as f64 * 100.0) as u32
            } else {
                0
            };
            let line = format!("- {name}: {successes}/{total} success ({rate}%)\n");
            let line_tokens = estimate_tokens(&line);
            if used + line_tokens > budget_tokens {
                break;
            }
            text.push_str(&line);
            used += line_tokens;
        }

        if text.len() > "[Tool Experience]\n".len() {
            Some(text)
        } else {
            None
        }
    }

    fn retrieve_relationships(
        &self,
        db: &Database,
        query: &str,
        budget_tokens: usize,
    ) -> Option<String> {
        if budget_tokens == 0 {
            return None;
        }

        let conn = db.conn();
        let mut stmt = conn
            .prepare(
                "SELECT entity_id, entity_name, trust_score, interaction_count \
                 FROM relationship_memory ORDER BY interaction_count DESC LIMIT 5",
            )
            .ok()?;

        let rows: Vec<(String, Option<String>, f64, i64)> = stmt
            .query_map([], |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, Option<String>>(1)?,
                    row.get::<_, f64>(2)?,
                    row.get::<_, i64>(3)?,
                ))
            })
            .inspect_err(|e| tracing::warn!("failed to query relationship memory: {e}"))
            .ok()?
            .filter_map(|r| {
                r.inspect_err(|e| tracing::warn!("skipping corrupted relationship row: {e}"))
                    .ok()
            })
            .collect();

        if rows.is_empty() {
            return None;
        }

        // Only include entities that might be relevant: name appears in query, or high interaction count
        let query_lower = query.to_lowercase();
        let relevant: Vec<_> = rows
            .into_iter()
            .filter(|(id, name, _, count)| {
                *count > 2
                    || query_lower.contains(&id.to_lowercase())
                    || name
                        .as_ref()
                        .is_some_and(|n| query_lower.contains(&n.to_lowercase()))
            })
            .collect();

        if relevant.is_empty() {
            return None;
        }

        let mut text = String::from("[Known Entities]\n");
        let mut used = estimate_tokens(&text);

        for (entity_id, name, trust, count) in &relevant {
            let display = name.as_deref().unwrap_or(entity_id);
            let line = format!("- {display}: trust={trust:.1}, interactions={count}\n");
            let line_tokens = estimate_tokens(&line);
            if used + line_tokens > budget_tokens {
                break;
            }
            text.push_str(&line);
            used += line_tokens;
        }

        if text.len() > "[Known Entities]\n".len() {
            Some(text)
        } else {
            None
        }
    }
}

fn estimate_tokens(text: &str) -> usize {
    text.len().div_ceil(4)
}

// ── Content chunking ────────────────────────────────────────────

pub struct ChunkConfig {
    pub max_tokens: usize,
    pub overlap_tokens: usize,
}

impl Default for ChunkConfig {
    fn default() -> Self {
        Self {
            max_tokens: 512,
            overlap_tokens: 64,
        }
    }
}

pub struct Chunk {
    pub text: String,
    pub index: usize,
    pub start_char: usize,
    pub end_char: usize,
}

/// Snap a byte offset to the nearest char boundary at or before `pos`.
fn floor_char_boundary(text: &str, pos: usize) -> usize {
    if pos >= text.len() {
        return text.len();
    }
    let mut p = pos;
    while p > 0 && !text.is_char_boundary(p) {
        p -= 1;
    }
    p
}

/// Split text into overlapping chunks for embedding.
pub fn chunk_text(text: &str, config: &ChunkConfig) -> Vec<Chunk> {
    if text.is_empty() || config.max_tokens == 0 {
        return Vec::new();
    }

    let max_bytes = config.max_tokens * 4;
    let overlap_bytes = config.overlap_tokens * 4;

    if text.len() <= max_bytes {
        return vec![Chunk {
            text: text.to_string(),
            index: 0,
            start_char: 0,
            end_char: text.len(),
        }];
    }

    let step = max_bytes.saturating_sub(overlap_bytes).max(1);
    let mut chunks = Vec::new();
    let mut start = 0;

    while start < text.len() {
        let raw_end = floor_char_boundary(text, (start + max_bytes).min(text.len()));

        let end = find_break_point(text, start, raw_end);

        chunks.push(Chunk {
            text: text[start..end].to_string(),
            index: chunks.len(),
            start_char: start,
            end_char: end,
        });

        if end >= text.len() {
            break;
        }

        let advance = step.min(end - start).max(1);
        start = floor_char_boundary(text, start + advance);
    }

    chunks
}

fn find_break_point(text: &str, start: usize, raw_end: usize) -> usize {
    if raw_end >= text.len() {
        return text.len();
    }

    let search_start = floor_char_boundary(text, start + (raw_end - start) / 2);
    let window = &text[search_start..raw_end];

    if let Some(pos) = window.rfind("\n\n") {
        return search_start + pos + 2;
    }
    for delim in [". ", ".\n", "? ", "! "] {
        if let Some(pos) = window.rfind(delim) {
            return search_start + pos + delim.len();
        }
    }
    if let Some(pos) = window.rfind(' ') {
        return search_start + pos + 1;
    }

    raw_end
}

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

    fn test_db() -> Database {
        Database::new(":memory:").unwrap()
    }

    fn default_config() -> MemoryConfig {
        MemoryConfig::default()
    }

    #[test]
    fn retriever_empty_db_returns_empty() {
        let db = test_db();
        let retriever = MemoryRetriever::new(default_config());
        let session_id = roboticus_db::sessions::find_or_create(&db, "test-agent", None).unwrap();
        let result = retriever.retrieve(&db, &session_id, "hello", None, ComplexityLevel::L1);
        assert!(result.is_empty());
    }

    #[test]
    fn retriever_returns_working_memory() {
        let db = test_db();
        let retriever = MemoryRetriever::new(default_config());
        let session_id = roboticus_db::sessions::find_or_create(&db, "test-agent", None).unwrap();

        roboticus_db::memory::store_working(&db, &session_id, "goal", "find documentation", 8)
            .unwrap();

        let result = retriever.retrieve(&db, &session_id, "hello", None, ComplexityLevel::L2);
        assert!(result.contains("Working Memory"));
        assert!(result.contains("find documentation"));
    }

    #[test]
    fn retriever_skips_turn_summary_working_entries() {
        let db = test_db();
        let retriever = MemoryRetriever::new(default_config());
        let session_id = roboticus_db::sessions::find_or_create(&db, "test-agent", None).unwrap();

        roboticus_db::memory::store_working(
            &db,
            &session_id,
            "turn_summary",
            "Good to be back on familiar ground.",
            9,
        )
        .unwrap();
        roboticus_db::memory::store_working(&db, &session_id, "goal", "fix Telegram loop", 8)
            .unwrap();

        let result = retriever.retrieve(&db, &session_id, "telegram", None, ComplexityLevel::L2);
        assert!(result.contains("Working Memory"));
        assert!(result.contains("fix Telegram loop"));
        assert!(!result.contains("Good to be back on familiar ground."));
    }

    #[test]
    fn retriever_returns_relevant_memories() {
        let db = test_db();
        let retriever = MemoryRetriever::new(default_config());
        let session_id = roboticus_db::sessions::find_or_create(&db, "test-agent", None).unwrap();

        roboticus_db::memory::store_semantic(&db, "facts", "sky", "the sky is blue", 0.9).unwrap();

        let result = retriever.retrieve(&db, &session_id, "sky", None, ComplexityLevel::L2);
        assert!(result.contains("Active Memory"));
    }

    #[test]
    fn retriever_returns_procedural_experience() {
        let db = test_db();
        let retriever = MemoryRetriever::new(default_config());
        let session_id = roboticus_db::sessions::find_or_create(&db, "test-agent", None).unwrap();

        roboticus_db::memory::store_procedural(&db, "web_search", "search the web").unwrap();
        roboticus_db::memory::record_procedural_success(&db, "web_search").unwrap();
        roboticus_db::memory::record_procedural_success(&db, "web_search").unwrap();

        let result = retriever.retrieve(&db, &session_id, "search", None, ComplexityLevel::L2);
        assert!(result.contains("Tool Experience"));
        assert!(result.contains("web_search"));
    }

    #[test]
    fn retriever_returns_relationships() {
        let db = test_db();
        let retriever = MemoryRetriever::new(default_config());
        let session_id = roboticus_db::sessions::find_or_create(&db, "test-agent", None).unwrap();

        roboticus_db::memory::store_relationship(&db, "user-1", "Jon", 0.9).unwrap();
        // Need > 2 interactions or name in query
        let result = retriever.retrieve(&db, &session_id, "Jon", None, ComplexityLevel::L2);
        assert!(result.contains("Known Entities") || result.contains("Jon"));
    }

    #[test]
    fn retriever_respects_zero_budget() {
        let config = MemoryConfig {
            working_budget_pct: 0.0,
            episodic_budget_pct: 0.0,
            semantic_budget_pct: 0.0,
            procedural_budget_pct: 0.0,
            relationship_budget_pct: 100.0,
            ..default_config()
        };
        let db = test_db();
        let retriever = MemoryRetriever::new(config);
        let session_id = roboticus_db::sessions::find_or_create(&db, "test-agent", None).unwrap();

        roboticus_db::memory::store_working(&db, &session_id, "goal", "test", 5).unwrap();

        let result = retriever.retrieve(&db, &session_id, "test", None, ComplexityLevel::L0);
        assert!(!result.contains("Working Memory"));
    }

    // ── Chunker tests ───────────────────────────────────────────

    #[test]
    fn chunk_empty_text() {
        let chunks = chunk_text("", &ChunkConfig::default());
        assert!(chunks.is_empty());
    }

    #[test]
    fn chunk_short_text() {
        let text = "This is a short sentence.";
        let chunks = chunk_text(text, &ChunkConfig::default());
        assert_eq!(chunks.len(), 1);
        assert_eq!(chunks[0].text, text);
        assert_eq!(chunks[0].index, 0);
    }

    #[test]
    fn chunk_long_text_produces_overlapping_chunks() {
        let text = "word ".repeat(1000);
        let config = ChunkConfig {
            max_tokens: 50,
            overlap_tokens: 10,
        };
        let chunks = chunk_text(&text, &config);
        assert!(chunks.len() > 1);

        for (i, chunk) in chunks.iter().enumerate() {
            assert_eq!(chunk.index, i);
            assert!(!chunk.text.is_empty());
        }

        // Verify continuity: each chunk's start is before the previous chunk's end
        for i in 1..chunks.len() {
            assert!(chunks[i].start_char < chunks[i - 1].end_char);
        }
    }

    #[test]
    fn chunk_respects_sentence_boundaries() {
        let text = "First sentence. Second sentence. Third sentence. Fourth sentence. Fifth sentence. \
                    Sixth sentence. Seventh sentence. Eighth sentence. Ninth sentence. Tenth sentence.";
        let config = ChunkConfig {
            max_tokens: 20,
            overlap_tokens: 5,
        };
        let chunks = chunk_text(text, &config);
        // Chunks should end at sentence boundaries when possible
        for chunk in &chunks {
            if chunk.end_char < text.len() {
                let ends_at_boundary = chunk.text.ends_with(". ")
                    || chunk.text.ends_with('.')
                    || chunk.text.ends_with(' ');
                assert!(
                    ends_at_boundary,
                    "chunk should end at a boundary: {:?}",
                    &chunk.text[chunk.text.len().saturating_sub(10)..]
                );
            }
        }
    }

    #[test]
    fn chunk_covers_full_text() {
        let text = "a ".repeat(500);
        let config = ChunkConfig {
            max_tokens: 25,
            overlap_tokens: 5,
        };
        let chunks = chunk_text(&text, &config);

        assert_eq!(chunks.first().unwrap().start_char, 0);
        assert_eq!(chunks.last().unwrap().end_char, text.len());
    }

    #[test]
    fn chunk_zero_max_tokens() {
        let chunks = chunk_text(
            "some text",
            &ChunkConfig {
                max_tokens: 0,
                overlap_tokens: 0,
            },
        );
        assert!(chunks.is_empty());
    }

    #[test]
    fn estimate_tokens_basic() {
        assert_eq!(estimate_tokens(""), 0);
        assert_eq!(estimate_tokens("abcd"), 1);
        assert_eq!(estimate_tokens("hello world!"), 3);
    }

    #[test]
    fn chunk_multibyte_does_not_panic() {
        let text = "Hello \u{1F600} world. ".repeat(200);
        let config = ChunkConfig {
            max_tokens: 20,
            overlap_tokens: 5,
        };
        let chunks = chunk_text(&text, &config);
        assert!(chunks.len() > 1);
        for chunk in &chunks {
            assert!(!chunk.text.is_empty());
            // Verify each chunk is valid UTF-8 (would panic on slice if not)
            let _ = chunk.text.as_bytes();
        }
    }

    #[test]
    fn chunk_cjk_text() {
        let text = "\u{4F60}\u{597D}\u{4E16}\u{754C} ".repeat(300);
        let config = ChunkConfig {
            max_tokens: 15,
            overlap_tokens: 3,
        };
        let chunks = chunk_text(&text, &config);
        assert!(chunks.len() > 1);
        assert_eq!(chunks.first().unwrap().start_char, 0);
        assert_eq!(chunks.last().unwrap().end_char, text.len());
    }

    #[test]
    fn floor_char_boundary_ascii() {
        let text = "hello world";
        assert_eq!(floor_char_boundary(text, 5), 5);
        assert_eq!(floor_char_boundary(text, 0), 0);
        assert_eq!(floor_char_boundary(text, 100), text.len());
    }

    #[test]
    fn floor_char_boundary_multibyte() {
        // "café" = c(1) a(1) f(1) é(2) = 5 bytes total
        let text = "caf\u{00E9}";
        assert_eq!(text.len(), 5);
        // Position 4 is inside the 2-byte é, should snap back to 3
        assert_eq!(floor_char_boundary(text, 4), 3);
        // Position 3 is a valid boundary (start of é)
        assert_eq!(floor_char_boundary(text, 3), 3);
        // Position 5 >= len, returns len
        assert_eq!(floor_char_boundary(text, 5), 5);
    }

    #[test]
    fn floor_char_boundary_emoji() {
        let text = "a\u{1F600}b"; // a(1) + emoji(4) + b(1) = 6 bytes
        assert_eq!(text.len(), 6);
        // Position 2 is inside the emoji
        assert_eq!(floor_char_boundary(text, 2), 1);
        // Position 5 is the start of 'b'
        assert_eq!(floor_char_boundary(text, 5), 5);
    }

    #[test]
    fn estimate_tokens_rounding() {
        // div_ceil(1, 4) = 1
        assert_eq!(estimate_tokens("a"), 1);
        // div_ceil(5, 4) = 2
        assert_eq!(estimate_tokens("abcde"), 2);
        // div_ceil(8, 4) = 2
        assert_eq!(estimate_tokens("abcdefgh"), 2);
    }

    #[test]
    fn retriever_with_procedural_no_history() {
        // Procedural with no success/failure counts should return None
        let db = test_db();
        let retriever = MemoryRetriever::new(default_config());
        let session_id = roboticus_db::sessions::find_or_create(&db, "test-agent", None).unwrap();

        roboticus_db::memory::store_procedural(&db, "unused_tool", "a tool").unwrap();

        let result = retriever.retrieve(&db, &session_id, "test", None, ComplexityLevel::L2);
        assert!(
            !result.contains("Tool Experience"),
            "tools with no success/failure should not appear"
        );
    }

    #[test]
    fn chunk_with_paragraph_breaks() {
        let text = "Paragraph one content.\n\nParagraph two content.\n\nParagraph three content.\n\n\
                    Paragraph four content.\n\nParagraph five content.";
        let config = ChunkConfig {
            max_tokens: 15,
            overlap_tokens: 3,
        };
        let chunks = chunk_text(text, &config);
        // Should prefer breaking at paragraph boundaries
        for chunk in &chunks {
            if chunk.end_char < text.len() {
                // Many chunks should end at paragraph breaks
                let last_few = &chunk.text[chunk.text.len().saturating_sub(5)..];
                let has_good_break =
                    last_few.contains('\n') || last_few.contains(". ") || last_few.ends_with(' ');
                assert!(has_good_break, "chunk should end at a reasonable boundary");
            }
        }
    }

    #[test]
    fn chunk_config_default() {
        let config = ChunkConfig::default();
        assert_eq!(config.max_tokens, 512);
        assert_eq!(config.overlap_tokens, 64);
    }

    #[test]
    fn find_break_point_at_end_of_text() {
        let text = "Hello world.";
        assert_eq!(find_break_point(text, 0, text.len()), text.len());
    }

    #[test]
    fn retriever_relationships_high_interaction_count() {
        let db = test_db();
        let retriever = MemoryRetriever::new(default_config());
        let session_id = roboticus_db::sessions::find_or_create(&db, "test-agent", None).unwrap();

        // store_relationship uses ON CONFLICT to increment interaction_count
        // Calling it 4 times gives interaction_count > 2
        for _ in 0..4 {
            roboticus_db::memory::store_relationship(&db, "alice", "Alice Smith", 0.8).unwrap();
        }

        // Query that doesn't contain "alice" but high interaction count should still include it
        let result = retriever.retrieve(
            &db,
            &session_id,
            "some random query",
            None,
            ComplexityLevel::L2,
        );
        assert!(
            result.contains("Known Entities") && result.contains("Alice Smith"),
            "high interaction count entity should appear in results"
        );
    }
}