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
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
//! Entity Enhancer - Semantic Entity Extraction
//!
//! Uses a provider to extract entities and relationships beyond
//! what regex patterns can capture, enriching the knowledge graph.

use std::sync::Arc;
use tracing::warn;

use brainwires_core::message::Message;
use brainwires_core::provider::{ChatOptions, Provider};

use super::InferenceTimer;

/// Enhanced entity type with semantic classification
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SemanticEntityType {
    /// A source file.
    File,
    /// A function or method.
    Function,
    /// A type, struct, class, or interface.
    Type,
    /// A variable or constant.
    Variable,
    /// A module or namespace.
    Module,
    /// A package, crate, or library.
    Package,

    /// A general domain concept.
    Concept,
    /// A design or architectural pattern.
    Pattern,
    /// An algorithm or computational technique.
    Algorithm,
    /// A communication or network protocol.
    Protocol,

    /// A CLI or shell command.
    Command,
    /// A runtime operation or action.
    Operation,
    /// A task or work item.
    Task,

    /// An error or exception.
    Error,
    /// A bug or known defect.
    Bug,
    /// A fix or patch for a defect.
    Fix,
    /// A product or code feature.
    Feature,

    /// A person or user.
    Person,
    /// A role or permission level.
    Role,

    /// A URL or web link.
    Url,
    /// A filesystem path.
    Path,
    /// A generic identifier or ID.
    Identifier,
}

impl SemanticEntityType {
    /// Parse from string
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> Option<Self> {
        let lower = s.to_lowercase();
        match lower.as_str() {
            "file" => Some(SemanticEntityType::File),
            "function" | "func" | "method" => Some(SemanticEntityType::Function),
            "type" | "struct" | "class" | "interface" => Some(SemanticEntityType::Type),
            "variable" | "var" | "const" => Some(SemanticEntityType::Variable),
            "module" | "mod" => Some(SemanticEntityType::Module),
            "package" | "crate" | "library" | "lib" => Some(SemanticEntityType::Package),
            "concept" => Some(SemanticEntityType::Concept),
            "pattern" => Some(SemanticEntityType::Pattern),
            "algorithm" | "algo" => Some(SemanticEntityType::Algorithm),
            "protocol" => Some(SemanticEntityType::Protocol),
            "command" | "cmd" => Some(SemanticEntityType::Command),
            "operation" | "op" => Some(SemanticEntityType::Operation),
            "task" => Some(SemanticEntityType::Task),
            "error" => Some(SemanticEntityType::Error),
            "bug" => Some(SemanticEntityType::Bug),
            "fix" => Some(SemanticEntityType::Fix),
            "feature" => Some(SemanticEntityType::Feature),
            "person" | "user" | "developer" => Some(SemanticEntityType::Person),
            "role" => Some(SemanticEntityType::Role),
            "url" | "link" => Some(SemanticEntityType::Url),
            "path" => Some(SemanticEntityType::Path),
            "identifier" | "id" => Some(SemanticEntityType::Identifier),
            _ => None,
        }
    }

    /// Convert to string
    pub fn as_str(&self) -> &'static str {
        match self {
            SemanticEntityType::File => "file",
            SemanticEntityType::Function => "function",
            SemanticEntityType::Type => "type",
            SemanticEntityType::Variable => "variable",
            SemanticEntityType::Module => "module",
            SemanticEntityType::Package => "package",
            SemanticEntityType::Concept => "concept",
            SemanticEntityType::Pattern => "pattern",
            SemanticEntityType::Algorithm => "algorithm",
            SemanticEntityType::Protocol => "protocol",
            SemanticEntityType::Command => "command",
            SemanticEntityType::Operation => "operation",
            SemanticEntityType::Task => "task",
            SemanticEntityType::Error => "error",
            SemanticEntityType::Bug => "bug",
            SemanticEntityType::Fix => "fix",
            SemanticEntityType::Feature => "feature",
            SemanticEntityType::Person => "person",
            SemanticEntityType::Role => "role",
            SemanticEntityType::Url => "url",
            SemanticEntityType::Path => "path",
            SemanticEntityType::Identifier => "identifier",
        }
    }
}

/// An entity extracted by LLM
#[derive(Clone, Debug)]
pub struct EnhancedEntity {
    /// Entity name/value
    pub name: String,
    /// Semantic type
    pub entity_type: SemanticEntityType,
    /// Confidence score (0.0-1.0)
    pub confidence: f32,
    /// Context where found
    pub context: Option<String>,
}

