brainwires-storage 0.9.0

Backend-agnostic storage, tiered memory, and document management for the Brainwires Agent Framework
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
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
//! Internal transport abstraction layer for NornicDB.
//!
//! Defines the [`NornicTransport`] trait and three concrete implementations:
//!
//! | Transport       | Feature gate        | Protocol          |
//! |-----------------|---------------------|-------------------|
//! | `RestTransport` | `nornicdb-backend`  | HTTP / REST       |
//! | `BoltTransport` | `nornicdb-bolt`     | Neo4j Bolt binary |
//! | `GrpcTransport` | `nornicdb-grpc`     | gRPC (Qdrant)     |
//!
//! `NornicDatabase` (in `mod.rs`) holds an `Arc<dyn NornicTransport>` and
//! delegates all wire-level communication through this trait.

use anyhow::{Context, Result};
use serde_json::{Value, json};

// ── Trait ───────────────────────────────────────────────────────────────

/// Wire-level transport abstraction for NornicDB.
///
/// Every method maps to a logical operation that may be implemented over
/// different protocols.  Implementations must be `Send + Sync` so the
/// trait object can live inside an `Arc`.
#[async_trait::async_trait]
pub(crate) trait NornicTransport: Send + Sync {
    /// Verify that the remote server is reachable and healthy.
    async fn health_check(&self) -> Result<bool>;

    /// Execute an arbitrary Cypher query with the given JSON parameters.
    async fn execute_cypher(&self, query: &str, params: Value) -> Result<Vec<Value>>;

    /// Combined vector + keyword (BM25) search.
    async fn hybrid_search(
        &self,
        query_text: &str,
        query_vector: Vec<f32>,
        limit: usize,
        min_score: f32,
        node_label: &str,
        filters: Value,
    ) -> Result<Vec<Value>>;

    /// Pure vector similarity search.
    async fn vector_search(
        &self,
        query_vector: Vec<f32>,
        limit: usize,
        min_score: f32,
        node_label: &str,
        filters: Value,
    ) -> Result<Vec<Value>>;

    /// Batch-upsert nodes.  Returns the number of nodes written.
    async fn store_nodes(&self, nodes: Vec<Value>, node_label: &str) -> Result<usize>;

    /// Delete nodes matching `{property}: value` on the given label.
    async fn delete_nodes(&self, node_label: &str, property: &str, value: &str) -> Result<usize>;

    /// Count nodes matching `{property}: value` on the given label.
    async fn count_nodes(&self, node_label: &str, property: &str, value: &str) -> Result<usize>;

    /// Return the distinct values of `property` on nodes whose
    /// `filter_prop` equals `filter_val`.
    async fn distinct_property(
        &self,
        node_label: &str,
        property: &str,
        filter_prop: &str,
        filter_val: &str,
    ) -> Result<Vec<String>>;

    /// Human-readable name of the transport (for diagnostics / logging).
    #[allow(dead_code)]
    fn transport_name(&self) -> &'static str;
}

// ════════════════════════════════════════════════════════════════════════
//  REST Transport  (always available when `nornicdb-backend` is enabled)
// ════════════════════════════════════════════════════════════════════════

use std::sync::Arc;
use tokio::sync::RwLock;

/// REST transport backed by `reqwest`.
///
/// Talks to a NornicDB server over its HTTP API.  Authentication is
/// performed lazily via [`authenticate`] which stores a JWT for
/// subsequent requests.
pub(crate) struct RestTransport {
    client: reqwest::Client,
    base_url: String,
    database: String,
    auth_token: Arc<RwLock<Option<String>>>,
}

impl RestTransport {
    /// Create a new REST transport targeting `base_url`.
    ///
    /// No network call is made until the first method invocation.
    pub(crate) async fn new(base_url: &str, database: &str) -> Result<Self> {
        let client = reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(30))
            .build()
            .context("Failed to build HTTP client for NornicDB REST transport")?;

        tracing::info!(
            "REST transport created for {} (database: {})",
            base_url,
            database
        );

