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
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
//! Personal Fact data structures
//!
//! Defines the core types for representing personal facts about the user -
//! preferences, context, capabilities, and other user-specific knowledge.

use chrono::Utc;
use serde::{Deserialize, Serialize};
use std::fmt;

/// A personal fact about the user
///
/// Examples:
/// - "User prefers Rust over Python"
/// - "Current project is brainwires-cli"
/// - "User is a Senior Engineer at Anthropic"
/// - "User uses VSCode with Vim keybindings"
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PersonalFact {
    /// Unique identifier (UUID)
    pub id: String,

    /// Category of fact (Identity, Preference, etc.)
    pub category: PersonalFactCategory,

    /// Key for the fact (e.g., "preferred_language", "current_project")
    pub key: String,

    /// The actual fact content
    pub value: String,

    /// Optional context when this applies
    pub context: Option<String>,

    // Confidence tracking (EMA-weighted)
    /// Current confidence score (0.0 - 1.0)
    pub confidence: f32,

    /// Number of times this fact has been reinforced
    pub reinforcements: u32,

    /// Number of times this fact has been contradicted
    pub contradictions: u32,

    /// Last time this fact was used (Unix timestamp)
    pub last_used: i64,

    // Provenance
    /// When this fact was created (Unix timestamp)
    pub created_at: i64,

    /// When this fact was last updated (Unix timestamp)
    pub updated_at: i64,

    /// How this fact was learned
    pub source: PersonalFactSource,

    /// Server-side version for sync conflict resolution
    #[serde(default)]
    pub version: u64,

    /// Whether this fact has been deleted (soft delete)
    #[serde(default)]
    pub deleted: bool,

    /// Whether this fact should never sync to server (privacy)
    #[serde(default)]
    pub local_only: bool,
}

impl PersonalFact {
    /// Create a new personal fact
    pub fn new(
        category: PersonalFactCategory,
        key: String,
        value: String,
        context: Option<String>,
        source: PersonalFactSource,
        local_only: bool,
    ) -> Self {
        let now = Utc::now().timestamp();
        let initial_confidence = source.initial_confidence();

        Self {
            id: uuid::Uuid::new_v4().to_string(),
            category,
            key,
            value,
            context,
            confidence: initial_confidence,
            reinforcements: 0,
            contradictions: 0,
            last_used: now,
            created_at: now,
            updated_at: now,
            source,
            version: 1,
            deleted: false,
            local_only,
        }
    }

    /// Reinforce this fact (successful use)
    ///
    /// Updates confidence using EMA: new = alpha * 1.0 + (1-alpha) * old
    pub fn reinforce(&mut self, ema_alpha: f32) {
        self.reinforcements += 1;
        self.last_used = Utc::now().timestamp();
        self.updated_at = self.last_used;
        self.confidence = ema_alpha * 1.0 + (1.0 - ema_alpha) * self.confidence;
        self.confidence = self.confidence.min(1.0);
        self.version += 1;
    }

    /// Contradict this fact (user provided different info)
    ///
    /// Updates confidence using EMA: new = alpha * 0.0 + (1-alpha) * old
    pub fn contradict(&mut self, ema_alpha: f32) {
        self.contradictions += 1;
        self.last_used = Utc::now().timestamp();
        self.updated_at = self.last_used;
        self.confidence = ema_alpha * 0.0 + (1.0 - ema_alpha) * self.confidence;
        self.version += 1;
    }

    /// Update the fact's value
    pub fn update_value(&mut self, new_value: String) {
        self.value = new_value;
        self.last_used = Utc::now().timestamp();
        self.updated_at = self.last_used;
        self.version += 1;
    }

    /// Apply time-based decay to confidence based on category
    pub fn apply_decay(&mut self) {
        let decay_days = self.category.decay_days();
        let now = Utc::now().timestamp();
        let days_since_use = (now - self.last_used) as f64 / 86400.0;

        // Only decay after category-specific threshold
        if days_since_use > decay_days as f64 {
            let excess_days = days_since_use - decay_days as f64;
            let decay_factor = 0.99_f64.powf(excess_days);
            self.confidence = (self.confidence as f64 * decay_factor) as f32;
        }
    }

