roboticus-agent 0.11.3

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
use roboticus_core::config::MemoryConfig;
use tracing::{debug, warn};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MemoryBudgets {
    pub working: usize,
    pub episodic: usize,
    pub semantic: usize,
    pub procedural: usize,
    pub relationship: usize,
}

pub struct MemoryBudgetManager {
    config: MemoryConfig,
}

impl MemoryBudgetManager {
    pub fn new(config: MemoryConfig) -> Self {
        Self { config }
    }

    /// Distributes `total_tokens` across the five memory tiers based on config percentages.
    /// Any remainder from rounding is added to the working memory tier.
    pub fn allocate_budgets(&self, total_tokens: usize) -> MemoryBudgets {
        let working = pct(total_tokens, self.config.working_budget_pct);
        let episodic = pct(total_tokens, self.config.episodic_budget_pct);
        let semantic = pct(total_tokens, self.config.semantic_budget_pct);
        let procedural = pct(total_tokens, self.config.procedural_budget_pct);
        let relationship = pct(total_tokens, self.config.relationship_budget_pct);

        let allocated = working + episodic + semantic + procedural + relationship;
        let rollover = total_tokens.saturating_sub(allocated);

        MemoryBudgets {
            working: working + rollover,
            episodic,
            semantic,
            procedural,
            relationship,
        }
    }
}

fn pct(total: usize, percent: f64) -> usize {
    ((total as f64) * percent / 100.0).floor() as usize
}

// ── Post-turn memory ingestion ──────────────────────────────────

/// Classifies the type of a conversational turn for memory routing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TurnType {
    Reasoning,
    ToolUse,
    Creative,
    Financial,
    Social,
}

/// Classifies a turn based on user + assistant content and tool results.
pub fn classify_turn(
    user_msg: &str,
    assistant_msg: &str,
    tool_results: &[(String, String)],
) -> TurnType {
    if !tool_results.is_empty() {
        return TurnType::ToolUse;
    }
    // BUG-08: Only check user_msg for financial keywords, and require >= 2 matches
    // to avoid false-positives (e.g. "balance" in generic error messages).
    let user_lower = user_msg.to_lowercase();
    let financial_keywords = [
        "transfer",
        "balance",
        "wallet",
        "payment",
        "usdc",
        "send funds",
    ];
    let financial_hits = financial_keywords
        .iter()
        .filter(|kw| user_lower.contains(*kw))
        .count();
    if financial_hits >= 2 {
        return TurnType::Financial;
    }
    let combined = format!("{user_msg} {assistant_msg}").to_lowercase();
    if combined.contains("hello")
        || combined.contains("thanks")
        || combined.contains("please")
        || combined.contains("how are you")
    {
        return TurnType::Social;
    }
    if combined.contains("write a")
        || combined.contains("create a")
        || combined.contains("design a")
        || combined.contains("compose a")
        || combined.contains("draw")
        || combined.contains("generate a")
    {
        return TurnType::Creative;
    }
    TurnType::Reasoning
}

/// Ingests a completed turn into the appropriate memory tiers.
///
/// # Silent Degradation
///
/// This function returns `()` by design: each `db.store_*()` call is
/// independently wrapped in `if let Err(e) = ... { warn!(...) }`, so any
/// combination of memory-tier writes can fail without aborting the turn.
/// Tools whose output is derivable — the agent can re-run them to get
/// current data. Storing their output creates stale facts that the agent
/// later cites as truth (e.g., "23 tasks" when there are now 19).
fn is_derivable_tool(name: &str) -> bool {
    matches!(
        name,
        "list_directory"
            | "list-subagent-roster"
            | "get_subagent_status"
            | "get_runtime_context"
            | "get_memory_stats"
            | "list-open-tasks"
            | "list-available-skills"
            | "task-status"
            | "get_wallet_balance"
            | "read_file"
    )
}

