brainwires-cognition 0.8.0

Unified intelligence layer — knowledge graphs, adaptive prompting, RAG, spectral math, and code analysis 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
//! Personal Fact Collector
//!
//! Detects implicit personal facts from conversation patterns.
//! Recognizes phrases like "I prefer...", "I'm working on...", "My name is...", etc.

use super::fact::{PersonalFact, PersonalFactCategory, PersonalFactSource};
use regex::Regex;

/// Collector for detecting personal facts from conversation
pub struct PersonalFactCollector {
    /// Patterns for detecting identity facts
    identity_patterns: Vec<PatternRule>,
    /// Patterns for detecting preference facts
    preference_patterns: Vec<PatternRule>,
    /// Patterns for detecting capability facts
    capability_patterns: Vec<PatternRule>,
    /// Patterns for detecting context facts
    context_patterns: Vec<PatternRule>,
    /// Patterns for detecting constraint facts
    constraint_patterns: Vec<PatternRule>,
    /// Minimum confidence for inferred facts
    min_confidence: f32,
    /// Whether implicit detection is enabled
    enabled: bool,
}

/// A pattern rule for detecting facts
struct PatternRule {
    /// Compiled regex pattern
    pattern: Regex,
    /// Key to use for the detected fact
    key_template: String,
    /// Category for detected facts
    category: PersonalFactCategory,
    /// Confidence score for matches
    confidence: f32,
    /// Group index for the value (1-based)
    value_group: usize,
    /// Optional group index for additional context
    context_group: Option<usize>,
}

impl Default for PersonalFactCollector {
    fn default() -> Self {
        Self::new(0.7, true)
    }
}

impl PersonalFactCollector {
    /// Create a new collector with default patterns
    pub fn new(min_confidence: f32, enabled: bool) -> Self {
        let mut collector = Self {
            identity_patterns: Vec::new(),
            preference_patterns: Vec::new(),
            capability_patterns: Vec::new(),
            context_patterns: Vec::new(),
            constraint_patterns: Vec::new(),
            min_confidence,
            enabled,
        };

        collector.init_patterns();
        collector
    }

