opencrabs 0.3.78

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Install with: cargo install opencrabs
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
//! Epistemic Engine — Belief Tracking with Confidence Levels
//!
//! Tracks beliefs (facts, decisions, context) with confidence levels and
//! source attribution. Implements decay logic and contradiction detection.
//!
//! Design:
//! - Confidence levels: verified, inferred, uncertain, contradicted
//! - Source attribution: every belief tagged with origin
//! - Decay: unverified beliefs lose confidence after 30 days
//! - Contradiction detection: new fact conflicts existing belief → flagged
//! - Storage: ~/.opencrabs/brain/epistemic/beliefs.toml
//!
//! Config: ralph_loop.toml [epistemic] section (already exists)

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::OnceLock;

/// Confidence levels for beliefs, ordered from most to least certain.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Confidence {
    /// Conflicts with another belief — needs resolution (lowest confidence)
    Contradicted,
    /// Not yet verified, assumed true
    Uncertain,
    /// Derived from other beliefs or logical inference
    Inferred,
    /// Confirmed by user or system verification (highest confidence)
    Verified,
}

impl Confidence {
    /// Decay confidence by one level. Verified beliefs don't decay.
    pub fn decay(self) -> Self {
        match self {
            Confidence::Verified => Confidence::Verified,
            Confidence::Inferred => Confidence::Uncertain,
            Confidence::Uncertain => Confidence::Contradicted,
            Confidence::Contradicted => Confidence::Contradicted,
        }
    }

    /// Human-readable label
    pub fn label(&self) -> &'static str {
        match self {
            Confidence::Verified => "verified",
            Confidence::Inferred => "inferred",
            Confidence::Uncertain => "uncertain",
            Confidence::Contradicted => "contradicted",
        }
    }
}

/// Source attribution for a belief.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Source {
    /// Who/what provided this belief (e.g. "user:adolfo", "inference", "session:abc123")
    pub origin: String,
    /// When the belief was first recorded
    pub recorded_at: DateTime<Utc>,
    /// When the belief was last verified
    pub last_verified: DateTime<Utc>,
}

/// A single belief with confidence and source tracking.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Belief {
    /// Unique key for this belief (e.g. "memory:truelens:staging_ip")
    pub key: String,
    /// The belief value (e.g. "159.65.49.225")
    pub value: String,
    /// Current confidence level
    pub confidence: Confidence,
    /// Source attribution
    pub source: Source,
    /// Optional notes or context
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub notes: Option<String>,
}

/// The epistemic store — all tracked beliefs.
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct EpistemicStore {
    /// Map of belief key → belief
    #[serde(default)]
    pub beliefs: HashMap<String, Belief>,
    /// Schema version for future migrations
    #[serde(default = "default_version")]
    pub version: u32,
}

fn default_version() -> u32 {
    1
}

impl EpistemicStore {
    /// Create a new empty store.
    pub fn new() -> Self {
        Self {
            beliefs: HashMap::new(),
            version: 1,
        }
    }

    /// Add or update a belief. If the key exists and the value differs,
    /// the old belief is marked as contradicted.
    pub fn add_belief(
        &mut self,
        key: &str,
        value: &str,
        confidence: Confidence,
        origin: &str,
    ) -> ContradictionResult {
        let now = Utc::now();

        // Check for contradiction with existing belief.
        // Clone first to avoid borrow conflict (immutable get + mutable insert).
        let existing = self.beliefs.get(key).cloned();
        if let Some(existing) = existing
            && existing.value != value
            && existing.confidence != Confidence::Contradicted
        {
            // Extract old_value BEFORE mutable borrow
            let old_value = existing.value.clone();

            // Mark existing belief as contradicted
            let mut contradicted = existing.clone();
            contradicted.confidence = Confidence::Contradicted;
            contradicted.notes = Some(format!(
                "Contradicted by new value '{}' from {} at {}",
                value,
                origin,
                now.format("%Y-%m-%d %H:%M:%S UTC")
            ));
            self.beliefs.insert(
                format!("{}:contradicted:{}", key, now.timestamp()),
                contradicted,
            );

            // Insert new belief
            let belief = Belief {
                key: key.to_string(),
                value: value.to_string(),
                confidence,
                source: Source {
                    origin: origin.to_string(),
                    recorded_at: now,
                    last_verified: now,
                },
                notes: None,
            };
            self.beliefs.insert(key.to_string(), belief);

            return ContradictionResult::Contradicted {
                old_value,
                new_value: value.to_string(),
            };
        }

        // No contradiction — insert or update
        let belief = Belief {
            key: key.to_string(),
            value: value.to_string(),
            confidence,
            source: Source {
                origin: origin.to_string(),
                recorded_at: now,
                last_verified: now,
            },
            notes: None,
        };
        self.beliefs.insert(key.to_string(), belief);

        ContradictionResult::NoContradiction
    }

