areev 0.2.0

Rust SDK for the Areev knowledge database — gRPC and HTTP transports
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
//! `Grains` resource — grain CRUD on the configured memory.
//!
//! Mirrors the Python SDK's `client.grains.*` surface: `add`,
//! `batch_add`, `recall`, `recall_chain`, `get`, `get_raw`, `list`,
//! `forget`, `forget_many`, `forget_user`, `supersede`, `accumulate`,
//! `detect_pii`, `cal`, `predicate_registry`, `predicate_hint`.
//!
//! All methods are loosely typed (`serde_json::Value`) — the goal is
//! parity with Python rather than a strongly typed surface, which is
//! deferred to a future generated layer. Builders are provided for the
//! verbs with many optional parameters (`recall`, `accumulate`).

use serde_json::{json, Map, Value};

use crate::error::{AreevError, Result};
use crate::http::HttpClient;

/// Grain CRUD on the client's configured memory.
///
/// Access via [`crate::Areev::grains`].
pub struct Grains<'a> {
    http: &'a HttpClient,
    memory_id: String,
}

impl<'a> Grains<'a> {
    /// Internal constructor — use [`crate::Areev::grains`].
    pub(crate) fn new(http: &'a HttpClient, memory_id: String) -> Self {
        Self { http, memory_id }
    }

    /// Add a grain of any of the 10 OMS types. Returns the
    /// content-address hash (`blob_hash`) of the new grain.
    ///
    /// `fields` is the typed payload for the grain — see
    /// `docs/facts/areev-overview.md` for the per-grain shape. The
    /// optional `namespace` is added as a top-level body field.
    ///
    /// # Errors
    ///
    /// Returns [`AreevError::Server`] (502, `SDK-E012`) when the server
    /// response carries no grain hash — the store did not happen.
    pub async fn add(
        &self,
        grain_type: &str,
        fields: Value,
        namespace: Option<&str>,
    ) -> Result<String> {
        let mut body = json!({ "grain_type": grain_type, "fields": fields });
        if let Some(ns) = namespace {
            body.as_object_mut()
                .unwrap()
                .insert("namespace".to_string(), Value::String(ns.to_string()));
        }
        let path = format!("/memories/{}/add", self.memory_id);
        let resp = self.http._post(&path, Some(&body)).await?;
        extract_string(&resp, &["blob_hash", "hash"]).ok_or_else(missing_hash_error)
    }

    /// Add multiple grains in one request. Returns the raw server
    /// response (`{"succeeded": [...], "failed": [...]}`).
    pub async fn batch_add(&self, grains: Vec<Value>) -> Result<Value> {
        let body = json!({ "grains": grains });
        let path = format!("/memories/{}/batch-add", self.memory_id);
        self.http._post(&path, Some(&body)).await
    }

    /// Start a [`RecallBuilder`] for the given query — chain
    /// `limit()`, `namespace()`, `tags()`, etc. and call `send()`.
    pub fn recall(&self, query: &str) -> RecallBuilder<'_, 'a> {
        RecallBuilder::new(self, query)
    }

    /// Multi-hop recall — decomposes `question` into sub-queries and
    /// merges results. Returns the raw server response.
    pub async fn recall_chain(&self, question: &str, limit: u32) -> Result<Value> {
        let body = json!({ "query": question, "limit": limit });
        let path = format!("/memories/{}/recall-chain", self.memory_id);
        self.http._post(&path, Some(&body)).await
    }

    /// Fetch a grain by its SHA-256 content-address hash.
    pub async fn get(&self, hash: &str) -> Result<Value> {
        let path = format!("/memories/{}/grains/{}", self.memory_id, hash);
        self.http._get(&path, None).await
    }

    /// Forget a single grain by hash.
    pub async fn forget(&self, hash: &str) -> Result<()> {
        let body = json!({ "blob_hash": hash });
        let path = format!("/memories/{}/forget", self.memory_id);
        self.http._post(&path, Some(&body)).await.map(|_| ())
    }

    /// Forget multiple grains in one request.
    pub async fn forget_many(&self, hashes: &[&str]) -> Result<()> {
        let body = json!({ "hashes": hashes });
        let path = format!("/memories/{}/forget", self.memory_id);
        self.http._post(&path, Some(&body)).await.map(|_| ())
    }

    /// GDPR Art. 17 forget-by-user — crypto-erases every grain attributed
    /// to `user_id`.
    ///
    /// **IRREVERSIBLE.** Destroys the user's grains and their key
    /// material; there is no undo. Emits an audit event.
    /// Requires: admin scope.
    ///
    /// This is a data-subject-rights operation — always issued, never
    /// blocked by tier or credit gates. The response body is excluded
    /// from SDK request logging and the call is **not** auto-retried.
    ///
    /// # Errors
    ///
    /// Returns [`AreevError::Validation`] (`SDK-E002`) when `confirm`
    /// is not `true`.
    pub async fn forget_user(&self, user_id: &str, confirm: bool) -> Result<Value> {
        if !confirm {
            return Err(confirm_error("grains.forget_user"));
        }
        let body = json!({ "user_id": user_id });
        let path = format!("/memories/{}/forget", self.memory_id);
        self.http._post_sensitive(&path, Some(&body), false).await
    }

