trustformers 0.1.1

TrustformeRS - Rust port of Hugging Face Transformers
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
//! Advanced reasoning capabilities and context processing.

use super::types::*;
use crate::core::error::Result;

/// Advanced reasoning engine for conversational AI
#[derive(Debug)]
pub struct ReasoningEngine {
    pub config: ReasoningConfig,
}

impl ReasoningEngine {
    pub fn new(config: ReasoningConfig) -> Self {
        Self { config }
    }

    /// Process reasoning step in conversation context
    pub fn process_reasoning_step(
        &self,
        context: &mut ReasoningContext,
        input: &str,
        step_type: ReasoningType,
    ) -> Result<ReasoningStep> {
        if !self.config.enabled {
            return Ok(ReasoningStep {
                step_type,
                description: "Reasoning disabled".to_string(),
                inputs: vec![input.to_string()],
                output: input.to_string(),
                confidence: 1.0,
            });
        }

        let step = match step_type {
            ReasoningType::Logical => self.process_logical_reasoning(input, context),
            ReasoningType::Causal => self.process_causal_reasoning(input, context),
            ReasoningType::Analogical => self.process_analogical_reasoning(input, context),
            ReasoningType::Creative => self.process_creative_reasoning(input, context),
            ReasoningType::Mathematical => self.process_mathematical_reasoning(input, context),
            ReasoningType::Emotional => self.process_emotional_reasoning(input, context),
        }?;

        context.reasoning_chain.push(step.clone());
        context.confidence = self.update_context_confidence(context);

        Ok(step)
    }

    fn process_logical_reasoning(
        &self,
        input: &str,
        context: &ReasoningContext,
    ) -> Result<ReasoningStep> {
        let mut premises = Vec::new();
        let mut conclusion = String::new();

        // Simple logical pattern detection
        if input.contains("if") && input.contains("then") {
            let parts: Vec<&str> = input.split("then").collect();
            if parts.len() == 2 {
                premises.push(parts[0].trim().to_string());
                conclusion = parts[1].trim().to_string();
            }
        } else if input.contains("because") {
            let parts: Vec<&str> = input.split("because").collect();
            if parts.len() == 2 {
                conclusion = parts[0].trim().to_string();
                premises.push(parts[1].trim().to_string());
            }
        } else {
            // Fallback: treat input as premise for logical chain
            premises.push(input.to_string());
            conclusion = self.derive_logical_conclusion(&premises, context)?;
        }

        Ok(ReasoningStep {
            step_type: ReasoningType::Logical,
            description: "Applied logical reasoning to derive conclusion".to_string(),
            inputs: premises,
            output: conclusion,
            confidence: 0.8,
        })
    }

    fn process_causal_reasoning(
        &self,
        input: &str,
        context: &ReasoningContext,
    ) -> Result<ReasoningStep> {
        let mut causes = Vec::new();
        let mut effects = Vec::new();

        // Detect causal language patterns
        if input.contains("causes") || input.contains("leads to") {
            let cause_effect: Vec<&str> = if input.contains("causes") {
                input.split("causes").collect()
            } else {
                input.split("leads to").collect()
            };
            if cause_effect.len() >= 2 {
                causes.push(cause_effect[0].trim().to_string());
                effects.push(cause_effect[1].trim().to_string());
            }
        } else if input.contains("results in") {
            let parts: Vec<&str> = input.split("results in").collect();
            if parts.len() >= 2 {
                causes.push(parts[0].trim().to_string());
                effects.push(parts[1].trim().to_string());
            }
        } else {
            // Analyze for implicit causal relationships
            causes.push(input.to_string());
            effects.push(self.predict_effects(&causes, context)?);
        }

        let output = format!(
            "Causal relationship: {} -> {}",
            causes.join(", "),
            effects.join(", ")
        );

        Ok(ReasoningStep {
            step_type: ReasoningType::Causal,
            description: "Analyzed causal relationships".to_string(),
            inputs: causes,
            output,
            confidence: 0.7,
        })
    }

