codenexus 0.3.3

A queryable code knowledge graph tool built on LadybugDB and tree-sitter
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
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
// Copyright (c) 2026 Kirky.X. All rights reserved.
// SPDX-License-Identifier: MIT

//! Embedding service client (SubTask 16.1, H10/D7).
//!
//! Defines the [`EmbedClient`] trait and three implementations:
//! - [`OpenAIEmbedClient`]: calls an OpenAI-compatible HTTP embedding API via
//!   [`reqwest::blocking`]. The API key is read from the environment and never
//!   persisted (TRD ยง6.1). Used when [`EmbeddingConfig::endpoint`] is `Some`.
//! - [`LocalEmbedClient`] (H10/D7): runs `arctic-embed-xs` inference locally
//!   via `ort` (ONNX Runtime). Works fully offline. Used when
//!   [`EmbeddingConfig::endpoint`] is `None`.
//! - [`MockEmbedClient`]: returns deterministic vectors for testing without
//!   network access.
//!
//! # OpenAI-compatible API contract
//!
//! `POST {endpoint}/embeddings`
//! ```json
//! {"model": "text-embedding-3-small", "input": ["text1", "text2"]}
//! ```
//! Response:
//! ```json
//! {"data": [{"embedding": [0.1, ...]}, {"embedding": [0.2, ...]}]}
//! ```

use std::sync::Mutex;

#[cfg(feature = "cache")]
use std::sync::Arc;

use serde::{Deserialize, Serialize};

use super::{EmbedError, EmbeddingConfig, Result, EMBEDDING_DIM, EMBED_MODEL_PATH_ENV};

#[cfg(feature = "cache")]
use crate::cache::CacheStore;

/// Trait for embedding text into dense vectors.
///
/// Implementations may call a remote HTTP service ([`OpenAIEmbedClient`]) or
/// return pre-computed/mock vectors ([`MockEmbedClient`]). The trait enables
/// dependency injection so callers can test without network access.
pub trait EmbedClient: Send + Sync {
    /// Embeds a batch of texts, returning one vector per input text.
    ///
    /// Each returned vector must have length [`EMBEDDING_DIM`].
    ///
    /// # Errors
    ///
    /// Returns [`EmbedError::Unavailable`] if the service cannot be reached,
    /// [`EmbedError::MissingApiKey`] if authentication is required but missing,
    /// or [`EmbedError::Api`] for non-2xx responses.
    fn embed(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>>;
}

// --- OpenAI-compatible request/response types ---

#[derive(Serialize)]
struct EmbeddingRequest<'a> {
    model: &'a str,
    input: Vec<&'a str>,
}

#[derive(Deserialize)]
struct EmbeddingResponse {
    data: Vec<EmbeddingData>,
}

#[derive(Deserialize)]
struct EmbeddingData {
    embedding: Vec<f32>,
}

/// HTTP client for an OpenAI-compatible embedding API.
///
/// Uses [`reqwest::blocking`] so it can be called from synchronous code. The
/// API key is held in memory only and never written to disk (TRD ยง6.1).
///
/// Only used when [`EmbeddingConfig::endpoint`] is `Some` (remote HTTP mode).
/// For local offline inference, see [`LocalEmbedClient`] (H10/D7).
pub struct OpenAIEmbedClient {
    config: EmbeddingConfig,
    http: reqwest::blocking::Client,
}

impl OpenAIEmbedClient {
    /// Creates a new client from the given [`EmbeddingConfig`].
    ///
    /// The config must be in remote HTTP mode (`endpoint = Some(url)`) and
    /// have an API key set.
    ///
    /// # Errors
    ///
    /// Returns [`EmbedError::Unavailable`] if `endpoint` is `None` (local mode
    /// โ€” use [`LocalEmbedClient`] instead).
    /// Returns [`EmbedError::MissingApiKey`] if no API key is configured.
    pub fn new(config: EmbeddingConfig) -> Result<Self> {
        if config.is_local() {
            return Err(EmbedError::Unavailable(
                "OpenAIEmbedClient requires endpoint=Some(url); for local mode use LocalEmbedClient"
                    .to_string(),
            ));
        }
        if !config.has_api_key() {
            return Err(EmbedError::MissingApiKey);
        }
        let http = reqwest::blocking::Client::builder()
            .timeout(std::time::Duration::from_secs(30))
            .build()?;
        Ok(Self { config, http })
    }

    /// Creates a client from environment variables (convenience).
    ///
    /// Requires `CODENEXUS_EMBED_ENDPOINT` to be set (remote HTTP mode).
    ///
    /// # Errors
    ///
    /// Returns [`EmbedError::Unavailable`] if endpoint is not set.
    /// Returns [`EmbedError::MissingApiKey`] if neither `CODENEXUS_EMBED_API_KEY`
    /// nor `OPENAI_API_KEY` is set.
    pub fn from_env() -> Result<Self> {
        Self::new(EmbeddingConfig::from_env())
    }

    /// Returns the configured endpoint URL.
    ///
    /// # Panics
    ///
    /// Panics if `endpoint` is `None` โ€” but [`OpenAIEmbedClient::new`] already
    /// rejects local-mode configs, so this should never occur for a
    /// successfully-constructed client.
    #[must_use]
    pub fn endpoint(&self) -> &str {
        self.config
            .endpoint
            .as_deref()
            .expect("OpenAIEmbedClient endpoint is Some (enforced by new())")
    }

