erebyx-sdk 0.1.1

Rust SDK for EREBYX — persistent AI memory across every AI you use. Encrypted in transit (TLS 1.3) and at rest with envelope encryption (server-held master KEK at v0.1.1); per-user zero-knowledge encryption in v0.2.
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Core EREBYX memory client.
//!
//! Provides the `Memory` struct with builder-pattern API for all memory operations.
//! Includes circuit breaker for graceful degradation — memory failure never crashes.

use std::sync::atomic::{AtomicU64, AtomicU8, Ordering};
use std::sync::Arc;
use std::time::Duration;

use reqwest::Client;
use serde_json::json;
use tokio::time::Instant;
use tracing::{debug, warn};

use crate::error::Error;
use crate::types::*;

/// Header name carrying substrate lifecycle hints (comma-separated).
/// See `core/api/middleware/erebyx_hints.py` for the canonical emission
/// rules and `Hooks Architecture v0.1.2 §3.1` for the contract.
const HINT_HEADER: &str = "X-Erebyx-Hint";

/// Header name carrying tools the substrate auto-fired on this call.
/// Typically `restore_identity,load_context` on the first call against a
/// fresh `(instance_id, session_id)` tuple. Empty thereafter.
const AUTO_FIRED_HEADER: &str = "X-Erebyx-Auto-Fired";

/// Header name the SDK uses to attribute every request to a stable
/// session. Required for the substrate's hint engine + auto-fire engine
/// to track per-session state.
const SESSION_ID_HEADER: &str = "X-Erebyx-Session-Id";

/// Parse a comma-separated header into a clean `Vec<String>`. Empty /
/// missing → empty vec. Whitespace stripped per element.
fn parse_csv_header(value: Option<&reqwest::header::HeaderValue>) -> Vec<String> {
    match value.and_then(|v| v.to_str().ok()) {
        Some(raw) if !raw.is_empty() => raw
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect(),
        _ => Vec::new(),
    }
}

/// Default API base URL.
const DEFAULT_API_URL: &str = "https://core.erebyx.com";

/// Maximum response body size we will buffer (10 MiB).
const MAX_RESPONSE_BYTES: u64 = 10 * 1024 * 1024;

/// Return true if URL is HTTPS, or HTTP pointed at localhost (dev affordance).
fn is_safe_url(url: &str) -> bool {
    if url.starts_with("https://") {
        return true;
    }
    if let Some(rest) = url.strip_prefix("http://") {
        let host_part = rest.split('/').next().unwrap_or("");
        let host = host_part.split(':').next().unwrap_or("");
        return matches!(host, "localhost" | "127.0.0.1" | "::1");
    }
    false
}

/// Circuit breaker: trips after this many consecutive failures.
const CIRCUIT_BREAK_THRESHOLD: u64 = 3;

// Tri-state circuit breaker (P0-3 fix, 2026-05-27).
// Prior implementation used AtomicBool which fully closed the circuit on
// cooldown elapse — every concurrent caller stampeded the substrate at
// second 30, defeating the entire purpose of the breaker. Tri-state
// machine: Closed (happy path) → Open (cooldown timer running) →
// HalfOpen (exactly one probe call permitted) → back to Closed on
// success or Open on failure.
const CIRCUIT_STATE_CLOSED: u8 = 0;
const CIRCUIT_STATE_OPEN: u8 = 1;
const CIRCUIT_STATE_HALF_OPEN: u8 = 2;

/// Circuit breaker: cooldown before retrying after trip.
const CIRCUIT_COOLDOWN: Duration = Duration::from_secs(30);

/// Default request timeout (10s to accommodate embedding generation on save).
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);

/// The core EREBYX memory client.
///
/// Thread-safe (uses Arc internally). Clone is cheap.
#[derive(Clone)]
pub struct Memory {
    inner: Arc<MemoryInner>,
}