impl EnhancedEntity {
    /// Create a new enhanced entity with the given name, type, and confidence.
    pub fn new(name: String, entity_type: SemanticEntityType, confidence: f32) -> Self {
        Self {
            name,
            entity_type,
            confidence,
            context: None,
        }
    }

    /// Attach contextual information describing where the entity was found.
    pub fn with_context(mut self, context: String) -> Self {
        self.context = Some(context);
        self
    }
}

/// A semantic relationship between entities
#[derive(Clone, Debug)]
pub struct EnhancedRelationship {
    /// Source entity
    pub from: String,
    /// Target entity
    pub to: String,
    /// Relationship type
    pub relation_type: RelationType,
    /// Confidence score
    pub confidence: f32,
}

/// Types of relationships we detect semantically
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RelationType {
    /// A contains B (parent-child).
    Contains,
    /// A is defined inside B.
    DefinedIn,
    /// A imports B.
    Imports,
    /// A exports B.
    Exports,
    /// A extends or inherits from B.
    Extends,
    /// A implements the interface or trait B.
    Implements,

    /// A calls or invokes B.
    Calls,
    /// A uses or references B.
    Uses,
    /// A modifies B.
    Modifies,
    /// A creates or constructs B.
    Creates,
    /// A deletes or removes B.
    Deletes,

    /// A is semantically related to B.
    RelatedTo,
    /// A is similar to B.
    SimilarTo,
    /// A depends on B.
    DependsOn,
    /// A causes B.
    Causes,
    /// A fixes or resolves B.
    Fixes,
    /// A replaces B.
    Replaces,
}

impl RelationType {
    /// Parse a relation type from a string label.
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> Option<Self> {
        let lower = s.to_lowercase();
        match lower.as_str() {
            "contains" => Some(RelationType::Contains),
            "defined_in" | "definedin" => Some(RelationType::DefinedIn),
            "imports" => Some(RelationType::Imports),
            "exports" => Some(RelationType::Exports),
            "extends" => Some(RelationType::Extends),
            "implements" => Some(RelationType::Implements),
            "calls" => Some(RelationType::Calls),
            "uses" => Some(RelationType::Uses),
            "modifies" => Some(RelationType::Modifies),
            "creates" => Some(RelationType::Creates),
            "deletes" => Some(RelationType::Deletes),
            "related_to" | "relatedto" => Some(RelationType::RelatedTo),
            "similar_to" | "similarto" => Some(RelationType::SimilarTo),
            "depends_on" | "dependson" => Some(RelationType::DependsOn),
            "causes" => Some(RelationType::Causes),
            "fixes" => Some(RelationType::Fixes),
            "replaces" => Some(RelationType::Replaces),
            _ => None,
        }
    }

    /// Return the canonical string label for this relation type.
    pub fn as_str(&self) -> &'static str {
        match self {
            RelationType::Contains => "contains",
            RelationType::DefinedIn => "defined_in",
            RelationType::Imports => "imports",
            RelationType::Exports => "exports",
            RelationType::Extends => "extends",
            RelationType::Implements => "implements",
            RelationType::Calls => "calls",
            RelationType::Uses => "uses",
            RelationType::Modifies => "modifies",
            RelationType::Creates => "creates",
            RelationType::Deletes => "deletes",
            RelationType::RelatedTo => "related_to",
            RelationType::SimilarTo => "similar_to",
            RelationType::DependsOn => "depends_on",
            RelationType::Causes => "causes",
            RelationType::Fixes => "fixes",
            RelationType::Replaces => "replaces",
        }
    }
}

/// Result of entity enhancement
#[derive(Clone, Debug)]
pub struct EnhancementResult {
    /// Extracted entities
    pub entities: Vec<EnhancedEntity>,
    /// Extracted relationships
    pub relationships: Vec<EnhancedRelationship>,
    /// Extracted domain concepts
    pub concepts: Vec<String>,
    /// Whether LLM was used
    pub used_local_llm: bool,
}

impl EnhancementResult {
    /// Create an empty enhancement result (no entities, relationships, or concepts).
    pub fn empty() -> Self {
        Self {
            entities: Vec::new(),
            relationships: Vec::new(),
            concepts: Vec::new(),
            used_local_llm: false,
        }
    }