    /// Returns the configured model name.
    #[must_use]
    pub fn model(&self) -> &str {
        &self.config.model
    }
}

impl EmbedClient for OpenAIEmbedClient {
    fn embed(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>> {
        let api_key = self
            .config
            .api_key
            .as_ref()
            .ok_or(EmbedError::MissingApiKey)?;

        // endpoint is guaranteed Some by new(), but use as_deref().unwrap_or
        // for defensive programming (avoids panic if config was mutated).
        let endpoint = self.config.endpoint.as_deref().ok_or_else(|| {
            EmbedError::Unavailable("endpoint is None in remote mode".to_string())
        })?;
        let url = format!("{endpoint}/embeddings");
        let body = EmbeddingRequest {
            model: &self.config.model,
            input: texts.to_vec(),
        };

        let resp = self
            .http
            .post(&url)
            .bearer_auth(api_key)
            .json(&body)
            .send()
            .map_err(|e| EmbedError::Unavailable(e.to_string()))?;

        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().unwrap_or_default();
            return Err(EmbedError::Api {
                status: status.as_u16(),
                body,
            });
        }

        let parsed: EmbeddingResponse = resp.json()?;
        let embeddings: Vec<Vec<f32>> = parsed.data.into_iter().map(|d| d.embedding).collect();

        // Validate dimensions.
        for emb in &embeddings {
            if emb.len() != EMBEDDING_DIM {
                return Err(EmbedError::DimensionMismatch {
                    expected: EMBEDDING_DIM,
                    actual: emb.len(),
                });
            }
        }

        Ok(embeddings)
    }
}

impl std::fmt::Debug for OpenAIEmbedClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OpenAIEmbedClient")
            .field("endpoint", &self.config.endpoint)
            .field("model", &self.config.model)
            .field("api_key", &"<redacted>")
            .finish()
    }
}

// ---------------------------------------------------------------------------
// LocalEmbedClient (H10/D7)
// ---------------------------------------------------------------------------

/// Local ONNX-based embedding client (H10/D7).
///
/// Runs `arctic-embed-xs` inference locally using [`ort`] (ONNX Runtime) and
/// HuggingFace [`tokenizers`]. Requires no network access โ€” the model and
/// tokenizer files must be present on disk.
///
/// # Thread safety
///
/// `ort::session::Session::run` requires `&mut self`, so the session is
/// wrapped in a [`Mutex`]. [`tokenizers::Tokenizer::encode`] takes `&self`
/// and needs no wrapping. `LocalEmbedClient` is `Send + Sync` via the
/// `Mutex<Session>` (Session is `Send`).
///
/// # Inference pipeline
///
/// 1. Tokenize input text โ†’ `input_ids`, `attention_mask`, `token_type_ids`
/// 2. Create `ndarray::Array2<i64>` tensors (shape `[1, seq_len]`)
/// 3. Run ONNX inference via `ort::inputs!` + `Session::run`
/// 4. Extract `last_hidden_state` tensor (shape `[1, seq_len, hidden_dim]`)
/// 5. Mean-pool over `seq_len` using `attention_mask` as weights
/// 6. L2-normalize the pooled vector
///
/// # Errors
///
/// [`LocalEmbedClient::new`] returns [`EmbedError::Unavailable`] if the model
/// or tokenizer file is missing or cannot be loaded.
pub struct LocalEmbedClient {
    /// ONNX Runtime session (requires `&mut self` for `run`, hence `Mutex`).
    session: Mutex<ort::session::Session>,
    /// HuggingFace tokenizer (BERT WordPiece for arctic-embed-xs).
    tokenizer: tokenizers::Tokenizer,
    /// Model name (for Debug output).
    model: String,
}

impl LocalEmbedClient {
    /// Creates a new local embedding client from the given config.
    ///
    /// Loads the ONNX model from [`EmbeddingConfig::resolved_model_path`] and
    /// the tokenizer from [`EmbeddingConfig::resolved_tokenizer_path`].
    ///
    /// # Errors
    ///
    /// Returns [`EmbedError::Unavailable`] if:
    /// - The model file does not exist (with guidance on how to fix).
    /// - The tokenizer file does not exist.
    /// - The ONNX session cannot be created (corrupt model, ort init failure).
    /// - The tokenizer cannot be loaded (corrupt tokenizer.json).
    pub fn new(config: &EmbeddingConfig) -> Result<Self> {
        let model_path = config.resolved_model_path();
        let tokenizer_path = config.resolved_tokenizer_path();

        if !model_path.exists() {
            return Err(EmbedError::Unavailable(format!(
                "local embedding model not found at {}. \
                 Place the arctic-embed-xs ONNX model at this path \
                 (or set the {EMBED_MODEL_PATH_ENV} env var to a custom location).",
                model_path.display(),
            )));
        }

        if !tokenizer_path.exists() {
            return Err(EmbedError::Unavailable(format!(
                "tokenizer not found at {}. \
                 Place the HuggingFace tokenizer.json co-located with the model.",
                tokenizer_path.display(),
            )));
        }

        let session = ort::session::Session::builder()
            .map_err(|e| EmbedError::Unavailable(format!("ort session builder failed: {e}")))?
            .with_intra_threads(1)
            .map_err(|e| EmbedError::Unavailable(format!("ort thread config failed: {e}")))?
            .commit_from_file(&model_path)
            .map_err(|e| EmbedError::Unavailable(format!("ort model load failed: {e}")))?;

        let tokenizer = tokenizers::Tokenizer::from_file(&tokenizer_path)
            .map_err(|e| EmbedError::Unavailable(format!("tokenizer load failed: {e}")))?;

        Ok(Self {
            session: Mutex::new(session),
            tokenizer,
            model: config.model.clone(),
        })
    }