        Ok(Self {
            client,
            base_url: base_url.trim_end_matches('/').to_string(),
            database: database.to_string(),
            auth_token: Arc::new(RwLock::new(None)),
        })
    }

    /// Authenticate against the NornicDB server and store the resulting
    /// JWT for future requests.
    pub(crate) async fn authenticate(&self, username: &str, password: &str) -> Result<()> {
        let url = format!("{}/auth/token", self.base_url);
        let body = json!({
            "username": username,
            "password": password,
        });

        let resp = self
            .client
            .post(&url)
            .json(&body)
            .send()
            .await
            .context("Failed to POST /auth/token")?;

        let status = resp.status();
        let payload: Value = resp
            .json()
            .await
            .context("Failed to parse authentication response")?;

        if !status.is_success() {
            anyhow::bail!(
                "Authentication failed (HTTP {}): {}",
                status,
                payload.get("error").unwrap_or(&Value::Null)
            );
        }

        let token = payload
            .get("token")
            .and_then(Value::as_str)
            .context("Authentication response missing 'token' field")?
            .to_string();

        *self.auth_token.write().await = Some(token);
        tracing::info!("REST transport authenticated successfully");
        Ok(())
    }

    /// Build a request with the Bearer token attached (if available).
    fn build_request(&self, method: reqwest::Method, path: &str) -> reqwest::RequestBuilder {
        let url = format!("{}{}", self.base_url, path);
        // We cannot await inside a non-async fn, so we use try_read to
        // opportunistically attach the token.  The token changes very
        // rarely (only on authenticate()) so this is safe.
        let builder = self.client.request(method, &url);
        if let Ok(guard) = self.auth_token.try_read()
            && let Some(ref token) = *guard
        {
            return builder.bearer_auth(token);
        }
        builder
    }
}

#[async_trait::async_trait]
impl NornicTransport for RestTransport {
    async fn health_check(&self) -> Result<bool> {
        let resp = self
            .build_request(reqwest::Method::GET, "/health")
            .send()
            .await;

        match resp {
            Ok(r) => Ok(r.status().is_success()),
            Err(e) => {
                tracing::warn!("NornicDB health check failed: {}", e);
                Ok(false)
            }
        }
    }

    async fn execute_cypher(&self, query: &str, params: Value) -> Result<Vec<Value>> {
        let path = format!("/db/{}/tx/commit", self.database);
        let body = json!({
            "statements": [{
                "statement": query,
                "parameters": params,
            }]
        });

        let resp = self
            .build_request(reqwest::Method::POST, &path)
            .json(&body)
            .send()
            .await
            .context("Failed to execute Cypher query via REST")?;

        let status = resp.status();
        let payload: Value = resp
            .json()
            .await
            .context("Failed to parse Cypher response")?;

        // Check for errors in the response envelope.
        if let Some(errors) = payload.get("errors").and_then(Value::as_array)
            && !errors.is_empty()
        {
            anyhow::bail!("Cypher error(s): {}", serde_json::to_string(errors)?);
        }

        if !status.is_success() {
            anyhow::bail!("Cypher query failed (HTTP {}): {}", status, payload);
        }

        // Extract rows: results[0].data[].row
        let rows = payload
            .get("results")
            .and_then(|r| r.get(0))
            .and_then(|r| r.get("data"))
            .and_then(Value::as_array)
            .map(|data| {
                data.iter()
                    .filter_map(|entry| entry.get("row").cloned())
                    .collect::<Vec<Value>>()
            })
            .unwrap_or_default();

        Ok(rows)
    }

    async fn hybrid_search(
        &self,
        query_text: &str,
        query_vector: Vec<f32>,
        limit: usize,
        min_score: f32,
        node_label: &str,
        filters: Value,
    ) -> Result<Vec<Value>> {
        let body = json!({
            "query": query_text,
            "embedding": query_vector,
            "limit": limit,
            "min_score": min_score,
            "labels": [node_label],
            "filters": filters,
        });

        let resp = self
            .build_request(reqwest::Method::POST, "/nornicdb/search")
            .json(&body)
            .send()
            .await
            .context("Failed to execute hybrid search via REST")?;

        let status = resp.status();
        let payload: Value = resp
            .json()
            .await
            .context("Failed to parse hybrid search response")?;

        if !status.is_success() {
            anyhow::bail!("Hybrid search failed (HTTP {}): {}", status, payload);
        }

        Self::map_search_results(&payload)
    }