    /// Create an enhancement result from LLM-extracted data.
    pub fn from_local(
        entities: Vec<EnhancedEntity>,
        relationships: Vec<EnhancedRelationship>,
        concepts: Vec<String>,
    ) -> Self {
        Self {
            entities,
            relationships,
            concepts,
            used_local_llm: true,
        }
    }
}

/// Entity enhancer using a provider
pub struct EntityEnhancer {
    provider: Arc<dyn Provider>,
    model_id: String,
    /// Minimum confidence threshold
    min_confidence: f32,
    /// Maximum entities to extract per call
    max_entities: usize,
}

impl EntityEnhancer {
    /// Create a new entity enhancer
    pub fn new(provider: Arc<dyn Provider>, model_id: impl Into<String>) -> Self {
        Self {
            provider,
            model_id: model_id.into(),
            min_confidence: 0.6,
            max_entities: 20,
        }
    }

    /// Set minimum confidence threshold
    pub fn with_min_confidence(mut self, confidence: f32) -> Self {
        self.min_confidence = confidence.clamp(0.0, 1.0);
        self
    }

    /// Set max entities per extraction
    pub fn with_max_entities(mut self, max: usize) -> Self {
        self.max_entities = max.max(1);
        self
    }

    /// Extract semantic entities from text using the provider
    pub async fn extract_entities(&self, text: &str) -> Option<Vec<EnhancedEntity>> {
        let timer = InferenceTimer::new("extract_entities", &self.model_id);

        let prompt = self.build_entity_prompt(text);

        let messages = vec![Message::user(&prompt)];
        let options = ChatOptions::deterministic(200);

        match self.provider.chat(&messages, None, &options).await {
            Ok(response) => {
                let output = response.message.text_or_summary();
                let entities = self.parse_entities(&output);
                timer.finish(true);
                Some(entities)
            }
            Err(e) => {
                warn!(target: "local_llm", "Entity extraction failed: {}", e);
                timer.finish(false);
                None
            }
        }
    }

    /// Extract relationships between entities using the provider
    pub async fn extract_relationships(
        &self,
        entities: &[String],
        context: &str,
    ) -> Option<Vec<EnhancedRelationship>> {
        if entities.len() < 2 {
            return Some(Vec::new());
        }

        let timer = InferenceTimer::new("extract_relationships", &self.model_id);

        let prompt = self.build_relationship_prompt(entities, context);

        let messages = vec![Message::user(&prompt)];
        let options = ChatOptions::deterministic(150);

        match self.provider.chat(&messages, None, &options).await {
            Ok(response) => {
                let output = response.message.text_or_summary();
                let relationships = self.parse_relationships(&output);
                timer.finish(true);
                Some(relationships)
            }
            Err(e) => {
                warn!(target: "local_llm", "Relationship extraction failed: {}", e);
                timer.finish(false);
                None
            }
        }
    }

    /// Extract domain concepts from text using the provider
    pub async fn extract_concepts(&self, text: &str) -> Option<Vec<String>> {
        let timer = InferenceTimer::new("extract_concepts", &self.model_id);

        let prompt = self.build_concept_prompt(text);

        let messages = vec![Message::user(&prompt)];
        let options = ChatOptions::deterministic(100);

        match self.provider.chat(&messages, None, &options).await {
            Ok(response) => {
                let output = response.message.text_or_summary();
                let concepts = self.parse_concepts(&output);
                timer.finish(true);
                Some(concepts)
            }
            Err(e) => {
                warn!(target: "local_llm", "Concept extraction failed: {}", e);
                timer.finish(false);
                None
            }
        }
    }

    /// Full enhancement - extract entities, relationships, and concepts
    pub async fn enhance(&self, text: &str) -> EnhancementResult {
        // Extract entities first
        let entities = self.extract_entities(text).await.unwrap_or_default();

        // Extract relationships if we have entities
        let entity_names: Vec<String> = entities.iter().map(|e| e.name.clone()).collect();
        let relationships = self
            .extract_relationships(&entity_names, text)
            .await
            .unwrap_or_default();

        // Extract concepts
        let concepts = self.extract_concepts(text).await.unwrap_or_default();

        EnhancementResult::from_local(entities, relationships, concepts)
    }

