dakera-client 0.9.3

Rust client SDK for Dakera AI Agent Memory Platform
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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
//! Memory-oriented client methods for Dakera AI Agent Memory Platform
//!
//! Provides high-level methods for storing, recalling, and managing
//! agent memories and sessions through the Dakera API.

use serde::{Deserialize, Serialize};

use crate::error::Result;
use crate::types::{
    AgentFeedbackSummary, EdgeType, FeedbackHealthResponse, FeedbackHistoryResponse,
    FeedbackResponse, FeedbackSignal, GraphExport, GraphLinkRequest, GraphLinkResponse,
    GraphOptions, GraphPath, MemoryFeedbackBody, MemoryGraph, MemoryImportancePatch,
};
use crate::DakeraClient;

// ============================================================================
// Memory Types (client-side)
// ============================================================================

/// Memory type classification
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub enum MemoryType {
    #[default]
    Episodic,
    Semantic,
    Procedural,
    Working,
}

/// Store a memory request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StoreMemoryRequest {
    pub agent_id: String,
    pub content: String,
    #[serde(default)]
    pub memory_type: MemoryType,
    #[serde(default = "default_importance")]
    pub importance: f32,
    #[serde(default)]
    pub tags: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Value>,
    /// Optional TTL in seconds. The memory is hard-deleted after this many
    /// seconds from creation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ttl_seconds: Option<u64>,
    /// Optional explicit expiry as a Unix timestamp (seconds). Takes precedence
    /// over `ttl_seconds` when both are set. The memory is hard-deleted by the
    /// decay engine on expiry (DECAY-3).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<u64>,
}

fn default_importance() -> f32 {
    0.5
}

impl StoreMemoryRequest {
    /// Create a new store memory request
    pub fn new(agent_id: impl Into<String>, content: impl Into<String>) -> Self {
        Self {
            agent_id: agent_id.into(),
            content: content.into(),
            memory_type: MemoryType::default(),
            importance: 0.5,
            tags: Vec::new(),
            session_id: None,
            metadata: None,
            ttl_seconds: None,
            expires_at: None,
        }
    }

    /// Set memory type
    pub fn with_type(mut self, memory_type: MemoryType) -> Self {
        self.memory_type = memory_type;
        self
    }

    /// Set importance score
    pub fn with_importance(mut self, importance: f32) -> Self {
        self.importance = importance.clamp(0.0, 1.0);
        self
    }

    /// Set tags
    pub fn with_tags(mut self, tags: Vec<String>) -> Self {
        self.tags = tags;
        self
    }

    /// Set session ID
    pub fn with_session(mut self, session_id: impl Into<String>) -> Self {
        self.session_id = Some(session_id.into());
        self
    }

    /// Set metadata
    pub fn with_metadata(mut self, metadata: serde_json::Value) -> Self {
        self.metadata = Some(metadata);
        self
    }

    /// Set TTL in seconds. The memory is hard-deleted after this many seconds
    /// from creation.
    pub fn with_ttl(mut self, ttl_seconds: u64) -> Self {
        self.ttl_seconds = Some(ttl_seconds);
        self
    }

    /// Set an explicit expiry Unix timestamp (seconds). Takes precedence over
    /// `ttl_seconds` when both are set (DECAY-3).
    pub fn with_expires_at(mut self, expires_at: u64) -> Self {
        self.expires_at = Some(expires_at);
        self
    }
}

/// Stored memory response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StoreMemoryResponse {
    pub memory_id: String,
    pub agent_id: String,
    pub namespace: String,
}

/// Recall memories request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RecallRequest {
    pub agent_id: String,
    pub query: String,
    #[serde(default = "default_top_k")]
    pub top_k: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub memory_type: Option<MemoryType>,
    #[serde(default)]
    pub min_importance: f32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    #[serde(default)]
    pub tags: Vec<String>,
}

fn default_top_k() -> usize {
    5
}