struct MemoryInner {
    client: Client,
    api_url: String,
    api_key: String,
    instance_id: String,
    /// Stable per-process session identifier. Used to populate the
    /// `X-Erebyx-Session-Id` request header so the substrate's hint
    /// engine + auto-fire engine can track per-session state.
    /// Defaults to a fresh UUID v4 created at builder time; can be
    /// overridden via `MemoryBuilder::session_id` for callers that
    /// want to bind the SDK lifetime to an external session id (e.g.
    /// the harness conversation id).
    session_id: String,
    /// Per-tenant passphrase for `argon2_passphrase` mode (default at
    /// v0.1.1+). When set, sent as the `X-Passphrase` header on every
    /// authenticated request. Resolved from `EREBYX_PASSPHRASE` env var
    /// in `from_env()` or passed explicitly via `MemoryBuilder::passphrase`.
    /// Empty values normalize to `None` so legacy `hkdf_api_key` tenants
    /// never transmit an empty header.
    passphrase: Option<String>,
    // Circuit breaker state
    consecutive_failures: AtomicU64,
    /// Tri-state breaker (Closed/Open/HalfOpen). See CIRCUIT_STATE_*
    /// constants above for semantics.
    circuit_state: AtomicU8,
    circuit_opened_at: std::sync::Mutex<Option<Instant>>,
    /// Cooldown duration before a HalfOpen probe is permitted. Defaults
    /// to `CIRCUIT_COOLDOWN` (30s) for prod; tests override to a small
    /// value so the breaker can be exercised against real HTTP in
    /// real time. Prod operators can tune via `MemoryBuilder::circuit_cooldown`
    /// when self-hosting a substrate with different recovery characteristics.
    circuit_cooldown: Duration,
}

impl Memory {
    /// Create a new Memory client with an API key.
    pub fn new(api_key: &str) -> Result<Self, Error> {
        Self::builder(api_key).build()
    }

    /// Create from environment variables.
    ///
    /// Reads `EREBYX_API_KEY`, `EREBYX_API_URL`, `EREBYX_INSTANCE_ID`,
    /// and `EREBYX_PASSPHRASE` (required for Argon2id-default-on tenants
    /// registered at v0.1.1+; empty values normalize to None for legacy
    /// `hkdf_api_key` tenants).
    pub fn from_env() -> Result<Self, Error> {
        let api_key = std::env::var("EREBYX_API_KEY")
            .map_err(|_| Error::Config("EREBYX_API_KEY not set".into()))?;
        let api_url = std::env::var("EREBYX_API_URL").unwrap_or_else(|_| DEFAULT_API_URL.into());
        let instance_id = std::env::var("EREBYX_INSTANCE_ID").unwrap_or_else(|_| "default".into());

        // Argon2id-default-on. Empty strings normalize to None so legacy
        // `hkdf_api_key` tenants never accidentally transmit an empty
        // `X-Passphrase` header — the server side distinguishes "header
        // absent" from "header empty".
        let passphrase = std::env::var("EREBYX_PASSPHRASE")
            .ok()
            .filter(|s| !s.trim().is_empty());

        let mut builder = Self::builder(&api_key)
            .api_url(&api_url)
            .instance_id(&instance_id);
        if let Some(p) = passphrase {
            builder = builder.passphrase(&p);
        }
        builder.build()
    }

    /// Create a builder for custom configuration.
    pub fn builder(api_key: &str) -> MemoryBuilder {
        MemoryBuilder {
            api_key: api_key.to_string(),
            api_url: DEFAULT_API_URL.to_string(),
            instance_id: "default".to_string(),
            // A fresh per-process UUID v4. Callers can override via
            // `MemoryBuilder::session_id` to bind the SDK lifetime to an
            // external session id (harness conversation id, etc.). The
            // substrate's hint engine + auto-fire engine key on this.
            session_id: uuid::Uuid::new_v4().to_string(),
            // None means hkdf_api_key tenant; Some(p) means
            // argon2_passphrase tenant. Set via `passphrase()`.
            passphrase: None,
            timeout: DEFAULT_TIMEOUT,
            circuit_cooldown: CIRCUIT_COOLDOWN,
        }
    }

