Skip to main content

aft/
semantic_index.rs

1use crate::config::{SemanticBackend, SemanticBackendConfig};
2use crate::parser::FileParser;
3use crate::symbols::{Symbol, SymbolKind};
4
5use fastembed::{EmbeddingModel as FastembedEmbeddingModel, InitOptions, TextEmbedding};
6use reqwest::blocking::Client;
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9use std::env;
10use std::fmt::Display;
11use std::fs;
12use std::path::{Path, PathBuf};
13use std::time::Duration;
14use std::time::SystemTime;
15use url::Url;
16
17const DEFAULT_DIMENSION: usize = 384;
18const MAX_ENTRIES: usize = 1_000_000;
19const MAX_DIMENSION: usize = 1024;
20const F32_BYTES: usize = std::mem::size_of::<f32>();
21const HEADER_BYTES_V1: usize = 9;
22const HEADER_BYTES_V2: usize = 13;
23const ONNX_RUNTIME_INSTALL_HINT: &str =
24    "ONNX Runtime not found. Install via: brew install onnxruntime (macOS) or apt install libonnxruntime (Linux).";
25
26const SEMANTIC_INDEX_VERSION_V1: u8 = 1;
27const SEMANTIC_INDEX_VERSION_V2: u8 = 2;
28/// V3 adds subsec_nanos to the file-mtime table so staleness detection survives
29/// restart round-trips on filesystems with subsecond mtime precision (APFS,
30/// ext4 with nsec, NTFS). V1/V2 persisted whole-second mtimes only, which
31/// caused every restart to flag ~99% of files as stale and re-embed them.
32const SEMANTIC_INDEX_VERSION_V3: u8 = 3;
33/// V4 keeps the V3 on-disk layout but rebuilds persisted snippets once after
34/// fixing symbol ranges that were incorrectly treated as 1-based.
35const SEMANTIC_INDEX_VERSION_V4: u8 = 4;
36const DEFAULT_OPENAI_EMBEDDING_PATH: &str = "/embeddings";
37const DEFAULT_OLLAMA_EMBEDDING_PATH: &str = "/api/embed";
38// Must stay below the bridge timeout (30s) to avoid bridge kills on slow backends.
39const DEFAULT_OPENAI_EMBEDDING_TIMEOUT_MS: u64 = 25_000;
40const DEFAULT_MAX_BATCH_SIZE: usize = 64;
41const FALLBACK_BACKEND: &str = "none";
42const EMBEDDING_REQUEST_MAX_ATTEMPTS: usize = 3;
43const EMBEDDING_REQUEST_BACKOFF_MS: [u64; 2] = [500, 1_000];
44
45#[derive(Debug, Clone, Serialize, Deserialize)]
46pub struct SemanticIndexFingerprint {
47    pub backend: String,
48    pub model: String,
49    #[serde(default)]
50    pub base_url: String,
51    pub dimension: usize,
52}
53
54impl SemanticIndexFingerprint {
55    fn from_config(config: &SemanticBackendConfig, dimension: usize) -> Self {
56        // Use normalized URL for fingerprinting so cosmetic differences
57        // (e.g. "http://host/v1" vs "http://host/v1/") don't cause rebuilds.
58        let base_url = config
59            .base_url
60            .as_ref()
61            .and_then(|u| normalize_base_url(u).ok())
62            .unwrap_or_else(|| FALLBACK_BACKEND.to_string());
63        Self {
64            backend: config.backend.as_str().to_string(),
65            model: config.model.clone(),
66            base_url,
67            dimension,
68        }
69    }
70
71    pub fn as_string(&self) -> String {
72        serde_json::to_string(self).unwrap_or_else(|_| String::new())
73    }
74
75    fn matches_expected(&self, expected: &str) -> bool {
76        let encoded = self.as_string();
77        !encoded.is_empty() && encoded == expected
78    }
79}
80
81enum SemanticEmbeddingEngine {
82    Fastembed(TextEmbedding),
83    OpenAiCompatible {
84        client: Client,
85        model: String,
86        base_url: String,
87        api_key: Option<String>,
88    },
89    Ollama {
90        client: Client,
91        model: String,
92        base_url: String,
93    },
94}
95
96pub struct SemanticEmbeddingModel {
97    backend: SemanticBackend,
98    model: String,
99    base_url: Option<String>,
100    timeout_ms: u64,
101    max_batch_size: usize,
102    dimension: Option<usize>,
103    engine: SemanticEmbeddingEngine,
104}
105
106pub type EmbeddingModel = SemanticEmbeddingModel;
107
108fn validate_embedding_batch(
109    vectors: &[Vec<f32>],
110    expected_count: usize,
111    context: &str,
112) -> Result<(), String> {
113    if expected_count > 0 && vectors.is_empty() {
114        return Err(format!(
115            "{context} returned no vectors for {expected_count} inputs"
116        ));
117    }
118
119    if vectors.len() != expected_count {
120        return Err(format!(
121            "{context} returned {} vectors for {} inputs",
122            vectors.len(),
123            expected_count
124        ));
125    }
126
127    let Some(first_vector) = vectors.first() else {
128        return Ok(());
129    };
130    let expected_dimension = first_vector.len();
131    for (index, vector) in vectors.iter().enumerate() {
132        if vector.len() != expected_dimension {
133            return Err(format!(
134                "{context} returned inconsistent embedding dimensions: vector 0 has length {expected_dimension}, vector {index} has length {}",
135                vector.len()
136            ));
137        }
138    }
139
140    Ok(())
141}
142
143fn normalize_base_url(raw: &str) -> Result<String, String> {
144    let parsed = Url::parse(raw).map_err(|error| format!("invalid base_url '{raw}': {error}"))?;
145    let scheme = parsed.scheme();
146    if scheme != "http" && scheme != "https" {
147        return Err(format!(
148            "unsupported URL scheme '{}' — only http:// and https:// are allowed",
149            scheme
150        ));
151    }
152    Ok(parsed.to_string().trim_end_matches('/').to_string())
153}
154
155fn build_openai_embeddings_endpoint(base_url: &str) -> String {
156    if base_url.ends_with("/v1") {
157        format!("{base_url}{DEFAULT_OPENAI_EMBEDDING_PATH}")
158    } else {
159        format!("{base_url}/v1{}", DEFAULT_OPENAI_EMBEDDING_PATH)
160    }
161}
162
163fn build_ollama_embeddings_endpoint(base_url: &str) -> String {
164    if base_url.ends_with("/api") {
165        format!("{base_url}/embed")
166    } else {
167        format!("{base_url}{DEFAULT_OLLAMA_EMBEDDING_PATH}")
168    }
169}
170
171fn normalize_api_key(value: Option<String>) -> Option<String> {
172    value.and_then(|token| {
173        let token = token.trim();
174        if token.is_empty() {
175            None
176        } else {
177            Some(token.to_string())
178        }
179    })
180}
181
182fn is_retryable_embedding_status(status: reqwest::StatusCode) -> bool {
183    status.is_server_error() || status == reqwest::StatusCode::TOO_MANY_REQUESTS
184}
185
186fn is_retryable_embedding_error(error: &reqwest::Error) -> bool {
187    error.is_connect()
188}
189
190fn sleep_before_embedding_retry(attempt_index: usize) {
191    if let Some(delay_ms) = EMBEDDING_REQUEST_BACKOFF_MS.get(attempt_index) {
192        std::thread::sleep(Duration::from_millis(*delay_ms));
193    }
194}
195
196fn send_embedding_request<F>(mut make_request: F, backend_label: &str) -> Result<String, String>
197where
198    F: FnMut() -> reqwest::blocking::RequestBuilder,
199{
200    for attempt_index in 0..EMBEDDING_REQUEST_MAX_ATTEMPTS {
201        let last_attempt = attempt_index + 1 == EMBEDDING_REQUEST_MAX_ATTEMPTS;
202
203        let response = match make_request().send() {
204            Ok(response) => response,
205            Err(error) => {
206                if !last_attempt && is_retryable_embedding_error(&error) {
207                    sleep_before_embedding_retry(attempt_index);
208                    continue;
209                }
210                return Err(format!("{backend_label} request failed: {error}"));
211            }
212        };
213
214        let status = response.status();
215        let raw = match response.text() {
216            Ok(raw) => raw,
217            Err(error) => {
218                if !last_attempt && is_retryable_embedding_error(&error) {
219                    sleep_before_embedding_retry(attempt_index);
220                    continue;
221                }
222                return Err(format!("{backend_label} response read failed: {error}"));
223            }
224        };
225
226        if status.is_success() {
227            return Ok(raw);
228        }
229
230        if !last_attempt && is_retryable_embedding_status(status) {
231            sleep_before_embedding_retry(attempt_index);
232            continue;
233        }
234
235        return Err(format!(
236            "{backend_label} request failed (HTTP {}): {}",
237            status, raw
238        ));
239    }
240
241    unreachable!("embedding request retries exhausted without returning")
242}
243
244impl SemanticEmbeddingModel {
245    pub fn from_config(config: &SemanticBackendConfig) -> Result<Self, String> {
246        let timeout_ms = if config.timeout_ms == 0 {
247            DEFAULT_OPENAI_EMBEDDING_TIMEOUT_MS
248        } else {
249            config.timeout_ms
250        };
251
252        let max_batch_size = if config.max_batch_size == 0 {
253            DEFAULT_MAX_BATCH_SIZE
254        } else {
255            config.max_batch_size
256        };
257
258        let api_key_env = normalize_api_key(config.api_key_env.clone());
259        let model = config.model.clone();
260
261        let client = Client::builder()
262            .timeout(Duration::from_millis(timeout_ms))
263            .redirect(reqwest::redirect::Policy::none())
264            .build()
265            .map_err(|error| format!("failed to configure embedding client: {error}"))?;
266
267        let engine = match config.backend {
268            SemanticBackend::Fastembed => {
269                SemanticEmbeddingEngine::Fastembed(initialize_text_embedding(&model)?)
270            }
271            SemanticBackend::OpenAiCompatible => {
272                let raw = config.base_url.as_ref().ok_or_else(|| {
273                    "base_url is required for openai_compatible backend".to_string()
274                })?;
275                let base_url = normalize_base_url(raw)?;
276
277                let api_key = match api_key_env {
278                    Some(var_name) => Some(env::var(&var_name).map_err(|_| {
279                        format!("missing api_key_env '{var_name}' for openai_compatible backend")
280                    })?),
281                    None => None,
282                };
283
284                SemanticEmbeddingEngine::OpenAiCompatible {
285                    client,
286                    model,
287                    base_url,
288                    api_key,
289                }
290            }
291            SemanticBackend::Ollama => {
292                let raw = config
293                    .base_url
294                    .as_ref()
295                    .ok_or_else(|| "base_url is required for ollama backend".to_string())?;
296                let base_url = normalize_base_url(raw)?;
297
298                SemanticEmbeddingEngine::Ollama {
299                    client,
300                    model,
301                    base_url,
302                }
303            }
304        };
305
306        Ok(Self {
307            backend: config.backend,
308            model: config.model.clone(),
309            base_url: config.base_url.clone(),
310            timeout_ms,
311            max_batch_size,
312            dimension: None,
313            engine,
314        })
315    }
316
317    pub fn backend(&self) -> SemanticBackend {
318        self.backend
319    }
320
321    pub fn model(&self) -> &str {
322        &self.model
323    }
324
325    pub fn base_url(&self) -> Option<&str> {
326        self.base_url.as_deref()
327    }
328
329    pub fn max_batch_size(&self) -> usize {
330        self.max_batch_size
331    }
332
333    pub fn timeout_ms(&self) -> u64 {
334        self.timeout_ms
335    }
336
337    pub fn fingerprint(
338        &mut self,
339        config: &SemanticBackendConfig,
340    ) -> Result<SemanticIndexFingerprint, String> {
341        let dimension = self.dimension()?;
342        Ok(SemanticIndexFingerprint::from_config(config, dimension))
343    }
344
345    pub fn dimension(&mut self) -> Result<usize, String> {
346        if let Some(dimension) = self.dimension {
347            return Ok(dimension);
348        }
349
350        let dimension = match &mut self.engine {
351            SemanticEmbeddingEngine::Fastembed(model) => {
352                let vectors = model
353                    .embed(vec!["semantic index fingerprint probe".to_string()], None)
354                    .map_err(|error| format_embedding_init_error(error.to_string()))?;
355                vectors
356                    .first()
357                    .map(|v| v.len())
358                    .ok_or_else(|| "embedding backend returned no vectors".to_string())?
359            }
360            SemanticEmbeddingEngine::OpenAiCompatible { .. } => {
361                let vectors =
362                    self.embed_texts(vec!["semantic index fingerprint probe".to_string()])?;
363                vectors
364                    .first()
365                    .map(|v| v.len())
366                    .ok_or_else(|| "embedding backend returned no vectors".to_string())?
367            }
368            SemanticEmbeddingEngine::Ollama { .. } => {
369                let vectors =
370                    self.embed_texts(vec!["semantic index fingerprint probe".to_string()])?;
371                vectors
372                    .first()
373                    .map(|v| v.len())
374                    .ok_or_else(|| "embedding backend returned no vectors".to_string())?
375            }
376        };
377
378        self.dimension = Some(dimension);
379        Ok(dimension)
380    }
381
382    pub fn embed(&mut self, texts: Vec<String>) -> Result<Vec<Vec<f32>>, String> {
383        self.embed_texts(texts)
384    }
385
386    fn embed_texts(&mut self, texts: Vec<String>) -> Result<Vec<Vec<f32>>, String> {
387        match &mut self.engine {
388            SemanticEmbeddingEngine::Fastembed(model) => model
389                .embed(texts, None::<usize>)
390                .map_err(|error| format_embedding_init_error(error.to_string()))
391                .map_err(|error| format!("failed to embed batch: {error}")),
392            SemanticEmbeddingEngine::OpenAiCompatible {
393                client,
394                model,
395                base_url,
396                api_key,
397            } => {
398                let expected_text_count = texts.len();
399                let endpoint = build_openai_embeddings_endpoint(base_url);
400                let body = serde_json::json!({
401                    "input": texts,
402                    "model": model,
403                });
404
405                let raw = send_embedding_request(
406                    || {
407                        let mut request = client
408                            .post(&endpoint)
409                            .json(&body)
410                            .header("Content-Type", "application/json");
411
412                        if let Some(api_key) = api_key {
413                            request = request.header("Authorization", format!("Bearer {api_key}"));
414                        }
415
416                        request
417                    },
418                    "openai compatible",
419                )?;
420
421                #[derive(Deserialize)]
422                struct OpenAiResponse {
423                    data: Vec<OpenAiEmbeddingResult>,
424                }
425
426                #[derive(Deserialize)]
427                struct OpenAiEmbeddingResult {
428                    embedding: Vec<f32>,
429                    index: Option<u32>,
430                }
431
432                let parsed: OpenAiResponse = serde_json::from_str(&raw)
433                    .map_err(|error| format!("invalid openai compatible response: {error}"))?;
434                if parsed.data.len() != expected_text_count {
435                    return Err(format!(
436                        "openai compatible response returned {} embeddings for {} inputs",
437                        parsed.data.len(),
438                        expected_text_count
439                    ));
440                }
441
442                let mut vectors = vec![Vec::new(); parsed.data.len()];
443                for (i, item) in parsed.data.into_iter().enumerate() {
444                    let index = item.index.unwrap_or(i as u32) as usize;
445                    if index >= vectors.len() {
446                        return Err(
447                            "openai compatible response contains invalid vector index".to_string()
448                        );
449                    }
450                    vectors[index] = item.embedding;
451                }
452
453                for vector in &vectors {
454                    if vector.is_empty() {
455                        return Err(
456                            "openai compatible response contained missing vectors".to_string()
457                        );
458                    }
459                }
460
461                self.dimension = vectors.first().map(Vec::len);
462                Ok(vectors)
463            }
464            SemanticEmbeddingEngine::Ollama {
465                client,
466                model,
467                base_url,
468            } => {
469                let expected_text_count = texts.len();
470                let endpoint = build_ollama_embeddings_endpoint(base_url);
471
472                #[derive(Serialize)]
473                struct OllamaPayload<'a> {
474                    model: &'a str,
475                    input: Vec<String>,
476                }
477
478                let payload = OllamaPayload {
479                    model,
480                    input: texts,
481                };
482
483                let raw = send_embedding_request(
484                    || {
485                        client
486                            .post(&endpoint)
487                            .json(&payload)
488                            .header("Content-Type", "application/json")
489                    },
490                    "ollama",
491                )?;
492
493                #[derive(Deserialize)]
494                struct OllamaResponse {
495                    embeddings: Vec<Vec<f32>>,
496                }
497
498                let parsed: OllamaResponse = serde_json::from_str(&raw)
499                    .map_err(|error| format!("invalid ollama response: {error}"))?;
500                if parsed.embeddings.is_empty() {
501                    return Err("ollama response returned no embeddings".to_string());
502                }
503                if parsed.embeddings.len() != expected_text_count {
504                    return Err(format!(
505                        "ollama response returned {} embeddings for {} inputs",
506                        parsed.embeddings.len(),
507                        expected_text_count
508                    ));
509                }
510
511                let vectors = parsed.embeddings;
512                for vector in &vectors {
513                    if vector.is_empty() {
514                        return Err("ollama response contained empty embeddings".to_string());
515                    }
516                }
517
518                self.dimension = vectors.first().map(Vec::len);
519                Ok(vectors)
520            }
521        }
522    }
523}
524
525/// Pre-validate ONNX Runtime by attempting a raw dlopen before ort touches it.
526/// This catches broken/incompatible .so files without risking a panic in the ort crate.
527/// Also checks the runtime version via OrtGetApiBase if available.
528pub fn pre_validate_onnx_runtime() -> Result<(), String> {
529    let dylib_path = std::env::var("ORT_DYLIB_PATH").ok();
530
531    #[cfg(any(target_os = "linux", target_os = "macos"))]
532    {
533        #[cfg(target_os = "linux")]
534        let default_name = "libonnxruntime.so";
535        #[cfg(target_os = "macos")]
536        let default_name = "libonnxruntime.dylib";
537
538        let lib_name = dylib_path.as_deref().unwrap_or(default_name);
539
540        unsafe {
541            let c_name = std::ffi::CString::new(lib_name)
542                .map_err(|e| format!("invalid library path: {}", e))?;
543            let handle = libc::dlopen(c_name.as_ptr(), libc::RTLD_NOW);
544            if handle.is_null() {
545                let err = libc::dlerror();
546                let msg = if err.is_null() {
547                    "unknown dlopen error".to_string()
548                } else {
549                    std::ffi::CStr::from_ptr(err).to_string_lossy().into_owned()
550                };
551                return Err(format!(
552                    "ONNX Runtime not found. dlopen('{}') failed: {}. \
553                     Run `bunx @cortexkit/aft-opencode@latest doctor` to diagnose.",
554                    lib_name, msg
555                ));
556            }
557
558            // Try to detect the runtime version from the file path or soname.
559            // libonnxruntime.so.1.19.0, libonnxruntime.1.24.4.dylib, etc.
560            let detected_version = detect_ort_version_from_path(lib_name);
561
562            libc::dlclose(handle);
563
564            // Check version compatibility — we need 1.24.x
565            if let Some(ref version) = detected_version {
566                let parts: Vec<&str> = version.split('.').collect();
567                if let (Some(major), Some(minor)) = (
568                    parts.first().and_then(|s| s.parse::<u32>().ok()),
569                    parts.get(1).and_then(|s| s.parse::<u32>().ok()),
570                ) {
571                    if major != 1 || minor < 20 {
572                        return Err(format!(
573                            "ONNX Runtime version mismatch: found v{} at '{}', but AFT requires v1.20+. \
574                             Solutions:\n\
575                             1. Remove the old library and restart (AFT auto-downloads the correct version):\n\
576                             {}\n\
577                             2. Or install ONNX Runtime 1.24: https://github.com/microsoft/onnxruntime/releases/tag/v1.24.0\n\
578                             3. Run `bunx @cortexkit/aft-opencode@latest doctor` for full diagnostics.",
579                            version,
580                            lib_name,
581                            suggest_removal_command(lib_name),
582                        ));
583                    }
584                }
585            }
586        }
587    }
588
589    #[cfg(target_os = "windows")]
590    {
591        // On Windows, skip pre-validation — let ort handle LoadLibrary
592        let _ = dylib_path;
593    }
594
595    Ok(())
596}
597
598/// Try to extract the ORT version from the library filename or resolved symlink.
599/// Examples: "libonnxruntime.so.1.19.0" → "1.19.0", "libonnxruntime.1.24.4.dylib" → "1.24.4"
600fn detect_ort_version_from_path(lib_path: &str) -> Option<String> {
601    let path = std::path::Path::new(lib_path);
602
603    // Try the path as given, then follow symlinks
604    for candidate in [Some(path.to_path_buf()), std::fs::canonicalize(path).ok()]
605        .into_iter()
606        .flatten()
607    {
608        if let Some(name) = candidate.file_name().and_then(|n| n.to_str()) {
609            if let Some(version) = extract_version_from_filename(name) {
610                return Some(version);
611            }
612        }
613    }
614
615    // Also check for versioned siblings in the same directory
616    if let Some(parent) = path.parent() {
617        if let Ok(entries) = std::fs::read_dir(parent) {
618            for entry in entries.flatten() {
619                if let Some(name) = entry.file_name().to_str() {
620                    if name.starts_with("libonnxruntime") {
621                        if let Some(version) = extract_version_from_filename(name) {
622                            return Some(version);
623                        }
624                    }
625                }
626            }
627        }
628    }
629
630    None
631}
632
633/// Extract version from filenames like "libonnxruntime.so.1.19.0" or "libonnxruntime.1.24.4.dylib"
634fn extract_version_from_filename(name: &str) -> Option<String> {
635    // Match patterns: .so.X.Y.Z or .X.Y.Z.dylib or .X.Y.Z.so
636    let re = regex::Regex::new(r"(\d+\.\d+\.\d+)").ok()?;
637    re.find(name).map(|m| m.as_str().to_string())
638}
639
640fn suggest_removal_command(lib_path: &str) -> String {
641    if lib_path.starts_with("/usr/local/lib")
642        || lib_path == "libonnxruntime.so"
643        || lib_path == "libonnxruntime.dylib"
644    {
645        #[cfg(target_os = "linux")]
646        return "   sudo rm /usr/local/lib/libonnxruntime* && sudo ldconfig".to_string();
647        #[cfg(target_os = "macos")]
648        return "   sudo rm /usr/local/lib/libonnxruntime*".to_string();
649        #[cfg(target_os = "windows")]
650        return "   Delete the ONNX Runtime DLL from your PATH".to_string();
651    }
652    format!("   rm '{}'", lib_path)
653}
654
655pub fn initialize_text_embedding(model: &str) -> Result<TextEmbedding, String> {
656    // Pre-validate before ort can panic on a bad library
657    pre_validate_onnx_runtime()?;
658
659    let selected_model = match model {
660        "all-MiniLM-L6-v2" | "all-minilm-l6-v2" => FastembedEmbeddingModel::AllMiniLML6V2,
661        _ => {
662            return Err(format!(
663                "unsupported fastembed model '{}'. Supported: all-MiniLM-L6-v2",
664                model
665            ))
666        }
667    };
668
669    TextEmbedding::try_new(InitOptions::new(selected_model)).map_err(format_embedding_init_error)
670}
671
672pub fn is_onnx_runtime_unavailable(message: &str) -> bool {
673    if message.trim_start().starts_with("ONNX Runtime not found.") {
674        return true;
675    }
676
677    let message = message.to_ascii_lowercase();
678    let mentions_onnx_runtime = ["onnx runtime", "onnxruntime", "libonnxruntime"]
679        .iter()
680        .any(|pattern| message.contains(pattern));
681    let mentions_dynamic_load_failure = [
682        "shared library",
683        "dynamic library",
684        "failed to load",
685        "could not load",
686        "unable to load",
687        "dlopen",
688        "loadlibrary",
689        "no such file",
690        "not found",
691    ]
692    .iter()
693    .any(|pattern| message.contains(pattern));
694
695    mentions_onnx_runtime && mentions_dynamic_load_failure
696}
697
698fn format_embedding_init_error(error: impl Display) -> String {
699    let message = error.to_string();
700
701    if is_onnx_runtime_unavailable(&message) {
702        return format!("{ONNX_RUNTIME_INSTALL_HINT} Original error: {message}");
703    }
704
705    format!("failed to initialize semantic embedding model: {message}")
706}
707
708/// A chunk of code ready for embedding — derived from a Symbol with context enrichment
709#[derive(Debug, Clone)]
710pub struct SemanticChunk {
711    /// Absolute file path
712    pub file: PathBuf,
713    /// Symbol name
714    pub name: String,
715    /// Symbol kind (function, class, struct, etc.)
716    pub kind: SymbolKind,
717    /// Line range (0-based internally, inclusive)
718    pub start_line: u32,
719    pub end_line: u32,
720    /// Whether the symbol is exported
721    pub exported: bool,
722    /// The enriched text that gets embedded (scope + signature + body snippet)
723    pub embed_text: String,
724    /// Short code snippet for display in results
725    pub snippet: String,
726}
727
728/// A stored embedding entry — chunk metadata + vector
729#[derive(Debug)]
730struct EmbeddingEntry {
731    chunk: SemanticChunk,
732    vector: Vec<f32>,
733}
734
735/// The semantic index — stores embeddings for all symbols in a project
736#[derive(Debug)]
737pub struct SemanticIndex {
738    entries: Vec<EmbeddingEntry>,
739    /// Track which files are indexed and their mtime for staleness detection
740    file_mtimes: HashMap<PathBuf, SystemTime>,
741    /// Embedding dimension (384 for MiniLM-L6-v2)
742    dimension: usize,
743    fingerprint: Option<SemanticIndexFingerprint>,
744}
745
746/// Search result from a semantic query
747#[derive(Debug)]
748pub struct SemanticResult {
749    pub file: PathBuf,
750    pub name: String,
751    pub kind: SymbolKind,
752    pub start_line: u32,
753    pub end_line: u32,
754    pub exported: bool,
755    pub snippet: String,
756    pub score: f32,
757}
758
759impl SemanticIndex {
760    pub fn new() -> Self {
761        Self {
762            entries: Vec::new(),
763            file_mtimes: HashMap::new(),
764            dimension: DEFAULT_DIMENSION, // MiniLM-L6-v2 default
765            fingerprint: None,
766        }
767    }
768
769    /// Number of embedded symbol entries.
770    pub fn entry_count(&self) -> usize {
771        self.entries.len()
772    }
773
774    /// Human-readable status label for the index.
775    pub fn status_label(&self) -> &'static str {
776        if self.entries.is_empty() {
777            "empty"
778        } else {
779            "ready"
780        }
781    }
782
783    fn collect_chunks(
784        project_root: &Path,
785        files: &[PathBuf],
786    ) -> (Vec<SemanticChunk>, HashMap<PathBuf, SystemTime>) {
787        let mut parser = FileParser::new();
788        let mut chunks: Vec<SemanticChunk> = Vec::new();
789        let mut file_mtimes: HashMap<PathBuf, SystemTime> = HashMap::new();
790
791        for file in files {
792            let mtime = std::fs::metadata(file)
793                .and_then(|m| m.modified())
794                .unwrap_or(SystemTime::UNIX_EPOCH);
795            file_mtimes.insert(file.clone(), mtime);
796
797            let source = match std::fs::read_to_string(file) {
798                Ok(s) => s,
799                Err(_) => continue,
800            };
801
802            let symbols = match parser.extract_symbols(file) {
803                Ok(s) => s,
804                Err(_) => continue,
805            };
806            let file_chunks = symbols_to_chunks(file, &symbols, &source, project_root);
807            chunks.extend(file_chunks);
808        }
809
810        (chunks, file_mtimes)
811    }
812
813    fn build_from_chunks<F, P>(
814        chunks: Vec<SemanticChunk>,
815        file_mtimes: HashMap<PathBuf, SystemTime>,
816        embed_fn: &mut F,
817        max_batch_size: usize,
818        mut progress: Option<&mut P>,
819    ) -> Result<Self, String>
820    where
821        F: FnMut(Vec<String>) -> Result<Vec<Vec<f32>>, String>,
822        P: FnMut(usize, usize),
823    {
824        let total_chunks = chunks.len();
825
826        if chunks.is_empty() {
827            return Ok(Self {
828                entries: Vec::new(),
829                file_mtimes,
830                dimension: DEFAULT_DIMENSION,
831                fingerprint: None,
832            });
833        }
834
835        // Embed in batches
836        let mut entries: Vec<EmbeddingEntry> = Vec::with_capacity(chunks.len());
837        let mut expected_dimension: Option<usize> = None;
838        let batch_size = max_batch_size.max(1);
839        for batch_start in (0..chunks.len()).step_by(batch_size) {
840            let batch_end = (batch_start + batch_size).min(chunks.len());
841            let batch_texts: Vec<String> = chunks[batch_start..batch_end]
842                .iter()
843                .map(|c| c.embed_text.clone())
844                .collect();
845
846            let vectors = embed_fn(batch_texts)?;
847            validate_embedding_batch(&vectors, batch_end - batch_start, "embedding backend")?;
848
849            // Track consistent dimension across all batches
850            if let Some(dim) = vectors.first().map(|v| v.len()) {
851                match expected_dimension {
852                    None => expected_dimension = Some(dim),
853                    Some(expected) if dim != expected => {
854                        return Err(format!(
855                            "embedding dimension changed across batches: expected {expected}, got {dim}"
856                        ));
857                    }
858                    _ => {}
859                }
860            }
861
862            for (i, vector) in vectors.into_iter().enumerate() {
863                let chunk_idx = batch_start + i;
864                entries.push(EmbeddingEntry {
865                    chunk: chunks[chunk_idx].clone(),
866                    vector,
867                });
868            }
869
870            if let Some(callback) = progress.as_mut() {
871                callback(entries.len(), total_chunks);
872            }
873        }
874
875        let dimension = entries
876            .first()
877            .map(|e| e.vector.len())
878            .unwrap_or(DEFAULT_DIMENSION);
879
880        Ok(Self {
881            entries,
882            file_mtimes,
883            dimension,
884            fingerprint: None,
885        })
886    }
887
888    /// Build the semantic index from a set of files using the provided embedding function.
889    /// `embed_fn` takes a batch of texts and returns a batch of embedding vectors.
890    pub fn build<F>(
891        project_root: &Path,
892        files: &[PathBuf],
893        embed_fn: &mut F,
894        max_batch_size: usize,
895    ) -> Result<Self, String>
896    where
897        F: FnMut(Vec<String>) -> Result<Vec<Vec<f32>>, String>,
898    {
899        let (chunks, file_mtimes) = Self::collect_chunks(project_root, files);
900        Self::build_from_chunks(
901            chunks,
902            file_mtimes,
903            embed_fn,
904            max_batch_size,
905            Option::<&mut fn(usize, usize)>::None,
906        )
907    }
908
909    /// Build the semantic index and report embedding progress using entry counts.
910    pub fn build_with_progress<F, P>(
911        project_root: &Path,
912        files: &[PathBuf],
913        embed_fn: &mut F,
914        max_batch_size: usize,
915        progress: &mut P,
916    ) -> Result<Self, String>
917    where
918        F: FnMut(Vec<String>) -> Result<Vec<Vec<f32>>, String>,
919        P: FnMut(usize, usize),
920    {
921        let (chunks, file_mtimes) = Self::collect_chunks(project_root, files);
922        let total_chunks = chunks.len();
923        progress(0, total_chunks);
924        Self::build_from_chunks(
925            chunks,
926            file_mtimes,
927            embed_fn,
928            max_batch_size,
929            Some(progress),
930        )
931    }
932
933    /// Search the index with a query embedding, returning top-K results sorted by relevance
934    pub fn search(&self, query_vector: &[f32], top_k: usize) -> Vec<SemanticResult> {
935        if self.entries.is_empty() || query_vector.len() != self.dimension {
936            return Vec::new();
937        }
938
939        let mut scored: Vec<(f32, usize)> = self
940            .entries
941            .iter()
942            .enumerate()
943            .map(|(i, entry)| (cosine_similarity(query_vector, &entry.vector), i))
944            .collect();
945
946        // Sort descending by score
947        scored.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
948
949        scored
950            .into_iter()
951            .take(top_k)
952            .filter(|(score, _)| *score > 0.0)
953            .map(|(score, idx)| {
954                let entry = &self.entries[idx];
955                SemanticResult {
956                    file: entry.chunk.file.clone(),
957                    name: entry.chunk.name.clone(),
958                    kind: entry.chunk.kind.clone(),
959                    start_line: entry.chunk.start_line,
960                    end_line: entry.chunk.end_line,
961                    exported: entry.chunk.exported,
962                    snippet: entry.chunk.snippet.clone(),
963                    score,
964                }
965            })
966            .collect()
967    }
968
969    /// Number of indexed entries
970    pub fn len(&self) -> usize {
971        self.entries.len()
972    }
973
974    /// Check if a file needs re-indexing based on mtime
975    pub fn is_file_stale(&self, file: &Path) -> bool {
976        match self.file_mtimes.get(file) {
977            None => true,
978            Some(stored_mtime) => match fs::metadata(file).and_then(|m| m.modified()) {
979                Ok(current_mtime) => *stored_mtime != current_mtime,
980                Err(_) => true,
981            },
982        }
983    }
984
985    pub fn count_stale_files(&self) -> usize {
986        self.file_mtimes
987            .keys()
988            .filter(|path| self.is_file_stale(path))
989            .count()
990    }
991
992    /// Remove entries for a specific file
993    pub fn remove_file(&mut self, file: &Path) {
994        self.invalidate_file(file);
995    }
996
997    pub fn invalidate_file(&mut self, file: &Path) {
998        self.entries.retain(|e| e.chunk.file != file);
999        self.file_mtimes.remove(file);
1000    }
1001
1002    /// Get the embedding dimension
1003    pub fn dimension(&self) -> usize {
1004        self.dimension
1005    }
1006
1007    pub fn fingerprint(&self) -> Option<&SemanticIndexFingerprint> {
1008        self.fingerprint.as_ref()
1009    }
1010
1011    pub fn backend_label(&self) -> Option<&str> {
1012        self.fingerprint.as_ref().map(|f| f.backend.as_str())
1013    }
1014
1015    pub fn model_label(&self) -> Option<&str> {
1016        self.fingerprint.as_ref().map(|f| f.model.as_str())
1017    }
1018
1019    pub fn set_fingerprint(&mut self, fingerprint: SemanticIndexFingerprint) {
1020        self.fingerprint = Some(fingerprint);
1021    }
1022
1023    /// Write the semantic index to disk using atomic temp+rename pattern
1024    pub fn write_to_disk(&self, storage_dir: &Path, project_key: &str) {
1025        // Don't persist empty indexes — they would be loaded on next startup
1026        // and prevent a fresh build that might find files.
1027        if self.entries.is_empty() {
1028            log::info!("[aft] skipping semantic index persistence (0 entries)");
1029            return;
1030        }
1031        let dir = storage_dir.join("semantic").join(project_key);
1032        if let Err(e) = fs::create_dir_all(&dir) {
1033            log::warn!("[aft] failed to create semantic cache dir: {}", e);
1034            return;
1035        }
1036        let data_path = dir.join("semantic.bin");
1037        let tmp_path = dir.join("semantic.bin.tmp");
1038        let bytes = self.to_bytes();
1039        if let Err(e) = fs::write(&tmp_path, &bytes) {
1040            log::warn!("[aft] failed to write semantic index: {}", e);
1041            let _ = fs::remove_file(&tmp_path);
1042            return;
1043        }
1044        if let Err(e) = fs::rename(&tmp_path, &data_path) {
1045            log::warn!("[aft] failed to rename semantic index: {}", e);
1046            let _ = fs::remove_file(&tmp_path);
1047            return;
1048        }
1049        log::info!(
1050            "[aft] semantic index persisted: {} entries, {:.1} KB",
1051            self.entries.len(),
1052            bytes.len() as f64 / 1024.0
1053        );
1054    }
1055
1056    /// Read the semantic index from disk
1057    pub fn read_from_disk(
1058        storage_dir: &Path,
1059        project_key: &str,
1060        expected_fingerprint: Option<&str>,
1061    ) -> Option<Self> {
1062        let data_path = storage_dir
1063            .join("semantic")
1064            .join(project_key)
1065            .join("semantic.bin");
1066        let file_len = usize::try_from(fs::metadata(&data_path).ok()?.len()).ok()?;
1067        if file_len < HEADER_BYTES_V1 {
1068            log::warn!(
1069                "[aft] corrupt semantic index (too small: {} bytes), removing",
1070                file_len
1071            );
1072            let _ = fs::remove_file(&data_path);
1073            return None;
1074        }
1075
1076        let bytes = fs::read(&data_path).ok()?;
1077        let version = bytes[0];
1078        if version != SEMANTIC_INDEX_VERSION_V4 {
1079            log::info!(
1080                "[aft] cached semantic index version {} is older than {}, rebuilding",
1081                version,
1082                SEMANTIC_INDEX_VERSION_V4
1083            );
1084            let _ = fs::remove_file(&data_path);
1085            return None;
1086        }
1087        match Self::from_bytes(&bytes) {
1088            Ok(index) => {
1089                if index.entries.is_empty() {
1090                    log::info!("[aft] cached semantic index is empty, will rebuild");
1091                    let _ = fs::remove_file(&data_path);
1092                    return None;
1093                }
1094                if let Some(expected) = expected_fingerprint {
1095                    let matches = index
1096                        .fingerprint()
1097                        .map(|fingerprint| fingerprint.matches_expected(expected))
1098                        .unwrap_or(false);
1099                    if !matches {
1100                        log::info!("[aft] cached semantic index fingerprint mismatch, rebuilding");
1101                        let _ = fs::remove_file(&data_path);
1102                        return None;
1103                    }
1104                }
1105                log::info!(
1106                    "[aft] loaded semantic index from disk: {} entries",
1107                    index.entries.len()
1108                );
1109                Some(index)
1110            }
1111            Err(e) => {
1112                log::warn!("[aft] corrupt semantic index, rebuilding: {}", e);
1113                let _ = fs::remove_file(&data_path);
1114                None
1115            }
1116        }
1117    }
1118
1119    /// Serialize the index to bytes for disk persistence
1120    pub fn to_bytes(&self) -> Vec<u8> {
1121        let mut buf = Vec::new();
1122        let fingerprint_bytes = self.fingerprint.as_ref().and_then(|fingerprint| {
1123            let encoded = fingerprint.as_string();
1124            if encoded.is_empty() {
1125                None
1126            } else {
1127                Some(encoded.into_bytes())
1128            }
1129        });
1130
1131        // Header: version(1) + dimension(4) + entry_count(4) + fingerprint_len(4) + fingerprint
1132        //
1133        // V4 (v0.16.0+) is the single write format. Layout matches V3:
1134        //   - fingerprint is always represented (absent ⇒ fingerprint_len=0,
1135        //     no bytes follow). Uniform format simplifies the reader.
1136        //   - mtimes stored as secs(u64) + subsec_nanos(u32). Preserves full
1137        //     APFS/ext4/NTFS precision so staleness checks survive restart
1138        //     round-trips.
1139        //
1140        // V1/V2 remain readable for backward compatibility (see from_bytes).
1141        // V3 loads as the same format but is rejected on disk so snippets are
1142        // rebuilt once after the symbol-range bug fixed in v0.16.0.
1143        let version = SEMANTIC_INDEX_VERSION_V4;
1144        buf.push(version);
1145        buf.extend_from_slice(&(self.dimension as u32).to_le_bytes());
1146        buf.extend_from_slice(&(self.entries.len() as u32).to_le_bytes());
1147        let fp_bytes_ref: &[u8] = fingerprint_bytes.as_deref().unwrap_or(&[]);
1148        buf.extend_from_slice(&(fp_bytes_ref.len() as u32).to_le_bytes());
1149        buf.extend_from_slice(fp_bytes_ref);
1150
1151        // File mtime table: count(4) + entries
1152        // V3 layout per entry: path_len(4) + path + secs(8) + subsec_nanos(4)
1153        buf.extend_from_slice(&(self.file_mtimes.len() as u32).to_le_bytes());
1154        for (path, mtime) in &self.file_mtimes {
1155            let path_bytes = path.to_string_lossy().as_bytes().to_vec();
1156            buf.extend_from_slice(&(path_bytes.len() as u32).to_le_bytes());
1157            buf.extend_from_slice(&path_bytes);
1158            let duration = mtime
1159                .duration_since(SystemTime::UNIX_EPOCH)
1160                .unwrap_or_default();
1161            buf.extend_from_slice(&duration.as_secs().to_le_bytes());
1162            buf.extend_from_slice(&duration.subsec_nanos().to_le_bytes());
1163        }
1164
1165        // Entries: each is metadata + vector
1166        for entry in &self.entries {
1167            let c = &entry.chunk;
1168
1169            // File path
1170            let file_bytes = c.file.to_string_lossy().as_bytes().to_vec();
1171            buf.extend_from_slice(&(file_bytes.len() as u32).to_le_bytes());
1172            buf.extend_from_slice(&file_bytes);
1173
1174            // Name
1175            let name_bytes = c.name.as_bytes();
1176            buf.extend_from_slice(&(name_bytes.len() as u32).to_le_bytes());
1177            buf.extend_from_slice(name_bytes);
1178
1179            // Kind (1 byte)
1180            buf.push(symbol_kind_to_u8(&c.kind));
1181
1182            // Lines + exported
1183            buf.extend_from_slice(&(c.start_line as u32).to_le_bytes());
1184            buf.extend_from_slice(&(c.end_line as u32).to_le_bytes());
1185            buf.push(c.exported as u8);
1186
1187            // Snippet
1188            let snippet_bytes = c.snippet.as_bytes();
1189            buf.extend_from_slice(&(snippet_bytes.len() as u32).to_le_bytes());
1190            buf.extend_from_slice(snippet_bytes);
1191
1192            // Embed text
1193            let embed_bytes = c.embed_text.as_bytes();
1194            buf.extend_from_slice(&(embed_bytes.len() as u32).to_le_bytes());
1195            buf.extend_from_slice(embed_bytes);
1196
1197            // Vector (f32 array)
1198            for &val in &entry.vector {
1199                buf.extend_from_slice(&val.to_le_bytes());
1200            }
1201        }
1202
1203        buf
1204    }
1205
1206    /// Deserialize the index from bytes
1207    pub fn from_bytes(data: &[u8]) -> Result<Self, String> {
1208        let mut pos = 0;
1209
1210        if data.len() < HEADER_BYTES_V1 {
1211            return Err("data too short".to_string());
1212        }
1213
1214        let version = data[pos];
1215        pos += 1;
1216        if version != SEMANTIC_INDEX_VERSION_V1
1217            && version != SEMANTIC_INDEX_VERSION_V2
1218            && version != SEMANTIC_INDEX_VERSION_V3
1219            && version != SEMANTIC_INDEX_VERSION_V4
1220        {
1221            return Err(format!("unsupported version: {}", version));
1222        }
1223        // V2, V3, and V4 share the same header layout (V3/V4 only differ from
1224        // V2 in the per-mtime entry layout): version(1) + dimension(4) +
1225        // entry_count(4) + fingerprint_len(4) + fingerprint bytes.
1226        if (version == SEMANTIC_INDEX_VERSION_V2
1227            || version == SEMANTIC_INDEX_VERSION_V3
1228            || version == SEMANTIC_INDEX_VERSION_V4)
1229            && data.len() < HEADER_BYTES_V2
1230        {
1231            return Err("data too short for semantic index v2/v3/v4 header".to_string());
1232        }
1233
1234        let dimension = read_u32(data, &mut pos)? as usize;
1235        let entry_count = read_u32(data, &mut pos)? as usize;
1236        if dimension == 0 || dimension > MAX_DIMENSION {
1237            return Err(format!("invalid embedding dimension: {}", dimension));
1238        }
1239        if entry_count > MAX_ENTRIES {
1240            return Err(format!("too many semantic index entries: {}", entry_count));
1241        }
1242
1243        // Fingerprint handling:
1244        //   - V1: no fingerprint field at all.
1245        //   - V2: fingerprint_len + fingerprint bytes; always present (writer
1246        //     only emitted V2 when fingerprint was Some).
1247        //   - V3: fingerprint_len always present; fingerprint_len==0 ⇒ None.
1248        let has_fingerprint_field = version == SEMANTIC_INDEX_VERSION_V2
1249            || version == SEMANTIC_INDEX_VERSION_V3
1250            || version == SEMANTIC_INDEX_VERSION_V4;
1251        let fingerprint = if has_fingerprint_field {
1252            let fingerprint_len = read_u32(data, &mut pos)? as usize;
1253            if pos + fingerprint_len > data.len() {
1254                return Err("unexpected end of data reading fingerprint".to_string());
1255            }
1256            if fingerprint_len == 0 {
1257                None
1258            } else {
1259                let raw = String::from_utf8_lossy(&data[pos..pos + fingerprint_len]).to_string();
1260                pos += fingerprint_len;
1261                Some(
1262                    serde_json::from_str::<SemanticIndexFingerprint>(&raw)
1263                        .map_err(|error| format!("invalid semantic fingerprint: {error}"))?,
1264                )
1265            }
1266        } else {
1267            None
1268        };
1269
1270        // File mtimes
1271        let mtime_count = read_u32(data, &mut pos)? as usize;
1272        if mtime_count > MAX_ENTRIES {
1273            return Err(format!("too many semantic file mtimes: {}", mtime_count));
1274        }
1275
1276        let vector_bytes = entry_count
1277            .checked_mul(dimension)
1278            .and_then(|count| count.checked_mul(F32_BYTES))
1279            .ok_or_else(|| "semantic vector allocation overflow".to_string())?;
1280        if vector_bytes > data.len().saturating_sub(pos) {
1281            return Err("semantic index vectors exceed available data".to_string());
1282        }
1283
1284        let mut file_mtimes = HashMap::with_capacity(mtime_count);
1285        for _ in 0..mtime_count {
1286            let path = read_string(data, &mut pos)?;
1287            let secs = read_u64(data, &mut pos)?;
1288            // V3 persists subsec_nanos alongside secs so staleness checks
1289            // survive restart round-trips. V1/V2 load with 0 nanos, which
1290            // causes one rebuild on upgrade (they never matched live APFS
1291            // mtimes anyway — the bug v0.15.2 fixes). After that rebuild,
1292            // the cache is persisted as V3 and stabilises.
1293            let nanos =
1294                if version == SEMANTIC_INDEX_VERSION_V3 || version == SEMANTIC_INDEX_VERSION_V4 {
1295                    read_u32(data, &mut pos)?
1296                } else {
1297                    0
1298                };
1299            // Hardening against corrupt / maliciously crafted cache files
1300            // (v0.15.2). `Duration::new(secs, nanos)` can panic when the
1301            // nanosecond carry overflows the second counter, and
1302            // `SystemTime + Duration` can panic on carry past the platform's
1303            // upper bound. Explicit validation keeps a corrupted semantic.bin
1304            // from taking down the whole aft process.
1305            if nanos >= 1_000_000_000 {
1306                return Err(format!(
1307                    "invalid semantic mtime: nanos {} >= 1_000_000_000",
1308                    nanos
1309                ));
1310            }
1311            let duration = std::time::Duration::new(secs, nanos);
1312            let mtime = SystemTime::UNIX_EPOCH
1313                .checked_add(duration)
1314                .ok_or_else(|| {
1315                    format!(
1316                        "invalid semantic mtime: secs={} nanos={} overflows SystemTime",
1317                        secs, nanos
1318                    )
1319                })?;
1320            file_mtimes.insert(PathBuf::from(path), mtime);
1321        }
1322
1323        // Entries
1324        let mut entries = Vec::with_capacity(entry_count);
1325        for _ in 0..entry_count {
1326            let file = PathBuf::from(read_string(data, &mut pos)?);
1327            let name = read_string(data, &mut pos)?;
1328
1329            if pos >= data.len() {
1330                return Err("unexpected end of data".to_string());
1331            }
1332            let kind = u8_to_symbol_kind(data[pos]);
1333            pos += 1;
1334
1335            let start_line = read_u32(data, &mut pos)?;
1336            let end_line = read_u32(data, &mut pos)?;
1337
1338            if pos >= data.len() {
1339                return Err("unexpected end of data".to_string());
1340            }
1341            let exported = data[pos] != 0;
1342            pos += 1;
1343
1344            let snippet = read_string(data, &mut pos)?;
1345            let embed_text = read_string(data, &mut pos)?;
1346
1347            // Vector
1348            let vec_bytes = dimension
1349                .checked_mul(F32_BYTES)
1350                .ok_or_else(|| "semantic vector allocation overflow".to_string())?;
1351            if pos + vec_bytes > data.len() {
1352                return Err("unexpected end of data reading vector".to_string());
1353            }
1354            let mut vector = Vec::with_capacity(dimension);
1355            for _ in 0..dimension {
1356                let bytes = [data[pos], data[pos + 1], data[pos + 2], data[pos + 3]];
1357                vector.push(f32::from_le_bytes(bytes));
1358                pos += 4;
1359            }
1360
1361            entries.push(EmbeddingEntry {
1362                chunk: SemanticChunk {
1363                    file,
1364                    name,
1365                    kind,
1366                    start_line,
1367                    end_line,
1368                    exported,
1369                    embed_text,
1370                    snippet,
1371                },
1372                vector,
1373            });
1374        }
1375
1376        Ok(Self {
1377            entries,
1378            file_mtimes,
1379            dimension,
1380            fingerprint,
1381        })
1382    }
1383}
1384
1385/// Build enriched embedding text from a symbol with cAST-style context
1386fn build_embed_text(symbol: &Symbol, source: &str, file: &Path, project_root: &Path) -> String {
1387    let relative = file
1388        .strip_prefix(project_root)
1389        .unwrap_or(file)
1390        .to_string_lossy();
1391
1392    let kind_label = match &symbol.kind {
1393        SymbolKind::Function => "function",
1394        SymbolKind::Class => "class",
1395        SymbolKind::Method => "method",
1396        SymbolKind::Struct => "struct",
1397        SymbolKind::Interface => "interface",
1398        SymbolKind::Enum => "enum",
1399        SymbolKind::TypeAlias => "type",
1400        SymbolKind::Variable => "variable",
1401        SymbolKind::Heading => "heading",
1402    };
1403
1404    // Build: "file:relative/path kind:function name:validateAuth signature:fn validateAuth(token: &str) -> bool"
1405    let mut text = format!("file:{} kind:{} name:{}", relative, kind_label, symbol.name);
1406
1407    if let Some(sig) = &symbol.signature {
1408        text.push_str(&format!(" signature:{}", sig));
1409    }
1410
1411    // Add body snippet (first ~300 chars of symbol body)
1412    let lines: Vec<&str> = source.lines().collect();
1413    let start = (symbol.range.start_line as usize).min(lines.len());
1414    // range.end_line is inclusive 0-based; +1 makes it an exclusive slice bound.
1415    let end = (symbol.range.end_line as usize + 1).min(lines.len());
1416    if start < end {
1417        let body: String = lines[start..end]
1418            .iter()
1419            .take(15) // max 15 lines
1420            .copied()
1421            .collect::<Vec<&str>>()
1422            .join("\n");
1423        let snippet = if body.len() > 300 {
1424            format!("{}...", &body[..body.floor_char_boundary(300)])
1425        } else {
1426            body
1427        };
1428        text.push_str(&format!(" body:{}", snippet));
1429    }
1430
1431    text
1432}
1433
1434/// Build a display snippet from a symbol's source
1435fn build_snippet(symbol: &Symbol, source: &str) -> String {
1436    let lines: Vec<&str> = source.lines().collect();
1437    let start = (symbol.range.start_line as usize).min(lines.len());
1438    // range.end_line is inclusive 0-based; +1 makes it an exclusive slice bound.
1439    let end = (symbol.range.end_line as usize + 1).min(lines.len());
1440    if start < end {
1441        let snippet_lines: Vec<&str> = lines[start..end].iter().take(5).copied().collect();
1442        let mut snippet = snippet_lines.join("\n");
1443        if end - start > 5 {
1444            snippet.push_str("\n  ...");
1445        }
1446        if snippet.len() > 300 {
1447            snippet = format!("{}...", &snippet[..snippet.floor_char_boundary(300)]);
1448        }
1449        snippet
1450    } else {
1451        String::new()
1452    }
1453}
1454
1455/// Convert symbols to semantic chunks with enriched context
1456fn symbols_to_chunks(
1457    file: &Path,
1458    symbols: &[Symbol],
1459    source: &str,
1460    project_root: &Path,
1461) -> Vec<SemanticChunk> {
1462    let mut chunks = Vec::new();
1463
1464    for symbol in symbols {
1465        // Skip Markdown / HTML heading chunks: empirically they dominate result
1466        // lists even for code-shaped queries because heading prose embeds well.
1467        // Agents querying for code lose the actual matches under doc noise.
1468        // README/docs queries are still served by grep on the same files.
1469        if matches!(symbol.kind, SymbolKind::Heading) {
1470            continue;
1471        }
1472
1473        // Skip very small symbols (single-line variables, etc.)
1474        let line_count = symbol
1475            .range
1476            .end_line
1477            .saturating_sub(symbol.range.start_line)
1478            + 1;
1479        if line_count < 2 && !matches!(symbol.kind, SymbolKind::Variable) {
1480            continue;
1481        }
1482
1483        let embed_text = build_embed_text(symbol, source, file, project_root);
1484        let snippet = build_snippet(symbol, source);
1485
1486        chunks.push(SemanticChunk {
1487            file: file.to_path_buf(),
1488            name: symbol.name.clone(),
1489            kind: symbol.kind.clone(),
1490            start_line: symbol.range.start_line,
1491            end_line: symbol.range.end_line,
1492            exported: symbol.exported,
1493            embed_text,
1494            snippet,
1495        });
1496
1497        // Note: Nested symbols are handled separately by the outline system
1498        // Each symbol is indexed individually
1499    }
1500
1501    chunks
1502}
1503
1504/// Cosine similarity between two vectors
1505fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
1506    if a.len() != b.len() {
1507        return 0.0;
1508    }
1509
1510    let mut dot = 0.0f32;
1511    let mut norm_a = 0.0f32;
1512    let mut norm_b = 0.0f32;
1513
1514    for i in 0..a.len() {
1515        dot += a[i] * b[i];
1516        norm_a += a[i] * a[i];
1517        norm_b += b[i] * b[i];
1518    }
1519
1520    let denom = norm_a.sqrt() * norm_b.sqrt();
1521    if denom == 0.0 {
1522        0.0
1523    } else {
1524        dot / denom
1525    }
1526}
1527
1528// Serialization helpers
1529fn symbol_kind_to_u8(kind: &SymbolKind) -> u8 {
1530    match kind {
1531        SymbolKind::Function => 0,
1532        SymbolKind::Class => 1,
1533        SymbolKind::Method => 2,
1534        SymbolKind::Struct => 3,
1535        SymbolKind::Interface => 4,
1536        SymbolKind::Enum => 5,
1537        SymbolKind::TypeAlias => 6,
1538        SymbolKind::Variable => 7,
1539        SymbolKind::Heading => 8,
1540    }
1541}
1542
1543fn u8_to_symbol_kind(v: u8) -> SymbolKind {
1544    match v {
1545        0 => SymbolKind::Function,
1546        1 => SymbolKind::Class,
1547        2 => SymbolKind::Method,
1548        3 => SymbolKind::Struct,
1549        4 => SymbolKind::Interface,
1550        5 => SymbolKind::Enum,
1551        6 => SymbolKind::TypeAlias,
1552        7 => SymbolKind::Variable,
1553        _ => SymbolKind::Heading,
1554    }
1555}
1556
1557fn read_u32(data: &[u8], pos: &mut usize) -> Result<u32, String> {
1558    if *pos + 4 > data.len() {
1559        return Err("unexpected end of data reading u32".to_string());
1560    }
1561    let val = u32::from_le_bytes([data[*pos], data[*pos + 1], data[*pos + 2], data[*pos + 3]]);
1562    *pos += 4;
1563    Ok(val)
1564}
1565
1566fn read_u64(data: &[u8], pos: &mut usize) -> Result<u64, String> {
1567    if *pos + 8 > data.len() {
1568        return Err("unexpected end of data reading u64".to_string());
1569    }
1570    let bytes: [u8; 8] = data[*pos..*pos + 8].try_into().unwrap();
1571    *pos += 8;
1572    Ok(u64::from_le_bytes(bytes))
1573}
1574
1575fn read_string(data: &[u8], pos: &mut usize) -> Result<String, String> {
1576    let len = read_u32(data, pos)? as usize;
1577    if *pos + len > data.len() {
1578        return Err("unexpected end of data reading string".to_string());
1579    }
1580    let s = String::from_utf8_lossy(&data[*pos..*pos + len]).to_string();
1581    *pos += len;
1582    Ok(s)
1583}
1584
1585#[cfg(test)]
1586mod tests {
1587    use super::*;
1588    use crate::config::{SemanticBackend, SemanticBackendConfig};
1589    use std::io::{Read, Write};
1590    use std::net::TcpListener;
1591    use std::thread;
1592
1593    fn start_mock_http_server<F>(handler: F) -> (String, thread::JoinHandle<()>)
1594    where
1595        F: Fn(String, String, String) -> String + Send + 'static,
1596    {
1597        let listener = TcpListener::bind("127.0.0.1:0").expect("bind test server");
1598        let addr = listener.local_addr().expect("local addr");
1599        let handle = thread::spawn(move || {
1600            let (mut stream, _) = listener.accept().expect("accept request");
1601            let mut buf = Vec::new();
1602            let mut chunk = [0u8; 4096];
1603            let mut header_end = None;
1604            let mut content_length = 0usize;
1605            loop {
1606                let n = stream.read(&mut chunk).expect("read request");
1607                if n == 0 {
1608                    break;
1609                }
1610                buf.extend_from_slice(&chunk[..n]);
1611                if header_end.is_none() {
1612                    if let Some(pos) = buf.windows(4).position(|window| window == b"\r\n\r\n") {
1613                        header_end = Some(pos + 4);
1614                        let headers = String::from_utf8_lossy(&buf[..pos + 4]);
1615                        for line in headers.lines() {
1616                            if let Some(value) = line.strip_prefix("Content-Length:") {
1617                                content_length = value.trim().parse::<usize>().unwrap_or(0);
1618                            }
1619                        }
1620                    }
1621                }
1622                if let Some(end) = header_end {
1623                    if buf.len() >= end + content_length {
1624                        break;
1625                    }
1626                }
1627            }
1628
1629            let end = header_end.expect("header terminator");
1630            let request = String::from_utf8_lossy(&buf[..end]).to_string();
1631            let body = String::from_utf8_lossy(&buf[end..end + content_length]).to_string();
1632            let mut lines = request.lines();
1633            let request_line = lines.next().expect("request line").to_string();
1634            let path = request_line
1635                .split_whitespace()
1636                .nth(1)
1637                .expect("request path")
1638                .to_string();
1639            let response_body = handler(request_line, path, body);
1640            let response = format!(
1641                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1642                response_body.len(),
1643                response_body
1644            );
1645            stream
1646                .write_all(response.as_bytes())
1647                .expect("write response");
1648        });
1649
1650        (format!("http://{}", addr), handle)
1651    }
1652
1653    #[test]
1654    fn test_cosine_similarity_identical() {
1655        let a = vec![1.0, 0.0, 0.0];
1656        let b = vec![1.0, 0.0, 0.0];
1657        assert!((cosine_similarity(&a, &b) - 1.0).abs() < 0.001);
1658    }
1659
1660    #[test]
1661    fn test_cosine_similarity_orthogonal() {
1662        let a = vec![1.0, 0.0, 0.0];
1663        let b = vec![0.0, 1.0, 0.0];
1664        assert!(cosine_similarity(&a, &b).abs() < 0.001);
1665    }
1666
1667    #[test]
1668    fn test_cosine_similarity_opposite() {
1669        let a = vec![1.0, 0.0, 0.0];
1670        let b = vec![-1.0, 0.0, 0.0];
1671        assert!((cosine_similarity(&a, &b) + 1.0).abs() < 0.001);
1672    }
1673
1674    #[test]
1675    fn test_serialization_roundtrip() {
1676        let mut index = SemanticIndex::new();
1677        index.entries.push(EmbeddingEntry {
1678            chunk: SemanticChunk {
1679                file: PathBuf::from("/src/main.rs"),
1680                name: "handle_request".to_string(),
1681                kind: SymbolKind::Function,
1682                start_line: 10,
1683                end_line: 25,
1684                exported: true,
1685                embed_text: "file:src/main.rs kind:function name:handle_request".to_string(),
1686                snippet: "fn handle_request() {\n  // ...\n}".to_string(),
1687            },
1688            vector: vec![0.1, 0.2, 0.3, 0.4],
1689        });
1690        index.dimension = 4;
1691        index
1692            .file_mtimes
1693            .insert(PathBuf::from("/src/main.rs"), SystemTime::UNIX_EPOCH);
1694        index.set_fingerprint(SemanticIndexFingerprint {
1695            backend: "fastembed".to_string(),
1696            model: "all-MiniLM-L6-v2".to_string(),
1697            base_url: FALLBACK_BACKEND.to_string(),
1698            dimension: 4,
1699        });
1700
1701        let bytes = index.to_bytes();
1702        let restored = SemanticIndex::from_bytes(&bytes).unwrap();
1703
1704        assert_eq!(restored.entries.len(), 1);
1705        assert_eq!(restored.entries[0].chunk.name, "handle_request");
1706        assert_eq!(restored.entries[0].vector, vec![0.1, 0.2, 0.3, 0.4]);
1707        assert_eq!(restored.dimension, 4);
1708        assert_eq!(restored.backend_label(), Some("fastembed"));
1709        assert_eq!(restored.model_label(), Some("all-MiniLM-L6-v2"));
1710    }
1711
1712    #[test]
1713    fn test_search_top_k() {
1714        let mut index = SemanticIndex::new();
1715        index.dimension = 3;
1716
1717        // Add entries with known vectors
1718        for (i, name) in ["auth", "database", "handler"].iter().enumerate() {
1719            let mut vec = vec![0.0f32; 3];
1720            vec[i] = 1.0; // orthogonal vectors
1721            index.entries.push(EmbeddingEntry {
1722                chunk: SemanticChunk {
1723                    file: PathBuf::from("/src/lib.rs"),
1724                    name: name.to_string(),
1725                    kind: SymbolKind::Function,
1726                    start_line: (i * 10 + 1) as u32,
1727                    end_line: (i * 10 + 5) as u32,
1728                    exported: true,
1729                    embed_text: format!("kind:function name:{}", name),
1730                    snippet: format!("fn {}() {{}}", name),
1731                },
1732                vector: vec,
1733            });
1734        }
1735
1736        // Query aligned with "auth" (index 0)
1737        let query = vec![0.9, 0.1, 0.0];
1738        let results = index.search(&query, 2);
1739
1740        assert_eq!(results.len(), 2);
1741        assert_eq!(results[0].name, "auth"); // highest score
1742        assert!(results[0].score > results[1].score);
1743    }
1744
1745    #[test]
1746    fn test_empty_index_search() {
1747        let index = SemanticIndex::new();
1748        let results = index.search(&[0.1, 0.2, 0.3], 10);
1749        assert!(results.is_empty());
1750    }
1751
1752    #[test]
1753    fn single_line_symbol_builds_non_empty_snippet() {
1754        let symbol = Symbol {
1755            name: "answer".to_string(),
1756            kind: SymbolKind::Variable,
1757            range: crate::symbols::Range {
1758                start_line: 0,
1759                start_col: 0,
1760                end_line: 0,
1761                end_col: 24,
1762            },
1763            signature: Some("const answer = 42".to_string()),
1764            scope_chain: Vec::new(),
1765            exported: true,
1766            parent: None,
1767        };
1768        let source = "export const answer = 42;\n";
1769
1770        let snippet = build_snippet(&symbol, source);
1771
1772        assert_eq!(snippet, "export const answer = 42;");
1773    }
1774
1775    #[test]
1776    fn rejects_oversized_dimension_during_deserialization() {
1777        let mut bytes = Vec::new();
1778        bytes.push(1u8);
1779        bytes.extend_from_slice(&((MAX_DIMENSION as u32) + 1).to_le_bytes());
1780        bytes.extend_from_slice(&0u32.to_le_bytes());
1781        bytes.extend_from_slice(&0u32.to_le_bytes());
1782
1783        assert!(SemanticIndex::from_bytes(&bytes).is_err());
1784    }
1785
1786    #[test]
1787    fn rejects_oversized_entry_count_during_deserialization() {
1788        let mut bytes = Vec::new();
1789        bytes.push(1u8);
1790        bytes.extend_from_slice(&(DEFAULT_DIMENSION as u32).to_le_bytes());
1791        bytes.extend_from_slice(&((MAX_ENTRIES as u32) + 1).to_le_bytes());
1792        bytes.extend_from_slice(&0u32.to_le_bytes());
1793
1794        assert!(SemanticIndex::from_bytes(&bytes).is_err());
1795    }
1796
1797    #[test]
1798    fn invalidate_file_removes_entries_and_mtime() {
1799        let target = PathBuf::from("/src/main.rs");
1800        let mut index = SemanticIndex::new();
1801        index.entries.push(EmbeddingEntry {
1802            chunk: SemanticChunk {
1803                file: target.clone(),
1804                name: "main".to_string(),
1805                kind: SymbolKind::Function,
1806                start_line: 0,
1807                end_line: 1,
1808                exported: false,
1809                embed_text: "main".to_string(),
1810                snippet: "fn main() {}".to_string(),
1811            },
1812            vector: vec![1.0; DEFAULT_DIMENSION],
1813        });
1814        index
1815            .file_mtimes
1816            .insert(target.clone(), SystemTime::UNIX_EPOCH);
1817
1818        index.invalidate_file(&target);
1819
1820        assert!(index.entries.is_empty());
1821        assert!(!index.file_mtimes.contains_key(&target));
1822    }
1823
1824    #[test]
1825    fn detects_missing_onnx_runtime_from_dynamic_load_error() {
1826        let message = "Failed to load ONNX Runtime shared library libonnxruntime.dylib via dlopen: no such file";
1827
1828        assert!(is_onnx_runtime_unavailable(message));
1829    }
1830
1831    #[test]
1832    fn formats_missing_onnx_runtime_with_install_hint() {
1833        let message = format_embedding_init_error(
1834            "Failed to load ONNX Runtime shared library libonnxruntime.so via dlopen: no such file",
1835        );
1836
1837        assert!(message.starts_with("ONNX Runtime not found. Install via:"));
1838        assert!(message.contains("Original error:"));
1839    }
1840
1841    #[test]
1842    fn openai_compatible_backend_embeds_with_mock_server() {
1843        let (base_url, handle) = start_mock_http_server(|request_line, path, _body| {
1844            assert!(request_line.starts_with("POST "));
1845            assert_eq!(path, "/v1/embeddings");
1846            "{\"data\":[{\"embedding\":[0.1,0.2,0.3],\"index\":0},{\"embedding\":[0.4,0.5,0.6],\"index\":1}]}".to_string()
1847        });
1848
1849        let config = SemanticBackendConfig {
1850            backend: SemanticBackend::OpenAiCompatible,
1851            model: "test-embedding".to_string(),
1852            base_url: Some(base_url),
1853            api_key_env: None,
1854            timeout_ms: 5_000,
1855            max_batch_size: 64,
1856        };
1857
1858        let mut model = SemanticEmbeddingModel::from_config(&config).unwrap();
1859        let vectors = model
1860            .embed(vec!["hello".to_string(), "world".to_string()])
1861            .unwrap();
1862
1863        assert_eq!(vectors, vec![vec![0.1, 0.2, 0.3], vec![0.4, 0.5, 0.6]]);
1864        handle.join().unwrap();
1865    }
1866
1867    #[test]
1868    fn ollama_backend_embeds_with_mock_server() {
1869        let (base_url, handle) = start_mock_http_server(|request_line, path, _body| {
1870            assert!(request_line.starts_with("POST "));
1871            assert_eq!(path, "/api/embed");
1872            "{\"embeddings\":[[0.7,0.8,0.9],[1.0,1.1,1.2]]}".to_string()
1873        });
1874
1875        let config = SemanticBackendConfig {
1876            backend: SemanticBackend::Ollama,
1877            model: "embeddinggemma".to_string(),
1878            base_url: Some(base_url),
1879            api_key_env: None,
1880            timeout_ms: 5_000,
1881            max_batch_size: 64,
1882        };
1883
1884        let mut model = SemanticEmbeddingModel::from_config(&config).unwrap();
1885        let vectors = model
1886            .embed(vec!["hello".to_string(), "world".to_string()])
1887            .unwrap();
1888
1889        assert_eq!(vectors, vec![vec![0.7, 0.8, 0.9], vec![1.0, 1.1, 1.2]]);
1890        handle.join().unwrap();
1891    }
1892
1893    #[test]
1894    fn read_from_disk_rejects_fingerprint_mismatch() {
1895        let storage = tempfile::tempdir().unwrap();
1896        let project_key = "proj";
1897
1898        let mut index = SemanticIndex::new();
1899        index.entries.push(EmbeddingEntry {
1900            chunk: SemanticChunk {
1901                file: PathBuf::from("/src/main.rs"),
1902                name: "handle_request".to_string(),
1903                kind: SymbolKind::Function,
1904                start_line: 10,
1905                end_line: 25,
1906                exported: true,
1907                embed_text: "file:src/main.rs kind:function name:handle_request".to_string(),
1908                snippet: "fn handle_request() {}".to_string(),
1909            },
1910            vector: vec![0.1, 0.2, 0.3],
1911        });
1912        index.dimension = 3;
1913        index
1914            .file_mtimes
1915            .insert(PathBuf::from("/src/main.rs"), SystemTime::UNIX_EPOCH);
1916        index.set_fingerprint(SemanticIndexFingerprint {
1917            backend: "openai_compatible".to_string(),
1918            model: "test-embedding".to_string(),
1919            base_url: "http://127.0.0.1:1234/v1".to_string(),
1920            dimension: 3,
1921        });
1922        index.write_to_disk(storage.path(), project_key);
1923
1924        let matching = index.fingerprint().unwrap().as_string();
1925        assert!(
1926            SemanticIndex::read_from_disk(storage.path(), project_key, Some(&matching)).is_some()
1927        );
1928
1929        let mismatched = SemanticIndexFingerprint {
1930            backend: "ollama".to_string(),
1931            model: "embeddinggemma".to_string(),
1932            base_url: "http://127.0.0.1:11434".to_string(),
1933            dimension: 3,
1934        }
1935        .as_string();
1936        assert!(
1937            SemanticIndex::read_from_disk(storage.path(), project_key, Some(&mismatched)).is_none()
1938        );
1939    }
1940
1941    #[test]
1942    fn read_from_disk_rejects_v3_cache_for_snippet_rebuild() {
1943        let storage = tempfile::tempdir().unwrap();
1944        let project_key = "proj-v3";
1945        let dir = storage.path().join("semantic").join(project_key);
1946        fs::create_dir_all(&dir).unwrap();
1947
1948        let mut index = SemanticIndex::new();
1949        index.entries.push(EmbeddingEntry {
1950            chunk: SemanticChunk {
1951                file: PathBuf::from("/src/main.rs"),
1952                name: "handle_request".to_string(),
1953                kind: SymbolKind::Function,
1954                start_line: 0,
1955                end_line: 0,
1956                exported: true,
1957                embed_text: "file:src/main.rs kind:function name:handle_request".to_string(),
1958                snippet: "fn handle_request() {}".to_string(),
1959            },
1960            vector: vec![0.1, 0.2, 0.3],
1961        });
1962        index.dimension = 3;
1963        index
1964            .file_mtimes
1965            .insert(PathBuf::from("/src/main.rs"), SystemTime::UNIX_EPOCH);
1966        let fingerprint = SemanticIndexFingerprint {
1967            backend: "fastembed".to_string(),
1968            model: "test".to_string(),
1969            base_url: FALLBACK_BACKEND.to_string(),
1970            dimension: 3,
1971        };
1972        index.set_fingerprint(fingerprint.clone());
1973
1974        let mut bytes = index.to_bytes();
1975        bytes[0] = SEMANTIC_INDEX_VERSION_V3;
1976        fs::write(dir.join("semantic.bin"), bytes).unwrap();
1977
1978        assert!(SemanticIndex::read_from_disk(
1979            storage.path(),
1980            project_key,
1981            Some(&fingerprint.as_string())
1982        )
1983        .is_none());
1984        assert!(!dir.join("semantic.bin").exists());
1985    }
1986
1987    fn make_symbol(kind: SymbolKind, name: &str, start: u32, end: u32) -> crate::symbols::Symbol {
1988        crate::symbols::Symbol {
1989            name: name.to_string(),
1990            kind,
1991            range: crate::symbols::Range {
1992                start_line: start,
1993                start_col: 0,
1994                end_line: end,
1995                end_col: 0,
1996            },
1997            signature: None,
1998            scope_chain: Vec::new(),
1999            exported: false,
2000            parent: None,
2001        }
2002    }
2003
2004    /// Heading symbols (Markdown / HTML headings) must NOT be indexed —
2005    /// they overwhelmingly dominated semantic results even on code-shaped
2006    /// queries because heading prose embeds far more strongly than code
2007    /// chunks. Skipping headings keeps aft_search a code-finder.
2008    #[test]
2009    fn symbols_to_chunks_skips_heading_symbols() {
2010        let project_root = PathBuf::from("/proj");
2011        let file = project_root.join("README.md");
2012        let source = "# Title\n\nbody text\n\n## Section\n\nmore text\n";
2013
2014        let symbols = vec![
2015            make_symbol(SymbolKind::Heading, "Title", 0, 2),
2016            make_symbol(SymbolKind::Heading, "Section", 4, 6),
2017        ];
2018
2019        let chunks = symbols_to_chunks(&file, &symbols, source, &project_root);
2020        assert!(
2021            chunks.is_empty(),
2022            "Heading symbols must be filtered out before embedding; got {} chunk(s)",
2023            chunks.len()
2024        );
2025    }
2026
2027    /// Code symbols (functions, classes, methods, structs, etc.) must still
2028    /// be indexed alongside the heading skip — otherwise we'd starve the
2029    /// index entirely.
2030    #[test]
2031    fn symbols_to_chunks_keeps_code_symbols_alongside_skipped_headings() {
2032        let project_root = PathBuf::from("/proj");
2033        let file = project_root.join("src/lib.rs");
2034        let source = "pub fn handle_request() -> bool {\n    true\n}\n";
2035
2036        let symbols = vec![
2037            // A heading mixed in (e.g. from a doc comment block elsewhere).
2038            make_symbol(SymbolKind::Heading, "doc heading", 0, 1),
2039            make_symbol(SymbolKind::Function, "handle_request", 0, 2),
2040            make_symbol(SymbolKind::Struct, "AuthService", 4, 6),
2041        ];
2042
2043        let chunks = symbols_to_chunks(&file, &symbols, source, &project_root);
2044        assert_eq!(
2045            chunks.len(),
2046            2,
2047            "Expected 2 code chunks (Function + Struct), got {}",
2048            chunks.len()
2049        );
2050        let names: Vec<&str> = chunks.iter().map(|c| c.name.as_str()).collect();
2051        assert!(names.contains(&"handle_request"));
2052        assert!(names.contains(&"AuthService"));
2053        assert!(
2054            !names.contains(&"doc heading"),
2055            "Heading symbol leaked into chunks: {names:?}"
2056        );
2057    }
2058}