    /// Returns the model name.
    #[must_use]
    pub fn model(&self) -> &str {
        &self.model
    }

    /// Mean-pools the last hidden state using the attention mask.
    ///
    /// `hidden` is flat row-major data for shape `[1, seq_len, hidden_dim]`.
    /// Returns a vector of length `hidden_dim` where each element is the mean
    /// of the non-masked token embeddings along the sequence dimension.
    fn mean_pool(
        hidden: &[f32],
        attention_mask: &[u32],
        seq_len: usize,
        hidden_dim: usize,
    ) -> Vec<f32> {
        let mut pooled = vec![0.0f32; hidden_dim];
        let mut count = 0u32;
        for (i, &mask_val) in attention_mask.iter().enumerate().take(seq_len) {
            if mask_val > 0 {
                let base = i * hidden_dim;
                let end = base + hidden_dim;
                for (p, &h) in pooled.iter_mut().zip(&hidden[base..end]) {
                    *p += h;
                }
                count += 1;
            }
        }
        if count > 0 {
            for v in &mut pooled {
                *v /= count as f32;
            }
        }
        pooled
    }

    /// L2-normalizes a vector in place.
    fn l2_normalize(vec: &mut [f32]) {
        let norm: f32 = vec.iter().map(|v| v * v).sum::<f32>().sqrt();
        if norm > 0.0 {
            for v in vec.iter_mut() {
                *v /= norm;
            }
        }
    }
}

impl EmbedClient for LocalEmbedClient {
    fn embed(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>> {
        let mut results = Vec::with_capacity(texts.len());
        for text in texts {
            let encoding = self
                .tokenizer
                .encode(*text, true)
                .map_err(|e| EmbedError::Unavailable(format!("tokenization failed: {e}")))?;

            let input_ids = encoding.get_ids();
            let attention_mask = encoding.get_attention_mask();
            let token_type_ids = encoding.get_type_ids();
            let seq_len = input_ids.len();

            if seq_len == 0 {
                return Err(EmbedError::Unavailable(
                    "tokenization produced empty sequence".to_string(),
                ));
            }

            // Build input tensors (shape: [1, seq_len], dtype: i64).
            let input_ids_arr = ndarray::Array2::from_shape_vec(
                (1, seq_len),
                input_ids.iter().map(|&v| v as i64).collect(),
            )
            .map_err(|e| EmbedError::Unavailable(format!("input_ids ndarray: {e}")))?;

            let attention_mask_arr = ndarray::Array2::from_shape_vec(
                (1, seq_len),
                attention_mask.iter().map(|&v| v as i64).collect(),
            )
            .map_err(|e| EmbedError::Unavailable(format!("attention_mask ndarray: {e}")))?;

            // arctic-embed-xs (BERT-style) uses token_type_ids; reuse the
            // tokenizer-provided ones rather than a zero vector to stay
            // faithful to the model's training distribution.
            let token_type_ids_arr = ndarray::Array2::from_shape_vec(
                (1, seq_len),
                token_type_ids.iter().map(|&v| v as i64).collect(),
            )
            .map_err(|e| EmbedError::Unavailable(format!("token_type_ids ndarray: {e}")))?;

            // ort 2.0.0-rc.12 requires Value objects (not raw ndarrays) in
            // `ort::inputs!`. Convert each array to a `Value<Tensor>` first.
            let input_ids_value = ort::value::Value::from_array(input_ids_arr)
                .map_err(|e| EmbedError::Unavailable(format!("input_ids value: {e}")))?;
            let attention_mask_value = ort::value::Value::from_array(attention_mask_arr)
                .map_err(|e| EmbedError::Unavailable(format!("attention_mask value: {e}")))?;
            let token_type_ids_value = ort::value::Value::from_array(token_type_ids_arr)
                .map_err(|e| EmbedError::Unavailable(format!("token_type_ids value: {e}")))?;

            // Run inference โ€” Session::run requires &mut self, so lock the mutex.
            let mut session = self
                .session
                .lock()
                .map_err(|e| EmbedError::Unavailable(format!("session mutex poisoned: {e}")))?;

            // `ort::inputs!` returns `[SessionInputValue; N]` directly (not a
            // Result) when all inputs are already `&Value` references.
            let inputs = ort::inputs![
                &input_ids_value,
                &attention_mask_value,
                &token_type_ids_value
            ];

            let outputs = session
                .run(inputs)
                .map_err(|e| EmbedError::Unavailable(format!("ort inference failed: {e}")))?;

            // `try_extract_tensor::<f32>()` returns `(&Shape, &[f32])` โ€” the
            // flat row-major tensor data. For arctic-embed-xs the output
            // `last_hidden_state` has shape `[1, seq_len, hidden_dim]`.
            let (_shape, hidden_data) = outputs["last_hidden_state"]
                .try_extract_tensor::<f32>()
                .map_err(|e| EmbedError::Unavailable(format!("ort output extract: {e}")))?;

            // hidden_data.len() = 1 * seq_len * hidden_dim
            let hidden_dim = hidden_data.len() / seq_len;

            // Mean-pool + L2-normalize.
            let mut pooled = Self::mean_pool(hidden_data, attention_mask, seq_len, hidden_dim);
            Self::l2_normalize(&mut pooled);

            if pooled.len() != EMBEDDING_DIM {
                return Err(EmbedError::DimensionMismatch {
                    expected: EMBEDDING_DIM,
                    actual: pooled.len(),
                });
            }

            results.push(pooled);
        }
        Ok(results)
    }
}

impl std::fmt::Debug for LocalEmbedClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LocalEmbedClient")
            .field("model", &self.model)
            .finish()
    }
}

