zkr 0.1.5

Evidence-backed temporal memory for personal agents
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
use serde::{Deserialize, Serialize};
use std::fmt;

macro_rules! string_id {
    ($name:ident) => {
        #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
        #[serde(transparent)]
        pub struct $name(pub String);

        impl $name {
            pub fn new(value: impl Into<String>) -> Result<Self, ValidationError> {
                let value = value.into();
                validate_text(stringify!($name), &value)?;
                Ok(Self(value))
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                self.0.fmt(formatter)
            }
        }
    };
}

string_id!(TenantId);
string_id!(PersonId);
string_id!(SourceId);
string_id!(EvidenceId);
string_id!(ClaimId);
string_id!(ProfileEntryId);
string_id!(DailyReviewId);

pub type Timestamp = i64;

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct TimeRange {
    pub from: Timestamp,
    pub until: Option<Timestamp>,
}

impl TimeRange {
    pub fn new(from: Timestamp, until: Option<Timestamp>) -> Result<Self, ValidationError> {
        if until.is_some_and(|until| until <= from) {
            return Err(ValidationError::InvalidTimeRange { from, until });
        }
        Ok(Self { from, until })
    }

    pub fn contains(&self, timestamp: Timestamp) -> bool {
        timestamp >= self.from && self.until.is_none_or(|until| timestamp < until)
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Source {
    pub id: SourceId,
    pub tenant_id: TenantId,
    pub person_id: PersonId,
    pub revision: u64,
    pub kind: SourceKind,
    pub content: String,
    pub captured_at: Timestamp,
    pub recorded_at: Timestamp,
    pub deleted_at: Option<Timestamp>,
}

impl Source {
    pub fn validate(&self) -> Result<(), ValidationError> {
        validate_ids([
            ("source id", &self.id.0),
            ("tenant id", &self.tenant_id.0),
            ("person id", &self.person_id.0),
        ])?;
        if self.revision == 0 {
            return Err(ValidationError::ZeroRevision);
        }
        validate_text("source content", &self.content)?;
        if self
            .deleted_at
            .is_some_and(|deleted| deleted < self.recorded_at)
        {
            return Err(ValidationError::DeletionBeforeRecording);
        }
        Ok(())
    }

    pub fn tombstone(&self, deleted_at: Timestamp) -> Result<Self, ValidationError> {
        if deleted_at < self.recorded_at {
            return Err(ValidationError::DeletionBeforeRecording);
        }
        Ok(Self {
            revision: self
                .revision
                .checked_add(1)
                .ok_or(ValidationError::RevisionOverflow)?,
            recorded_at: deleted_at,
            deleted_at: Some(deleted_at),
            ..self.clone()
        })
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SourceKind {
    Conversation,
    Screen,
    Audio,
    Document,
    Integration,
    UserCorrection,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Evidence {
    pub id: EvidenceId,
    pub tenant_id: TenantId,
    pub person_id: PersonId,
    pub source_id: SourceId,
    pub source_revision: u64,
    pub quote: String,
    pub byte_range: Option<ByteRange>,
    pub recorded_at: Timestamp,
}

impl Evidence {
    pub fn validate(&self) -> Result<(), ValidationError> {
        validate_ids([
            ("evidence id", &self.id.0),
            ("tenant id", &self.tenant_id.0),
            ("person id", &self.person_id.0),
            ("source id", &self.source_id.0),
        ])?;
        if self.source_revision == 0 {
            return Err(ValidationError::ZeroRevision);
        }
        validate_text("evidence quote", &self.quote)?;
        if let Some(range) = &self.byte_range {
            range.validate()?;
        }
        Ok(())
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ByteRange {
    pub start: u64,
    pub end: u64,
}

impl ByteRange {
    pub fn validate(&self) -> Result<(), ValidationError> {
        if self.start >= self.end {
            return Err(ValidationError::InvalidByteRange {
                start: self.start,
                end: self.end,
            });
        }
        Ok(())
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Claim {
    pub id: ClaimId,
    pub tenant_id: TenantId,
    pub person_id: PersonId,
    pub subject: String,
    pub predicate: String,
    pub value: String,
    pub valid_time: TimeRange,
    pub recorded_time: TimeRange,
    pub status: ClaimStatus,
}

impl Claim {
    pub fn validate(&self) -> Result<(), ValidationError> {
        validate_ids([
            ("claim id", &self.id.0),
            ("tenant id", &self.tenant_id.0),
            ("person id", &self.person_id.0),
        ])?;
        validate_text("claim subject", &self.subject)?;
        validate_text("claim predicate", &self.predicate)?;
        validate_text("claim value", &self.value)?;
        TimeRange::new(self.valid_time.from, self.valid_time.until)?;
        TimeRange::new(self.recorded_time.from, self.recorded_time.until)?;
        Ok(())
    }

    pub fn accept(&mut self) -> Result<(), ValidationError> {
        if self.status != ClaimStatus::Proposed {
            return Err(ValidationError::InvalidClaimTransition {
                from: self.status.clone(),
                to: ClaimStatus::Accepted,
            });
        }
        self.status = ClaimStatus::Accepted;
        Ok(())
    }

    pub fn supersede(&mut self, at: Timestamp) -> Result<(), ValidationError> {
        if self.status != ClaimStatus::Accepted {
            return Err(ValidationError::InvalidClaimTransition {
                from: self.status.clone(),
                to: ClaimStatus::Superseded,
            });
        }
        self.recorded_time = TimeRange::new(self.recorded_time.from, Some(at))?;
        self.status = ClaimStatus::Superseded;
        Ok(())
    }

    pub fn reject(&mut self) -> Result<(), ValidationError> {
        if self.status != ClaimStatus::Proposed {
            return Err(ValidationError::InvalidClaimTransition {
                from: self.status.clone(),
                to: ClaimStatus::Rejected,
            });
        }
        self.status = ClaimStatus::Rejected;
        Ok(())
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ClaimStatus {
    Proposed,
    Accepted,
    Superseded,
    Rejected,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ClaimEvidence {
    pub tenant_id: TenantId,
    pub person_id: PersonId,
    pub claim_id: ClaimId,
    pub evidence_id: EvidenceId,
    pub relation: EvidenceRelation,
    pub confidence_basis_points: u16,
}

impl ClaimEvidence {
    pub fn validate(&self) -> Result<(), ValidationError> {
        validate_ids([
            ("tenant id", &self.tenant_id.0),
            ("person id", &self.person_id.0),
            ("claim id", &self.claim_id.0),
            ("evidence id", &self.evidence_id.0),
        ])?;
        if self.confidence_basis_points > 10_000 {
            return Err(ValidationError::InvalidConfidence(
                self.confidence_basis_points,
            ));
        }
        Ok(())
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EvidenceRelation {
    Supports,
    Contradicts,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ProfileEntry {
    pub id: ProfileEntryId,
    pub tenant_id: TenantId,
    pub person_id: PersonId,
    pub key: String,
    pub value: String,
    pub stability: ProfileStability,
    pub claim_id: ClaimId,
    pub recorded_at: Timestamp,
}

impl ProfileEntry {
    pub fn validate(&self) -> Result<(), ValidationError> {
        validate_ids([
            ("profile entry id", &self.id.0),
            ("tenant id", &self.tenant_id.0),
            ("person id", &self.person_id.0),
            ("claim id", &self.claim_id.0),
        ])?;
        validate_text("profile key", &self.key)?;
        validate_text("profile value", &self.value)
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProfileStability {
    Stable,
    Current,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct DailyReview {
    pub id: DailyReviewId,
    pub tenant_id: TenantId,
    pub person_id: PersonId,
    pub day: String,
    pub summary: String,
    pub evidence_ids: Vec<EvidenceId>,
    pub recorded_at: Timestamp,
}

impl DailyReview {
    pub fn validate(&self) -> Result<(), ValidationError> {
        validate_ids([
            ("daily review id", &self.id.0),
            ("tenant id", &self.tenant_id.0),
            ("person id", &self.person_id.0),
        ])?;
        validate_text("daily review day", &self.day)?;
        validate_text("daily review summary", &self.summary)?;
        if self.evidence_ids.is_empty() {
            return Err(ValidationError::MissingEvidence);
        }
        for id in &self.evidence_ids {
            validate_text("evidence id", &id.0)?;
        }
        Ok(())
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct RetrievalPack {
    pub query: String,
    pub items: Vec<RetrievalItem>,
    pub gaps: Vec<String>,
}

impl RetrievalPack {
    pub fn validate(&self) -> Result<(), ValidationError> {
        validate_text("retrieval query", &self.query)?;
        for item in &self.items {
            item.validate()?;
        }
        if self.gaps.iter().any(|gap| gap.trim().is_empty()) {
            return Err(ValidationError::EmptyText("retrieval gap"));
        }
        Ok(())
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct RetrievalItem {
    pub memory: MemoryRef,
    pub excerpt: String,
    pub relevance_basis_points: u16,
    pub evidence_ids: Vec<EvidenceId>,
}

impl RetrievalItem {
    pub fn validate(&self) -> Result<(), ValidationError> {
        self.memory.validate()?;
        validate_text("retrieval excerpt", &self.excerpt)?;
        if self.relevance_basis_points > 10_000 {
            return Err(ValidationError::InvalidRelevance(
                self.relevance_basis_points,
            ));
        }
        if self.evidence_ids.is_empty() {
            return Err(ValidationError::MissingEvidence);
        }
        for id in &self.evidence_ids {
            validate_text("evidence id", &id.0)?;
        }
        Ok(())
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", content = "id", rename_all = "snake_case")]
pub enum MemoryRef {
    Source(SourceId),
    Evidence(EvidenceId),
    Claim(ClaimId),
    ProfileEntry(ProfileEntryId),
    DailyReview(DailyReviewId),
}

impl MemoryRef {
    fn validate(&self) -> Result<(), ValidationError> {
        match self {
            Self::Source(id) => validate_text("source id", &id.0),
            Self::Evidence(id) => validate_text("evidence id", &id.0),
            Self::Claim(id) => validate_text("claim id", &id.0),
            Self::ProfileEntry(id) => validate_text("profile entry id", &id.0),
            Self::DailyReview(id) => validate_text("daily review id", &id.0),
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
pub enum ValidationError {
    #[error("{0} must not be empty")]
    EmptyText(&'static str),
    #[error("revision must be greater than zero")]
    ZeroRevision,
    #[error("source revision overflowed")]
    RevisionOverflow,
    #[error("time range ending at {until:?} must end after {from}")]
    InvalidTimeRange {
        from: Timestamp,
        until: Option<Timestamp>,
    },
    #[error("byte range {start}..{end} must not be empty or reversed")]
    InvalidByteRange { start: u64, end: u64 },
    #[error("source cannot be deleted before it was recorded")]
    DeletionBeforeRecording,
    #[error("confidence {0} must be at most 10000 basis points")]
    InvalidConfidence(u16),
    #[error("relevance {0} must be at most 10000 basis points")]
    InvalidRelevance(u16),
    #[error("record requires at least one evidence citation")]
    MissingEvidence,
    #[error("claim cannot transition from {from:?} to {to:?}")]
    InvalidClaimTransition { from: ClaimStatus, to: ClaimStatus },
}

fn validate_text(field: &'static str, value: &str) -> Result<(), ValidationError> {
    if value.trim().is_empty() {
        return Err(ValidationError::EmptyText(field));
    }
    Ok(())
}

fn validate_ids<const N: usize>(ids: [(&'static str, &str); N]) -> Result<(), ValidationError> {
    for (field, value) in ids {
        validate_text(field, value)?;
    }
    Ok(())
}

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

    fn claim(status: ClaimStatus) -> Claim {
        Claim {
            id: ClaimId("claim-1".into()),
            tenant_id: TenantId("tenant-1".into()),
            person_id: PersonId("person-1".into()),
            subject: "person-1".into(),
            predicate: "employer".into(),
            value: "Example Corp".into(),
            valid_time: TimeRange::new(100, None).expect("valid time"),
            recorded_time: TimeRange::new(110, None).expect("recorded time"),
            status,
        }
    }

    #[test]
    fn time_ranges_are_half_open() {
        let range = TimeRange::new(10, Some(20)).expect("valid range");
        assert!(range.contains(10));
        assert!(range.contains(19));
        assert!(!range.contains(20));
        assert!(TimeRange::new(10, Some(10)).is_err());
    }

    #[test]
    fn accepted_claim_can_be_superseded_without_losing_history() {
        let mut old = claim(ClaimStatus::Proposed);
        old.accept().expect("proposed claim can be accepted");
        old.supersede(200)
            .expect("accepted claim can be superseded");

        assert_eq!(old.status, ClaimStatus::Superseded);
        assert_eq!(old.recorded_time.until, Some(200));
        assert!(old.recorded_time.contains(199));
        assert!(!old.recorded_time.contains(200));
    }

    #[test]
    fn invalid_claim_transitions_are_rejected() {
        let mut accepted = claim(ClaimStatus::Accepted);
        assert!(matches!(
            accepted.reject(),
            Err(ValidationError::InvalidClaimTransition { .. })
        ));

        let mut proposed = claim(ClaimStatus::Proposed);
        assert!(matches!(
            proposed.supersede(200),
            Err(ValidationError::InvalidClaimTransition { .. })
        ));
    }

    #[test]
    fn evidence_backed_outputs_require_citations() {
        let review = DailyReview {
            id: DailyReviewId("review-1".into()),
            tenant_id: TenantId("tenant-1".into()),
            person_id: PersonId("person-1".into()),
            day: "2026-07-21".into(),
            summary: "Finished the memory core.".into(),
            evidence_ids: Vec::new(),
            recorded_at: 100,
        };
        assert_eq!(review.validate(), Err(ValidationError::MissingEvidence));

        let item = RetrievalItem {
            memory: MemoryRef::Claim(ClaimId("claim-1".into())),
            excerpt: "Works at Example Corp".into(),
            relevance_basis_points: 9_000,
            evidence_ids: Vec::new(),
        };
        assert_eq!(item.validate(), Err(ValidationError::MissingEvidence));
    }

    #[test]
    fn source_tombstone_cannot_predate_recording() {
        let source = Source {
            id: SourceId("source-1".into()),
            tenant_id: TenantId("tenant-1".into()),
            person_id: PersonId("person-1".into()),
            revision: 1,
            kind: SourceKind::Conversation,
            content: "I joined Example Corp.".into(),
            captured_at: 90,
            recorded_at: 100,
            deleted_at: None,
        };

        assert_eq!(
            source.tombstone(99),
            Err(ValidationError::DeletionBeforeRecording)
        );
        let tombstone = source.tombstone(101).expect("valid deletion timestamp");
        assert_eq!(source.revision, 1);
        assert_eq!(source.deleted_at, None);
        assert_eq!(tombstone.revision, 2);
        assert_eq!(tombstone.deleted_at, Some(101));
    }

    #[test]
    fn serde_keeps_memory_reference_kind_explicit() {
        let memory = MemoryRef::Claim(ClaimId("claim-1".into()));
        let json = serde_json::to_string(&memory).expect("serialize memory reference");
        assert_eq!(json, r#"{"kind":"claim","id":"claim-1"}"#);
    }
}