    fn process_analogical_reasoning(
        &self,
        input: &str,
        context: &ReasoningContext,
    ) -> Result<ReasoningStep> {
        let analogies = self.find_analogies(input, context)?;

        let output = if analogies.is_empty() {
            format!("Analyzed '{}' for analogical patterns", input)
        } else {
            format!("Found analogies: {}", analogies.join("; "))
        };

        Ok(ReasoningStep {
            step_type: ReasoningType::Analogical,
            description: "Searched for analogical relationships".to_string(),
            inputs: vec![input.to_string()],
            output,
            confidence: 0.6,
        })
    }

    fn process_creative_reasoning(
        &self,
        input: &str,
        context: &ReasoningContext,
    ) -> Result<ReasoningStep> {
        let creative_elements = self.extract_creative_elements(input)?;
        let output = self.generate_creative_response(input, &creative_elements, context)?;

        Ok(ReasoningStep {
            step_type: ReasoningType::Creative,
            description: "Applied creative reasoning and idea generation".to_string(),
            inputs: vec![input.to_string()],
            output,
            confidence: 0.7,
        })
    }

    fn process_mathematical_reasoning(
        &self,
        input: &str,
        context: &ReasoningContext,
    ) -> Result<ReasoningStep> {
        let math_expressions = self.extract_mathematical_expressions(input)?;
        let solutions = self.solve_mathematical_problems(&math_expressions)?;

        let output = if solutions.is_empty() {
            format!("Analyzed '{}' for mathematical content", input)
        } else {
            format!("Mathematical solutions: {}", solutions.join("; "))
        };

        Ok(ReasoningStep {
            step_type: ReasoningType::Mathematical,
            description: "Applied mathematical reasoning".to_string(),
            inputs: math_expressions,
            output,
            confidence: 0.9,
        })
    }

    fn process_emotional_reasoning(
        &self,
        input: &str,
        context: &ReasoningContext,
    ) -> Result<ReasoningStep> {
        let emotional_content = self.analyze_emotional_content(input)?;
        let empathetic_response = self.generate_empathetic_response(input, &emotional_content)?;

        Ok(ReasoningStep {
            step_type: ReasoningType::Emotional,
            description: "Applied emotional reasoning and empathy".to_string(),
            inputs: vec![input.to_string()],
            output: empathetic_response,
            confidence: 0.8,
        })
    }

    fn derive_logical_conclusion(
        &self,
        premises: &[String],
        context: &ReasoningContext,
    ) -> Result<String> {
        // Simple logical derivation (placeholder)
        if premises.is_empty() {
            return Ok("No premises available for logical conclusion".to_string());
        }

        // Look for patterns in existing reasoning chain
        let related_steps: Vec<_> = context
            .reasoning_chain
            .iter()
            .filter(|step| matches!(step.step_type, ReasoningType::Logical))
            .collect();

        if !related_steps.is_empty() {
            Ok(format!(
                "Based on premises '{}' and previous logical steps, conclusion follows",
                premises.join(", ")
            ))
        } else {
            Ok(format!(
                "Logical conclusion derived from: {}",
                premises.join(", ")
            ))
        }
    }

    fn predict_effects(&self, causes: &[String], context: &ReasoningContext) -> Result<String> {
        // Simple effect prediction (placeholder for actual causal model)
        if causes.is_empty() {
            return Ok("No causes specified for effect prediction".to_string());
        }

        Ok(format!(
            "Predicted effects based on causes: {}",
            causes.join(", ")
        ))
    }

    fn find_analogies(&self, input: &str, context: &ReasoningContext) -> Result<Vec<String>> {
        let mut analogies = Vec::new();

        // Simple analogy detection patterns
        if input.contains("like") || input.contains("similar to") {
            let parts: Vec<&str> = if input.contains("like") {
                input.split("like").collect()
            } else {
                input.split("similar to").collect()
            };
            if parts.len() >= 2 {
                analogies.push(format!("{} is like {}", parts[0].trim(), parts[1].trim()));
            }
        }

        // Check against previous reasoning steps for analogical patterns
        for step in &context.reasoning_chain {
            if let ReasoningType::Analogical = step.step_type {
                // Build on previous analogies
                if step.output.contains("analogy") {
                    analogies.push(format!("Related to previous analogy: {}", step.output));
                }
            }
        }

        Ok(analogies)
    }