/// Mock embedding client for testing (no network access).
///
/// Generates deterministic pseudo-random vectors based on a hash of the input
/// text. All vectors have length [`EMBEDDING_DIM`]. This allows tests to verify
/// storage and search logic without calling a real embedding service.
pub struct MockEmbedClient {
    /// Override dimension (defaults to [`EMBEDDING_DIM`]).
    dim: usize,
    /// If set, `embed()` returns this error instead of vectors.
    error: Option<EmbedError>,
}

impl MockEmbedClient {
    /// Creates a mock client that produces vectors of the standard dimension.
    #[must_use]
    pub fn new() -> Self {
        Self {
            dim: EMBEDDING_DIM,
            error: None,
        }
    }

    /// Creates a mock client with a custom vector dimension.
    #[must_use]
    pub fn with_dim(dim: usize) -> Self {
        Self { dim, error: None }
    }

    /// Creates a mock client that always returns the given error.
    #[must_use]
    pub fn with_error(error: EmbedError) -> Self {
        Self {
            dim: EMBEDDING_DIM,
            error: Some(error),
        }
    }
}

impl Default for MockEmbedClient {
    fn default() -> Self {
        Self::new()
    }
}

impl EmbedClient for MockEmbedClient {
    fn embed(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>> {
        if let Some(ref err) = self.error {
            return Err(EmbedError::Unavailable(err.to_string()));
        }
        // Deterministic pseudo-embedding: hash each text and fill the vector.
        let mut results = Vec::with_capacity(texts.len());
        for text in texts {
            let mut hasher = std::collections::hash_map::DefaultHasher::new();
            std::hash::Hash::hash(text, &mut hasher);
            let seed = std::hash::Hasher::finish(&hasher);
            let mut vec = Vec::with_capacity(self.dim);
            let mut state = seed;
            for _ in 0..self.dim {
                // Simple LCG for deterministic pseudo-random floats in [0, 1).
                state = state
                    .wrapping_mul(6364136223846793005)
                    .wrapping_add(1442695040888963407);
                let val = ((state >> 33) as f32) / (1u64 << 31) as f32;
                vec.push(val);
            }
            results.push(vec);
        }
        Ok(results)
    }
}

impl std::fmt::Debug for MockEmbedClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MockEmbedClient")
            .field("dim", &self.dim)
            .field("error", &self.error.is_some())
            .finish()
    }
}

// ---------------------------------------------------------------------------
// CachedEmbedClient (T021)
// ---------------------------------------------------------------------------

/// Serializes a `Vec<f32>` to little-endian bytes for cache storage.
///
/// Each `f32` is written as 4 little-endian bytes. The inverse is
/// [`deserialize_vec`].
#[cfg(feature = "cache")]
fn serialize_vec(vec: &[f32]) -> Vec<u8> {
    let mut bytes = Vec::with_capacity(vec.len() * 4);
    for &v in vec {
        bytes.extend_from_slice(&v.to_le_bytes());
    }
    bytes
}

/// Deserializes little-endian bytes back to `Vec<f32>`.
///
/// Inverse of [`serialize_vec`]. Returns an empty `Vec` when the byte
/// length is not a multiple of 4 โ€” this signals corrupt cache data so the
/// caller can treat it as a cache miss and recompute.
///
/// Note: [`chunks_exact`] silently drops a trailing partial chunk; the
/// explicit length check here makes that behavior visible and recoverable.
///
/// [`chunks_exact`]: slice::chunks_exact
#[cfg(feature = "cache")]
fn deserialize_vec(bytes: &[u8]) -> Vec<f32> {
    if !bytes.len().is_multiple_of(4) {
        return Vec::new();
    }
    bytes
        .chunks_exact(4)
        .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
        .collect()
}