    async fn vector_search(
        &self,
        query_vector: Vec<f32>,
        limit: usize,
        min_score: f32,
        node_label: &str,
        filters: Value,
    ) -> Result<Vec<Value>> {
        let body = json!({
            "vector": query_vector,
            "limit": limit,
            "min_score": min_score,
            "labels": [node_label],
            "filters": filters,
        });

        let resp = self
            .build_request(reqwest::Method::POST, "/nornicdb/similar")
            .json(&body)
            .send()
            .await
            .context("Failed to execute vector search via REST")?;

        let status = resp.status();
        let payload: Value = resp
            .json()
            .await
            .context("Failed to parse vector search response")?;

        if !status.is_success() {
            anyhow::bail!("Vector search failed (HTTP {}): {}", status, payload);
        }

        Self::map_search_results(&payload)
    }

    async fn store_nodes(&self, nodes: Vec<Value>, node_label: &str) -> Result<usize> {
        const BATCH_SIZE: usize = 500;
        let mut total = 0usize;

        for chunk in nodes.chunks(BATCH_SIZE) {
            let batch: Vec<Value> = chunk.to_vec();
            let cypher = format!(
                "UNWIND $batch AS item \
                 MERGE (n:{node_label} {{file_path: item.file_path, start_line: item.start_line}}) \
                 SET n += item"
            );
            let params = json!({ "batch": batch });
            self.execute_cypher(&cypher, params)
                .await
                .context("Failed to store node batch via REST")?;
            total += chunk.len();
        }

        tracing::debug!("Stored {} nodes (label: {})", total, node_label);
        Ok(total)
    }

    async fn delete_nodes(&self, node_label: &str, property: &str, value: &str) -> Result<usize> {
        let cypher = format!(
            "MATCH (n:{node_label} {{{property}: $value}}) \
             WITH n, count(n) AS cnt \
             DETACH DELETE n \
             RETURN cnt"
        );
        let params = json!({ "value": value });
        let rows = self
            .execute_cypher(&cypher, params)
            .await
            .context("Failed to delete nodes via REST")?;

        let count = rows
            .first()
            .and_then(|r| r.get(0))
            .and_then(Value::as_u64)
            .unwrap_or(0) as usize;

        tracing::debug!(
            "Deleted {} nodes (label: {}, {}: {})",
            count,
            node_label,
            property,
            value
        );
        Ok(count)
    }

    async fn count_nodes(&self, node_label: &str, property: &str, value: &str) -> Result<usize> {
        let cypher =
            format!("MATCH (n:{node_label}) WHERE n.{property} = $value RETURN count(n) AS cnt");
        let params = json!({ "value": value });
        let rows = self
            .execute_cypher(&cypher, params)
            .await
            .context("Failed to count nodes via REST")?;

        let count = rows
            .first()
            .and_then(|r| r.get(0))
            .and_then(Value::as_u64)
            .unwrap_or(0) as usize;

        Ok(count)
    }

    async fn distinct_property(
        &self,
        node_label: &str,
        property: &str,
        filter_prop: &str,
        filter_val: &str,
    ) -> Result<Vec<String>> {
        let cypher = format!(
            "MATCH (n:{node_label}) WHERE n.{filter_prop} = $filter_val \
             RETURN DISTINCT n.{property} AS val"
        );
        let params = json!({ "filter_val": filter_val });
        let rows = self
            .execute_cypher(&cypher, params)
            .await
            .context("Failed to query distinct property via REST")?;

        let values = rows
            .iter()
            .filter_map(|r| r.get(0).and_then(Value::as_str).map(String::from))
            .collect();

        Ok(values)
    }

    fn transport_name(&self) -> &'static str {
        "REST"
    }
}

impl RestTransport {
    /// Map the server-side search response into a normalised `Vec<Value>`.
    fn map_search_results(payload: &Value) -> Result<Vec<Value>> {
        let results = payload
            .get("results")
            .and_then(Value::as_array)
            .cloned()
            .unwrap_or_default();

        let mapped: Vec<Value> = results
            .into_iter()
            .map(|item| {
                json!({
                    "file_path":     item.get("file_path").cloned().unwrap_or(Value::Null),
                    "content":       item.get("content").cloned().unwrap_or(Value::Null),
                    "score":         item.get("score").cloned().unwrap_or(Value::Null),
                    "vector_score":  item.get("vector_score").cloned().unwrap_or(Value::Null),
                    "keyword_score": item.get("keyword_score").cloned().unwrap_or(Value::Null),
                    "start_line":    item.get("start_line").cloned().unwrap_or(Value::Null),
                    "end_line":      item.get("end_line").cloned().unwrap_or(Value::Null),
                    "language":      item.get("language").cloned().unwrap_or(Value::Null),
                    "project":       item.get("project").cloned().unwrap_or(Value::Null),
                    "root_path":     item.get("root_path").cloned().unwrap_or(Value::Null),
                    "indexed_at":    item.get("indexed_at").cloned().unwrap_or(Value::Null),
                })
            })
            .collect();

        Ok(mapped)
    }
}

