brainwires-agents 0.7.0

Agent orchestration, coordination, and lifecycle management for the Brainwires Agent Framework
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
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
//! Reflection Module for Error Detection and Correction
//!
//! Provides post-execution analysis to detect issues and suggest corrections.
//! Implements error classification, root cause analysis, and correction strategies.
//!
//! ## Reflection Flow
//!
//! ```text
//! Query Execution Result
//!//!//! ┌───────────────────┐
//! │  Analyze Result   │ ◄── Check for empty results, overflow, etc.
//! └─────────┬─────────┘
//!//!//! ┌───────────────────┐
//! │  Classify Issues  │ ◄── Determine error types and severity
//! └─────────┬─────────┘
//!//!//! ┌───────────────────┐
//! │  Suggest Fixes    │ ◄── Generate correction strategies
//! └─────────┬─────────┘
//!//!//! ┌───────────────────┐
//! │ Attempt Correction│ ◄── Try fixes with retry limit
//! └───────────────────┘
//! ```
//!
//! ## Error Types
//!
//! - `EmptyResult`: Query returned no results
//! - `ResultOverflow`: Too many results to be useful
//! - `EntityNotFound`: Referenced entity doesn't exist
//! - `RelationMismatch`: Relationship type doesn't apply
//! - `CoreferenceFailure`: Could not resolve reference
//! - `SchemaAlignment`: Query structure doesn't match data
//!
//! ## Example
//!
//! ```rust,ignore
//! let mut reflection = ReflectionModule::new(ReflectionConfig::default());
//!
//! let report = reflection.analyze(&query_core, &result, &graph);
//! if !report.issues.is_empty() {
//!     if reflection.attempt_correction(&mut report, &graph, &executor) {
//!         // Use corrected_result
//!     }
//! }
//! ```

use super::learning::LearningCoordinator;
use super::query_core::{QueryCore, QueryExpr, QueryOp, QueryResult, RelationType};
use brainwires_core::graph::RelationshipGraphT;
use std::collections::HashMap;

/// Types of errors that can be detected
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ErrorType {
    /// Query returned no results
    EmptyResult,
    /// Too many results (overflow threshold exceeded)
    ResultOverflow,
    /// Referenced entity was not found in the graph
    EntityNotFound(String),
    /// Relationship type doesn't match entities
    RelationMismatch(String),
    /// Coreference resolution failed
    CoreferenceFailure(String),
    /// Query structure doesn't align with schema
    SchemaAlignment(String),
    /// Execution timeout
    Timeout,
    /// Unknown error
    Unknown(String),
}

impl ErrorType {
    /// Get a human-readable description
    pub fn description(&self) -> String {
        match self {
            ErrorType::EmptyResult => "Query returned no results".to_string(),
            ErrorType::ResultOverflow => "Query returned too many results".to_string(),
            ErrorType::EntityNotFound(name) => format!("Entity '{}' not found", name),
            ErrorType::RelationMismatch(rel) => format!("Relationship '{}' does not apply", rel),
            ErrorType::CoreferenceFailure(ref_text) => {
                format!("Could not resolve reference '{}'", ref_text)
            }
            ErrorType::SchemaAlignment(msg) => format!("Schema alignment issue: {}", msg),
            ErrorType::Timeout => "Query execution timed out".to_string(),
            ErrorType::Unknown(msg) => format!("Unknown error: {}", msg),
        }
    }
}

/// Severity level for issues
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Severity {
    /// Informational - not a problem
    Info,
    /// Warning - may indicate a problem
    Warning,
    /// Error - query failed but may be recoverable
    Error,
    /// Critical - unrecoverable error
    Critical,
}

impl Severity {
    /// Get the severity as a string
    pub fn as_str(&self) -> &'static str {
        match self {
            Severity::Info => "info",
            Severity::Warning => "warning",
            Severity::Error => "error",
            Severity::Critical => "critical",
        }
    }
}

/// An issue detected during reflection
#[derive(Debug, Clone)]
pub struct Issue {
    /// Type of error
    pub error_type: ErrorType,
    /// Severity level
    pub severity: Severity,
    /// Human-readable message
    pub message: String,
    /// Suggested fixes
    pub suggested_fixes: Vec<SuggestedFix>,
    /// Source location in query (if applicable)
    pub source: Option<String>,
}

impl Issue {
    /// Create a new issue
    pub fn new(error_type: ErrorType, severity: Severity, message: &str) -> Self {
        Self {
            error_type,
            severity,
            message: message.to_string(),
            suggested_fixes: Vec::new(),
            source: None,
        }
    }