    fn extract_creative_elements(&self, input: &str) -> Result<Vec<String>> {
        let mut elements = Vec::new();

        let creative_keywords = [
            "imagine",
            "creative",
            "innovative",
            "original",
            "unique",
            "novel",
            "inventive",
            "artistic",
            "design",
            "create",
        ];

        for keyword in &creative_keywords {
            if input.to_lowercase().contains(keyword) {
                elements.push(keyword.to_string());
            }
        }

        Ok(elements)
    }

    fn generate_creative_response(
        &self,
        input: &str,
        elements: &[String],
        context: &ReasoningContext,
    ) -> Result<String> {
        if elements.is_empty() {
            return Ok(format!("Applied creative analysis to: {}", input));
        }

        Ok(format!(
            "Creative exploration of '{}' focusing on: {}",
            input,
            elements.join(", ")
        ))
    }

    fn extract_mathematical_expressions(&self, input: &str) -> Result<Vec<String>> {
        let mut expressions = Vec::new();

        // Simple math pattern detection
        let math_patterns = [
            r"\d+\s*[+\-*/]\s*\d+",
            r"\d+\s*=\s*\d+",
            r"calculate|compute|solve",
            r"\d+%",
            r"\$\d+",
        ];

        for pattern in &math_patterns {
            if let Ok(regex) = regex::Regex::new(pattern) {
                for mat in regex.find_iter(input) {
                    expressions.push(mat.as_str().to_string());
                }
            }
        }

        Ok(expressions)
    }

    fn solve_mathematical_problems(&self, expressions: &[String]) -> Result<Vec<String>> {
        let mut solutions = Vec::new();

        for expr in expressions {
            // Very basic mathematical problem solving
            if expr.contains('+') {
                solutions.push(format!("Addition problem: {}", expr));
            } else if expr.contains('-') {
                solutions.push(format!("Subtraction problem: {}", expr));
            } else if expr.contains('*') {
                solutions.push(format!("Multiplication problem: {}", expr));
            } else if expr.contains('/') {
                solutions.push(format!("Division problem: {}", expr));
            } else {
                solutions.push(format!("Mathematical expression: {}", expr));
            }
        }

        Ok(solutions)
    }

    fn analyze_emotional_content(&self, input: &str) -> Result<EmotionalContent> {
        let mut emotions = Vec::new();
        let mut intensity: f32 = 0.0;

        let emotion_patterns = [
            (
                "joy",
                &["happy", "joyful", "excited", "cheerful", "delighted"] as &[&str],
            ),
            (
                "sadness",
                &["sad", "depressed", "sorrowful", "melancholy", "grief"],
            ),
            (
                "anger",
                &["angry", "furious", "irritated", "annoyed", "rage"],
            ),
            (
                "fear",
                &["afraid", "scared", "anxious", "worried", "nervous"],
            ),
            (
                "surprise",
                &["surprised", "amazed", "astonished", "shocked"],
            ),
            ("love", &["love", "affection", "adore", "cherish", "care"]),
        ];

        let content_lower = input.to_lowercase();

        for (emotion, keywords) in &emotion_patterns {
            for keyword in *keywords {
                if content_lower.contains(keyword) {
                    emotions.push(emotion.to_string());
                    intensity += 0.2;
                    break;
                }
            }
        }

        // Analyze intensity indicators
        if input.contains('!') {
            intensity += 0.3;
        }
        if input.chars().filter(|c| c.is_uppercase()).count() > input.len() / 3 {
            intensity += 0.2;
        }

        Ok(EmotionalContent {
            detected_emotions: emotions,
            intensity: intensity.min(1.0),
            valence: self.calculate_emotional_valence(&content_lower),
        })
    }