/// Embedding client wrapper that caches vectors by text content hash (T021).
///
/// Wraps an inner [`EmbedClient`] and a [`CacheStore`](crate::cache::CacheStore).
/// On `embed`, each input text is looked up in the cache by
/// `format!("embed:{content_hash}")` where `content_hash` is the SHA-256 of
/// the text (via [`compute_content_hash`](crate::index::hash::compute_content_hash)).
/// Hits are returned from the cache; misses are batched and delegated to the
/// inner client, then written back to the cache.
///
/// Existing API is unchanged: [`EmbedClient`], [`OpenAIEmbedClient`],
/// [`LocalEmbedClient`], and [`MockEmbedClient`] are not modified.
#[cfg(feature = "cache")]
pub struct CachedEmbedClient {
    inner: Box<dyn EmbedClient>,
    cache: Arc<dyn CacheStore>,
}

#[cfg(feature = "cache")]
impl CachedEmbedClient {
    /// Creates a new cached embedding client wrapping `inner` with `cache`.
    #[must_use]
    pub fn new(inner: Box<dyn EmbedClient>, cache: Arc<dyn CacheStore>) -> Self {
        Self { inner, cache }
    }
}

#[cfg(feature = "cache")]
impl EmbedClient for CachedEmbedClient {
    fn embed(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>> {
        let mut results: Vec<Vec<f32>> = Vec::with_capacity(texts.len());
        let mut miss_indices: Vec<usize> = Vec::with_capacity(texts.len());
        let mut miss_texts: Vec<&str> = Vec::with_capacity(texts.len());

        // 1. Probe cache per text. Misses are collected for batch delegation.
        for (i, text) in texts.iter().enumerate() {
            let hash = crate::index::hash::compute_content_hash(text.as_bytes());
            let key = format!("embed:{hash}");
            if let Some(bytes) = self.cache.get(&key) {
                let vec = deserialize_vec(&bytes);
                if vec.len() == EMBEDDING_DIM {
                    results.push(vec);
                } else {
                    // Corrupt cache entry (wrong byte length or dim
                    // mismatch): treat as miss and overwrite with a fresh
                    // computation on the next phase.
                    results.push(Vec::new());
                    miss_indices.push(i);
                    miss_texts.push(*text);
                }
            } else {
                results.push(Vec::new());
                miss_indices.push(i);
                miss_texts.push(*text);
            }
        }

        // 2. Batch-call inner client for misses, then write results to cache.
        if !miss_texts.is_empty() {
            let embeddings = self.inner.embed(&miss_texts)?;
            for (idx, emb) in miss_indices.iter().zip(embeddings) {
                let text = texts[*idx];
                let hash = crate::index::hash::compute_content_hash(text.as_bytes());
                let key = format!("embed:{hash}");
                self.cache.set(&key, serialize_vec(&emb));
                results[*idx] = emb;
            }
        }

        Ok(results)
    }
}

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

    // --- MockEmbedClient ---

    #[test]
    fn mock_client_returns_correct_count() {
        let client = MockEmbedClient::new();
        let texts = ["hello", "world", "foo"];
        let result = client.embed(&texts).expect("embed");
        assert_eq!(result.len(), 3, "should return one vector per text");
    }

    #[test]
    fn mock_client_returns_correct_dimension() {
        let client = MockEmbedClient::new();
        let result = client.embed(&["test"]).expect("embed");
        assert_eq!(result[0].len(), EMBEDDING_DIM, "dimension should be 384");
    }

    #[test]
    fn mock_client_is_deterministic() {
        let client = MockEmbedClient::new();
        let a = client.embed(&["hello"]).expect("embed");
        let b = client.embed(&["hello"]).expect("embed");
        assert_eq!(a, b, "same input should produce same output");
    }

    #[test]
    fn mock_client_different_inputs_differ() {
        let client = MockEmbedClient::new();
        let a = client.embed(&["hello"]).expect("embed");
        let b = client.embed(&["world"]).expect("embed");
        assert_ne!(a, b, "different inputs should produce different outputs");
    }

    #[test]
    fn mock_client_with_custom_dim() {
        let client = MockEmbedClient::with_dim(128);
        let result = client.embed(&["test"]).expect("embed");
        assert_eq!(result[0].len(), 128);
    }

    #[test]
    fn mock_client_with_error_returns_error() {
        let client =
            MockEmbedClient::with_error(EmbedError::Unavailable("service down".to_string()));
        let result = client.embed(&["test"]);
        assert!(result.is_err(), "should return error");
        assert!(result.unwrap_err().to_string().contains("unavailable"));
    }

    #[test]
    fn mock_client_empty_input_returns_empty() {
        let client = MockEmbedClient::new();
        let result = client.embed(&[]).expect("embed");
        assert!(result.is_empty(), "empty input should return empty");
    }

    #[test]
    fn mock_client_default_is_new() {
        let client = MockEmbedClient::default();
        let result = client.embed(&["x"]).expect("embed");
        assert_eq!(result[0].len(), EMBEDDING_DIM);
    }

    #[test]
    fn mock_client_debug_does_not_leak_vectors() {
        let client = MockEmbedClient::new();
        let s = format!("{client:?}");
        assert!(s.contains("MockEmbedClient"));
        assert!(s.contains("dim"));
    }

    // --- OpenAIEmbedClient ---