// ════════════════════════════════════════════════════════════════════════
//  Bolt Transport  (requires `nornicdb-bolt` feature)
// ════════════════════════════════════════════════════════════════════════

#[cfg(feature = "nornicdb-bolt")]
mod bolt {
    use super::*;
    use neo4rs::Graph;

    /// Bolt (binary) transport using the `neo4rs` driver.
    ///
    /// Connects to a Neo4j-compatible server over the Bolt protocol,
    /// which is more efficient than REST for high-throughput workloads.
    pub(crate) struct BoltTransport {
        graph: Graph,
    }

    impl BoltTransport {
        /// Open a Bolt connection.
        pub(crate) async fn new(url: &str, username: &str, password: &str) -> Result<Self> {
            tracing::info!("Connecting to NornicDB via Bolt at {}", url);
            let graph = Graph::new(url, username, password)
                .context("Failed to connect to NornicDB via Bolt")?;
            Ok(Self { graph })
        }

        /// Convert a `serde_json::Value` object into a `neo4rs::Query`
        /// with all parameters bound.
        fn bind_params(query_str: &str, params: &Value) -> neo4rs::Query {
            let mut q = neo4rs::query(query_str);
            if let Some(obj) = params.as_object() {
                for (key, val) in obj {
                    match val {
                        Value::String(s) => q = q.param(key.as_str(), s.clone()),
                        Value::Number(n) if n.is_i64() => {
                            q = q.param(key.as_str(), n.as_i64().unwrap());
                        }
                        Value::Number(n) if n.is_f64() => {
                            q = q.param(key.as_str(), n.as_f64().unwrap());
                        }
                        Value::Bool(b) => q = q.param(key.as_str(), *b),
                        other => {
                            // Fall back to stringified JSON.
                            q = q.param(key.as_str(), other.to_string());
                        }
                    }
                }
            }
            q
        }

        /// Execute a query and collect all result rows into `Vec<Value>`.
        async fn run_query(&self, query_str: &str, params: &Value) -> Result<Vec<Value>> {
            let q = Self::bind_params(query_str, params);
            let mut result = self
                .graph
                .execute(q)
                .await
                .context("Bolt query execution failed")?;

            let mut rows: Vec<Value> = Vec::new();
            while let Some(row) = result.next().await? {
                // Attempt to pull known column names.  neo4rs rows are
                // positional; we serialise each column as a JSON value.
                let mut row_values: Vec<Value> = Vec::new();
                // neo4rs exposes columns via `row.get::<T>(name)`.
                // We try common column names and fall back to index-based
                // extraction. Since we control the queries, we know the
                // expected column names.
                if let Ok(val) = row.get::<String>("cnt") {
                    row_values.push(Value::String(val));
                } else if let Ok(val) = row.get::<i64>("cnt") {
                    row_values.push(json!(val));
                } else if let Ok(val) = row.get::<String>("val") {
                    row_values.push(Value::String(val));
                } else {
                    // Generic fallback: try to get the first column as a string.
                    if let Ok(val) = row.get::<String>("n") {
                        row_values.push(Value::String(val));
                    }
                }

                if !row_values.is_empty() {
                    rows.push(Value::Array(row_values));
                }
            }

            Ok(rows)
        }
    }

    #[async_trait::async_trait]
    impl NornicTransport for BoltTransport {
        async fn health_check(&self) -> Result<bool> {
            let q = neo4rs::query("RETURN 1 AS ping");
            match self.graph.execute(q).await {
                Ok(_) => Ok(true),
                Err(e) => {
                    tracing::warn!("Bolt health check failed: {}", e);
                    Ok(false)
                }
            }
        }

        async fn execute_cypher(&self, query: &str, params: Value) -> Result<Vec<Value>> {
            self.run_query(query, &params).await
        }

        async fn hybrid_search(
            &self,
            _query_text: &str,
            query_vector: Vec<f32>,
            limit: usize,
            min_score: f32,
            node_label: &str,
            filters: Value,
        ) -> Result<Vec<Value>> {
            // Bolt does not expose a server-side BM25 endpoint.
            // Fall back to pure vector search.
            tracing::debug!(
                "Bolt transport: hybrid_search delegates to vector_search (no BM25 via Bolt)"
            );
            self.vector_search(query_vector, limit, min_score, node_label, filters)
                .await
        }