    /// Add a suggested fix
    pub fn with_fix(mut self, fix: SuggestedFix) -> Self {
        self.suggested_fixes.push(fix);
        self
    }

    /// Set the source location
    pub fn with_source(mut self, source: &str) -> Self {
        self.source = Some(source.to_string());
        self
    }
}

/// Suggested fix for an issue
#[derive(Debug, Clone)]
pub enum SuggestedFix {
    /// Retry with a modified query
    RetryWithQuery(QueryCore),
    /// Expand search scope by adding relationships
    ExpandScope {
        /// The relationship to expand search by.
        relation: String,
    },
    /// Narrow scope with a filter
    NarrowScope {
        /// The filter expression to apply.
        filter: String,
    },
    /// Suggest a different entity resolution
    ResolveEntity {
        /// The original entity name.
        original: String,
        /// The suggested replacement entity name.
        suggested: String,
    },
    /// Add a relationship that might be missing
    AddRelation {
        /// Source entity.
        from: String,
        /// Target entity.
        to: String,
        /// Relationship type.
        relation: String,
    },
    /// Requires manual intervention
    ManualIntervention(String),
}

impl SuggestedFix {
    /// Get a description of the fix
    pub fn description(&self) -> String {
        match self {
            SuggestedFix::RetryWithQuery(_) => "Retry with modified query".to_string(),
            SuggestedFix::ExpandScope { relation } => {
                format!("Expand scope to include {} relationships", relation)
            }
            SuggestedFix::NarrowScope { filter } => {
                format!("Narrow scope with filter: {}", filter)
            }
            SuggestedFix::ResolveEntity {
                original,
                suggested,
            } => {
                format!("Resolve '{}' as '{}'", original, suggested)
            }
            SuggestedFix::AddRelation { from, to, relation } => {
                format!("Add {} relationship from {} to {}", relation, from, to)
            }
            SuggestedFix::ManualIntervention(msg) => format!("Manual intervention: {}", msg),
        }
    }
}

/// Record of a correction attempt
#[derive(Debug, Clone)]
pub struct CorrectionRecord {
    /// The original issue
    pub issue: Issue,
    /// The fix that was attempted
    pub fix_applied: SuggestedFix,
    /// Whether the correction was successful
    pub success: bool,
    /// Timestamp
    pub timestamp: i64,
}

/// Reflection report
#[derive(Debug, Clone)]
pub struct ReflectionReport {
    /// Original query core
    pub query: QueryCore,
    /// Original result
    pub result: QueryResult,
    /// Issues detected
    pub issues: Vec<Issue>,
    /// Overall quality score (0.0 - 1.0)
    pub quality_score: f32,
    /// Whether correction was attempted
    pub correction_attempted: bool,
    /// Corrected query (if correction was attempted)
    pub corrected_query: Option<QueryCore>,
    /// Corrected result (if correction succeeded)
    pub corrected_result: Option<QueryResult>,
}

impl ReflectionReport {
    /// Create a new reflection report
    pub fn new(query: QueryCore, result: QueryResult) -> Self {
        Self {
            query,
            result,
            issues: Vec::new(),
            quality_score: 1.0,
            correction_attempted: false,
            corrected_query: None,
            corrected_result: None,
        }
    }

    /// Check if the result is acceptable
    pub fn is_acceptable(&self) -> bool {
        self.quality_score >= 0.5 && !self.issues.iter().any(|i| i.severity >= Severity::Error)
    }

    /// Get the highest severity issue
    pub fn max_severity(&self) -> Option<Severity> {
        self.issues.iter().map(|i| i.severity).max()
    }
}

/// Configuration for reflection
#[derive(Debug, Clone)]
pub struct ReflectionConfig {
    /// Maximum results before overflow warning
    pub max_results: usize,
    /// Minimum results before empty warning (if expecting results)
    pub min_results: usize,
    /// Maximum correction retries
    pub max_retries: u32,
    /// Whether to auto-apply simple corrections
    pub auto_correct: bool,
}

impl Default for ReflectionConfig {
    fn default() -> Self {
        Self {
            max_results: 100,
            min_results: 1,
            max_retries: 2,
            auto_correct: true,
        }
    }
}

/// Reflection module for analyzing and correcting query results
pub struct ReflectionModule {
    /// Configuration
    config: ReflectionConfig,
    /// Error pattern counts for learning
    error_patterns: HashMap<ErrorType, u32>,
    /// History of correction attempts
    correction_history: Vec<CorrectionRecord>,
}