    // =========================================================================
    // Public API — v0.1.1 launch surface (5 cognitive verbs)
    // =========================================================================

    /// Save a memory. Returns a builder for optional fields.
    pub fn save<'a>(&'a self, content: &str, category: &str) -> SaveBuilder<'a> {
        SaveBuilder {
            client: self,
            content: content.to_string(),
            category: category.to_string(),
            title: None,
            anchors: None,
            importance: None,
            memory_type: None,
        }
    }

    /// Search memories. Returns a builder for optional filters.
    pub fn search<'a>(&'a self, query: &str) -> SearchBuilder<'a> {
        SearchBuilder {
            client: self,
            query: query.to_string(),
            limit: None,
            hint_anchors: None,
            time_range: None,
            types: None,
        }
    }

    /// Create a session handoff. Returns a builder.
    pub fn wrap_up<'a>(&'a self, what_we_built: &str, whats_next: &str) -> WrapUpBuilder<'a> {
        WrapUpBuilder {
            client: self,
            what_we_built: what_we_built.to_string(),
            whats_next: whats_next.to_string(),
            diary: None,
            anchors: None,
            energy: None,
            memories: None,
        }
    }

    /// Load identity at session start. Returns a builder.
    pub fn restore_identity<'a>(&'a self) -> RestoreIdentityBuilder<'a> {
        RestoreIdentityBuilder {
            client: self,
            detail_level: None,
            include_guide: None,
            limit: None,
        }
    }

    /// Load work context (call after restore_identity). Returns a builder.
    pub fn load_context<'a>(&'a self) -> LoadContextBuilder<'a> {
        LoadContextBuilder {
            client: self,
            anchors: None,
            mode: None,
            specialization_name: None,
            detail_level: None,
            load_priority: None,
        }
    }

    // =========================================================================
    // Internal execution methods (called by builders)
    // =========================================================================

    pub(crate) async fn execute_save(&self, builder: SaveBuilder<'_>) -> Result<SaveResult, Error> {
        self.check_circuit()?;

        let mut body = json!({
            "content": builder.content,
            "category": builder.category,
        });

        if let Some(title) = &builder.title {
            body["title"] = json!(title);
        }
        if let Some(anchors) = &builder.anchors {
            body["anchors"] = json!(anchors);
        }
        if let Some(importance) = builder.importance {
            body["importance"] = json!(importance);
        }
        if let Some(memory_type) = &builder.memory_type {
            body["type"] = json!(memory_type);
        }

        let (response, hints, auto_fired) = self.post("/v0/memory/store", &body).await?;
        self.record_success();

        let mut result: SaveResult = serde_json::from_value(response)?;
        // Headers are the canonical source of truth for hints / auto-fired —
        // overwrite anything the body happened to ship so callers always
        // read the substrate's authoritative signal.
        result.hints = hints;
        result.auto_fired = auto_fired;
        Ok(result)
    }

    pub(crate) async fn execute_search(
        &self,
        builder: SearchBuilder<'_>,
    ) -> Result<SearchResult, Error> {
        self.check_circuit()?;

        let mut body = json!({
            "query": builder.query,
        });

        if let Some(limit) = builder.limit {
            body["limit"] = json!(limit);
        }
        if let Some(anchors) = &builder.hint_anchors {
            body["hint_anchors"] = json!(anchors);
        }
        if let Some(range) = &builder.time_range {
            body["time_range"] = json!(range);
        }
        if let Some(types) = &builder.types {
            body["types"] = json!(types);
        }

        let (response, hints, auto_fired) = self.post("/v0/memory/remember", &body).await?;
        self.record_success();

        let mut result: SearchResult = serde_json::from_value(response)?;
        result.hints = hints;
        result.auto_fired = auto_fired;
        Ok(result)
    }

    pub(crate) async fn execute_wrap_up(
        &self,
        builder: WrapUpBuilder<'_>,
    ) -> Result<WrapUpResult, Error> {
        self.check_circuit()?;

        // Bucket B (2026-05-27): include session_id so the substrate
        // can deduplicate retries against the same logical session.
        // Without this the substrate generates a fresh session_id on
        // every call → duplicate handoffs every time a caller retries
        // (network blip, transient 5xx, builder.send().await chained
        // through a retry middleware). The substrate's WrapUpRequest
        // accepts session_id as optional + auto-generates when None,
        // so older SDK versions still work; explicitly passing it is
        // the idempotency contract.
        let mut body = json!({
            "session_id": &self.inner.session_id,
            "what_we_built": builder.what_we_built,
            "whats_next": builder.whats_next,
        });

        if let Some(diary) = &builder.diary {
            body["diary"] = json!(diary);
        }
        if let Some(anchors) = &builder.anchors {
            body["anchors"] = json!(anchors);
        }
        if let Some(energy) = &builder.energy {
            body["energy"] = json!(energy);
        }
        if let Some(memories) = &builder.memories {
            body["memories"] = json!(memories);
        }

        let (response, hints, auto_fired) = self.post("/v0/session/wrap-up", &body).await?;
        self.record_success();

        let mut result: WrapUpResult = serde_json::from_value(response)?;
        result.hints = hints;
        result.auto_fired = auto_fired;
        Ok(result)
    }

    pub(crate) async fn execute_restore_identity(
        &self,
        builder: RestoreIdentityBuilder<'_>,
    ) -> Result<RestoreIdentityResult, Error> {
        self.check_circuit()?;

        // Bucket B (2026-05-27): switch from GET /v0/identity (which
        // accepts ZERO query params — the legacy minimal-shape route)
        // to POST /v0/identity/restore (the api-first canonical surface
        // declared in mcp_substrate.py:225). The POST route accepts
        // {limit, include_guide, detail_level} in the body and returns
        // the full RestoreIdentityResponse — ethos, foundation_memories,
        // topology, continuity, needs_onboarding, narrative,
        // suggested_next_call, meta. The old SDK silently dropped 6
        // fields on every restore call.
        let mut body = serde_json::Map::new();
        if let Some(limit) = builder.limit {
            body.insert("limit".into(), json!(limit));
        }
        if let Some(include) = builder.include_guide {
            body.insert("include_guide".into(), json!(include));
        }
        if let Some(level) = &builder.detail_level {
            body.insert("detail_level".into(), json!(level));
        }
        let body_value = serde_json::Value::Object(body);

        let (response, hints, auto_fired) = self.post("/v0/identity/restore", &body_value).await?;
        self.record_success();

        let mut result: RestoreIdentityResult = serde_json::from_value(response)?;
        result.hints = hints;
        result.auto_fired = auto_fired;
        Ok(result)
    }

    pub(crate) async fn execute_load_context(
        &self,
        builder: LoadContextBuilder<'_>,
    ) -> Result<LoadContextResult, Error> {
        self.check_circuit()?;

        // Bucket B (2026-05-27): switch from GET /v0/handoff/context
        // (legacy minimal-shape route — accepts only ?anchors=) to
        // POST /v0/session/load (api-first canonical surface declared
        // in mcp_substrate.py:250). The POST route accepts the full
        // {anchors, mode, specialization_name, detail_level,
        // load_priority} body and returns the full LoadContextResponse
        // — handoff, related_memories, skills, topology, narrative,
        // suggested_next_call, meta. The old SDK silently dropped 7
        // fields on every load_context call.
        let mut body = serde_json::Map::new();
        if let Some(anchors) = &builder.anchors {
            body.insert("anchors".into(), json!(anchors));
        } else {
            // Substrate's LoadContextRequest defaults anchors to []
            // (load most-recent absolute). Send the explicit empty
            // list so the wire format is unambiguous.
            body.insert("anchors".into(), json!(Vec::<String>::new()));
        }
        if let Some(mode) = &builder.mode {
            body.insert("mode".into(), json!(mode));
        }
        if let Some(spec) = &builder.specialization_name {
            body.insert("specialization_name".into(), json!(spec));
        }
        if let Some(level) = &builder.detail_level {
            body.insert("detail_level".into(), json!(level));
        }
        if let Some(priority) = &builder.load_priority {
            body.insert("load_priority".into(), json!(priority));
        }
        let body_value = serde_json::Value::Object(body);

        let (response, hints, auto_fired) = self.post("/v0/session/load", &body_value).await?;
        self.record_success();

        let mut result: LoadContextResult = serde_json::from_value(response)?;
        result.hints = hints;
        result.auto_fired = auto_fired;
        Ok(result)
    }

    // =========================================================================
    // HTTP layer
    // =========================================================================

    /// POST helper. Same contract as `get` — returns body + hints +
    /// auto_fired so callers can fold the substrate's lifecycle headers
    /// onto the typed result struct.
    async fn post(
        &self,
        path: &str,
        body: &serde_json::Value,
    ) -> Result<(serde_json::Value, Vec<String>, Vec<String>), Error> {
        let url = format!("{}{}", self.inner.api_url.trim_end_matches('/'), path);

        debug!(url = %url, "erebyx-sdk POST");

        let mut rb = self
            .inner
            .client
            .post(&url)
            .header("Content-Type", "application/json")
            .bearer_auth(&self.inner.api_key)
            .header("X-Instance-ID", &self.inner.instance_id)
            .header(SESSION_ID_HEADER, &self.inner.session_id);
        // Argon2id-default-on. Header absent for legacy `hkdf_api_key`
        // tenants — never emit an empty value.
        if let Some(ref p) = self.inner.passphrase {
            rb = rb.header("X-Passphrase", p);
        }
        let response = rb.json(body).send().await.map_err(|e| {
            self.record_failure();
            Error::Network(e)
        })?;

        let status = response.status().as_u16();

        if status == 401 || status == 403 {
            return Err(Error::AuthenticationFailed(format!("HTTP {status}")));
        }
        if status == 429 {
            let retry_after = response
                .headers()
                .get("retry-after")
                .and_then(|v| v.to_str().ok())
                .and_then(|v| v.parse().ok())
                .unwrap_or(10);
            return Err(Error::RateLimit {
                retry_after_secs: retry_after,
            });
        }
        if status == 404 {
            return Err(Error::NotFound(path.to_string()));
        }
        if (400..500).contains(&status) {
            // P0-6 fix (2026-05-27): propagate body-read failures instead
            // of substituting "" silently. A transient TLS truncation or
            // connection reset mid-body is qualitatively the same as a
            // .send() failure and the breaker should see it.
            let text = match response.text().await {
                Ok(t) => t,
                Err(e) => {
                    self.record_failure();
                    return Err(Error::Network(e));
                }
            };
            return Err(Error::Validation(text));
        }
        if status >= 500 {
            self.record_failure();
            let text = match response.text().await {
                Ok(t) => t,
                Err(e) => return Err(Error::Network(e)),
            };
            return Err(Error::Server {
                status,
                message: text,
            });
        }

        if let Some(len) = response.content_length() {
            if len > MAX_RESPONSE_BYTES {
                return Err(Error::Server {
                    status,
                    message: format!(
                        "Response body too large ({} bytes; cap is {})",
                        len, MAX_RESPONSE_BYTES
                    ),
                });
            }
        }

        // Capture lifecycle headers BEFORE `.json()` consumes the response.
        let hints = parse_csv_header(response.headers().get(HINT_HEADER));
        let auto_fired = parse_csv_header(response.headers().get(AUTO_FIRED_HEADER));

        let json: serde_json::Value = response.json().await.map_err(|e| {
            self.record_failure();
            Error::Network(e)
        })?;

        Ok((json, hints, auto_fired))
    }

    // =========================================================================
    // Circuit breaker
    // =========================================================================

    fn check_circuit(&self) -> Result<(), Error> {
        let state = self.inner.circuit_state.load(Ordering::Acquire);
        match state {
            CIRCUIT_STATE_CLOSED => Ok(()),
            CIRCUIT_STATE_HALF_OPEN => {
                // Probe in flight by another task. Reject this call so
                // exactly one request lands on the substrate during
                // recovery.
                Err(Error::CircuitOpen {
                    cooldown_secs: self.inner.circuit_cooldown.as_secs(),
                })
            }
            CIRCUIT_STATE_OPEN => {
                let opened_at = self
                    .inner
                    .circuit_opened_at
                    .lock()
                    .unwrap_or_else(|e| e.into_inner());
                let elapsed = match *opened_at {
                    Some(t) => t.elapsed() >= self.inner.circuit_cooldown,
                    None => true,
                };
                drop(opened_at);

                if elapsed {
                    // Try to grab the probe slot via CAS — exactly one
                    // concurrent caller wins and is allowed through.
                    if self
                        .inner
                        .circuit_state
                        .compare_exchange(
                            CIRCUIT_STATE_OPEN,
                            CIRCUIT_STATE_HALF_OPEN,
                            Ordering::AcqRel,
                            Ordering::Acquire,
                        )
                        .is_ok()
                    {
                        debug!("erebyx-sdk circuit HALF_OPEN — probe call allowed");
                        return Ok(());
                    }
                }
                Err(Error::CircuitOpen {
                    cooldown_secs: self.inner.circuit_cooldown.as_secs(),
                })
            }
            _ => Ok(()),
        }
    }

    fn record_success(&self) {
        self.inner.consecutive_failures.store(0, Ordering::Relaxed);
        let prev = self
            .inner
            .circuit_state
            .swap(CIRCUIT_STATE_CLOSED, Ordering::AcqRel);
        if prev != CIRCUIT_STATE_CLOSED {
            let mut guard = self
                .inner
                .circuit_opened_at
                .lock()
                .unwrap_or_else(|e| e.into_inner());
            *guard = None;
            debug!(
                prev_state = prev,
                "erebyx-sdk circuit CLOSED — substrate healthy again"
            );
        }
    }

    fn record_failure(&self) {
        let state = self.inner.circuit_state.load(Ordering::Acquire);
        if state == CIRCUIT_STATE_HALF_OPEN {
            // Probe failed → back to Open with a fresh cooldown window.
            self.inner
                .circuit_state
                .store(CIRCUIT_STATE_OPEN, Ordering::Release);
            let mut guard = self
                .inner
                .circuit_opened_at
                .lock()
                .unwrap_or_else(|e| e.into_inner());
            *guard = Some(Instant::now());
            warn!("erebyx-sdk circuit RE-OPENED — half-open probe failed");
            return;
        }
        if state == CIRCUIT_STATE_OPEN {
            return; // already open; counter + timer already set
        }
        let failures = self
            .inner
            .consecutive_failures
            .fetch_add(1, Ordering::Relaxed)
            + 1;
        if failures >= CIRCUIT_BREAK_THRESHOLD {
            // Only trip Closed → Open; never trample HalfOpen from a
            // concurrent record_success call.
            if self
                .inner
                .circuit_state
                .compare_exchange(
                    CIRCUIT_STATE_CLOSED,
                    CIRCUIT_STATE_OPEN,
                    Ordering::AcqRel,
                    Ordering::Acquire,
                )
                .is_ok()
            {
                let mut guard = self
                    .inner
                    .circuit_opened_at
                    .lock()
                    .unwrap_or_else(|e| e.into_inner());
                *guard = Some(Instant::now());
                warn!(
                    failures = failures,
                    "erebyx-sdk circuit OPEN — {CIRCUIT_BREAK_THRESHOLD} consecutive failures"
                );
            }
        }
    }
}