        async fn vector_search(
            &self,
            query_vector: Vec<f32>,
            limit: usize,
            min_score: f32,
            _node_label: &str,
            _filters: Value,
        ) -> Result<Vec<Value>> {
            let cypher = "CALL db.index.vector.queryNodes($index_name, $limit, $query_vector) \
                          YIELD node, score \
                          WHERE score >= $min_score \
                          RETURN node, score";

            let params = json!({
                "index_name": "code_embedding_index",
                "limit": limit,
                "query_vector": query_vector,
                "min_score": min_score,
            });

            let rows = self.run_query(cypher, &params).await?;

            // Map Bolt rows into the canonical search-result shape.
            let results: Vec<Value> = rows
                .into_iter()
                .map(|row| {
                    // row is expected to be [node, score]
                    let node = row.get(0).cloned().unwrap_or(Value::Null);
                    let score = row.get(1).cloned().unwrap_or(Value::Null);
                    json!({
                        "file_path":     node.get("file_path").cloned().unwrap_or(Value::Null),
                        "content":       node.get("content").cloned().unwrap_or(Value::Null),
                        "score":         score,
                        "vector_score":  score,
                        "keyword_score": Value::Null,
                        "start_line":    node.get("start_line").cloned().unwrap_or(Value::Null),
                        "end_line":      node.get("end_line").cloned().unwrap_or(Value::Null),
                        "language":      node.get("language").cloned().unwrap_or(Value::Null),
                        "project":       node.get("project").cloned().unwrap_or(Value::Null),
                        "root_path":     node.get("root_path").cloned().unwrap_or(Value::Null),
                        "indexed_at":    node.get("indexed_at").cloned().unwrap_or(Value::Null),
                    })
                })
                .collect();

            Ok(results)
        }

        async fn store_nodes(&self, nodes: Vec<Value>, node_label: &str) -> Result<usize> {
            const BATCH_SIZE: usize = 500;
            let mut total = 0usize;

            for chunk in nodes.chunks(BATCH_SIZE) {
                let batch: Vec<Value> = chunk.to_vec();
                let cypher = format!(
                    "UNWIND $batch AS item \
                     MERGE (n:{node_label} {{file_path: item.file_path, start_line: item.start_line}}) \
                     SET n += item"
                );
                let params = json!({ "batch": batch });
                self.run_query(&cypher, &params)
                    .await
                    .context("Failed to store node batch via Bolt")?;
                total += chunk.len();
            }

            tracing::debug!("Bolt: stored {} nodes (label: {})", total, node_label);
            Ok(total)
        }

        async fn delete_nodes(
            &self,
            node_label: &str,
            property: &str,
            value: &str,
        ) -> Result<usize> {
            let cypher = format!(
                "MATCH (n:{node_label} {{{property}: $value}}) \
                 WITH n, count(n) AS cnt \
                 DETACH DELETE n \
                 RETURN cnt"
            );
            let params = json!({ "value": value });
            let rows = self
                .run_query(&cypher, &params)
                .await
                .context("Failed to delete nodes via Bolt")?;

            let count = rows
                .first()
                .and_then(|r| r.get(0))
                .and_then(Value::as_u64)
                .unwrap_or(0) as usize;

            Ok(count)
        }

        async fn count_nodes(
            &self,
            node_label: &str,
            property: &str,
            value: &str,
        ) -> Result<usize> {
            let cypher = format!(
                "MATCH (n:{node_label}) WHERE n.{property} = $value RETURN count(n) AS cnt"
            );
            let params = json!({ "value": value });
            let rows = self
                .run_query(&cypher, &params)
                .await
                .context("Failed to count nodes via Bolt")?;

            let count = rows
                .first()
                .and_then(|r| r.get(0))
                .and_then(Value::as_u64)
                .unwrap_or(0) as usize;

            Ok(count)
        }

        async fn distinct_property(
            &self,
            node_label: &str,
            property: &str,
            filter_prop: &str,
            filter_val: &str,
        ) -> Result<Vec<String>> {
            let cypher = format!(
                "MATCH (n:{node_label}) WHERE n.{filter_prop} = $filter_val \
                 RETURN DISTINCT n.{property} AS val"
            );
            let params = json!({ "filter_val": filter_val });
            let rows = self
                .run_query(&cypher, &params)
                .await
                .context("Failed to query distinct property via Bolt")?;

            let values = rows
                .iter()
                .filter_map(|r| r.get(0).and_then(Value::as_str).map(String::from))
                .collect();

            Ok(values)
        }