    fn calculate_emotional_valence(&self, content: &str) -> f32 {
        let positive_words = ["good", "great", "wonderful", "amazing", "love", "happy"];
        let negative_words = ["bad", "terrible", "awful", "hate", "sad", "angry"];

        let pos_count = positive_words.iter().filter(|word| content.contains(*word)).count();
        let neg_count = negative_words.iter().filter(|word| content.contains(*word)).count();

        if pos_count > neg_count {
            0.7
        } else if neg_count > pos_count {
            -0.7
        } else {
            0.0
        }
    }

    fn generate_empathetic_response(
        &self,
        input: &str,
        emotional_content: &EmotionalContent,
    ) -> Result<String> {
        if emotional_content.detected_emotions.is_empty() {
            return Ok(format!("Acknowledged emotional context in: {}", input));
        }

        let response = match emotional_content.valence {
            v if v > 0.5 => {
                format!(
                    "I can sense the positive emotions ({}) in your message",
                    emotional_content.detected_emotions.join(", ")
                )
            },
            v if v < -0.5 => {
                format!(
                    "I understand this might be difficult given the emotions you're experiencing ({})",
                    emotional_content.detected_emotions.join(", ")
                )
            },
            _ => {
                format!(
                    "I recognize the emotional complexity in your message involving {}",
                    emotional_content.detected_emotions.join(", ")
                )
            },
        };

        Ok(response)
    }

    fn update_context_confidence(&self, context: &ReasoningContext) -> f32 {
        if context.reasoning_chain.is_empty() {
            return 1.0;
        }

        let total_confidence: f32 =
            context.reasoning_chain.iter().map(|step| step.confidence).sum();

        let avg_confidence = total_confidence / context.reasoning_chain.len() as f32;

        // Adjust based on chain length and consistency
        let chain_factor = if context.reasoning_chain.len() > 5 {
            0.9 // Longer chains might have accumulated uncertainty
        } else {
            1.0
        };

        (avg_confidence * chain_factor).min(1.0)
    }

    /// Detect the primary reasoning type needed for input
    pub fn detect_reasoning_type(&self, input: &str) -> ReasoningType {
        let content_lower = input.to_lowercase();

        // Mathematical patterns
        if content_lower.contains("calculate")
            || content_lower.contains("math")
            || regex::Regex::new(r"\d+\s*[+\-*/]\s*\d+")
                .expect("static regex pattern is valid")
                .is_match(&content_lower)
        {
            return ReasoningType::Mathematical;
        }

        // Logical patterns
        if content_lower.contains("because")
            || content_lower.contains("therefore")
            || content_lower.contains("if") && content_lower.contains("then")
        {
            return ReasoningType::Logical;
        }

        // Causal patterns
        if content_lower.contains("causes")
            || content_lower.contains("leads to")
            || content_lower.contains("results in")
        {
            return ReasoningType::Causal;
        }

        // Creative patterns
        if content_lower.contains("imagine")
            || content_lower.contains("creative")
            || content_lower.contains("design")
        {
            return ReasoningType::Creative;
        }

        // Emotional patterns
        if content_lower.contains("feel")
            || content_lower.contains("emotion")
            || ["happy", "sad", "angry", "afraid"]
                .iter()
                .any(|&word| content_lower.contains(word))
        {
            return ReasoningType::Emotional;
        }

        // Analogical patterns
        if content_lower.contains("like")
            || content_lower.contains("similar")
            || content_lower.contains("analogous")
        {
            return ReasoningType::Analogical;
        }

        // Default to logical reasoning
        ReasoningType::Logical
    }

    /// Check if reasoning timeout is exceeded
    pub fn is_timeout_exceeded(&self, start_time: std::time::Instant) -> bool {
        start_time.elapsed().as_millis() > self.config.timeout_ms as u128
    }