    #[test]
    fn openai_client_new_without_endpoint_returns_error() {
        // H10/D7: default config is local mode (endpoint=None).
        // OpenAIEmbedClient should reject local-mode configs.
        let cfg = EmbeddingConfig::default();
        let result = OpenAIEmbedClient::new(cfg);
        assert!(result.is_err(), "should error without endpoint");
        assert!(
            matches!(result.unwrap_err(), EmbedError::Unavailable(_)),
            "should return Unavailable for local-mode config"
        );
    }

    #[test]
    fn openai_client_new_with_endpoint_but_no_key_returns_missing_key() {
        let _lock = crate::embed::ENV_TEST_LOCK.lock().unwrap();
        // Remote mode (endpoint=Some) but no API key โ†’ MissingApiKey.
        std::env::remove_var("CODENEXUS_EMBED_API_KEY");
        std::env::remove_var("OPENAI_API_KEY");
        let cfg = EmbeddingConfig {
            endpoint: Some("https://api.openai.com/v1".to_string()),
            ..EmbeddingConfig::default()
        };
        let result = OpenAIEmbedClient::new(cfg);
        assert!(result.is_err(), "should error without API key");
        assert!(matches!(result.unwrap_err(), EmbedError::MissingApiKey));
    }

    #[test]
    fn openai_client_new_with_endpoint_and_key_succeeds() {
        let cfg = EmbeddingConfig {
            endpoint: Some("https://api.openai.com/v1".to_string()),
            api_key: Some("test-key".to_string()),
            ..EmbeddingConfig::default()
        };
        let client = OpenAIEmbedClient::new(cfg).expect("should succeed with endpoint+key");
        assert!(client.endpoint().contains("openai.com"));
        assert!(!client.model().is_empty());
    }

    #[test]
    fn openai_client_from_env_without_endpoint_errors() {
        let _lock = crate::embed::ENV_TEST_LOCK.lock().unwrap();
        // H10/D7: without CODENEXUS_EMBED_ENDPOINT, from_env returns local-mode
        // config, which OpenAIEmbedClient rejects.
        std::env::remove_var("CODENEXUS_EMBED_ENDPOINT");
        std::env::remove_var("CODENEXUS_EMBED_API_KEY");
        std::env::remove_var("OPENAI_API_KEY");
        let result = OpenAIEmbedClient::from_env();
        assert!(result.is_err());
        assert!(
            matches!(result.unwrap_err(), EmbedError::Unavailable(_)),
            "should return Unavailable when endpoint not set"
        );
    }

    #[test]
    fn openai_client_from_env_with_endpoint_and_key_succeeds() {
        let _lock = crate::embed::ENV_TEST_LOCK.lock().unwrap();
        std::env::set_var("CODENEXUS_EMBED_ENDPOINT", "https://api.openai.com/v1");
        std::env::set_var("CODENEXUS_EMBED_API_KEY", "env-key");
        let client = OpenAIEmbedClient::from_env().expect("should succeed");
        assert_eq!(client.endpoint(), "https://api.openai.com/v1");
        std::env::remove_var("CODENEXUS_EMBED_ENDPOINT");
        std::env::remove_var("CODENEXUS_EMBED_API_KEY");
    }

    #[test]
    fn openai_client_debug_redacts_api_key() {
        let cfg = EmbeddingConfig {
            endpoint: Some("https://api.openai.com/v1".to_string()),
            api_key: Some("secret-key-12345".to_string()),
            ..EmbeddingConfig::default()
        };
        let client = OpenAIEmbedClient::new(cfg).expect("client");
        let s = format!("{client:?}");
        assert!(s.contains("<redacted>"), "API key must be redacted: {s}");
        assert!(
            !s.contains("secret-key-12345"),
            "API key must not appear in debug: {s}"
        );
    }

    #[test]
    fn openai_client_embed_without_key_returns_missing_key() {
        // Create a client with endpoint+key, then test the embed path.
        // We can't make a real HTTP call, but we can verify the client
        // is constructed correctly.
        let cfg = EmbeddingConfig {
            endpoint: Some("http://localhost:1".to_string()), // unreachable port
            api_key: Some("test".to_string()),
            ..EmbeddingConfig::default()
        };
        let client = OpenAIEmbedClient::new(cfg).expect("client");
        let result = client.embed(&["test"]);
        // Should get an Unavailable error (connection refused).
        assert!(result.is_err(), "should fail to connect");
        let err = result.unwrap_err();
        assert!(
            matches!(err, EmbedError::Unavailable(_)),
            "expected Unavailable, got: {err}"
        );
    }

    // --- LocalEmbedClient (H10/D7) ---

    #[test]
    fn local_client_new_without_model_returns_unavailable() {
        // Default config โ†’ local mode, model path doesn't exist.
        let cfg = EmbeddingConfig::default();
        let result = LocalEmbedClient::new(&cfg);
        assert!(result.is_err(), "should error when model file is missing");
        let err = result.unwrap_err();
        assert!(
            matches!(err, EmbedError::Unavailable(ref msg) if msg.contains("not found")),
            "expected Unavailable with 'not found', got: {err}"
        );
    }