/// Builder for constructing a Memory client with custom configuration.
pub struct MemoryBuilder {
    api_key: String,
    api_url: String,
    instance_id: String,
    session_id: String,
    passphrase: Option<String>,
    timeout: Duration,
    circuit_cooldown: Duration,
}

impl MemoryBuilder {
    pub fn api_url(mut self, url: &str) -> Self {
        self.api_url = url.to_string();
        self
    }

    pub fn instance_id(mut self, id: &str) -> Self {
        self.instance_id = id.to_string();
        self
    }

    /// Set the per-tenant passphrase used to derive the Argon2id KEK
    /// at request time. Required for tenants registered at v0.1.1+.
    ///
    /// The substrate hashes the passphrase with the tenant's stored
    /// Argon2id parameters and derives a per-tenant KEK at request time;
    /// the server never persists the passphrase itself. At v0.1.1 this is
    /// **not** zero-knowledge — the tenant KEK is also wrapped under a
    /// server-held master KEK that EREBYX operationally holds, so EREBYX
    /// can still decrypt (support, backup, recovery) and a lost passphrase
    /// is recoverable. When per-user zero-knowledge ships in v0.2, the
    /// passphrase + BIP39 recovery seed become the ONLY keys to your data,
    /// and losing both is unrecoverable by design.
    ///
    /// Empty input is silently dropped to keep the default (None). The
    /// server distinguishes "header absent" (legacy hkdf_api_key
    /// tenant) from "header present-but-empty" (rejected) — silently
    /// dropping is friendlier than erroring at the SDK boundary.
    pub fn passphrase(mut self, passphrase: &str) -> Self {
        let trimmed = passphrase.trim();
        if !trimmed.is_empty() {
            self.passphrase = Some(trimmed.to_string());
        }
        self
    }