    /// Get the decayed confidence (without modifying)
    pub fn decayed_confidence(&self) -> f32 {
        let decay_days = self.category.decay_days();
        let now = Utc::now().timestamp();
        let days_since_use = (now - self.last_used) as f64 / 86400.0;

        if days_since_use > decay_days as f64 {
            let excess_days = days_since_use - decay_days as f64;
            let decay_factor = 0.99_f64.powf(excess_days);
            (self.confidence as f64 * decay_factor) as f32
        } else {
            self.confidence
        }
    }

    /// Check if this fact is still reliable (above threshold)
    pub fn is_reliable(&self, min_confidence: f32) -> bool {
        self.decayed_confidence() >= min_confidence
    }

    /// Mark as deleted (soft delete)
    pub fn delete(&mut self) {
        self.deleted = true;
        self.updated_at = Utc::now().timestamp();
        self.version += 1;
    }

    /// Get a display string for context injection
    pub fn to_context_string(&self) -> String {
        if let Some(ref ctx) = self.context {
            format!("{}: {} (when {})", self.key, self.value, ctx)
        } else {
            format!("{}: {}", self.key, self.value)
        }
    }
}

impl fmt::Display for PersonalFact {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "[{:.0}%] {}/{}: {}",
            self.confidence * 100.0,
            self.category,
            self.key,
            self.value
        )
    }
}

/// Category of personal fact
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PersonalFactCategory {
    /// Name, role, team, organization (decay: 180 days)
    Identity,

    /// Coding style, communication tone, tool preferences (decay: 60 days)
    Preference,

    /// Skills, languages, frameworks known (decay: 90 days)
    Capability,

    /// Current project, recent work, active files (decay: 14 days)
    Context,

    /// Limitations, access restrictions, time zones (decay: 90 days)
    Constraint,

    /// Connections between facts, Zettelkasten-style (decay: 60 days)
    Relationship,

    /// User's preferred ambiguity types for disambiguation (decay: 60 days)
    /// Example: "User prefers SEMANTIC type for technical term disambiguation"
    AmbiguityTypePreference,
}

impl PersonalFactCategory {
    /// Get all categories
    pub fn all() -> &'static [PersonalFactCategory] {
        &[
            PersonalFactCategory::Identity,
            PersonalFactCategory::Preference,
            PersonalFactCategory::Capability,
            PersonalFactCategory::Context,
            PersonalFactCategory::Constraint,
            PersonalFactCategory::Relationship,
            PersonalFactCategory::AmbiguityTypePreference,
        ]
    }

    /// Get the decay days for this category
    pub fn decay_days(&self) -> u32 {
        match self {
            PersonalFactCategory::Identity => 180,
            PersonalFactCategory::Preference => 60,
            PersonalFactCategory::Capability => 90,
            PersonalFactCategory::Context => 14,
            PersonalFactCategory::Constraint => 90,
            PersonalFactCategory::Relationship => 60,
            PersonalFactCategory::AmbiguityTypePreference => 60,
        }
    }

    /// Get a short code for the category
    pub fn code(&self) -> &'static str {
        match self {
            PersonalFactCategory::Identity => "id",
            PersonalFactCategory::Preference => "pref",
            PersonalFactCategory::Capability => "cap",
            PersonalFactCategory::Context => "ctx",
            PersonalFactCategory::Constraint => "limit",
            PersonalFactCategory::Relationship => "rel",
            PersonalFactCategory::AmbiguityTypePreference => "amb",
        }
    }

    /// Get a human-readable description
    pub fn description(&self) -> &'static str {
        match self {
            PersonalFactCategory::Identity => "Identity (name, role, organization)",
            PersonalFactCategory::Preference => "Preferences (coding style, tools)",
            PersonalFactCategory::Capability => "Capabilities (skills, languages)",
            PersonalFactCategory::Context => "Context (current project, recent work)",
            PersonalFactCategory::Constraint => "Constraints (limitations, restrictions)",
            PersonalFactCategory::Relationship => "Relationships (fact connections)",
            PersonalFactCategory::AmbiguityTypePreference => "Ambiguity Type Preferences (AT-CoT)",
        }
    }
}