impl ReflectionModule {
    /// Create a new reflection module
    pub fn new(config: ReflectionConfig) -> Self {
        Self {
            config,
            error_patterns: HashMap::new(),
            correction_history: Vec::new(),
        }
    }

    /// Analyze a query result and generate a reflection report
    pub fn analyze(
        &mut self,
        query: &QueryCore,
        result: &QueryResult,
        graph: &dyn RelationshipGraphT,
    ) -> ReflectionReport {
        let mut report = ReflectionReport::new(query.clone(), result.clone());

        // Check for execution errors
        if let Some(ref error) = result.error {
            report.issues.push(Issue::new(
                ErrorType::Unknown(error.clone()),
                Severity::Error,
                error,
            ));
            report.quality_score = 0.0;
            return report;
        }

        // Check for empty results
        if result.values.is_empty() && result.count != Some(0) {
            let issue = self.analyze_empty_result(query, graph);
            report.issues.push(issue);
            report.quality_score = 0.3;
        }

        // Check for result overflow
        if result.values.len() > self.config.max_results {
            let issue = Issue::new(
                ErrorType::ResultOverflow,
                Severity::Warning,
                &format!(
                    "Query returned {} results (max: {})",
                    result.values.len(),
                    self.config.max_results
                ),
            )
            .with_fix(SuggestedFix::NarrowScope {
                filter: "Add type or name filter".to_string(),
            });
            report.issues.push(issue);
            report.quality_score = 0.6;
        }

        // Validate entities in the query
        for (entity_name, _entity_type) in &query.entities {
            if graph.get_node(entity_name).is_none() {
                let similar = self.find_similar_entities(entity_name, graph);
                let mut issue = Issue::new(
                    ErrorType::EntityNotFound(entity_name.clone()),
                    Severity::Warning,
                    &format!("Entity '{}' not found in graph", entity_name),
                );

                if let Some(suggestion) = similar.first() {
                    issue = issue.with_fix(SuggestedFix::ResolveEntity {
                        original: entity_name.clone(),
                        suggested: suggestion.clone(),
                    });
                }

                report.issues.push(issue);
                report.quality_score = (report.quality_score - 0.2).max(0.0);
            }
        }

        // Validate relationships
        self.validate_relationships(query, graph, &mut report);

        // Update error pattern counts
        for issue in &report.issues {
            *self
                .error_patterns
                .entry(issue.error_type.clone())
                .or_insert(0) += 1;
        }

        report
    }

    /// Analyze why a result is empty
    fn analyze_empty_result(&self, query: &QueryCore, graph: &dyn RelationshipGraphT) -> Issue {
        // Check if entities exist
        for (entity_name, _) in &query.entities {
            if graph.get_node(entity_name).is_none() {
                return Issue::new(
                    ErrorType::EntityNotFound(entity_name.clone()),
                    Severity::Error,
                    &format!(
                        "Entity '{}' not found - query cannot return results",
                        entity_name
                    ),
                );
            }
        }

        // Check if the relationship type applies
        if let Some(relation_msg) = self.check_relationship_applicability(&query.root, graph) {
            return Issue::new(
                ErrorType::RelationMismatch(relation_msg.clone()),
                Severity::Error,
                &relation_msg,
            )
            .with_fix(SuggestedFix::ExpandScope {
                relation: "CoOccurs".to_string(),
            });
        }

        // Generic empty result
        Issue::new(
            ErrorType::EmptyResult,
            Severity::Warning,
            "Query returned no results",
        )
        .with_fix(SuggestedFix::ExpandScope {
            relation: "All".to_string(),
        })
    }

    /// Check if a relationship type applies to the entities
    fn check_relationship_applicability(
        &self,
        expr: &QueryExpr,
        graph: &dyn RelationshipGraphT,
    ) -> Option<String> {
        match expr {
            QueryExpr::Op(QueryOp::Join {
                relation,
                subject,
                object,
            }) => {
                // Get entity names
                let subject_name = match subject.as_ref() {
                    QueryExpr::Constant(name, _) => Some(name.as_str()),
                    _ => None,
                };
                let object_name = match object.as_ref() {
                    QueryExpr::Constant(name, _) => Some(name.as_str()),
                    _ => None,
                };

                // Check if any edges of this type exist for the entities
                if let Some(name) = subject_name.or(object_name) {
                    let edges = graph.get_edges(name);
                    if let Some(edge_type) = relation.to_edge_type()
                        && !edges.iter().any(|e| e.edge_type == edge_type)
                    {
                        return Some(format!(
                            "No {:?} relationships found for '{}'",
                            relation, name
                        ));
                    }
                }

                None
            }
            _ => None,
        }
    }