    /// Fetch a grain's raw `.mg` blob (9-byte header + canonical
    /// MessagePack) by content-address hash.
    ///
    /// The endpoint responds with `application/octet-stream` — raw bytes,
    /// not JSON — so this returns the bytes verbatim. Parse them with an
    /// `.mg` reader; do **not** assume UTF-8 / JSON.
    pub async fn get_raw(&self, hash: &str) -> Result<Vec<u8>> {
        let path = format!("/memories/{}/grains/{}/raw", self.memory_id, hash);
        self.http._get_bytes(&path, None).await
    }

    /// List grains in the memory, optionally filtered. `filters` is added
    /// as query parameters (e.g. `namespace`, `grain_type`, `limit`).
    pub async fn list(&self, filters: Option<&Value>) -> Result<Value> {
        let path = format!("/memories/{}/grains", self.memory_id);
        self.http._get(&path, filters).await
    }

    /// Run a CAL (Contextual Access Language) query. `query` is the raw
    /// CAL text (e.g. `RECALL facts WHERE subject = "john"`).
    ///
    /// The query is sent as the raw request body with Content-Type
    /// `text/cal`; the server parses the text into a `CalQuery` AST. Do
    /// **not** wrap it in `{"query": ...}` — the JSON path
    /// (`application/json+cal`) expects a pre-parsed AST and rejects a
    /// bare string with `CAL-E120`. For callers that already hold a
    /// JSON-CAL AST, use [`Grains::cal_ast`].
    pub async fn cal(&self, query: &str) -> Result<Value> {
        let path = format!("/memories/{}/cal", self.memory_id);
        self.http
            ._post_raw(&path, query.to_string(), "text/cal")
            .await
    }

    /// Run a CAL query from a pre-parsed JSON-CAL AST (`CalQuery` shape —
    /// `{"statement": {"kind": "recall", ...}, ...}`).
    ///
    /// Sends `ast` as the request body with Content-Type
    /// `application/json+cal`. Most callers want [`Grains::cal`] (raw
    /// text); reach for this only when you build the AST yourself (e.g. a
    /// query builder) and want to skip the server-side text parse.
    pub async fn cal_ast(&self, ast: &Value) -> Result<Value> {
        let path = format!("/memories/{}/cal", self.memory_id);
        let body = serde_json::to_string(ast).map_err(AreevError::from)?;
        self.http
            ._post_raw(&path, body, "application/json+cal")
            .await
    }

    /// List the memory's registered predicates (relations) and metadata.
    pub async fn predicate_registry(&self) -> Result<Value> {
        let path = format!("/memories/{}/predicate-registry", self.memory_id);
        self.http._get(&path, None).await
    }

    /// Register a normalization hint for a relation predicate.
    ///
    /// Requires: Scale or Custom plan. Emits an audit event.
    pub async fn predicate_hint(
        &self,
        relation: &str,
        hint: &str,
        confidence: f64,
        user_id: &str,
    ) -> Result<Value> {
        let body = json!({
            "relation": relation,
            "hint": hint,
            "confidence": confidence,
            "user_id": user_id,
        });
        let path = format!("/memories/{}/predicate-hint", self.memory_id);
        self.http._post(&path, Some(&body)).await
    }

    /// Replace `old_hash` with a new grain (versioned, audit-trailed).
    /// Returns the new content-address hash.
    ///
    /// `old_hash` is sent as `blob_hash` and the field overrides under
    /// `fields`.
    pub async fn supersede(&self, old_hash: &str, fields: Value) -> Result<String> {
        let body = json!({
            "blob_hash": old_hash,
            "fields": fields,
        });
        let path = format!("/memories/{}/supersede", self.memory_id);
        let resp = self.http._post(&path, Some(&body)).await?;
        extract_string(&resp, &["new_hash", "blob_hash", "hash"]).ok_or_else(missing_hash_error)
    }

    /// Start an [`AccumulateBuilder`] for the given grain — chain
    /// `deltas()`, `reason()` and call `send()`.
    pub fn accumulate<'b>(
        &'b self,
        grain_type: &str,
        subject: &str,
        relation: &str,
    ) -> AccumulateBuilder<'b, 'a> {
        AccumulateBuilder::new(self, grain_type, subject, relation)
    }

    /// Scan text for PII categories without storing anything.
    ///
    /// The scanned text + detected spans are excluded from the SDK's
    /// request logging.
    pub async fn detect_pii(&self, text: &str) -> Result<Value> {
        let body = json!({ "text": text });
        let path = format!("/memories/{}/detect-pii", self.memory_id);
        self.http._post_sensitive(&path, Some(&body), true).await
    }
}

/// Builder for [`Grains::recall`]. Chain optional knobs and call
/// `send()` to issue the request.
pub struct RecallBuilder<'b, 'a> {
    grains: &'b Grains<'a>,
    body: Map<String, Value>,
}