    /// Heuristic entity extraction (pattern-based fallback)
    pub fn extract_heuristic(&self, text: &str) -> Vec<EnhancedEntity> {
        let mut entities = Vec::new();

        // URL pattern
        let url_pattern = regex::Regex::new(r#"https?://[^\s<>"']+"#).expect("valid url regex");
        for cap in url_pattern.find_iter(text) {
            entities.push(EnhancedEntity::new(
                cap.as_str().to_string(),
                SemanticEntityType::Url,
                0.9,
            ));
        }

        // Path-like patterns (beyond file extensions)
        let path_pattern =
            regex::Regex::new(r#"(?:^|[\s"'])(/[a-zA-Z0-9_./-]+)"#).expect("valid path regex");
        for cap in path_pattern.captures_iter(text) {
            if let Some(m) = cap.get(1) {
                let path = m.as_str();
                // Filter common false positives
                if path.len() > 3 && !path.starts_with("//") {
                    entities.push(EnhancedEntity::new(
                        path.to_string(),
                        SemanticEntityType::Path,
                        0.7,
                    ));
                }
            }
        }

        // Package/crate names (Rust-style)
        let crate_pattern = regex::Regex::new(r"(?:use|extern crate|mod)\s+([a-z_][a-z0-9_]*)")
            .expect("valid crate regex");
        for cap in crate_pattern.captures_iter(text) {
            if let Some(m) = cap.get(1) {
                entities.push(EnhancedEntity::new(
                    m.as_str().to_string(),
                    SemanticEntityType::Module,
                    0.8,
                ));
            }
        }

        // Problem/fix indicators
        let lower = text.to_lowercase();
        if lower.contains("bug") || lower.contains("issue") || lower.contains("problem") {
            // Look for identifiers near these words
            let bug_context =
                regex::Regex::new(r"(?i)(?:bug|issue|problem)\s*(?:#|:)?\s*(\d+|[A-Z]+-\d+)")
                    .expect("valid bug regex");
            for cap in bug_context.captures_iter(text) {
                if let Some(m) = cap.get(1) {
                    entities.push(EnhancedEntity::new(
                        m.as_str().to_string(),
                        SemanticEntityType::Bug,
                        0.85,
                    ));
                }
            }
        }

        if lower.contains("fix") || lower.contains("fixed") || lower.contains("resolved") {
            let fix_context = regex::Regex::new(r"(?i)fix(?:ed|es)?\s+(?:#|:)?\s*(\d+|[A-Z]+-\d+)")
                .expect("valid fix regex");
            for cap in fix_context.captures_iter(text) {
                if let Some(m) = cap.get(1) {
                    entities.push(EnhancedEntity::new(
                        m.as_str().to_string(),
                        SemanticEntityType::Fix,
                        0.85,
                    ));
                }
            }
        }

        // Feature indicators
        if lower.contains("feature") || lower.contains("implement") || lower.contains("add") {
            let feature_context =
                regex::Regex::new(r"(?i)(?:feature|implement|add)\s+(\w+(?:\s+\w+)?)")
                    .expect("valid feature regex");
            for cap in feature_context.captures_iter(text) {
                if let Some(m) = cap.get(1) {
                    let feature = m.as_str().trim();
                    if feature.len() > 2 && feature.len() < 50 {
                        entities.push(EnhancedEntity::new(
                            feature.to_string(),
                            SemanticEntityType::Feature,
                            0.6,
                        ));
                    }
                }
            }
        }

        entities
    }

    /// Build the entity extraction prompt
    fn build_entity_prompt(&self, text: &str) -> String {
        format!(
            r#"Extract named entities from this text. Focus on:
- Code elements: files, functions, types, modules, packages
- Domain concepts: patterns, algorithms, protocols
- Problems: errors, bugs, issues
- Actions: commands, operations, tasks

Text: "{}"

Output format (one per line):
TYPE: name

Example:
FUNCTION: process_data
ERROR: AuthenticationError
CONCEPT: dependency injection

Entities:"#,
            if text.len() > 500 { &text[..500] } else { text }
        )
    }

    /// Build the relationship extraction prompt
    fn build_relationship_prompt(&self, entities: &[String], context: &str) -> String {
        let entity_list = entities
            .iter()
            .take(10)
            .cloned()
            .collect::<Vec<_>>()
            .join(", ");

        format!(
            r#"Given these entities: [{}]

And this context: "{}"

Identify relationships between entities. Types:
- CONTAINS: A contains B
- USES: A uses B
- CALLS: A calls B
- DEPENDS_ON: A depends on B
- MODIFIES: A modifies B
- FIXES: A fixes B

Output format (one per line):
FROM -> RELATION -> TO

Relationships:"#,
            entity_list,
            if context.len() > 300 {
                &context[..300]
            } else {
                context
            }
        )
    }

    /// Build the concept extraction prompt
    fn build_concept_prompt(&self, text: &str) -> String {
        format!(
            r#"Extract domain concepts and technical terms from this text.
Focus on: frameworks, patterns, methodologies, technologies, abstractions.

Text: "{}"

Output: comma-separated list of concepts
Example: REST API, dependency injection, authentication

Concepts:"#,
            if text.len() > 400 { &text[..400] } else { text }
        )
    }

    /// Parse entity extraction output
    fn parse_entities(&self, output: &str) -> Vec<EnhancedEntity> {
        let mut entities = Vec::new();

        for line in output.lines() {
            let line = line.trim();
            if line.is_empty() {
                continue;
            }

            // Parse "TYPE: name" format
            if let Some((type_str, name)) = line.split_once(':') {
                let type_str = type_str.trim().to_uppercase();
                let name = name.trim();

                if name.is_empty() {
                    continue;
                }

                let entity_type = match type_str.as_str() {
                    "FILE" => SemanticEntityType::File,
                    "FUNCTION" | "FUNC" | "FN" => SemanticEntityType::Function,
                    "TYPE" | "STRUCT" | "CLASS" => SemanticEntityType::Type,
                    "VARIABLE" | "VAR" => SemanticEntityType::Variable,
                    "MODULE" | "MOD" => SemanticEntityType::Module,
                    "PACKAGE" | "CRATE" => SemanticEntityType::Package,
                    "CONCEPT" => SemanticEntityType::Concept,
                    "PATTERN" => SemanticEntityType::Pattern,
                    "ALGORITHM" => SemanticEntityType::Algorithm,
                    "PROTOCOL" => SemanticEntityType::Protocol,
                    "COMMAND" | "CMD" => SemanticEntityType::Command,
                    "OPERATION" => SemanticEntityType::Operation,
                    "TASK" => SemanticEntityType::Task,
                    "ERROR" => SemanticEntityType::Error,
                    "BUG" => SemanticEntityType::Bug,
                    "FIX" => SemanticEntityType::Fix,
                    "FEATURE" => SemanticEntityType::Feature,
                    "PERSON" | "USER" => SemanticEntityType::Person,
                    "URL" | "LINK" => SemanticEntityType::Url,
                    "PATH" => SemanticEntityType::Path,
                    _ => continue,
                };

                entities.push(EnhancedEntity::new(name.to_string(), entity_type, 0.8));

                if entities.len() >= self.max_entities {
                    break;
                }
            }
        }

        entities
    }

    /// Parse relationship extraction output
    fn parse_relationships(&self, output: &str) -> Vec<EnhancedRelationship> {
        let mut relationships = Vec::new();

        for line in output.lines() {
            let line = line.trim();
            if line.is_empty() {
                continue;
            }

            // Parse "FROM -> RELATION -> TO" format
            let parts: Vec<&str> = line.split("->").map(|s| s.trim()).collect();
            if parts.len() >= 3 {
                let from = parts[0].to_string();
                let relation_str = parts[1].to_uppercase();
                let to = parts[2].to_string();

                let relation_type = match relation_str.as_str() {
                    "CONTAINS" => RelationType::Contains,
                    "DEFINED_IN" | "DEFINEDIN" => RelationType::DefinedIn,
                    "IMPORTS" => RelationType::Imports,
                    "EXPORTS" => RelationType::Exports,
                    "EXTENDS" => RelationType::Extends,
                    "IMPLEMENTS" => RelationType::Implements,
                    "CALLS" => RelationType::Calls,
                    "USES" => RelationType::Uses,
                    "MODIFIES" => RelationType::Modifies,
                    "CREATES" => RelationType::Creates,
                    "DELETES" => RelationType::Deletes,
                    "RELATED_TO" | "RELATEDTO" => RelationType::RelatedTo,
                    "SIMILAR_TO" | "SIMILARTO" => RelationType::SimilarTo,
                    "DEPENDS_ON" | "DEPENDSON" => RelationType::DependsOn,
                    "CAUSES" => RelationType::Causes,
                    "FIXES" => RelationType::Fixes,
                    "REPLACES" => RelationType::Replaces,
                    _ => RelationType::RelatedTo, // Default
                };

                relationships.push(EnhancedRelationship {
                    from,
                    to,
                    relation_type,
                    confidence: 0.75,
                });
            }
        }

        relationships
    }

    /// Parse concept extraction output
    fn parse_concepts(&self, output: &str) -> Vec<String> {
        let mut concepts = Vec::new();

        // Handle comma-separated list
        for concept in output.split(',') {
            let concept = concept.trim().to_lowercase();
            if !concept.is_empty() && concept.len() > 2 && concept.len() < 50 {
                concepts.push(concept);
            }
        }

        // Also handle newline-separated
        if concepts.is_empty() {
            for line in output.lines() {
                let concept = line.trim().to_lowercase();
                if !concept.is_empty() && concept.len() > 2 && concept.len() < 50 {
                    concepts.push(concept);
                }
            }
        }

        concepts
    }
}

/// Builder for EntityEnhancer
pub struct EntityEnhancerBuilder {
    provider: Option<Arc<dyn Provider>>,
    model_id: String,
    min_confidence: f32,
    max_entities: usize,
}

impl Default for EntityEnhancerBuilder {
    fn default() -> Self {
        Self {
            provider: None,
            model_id: "lfm2-350m".to_string(), // Fast model for entity extraction
            min_confidence: 0.6,
            max_entities: 20,
        }
    }
}

impl EntityEnhancerBuilder {
    /// Create a new builder with default settings.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the provider to use for entity extraction.
    pub fn provider(mut self, provider: Arc<dyn Provider>) -> Self {
        self.provider = Some(provider);
        self
    }

    /// Set the model ID to use for inference.
    pub fn model_id(mut self, model_id: impl Into<String>) -> Self {
        self.model_id = model_id.into();
        self
    }

    /// Set the minimum confidence threshold for extracted entities.
    pub fn min_confidence(mut self, confidence: f32) -> Self {
        self.min_confidence = confidence.clamp(0.0, 1.0);
        self
    }

    /// Set the maximum number of entities to extract per call.
    pub fn max_entities(mut self, max: usize) -> Self {
        self.max_entities = max.max(1);
        self
    }

    /// Build the entity enhancer, returning `None` if no provider was set.
    pub fn build(self) -> Option<EntityEnhancer> {
        self.provider.map(|p| {
            EntityEnhancer::new(p, self.model_id)
                .with_min_confidence(self.min_confidence)
                .with_max_entities(self.max_entities)
        })
    }
}

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

    #[test]
    fn test_semantic_entity_type_parsing() {
        assert_eq!(
            SemanticEntityType::from_str("function"),
            Some(SemanticEntityType::Function)
        );
        assert_eq!(
            SemanticEntityType::from_str("STRUCT"),
            Some(SemanticEntityType::Type)
        );
        assert_eq!(
            SemanticEntityType::from_str("crate"),
            Some(SemanticEntityType::Package)
        );
        assert_eq!(SemanticEntityType::from_str("invalid"), None);
    }

    #[test]
    fn test_relation_type_parsing() {
        assert_eq!(
            RelationType::from_str("contains"),
            Some(RelationType::Contains)
        );
        assert_eq!(
            RelationType::from_str("DEPENDS_ON"),
            Some(RelationType::DependsOn)
        );
        assert_eq!(RelationType::from_str("invalid"), None);
    }

    #[test]
    fn test_heuristic_extraction_url() {
        let _enhancer = EntityEnhancerBuilder::default();
        let result = extract_heuristic_direct("Check https://example.com/docs for more info");
        assert!(
            result
                .iter()
                .any(|e| e.entity_type == SemanticEntityType::Url)
        );
    }

    #[test]
    fn test_heuristic_extraction_path() {
        let result = extract_heuristic_direct("Look at /home/user/project/src");
        assert!(
            result
                .iter()
                .any(|e| e.entity_type == SemanticEntityType::Path)
        );
    }

    #[test]
    fn test_heuristic_extraction_bug() {
        // "Fixed #123" should match the fix pattern
        let result = extract_heuristic_direct("Fixed #123 in the parser");
        assert!(
            result
                .iter()
                .any(|e| e.entity_type == SemanticEntityType::Fix)
        );
    }

    fn extract_heuristic_direct(text: &str) -> Vec<EnhancedEntity> {
        let mut entities = Vec::new();

        // URL pattern
        let url_pattern = regex::Regex::new(r#"https?://[^\s<>"']+"#).unwrap();
        for cap in url_pattern.find_iter(text) {
            entities.push(EnhancedEntity::new(
                cap.as_str().to_string(),
                SemanticEntityType::Url,
                0.9,
            ));
        }

        // Path pattern
        let path_pattern = regex::Regex::new(r#"(?:^|[\s"'])(/[a-zA-Z0-9_./-]+)"#).unwrap();
        for cap in path_pattern.captures_iter(text) {
            if let Some(m) = cap.get(1) {
                let path = m.as_str();
                if path.len() > 3 && !path.starts_with("//") {
                    entities.push(EnhancedEntity::new(
                        path.to_string(),
                        SemanticEntityType::Path,
                        0.7,
                    ));
                }
            }
        }

        // Fix pattern
        let lower = text.to_lowercase();
        if lower.contains("fix") {
            let fix_context =
                regex::Regex::new(r"(?i)fix(?:ed|es)?\s+(?:#|:)?\s*(\d+|[A-Z]+-\d+)").unwrap();
            for cap in fix_context.captures_iter(text) {
                if let Some(m) = cap.get(1) {
                    entities.push(EnhancedEntity::new(
                        m.as_str().to_string(),
                        SemanticEntityType::Fix,
                        0.85,
                    ));
                }
            }
        }

        entities
    }

    #[test]
    fn test_parse_entities() {
        let output = r#"FUNCTION: process_data
ERROR: AuthenticationError
CONCEPT: dependency injection"#;

        let entities = parse_entities_direct(output);
        assert_eq!(entities.len(), 3);
        assert!(entities.iter().any(|e| e.name == "process_data"));
        assert!(
            entities
                .iter()
                .any(|e| e.entity_type == SemanticEntityType::Error)
        );
    }

    fn parse_entities_direct(output: &str) -> Vec<EnhancedEntity> {
        let mut entities = Vec::new();

        for line in output.lines() {
            let line = line.trim();
            if line.is_empty() {
                continue;
            }

            if let Some((type_str, name)) = line.split_once(':') {
                let type_str = type_str.trim().to_uppercase();
                let name = name.trim();

                if name.is_empty() {
                    continue;
                }

                let entity_type = match type_str.as_str() {
                    "FUNCTION" => SemanticEntityType::Function,
                    "ERROR" => SemanticEntityType::Error,
                    "CONCEPT" => SemanticEntityType::Concept,
                    _ => continue,
                };

                entities.push(EnhancedEntity::new(name.to_string(), entity_type, 0.8));
            }
        }

        entities
    }

    #[test]
    fn test_parse_relationships() {
        let output = "process_data -> CALLS -> validate_input\nModule -> CONTAINS -> Function";

        let relationships = parse_relationships_direct(output);
        assert_eq!(relationships.len(), 2);
        assert!(
            relationships
                .iter()
                .any(|r| r.relation_type == RelationType::Calls)
        );
    }

    fn parse_relationships_direct(output: &str) -> Vec<EnhancedRelationship> {
        let mut relationships = Vec::new();

        for line in output.lines() {
            let parts: Vec<&str> = line.split("->").map(|s| s.trim()).collect();
            if parts.len() >= 3 {
                let from = parts[0].to_string();
                let relation_str = parts[1].to_uppercase();
                let to = parts[2].to_string();

                let relation_type = match relation_str.as_str() {
                    "CALLS" => RelationType::Calls,
                    "CONTAINS" => RelationType::Contains,
                    _ => RelationType::RelatedTo,
                };

                relationships.push(EnhancedRelationship {
                    from,
                    to,
                    relation_type,
                    confidence: 0.75,
                });
            }
        }

        relationships
    }

    #[test]
    fn test_parse_concepts() {
        let output = "REST API, dependency injection, authentication";
        let concepts = parse_concepts_direct(output);
        assert_eq!(concepts.len(), 3);
        assert!(concepts.contains(&"rest api".to_string()));
    }

    fn parse_concepts_direct(output: &str) -> Vec<String> {
        let mut concepts = Vec::new();

        for concept in output.split(',') {
            let concept = concept.trim().to_lowercase();
            if !concept.is_empty() && concept.len() > 2 && concept.len() < 50 {
                concepts.push(concept);
            }
        }

        concepts
    }
}