    /// Find similar entity names
    fn find_similar_entities(&self, name: &str, graph: &dyn RelationshipGraphT) -> Vec<String> {
        let candidates = graph.search(name, 5);
        candidates
            .iter()
            .map(|node| node.entity_name.clone())
            .collect()
    }

    /// Validate relationships in the query
    fn validate_relationships(
        &self,
        query: &QueryCore,
        graph: &dyn RelationshipGraphT,
        report: &mut ReflectionReport,
    ) {
        self.validate_expr(&query.root, graph, report);
    }

    #[allow(clippy::only_used_in_recursion)]
    fn validate_expr(
        &self,
        expr: &QueryExpr,
        graph: &dyn RelationshipGraphT,
        report: &mut ReflectionReport,
    ) {
        match expr {
            QueryExpr::Op(QueryOp::Join {
                relation,
                subject,
                object,
            }) => {
                // Check if the relation type is valid for the entity types
                if relation.to_edge_type().is_none()
                    && !matches!(
                        relation,
                        RelationType::HasType
                            | RelationType::HasError
                            | RelationType::CreatedAt
                            | RelationType::ModifiedAt
                    )
                    && let RelationType::Custom(name) = relation
                {
                    report.issues.push(
                        Issue::new(
                            ErrorType::RelationMismatch(name.clone()),
                            Severity::Warning,
                            &format!("Custom relationship '{}' may not exist", name),
                        )
                        .with_source(&format!("{:?}", relation)),
                    );
                }

                // Recursively validate sub-expressions
                self.validate_expr(subject, graph, report);
                self.validate_expr(object, graph, report);
            }
            QueryExpr::Op(QueryOp::And(exprs)) | QueryExpr::Op(QueryOp::Or(exprs)) => {
                for e in exprs {
                    self.validate_expr(e, graph, report);
                }
            }
            QueryExpr::Op(QueryOp::Filter { source, .. }) => {
                self.validate_expr(source, graph, report);
            }
            QueryExpr::Op(QueryOp::Count(inner)) => {
                self.validate_expr(inner, graph, report);
            }
            QueryExpr::Op(QueryOp::Superlative { source, .. }) => {
                self.validate_expr(source, graph, report);
            }
            _ => {}
        }
    }

    /// Validate a query core structure (before execution)
    pub fn validate_query_core(&self, query: &QueryCore) -> Vec<Issue> {
        let mut issues = Vec::new();

        // Check for missing entities
        if query.entities.is_empty() {
            issues.push(Issue::new(
                ErrorType::SchemaAlignment("No entities in query".to_string()),
                Severity::Warning,
                "Query does not reference any entities",
            ));
        }

        // Check for valid question type
        if matches!(
            query.question_type,
            super::query_core::QuestionType::Unknown
        ) {
            issues.push(Issue::new(
                ErrorType::SchemaAlignment("Unknown question type".to_string()),
                Severity::Info,
                "Could not determine question type",
            ));
        }

        issues
    }

    /// Attempt to correct issues in a report
    pub fn attempt_correction(
        &mut self,
        report: &mut ReflectionReport,
        graph: &dyn RelationshipGraphT,
        _executor: &super::query_core::QueryExecutor,
    ) -> bool {
        if !self.config.auto_correct {
            return false;
        }

        if report.issues.is_empty() {
            return true; // Nothing to correct
        }

        report.correction_attempted = true;

        // Try to apply fixes for each issue
        for issue in &report.issues {
            if issue.severity < Severity::Warning {
                continue;
            }

            for fix in &issue.suggested_fixes {
                match fix {
                    SuggestedFix::ResolveEntity {
                        original,
                        suggested,
                    } => {
                        // Try resolving to a different entity
                        if graph.get_node(suggested).is_some() {
                            // Create a corrected query by substituting the entity
                            let corrected =
                                self.substitute_entity(&report.query, original, suggested);
                            if let Some(corrected) = corrected {
                                report.corrected_query = Some(corrected);
                                // Note: Would re-execute here, but we don't have executor access
                                // in a way that allows us to return the result
                                self.record_correction(issue.clone(), fix.clone(), true);
                                return true;
                            }
                        }
                    }
                    SuggestedFix::ExpandScope { .. } => {
                        // Would need to modify query to use different relationship
                        // This is more complex and requires query rewriting
                    }
                    _ => {}
                }
            }
        }

        false
    }