    /// Initialize detection patterns
    fn init_patterns(&mut self) {
        // Identity patterns
        self.identity_patterns = vec![
            PatternRule::new(
                r"(?i)my name is\s+([A-Z][a-z]+(?:\s+[A-Z][a-z]+)?)",
                "name",
                PersonalFactCategory::Identity,
                0.9,
                1,
                None,
            ),
            PatternRule::new(
                r"(?i)call me\s+([A-Z][a-z]+)",
                "preferred_name",
                PersonalFactCategory::Identity,
                0.85,
                1,
                None,
            ),
            PatternRule::new(
                r"(?i)i(?:'m| am) (?:a |an )?([a-z]+(?:\s+[a-z]+)*)\s+(?:at|for|with)\s+([A-Za-z0-9]+)",
                "role",
                PersonalFactCategory::Identity,
                0.8,
                1,
                Some(2),
            ),
            PatternRule::new(
                r"(?i)i work (?:at|for|with)\s+([A-Za-z0-9]+(?:\s+[A-Za-z0-9]+)*)",
                "organization",
                PersonalFactCategory::Identity,
                0.8,
                1,
                None,
            ),
            PatternRule::new(
                r"(?i)i(?:'m| am) on the\s+([a-z]+(?:\s+[a-z]+)*)\s+team",
                "team",
                PersonalFactCategory::Identity,
                0.8,
                1,
                None,
            ),
        ];

        // Preference patterns
        self.preference_patterns = vec![
            PatternRule::new(
                r"(?i)i prefer\s+(.+?)(?:\s+over|\s+to|\s*[,.]|$)",
                "preference",
                PersonalFactCategory::Preference,
                0.85,
                1,
                None,
            ),
            PatternRule::new(
                r"(?i)i (?:really |always |usually )?like\s+(?:using |working with )?(.+?)(?:\s+for|\s*[,.]|$)",
                "liked_tool",
                PersonalFactCategory::Preference,
                0.7,
                1,
                None,
            ),
            PatternRule::new(
                r"(?i)i(?:'d| would) rather\s+(.+?)(?:\s+than|\s*[,.]|$)",
                "preference",
                PersonalFactCategory::Preference,
                0.75,
                1,
                None,
            ),
            PatternRule::new(
                r"(?i)my favorite\s+([a-z]+)\s+is\s+([A-Za-z0-9]+)",
                "favorite_{1}",
                PersonalFactCategory::Preference,
                0.8,
                2,
                None,
            ),
            PatternRule::new(
                r"(?i)i use\s+([A-Za-z0-9]+(?:\s+[A-Za-z0-9]+)?)\s+(?:as my |for )([a-z]+)",
                "{2}_tool",
                PersonalFactCategory::Preference,
                0.75,
                1,
                None,
            ),
        ];

        // Capability patterns
        self.capability_patterns = vec![
            PatternRule::new(
                r"(?i)i(?:'m| am) (?:fluent|proficient|experienced) (?:in|with)\s+([A-Za-z0-9#+]+)",
                "proficient_in",
                PersonalFactCategory::Capability,
                0.8,
                1,
                None,
            ),
            PatternRule::new(
                r"(?i)i know\s+([A-Za-z0-9#+]+)(?:\s+(?:well|pretty well))?",
                "knows",
                PersonalFactCategory::Capability,
                0.7,
                1,
                None,
            ),
            PatternRule::new(
                r"(?i)i(?:'ve| have) (?:been )?(?:using|working with)\s+([A-Za-z0-9#+]+)\s+for\s+(\d+)\s+years?",
                "experience_{1}",
                PersonalFactCategory::Capability,
                0.85,
                1,
                Some(2),
            ),
            PatternRule::new(
                r"(?i)i(?:'m| am) (?:a |an )?expert (?:in|at|with)\s+([A-Za-z0-9#+]+)",
                "expert_in",
                PersonalFactCategory::Capability,
                0.85,
                1,
                None,
            ),
        ];

        // Context patterns
        self.context_patterns = vec![
            PatternRule::new(
                r"(?i)i(?:'m| am) (?:currently )?working on\s+([A-Za-z0-9_-]+(?:\s+[A-Za-z0-9_-]+)*)",
                "current_project",
                PersonalFactCategory::Context,
                0.8,
                1,
                None,
            ),
            PatternRule::new(
                r"(?i)my (?:current )?project is\s+([A-Za-z0-9_-]+)",
                "current_project",
                PersonalFactCategory::Context,
                0.85,
                1,
                None,
            ),
            PatternRule::new(
                r"(?i)i(?:'m| am) (?:trying to|working to)\s+(.+?)(?:\s*[,.]|$)",
                "current_goal",
                PersonalFactCategory::Context,
                0.7,
                1,
                None,
            ),
            PatternRule::new(
                r"(?i)today i(?:'m| am)\s+(.+?)(?:\s*[,.]|$)",
                "current_task",
                PersonalFactCategory::Context,
                0.65,
                1,
                None,
            ),
        ];

        // Constraint patterns
        self.constraint_patterns = vec![
            PatternRule::new(
                r"(?i)i (?:can't|cannot|don't have access to)\s+(.+?)(?:\s*[,.]|$)",
                "cannot_access",
                PersonalFactCategory::Constraint,
                0.8,
                1,
                None,
            ),
            PatternRule::new(
                r"(?i)i(?:'m| am) in (?:the )?([A-Za-z]+(?:\s+[A-Za-z]+)?)\s+time ?zone",
                "timezone",
                PersonalFactCategory::Constraint,
                0.85,
                1,
                None,
            ),
            PatternRule::new(
                r"(?i)i(?:'m| am) limited (?:to|by)\s+(.+?)(?:\s*[,.]|$)",
                "limitation",
                PersonalFactCategory::Constraint,
                0.75,
                1,
                None,
            ),
            PatternRule::new(
                r"(?i)i(?:'m| am) not allowed to\s+(.+?)(?:\s*[,.]|$)",
                "restriction",
                PersonalFactCategory::Constraint,
                0.8,
                1,
                None,
            ),
        ];
    }

    /// Process user message and extract any personal facts
    pub fn process_message(&self, message: &str) -> Vec<PersonalFact> {
        if !self.enabled {
            return Vec::new();
        }

        let mut facts = Vec::new();

        // Check all pattern categories
        facts.extend(self.check_patterns(message, &self.identity_patterns));
        facts.extend(self.check_patterns(message, &self.preference_patterns));
        facts.extend(self.check_patterns(message, &self.capability_patterns));
        facts.extend(self.check_patterns(message, &self.context_patterns));
        facts.extend(self.check_patterns(message, &self.constraint_patterns));

        // Filter by minimum confidence
        facts
            .into_iter()
            .filter(|f| f.confidence >= self.min_confidence)
            .collect()
    }

    /// Check message against a set of patterns
    fn check_patterns(&self, message: &str, patterns: &[PatternRule]) -> Vec<PersonalFact> {
        let mut facts = Vec::new();

        for rule in patterns {
            if let Some(captures) = rule.pattern.captures(message)
                && let Some(value_match) = captures.get(rule.value_group)
            {
                let value = value_match.as_str().trim().to_string();

                // Skip very short or very long values
                if value.len() < 2 || value.len() > 100 {
                    continue;
                }

                // Build the key (may contain template placeholders)
                let key = self.build_key(&rule.key_template, &captures);

                // Get optional context
                let context = rule
                    .context_group
                    .and_then(|g| captures.get(g).map(|m| m.as_str().trim().to_string()));

                let fact = PersonalFact::new(
                    rule.category,
                    key,
                    value,
                    context,
                    PersonalFactSource::InferredFromBehavior,
                    false, // Default to synced, not local-only
                );

                // Adjust confidence based on rule
                let mut adjusted_fact = fact;
                adjusted_fact.confidence = rule.confidence;

                facts.push(adjusted_fact);
            }
        }

        facts
    }