    /// Get a belief by key.
    pub fn get_belief(&self, key: &str) -> Option<&Belief> {
        self.beliefs.get(key)
    }

    /// Re-verify a belief (updates last_verified timestamp).
    pub fn verify_belief(&mut self, key: &str) -> bool {
        if let Some(belief) = self.beliefs.get_mut(key) {
            belief.source.last_verified = Utc::now();
            belief.confidence = Confidence::Verified;
            true
        } else {
            false
        }
    }

    /// Apply decay logic: beliefs not verified within `decay_days` drop
    /// one confidence level. Verified beliefs are immune.
    pub fn apply_decay(&mut self, decay_days: i64) -> Vec<String> {
        let now = Utc::now();
        let mut decayed = Vec::new();

        for belief in self.beliefs.values_mut() {
            if belief.confidence == Confidence::Verified {
                continue; // Verified beliefs don't decay
            }

            let age_days = (now - belief.source.last_verified).num_days();
            if age_days >= decay_days {
                let old = belief.confidence;
                belief.confidence = belief.confidence.decay();
                if belief.confidence != old {
                    decayed.push(format!(
                        "{}: {}{} ({} days since verification)",
                        belief.key,
                        old.label(),
                        belief.confidence.label(),
                        age_days
                    ));
                }
            }
        }

        decayed
    }

    /// List beliefs filtered by confidence level.
    pub fn list_by_confidence(&self, confidence: Confidence) -> Vec<&Belief> {
        self.beliefs
            .values()
            .filter(|b| b.confidence == confidence)
            .collect()
    }

    /// List all contradicted beliefs (for review).
    pub fn list_contradictions(&self) -> Vec<&Belief> {
        self.list_by_confidence(Confidence::Contradicted)
    }

    /// List beliefs whose key starts with `prefix`.
    pub fn list_by_key_prefix(&self, prefix: &str) -> Vec<&Belief> {
        self.beliefs
            .values()
            .filter(|b| b.key.starts_with(prefix))
            .collect()
    }

    /// Save the store to disk.
    pub fn save(&self, path: &PathBuf) -> std::io::Result<()> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let content = toml::to_string_pretty(self).map_err(std::io::Error::other)?;
        std::fs::write(path, content)
    }

    /// Load the store from disk. Returns empty store if file missing.
    pub fn load(path: &PathBuf) -> Self {
        match std::fs::read_to_string(path) {
            Ok(content) => match toml::from_str(&content) {
                Ok(store) => store,
                Err(e) => {
                    tracing::warn!("Epistemic store parse error: {}", e);
                    Self::new()
                }
            },
            Err(_) => Self::new(),
        }
    }
}

/// Result of adding a belief — indicates if a contradiction was detected.
#[derive(Debug, Clone, PartialEq)]
pub enum ContradictionResult {
    /// No contradiction — belief added/updated normally
    NoContradiction,
    /// Contradiction detected — old belief marked as contradicted
    Contradicted {
        old_value: String,
        new_value: String,
    },
}

/// Get the epistemic store path.
fn epistemic_store_path() -> Option<PathBuf> {
    let home = dirs::home_dir()?;
    Some(home.join(".opencrabs/brain/epistemic/beliefs.toml"))
}