        fn transport_name(&self) -> &'static str {
            "Bolt"
        }
    }
}

#[cfg(feature = "nornicdb-bolt")]
pub(crate) use bolt::BoltTransport;

// ════════════════════════════════════════════════════════════════════════
//  gRPC Transport  (requires `nornicdb-grpc` feature)
// ════════════════════════════════════════════════════════════════════════

#[cfg(feature = "nornicdb-grpc")]
mod grpc {
    use super::*;
    use qdrant_client::qdrant::{
        Condition, CountPointsBuilder, DeletePointsBuilder, Filter, PointStruct,
        ScrollPointsBuilder, SearchPointsBuilder, UpsertPointsBuilder,
    };
    use qdrant_client::{Payload, Qdrant};
    use std::collections::HashSet;

    const COLLECTION_NAME: &str = "code_embeddings";

    /// gRPC transport targeting a Qdrant-compatible endpoint.
    ///
    /// Cypher operations are **not** supported over gRPC; only vector
    /// operations are available.
    pub(crate) struct GrpcTransport {
        client: Qdrant,
    }

    impl GrpcTransport {
        /// Connect to a Qdrant-compatible gRPC endpoint.
        pub(crate) async fn new(url: &str) -> Result<Self> {
            tracing::info!("Connecting to NornicDB via gRPC at {}", url);
            let client = Qdrant::from_url(url)
                .build()
                .context("Failed to build gRPC client for NornicDB")?;
            Ok(Self { client })
        }

        /// Convert a scored Qdrant point into the canonical search-result
        /// JSON shape.
        fn scored_point_to_value(point: &qdrant_client::qdrant::ScoredPoint) -> Value {
            let p = &point.payload;
            let get_str = |key: &str| -> Value {
                p.get(key)
                    .and_then(|v| v.as_str())
                    .map(|s| Value::String(s.to_string()))
                    .unwrap_or(Value::Null)
            };
            let get_int = |key: &str| -> Value {
                p.get(key)
                    .and_then(|v| v.as_integer())
                    .map(|n| json!(n))
                    .unwrap_or(Value::Null)
            };

            json!({
                "file_path":     get_str("file_path"),
                "content":       get_str("content"),
                "score":         point.score,
                "vector_score":  point.score,
                "keyword_score": Value::Null,
                "start_line":    get_int("start_line"),
                "end_line":      get_int("end_line"),
                "language":      get_str("language"),
                "project":       get_str("project"),
                "root_path":     get_str("root_path"),
                "indexed_at":    get_int("indexed_at"),
            })
        }

        /// Build a Qdrant `Filter` from a serde_json filters object.
        ///
        /// Supported keys: `project`, `root_path`, `file_path`.  All are
        /// treated as exact-match string conditions.
        fn build_filter(filters: &Value) -> Option<Filter> {
            let obj = filters.as_object()?;
            let mut conditions: Vec<Condition> = Vec::new();

            for key in &["project", "root_path", "file_path"] {
                if let Some(val) = obj.get(*key).and_then(Value::as_str) {
                    conditions.push(Condition::matches(*key, val.to_string()));
                }
            }

            if conditions.is_empty() {
                None
            } else {
                Some(Filter::must(conditions))
            }
        }
    }

    #[async_trait::async_trait]
    impl NornicTransport for GrpcTransport {
        async fn health_check(&self) -> Result<bool> {
            match self.client.list_collections().await {
                Ok(_) => Ok(true),
                Err(e) => {
                    tracing::warn!("gRPC health check failed: {}", e);
                    Ok(false)
                }
            }
        }

        async fn execute_cypher(&self, _query: &str, _params: Value) -> Result<Vec<Value>> {
            Err(anyhow::anyhow!(
                "Cypher queries are not supported over gRPC. Use REST or Bolt transport."
            ))
        }

        async fn hybrid_search(
            &self,
            _query_text: &str,
            query_vector: Vec<f32>,
            limit: usize,
            min_score: f32,
            node_label: &str,
            filters: Value,
        ) -> Result<Vec<Value>> {
            tracing::debug!(
                "gRPC transport: hybrid_search delegates to vector_search (no BM25 via gRPC)"
            );
            self.vector_search(query_vector, limit, min_score, node_label, filters)
                .await
        }