    /// Override the per-process session id sent on `X-Erebyx-Session-Id`.
    ///
    /// Defaults to a fresh UUID v4 per `MemoryBuilder`. Override when
    /// you want to bind the SDK lifetime to an external identifier — e.g.
    /// the harness conversation id, an LLM thread id, or a per-tab id in
    /// a browser harness — so substrate-side per-session counters
    /// (hint engine, auto-fire engine) stay coherent across reloads.
    ///
    /// Empty input is silently dropped to keep the default UUID — the
    /// substrate refuses to attribute hint state to an empty session id,
    /// and silently ignoring the empty case is friendlier than erroring.
    pub fn session_id(mut self, id: &str) -> Self {
        if !id.is_empty() {
            self.session_id = id.to_string();
        }
        self
    }

    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Override the circuit-breaker cooldown — the time between the
    /// breaker tripping Open and the substrate being permitted a
    /// single HalfOpen probe call.
    ///
    /// Defaults to 30s. Self-hosted substrate operators may want a
    /// shorter cooldown for environments with faster recovery
    /// characteristics, or a longer cooldown when the substrate is
    /// fronted by a load balancer with its own retry behavior.
    ///
    /// Tests use a short cooldown (~50ms) to exercise the breaker
    /// against real HTTP without paused time.
    pub fn circuit_cooldown(mut self, cooldown: Duration) -> Self {
        self.circuit_cooldown = cooldown;
        self
    }

    pub fn build(self) -> Result<Memory, Error> {
        if self.api_key.is_empty() {
            return Err(Error::Config("API key cannot be empty".into()));
        }

        // Reject non-HTTPS URLs (allow http://localhost:* for dev).
        if !is_safe_url(&self.api_url) {
            return Err(Error::Config(format!(
                "api_url must be https:// (got {}). \
                 Plain http:// is only allowed for localhost/127.0.0.1.",
                self.api_url
            )));
        }

        let client = Client::builder()
            .timeout(self.timeout)
            .connect_timeout(Duration::from_secs(5))
            .build()
            .map_err(|e| Error::Config(format!("Failed to create HTTP client: {e}")))?;

        Ok(Memory {
            inner: Arc::new(MemoryInner {
                client,
                api_url: self.api_url,
                api_key: self.api_key,
                instance_id: self.instance_id,
                session_id: self.session_id,
                passphrase: self.passphrase,
                consecutive_failures: AtomicU64::new(0),
                circuit_state: AtomicU8::new(CIRCUIT_STATE_CLOSED),
                circuit_opened_at: std::sync::Mutex::new(None),
                circuit_cooldown: self.circuit_cooldown,
            }),
        })
    }
}