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
//! 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();
// Archive the superseded belief under its OWN namespace (#1083).
// The archive key PREFIXES rather than extends the original: a
// `{key}:contradicted:{ts}` suffix still starts with the original
// key, so every superseded copy kept matching prefix queries
// forever and piled up in whatever surface reads them. The `key`
// field is set to the archive key too, so field and map key agree.
let archive_key = format!("contradicted:{}:{}", now.timestamp(), key);
let mut contradicted = existing.clone();
contradicted.key = archive_key.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(archive_key, 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()
}