impl fmt::Display for PersonalFactCategory {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.code())
    }
}

impl std::str::FromStr for PersonalFactCategory {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "id" | "identity" => Ok(PersonalFactCategory::Identity),
            "pref" | "preference" => Ok(PersonalFactCategory::Preference),
            "cap" | "capability" => Ok(PersonalFactCategory::Capability),
            "ctx" | "context" => Ok(PersonalFactCategory::Context),
            "limit" | "constraint" => Ok(PersonalFactCategory::Constraint),
            "rel" | "relationship" => Ok(PersonalFactCategory::Relationship),
            _ => Err(format!("Unknown category: {}", s)),
        }
    }
}

/// How a personal fact was learned
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PersonalFactSource {
    /// User directly stated via /profile command (confidence: 0.9)
    ExplicitStatement,

    /// Detected from conversation patterns like "I prefer..." (confidence: 0.7)
    InferredFromBehavior,

    /// From initial profile setup (confidence: 0.85)
    ProfileSetup,

    /// Observed from tool usage patterns (confidence: 0.6)
    SystemObserved,
}

impl PersonalFactSource {
    /// Get the initial confidence for this source type
    pub fn initial_confidence(&self) -> f32 {
        match self {
            PersonalFactSource::ExplicitStatement => 0.9,
            PersonalFactSource::InferredFromBehavior => 0.7,
            PersonalFactSource::ProfileSetup => 0.85,
            PersonalFactSource::SystemObserved => 0.6,
        }
    }

    /// Get a human-readable description
    pub fn description(&self) -> &'static str {
        match self {
            PersonalFactSource::ExplicitStatement => "Explicitly stated via /profile",
            PersonalFactSource::InferredFromBehavior => "Inferred from conversation",
            PersonalFactSource::ProfileSetup => "From profile setup",
            PersonalFactSource::SystemObserved => "Observed from usage patterns",
        }
    }
}

impl fmt::Display for PersonalFactSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            PersonalFactSource::ExplicitStatement => "explicit",
            PersonalFactSource::InferredFromBehavior => "inferred",
            PersonalFactSource::ProfileSetup => "setup",
            PersonalFactSource::SystemObserved => "observed",
        };
        write!(f, "{}", s)
    }
}

/// A pending fact submission (for offline queue)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PendingFactSubmission {
    /// The fact to submit
    pub fact: PersonalFact,

    /// When this submission was queued
    pub queued_at: i64,

    /// Number of submission attempts
    pub attempts: u32,

    /// Last error message (if any)
    pub last_error: Option<String>,
}

impl PendingFactSubmission {
    /// Create a new pending submission for the given fact.
    pub fn new(fact: PersonalFact) -> Self {
        Self {
            fact,
            queued_at: Utc::now().timestamp(),
            attempts: 0,
            last_error: None,
        }
    }

    /// Record a submission attempt with an optional error.
    pub fn record_attempt(&mut self, error: Option<String>) {
        self.attempts += 1;
        self.last_error = error;
    }
}

/// A reinforcement or contradiction report to send to server
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PersonalFactFeedback {
    /// ID of the fact being reported on
    pub fact_id: String,

    /// Whether this is a reinforcement (true) or contradiction (false)
    pub is_reinforcement: bool,

    /// Optional context about the feedback
    pub context: Option<String>,

    /// When this feedback was generated
    pub timestamp: i64,
}

impl PersonalFactFeedback {
    /// Create a reinforcement feedback for the given fact.
    pub fn reinforcement(fact_id: String, context: Option<String>) -> Self {
        Self {
            fact_id,
            is_reinforcement: true,
            context,
            timestamp: Utc::now().timestamp(),
        }
    }