    /// Substitute an entity in a query
    fn substitute_entity(
        &self,
        query: &QueryCore,
        original: &str,
        replacement: &str,
    ) -> Option<QueryCore> {
        let mut corrected = query.clone();

        // Update entities list
        for (name, _) in &mut corrected.entities {
            if name == original {
                *name = replacement.to_string();
            }
        }

        // Update the expression tree
        corrected.root = Self::substitute_in_expr(&query.root, original, replacement);

        Some(corrected)
    }

    fn substitute_in_expr(expr: &QueryExpr, original: &str, replacement: &str) -> QueryExpr {
        match expr {
            QueryExpr::Constant(name, entity_type) => {
                if name == original {
                    QueryExpr::Constant(replacement.to_string(), entity_type.clone())
                } else {
                    expr.clone()
                }
            }
            QueryExpr::Op(op) => QueryExpr::Op(match op {
                QueryOp::Join {
                    relation,
                    subject,
                    object,
                } => QueryOp::Join {
                    relation: relation.clone(),
                    subject: Box::new(Self::substitute_in_expr(subject, original, replacement)),
                    object: Box::new(Self::substitute_in_expr(object, original, replacement)),
                },
                QueryOp::And(exprs) => QueryOp::And(
                    exprs
                        .iter()
                        .map(|e| Self::substitute_in_expr(e, original, replacement))
                        .collect(),
                ),
                QueryOp::Or(exprs) => QueryOp::Or(
                    exprs
                        .iter()
                        .map(|e| Self::substitute_in_expr(e, original, replacement))
                        .collect(),
                ),
                QueryOp::Filter { source, predicate } => QueryOp::Filter {
                    source: Box::new(Self::substitute_in_expr(source, original, replacement)),
                    predicate: predicate.clone(),
                },
                QueryOp::Count(inner) => QueryOp::Count(Box::new(Self::substitute_in_expr(
                    inner,
                    original,
                    replacement,
                ))),
                QueryOp::Superlative {
                    source,
                    property,
                    direction,
                } => QueryOp::Superlative {
                    source: Box::new(Self::substitute_in_expr(source, original, replacement)),
                    property: property.clone(),
                    direction: direction.clone(),
                },
                _ => op.clone(),
            }),
            _ => expr.clone(),
        }
    }

    /// Record a correction attempt
    fn record_correction(&mut self, issue: Issue, fix: SuggestedFix, success: bool) {
        self.correction_history.push(CorrectionRecord {
            issue,
            fix_applied: fix,
            success,
            timestamp: chrono::Utc::now().timestamp(),
        });
    }

    /// Provide feedback to the learning coordinator
    pub fn provide_feedback(
        &self,
        report: &ReflectionReport,
        coordinator: &mut LearningCoordinator,
    ) {
        // Record the query outcome
        let success = report.is_acceptable();
        let result_count = report.result.values.len();

        coordinator.record_outcome(
            None, // Pattern ID not tracked here
            success,
            result_count,
            Some(&report.query),
            0, // Reflection doesn't track query execution timing
        );

        // Track specific error patterns for future avoidance
        for issue in &report.issues {
            if issue.severity >= Severity::Error {
                // This could be used to create negative patterns
                // that the learning system avoids
            }
        }
    }

    /// Get error statistics
    pub fn get_error_stats(&self) -> HashMap<ErrorType, u32> {
        self.error_patterns.clone()
    }

    /// Get correction success rate
    pub fn correction_success_rate(&self) -> f32 {
        if self.correction_history.is_empty() {
            return 0.0;
        }

        let successes = self.correction_history.iter().filter(|r| r.success).count();
        successes as f32 / self.correction_history.len() as f32
    }
}

