bra0-kg 0.2.0

bra0 Knowledge Graph core — RDF transformations (sophia) + KgStore trait (NextGraph-First)
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
//! TP-2 Social Perception — EDGY entity extraction from markdown
//!
//! Two-tier extraction (Symbolic Cascade principle):
//!   Tier 1 (regex): fast, deterministic pattern matching for names/roles/orgs
//!   Tier 2 (NER):   sentence-level classification via SKOS vocabulary similarity
//!
//! Pipeline: scan → split → extract (regex + NER) → merge → emit Turtle
//!
//! Reference: ADR-027 (Symbolic Cascade), sprint-plan-v08

use std::collections::{HashMap, HashSet};

/// An entity extracted from markdown by social perception.
#[derive(Debug, Clone)]
pub struct SocialEntity {
    pub entity_type: EntityType,
    pub label: String,
    /// Role (for Person entities)
    pub role: Option<String>,
    /// Source document (file basename without .md)
    pub source: String,
    /// Origin: Symbolic (regex) or Neural (NER)
    pub origin: EntityOrigin,
    /// Confidence: 1.0 for regex, 0..1 for NER
    pub confidence: f32,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum EntityType {
    Person,
    Organisation,
    Capability,
}

#[derive(Debug, Clone, PartialEq)]
pub enum EntityOrigin {
    Symbolic,
    Neural,
}

/// Result of social perception on a corpus.
#[derive(Debug)]
pub struct SocialResult {
    pub entities: Vec<SocialEntity>,
    pub documents_scanned: usize,
    pub symbolic_count: usize,
    pub neural_count: usize,
}

/// Configuration for social perception.
#[derive(Debug, Clone)]
pub struct SocialConfig {
    /// Base IRI for generated entities. Default: "urn:topo:social:"
    pub base_iri: String,
    /// NER similarity threshold for tier 2. Default: 0.70
    pub ner_threshold: f32,
}

impl Default for SocialConfig {
    fn default() -> Self {
        Self {
            base_iri: "urn:topo:social:".to_string(),
            ner_threshold: 0.70,
        }
    }
}

// ─── Tier 1: Regex extraction ─────────────────────────────────────────

/// Extract persons via regex patterns (Name — Role).
fn extract_persons_regex(content: &str, source: &str) -> Vec<SocialEntity> {
    use regex::Regex;
    let mut results = Vec::new();
    let mut seen = HashSet::new();

    // Pattern 1a: "Firstname Lastname — Role" (mixed case)
    let re1a = Regex::new(
        r"(?:^|\s)([A-Z][a-zéèêëàâäùûü]+ [A-Z][a-zéèêëàâäùûü]+)\s*[-–—,]\s*(CEO|CTO|CIO|CISO|CFO|COO|DPO|RSSI|DSI|Founder|Director|Lead|Manager|Architect|Engineer|Developer|Consultant|Partner|Directeur|Responsable|Ingénieur|Fondateur)"
    ).unwrap();

    // Pattern 1b: "Firstname LASTNAME — Role" (surname ALL CAPS, common in French docs)
    let re1b = Regex::new(
        r"(?:^|\s)([A-Z][a-zéèêëàâäùûü]+ [A-Z]{2,}[A-Z]*)\s*[-–—,]\s*(CEO|CTO|CIO|CISO|CFO|COO|DPO|RSSI|DSI|Founder|Director|Lead|Manager|Architect|Engineer|Developer|Consultant|Partner|Directeur|Responsable|Ingénieur|Fondateur)"
    ).unwrap();

    // Pattern 1c: "Firstname Lastname" or "Firstname LASTNAME" in structured headers
    // Matches: "# ... — Firstname LASTNAME, Role" or "**Firstname Lastname**"
    let re1c = Regex::new(
        r"(?:^[#*\s]*|—\s*)([A-Z][a-zéèêëàâäùûü]+ [A-Z][A-ZÉÈÊËÀÂÄÙÛÜa-zéèêëàâäùûü]+)\s*[,]\s*(CEO|CTO|CIO|CISO|CFO|COO|DPO|RSSI|DSI|Founder|Fondateur|Lead\s*\w+|Architecte?\s*\w*)"
    ).unwrap();

    for re in [&re1a, &re1b, &re1c] {
        for cap in re.captures_iter(content) {
            let name = cap[1].trim().to_string();
            let role = cap[2].trim().to_string();
            // Normalize: "Gérald AROULANDA" → "Gérald Aroulanda" for dedup
            let name_normalized = normalize_person_name(&name);
            if name_normalized.len() > 2 && seen.insert(name_normalized.to_lowercase()) {
                results.push(SocialEntity {
                    entity_type: EntityType::Person,
                    label: name_normalized,
                    role: Some(role),
                    source: source.to_string(),
                    origin: EntityOrigin::Symbolic,
                    confidence: 1.0,
                });
            }
        }
    }

    // Pattern 2: "Firstname (... Role ...)"
    let re2 = Regex::new(
        r"(?:^|\s)([A-Z][a-zéèêëàâäùûü]+)\s*\(([^)]*(?:CEO|CTO|CIO|CISO|CFO|Founder|Architect|Lead|Developer|Directeur|Responsable)[^)]*)\)"
    ).unwrap();

    // Common nouns that look like names but aren't persons
    let not_persons: HashSet<&str> = [
        "Scanner", "Module", "Pipeline", "Système", "Plateforme", "Solution",
        "Document", "Projet", "Analyse", "Note", "Support", "Version",
    ].iter().copied().collect();

    for cap in re2.captures_iter(content) {
        let name = cap[1].trim().to_string();
        let role = cap[2].trim().to_string();
        if name.len() > 2 && !not_persons.contains(name.as_str()) && seen.insert(name.to_lowercase()) {
            results.push(SocialEntity {
                entity_type: EntityType::Person,
                label: name,
                role: Some(role),
                source: source.to_string(),
                origin: EntityOrigin::Symbolic,
                confidence: 1.0,
            });
        }
    }

    // Pattern 3: "Firstname — standalone" in interview contexts
    // Looks for single capitalized names followed by role keywords nearby
    let re3 = Regex::new(
        r"(?m)^(?:\s*>?\s*)?([A-Z][a-zéèêëàâäùûü]+)\s+(?:est|mon|notre|le|la)\s+(\w+(?:\s+\w+)?)\s"
    ).unwrap();

    let role_words: HashSet<&str> = [
        "architecte", "développeur", "ingénieur", "directeur", "responsable",
        "lead", "consultant", "fondateur", "CEO", "CTO",
    ].iter().copied().collect();

    for cap in re3.captures_iter(content) {
        let name = cap[1].trim().to_string();
        let context = cap[2].trim().to_lowercase();
        if role_words.iter().any(|rw| context.contains(rw)) && !not_persons.contains(name.as_str()) && seen.insert(name.to_lowercase()) {
            results.push(SocialEntity {
                entity_type: EntityType::Person,
                label: name,
                role: Some(context),
                source: source.to_string(),
                origin: EntityOrigin::Symbolic,
                confidence: 0.8,
            });
        }
    }

    results
}

/// Normalize a person name: "Gérald AROULANDA" → "Gérald Aroulanda"
fn normalize_person_name(name: &str) -> String {
    name.split_whitespace()
        .map(|word| {
            // If the word is ALL CAPS (and > 1 char), title-case it
            if word.len() > 1 && word.chars().all(|c| c.is_uppercase() || !c.is_alphabetic()) {
                let mut chars = word.chars();
                let first: String = chars.next().into_iter().collect();
                let rest: String = chars.collect::<String>().to_lowercase();
                format!("{}{}", first, rest)
            } else {
                word.to_string()
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

/// Extract organizations via regex (known org names).
fn extract_orgs_regex(content: &str, source: &str) -> Vec<SocialEntity> {
    use regex::Regex;
    let re = Regex::new(
        r"\b(ANSSI|CLUSIF|AFNOR|ENISA|BSI|NIST|ISO|IEEE|W3C|OWASP|MITRE|Gartner|Forrester|Deloitte|PwC|EY|KPMG|Accenture|Thales|Atos|Capgemini|OVH|AWS|Azure|GCP|Mistral|OpenAI|Anthropic|HuggingFace)\b"
    ).unwrap();

    let mut seen = HashSet::new();
    let mut results = Vec::new();

    for cap in re.captures_iter(content) {
        let org = cap[1].trim().to_string();
        if seen.insert(org.clone()) {
            results.push(SocialEntity {
                entity_type: EntityType::Organisation,
                label: org,
                role: None,
                source: source.to_string(),
                origin: EntityOrigin::Symbolic,
                confidence: 1.0,
            });
        }
    }

    results
}

/// Extract capabilities via regex patterns.
///
/// Two tiers of patterns:
///   P1: explicit markers (module: xxx, service: xxx) — high precision
///   P2: natural language (un scanner, une plateforme, un module GRC) — broader recall
fn extract_capabilities_regex(content: &str, source: &str) -> Vec<SocialEntity> {
    use regex::Regex;

    let mut seen = HashSet::new();
    let mut results = Vec::new();

    // P1: explicit "keyword: description" — strict, high precision
    let re_explicit = Regex::new(
        r"(?i)(?:module|capability|feature|service|capacité|fonctionnalité)\s*[:]\s*([^\n.]{5,80})"
    ).unwrap();

    for cap in re_explicit.captures_iter(content) {
        let desc = cap[1].trim().to_string();
        if desc.len() > 5 && seen.insert(desc.to_lowercase()) {
            results.push(SocialEntity {
                entity_type: EntityType::Capability,
                label: desc,
                role: None,
                source: source.to_string(),
                origin: EntityOrigin::Symbolic,
                confidence: 1.0,
            });
        }
    }

    // P2: natural language — "un/une/le/la/les (adj?) capability-noun complement"
    // Matches: "un scanner modulaire IT/OT/Cloud", "une plateforme GRC", "le module de conformité"
    // Captures the full noun phrase including French apostrophes (l', d', qu')
    let re_natural = Regex::new(
        r"(?i)\b(?:un|une|le|la|les|du|des|notre|leur|son|sa)\s+(?:[a-zéèêëàâäùûüôïî]+\s+)?(?:scanner|plateforme|module|moteur|pipeline|outil|système|solution|framework|connecteur|intégration|API|LLM|modèle|algorithme|brique|composant)\s+(?:[a-zéèêëàâäùûüôïîA-Z0-9/''\-()]+(?:\s+[a-zéèêëàâäùûüôïîA-Z0-9/''\-()]+){0,6})"
    ).unwrap();

    for m in re_natural.find_iter(content) {
        let full_match = m.as_str().trim().to_string();

        // Skip if ends mid-word at apostrophe (truncated)
        if full_match.ends_with('\'') || full_match.ends_with('\u{2019}') || full_match.ends_with(" d") || full_match.ends_with(" l") || full_match.ends_with(" qu") {
            continue;
        }

        // Min length filter: require at least 15 chars for meaningful capability name
        if full_match.len() < 15 {
            continue;
        }

        // Skip multi-line matches (usually regex noise spanning paragraphs)
        if full_match.contains('\n') {
            continue;
        }

        // Skip question-like patterns (not a capability declaration)
        if full_match.contains('?') || full_match.contains("tient-il") || full_match.contains("comment") {
            continue;
        }

        if seen.insert(full_match.to_lowercase()) {
            results.push(SocialEntity {
                entity_type: EntityType::Capability,
                label: full_match,
                role: None,
                source: source.to_string(),
                origin: EntityOrigin::Symbolic,
                confidence: 0.5,
            });
        }
    }

    results
}

// ─── Tier 2: NER classification ───────────────────────────────────────

/// EDGY vocabulary candidates for NER classification.
/// Each sentence is classified as being "about" one of these entity types.
#[cfg(feature = "ner")]
fn edgy_candidates() -> Vec<crate::ner::Candidate> {
    vec![
        crate::ner::Candidate { label: "person individual team member stakeholder employee".into(), iri: "edgy:Person".into() },
        crate::ner::Candidate { label: "organization company institution agency partner vendor".into(), iri: "edgy:Organisation".into() },
        crate::ner::Candidate { label: "capability service feature module function system".into(), iri: "edgy:Capability".into() },
        crate::ner::Candidate { label: "product tool platform software application".into(), iri: "edgy:Product".into() },
    ]
}

/// Classify sentences by EDGY type using NER, extract entity names from
/// sentences classified as Person/Organisation/Capability.
#[cfg(feature = "ner")]
fn extract_via_ner(
    content: &str,
    source: &str,
    engine: &crate::ner::NerEngine,
    threshold: f32,
) -> Vec<SocialEntity> {
    let candidates = edgy_candidates();
    let mut results = Vec::new();

    // Split into sentences (rough: split on . or newline, filter short)
    let sentences: Vec<&str> = content
        .split(|c: char| c == '.' || c == '\n')
        .map(|s| s.trim())
        .filter(|s| s.len() > 20)
        .collect();

    for sentence in sentences {
        let ner_results = match engine.zero_shot_ner(sentence, &candidates, threshold) {
            Ok(r) => r,
            Err(_) => continue,
        };

        if ner_results.is_empty() {
            continue;
        }

        let top = &ner_results[0];
        let entity_type = match top.iri.as_str() {
            "edgy:Person" => EntityType::Person,
            "edgy:Organisation" => EntityType::Organisation,
            "edgy:Capability" => EntityType::Capability,
            _ => continue,
        };

        // Extract a meaningful label from the sentence
        let label = extract_label_from_sentence(sentence, &entity_type);
        if let Some(label) = label {
            results.push(SocialEntity {
                entity_type,
                label,
                role: None,
                source: source.to_string(),
                origin: EntityOrigin::Neural,
                confidence: top.similarity,
            });
        }
    }

    results
}

/// Extract a meaningful entity name from a classified sentence.
/// Uses capitalized words for Person/Org, full phrase for Capability.
#[cfg(feature = "ner")]
fn extract_label_from_sentence(sentence: &str, entity_type: &EntityType) -> Option<String> {
    use regex::Regex;

    match entity_type {
        EntityType::Person => {
            // Look for capitalized word pairs (first + last name)
            let re = Regex::new(r"([A-Z][a-zéèêëàâäùûü]+ [A-Z][a-zéèêëàâäùûü]+)").unwrap();
            re.find(sentence).map(|m| m.as_str().to_string())
        }
        EntityType::Organisation => {
            // Look for all-caps words or known patterns
            let re = Regex::new(r"\b([A-Z]{2,}(?:\s+[A-Z]{2,})*)\b").unwrap();
            re.find(sentence).map(|m| m.as_str().to_string())
        }
        EntityType::Capability => {
            // Use the core phrase (trim to ~80 chars on a char boundary)
            let trimmed = sentence.trim();
            let end = trimmed.char_indices()
                .take_while(|(i, _)| *i < 80)
                .last()
                .map(|(i, c)| i + c.len_utf8())
                .unwrap_or(trimmed.len());
            Some(trimmed[..end].to_string())
        }
    }
}

// ─── Full pipeline ────────────────────────────────────────────────────

/// Run social perception on a directory of markdown files.
///
/// Tier 1 (regex) always runs. Tier 2 (NER) runs if engine is provided.
/// Results are merged: symbolic wins for duplicates (same label + type).
pub fn extract_social(
    dir: &str,
    #[cfg(feature = "ner")] ner_engine: Option<&crate::ner::NerEngine>,
    config: &SocialConfig,
) -> Result<SocialResult, Box<dyn std::error::Error>> {
    let mut all_entities = Vec::new();
    let mut documents_scanned = 0usize;

    // Find all .md files recursively
    let md_files = find_md_files(dir)?;

    for md_path in &md_files {
        let content = std::fs::read_to_string(md_path)?;
        let source = std::path::Path::new(md_path)
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("unknown")
            .to_string();

        documents_scanned += 1;

        // Tier 1: regex
        all_entities.extend(extract_persons_regex(&content, &source));
        all_entities.extend(extract_orgs_regex(&content, &source));
        all_entities.extend(extract_capabilities_regex(&content, &source));

        // Tier 2: NER (if available)
        #[cfg(feature = "ner")]
        if let Some(engine) = ner_engine {
            let neural = extract_via_ner(&content, &source, engine, config.ner_threshold);
            all_entities.extend(neural);
        }
    }

    // Merge: symbolic wins for same (label, type) pair
    let (merged, symbolic_count, neural_count) = merge_social_entities(all_entities);

    Ok(SocialResult {
        entities: merged,
        documents_scanned,
        symbolic_count,
        neural_count,
    })
}

/// Find .md files recursively in a directory.
fn find_md_files(dir: &str) -> Result<Vec<String>, Box<dyn std::error::Error>> {
    let mut files = Vec::new();
    fn walk(dir: &std::path::Path, files: &mut Vec<String>) -> std::io::Result<()> {
        for entry in std::fs::read_dir(dir)? {
            let entry = entry?;
            let name = entry.file_name();
            let name_str = name.to_string_lossy();
            if name_str.starts_with('.') {
                continue;
            }
            let path = entry.path();
            if path.is_dir() {
                walk(&path, files)?;
            } else if path.extension().map_or(false, |e| e == "md") {
                files.push(path.to_string_lossy().to_string());
            }
        }
        Ok(())
    }
    walk(std::path::Path::new(dir), &mut files)?;
    Ok(files)
}

/// Merge entities: symbolic wins for duplicates (same label + type).
fn merge_social_entities(
    entities: Vec<SocialEntity>,
) -> (Vec<SocialEntity>, usize, usize) {
    let mut seen: HashMap<(String, EntityType), SocialEntity> = HashMap::new();
    let mut symbolic_count = 0usize;
    let mut neural_count = 0usize;

    for entity in entities {
        let key = (entity.label.clone(), entity.entity_type.clone());
        match entity.origin {
            EntityOrigin::Symbolic => symbolic_count += 1,
            EntityOrigin::Neural => neural_count += 1,
        }
        // Symbolic wins: only insert if not already present or current is symbolic
        if let Some(existing) = seen.get(&key) {
            if existing.origin == EntityOrigin::Neural && entity.origin == EntityOrigin::Symbolic {
                seen.insert(key, entity);
            }
            // else keep existing (symbolic already there, or both neural → keep first)
        } else {
            seen.insert(key, entity);
        }
    }

    (seen.into_values().collect(), symbolic_count, neural_count)
}

/// Emit Turtle RDF from social extraction results.
pub fn social_to_turtle(result: &SocialResult, config: &SocialConfig) -> String {
    let mut lines = vec![
        "@prefix edgy: <https://edgy.is/schema/0.95#> .".to_string(),
        "@prefix prov: <http://www.w3.org/ns/prov#> .".to_string(),
        "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .".to_string(),
        "@prefix re: <https://omyn.ai/schema/retroeng#> .".to_string(),
        format!("@prefix tp: <{}> .", config.base_iri),
        String::new(),
    ];

    // Collect unique sources for provenance
    let sources: HashSet<&str> = result.entities.iter().map(|e| e.source.as_str()).collect();
    for source in &sources {
        let local = sanitize_local(source);
        lines.push(format!("tp:doc-{} a prov:Entity ;", local));
        lines.push(format!("    rdfs:label \"{}\"@en .", source));
        lines.push(String::new());
    }

    for entity in &result.entities {
        let (prefix, rdf_type) = match entity.entity_type {
            EntityType::Person => ("person", "edgy:Person"),
            EntityType::Organisation => ("org", "edgy:Organisation"),
            EntityType::Capability => ("cap", "edgy:Capability"),
        };

        let local = sanitize_local(&entity.label);
        let local = {
            let end = local.char_indices()
                .take_while(|(i, _)| *i < 60)
                .last()
                .map(|(i, c)| i + c.len_utf8())
                .unwrap_or(local.len());
            &local[..end]
        };
        let escaped_label = entity.label.replace('"', "\\\"").replace('\n', " ").replace('\r', "");
        let source_local = sanitize_local(&entity.source);

        lines.push(format!("tp:{}-{} a {} ;", prefix, local, rdf_type));
        lines.push(format!("    rdfs:label \"{}\"@en ;", escaped_label));

        if let Some(ref role) = entity.role {
            lines.push(format!("    edgy:role \"{}\"@en ;", role));
        }

        // Confidence as structured property (always emitted)
        lines.push(format!("    re:extractionConfidence {:.2} ;", entity.confidence));

        // Origin annotation
        let origin_label = match entity.origin {
            EntityOrigin::Symbolic => "symbolic",
            EntityOrigin::Neural => "neural",
        };
        lines.push(format!("    re:extractionOrigin \"{}\" ;", origin_label));

        lines.push("    re:verificationStatus re:Claimed ;".to_string());
        lines.push(format!("    prov:wasDerivedFrom tp:doc-{} .", source_local));
        lines.push(String::new());
    }

    lines.join("\n")
}

fn sanitize_local(s: &str) -> String {
    s.chars()
        .map(|c| if c.is_alphanumeric() || c == '_' || c == '-' { c } else { '_' })
        .collect::<String>()
        .to_lowercase()
}

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

    #[test]
    fn test_extract_persons_regex() {
        let text = "Le projet est dirigé par Jean Dupont — CTO et Marie Martin, Architect du SI.";
        let results = extract_persons_regex(text, "test_doc");
        assert!(results.len() >= 2, "Expected 2 persons, got {}", results.len());
        assert!(results.iter().any(|e| e.label.contains("Jean Dupont")));
        assert!(results.iter().any(|e| e.label.contains("Marie Martin")));
    }

    #[test]
    fn test_extract_persons_uppercase_surname() {
        let text = "# Support d'entretien — Gérald AROULANDA, CEO RiskHunter";
        let results = extract_persons_regex(text, "test_doc");
        assert!(!results.is_empty(), "Should extract Gérald AROULANDA");
        let gerald = results.iter().find(|e| e.label.contains("Aroulanda"));
        assert!(gerald.is_some(), "Should normalize AROULANDA → Aroulanda");
        assert_eq!(gerald.unwrap().confidence, 1.0);
    }

    #[test]
    fn test_normalize_person_name() {
        assert_eq!(normalize_person_name("Gérald AROULANDA"), "Gérald Aroulanda");
        assert_eq!(normalize_person_name("Jean Dupont"), "Jean Dupont");
        assert_eq!(normalize_person_name("JEAN DUPONT"), "Jean Dupont");
    }

    #[test]
    fn test_extract_orgs_regex() {
        let text = "L'audit a été réalisé conformément aux recommandations de l'ANSSI et du NIST, avec le support de Thales.";
        let results = extract_orgs_regex(text, "test_doc");
        assert_eq!(results.len(), 3);
        let labels: Vec<&str> = results.iter().map(|e| e.label.as_str()).collect();
        assert!(labels.contains(&"ANSSI"));
        assert!(labels.contains(&"NIST"));
        assert!(labels.contains(&"Thales"));
    }

    #[test]
    fn test_extract_capabilities_regex() {
        let text = "module: Identity and Access Management\nfeature: multi-factor authentication\nservice: API gateway";
        let results = extract_capabilities_regex(text, "test_doc");
        assert_eq!(results.len(), 3, "Expected 3 capabilities, got {:?}", results);
    }

    #[test]
    fn test_merge_symbolic_wins() {
        let entities = vec![
            SocialEntity {
                entity_type: EntityType::Person,
                label: "Jean Dupont".into(),
                role: Some("CTO".into()),
                source: "doc1".into(),
                origin: EntityOrigin::Neural,
                confidence: 0.85,
            },
            SocialEntity {
                entity_type: EntityType::Person,
                label: "Jean Dupont".into(),
                role: Some("CTO".into()),
                source: "doc2".into(),
                origin: EntityOrigin::Symbolic,
                confidence: 1.0,
            },
        ];

        let (merged, _, _) = merge_social_entities(entities);
        assert_eq!(merged.len(), 1);
        assert_eq!(merged[0].origin, EntityOrigin::Symbolic, "Symbolic should win");
    }

    #[test]
    fn test_social_to_turtle() {
        let result = SocialResult {
            entities: vec![
                SocialEntity {
                    entity_type: EntityType::Person,
                    label: "Jean Dupont".into(),
                    role: Some("CTO".into()),
                    source: "interview_01".into(),
                    origin: EntityOrigin::Symbolic,
                    confidence: 1.0,
                },
                SocialEntity {
                    entity_type: EntityType::Organisation,
                    label: "ANSSI".into(),
                    role: None,
                    source: "interview_01".into(),
                    origin: EntityOrigin::Symbolic,
                    confidence: 1.0,
                },
            ],
            documents_scanned: 1,
            symbolic_count: 2,
            neural_count: 0,
        };

        let config = SocialConfig::default();
        let turtle = social_to_turtle(&result, &config);
        assert!(turtle.contains("edgy:Person"));
        assert!(turtle.contains("Jean Dupont"));
        assert!(turtle.contains("edgy:Organisation"));
        assert!(turtle.contains("ANSSI"));
        assert!(turtle.contains("prov:wasDerivedFrom"));
    }
}