impl RecallRequest {
    /// Create a new recall request
    pub fn new(agent_id: impl Into<String>, query: impl Into<String>) -> Self {
        Self {
            agent_id: agent_id.into(),
            query: query.into(),
            top_k: 5,
            memory_type: None,
            min_importance: 0.0,
            session_id: None,
            tags: Vec::new(),
        }
    }

    /// Set number of results
    pub fn with_top_k(mut self, top_k: usize) -> Self {
        self.top_k = top_k;
        self
    }

    /// Filter by memory type
    pub fn with_type(mut self, memory_type: MemoryType) -> Self {
        self.memory_type = Some(memory_type);
        self
    }

    /// Set minimum importance threshold
    pub fn with_min_importance(mut self, min: f32) -> Self {
        self.min_importance = min;
        self
    }

    /// Filter by session
    pub fn with_session(mut self, session_id: impl Into<String>) -> Self {
        self.session_id = Some(session_id.into());
        self
    }

    /// Filter by tags
    pub fn with_tags(mut self, tags: Vec<String>) -> Self {
        self.tags = tags;
        self
    }
}

/// A recalled memory
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RecalledMemory {
    pub id: String,
    pub content: String,
    pub memory_type: MemoryType,
    pub importance: f32,
    pub score: f32,
    #[serde(default)]
    pub tags: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Value>,
    pub created_at: u64,
    pub last_accessed_at: u64,
    pub access_count: u32,
}

/// Recall response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RecallResponse {
    pub memories: Vec<RecalledMemory>,
    pub total_found: usize,
}

/// Forget (delete) memories request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ForgetRequest {
    pub agent_id: String,
    #[serde(default)]
    pub memory_ids: Vec<String>,
    #[serde(default)]
    pub tags: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before_timestamp: Option<u64>,
}

impl ForgetRequest {
    /// Forget specific memories by ID
    pub fn by_ids(agent_id: impl Into<String>, ids: Vec<String>) -> Self {
        Self {
            agent_id: agent_id.into(),
            memory_ids: ids,
            tags: Vec::new(),
            session_id: None,
            before_timestamp: None,
        }
    }

    /// Forget memories with specific tags
    pub fn by_tags(agent_id: impl Into<String>, tags: Vec<String>) -> Self {
        Self {
            agent_id: agent_id.into(),
            memory_ids: Vec::new(),
            tags,
            session_id: None,
            before_timestamp: None,
        }
    }

    /// Forget all memories in a session
    pub fn by_session(agent_id: impl Into<String>, session_id: impl Into<String>) -> Self {
        Self {
            agent_id: agent_id.into(),
            memory_ids: Vec::new(),
            tags: Vec::new(),
            session_id: Some(session_id.into()),
            before_timestamp: None,
        }
    }
}

/// Forget response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ForgetResponse {
    pub deleted_count: u64,
}

/// Session start request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionStartRequest {
    pub agent_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Value>,
}

/// Session information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Session {
    pub id: String,
    pub agent_id: String,
    pub started_at: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ended_at: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub summary: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Value>,
}

/// Session end request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionEndRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub summary: Option<String>,
}

/// Request to update a memory
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateMemoryRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub memory_type: Option<MemoryType>,
}

/// Request to update memory importance
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateImportanceRequest {
    pub memory_ids: Vec<String>,
    pub importance: f32,
}

/// Request to consolidate memories
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConsolidateRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub memory_type: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub threshold: Option<f32>,
    #[serde(default)]
    pub dry_run: bool,
}

/// Response from consolidation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConsolidateResponse {
    pub consolidated_count: usize,
    pub removed_count: usize,
    pub new_memories: Vec<String>,
}

/// Request for memory feedback
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FeedbackRequest {
    pub memory_id: String,
    pub feedback: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub relevance_score: Option<f32>,
}