    #[test]
    fn local_client_new_with_nonexistent_custom_path_returns_unavailable() {
        let cfg = EmbeddingConfig {
            model_path: Some(std::path::PathBuf::from("/nonexistent/model.onnx")),
            ..EmbeddingConfig::default()
        };
        let result = LocalEmbedClient::new(&cfg);
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("not found"),
            "error should mention 'not found': {msg}"
        );
        assert!(
            msg.contains("/nonexistent/model.onnx"),
            "error should mention the path: {msg}"
        );
    }

    #[test]
    fn local_client_debug_shows_model_name() {
        // We can't construct a LocalEmbedClient without a real model file,
        // but we can verify the Debug impl format via MockEmbedClient
        // pattern. This test documents the expected Debug format.
        // (Actual Debug test requires a model file โ€” integration concern.)
    }

    #[test]
    fn local_client_mean_pool_correctness() {
        // Unit test for the mean_pool helper (no model file needed).
        // Shape: [1, 3, 2] โ€” 3 tokens, 2 hidden dims. Flat row-major data.
        let hidden_data = vec![
            // token 0 (masked in)
            1.0, 2.0, // token 1 (masked out)
            100.0, 200.0, // token 2 (masked in)
            3.0, 4.0,
        ];
        let attention_mask = vec![1u32, 0u32, 1u32];

        let pooled = LocalEmbedClient::mean_pool(&hidden_data, &attention_mask, 3, 2);

        // Mean of [1.0, 3.0] = 2.0; mean of [2.0, 4.0] = 3.0
        // (token 1 is masked out and excluded)
        assert_eq!(pooled, vec![2.0, 3.0]);
    }

    #[test]
    fn local_client_mean_pool_all_masked_returns_zeros() {
        // Edge case: all tokens masked out โ†’ returns zeros (no division by zero).
        let hidden_data = vec![1.0, 2.0, 3.0, 4.0];
        let attention_mask = vec![0u32, 0u32];

        let pooled = LocalEmbedClient::mean_pool(&hidden_data, &attention_mask, 2, 2);
        assert_eq!(pooled, vec![0.0, 0.0]);
    }

    #[test]
    fn local_client_l2_normalize_correctness() {
        let mut vec = vec![3.0, 4.0]; // norm = 5.0
        LocalEmbedClient::l2_normalize(&mut vec);
        assert!((vec[0] - 0.6).abs() < 1e-6, "expected 0.6, got {}", vec[0]);
        assert!((vec[1] - 0.8).abs() < 1e-6, "expected 0.8, got {}", vec[1]);
    }

    #[test]
    fn local_client_l2_normalize_zero_vector_noop() {
        let mut vec = vec![0.0, 0.0, 0.0];
        LocalEmbedClient::l2_normalize(&mut vec);
        assert_eq!(vec, vec![0.0, 0.0, 0.0]);
    }

    // --- EmbedClient trait object ---

    #[test]
    fn embed_client_trait_object_works() {
        let client: Box<dyn EmbedClient> = Box::new(MockEmbedClient::new());
        let result = client.embed(&["hello", "world"]).expect("embed");
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn embed_client_trait_is_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<Box<dyn EmbedClient>>();
    }

    // --- CachedEmbedClient (T021) ---

    #[cfg(feature = "cache")]
    mod cached_tests {
        use super::*;
        use crate::cache::CacheStore;
        use std::collections::HashMap;
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::{Arc, Mutex};

        /// Wraps [`MockEmbedClient`], counting `embed()` calls and recording
        /// the texts passed to each call. Inspection handles are shared via
        /// [`Arc`] so the test can read them after the client is boxed.
        struct CountingEmbedClient {
            calls: Arc<AtomicUsize>,
            recorded: Arc<Mutex<Vec<Vec<String>>>>,
            inner: MockEmbedClient,
        }

        impl CountingEmbedClient {
            fn new() -> Self {
                Self {
                    calls: Arc::new(AtomicUsize::new(0)),
                    recorded: Arc::new(Mutex::new(Vec::new())),
                    inner: MockEmbedClient::new(),
                }
            }
        }

        impl EmbedClient for CountingEmbedClient {
            fn embed(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>> {
                self.calls.fetch_add(1, Ordering::SeqCst);
                self.recorded
                    .lock()
                    .expect("lock")
                    .push(texts.iter().map(|s| s.to_string()).collect());
                self.inner.embed(texts)
            }
        }

        /// HashMap-backed [`CacheStore`] for testing.
        struct MockCache {
            store: Mutex<HashMap<String, Vec<u8>>>,
        }

        impl MockCache {
            fn new() -> Self {
                Self {
                    store: Mutex::new(HashMap::new()),
                }
            }

            fn snapshot(&self) -> HashMap<String, Vec<u8>> {
                self.store.lock().expect("lock").clone()
            }

            fn len(&self) -> usize {
                self.store.lock().expect("lock").len()
            }
        }

        impl CacheStore for MockCache {
            fn get(&self, key: &str) -> Option<Vec<u8>> {
                self.store.lock().expect("lock").get(key).cloned()
            }

            fn set(&self, key: &str, val: Vec<u8>) {
                self.store
                    .lock()
                    .expect("lock")
                    .insert(key.to_string(), val);
            }

            fn invalidate_all(&self) {
                self.store.lock().expect("lock").clear();
            }
        }

        #[test]
        fn cached_embed_miss_then_hit_skips_inner_call() {
            let inner = CountingEmbedClient::new();
            let calls = Arc::clone(&inner.calls);
            let cached = CachedEmbedClient::new(Box::new(inner), Arc::new(MockCache::new()));

            let r1 = cached.embed(&["hello"]).expect("first embed");
            let r2 = cached.embed(&["hello"]).expect("second embed (cache hit)");

            assert_eq!(
                calls.load(Ordering::SeqCst),
                1,
                "inner should be called once; second call must hit cache"
            );
            assert_eq!(r1, r2, "both calls should return identical vectors");
        }

        #[test]
        fn cached_embed_batch_partial_cache_hit() {
            let inner = CountingEmbedClient::new();
            let calls = Arc::clone(&inner.calls);
            let recorded = Arc::clone(&inner.recorded);
            let cache = Arc::new(MockCache::new());
            let cached = CachedEmbedClient::new(Box::new(inner), cache.clone());

            // Prime the cache: embed "cached_text" once.
            let primed = cached
                .embed(&["cached_text"])
                .expect("prime")
                .into_iter()
                .next()
                .expect("one vector");
            let prime_calls = calls.load(Ordering::SeqCst);

            // Batch call: "cached_text" is cached, "fresh_text" is a miss.
            let results = cached
                .embed(&["cached_text", "fresh_text"])
                .expect("batch embed");

            assert_eq!(results.len(), 2, "should return one vector per input");
            assert_eq!(
                results[0], primed,
                "cached_text result should match the primed vector"
            );
            let batch_calls = calls.load(Ordering::SeqCst) - prime_calls;
            assert_eq!(
                batch_calls, 1,
                "inner should be called once for the miss only"
            );
            let last = recorded
                .lock()
                .expect("lock")
                .last()
                .cloned()
                .unwrap_or_default();
            assert_eq!(
                last,
                vec!["fresh_text".to_string()],
                "inner should only receive uncached texts"
            );
        }

        #[test]
        fn cached_embed_same_text_same_key() {
            let inner = CountingEmbedClient::new();
            let cache = Arc::new(MockCache::new());
            let cached = CachedEmbedClient::new(Box::new(inner), cache.clone());

            cached.embed(&["hello"]).expect("first");
            cached.embed(&["hello"]).expect("second");

            let snap = cache.snapshot();
            assert_eq!(
                snap.len(),
                1,
                "same text should produce same key โ†’ exactly one entry"
            );
            let key = snap.keys().next().expect("one entry");
            assert!(
                key.starts_with("embed:"),
                "key should start with 'embed:': {key}"
            );
        }

        #[test]
        fn cached_embed_different_texts_different_keys() {
            let inner = CountingEmbedClient::new();
            let cache = Arc::new(MockCache::new());
            let cached = CachedEmbedClient::new(Box::new(inner), cache.clone());

            cached.embed(&["hello", "world"]).expect("embed");

            let snap = cache.snapshot();
            assert_eq!(
                snap.len(),
                2,
                "different texts should produce different keys โ†’ two entries"
            );
            for key in snap.keys() {
                assert!(
                    key.starts_with("embed:"),
                    "key should start with 'embed:': {key}"
                );
            }
        }

        #[test]
        fn cached_embed_empty_input_returns_empty() {
            let inner = CountingEmbedClient::new();
            let calls = Arc::clone(&inner.calls);
            let cache = Arc::new(MockCache::new());
            let cached = CachedEmbedClient::new(Box::new(inner), cache.clone());

            let results = cached.embed(&[]).expect("empty embed");
            assert!(results.is_empty(), "empty input should return empty");
            assert_eq!(
                calls.load(Ordering::SeqCst),
                0,
                "inner should not be called for empty input"
            );
            assert_eq!(cache.len(), 0, "cache should remain empty");
        }

        #[test]
        fn cached_embed_stores_correct_vector() {
            let inner = CountingEmbedClient::new();
            let calls = Arc::clone(&inner.calls);
            let cache = Arc::new(MockCache::new());
            let cached = CachedEmbedClient::new(Box::new(inner), cache.clone());

            let r1 = cached.embed(&["hello"]).expect("first embed");
            let v1 = r1.into_iter().next().expect("one vector");

            // Cache should have exactly one entry with an embed: prefix.
            let snap = cache.snapshot();
            assert_eq!(snap.len(), 1, "exactly one entry should be cached");
            let (key, _val) = snap.iter().next().expect("one entry");
            assert!(
                key.starts_with("embed:"),
                "key should start with 'embed:': {key}"
            );

            // Second call returns from cache โ€” proves serialize/deserialize
            // round-trip preserves the vector exactly.
            let r2 = cached.embed(&["hello"]).expect("second embed (cache hit)");
            let v2 = r2.into_iter().next().expect("one vector");
            assert_eq!(
                v1, v2,
                "cache hit should return the same vector (round-trip correctness)"
            );
            assert_eq!(
                calls.load(Ordering::SeqCst),
                1,
                "inner should be called once; second call was a cache hit"
            );
        }
    }
}