semantic-memory 0.5.14

Local-first hybrid semantic search (SQLite + FTS5 + usearch 2.25) with bitemporal truth and typed receipts
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
//! Versioned wire contracts for authority, witnessed retrieval, and injection governance.

use crate::StateView;
use serde::{Deserialize, Deserializer, Serialize};

macro_rules! bounded_f64 {
    ($name:ident, $min:expr, $max:expr) => {
        #[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Serialize)]
        #[serde(transparent)]
        pub struct $name(f64);

        impl $name {
            pub fn new(value: f64) -> Result<Self, String> {
                if !value.is_finite() || value < $min || value > $max {
                    return Err(format!(
                        "{} must be finite and within [{}, {}]",
                        stringify!($name),
                        $min,
                        $max
                    ));
                }
                Ok(Self(value))
            }

            pub fn get(self) -> f64 {
                self.0
            }
        }

        impl<'de> Deserialize<'de> for $name {
            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
                let value = f64::deserialize(deserializer)?;
                Self::new(value).map_err(serde::de::Error::custom)
            }
        }
    };
}

bounded_f64!(Probability, 0.0, 1.0);
bounded_f64!(Confidence, 0.0, 1.0);
bounded_f64!(CosineSimilarity, -1.0, 1.0);
bounded_f64!(NonNegativeWeight, 0.0, f64::MAX);

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct AuthoritySnapshotId(pub String);

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct RetrievalEpoch(pub u64);

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MemoryEnvelopeV1 {
    pub schema_version: String,
    pub memory_id: String,
    pub namespace: String,
    pub content: String,
    pub source: Option<String>,
    pub valid_at: String,
    pub recorded_at: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CapabilityManifestV1 {
    pub schema_version: String,
    pub principal: String,
    pub capabilities: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StageOutcomeV1 {
    NotPlanned,
    Skipped,
    AnalysisOnly,
    Applied,
    Degraded,
    Failed,
    BudgetExceeded,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RetrievalWitnessV1 {
    pub schema_version: String,
    pub request_id: String,
    pub evaluated_at: String,
    pub authority_snapshot_id: AuthoritySnapshotId,
    pub retrieval_epoch: RetrievalEpoch,
    pub query_digest: String,
    pub config_digest: String,
    pub ordered_result_ids: Vec<String>,
    pub ordered_result_digests: Vec<String>,
    pub stage_outcomes: Vec<(String, StageOutcomeV1)>,
    pub degradations: Vec<String>,
    pub cached_witness_parent: Option<String>,
}

/// Snapshot metadata used by governing systems for cache validation and replay integrity.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AuthorityStateV1 {
    pub snapshot_id: AuthoritySnapshotId,
    pub retrieval_epoch: RetrievalEpoch,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RetrievalResponseV1<T> {
    pub schema_version: String,
    pub state_view: StateView,
    pub results: Vec<T>,
    pub witness: RetrievalWitnessV1,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum InjectionDisposition {
    Admitted,
    PartiallyAdmitted,
    Rejected,
    FailedClosed,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InjectionDecisionV1 {
    pub schema_version: String,
    pub retrieval_receipt_id: String,
    pub principal: String,
    pub host: String,
    pub policy_digest: String,
    pub admitted_ids: Vec<String>,
    pub rejected_ids: Vec<String>,
    pub disposition: InjectionDisposition,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SupersessionReceiptV1 {
    pub schema_version: String,
    pub operation_id: String,
    pub caller_idempotency_key: String,
    pub superseded_id: String,
    pub replacement_id: String,
    pub authority_snapshot_id: AuthoritySnapshotId,
    pub retrieval_epoch: RetrievalEpoch,
    pub committed_at: String,
}

/// Capability-bearing caller permit for the governed authority mutation lane.
///
/// Ordinary callers cannot construct or deserialize this credential:
/// ```compile_fail
/// use semantic_memory::{AuthorityAdmission, AuthorityPermit};
/// let _forged = AuthorityPermit {
///     principal: "attacker".into(),
///     caller_id: "attacker".into(),
///     capability: AuthorityPermit::APPEND_CAPABILITY.into(),
///     admission: AuthorityAdmission::OperatorSystem,
///     origin_authority: None,
/// };
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct AuthorityPermit {
    pub(crate) principal: String,
    pub(crate) caller_id: String,
    pub(crate) capability: String,
    pub(crate) admission: AuthorityAdmission,
    /// Immutable origin proposed for the governed write. Missing origin fails closed.
    #[serde(default)]
    pub(crate) origin_authority: Option<crate::OriginAuthorityLabelV1>,
}

/// Admission basis carried by a governed authority permit.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuthorityAdmission {
    Unspecified,
    Evidence { evidence_refs: Vec<String> },
    OperatorSystem,
}

/// Trusted in-process issuer. It has no public constructor, so ordinary callers cannot mint
/// capability-bearing permits or supply caller identities as request data.
///
/// The operator-token constructor (`from_operator_token`) is the production path:
/// it requires an explicit secret provided by the operator at process startup.
/// Without that token, no issuer exists and governed mutations fail closed.
pub struct AuthorityIssuer {
    _private: (),
}

impl Clone for AuthorityIssuer {
    fn clone(&self) -> Self {
        Self { _private: () }
    }
}

impl AuthorityIssuer {
    #[cfg(feature = "testing")]
    pub(crate) fn trusted() -> Self {
        Self { _private: () }
    }

    /// Construct an issuer from an operator-provided token.
    ///
    /// The token is validated (non-empty, no internal whitespace) but not
    /// stored — the issuer is a zero-sized capability that exists only in
    /// the process that was started with the correct token. The token itself
    /// is consumed and not retained, so it cannot leak through the issuer.
    ///
    /// Returns `None` if the token is empty or invalid, preserving fail-closed
    /// semantics for misconfigured deployments.
    pub fn from_operator_token(token: &str) -> Option<Self> {
        let token = token.trim();
        if token.is_empty() || token.chars().any(char::is_whitespace) {
            return None;
        }
        Some(Self { _private: () })
    }

    pub fn mint_operator_system(
        &self,
        principal: impl Into<String>,
        caller_id: impl Into<String>,
        capability: impl Into<String>,
    ) -> AuthorityPermit {
        let principal = principal.into();
        let caller_id = caller_id.into();
        AuthorityPermit {
            origin_authority: Some(crate::OriginAuthorityLabelV1::operator_system(
                &principal, &caller_id,
            )),
            principal,
            caller_id,
            capability: capability.into(),
            admission: AuthorityAdmission::OperatorSystem,
        }
    }

    pub fn mint_with_resolved_evidence(
        &self,
        principal: impl Into<String>,
        caller_id: impl Into<String>,
        capability: impl Into<String>,
        evidence: Vec<ResolvedEvidenceDigest>,
        origin_authority: crate::OriginAuthorityLabelV1,
    ) -> AuthorityPermit {
        AuthorityPermit {
            principal: principal.into(),
            caller_id: caller_id.into(),
            capability: capability.into(),
            admission: AuthorityAdmission::Evidence {
                evidence_refs: evidence.into_iter().map(|digest| digest.0).collect(),
            },
            origin_authority: Some(origin_authority),
        }
    }
}

/// Resolver-produced immutable evidence identity.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedEvidenceDigest(String);

impl ResolvedEvidenceDigest {
    pub fn from_resolver(digest: String) -> Option<Self> {
        let hex = digest.strip_prefix("blake3:")?;
        (hex.len() == 64 && hex.bytes().all(|byte| byte.is_ascii_hexdigit()))
            .then_some(Self(digest))
    }
}

impl AuthorityPermit {
    pub const APPEND_CAPABILITY: &'static str = "memory.authority.append";
    pub const SUPERSEDE_CAPABILITY: &'static str = "memory.authority.supersede";
    pub const REDACT_CAPABILITY: &'static str = "memory.authority.redact";
    pub const REVOKE_ORIGIN_CAPABILITY: &'static str = "memory.authority.revoke_origin";
    pub const FORGET_CAPABILITY: &'static str = "memory.authority.forget";

    #[cfg(feature = "testing")]
    pub fn new(
        principal: impl Into<String>,
        caller_id: impl Into<String>,
        capability: impl Into<String>,
    ) -> Self {
        Self {
            principal: principal.into(),
            caller_id: caller_id.into(),
            capability: capability.into(),
            admission: AuthorityAdmission::Unspecified,
            origin_authority: None,
        }
    }

    /// Construct a permit for a fact proposal supported by explicit evidence.
    #[cfg(feature = "testing")]
    pub fn with_evidence(
        principal: impl Into<String>,
        caller_id: impl Into<String>,
        capability: impl Into<String>,
        evidence_refs: Vec<String>,
    ) -> Self {
        Self {
            principal: principal.into(),
            caller_id: caller_id.into(),
            capability: capability.into(),
            admission: AuthorityAdmission::Evidence { evidence_refs },
            origin_authority: None,
        }
    }

    /// Construct the explicit operator/system bypass used for trusted inserts.
    #[cfg(feature = "testing")]
    pub fn operator_system(
        principal: impl Into<String>,
        caller_id: impl Into<String>,
        capability: impl Into<String>,
    ) -> Self {
        AuthorityIssuer::trusted().mint_operator_system(principal, caller_id, capability)
    }

    /// Bind an immutable origin label to this governed write permit.
    #[cfg(feature = "testing")]
    pub fn with_origin(mut self, origin: crate::OriginAuthorityLabelV1) -> Self {
        self.origin_authority = Some(origin);
        self
    }
}

/// Authority mutation kind recorded in the operation journal and receipt.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuthorityOperationKind {
    Append,
    Supersede,
    Redact,
}

/// Typed fault-injection points for atomic authority tests.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuthorityFaultStage {
    BeforeAppend,
    AfterAppend,
    BeforeLineage,
    AfterLineage,
    BeforeJournal,
    AfterJournal,
    BeforeEpoch,
    AfterEpoch,
    BeforeReceipt,
    AfterReceipt,
    BeforeForgettingMutation,
    AfterForgettingMutation,
    BeforeForgettingReceipt,
    AfterForgettingReceipt,
    BeforeShadowPromotion,
    AfterShadowPromotion,
}

/// Durable receipt for one governed authority mutation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AuthorityReceiptV1 {
    pub schema_version: String,
    pub receipt_id: String,
    pub operation_id: String,
    pub caller_idempotency_key: String,
    pub principal: String,
    pub caller_id: String,
    pub operation_kind: AuthorityOperationKind,
    pub before_snapshot_id: AuthoritySnapshotId,
    pub after_snapshot_id: AuthoritySnapshotId,
    pub before_epoch: RetrievalEpoch,
    pub after_epoch: RetrievalEpoch,
    pub affected_ids: Vec<String>,
    pub content_digest: String,
    /// Digest of the immutable origin label persisted for the written fact.
    #[serde(default)]
    pub origin_label_digest: Option<String>,
    pub receipt_digest: String,
    pub committed_at: String,
}

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

    #[test]
    fn bounded_numbers_reject_non_finite_and_out_of_range() {
        for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -0.1, 1.1] {
            assert!(Probability::new(value).is_err());
            assert!(serde_json::from_str::<Probability>(&value.to_string()).is_err());
        }
        assert!(CosineSimilarity::new(-1.0).is_ok());
        assert!(CosineSimilarity::new(1.0).is_ok());
        assert!(NonNegativeWeight::new(-f64::EPSILON).is_err());
    }

    #[test]
    fn bounded_number_serde_round_trips_boundaries() {
        for value in [0.0, 0.5, 1.0] {
            let bounded = Probability::new(value).unwrap();
            let json = serde_json::to_string(&bounded).unwrap();
            assert_eq!(serde_json::from_str::<Probability>(&json).unwrap(), bounded);
        }
    }
}