    /// Generate reasoning summary
    pub fn generate_reasoning_summary(&self, context: &ReasoningContext) -> ReasoningSummary {
        let step_types: std::collections::HashMap<ReasoningType, usize> = context
            .reasoning_chain
            .iter()
            .fold(std::collections::HashMap::new(), |mut acc, step| {
                *acc.entry(step.step_type.clone()).or_insert(0) += 1;
                acc
            });

        let avg_confidence = if context.reasoning_chain.is_empty() {
            0.0
        } else {
            context.reasoning_chain.iter().map(|s| s.confidence).sum::<f32>()
                / context.reasoning_chain.len() as f32
        };

        ReasoningSummary {
            total_steps: context.reasoning_chain.len(),
            step_type_distribution: step_types,
            avg_confidence,
            final_confidence: context.confidence,
            current_goal: context.current_goal.clone(),
            evidence_count: context.evidence.len(),
            assumption_count: context.assumptions.len(),
        }
    }
}

/// Emotional content analysis
#[derive(Debug, Clone)]
pub struct EmotionalContent {
    pub detected_emotions: Vec<String>,
    pub intensity: f32,
    pub valence: f32, // -1.0 (negative) to 1.0 (positive)
}

/// Summary of reasoning process
#[derive(Debug, Clone)]
pub struct ReasoningSummary {
    pub total_steps: usize,
    pub step_type_distribution: std::collections::HashMap<ReasoningType, usize>,
    pub avg_confidence: f32,
    pub final_confidence: f32,
    pub current_goal: Option<String>,
    pub evidence_count: usize,
    pub assumption_count: usize,
}

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

    fn make_context() -> ReasoningContext {
        ReasoningContext {
            reasoning_chain: Vec::new(),
            current_goal: None,
            evidence: Vec::new(),
            assumptions: Vec::new(),
            confidence: 1.0,
        }
    }

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

    // ---- Engine construction ----

    #[test]
    fn test_engine_new_stores_config() {
        let config = default_config();
        let engine = ReasoningEngine::new(config.clone());
        assert_eq!(
            engine.config.enabled, config.enabled,
            "config must be stored correctly"
        );
    }

    // ---- detect_reasoning_type ----

    #[test]
    fn test_detect_reasoning_type_mathematical() {
        let engine = ReasoningEngine::new(default_config());
        let rt = engine.detect_reasoning_type("please calculate the sum of 3 + 5");
        assert_eq!(
            rt,
            ReasoningType::Mathematical,
            "'calculate' should detect Mathematical"
        );
    }

    #[test]
    fn test_detect_reasoning_type_logical_because() {
        let engine = ReasoningEngine::new(default_config());
        let rt = engine.detect_reasoning_type("It is cold because winter arrived.");
        assert_eq!(
            rt,
            ReasoningType::Logical,
            "'because' should detect Logical"
        );
    }

    #[test]
    fn test_detect_reasoning_type_causal() {
        let engine = ReasoningEngine::new(default_config());
        let rt = engine.detect_reasoning_type("Exercise leads to better health.");
        assert_eq!(rt, ReasoningType::Causal, "'leads to' should detect Causal");
    }

    #[test]
    fn test_detect_reasoning_type_creative() {
        let engine = ReasoningEngine::new(default_config());
        let rt = engine.detect_reasoning_type("Imagine a creative design for this project.");
        assert_eq!(
            rt,
            ReasoningType::Creative,
            "'imagine' and 'creative' should detect Creative"
        );
    }

    #[test]
    fn test_detect_reasoning_type_emotional() {
        let engine = ReasoningEngine::new(default_config());
        let rt = engine.detect_reasoning_type("I feel happy today.");
        assert_eq!(
            rt,
            ReasoningType::Emotional,
            "'feel' should detect Emotional"
        );
    }

    #[test]
    fn test_detect_reasoning_type_default_logical_fallback() {
        let engine = ReasoningEngine::new(default_config());
        let rt = engine.detect_reasoning_type("The earth orbits the sun.");
        // No special keyword → defaults to Logical
        assert_eq!(
            rt,
            ReasoningType::Logical,
            "generic text should default to Logical"
        );
    }

    // ---- process_reasoning_step ----

    #[test]
    fn test_process_logical_step_returns_step() {
        let engine = ReasoningEngine::new(default_config());
        let mut ctx = make_context();
        let result = engine.process_reasoning_step(&mut ctx, "if A then B", ReasoningType::Logical);
        assert!(result.is_ok(), "logical reasoning step must succeed");
        let step = result.expect("step must be Ok");
        assert_eq!(
            step.step_type,
            ReasoningType::Logical,
            "step type must be Logical"
        );
    }

    #[test]
    fn test_process_step_appends_to_chain() {
        let engine = ReasoningEngine::new(default_config());
        let mut ctx = make_context();
        let _ = engine
            .process_reasoning_step(&mut ctx, "something causes another", ReasoningType::Causal)
            .expect("step must succeed");
        assert_eq!(
            ctx.reasoning_chain.len(),
            1,
            "step must be appended to reasoning chain"
        );
    }

    #[test]
    fn test_process_multiple_steps_accumulate() {
        let engine = ReasoningEngine::new(default_config());
        let mut ctx = make_context();
        for _ in 0..3u32 {
            engine
                .process_reasoning_step(&mut ctx, "input", ReasoningType::Logical)
                .expect("step must succeed");
        }
        assert_eq!(
            ctx.reasoning_chain.len(),
            3,
            "three steps must accumulate in chain"
        );
    }

    #[test]
    fn test_process_step_disabled_engine_returns_passthrough() {
        let mut config = default_config();
        config.enabled = false;
        let engine = ReasoningEngine::new(config);
        let mut ctx = make_context();
        let step = engine
            .process_reasoning_step(&mut ctx, "test input", ReasoningType::Logical)
            .expect("disabled engine should still return a step");
        assert_eq!(
            step.output, "test input",
            "disabled engine must passthrough input as output"
        );
    }

    // ---- generate_reasoning_summary ----

    #[test]
    fn test_summary_empty_chain() {
        let engine = ReasoningEngine::new(default_config());
        let ctx = make_context();
        let summary = engine.generate_reasoning_summary(&ctx);
        assert_eq!(
            summary.total_steps, 0,
            "empty chain should yield 0 total_steps"
        );
        assert!(
            (summary.avg_confidence - 0.0).abs() < f32::EPSILON,
            "empty chain avg confidence should be 0"
        );
    }

    #[test]
    fn test_summary_reflects_step_count() {
        let engine = ReasoningEngine::new(default_config());
        let mut ctx = make_context();
        for _ in 0..4u32 {
            engine
                .process_reasoning_step(&mut ctx, "premise", ReasoningType::Logical)
                .expect("step must succeed");
        }
        let summary = engine.generate_reasoning_summary(&ctx);
        assert_eq!(
            summary.total_steps, 4,
            "summary total_steps must reflect chain length"
        );
    }

    #[test]
    fn test_summary_avg_confidence_within_bounds() {
        let engine = ReasoningEngine::new(default_config());
        let mut ctx = make_context();
        engine
            .process_reasoning_step(&mut ctx, "a therefore b", ReasoningType::Logical)
            .expect("step must succeed");
        let summary = engine.generate_reasoning_summary(&ctx);
        assert!(
            (0.0..=1.0).contains(&summary.avg_confidence),
            "avg_confidence must be in [0,1]"
        );
    }

    #[test]
    fn test_summary_goal_propagated() {
        let engine = ReasoningEngine::new(default_config());
        let ctx = ReasoningContext {
            reasoning_chain: Vec::new(),
            current_goal: Some("find answer".to_string()),
            evidence: Vec::new(),
            assumptions: Vec::new(),
            confidence: 1.0,
        };
        let summary = engine.generate_reasoning_summary(&ctx);
        assert_eq!(
            summary.current_goal.as_deref(),
            Some("find answer"),
            "summary must propagate the current goal"
        );
    }

    // ---- is_timeout_exceeded ----

    #[test]
    fn test_timeout_not_exceeded_immediately() {
        let engine = ReasoningEngine::new(default_config());
        let start = std::time::Instant::now();
        assert!(
            !engine.is_timeout_exceeded(start),
            "timeout must not be exceeded immediately after start"
        );
    }
}