/// Response from legacy feedback endpoint (POST /v1/agents/:id/memories/feedback)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LegacyFeedbackResponse {
    pub status: String,
    pub updated_importance: Option<f32>,
}

// ============================================================================
// CE-2: Batch Recall / Forget Types
// ============================================================================

/// Filter predicates for batch memory operations (CE-2).
///
/// All fields are optional.  For [`BatchForgetRequest`] at least one must be
/// set (server-side safety guard).
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct BatchMemoryFilter {
    /// Restrict to memories that carry **all** listed tags.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<String>>,
    /// Minimum importance (inclusive).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_importance: Option<f32>,
    /// Maximum importance (inclusive).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_importance: Option<f32>,
    /// Only memories created at or after this Unix timestamp (seconds).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_after: Option<u64>,
    /// Only memories created before or at this Unix timestamp (seconds).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_before: Option<u64>,
    /// Restrict to a specific memory type.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub memory_type: Option<MemoryType>,
    /// Restrict to memories from a specific session.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
}

impl BatchMemoryFilter {
    /// Convenience: filter by tags.
    pub fn with_tags(mut self, tags: Vec<String>) -> Self {
        self.tags = Some(tags);
        self
    }

    /// Convenience: filter by minimum importance.
    pub fn with_min_importance(mut self, min: f32) -> Self {
        self.min_importance = Some(min);
        self
    }

    /// Convenience: filter by maximum importance.
    pub fn with_max_importance(mut self, max: f32) -> Self {
        self.max_importance = Some(max);
        self
    }

    /// Convenience: filter by session.
    pub fn with_session(mut self, session_id: impl Into<String>) -> Self {
        self.session_id = Some(session_id.into());
        self
    }
}

/// Request body for `POST /v1/memories/recall/batch`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchRecallRequest {
    /// Agent whose memory namespace to search.
    pub agent_id: String,
    /// Filter predicates to apply.
    #[serde(default)]
    pub filter: BatchMemoryFilter,
    /// Maximum number of results to return (default: 100).
    #[serde(default = "default_batch_limit")]
    pub limit: usize,
}

fn default_batch_limit() -> usize {
    100
}

impl BatchRecallRequest {
    /// Create a new batch recall request for an agent.
    pub fn new(agent_id: impl Into<String>) -> Self {
        Self {
            agent_id: agent_id.into(),
            filter: BatchMemoryFilter::default(),
            limit: 100,
        }
    }

    /// Set filter predicates.
    pub fn with_filter(mut self, filter: BatchMemoryFilter) -> Self {
        self.filter = filter;
        self
    }

    /// Set result limit.
    pub fn with_limit(mut self, limit: usize) -> Self {
        self.limit = limit;
        self
    }
}

/// Response from `POST /v1/memories/recall/batch`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchRecallResponse {
    pub memories: Vec<RecalledMemory>,
    /// Total memories in the agent namespace.
    pub total: usize,
    /// Number of memories that passed the filter.
    pub filtered: usize,
}

/// Request body for `DELETE /v1/memories/forget/batch`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchForgetRequest {
    /// Agent whose memory namespace to purge from.
    pub agent_id: String,
    /// Filter predicates — **at least one must be set** (server safety guard).
    pub filter: BatchMemoryFilter,
}

impl BatchForgetRequest {
    /// Create a new batch forget request with the given filter.
    pub fn new(agent_id: impl Into<String>, filter: BatchMemoryFilter) -> Self {
        Self {
            agent_id: agent_id.into(),
            filter,
        }
    }
}

/// Response from `DELETE /v1/memories/forget/batch`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchForgetResponse {
    pub deleted_count: usize,
}

// ============================================================================
// Memory Client Methods
// ============================================================================

impl DakeraClient {
    // ========================================================================
    // Memory Operations
    // ========================================================================