impl<'b, 'a> RecallBuilder<'b, 'a> {
    fn new(grains: &'b Grains<'a>, query: &str) -> Self {
        let mut body = Map::new();
        body.insert("query".to_string(), Value::String(query.to_string()));
        body.insert("limit".to_string(), Value::from(10u32));
        Self { grains, body }
    }

    /// Maximum number of hits to return (default 10).
    pub fn limit(mut self, limit: u32) -> Self {
        self.body.insert("limit".to_string(), Value::from(limit));
        self
    }

    /// Restrict recall to a specific namespace.
    pub fn namespace(mut self, namespace: &str) -> Self {
        self.body.insert(
            "namespace".to_string(),
            Value::String(namespace.to_string()),
        );
        self
    }

    /// Restrict recall to grains tagged with all of `tags`.
    pub fn tags(mut self, tags: &[&str]) -> Self {
        let arr: Vec<Value> = tags.iter().map(|t| Value::String(t.to_string())).collect();
        self.body.insert("tags".to_string(), Value::Array(arr));
        self
    }

    /// Restrict recall to a grain type.
    pub fn grain_type(mut self, grain_type: &str) -> Self {
        self.body.insert(
            "grain_type".to_string(),
            Value::String(grain_type.to_string()),
        );
        self
    }

    /// Set the user attribution filter.
    pub fn user_id(mut self, user_id: &str) -> Self {
        self.body
            .insert("user_id".to_string(), Value::String(user_id.to_string()));
        self
    }

    /// Set an arbitrary additional field on the request body — escape
    /// hatch for server flags the typed builder doesn't expose yet.
    pub fn extra(mut self, key: &str, value: Value) -> Self {
        self.body.insert(key.to_string(), value);
        self
    }

    /// Issue the request.
    pub async fn send(self) -> Result<Value> {
        let path = format!("/memories/{}/recall", self.grains.memory_id);
        self.grains
            .http
            ._post(&path, Some(&Value::Object(self.body)))
            .await
    }
}

/// Builder for [`Grains::accumulate`].
pub struct AccumulateBuilder<'b, 'a> {
    grains: &'b Grains<'a>,
    body: Map<String, Value>,
}

impl<'b, 'a> AccumulateBuilder<'b, 'a> {
    fn new(grains: &'b Grains<'a>, grain_type: &str, subject: &str, relation: &str) -> Self {
        let mut body = Map::new();
        body.insert(
            "grain_type".to_string(),
            Value::String(grain_type.to_string()),
        );
        // The target grain is resolved by subject + relation (tip-resolved).
        body.insert(
            "target".to_string(),
            json!({
                "kind": "tip_resolved",
                "subject": subject,
                "relation": relation,
            }),
        );
        body.insert("add".to_string(), Value::Object(Map::new()));
        // `reason` is required by the server — default to empty until set.
        body.insert("reason".to_string(), Value::String(String::new()));
        Self { grains, body }
    }

    /// Numeric deltas to apply (field name → delta).
    pub fn deltas(mut self, deltas: &[(&str, f64)]) -> Self {
        let mut map = Map::new();
        for (k, v) in deltas {
            map.insert((*k).to_string(), Value::from(*v));
        }
        self.body.insert("add".to_string(), Value::Object(map));
        self
    }

    /// Reason for the accumulation — surfaced in the audit log.
    pub fn reason(mut self, reason: &str) -> Self {
        self.body
            .insert("reason".to_string(), Value::String(reason.to_string()));
        self
    }

    /// Issue the request.
    pub async fn send(self) -> Result<Value> {
        let path = format!("/memories/{}/accumulate", self.grains.memory_id);
        self.grains
            .http
            ._post(&path, Some(&Value::Object(self.body)))
            .await
    }
}

/// Pull the first non-empty string field from `keys` out of `v`.
fn extract_string(v: &Value, keys: &[&str]) -> Option<String> {
    let map = v.as_object()?;
    for k in keys {
        if let Some(s) = map.get(*k).and_then(|x| x.as_str()) {
            if !s.is_empty() {
                return Some(s.to_string());
            }
        }
    }
    None
}

/// Error for a successful store whose response carries no grain hash —
/// the store did not happen, and a silent empty string would mask it.
/// Shared by `grains.add` and `grains.supersede`.
///
/// Reported as a **server** error (`AreevError::Server`, HTTP 502) — the
/// fault is the server's malformed response, not the caller's request. All
/// three SDKs surface this identically (server-error variant, 502,
/// `SDK-E012`).
fn missing_hash_error() -> AreevError {
    AreevError::Server {
        code: Some("SDK-E012".to_string()),
        http_status: 502,
        message: "unexpected server response: no grain hash".to_string(),
        body: Value::Null,
        request_id: None,
    }
}

/// Build the `confirm=false` guard error shared by destructive ops
/// (`grains.forget_user`, `scope.erase`, `namespaces.purge`).
pub(crate) fn confirm_error(op: &str) -> AreevError {
    AreevError::Validation {
        code: Some("SDK-E002".to_string()),
        http_status: 0,
        message: format!(
            "{op} requires confirm=true — this is irreversible (crypto-erasure / drops grains)"
        ),
        body: serde_json::Value::Null,
        request_id: None,
    }
}