    /// Build a key from a template, replacing {n} with capture groups
    fn build_key(&self, template: &str, captures: &regex::Captures) -> String {
        let mut key = template.to_string();

        // Replace {n} patterns with capture groups
        use std::sync::LazyLock;
        static RE: LazyLock<Regex> =
            LazyLock::new(|| Regex::new(r"\{(\d+)\}").expect("valid regex"));
        let re = &*RE;
        for cap in re.captures_iter(template) {
            if let Ok(group_num) = cap[1].parse::<usize>()
                && let Some(value) = captures.get(group_num)
            {
                let replacement = value.as_str().to_lowercase().replace(' ', "_");
                key = key.replace(&cap[0], &replacement);
            }
        }

        key.to_lowercase().replace(' ', "_")
    }

    /// Enable or disable the collector
    pub fn set_enabled(&mut self, enabled: bool) {
        self.enabled = enabled;
    }

    /// Check if the collector is enabled
    pub fn is_enabled(&self) -> bool {
        self.enabled
    }

    /// Set minimum confidence threshold
    pub fn set_min_confidence(&mut self, confidence: f32) {
        self.min_confidence = confidence;
    }
}

impl PatternRule {
    fn new(
        pattern: &str,
        key_template: &str,
        category: PersonalFactCategory,
        confidence: f32,
        value_group: usize,
        context_group: Option<usize>,
    ) -> Self {
        Self {
            pattern: Regex::new(pattern).expect("Invalid pattern regex"),
            key_template: key_template.to_string(),
            category,
            confidence,
            value_group,
            context_group,
        }
    }
}

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

    #[test]
    fn test_collector_creation() {
        let collector = PersonalFactCollector::default();
        assert!(collector.is_enabled());
    }

    #[test]
    fn test_name_detection() {
        let collector = PersonalFactCollector::default();
        let facts = collector.process_message("My name is John Smith");

        assert!(!facts.is_empty());
        let name_fact = facts.iter().find(|f| f.key == "name").unwrap();
        assert_eq!(name_fact.value, "John Smith");
        assert_eq!(name_fact.category, PersonalFactCategory::Identity);
    }

    #[test]
    fn test_preference_detection() {
        let collector = PersonalFactCollector::default();
        let facts = collector.process_message("I prefer Rust over Python");

        assert!(!facts.is_empty());
        let pref_fact = facts.iter().find(|f| f.key == "preference").unwrap();
        assert!(pref_fact.value.contains("Rust"));
        assert_eq!(pref_fact.category, PersonalFactCategory::Preference);
    }

    #[test]
    fn test_current_project_detection() {
        let collector = PersonalFactCollector::default();
        let facts = collector.process_message("I'm working on brainwires-cli");

        assert!(!facts.is_empty());
        let project_fact = facts.iter().find(|f| f.key == "current_project").unwrap();
        assert_eq!(project_fact.value, "brainwires-cli");
        assert_eq!(project_fact.category, PersonalFactCategory::Context);
    }

    #[test]
    fn test_organization_detection() {
        let collector = PersonalFactCollector::default();
        let facts = collector.process_message("I work at Anthropic");

        assert!(!facts.is_empty());
        let org_fact = facts.iter().find(|f| f.key == "organization").unwrap();
        assert_eq!(org_fact.value, "Anthropic");
        assert_eq!(org_fact.category, PersonalFactCategory::Identity);
    }

    #[test]
    fn test_capability_detection() {
        let collector = PersonalFactCollector::default();
        let facts = collector.process_message("I'm proficient in Rust");

        assert!(!facts.is_empty());
        let cap_fact = facts.iter().find(|f| f.key == "proficient_in").unwrap();
        assert_eq!(cap_fact.value, "Rust");
        assert_eq!(cap_fact.category, PersonalFactCategory::Capability);
    }

    #[test]
    fn test_disabled_collector() {
        let mut collector = PersonalFactCollector::default();
        collector.set_enabled(false);

        let facts = collector.process_message("My name is John");
        assert!(facts.is_empty());
    }

    #[test]
    fn test_confidence_filtering() {
        let collector = PersonalFactCollector::new(0.95, true);
        // Most patterns have confidence < 0.95, so should filter out
        let facts = collector.process_message("I prefer Rust");
        // May or may not have results depending on pattern confidences
        for fact in &facts {
            assert!(fact.confidence >= 0.95);
        }
    }
}