    /// Store a memory for an agent
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use dakera_client::{DakeraClient, memory::StoreMemoryRequest};
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = DakeraClient::new("http://localhost:3000")?;
    ///
    /// let request = StoreMemoryRequest::new("agent-1", "The user prefers dark mode")
    ///     .with_importance(0.8)
    ///     .with_tags(vec!["preferences".to_string()]);
    ///
    /// let response = client.store_memory(request).await?;
    /// println!("Stored memory: {}", response.memory_id);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn store_memory(&self, request: StoreMemoryRequest) -> Result<StoreMemoryResponse> {
        let url = format!("{}/v1/memory/store", self.base_url);
        let response = self.client.post(&url).json(&request).send().await?;
        self.handle_response(response).await
    }

    /// Recall memories by semantic query
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use dakera_client::{DakeraClient, memory::RecallRequest};
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = DakeraClient::new("http://localhost:3000")?;
    ///
    /// let request = RecallRequest::new("agent-1", "user preferences")
    ///     .with_top_k(10);
    ///
    /// let response = client.recall(request).await?;
    /// for memory in response.memories {
    ///     println!("{}: {} (score: {})", memory.id, memory.content, memory.score);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn recall(&self, request: RecallRequest) -> Result<RecallResponse> {
        let url = format!("{}/v1/memory/recall", self.base_url);
        let response = self.client.post(&url).json(&request).send().await?;
        self.handle_response(response).await
    }

    /// Simple recall with just agent_id and query (convenience method)
    pub async fn recall_simple(
        &self,
        agent_id: &str,
        query: &str,
        top_k: usize,
    ) -> Result<RecallResponse> {
        self.recall(RecallRequest::new(agent_id, query).with_top_k(top_k))
            .await
    }

    /// Get a specific memory by ID
    pub async fn get_memory(&self, memory_id: &str) -> Result<RecalledMemory> {
        let url = format!("{}/v1/memory/get/{}", self.base_url, memory_id);
        let response = self.client.get(&url).send().await?;
        self.handle_response(response).await
    }

    /// Forget (delete) memories
    pub async fn forget(&self, request: ForgetRequest) -> Result<ForgetResponse> {
        let url = format!("{}/v1/memory/forget", self.base_url);
        let response = self.client.post(&url).json(&request).send().await?;
        self.handle_response(response).await
    }

    /// Search memories with advanced filters
    pub async fn search_memories(&self, request: RecallRequest) -> Result<RecallResponse> {
        let url = format!("{}/v1/memory/search", self.base_url);
        let response = self.client.post(&url).json(&request).send().await?;
        self.handle_response(response).await
    }

    /// Update an existing memory
    pub async fn update_memory(
        &self,
        agent_id: &str,
        memory_id: &str,
        request: UpdateMemoryRequest,
    ) -> Result<StoreMemoryResponse> {
        let url = format!(
            "{}/v1/agents/{}/memories/{}",
            self.base_url, agent_id, memory_id
        );
        let response = self.client.put(&url).json(&request).send().await?;
        self.handle_response(response).await
    }

    /// Update importance of memories
    pub async fn update_importance(
        &self,
        agent_id: &str,
        request: UpdateImportanceRequest,
    ) -> Result<serde_json::Value> {
        let url = format!(
            "{}/v1/agents/{}/memories/importance",
            self.base_url, agent_id
        );
        let response = self.client.put(&url).json(&request).send().await?;
        self.handle_response(response).await
    }

    /// Consolidate memories for an agent
    pub async fn consolidate(
        &self,
        agent_id: &str,
        request: ConsolidateRequest,
    ) -> Result<ConsolidateResponse> {
        let url = format!(
            "{}/v1/agents/{}/memories/consolidate",
            self.base_url, agent_id
        );
        let response = self.client.post(&url).json(&request).send().await?;
        self.handle_response(response).await
    }

    /// Submit feedback on a memory recall
    pub async fn memory_feedback(
        &self,
        agent_id: &str,
        request: FeedbackRequest,
    ) -> Result<LegacyFeedbackResponse> {
        let url = format!("{}/v1/agents/{}/memories/feedback", self.base_url, agent_id);
        let response = self.client.post(&url).json(&request).send().await?;
        self.handle_response(response).await
    }

    // ========================================================================
    // Memory Feedback Loop — INT-1
    // ========================================================================

    /// Submit upvote/downvote/flag feedback on a memory (INT-1).
    ///
    /// # Arguments
    /// * `memory_id` – The memory to give feedback on.
    /// * `agent_id` – The agent that owns the memory.
    /// * `signal` – [`FeedbackSignal`] value: `Upvote`, `Downvote`, or `Flag`.
    ///
    /// # Example
    /// ```no_run
    /// # use dakera_client::{DakeraClient, FeedbackSignal};
    /// # async fn example(client: &DakeraClient) -> dakera_client::Result<()> {
    /// let resp = client.feedback_memory("mem-abc", "agent-1", FeedbackSignal::Upvote).await?;
    /// println!("new importance: {}", resp.new_importance);
    /// # Ok(()) }
    /// ```
    pub async fn feedback_memory(
        &self,
        memory_id: &str,
        agent_id: &str,
        signal: FeedbackSignal,
    ) -> Result<FeedbackResponse> {
        let url = format!("{}/v1/memories/{}/feedback", self.base_url, memory_id);
        let body = MemoryFeedbackBody {
            agent_id: agent_id.to_string(),
            signal,
        };
        let response = self.client.post(&url).json(&body).send().await?;
        self.handle_response(response).await
    }

    /// Get the full feedback history for a memory (INT-1).
    pub async fn get_memory_feedback_history(
        &self,
        memory_id: &str,
    ) -> Result<FeedbackHistoryResponse> {
        let url = format!("{}/v1/memories/{}/feedback", self.base_url, memory_id);
        let response = self.client.get(&url).send().await?;
        self.handle_response(response).await
    }

    /// Get aggregate feedback counts and health score for an agent (INT-1).
    pub async fn get_agent_feedback_summary(&self, agent_id: &str) -> Result<AgentFeedbackSummary> {
        let url = format!("{}/v1/agents/{}/feedback/summary", self.base_url, agent_id);
        let response = self.client.get(&url).send().await?;
        self.handle_response(response).await
    }

    /// Directly override a memory's importance score (INT-1).
    ///
    /// # Arguments
    /// * `memory_id` – The memory to update.
    /// * `agent_id` – The agent that owns the memory.
    /// * `importance` – New importance value (0.0–1.0).
    pub async fn patch_memory_importance(
        &self,
        memory_id: &str,
        agent_id: &str,
        importance: f32,
    ) -> Result<FeedbackResponse> {
        let url = format!("{}/v1/memories/{}/importance", self.base_url, memory_id);
        let body = MemoryImportancePatch {
            agent_id: agent_id.to_string(),
            importance,
        };
        let response = self.client.patch(&url).json(&body).send().await?;
        self.handle_response(response).await
    }

    /// Get overall feedback health score for an agent (INT-1).
    ///
    /// The health score is the mean importance of all non-expired memories (0.0–1.0).
    /// A higher score indicates a healthier, more relevant memory store.
    pub async fn get_feedback_health(&self, agent_id: &str) -> Result<FeedbackHealthResponse> {
        let url = format!("{}/v1/feedback/health?agent_id={}", self.base_url, agent_id);
        let response = self.client.get(&url).send().await?;
        self.handle_response(response).await
    }

    // ========================================================================
    // Memory Knowledge Graph Operations (CE-5 / SDK-9)
    // ========================================================================

    /// Traverse the knowledge graph from a memory node.
    ///
    /// Requires CE-5 (Memory Knowledge Graph) on the server.
    ///
    /// # Arguments
    /// * `memory_id` – Root memory ID to start traversal from.
    /// * `options` – Traversal options (depth, edge type filters).
    ///
    /// # Example
    /// ```no_run
    /// # use dakera_client::{DakeraClient, GraphOptions};
    /// # async fn example(client: &DakeraClient) -> dakera_client::Result<()> {
    /// let graph = client.memory_graph("mem-abc", GraphOptions::new().depth(2)).await?;
    /// println!("{} nodes, {} edges", graph.nodes.len(), graph.edges.len());
    /// # Ok(()) }
    /// ```
    pub async fn memory_graph(
        &self,
        memory_id: &str,
        options: GraphOptions,
    ) -> Result<MemoryGraph> {
        let mut url = format!("{}/v1/memories/{}/graph", self.base_url, memory_id);
        let depth = options.depth.unwrap_or(1);
        url.push_str(&format!("?depth={}", depth));
        if let Some(types) = &options.types {
            let type_strs: Vec<String> = types
                .iter()
                .map(|t| {
                    serde_json::to_value(t)
                        .unwrap()
                        .as_str()
                        .unwrap_or("")
                        .to_string()
                })
                .collect();
            if !type_strs.is_empty() {
                url.push_str(&format!("&types={}", type_strs.join(",")));
            }
        }
        let response = self.client.get(&url).send().await?;
        self.handle_response(response).await
    }

    /// Find the shortest path between two memories in the knowledge graph.
    ///
    /// Requires CE-5 (Memory Knowledge Graph) on the server.
    ///
    /// # Example
    /// ```no_run
    /// # use dakera_client::DakeraClient;
    /// # async fn example(client: &DakeraClient) -> dakera_client::Result<()> {
    /// let path = client.memory_path("mem-abc", "mem-xyz").await?;
    /// println!("{} hops: {:?}", path.hops, path.path);
    /// # Ok(()) }
    /// ```
    pub async fn memory_path(&self, source_id: &str, target_id: &str) -> Result<GraphPath> {
        let url = format!(
            "{}/v1/memories/{}/path?target={}",
            self.base_url,
            source_id,
            urlencoding::encode(target_id)
        );
        let response = self.client.get(&url).send().await?;
        self.handle_response(response).await
    }

    /// Create an explicit edge between two memories.
    ///
    /// Requires CE-5 (Memory Knowledge Graph) on the server.
    ///
    /// # Example
    /// ```no_run
    /// # use dakera_client::{DakeraClient, EdgeType};
    /// # async fn example(client: &DakeraClient) -> dakera_client::Result<()> {
    /// let resp = client.memory_link("mem-abc", "mem-xyz", EdgeType::LinkedBy).await?;
    /// println!("Created edge: {}", resp.edge.id);
    /// # Ok(()) }
    /// ```
    pub async fn memory_link(
        &self,
        source_id: &str,
        target_id: &str,
        edge_type: EdgeType,
    ) -> Result<GraphLinkResponse> {
        let url = format!("{}/v1/memories/{}/links", self.base_url, source_id);
        let request = GraphLinkRequest {
            target_id: target_id.to_string(),
            edge_type,
        };
        let response = self.client.post(&url).json(&request).send().await?;
        self.handle_response(response).await
    }

    /// Export the full knowledge graph for an agent.
    ///
    /// Requires CE-5 (Memory Knowledge Graph) on the server.
    ///
    /// # Arguments
    /// * `agent_id` – Agent whose graph to export.
    /// * `format` – Export format: `"json"` (default), `"graphml"`, or `"csv"`.
    pub async fn agent_graph_export(&self, agent_id: &str, format: &str) -> Result<GraphExport> {
        let url = format!(
            "{}/v1/agents/{}/graph/export?format={}",
            self.base_url, agent_id, format
        );
        let response = self.client.get(&url).send().await?;
        self.handle_response(response).await
    }

    // ========================================================================
    // Session Operations
    // ========================================================================

    /// Start a new session for an agent
    pub async fn start_session(&self, agent_id: &str) -> Result<Session> {
        let url = format!("{}/v1/sessions/start", self.base_url);
        let request = SessionStartRequest {
            agent_id: agent_id.to_string(),
            metadata: None,
        };
        let response = self.client.post(&url).json(&request).send().await?;
        self.handle_response(response).await
    }

    /// Start a session with metadata
    pub async fn start_session_with_metadata(
        &self,
        agent_id: &str,
        metadata: serde_json::Value,
    ) -> Result<Session> {
        let url = format!("{}/v1/sessions/start", self.base_url);
        let request = SessionStartRequest {
            agent_id: agent_id.to_string(),
            metadata: Some(metadata),
        };
        let response = self.client.post(&url).json(&request).send().await?;
        self.handle_response(response).await
    }

    /// End a session, optionally with a summary
    pub async fn end_session(&self, session_id: &str, summary: Option<String>) -> Result<Session> {
        let url = format!("{}/v1/sessions/{}/end", self.base_url, session_id);
        let request = SessionEndRequest { summary };
        let response = self.client.post(&url).json(&request).send().await?;
        self.handle_response(response).await
    }

    /// Get a session by ID
    pub async fn get_session(&self, session_id: &str) -> Result<Session> {
        let url = format!("{}/v1/sessions/{}", self.base_url, session_id);
        let response = self.client.get(&url).send().await?;
        self.handle_response(response).await
    }

    /// List sessions for an agent
    pub async fn list_sessions(&self, agent_id: &str) -> Result<Vec<Session>> {
        let url = format!("{}/v1/sessions?agent_id={}", self.base_url, agent_id);
        let response = self.client.get(&url).send().await?;
        self.handle_response(response).await
    }

    /// Get memories in a session
    pub async fn session_memories(&self, session_id: &str) -> Result<RecallResponse> {
        let url = format!("{}/v1/sessions/{}/memories", self.base_url, session_id);
        let response = self.client.get(&url).send().await?;
        self.handle_response(response).await
    }

    // ========================================================================
    // CE-2: Batch Recall / Forget
    // ========================================================================

    /// Bulk-recall memories using filter predicates (CE-2).
    ///
    /// Uses `POST /v1/memories/recall/batch` — no embedding required.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use dakera_client::{DakeraClient, memory::{BatchRecallRequest, BatchMemoryFilter}};
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = DakeraClient::new("http://localhost:3000")?;
    ///
    /// let filter = BatchMemoryFilter::default().with_min_importance(0.7);
    /// let req = BatchRecallRequest::new("agent-1").with_filter(filter).with_limit(50);
    /// let resp = client.batch_recall(req).await?;
    /// println!("Found {} memories", resp.filtered);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn batch_recall(&self, request: BatchRecallRequest) -> Result<BatchRecallResponse> {
        let url = format!("{}/v1/memories/recall/batch", self.base_url);
        let response = self.client.post(&url).json(&request).send().await?;
        self.handle_response(response).await
    }

    /// Bulk-delete memories using filter predicates (CE-2).
    ///
    /// Uses `DELETE /v1/memories/forget/batch`.  The server requires at least
    /// one filter predicate to be set as a safety guard.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use dakera_client::{DakeraClient, memory::{BatchForgetRequest, BatchMemoryFilter}};
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = DakeraClient::new("http://localhost:3000")?;
    ///
    /// let filter = BatchMemoryFilter::default().with_min_importance(0.0).with_max_importance(0.2);
    /// let resp = client.batch_forget(BatchForgetRequest::new("agent-1", filter)).await?;
    /// println!("Deleted {} memories", resp.deleted_count);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn batch_forget(&self, request: BatchForgetRequest) -> Result<BatchForgetResponse> {
        let url = format!("{}/v1/memories/forget/batch", self.base_url);
        let response = self.client.delete(&url).json(&request).send().await?;
        self.handle_response(response).await
    }
}