/// Global epistemic store (cached for session lifetime).
static STORE: OnceLock<std::sync::Mutex<EpistemicStore>> = OnceLock::new();

fn get_store() -> &'static std::sync::Mutex<EpistemicStore> {
    STORE.get_or_init(|| {
        let path = epistemic_store_path().expect("home dir must exist");
        std::sync::Mutex::new(EpistemicStore::load(&path))
    })
}

/// Add a belief to the global store. Returns contradiction result.
pub fn add_belief(
    key: &str,
    value: &str,
    confidence: Confidence,
    origin: &str,
) -> ContradictionResult {
    let store = get_store();
    let mut guard = store.lock().expect("epistemic store lock poisoned");
    let result = guard.add_belief(key, value, confidence, origin);

    // Auto-save after modification
    if let Some(path) = epistemic_store_path()
        && let Err(e) = guard.save(&path)
    {
        tracing::warn!("Failed to save epistemic store: {}", e);
    }

    result
}

/// Get a belief from the global store.
pub fn get_belief(key: &str) -> Option<Belief> {
    let store = get_store();
    let guard = store.lock().expect("epistemic store lock poisoned");
    guard.get_belief(key).cloned()
}

/// Verify a belief in the global store.
pub fn verify_belief(key: &str) -> bool {
    let store = get_store();
    let mut guard = store.lock().expect("epistemic store lock poisoned");
    let result = guard.verify_belief(key);

    if result
        && let Some(path) = epistemic_store_path()
        && let Err(e) = guard.save(&path)
    {
        tracing::warn!("Failed to save epistemic store: {}", e);
    }

    result
}

/// Apply decay to the global store. Returns list of decayed beliefs.
pub fn apply_decay(decay_days: i64) -> Vec<String> {
    let store = get_store();
    let mut guard = store.lock().expect("epistemic store lock poisoned");
    let decayed = guard.apply_decay(decay_days);

    if !decayed.is_empty()
        && let Some(path) = epistemic_store_path()
        && let Err(e) = guard.save(&path)
    {
        tracing::warn!("Failed to save epistemic store: {}", e);
    }

    decayed
}

/// List all contradicted beliefs in the global store.
pub fn list_contradictions() -> Vec<Belief> {
    let store = get_store();
    let guard = store.lock().expect("epistemic store lock poisoned");
    guard.list_contradictions().into_iter().cloned().collect()
}