/// This is intentional -- memory ingestion runs in a background
/// `tokio::spawn` and must not block the response path.  A future
/// improvement could return a count of failed operations for
/// observability (see BUG-060 in the bug ledger).
pub fn ingest_turn(
    db: &roboticus_db::Database,
    session_id: &str,
    user_msg: &str,
    assistant_msg: &str,
    tool_results: &[(String, String)],
) {
    let turn_type = classify_turn(user_msg, assistant_msg, tool_results);

    // Working memory: update active goals/context
    let summary = if assistant_msg.len() > 200 {
        &assistant_msg[..assistant_msg.floor_char_boundary(200)]
    } else {
        assistant_msg
    };
    if let Err(e) = roboticus_db::memory::store_working(db, session_id, "turn_summary", summary, 3)
    {
        warn!(error = %e, "failed to store working memory");
    }

    ingest_relationship_memory(db, session_id, user_msg, summary, turn_type);

    // Episodic: record significant events (tool use, financial operations).
    // Don't-store-derivable: skip read-only introspection tools whose output
    // can be re-derived by calling the tool again. Store the ACTION taken
    // (e.g., "delegated to sentinel"), not the OBSERVATION (e.g., "5 files
    // found"). This prevents stale-fact hallucination.
    match turn_type {
        TurnType::ToolUse => {
            for (tool_name, result) in tool_results {
                // Skip derivable tool outputs — these can be re-queried
                if is_derivable_tool(tool_name) {
                    debug!(
                        tool = tool_name,
                        "skipping derivable tool output from memory"
                    );
                    continue;
                }
                // Store action description, not full output
                let event = if result.len() > 200 {
                    format!(
                        "Executed '{tool_name}' (result: {}...)",
                        &result[..result.floor_char_boundary(150)]
                    )
                } else {
                    format!("Executed '{tool_name}': {result}")
                };
                if let Err(e) = roboticus_db::memory::store_episodic(db, "tool_use", &event, 7) {
                    warn!(error = %e, "failed to store episodic tool_use memory");
                }
            }
        }
        TurnType::Financial => {
            let event = format!("Financial interaction: {summary}");
            if let Err(e) = roboticus_db::memory::store_episodic(db, "financial", &event, 8) {
                warn!(error = %e, "failed to store episodic financial memory");
            }
        }
        _ => {}
    }

    // Semantic: extract factual information from responses longer than a threshold
    if assistant_msg.len() > 100
        && (turn_type == TurnType::Reasoning || turn_type == TurnType::Creative)
    {
        let key_prefix = format!("session:{session_id}:");
        let key = format!("{key_prefix}{}", uuid::Uuid::new_v4());
        match roboticus_db::memory::store_semantic(db, "learned", &key, summary, 0.6) {
            Ok(semantic_id) => {
                if let Err(e) = roboticus_db::memory::mark_semantic_stale_by_category_and_key_prefix(
                    db,
                    "learned",
                    &key_prefix,
                    &semantic_id,
                    "superseded_by_newer_session_summary",
                ) {
                    warn!(error = %e, session_id, "failed to mark older semantic memories stale");
                }
            }
            Err(e) => warn!(error = %e, "failed to store semantic memory"),
        }
    }

    // Procedural: track tool success/failure
    if turn_type == TurnType::ToolUse {
        for (tool_name, result) in tool_results {
            if is_tool_failure(result) {
                if let Err(e) = roboticus_db::memory::record_procedural_failure(db, tool_name) {
                    warn!(error = %e, tool = %tool_name, "failed to record procedural failure");
                }
            } else if let Err(e) = roboticus_db::memory::record_procedural_success(db, tool_name) {
                warn!(error = %e, tool = %tool_name, "failed to record procedural success");
            }
        }
    }
}