        async fn vector_search(
            &self,
            query_vector: Vec<f32>,
            limit: usize,
            min_score: f32,
            _node_label: &str,
            filters: Value,
        ) -> Result<Vec<Value>> {
            let mut builder = SearchPointsBuilder::new(COLLECTION_NAME, query_vector, limit as u64)
                .score_threshold(min_score)
                .with_payload(true);

            if let Some(filter) = Self::build_filter(&filters) {
                builder = builder.filter(filter);
            }

            let search_result = self
                .client
                .search_points(builder)
                .await
                .context("gRPC vector search failed")?;

            let results: Vec<Value> = search_result
                .result
                .iter()
                .map(Self::scored_point_to_value)
                .collect();

            Ok(results)
        }

        async fn store_nodes(&self, nodes: Vec<Value>, _node_label: &str) -> Result<usize> {
            if nodes.is_empty() {
                return Ok(0);
            }

            let count = nodes.len();
            let points: Vec<PointStruct> = nodes
                .into_iter()
                .enumerate()
                .filter_map(|(idx, node)| {
                    // Extract the embedding vector; skip nodes without one.
                    let embedding: Vec<f32> =
                        node.get("embedding").and_then(Value::as_array).map(|arr| {
                            arr.iter()
                                .filter_map(|v| v.as_f64().map(|f| f as f32))
                                .collect()
                        })?;

                    let payload: Payload = node
                        .clone()
                        .try_into()
                        .expect("JSON object always converts to Payload");

                    Some(PointStruct::new(idx as u64, embedding, payload))
                })
                .collect();

            let written = points.len();
            self.client
                .upsert_points(UpsertPointsBuilder::new(COLLECTION_NAME, points))
                .await
                .context("gRPC upsert_points failed")?;

            tracing::debug!("gRPC: stored {}/{} nodes", written, count);
            Ok(written)
        }

        async fn delete_nodes(
            &self,
            _node_label: &str,
            property: &str,
            value: &str,
        ) -> Result<usize> {
            let filter = Filter::must([Condition::matches(property, value.to_string())]);

            self.client
                .delete_points(DeletePointsBuilder::new(COLLECTION_NAME).points(filter))
                .await
                .context("gRPC delete_points failed")?;

            // Qdrant does not return a deleted count directly.
            tracing::debug!("gRPC: deleted nodes where {} = {}", property, value);
            Ok(0)
        }

        async fn count_nodes(
            &self,
            _node_label: &str,
            property: &str,
            value: &str,
        ) -> Result<usize> {
            let filter = Filter::must([Condition::matches(property, value.to_string())]);

            let result = self
                .client
                .count(CountPointsBuilder::new(COLLECTION_NAME).filter(filter))
                .await
                .context("gRPC count_points failed")?;

            let count = result.result.map(|r| r.count).unwrap_or(0) as usize;
            Ok(count)
        }

        async fn distinct_property(
            &self,
            _node_label: &str,
            property: &str,
            filter_prop: &str,
            filter_val: &str,
        ) -> Result<Vec<String>> {
            let filter = Filter::must([Condition::matches(filter_prop, filter_val.to_string())]);

            let mut distinct: HashSet<String> = HashSet::new();
            let mut offset: Option<qdrant_client::qdrant::PointId> = None;

            loop {
                let mut builder = ScrollPointsBuilder::new(COLLECTION_NAME)
                    .filter(filter.clone())
                    .with_payload(true)
                    .limit(500);

                if let Some(ref point_id) = offset {
                    builder = builder.offset(point_id.clone());
                }

                let scroll_result = self
                    .client
                    .scroll(builder)
                    .await
                    .context("gRPC scroll failed during distinct_property")?;

                if scroll_result.result.is_empty() {
                    break;
                }

                for point in &scroll_result.result {
                    if let Some(val) = point.payload.get(property).and_then(|v| v.as_str()) {
                        distinct.insert(val.to_string());
                    }
                }

                offset = scroll_result.next_page_offset;
                if offset.is_none() {
                    break;
                }
            }

            Ok(distinct.into_iter().collect())
        }

        fn transport_name(&self) -> &'static str {
            "gRPC"
        }
    }
}

#[cfg(feature = "nornicdb-grpc")]
pub(crate) use grpc::GrpcTransport;