    /// Create a contradiction feedback for the given fact.
    pub fn contradiction(fact_id: String, context: Option<String>) -> Self {
        Self {
            fact_id,
            is_reinforcement: false,
            context,
            timestamp: Utc::now().timestamp(),
        }
    }
}

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

    #[test]
    fn test_fact_creation() {
        let fact = PersonalFact::new(
            PersonalFactCategory::Preference,
            "preferred_language".to_string(),
            "Rust".to_string(),
            None,
            PersonalFactSource::ExplicitStatement,
            false,
        );

        assert_eq!(fact.category, PersonalFactCategory::Preference);
        assert_eq!(fact.confidence, 0.9); // ExplicitStatement initial
        assert_eq!(fact.reinforcements, 0);
        assert!(!fact.deleted);
        assert!(!fact.local_only);
    }

    #[test]
    fn test_reinforcement() {
        let mut fact = PersonalFact::new(
            PersonalFactCategory::Context,
            "current_project".to_string(),
            "brainwires".to_string(),
            None,
            PersonalFactSource::SystemObserved, // 0.6 initial
            false,
        );

        assert_eq!(fact.confidence, 0.6);

        // Reinforce with alpha = 0.1
        fact.reinforce(0.1);

        // new = 0.1 * 1.0 + 0.9 * 0.6 = 0.1 + 0.54 = 0.64
        assert!((fact.confidence - 0.64).abs() < 0.001);
        assert_eq!(fact.reinforcements, 1);
    }

    #[test]
    fn test_contradiction() {
        let mut fact = PersonalFact::new(
            PersonalFactCategory::Preference,
            "editor".to_string(),
            "VSCode".to_string(),
            None,
            PersonalFactSource::ExplicitStatement, // 0.9 initial
            false,
        );

        // Contradict with alpha = 0.1
        fact.contradict(0.1);

        // new = 0.1 * 0.0 + 0.9 * 0.9 = 0 + 0.81 = 0.81
        assert!((fact.confidence - 0.81).abs() < 0.001);
        assert_eq!(fact.contradictions, 1);
    }

    #[test]
    fn test_category_decay_days() {
        assert_eq!(PersonalFactCategory::Identity.decay_days(), 180);
        assert_eq!(PersonalFactCategory::Preference.decay_days(), 60);
        assert_eq!(PersonalFactCategory::Context.decay_days(), 14);
        assert_eq!(PersonalFactCategory::Capability.decay_days(), 90);
    }

    #[test]
    fn test_category_parsing() {
        assert_eq!(
            "id".parse::<PersonalFactCategory>().unwrap(),
            PersonalFactCategory::Identity
        );
        assert_eq!(
            "pref".parse::<PersonalFactCategory>().unwrap(),
            PersonalFactCategory::Preference
        );
        assert_eq!(
            "ctx".parse::<PersonalFactCategory>().unwrap(),
            PersonalFactCategory::Context
        );
        assert!("invalid".parse::<PersonalFactCategory>().is_err());
    }

    #[test]
    fn test_source_initial_confidence() {
        assert_eq!(
            PersonalFactSource::ExplicitStatement.initial_confidence(),
            0.9
        );
        assert_eq!(
            PersonalFactSource::InferredFromBehavior.initial_confidence(),
            0.7
        );
        assert_eq!(PersonalFactSource::ProfileSetup.initial_confidence(), 0.85);
        assert_eq!(PersonalFactSource::SystemObserved.initial_confidence(), 0.6);
    }

    #[test]
    fn test_fact_display() {
        let fact = PersonalFact::new(
            PersonalFactCategory::Preference,
            "language".to_string(),
            "Rust".to_string(),
            None,
            PersonalFactSource::ExplicitStatement,
            false,
        );

        let display = format!("{}", fact);
        assert!(display.contains("90%"));
        assert!(display.contains("pref"));
        assert!(display.contains("language"));
        assert!(display.contains("Rust"));
    }

    #[test]
    fn test_context_string() {
        let fact = PersonalFact::new(
            PersonalFactCategory::Preference,
            "framework".to_string(),
            "React".to_string(),
            Some("frontend projects".to_string()),
            PersonalFactSource::ExplicitStatement,
            false,
        );

        assert_eq!(
            fact.to_context_string(),
            "framework: React (when frontend projects)"
        );

        let fact_no_context = PersonalFact::new(
            PersonalFactCategory::Identity,
            "name".to_string(),
            "John".to_string(),
            None,
            PersonalFactSource::ExplicitStatement,
            false,
        );

        assert_eq!(fact_no_context.to_context_string(), "name: John");
    }
}