/// Heuristic: does the tool result text indicate a failure?
///
/// Checks for common error prefixes and patterns in tool output.  We lean
/// toward *not* marking ambiguous results as failures (false negatives are
/// cheaper than false positives in the procedural memory tier).
fn is_tool_failure(result: &str) -> bool {
    let lower = result.to_lowercase();
    let trimmed = lower.trim_start();

    // Explicit error/failure prefixes
    if trimmed.starts_with("error:")
        || trimmed.starts_with("error -")
        || trimmed.starts_with("failed:")
        || trimmed.starts_with("failure:")
        || trimmed.starts_with("fatal:")
        || trimmed.starts_with("panic:")
    {
        return true;
    }

    // Common structured error patterns
    if trimmed.starts_with("{\"error\"") || trimmed.starts_with("{\"err\"") {
        return true;
    }

    // Non-zero exit codes from shell tools.
    // Use word-boundary-aware matching to avoid "exit code 0" matching inside
    // "exit code 0137" (which would incorrectly classify as success).
    if trimmed.contains("exit code") || trimmed.contains("exit status") {
        // Exact "exit code 0" / "exit status 0" followed by non-digit → success.
        // We check that the 0 isn't followed by another digit.
        let is_zero_exit = |s: &str, prefix: &str| -> bool {
            if let Some(idx) = s.find(prefix) {
                let after = &s[idx + prefix.len()..];
                // next char must be non-digit or end-of-string to be "exit code 0"
                after.is_empty() || !after.starts_with(|c: char| c.is_ascii_digit())
            } else {
                false
            }
        };
        if is_zero_exit(trimmed, "exit code 0") || is_zero_exit(trimmed, "exit status 0") {
            return false;
        }
        return true;
    }

    false
}

fn ingest_relationship_memory(
    db: &roboticus_db::Database,
    session_id: &str,
    user_msg: &str,
    assistant_summary: &str,
    turn_type: TurnType,
) {
    let Some(session) = roboticus_db::sessions::get_session(db, session_id)
        .inspect_err(
            |e| warn!(error = %e, session_id, "failed to load session for relationship ingest"),
        )
        .ok()
        .flatten()
    else {
        return;
    };

    let Some((channel, peer_id)) = session.scope_key.as_deref().and_then(parse_peer_scope_key)
    else {
        return;
    };

    let entity_id = format!("peer:{channel}:{peer_id}");
    let entity_name = peer_id;
    let trust_score = match turn_type {
        TurnType::Social => 0.8,
        TurnType::Financial => 0.75,
        TurnType::ToolUse | TurnType::Reasoning | TurnType::Creative => 0.65,
    };
    let interaction_summary = summarize_relationship_interaction(user_msg, assistant_summary);
    if let Err(e) = roboticus_db::memory::store_relationship_interaction(
        db,
        &entity_id,
        entity_name,
        trust_score,
        interaction_summary.as_deref(),
    ) {
        warn!(error = %e, entity_id, "failed to store relationship memory");
    }
}

fn parse_peer_scope_key(scope_key: &str) -> Option<(&str, &str)> {
    let rest = scope_key.strip_prefix("peer:")?;
    let (channel, peer_id) = rest.split_once(':')?;
    if channel.is_empty() || peer_id.is_empty() {
        return None;
    }
    Some((channel, peer_id))
}