impl Default for ReflectionModule {
    fn default() -> Self {
        Self::new(ReflectionConfig::default())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::seal::query_core::{QueryExpr, QueryResultValue, QuestionType};
    use brainwires_cognition::RelationshipGraph;
    use brainwires_core::graph::EntityType;

    fn create_test_query() -> QueryCore {
        QueryCore::new(
            QuestionType::Definition,
            QueryExpr::var("x"),
            vec![("main.rs".to_string(), EntityType::File)],
            "What is main.rs?".to_string(),
        )
    }

    #[test]
    fn test_analyze_empty_result() {
        let mut reflection = ReflectionModule::new(ReflectionConfig::default());
        let query = create_test_query();
        let result = QueryResult::empty();
        let graph = RelationshipGraph::new();

        let report = reflection.analyze(&query, &result, &graph);

        assert!(!report.issues.is_empty());
        assert!(report.issues.iter().any(|i| matches!(
            i.error_type,
            ErrorType::EmptyResult | ErrorType::EntityNotFound(_)
        )));
    }

    #[test]
    fn test_analyze_overflow_result() {
        let mut reflection = ReflectionModule::new(ReflectionConfig {
            max_results: 10,
            ..Default::default()
        });
        let query = create_test_query();

        // Create result with many values
        let mut values = Vec::new();
        for i in 0..20 {
            values.push(QueryResultValue {
                value: format!("entity_{}", i),
                entity_type: Some(EntityType::File),
                score: 0.8,
                metadata: std::collections::HashMap::new(),
            });
        }
        let result = crate::seal::query_core::QueryResult::with_values(values);
        let graph = RelationshipGraph::new();

        let report = reflection.analyze(&query, &result, &graph);

        assert!(
            report
                .issues
                .iter()
                .any(|i| i.error_type == ErrorType::ResultOverflow)
        );
    }

    #[test]
    fn test_validate_query_core() {
        let reflection = ReflectionModule::new(ReflectionConfig::default());

        // Query with no entities
        let query = QueryCore::new(
            QuestionType::Unknown,
            QueryExpr::var("x"),
            vec![],
            "Test".to_string(),
        );

        let issues = reflection.validate_query_core(&query);
        assert!(!issues.is_empty());
    }

    #[test]
    fn test_issue_creation() {
        let issue = Issue::new(ErrorType::EmptyResult, Severity::Warning, "No results")
            .with_fix(SuggestedFix::ExpandScope {
                relation: "All".to_string(),
            })
            .with_source("query_root");

        assert_eq!(issue.severity, Severity::Warning);
        assert_eq!(issue.suggested_fixes.len(), 1);
        assert!(issue.source.is_some());
    }

    #[test]
    fn test_severity_ordering() {
        assert!(Severity::Info < Severity::Warning);
        assert!(Severity::Warning < Severity::Error);
        assert!(Severity::Error < Severity::Critical);
    }

    #[test]
    fn test_reflection_report_acceptable() {
        let query = create_test_query();
        let result = QueryResult::empty();
        let mut report = ReflectionReport::new(query, result);

        report.quality_score = 0.7;
        assert!(report.is_acceptable());

        report.quality_score = 0.3;
        assert!(!report.is_acceptable());

        report.quality_score = 0.7;
        report
            .issues
            .push(Issue::new(ErrorType::EmptyResult, Severity::Error, "Error"));
        assert!(!report.is_acceptable());
    }

    #[test]
    fn test_suggested_fix_description() {
        let fix = SuggestedFix::ResolveEntity {
            original: "main".to_string(),
            suggested: "main.rs".to_string(),
        };

        let desc = fix.description();
        assert!(desc.contains("main"));
        assert!(desc.contains("main.rs"));
    }

    #[test]
    fn test_error_type_description() {
        let error = ErrorType::EntityNotFound("test.rs".to_string());
        let desc = error.description();
        assert!(desc.contains("test.rs"));
    }

    #[test]
    fn test_substitute_entity() {
        let reflection = ReflectionModule::new(ReflectionConfig::default());

        let query = QueryCore::new(
            QuestionType::Definition,
            QueryExpr::constant("main", EntityType::File),
            vec![("main".to_string(), EntityType::File)],
            "What is main?".to_string(),
        );

        let corrected = reflection.substitute_entity(&query, "main", "main.rs");
        assert!(corrected.is_some());

        let corrected = corrected.unwrap();
        assert!(corrected.entities.iter().any(|(name, _)| name == "main.rs"));
    }

    #[test]
    fn test_correction_success_rate() {
        let mut reflection = ReflectionModule::new(ReflectionConfig::default());

        assert_eq!(reflection.correction_success_rate(), 0.0);

        reflection.record_correction(
            Issue::new(ErrorType::EmptyResult, Severity::Warning, "test"),
            SuggestedFix::ExpandScope {
                relation: "All".to_string(),
            },
            true,
        );

        reflection.record_correction(
            Issue::new(ErrorType::EmptyResult, Severity::Warning, "test"),
            SuggestedFix::ExpandScope {
                relation: "All".to_string(),
            },
            false,
        );

        assert_eq!(reflection.correction_success_rate(), 0.5);
    }
}