/// List beliefs whose key starts with `prefix` from the global store.
pub fn list_by_prefix(prefix: &str) -> Vec<Belief> {
    let store = get_store();
    let guard = store.lock().expect("epistemic store lock poisoned");
    guard
        .list_by_key_prefix(prefix)
        .into_iter()
        .cloned()
        .collect()
}

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

    #[test]
    fn test_confidence_ordering() {
        assert!(Confidence::Verified > Confidence::Inferred);
        assert!(Confidence::Inferred > Confidence::Uncertain);
        assert!(Confidence::Uncertain > Confidence::Contradicted);
    }

    #[test]
    fn test_confidence_decay() {
        assert_eq!(Confidence::Verified.decay(), Confidence::Verified);
        assert_eq!(Confidence::Inferred.decay(), Confidence::Uncertain);
        assert_eq!(Confidence::Uncertain.decay(), Confidence::Contradicted);
        assert_eq!(Confidence::Contradicted.decay(), Confidence::Contradicted);
    }

    #[test]
    fn test_add_belief_no_contradiction() {
        let mut store = EpistemicStore::new();
        let result = store.add_belief("test:key", "value1", Confidence::Verified, "test");
        assert_eq!(result, ContradictionResult::NoContradiction);
        assert_eq!(store.get_belief("test:key").unwrap().value, "value1");
    }

    #[test]
    fn test_add_belief_contradiction() {
        let mut store = EpistemicStore::new();
        store.add_belief("test:key", "value1", Confidence::Verified, "test");
        let result = store.add_belief("test:key", "value2", Confidence::Inferred, "test2");

        assert!(matches!(result, ContradictionResult::Contradicted { .. }));

        // Old belief should be marked as contradicted
        let contradicted: Vec<_> = store.list_contradictions();
        assert_eq!(contradicted.len(), 1);
        assert_eq!(contradicted[0].value, "value1");

        // New belief should be active
        assert_eq!(store.get_belief("test:key").unwrap().value, "value2");
    }

    #[test]
    fn test_verify_belief() {
        let mut store = EpistemicStore::new();
        store.add_belief("test:key", "value", Confidence::Uncertain, "test");
        assert!(store.verify_belief("test:key"));
        assert_eq!(
            store.get_belief("test:key").unwrap().confidence,
            Confidence::Verified
        );
    }

    #[test]
    fn test_decay_logic() {
        let mut store = EpistemicStore::new();

        // Add a belief with old last_verified
        let mut belief = Belief {
            key: "test:old".to_string(),
            value: "old_value".to_string(),
            confidence: Confidence::Inferred,
            source: Source {
                origin: "test".to_string(),
                recorded_at: Utc::now() - chrono::Duration::days(45),
                last_verified: Utc::now() - chrono::Duration::days(45),
            },
            notes: None,
        };
        store.beliefs.insert("test:old".to_string(), belief.clone());

        // Add a recent belief
        belief.key = "test:recent".to_string();
        belief.confidence = Confidence::Inferred;
        belief.source.last_verified = Utc::now();
        store.beliefs.insert("test:recent".to_string(), belief);

        // Apply decay with 30-day threshold
        let decayed = store.apply_decay(30);

        // Only the old belief should decay
        assert_eq!(decayed.len(), 1);
        assert!(decayed[0].contains("test:old"));
        assert_eq!(
            store.get_belief("test:old").unwrap().confidence,
            Confidence::Uncertain
        );
        assert_eq!(
            store.get_belief("test:recent").unwrap().confidence,
            Confidence::Inferred
        );
    }

    #[test]
    fn test_verified_beliefs_dont_decay() {
        let mut store = EpistemicStore::new();

        let belief = Belief {
            key: "test:verified".to_string(),
            value: "verified_value".to_string(),
            confidence: Confidence::Verified,
            source: Source {
                origin: "test".to_string(),
                recorded_at: Utc::now() - chrono::Duration::days(100),
                last_verified: Utc::now() - chrono::Duration::days(100),
            },
            notes: None,
        };
        store.beliefs.insert("test:verified".to_string(), belief);

        let decayed = store.apply_decay(30);
        assert!(decayed.is_empty());
        assert_eq!(
            store.get_belief("test:verified").unwrap().confidence,
            Confidence::Verified
        );
    }

    #[test]
    fn test_serialization_roundtrip() {
        let mut store = EpistemicStore::new();
        store.add_belief("test:key", "value", Confidence::Inferred, "test:origin");

        let toml_str = toml::to_string_pretty(&store).unwrap();
        let loaded: EpistemicStore = toml::from_str(&toml_str).unwrap();

        assert_eq!(loaded.get_belief("test:key").unwrap().value, "value");
        assert_eq!(
            loaded.get_belief("test:key").unwrap().confidence,
            Confidence::Inferred
        );
    }

    #[test]
    fn test_list_by_key_prefix() {
        let mut store = EpistemicStore::new();
        store.add_belief(
            "plan:task:1:abc",
            "failed",
            Confidence::Contradicted,
            "test",
        );
        store.add_belief("plan:task:2:def", "done", Confidence::Verified, "test");
        store.add_belief(
            "memory:truelens:ip",
            "1.2.3.4",
            Confidence::Inferred,
            "test",
        );

        let plan_beliefs = store.list_by_key_prefix("plan:task:");
        assert_eq!(plan_beliefs.len(), 2);

        let memory_beliefs = store.list_by_key_prefix("memory:");
        assert_eq!(memory_beliefs.len(), 1);
        assert_eq!(memory_beliefs[0].key, "memory:truelens:ip");

        let empty = store.list_by_key_prefix("nonexistent:");
        assert!(empty.is_empty());
    }
}