fn summarize_relationship_interaction(user_msg: &str, assistant_summary: &str) -> Option<String> {
    let user_summary = user_msg.trim();
    let assistant_summary = assistant_summary.trim();
    if user_summary.is_empty() && assistant_summary.is_empty() {
        return None;
    }

    let user_summary = if user_summary.len() > 120 {
        &user_summary[..user_summary.floor_char_boundary(120)]
    } else {
        user_summary
    };
    let assistant_summary = if assistant_summary.len() > 120 {
        &assistant_summary[..assistant_summary.floor_char_boundary(120)]
    } else {
        assistant_summary
    };

    Some(format!(
        "User: {user_summary}; Assistant: {assistant_summary}"
    ))
}

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

    fn default_config() -> MemoryConfig {
        MemoryConfig {
            working_budget_pct: 30.0,
            episodic_budget_pct: 25.0,
            semantic_budget_pct: 20.0,
            procedural_budget_pct: 15.0,
            relationship_budget_pct: 10.0,
            embedding_provider: None,
            embedding_model: None,
            hybrid_weight: 0.5,
            ann_index: false,
            similarity_threshold: 0.0,
            decay_half_life_days: 7.0,
            ann_activation_threshold: 1000,
        }
    }

    #[test]
    fn budget_allocation_matches_percentages() {
        let mgr = MemoryBudgetManager::new(default_config());
        let budgets = mgr.allocate_budgets(10_000);

        assert_eq!(budgets.working, 3_000);
        assert_eq!(budgets.episodic, 2_500);
        assert_eq!(budgets.semantic, 2_000);
        assert_eq!(budgets.procedural, 1_500);
        assert_eq!(budgets.relationship, 1_000);

        let sum = budgets.working
            + budgets.episodic
            + budgets.semantic
            + budgets.procedural
            + budgets.relationship;
        assert_eq!(sum, 10_000);
    }

    #[test]
    fn rollover_goes_to_working() {
        let mgr = MemoryBudgetManager::new(default_config());
        let budgets = mgr.allocate_budgets(99);

        let sum = budgets.working
            + budgets.episodic
            + budgets.semantic
            + budgets.procedural
            + budgets.relationship;
        assert_eq!(sum, 99, "all tokens must be distributed");
        assert!(budgets.working >= pct(99, 30.0));
    }

    #[test]
    fn zero_total_tokens() {
        let mgr = MemoryBudgetManager::new(default_config());
        let budgets = mgr.allocate_budgets(0);

        assert_eq!(
            budgets,
            MemoryBudgets {
                working: 0,
                episodic: 0,
                semantic: 0,
                procedural: 0,
                relationship: 0,
            }
        );
    }

    #[test]
    fn classify_turn_tool_use() {
        let results = vec![("echo".into(), "hello".into())];
        assert_eq!(
            classify_turn("test", "response", &results),
            TurnType::ToolUse
        );
    }

    #[test]
    fn classify_turn_financial() {
        assert_eq!(
            classify_turn("check my wallet balance", "Your balance is 42 USDC", &[]),
            TurnType::Financial
        );
    }

    #[test]
    fn classify_turn_social() {
        assert_eq!(
            classify_turn("hello how are you", "I'm great!", &[]),
            TurnType::Social
        );
    }

    #[test]
    fn classify_turn_creative() {
        assert_eq!(
            classify_turn("write a poem about rust", "Here's a poem...", &[]),
            TurnType::Creative
        );
    }

    #[test]
    fn classify_turn_reasoning() {
        assert_eq!(
            classify_turn("explain monads", "A monad is a design pattern...", &[]),
            TurnType::Reasoning
        );
    }

    #[test]
    fn ingest_turn_stores_memories() {
        let db = roboticus_db::Database::new(":memory:").unwrap();
        let session_id = roboticus_db::sessions::find_or_create(&db, "test-agent", None).unwrap();
        ingest_turn(
            &db,
            &session_id,
            "What is Rust?",
            "Rust is a systems programming language focused on safety and performance.",
            &[],
        );
        let working = roboticus_db::memory::retrieve_working(&db, &session_id).unwrap();
        assert!(
            !working.is_empty(),
            "should store turn summary in working memory"
        );
    }

    #[test]
    fn ingest_turn_with_tools_stores_episodic() {
        let db = roboticus_db::Database::new(":memory:").unwrap();
        let session_id = roboticus_db::sessions::find_or_create(&db, "test-agent", None).unwrap();
        roboticus_db::memory::store_procedural(&db, "echo", "echo tool").ok();
        ingest_turn(
            &db,
            &session_id,
            "echo hello",
            "Tool says: hello",
            &[("echo".into(), "hello".into())],
        );
        let episodic = roboticus_db::memory::retrieve_episodic(&db, 10).unwrap();
        assert!(
            !episodic.is_empty(),
            "should store tool use in episodic memory"
        );
    }

    #[test]
    fn ingest_turn_financial_stores_episodic() {
        let db = roboticus_db::Database::new(":memory:").unwrap();
        let session_id = roboticus_db::sessions::find_or_create(&db, "test-agent", None).unwrap();
        ingest_turn(
            &db,
            &session_id,
            "check my wallet balance",
            "Your balance is 42 USDC",
            &[],
        );
        let episodic = roboticus_db::memory::retrieve_episodic(&db, 10).unwrap();
        assert!(
            !episodic.is_empty(),
            "financial turn should store episodic memory"
        );
        assert!(
            episodic
                .iter()
                .any(|e| e.content.contains("Financial interaction")),
            "should prefix with 'Financial interaction'"
        );
    }

    #[test]
    fn ingest_turn_long_reasoning_stores_semantic() {
        let db = roboticus_db::Database::new(":memory:").unwrap();
        let session_id = roboticus_db::sessions::find_or_create(&db, "test-agent", None).unwrap();
        // assistant_msg > 100 chars + Reasoning turn type -> stores semantic
        let long_response = "A ".repeat(60); // 120 chars
        ingest_turn(&db, &session_id, "explain monads", &long_response, &[]);
        let semantic = roboticus_db::memory::retrieve_semantic(&db, "learned").unwrap();
        assert!(
            !semantic.is_empty(),
            "long reasoning turn should store semantic memory"
        );
        assert!(
            semantic[0]
                .key
                .starts_with(&format!("session:{session_id}:"))
        );
        assert_eq!(semantic[0].memory_state, "active");
    }

    #[test]
    fn ingest_turn_long_creative_stores_semantic() {
        let db = roboticus_db::Database::new(":memory:").unwrap();
        let session_id = roboticus_db::sessions::find_or_create(&db, "test-agent", None).unwrap();
        let long_response = "B ".repeat(60); // 120 chars
        ingest_turn(
            &db,
            &session_id,
            "write a poem about Rust",
            &long_response,
            &[],
        );
        let semantic = roboticus_db::memory::retrieve_semantic(&db, "learned").unwrap();
        assert!(
            !semantic.is_empty(),
            "long creative turn should store semantic memory"
        );
    }

    #[test]
    fn ingest_turn_short_reasoning_skips_semantic() {
        let db = roboticus_db::Database::new(":memory:").unwrap();
        let session_id = roboticus_db::sessions::find_or_create(&db, "test-agent", None).unwrap();
        // assistant_msg <= 100 chars => no semantic storage
        ingest_turn(&db, &session_id, "explain monads", "short answer", &[]);
        let semantic = roboticus_db::memory::retrieve_semantic(&db, "learned").unwrap();
        assert!(
            semantic.is_empty(),
            "short reasoning turn should not store semantic memory"
        );
    }

    #[test]
    fn ingest_turn_truncates_long_summary() {
        let db = roboticus_db::Database::new(":memory:").unwrap();
        let session_id = roboticus_db::sessions::find_or_create(&db, "test-agent", None).unwrap();
        // assistant_msg > 200 chars -> summary truncated to first 200
        let long_response = "X".repeat(300);
        ingest_turn(&db, &session_id, "explain something", &long_response, &[]);
        let working = roboticus_db::memory::retrieve_working(&db, &session_id).unwrap();
        assert!(!working.is_empty());
        // The stored summary should be at most 200 chars
        for entry in &working {
            assert!(
                entry.content.len() <= 200,
                "working memory summary should be truncated to 200 chars, got {}",
                entry.content.len()
            );
        }
    }

    #[test]
    fn ingest_turn_records_procedural_success() {
        let db = roboticus_db::Database::new(":memory:").unwrap();
        let session_id = roboticus_db::sessions::find_or_create(&db, "test-agent", None).unwrap();
        roboticus_db::memory::store_procedural(&db, "custom_tool", "a tool").ok();
        ingest_turn(
            &db,
            &session_id,
            "use custom_tool",
            "done",
            &[("custom_tool".into(), "success".into())],
        );
        // This exercises the procedural success recording path
        // The test passes if no panic occurs
    }

    #[test]
    fn truncation_emoji_at_boundary() {
        // 🦀 is 4 bytes; 198 ASCII + 🦀 = 202 bytes, slice at 200 would split the emoji
        let msg = format!("{}{}", "A".repeat(198), "🦀");
        assert!(msg.len() == 202);
        let summary = if msg.len() > 200 {
            &msg[..msg.floor_char_boundary(200)]
        } else {
            &msg
        };
        assert!(summary.len() <= 200);
        assert!(summary.is_char_boundary(summary.len()));
    }

    #[test]
    fn truncation_cjk_near_boundary() {
        // CJK characters are 3 bytes each; 199 ASCII + 中 = 202 bytes
        let msg = format!("{}{}", "B".repeat(199), "中");
        assert!(msg.len() == 202);
        let summary = if msg.len() > 200 {
            &msg[..msg.floor_char_boundary(200)]
        } else {
            &msg
        };
        assert!(summary.len() <= 200);
        assert!(summary.is_char_boundary(summary.len()));
    }

    #[test]
    fn truncation_ascii_over_200() {
        let msg = "C".repeat(300);
        let summary = if msg.len() > 200 {
            &msg[..msg.floor_char_boundary(200)]
        } else {
            &msg
        };
        assert_eq!(summary.len(), 200);
    }

    #[test]
    fn classify_turn_financial_payment() {
        // BUG-08: need >= 2 financial keywords to classify as Financial
        assert_eq!(
            classify_turn(
                "make a payment of $50 from wallet",
                "Processing payment",
                &[]
            ),
            TurnType::Financial
        );
    }

    #[test]
    fn classify_turn_financial_transfer() {
        assert_eq!(
            classify_turn("transfer 10 USDC", "Transferring...", &[]),
            TurnType::Financial
        );
    }

    #[test]
    fn classify_turn_creative_compose() {
        assert_eq!(
            classify_turn("compose a sonnet", "Here is your sonnet...", &[]),
            TurnType::Creative
        );
    }

    #[test]
    fn classify_turn_creative_design() {
        assert_eq!(
            classify_turn("design a logo concept", "Here's the concept...", &[]),
            TurnType::Creative
        );
    }

    #[test]
    fn classify_turn_creative_generate() {
        assert_eq!(
            classify_turn("generate a story", "Once upon a time...", &[]),
            TurnType::Creative
        );
    }

    #[test]
    fn classify_turn_social_thanks() {
        assert_eq!(
            classify_turn("thanks for your help", "You're welcome!", &[]),
            TurnType::Social
        );
    }

    #[test]
    fn classify_turn_tool_use_takes_precedence() {
        // Even if content matches financial keywords, tool_results non-empty -> ToolUse
        assert_eq!(
            classify_turn(
                "check my wallet balance",
                "Done",
                &[("wallet".into(), "42".into())]
            ),
            TurnType::ToolUse
        );
    }

    // ── is_tool_failure tests ──────────────────────────────────────

    #[test]
    fn tool_failure_error_prefix() {
        assert!(is_tool_failure("Error: file not found"));
        assert!(is_tool_failure("error: connection refused"));
        assert!(is_tool_failure("  Error: indented"));
    }

    #[test]
    fn tool_failure_failed_prefix() {
        assert!(is_tool_failure("Failed: command returned non-zero"));
        assert!(is_tool_failure("failure: assertion failed"));
        assert!(is_tool_failure("fatal: not a git repository"));
        assert!(is_tool_failure("panic: index out of bounds"));
    }

    #[test]
    fn tool_failure_json_error() {
        assert!(is_tool_failure(r#"{"error": "not found"}"#));
        assert!(is_tool_failure(r#"{"err": "timeout"}"#));
    }

    #[test]
    fn tool_failure_exit_code() {
        assert!(is_tool_failure("process exited with exit code 1"));
        assert!(is_tool_failure("exit status 127"));
        assert!(!is_tool_failure("exit code 0 — success"));
        assert!(!is_tool_failure("exit status 0"));
    }

    #[test]
    fn tool_success_normal_output() {
        assert!(!is_tool_failure("hello world"));
        assert!(!is_tool_failure("42"));
        assert!(!is_tool_failure("file created successfully"));
        assert!(!is_tool_failure(""));
    }

    #[test]
    fn ingest_turn_records_procedural_failure() {
        let db = roboticus_db::Database::new(":memory:").unwrap();
        let session_id = roboticus_db::sessions::find_or_create(&db, "test-agent", None).unwrap();
        roboticus_db::memory::store_procedural(&db, "bad_tool", "a tool").ok();
        ingest_turn(
            &db,
            &session_id,
            "use bad_tool",
            "error occurred",
            &[("bad_tool".into(), "Error: something broke".into())],
        );
        // If the procedural entry exists, failure_count should have incremented.
        // The test passes if no panic occurs (silent degradation).
    }

    #[test]
    fn ingest_turn_peer_scope_stores_relationship_memory() {
        let db = roboticus_db::Database::new(":memory:").unwrap();
        let scope = roboticus_db::sessions::SessionScope::Peer {
            peer_id: "alice".into(),
            channel: "telegram".into(),
        };
        let session_id =
            roboticus_db::sessions::find_or_create(&db, "test-agent", Some(&scope)).unwrap();

        ingest_turn(
            &db,
            &session_id,
            "Can you remind me what we decided?",
            "We agreed to prioritize the Telegram stability work first.",
            &[],
        );

        let entry = roboticus_db::memory::retrieve_relationship(&db, "peer:telegram:alice")
            .unwrap()
            .expect("peer-scoped turns should create relationship memory");
        assert_eq!(entry.entity_name.as_deref(), Some("alice"));
        assert_eq!(entry.interaction_count, 1);
        assert!(
            entry
                .interaction_summary
                .as_deref()
                .unwrap_or("")
                .contains("prioritize the Telegram stability work"),
            "relationship interaction summary should capture the turn context"
        );
    }

    #[test]
    fn parse_peer_scope_key_parses_identity() {
        assert_eq!(
            parse_peer_scope_key("peer:telegram:user-42"),
            Some(("telegram", "user-42"))
        );
        assert_eq!(parse_peer_scope_key("agent"), None);
        assert_eq!(parse_peer_scope_key("peer::user-42"), None);
    }

    #[test]
    fn ingest_turn_marks_older_semantic_summaries_stale_per_session() {
        let db = roboticus_db::Database::new(":memory:").unwrap();
        let session_id = roboticus_db::sessions::find_or_create(&db, "test-agent", None).unwrap();
        let first = "Alpha incident resolved after rollback with careful verification and communication to every stakeholder involved. ".repeat(2);
        let second = "Beta migration is active with the new phased plan, improved monitoring, and rollback checkpoints in place. ".repeat(2);

        ingest_turn(&db, &session_id, "summarize alpha", &first, &[]);
        ingest_turn(&db, &session_id, "summarize beta", &second, &[]);

        let semantic = roboticus_db::memory::retrieve_semantic(&db, "learned").unwrap();
        assert_eq!(semantic.len(), 2);
        let active = semantic
            .iter()
            .filter(|entry| entry.memory_state == "active")
            .collect::<Vec<_>>();
        let stale = semantic
            .iter()
            .filter(|entry| entry.memory_state == "stale")
            .collect::<Vec<_>>();
        assert_eq!(active.len(), 1);
        assert_eq!(stale.len(), 1);
        assert!(active[0].value.contains("Beta migration is active"));
        assert!(stale[0].value.contains("Alpha incident resolved"));
        assert_eq!(
            stale[0].state_reason.as_deref(),
            Some("superseded_by_newer_session_summary")
        );
    }
}