Skip to main content

aft/
semantic_index.rs

1use crate::cache_freshness::{self, FileFreshness, FreshnessVerdict};
2use crate::config::{
3    SemanticBackend, SemanticBackendConfig, DEFAULT_SEMANTIC_QUERY_TIMEOUT_MS,
4    MAX_SEMANTIC_QUERY_TIMEOUT_MS, MIN_SEMANTIC_QUERY_TIMEOUT_MS,
5};
6use crate::fs_lock;
7use crate::parser::{detect_language, extract_symbols_from_tree, parse_source_with_cached_parser};
8use crate::search_index::{cache_relative_path, cached_path_under_root};
9use crate::symbols::{Symbol, SymbolKind};
10use crate::{slog_info, slog_warn};
11
12use crate::local_embed::LocalEmbedder;
13use rayon::prelude::*;
14use reqwest::blocking::Client;
15use serde::{Deserialize, Serialize};
16use std::collections::{HashMap, HashSet, VecDeque};
17use std::env;
18use std::error::Error;
19use std::fmt::Display;
20use std::fs;
21use std::io::{self, BufReader, BufWriter, Cursor, Read, Write};
22use std::path::{Path, PathBuf};
23use std::sync::atomic::{AtomicUsize, Ordering};
24use std::sync::{Arc, Mutex, OnceLock, Weak};
25use std::time::{Duration, Instant, SystemTime};
26use url::Url;
27
28const DEFAULT_DIMENSION: usize = 384;
29const MAX_ENTRIES: usize = 1_000_000;
30// Covers high-dimensional backends such as OpenAI text-embedding-3-large (3072)
31// and common local models (4096) while keeping a bounded supported shape.
32const MAX_DIMENSION: usize = 4096;
33const F32_BYTES: usize = std::mem::size_of::<f32>();
34const HEADER_BYTES_V1: usize = 9;
35const HEADER_BYTES_V2: usize = 13;
36const ONNX_RUNTIME_INSTALL_HINT: &str =
37    "ONNX Runtime not found. Install via: brew install onnxruntime (macOS), \
38     apt install libonnxruntime (Linux), or place onnxruntime.dll in your PATH (Windows). \
39     AFT can auto-download ONNX Runtime — run `npx @cortexkit/aft doctor` to diagnose.";
40
41const SEMANTIC_INDEX_VERSION_V1: u8 = 1;
42const SEMANTIC_INDEX_VERSION_V2: u8 = 2;
43/// V3 adds subsec_nanos to the file-mtime table so staleness detection survives
44/// restart round-trips on filesystems with subsecond mtime precision (APFS,
45/// ext4 with nsec, NTFS). V1/V2 persisted whole-second mtimes only, which
46/// caused every restart to flag ~99% of files as stale and re-embed them.
47const SEMANTIC_INDEX_VERSION_V3: u8 = 3;
48/// V4 keeps the V3 on-disk layout but rebuilds persisted snippets once after
49/// fixing symbol ranges that were incorrectly treated as 1-based.
50const SEMANTIC_INDEX_VERSION_V4: u8 = 4;
51/// V5 adds file sizes to the file metadata table so incremental staleness
52/// detection can catch content changes even when mtime precision misses them.
53const SEMANTIC_INDEX_VERSION_V5: u8 = 5;
54/// V6 stores paths relative to project_root and adds content hashes.
55const SEMANTIC_INDEX_VERSION_V6: u8 = 6;
56/// V7 adds qualified symbol names for ranking metadata without changing embeddings.
57const SEMANTIC_INDEX_VERSION_V7: u8 = 7;
58const DEFAULT_OPENAI_EMBEDDING_PATH: &str = "/embeddings";
59const DEFAULT_OLLAMA_EMBEDDING_PATH: &str = "/api/embed";
60// Build/refresh embedding requests keep a larger budget because they run on
61// background workers and often batch many texts through a cold local backend.
62const DEFAULT_OPENAI_EMBEDDING_TIMEOUT_MS: u64 = 25_000;
63const DEFAULT_MAX_BATCH_SIZE: usize = 64;
64const QUERY_EMBEDDING_CACHE_CAP: usize = 1_000;
65const FALLBACK_BACKEND: &str = "none";
66const EMBEDDING_REQUEST_MAX_ATTEMPTS: usize = 3;
67const EMBEDDING_REQUEST_BACKOFF_MS: [u64; 2] = [500, 1_000];
68static SEMANTIC_LOCK_ACQUIRE_MUTEX: Mutex<()> = Mutex::new(());
69
70/// Test-only probe counter for the managed-ONNX resolver (see
71/// `find_managed_onnx_runtime`). Counts storage-tree reads so a negative-control
72/// test can assert a pre-set ORT_DYLIB_PATH short-circuits the resolver.
73#[cfg(test)]
74static MANAGED_ORT_PROBE_READS: AtomicUsize = AtomicUsize::new(0);
75
76/// Per-query request policy kept separate from the background build timeout.
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub struct QueryBudget {
79    timeout_ms: u64,
80}
81
82impl QueryBudget {
83    pub fn from_config(config: &SemanticBackendConfig) -> Self {
84        let configured = if config.query_timeout_ms == 0 {
85            DEFAULT_SEMANTIC_QUERY_TIMEOUT_MS
86        } else {
87            config.query_timeout_ms
88        };
89        Self {
90            timeout_ms: configured
91                .clamp(MIN_SEMANTIC_QUERY_TIMEOUT_MS, MAX_SEMANTIC_QUERY_TIMEOUT_MS),
92        }
93    }
94
95    #[cfg(test)]
96    fn timeout_ms(self) -> u64 {
97        self.timeout_ms
98    }
99}
100
101#[derive(Debug, Clone, Copy)]
102enum EmbeddingRequestPolicy {
103    Build,
104    Query(QueryBudget),
105}
106
107impl EmbeddingRequestPolicy {
108    fn max_attempts(self) -> usize {
109        match self {
110            Self::Build => EMBEDDING_REQUEST_MAX_ATTEMPTS,
111            Self::Query(_) => 1,
112        }
113    }
114
115    fn request_timeout(self) -> Option<Duration> {
116        match self {
117            Self::Build => None,
118            Self::Query(budget) => Some(Duration::from_millis(budget.timeout_ms)),
119        }
120    }
121}
122
123pub struct SemanticIndexLock {
124    _guard: Option<fs_lock::LockGuard>,
125}
126
127impl SemanticIndexLock {
128    pub fn acquire(
129        storage_dir: &Path,
130        project_key: &str,
131        project_root: &Path,
132    ) -> std::io::Result<Self> {
133        let dir = storage_dir.join("semantic").join(project_key);
134        let path = dir.join("cache.lock");
135        let access = crate::root_cache::ArtifactAccess::for_root(project_root);
136        if !access.allows_write(project_key, &path) {
137            return Ok(Self { _guard: None });
138        }
139        fs::create_dir_all(&dir)?;
140        let _acquire_guard = SEMANTIC_LOCK_ACQUIRE_MUTEX
141            .lock()
142            .map_err(|_| std::io::Error::other("semantic cache lock acquisition mutex poisoned"))?;
143        fs_lock::try_acquire(&path, Duration::from_secs(2))
144            .map(|guard| Self {
145                _guard: Some(guard),
146            })
147            .map_err(|error| match error {
148                fs_lock::AcquireError::Timeout => {
149                    std::io::Error::other("timed out acquiring semantic cache lock")
150                }
151                fs_lock::AcquireError::Io(error) => error,
152            })
153    }
154}
155
156#[derive(Debug, Clone, Serialize, Deserialize)]
157pub struct SemanticIndexFingerprint {
158    pub backend: String,
159    pub model: String,
160    #[serde(default)]
161    pub base_url: String,
162    pub dimension: usize,
163    #[serde(default = "default_chunking_version")]
164    pub chunking_version: u32,
165}
166
167fn default_chunking_version() -> u32 {
168    2
169}
170
171impl SemanticIndexFingerprint {
172    fn from_config(config: &SemanticBackendConfig, dimension: usize) -> Self {
173        // Use normalized URL for fingerprinting so cosmetic differences
174        // (e.g. "http://host/v1" vs "http://host/v1/") don't cause rebuilds.
175        let base_url = config
176            .base_url
177            .as_ref()
178            .and_then(|u| normalize_base_url(u).ok())
179            .unwrap_or_else(|| FALLBACK_BACKEND.to_string());
180        Self {
181            backend: config.backend.as_str().to_string(),
182            model: config.model.clone(),
183            base_url,
184            dimension,
185            chunking_version: default_chunking_version(),
186        }
187    }
188
189    pub fn as_string(&self) -> String {
190        serde_json::to_string(self).unwrap_or_else(|_| String::new())
191    }
192
193    pub(crate) fn for_config_dimension(config: &SemanticBackendConfig, dimension: usize) -> Self {
194        Self::from_config(config, dimension)
195    }
196
197    fn matches_expected(&self, expected: &str) -> bool {
198        let encoded = self.as_string();
199        !encoded.is_empty() && encoded == expected
200    }
201}
202
203fn redacted_base_url_host(base_url: &str) -> String {
204    if base_url.is_empty() {
205        return "<empty>".to_string();
206    }
207    if base_url == FALLBACK_BACKEND {
208        return FALLBACK_BACKEND.to_string();
209    }
210
211    match Url::parse(base_url) {
212        Ok(parsed) => {
213            let host = parsed.host_str().unwrap_or("<missing-host>");
214            match parsed.port() {
215                Some(port) => format!("{host}:{port}"),
216                None => host.to_string(),
217            }
218        }
219        Err(_) => "<invalid>".to_string(),
220    }
221}
222
223fn format_fingerprint_mismatch_details(
224    cached: Option<&SemanticIndexFingerprint>,
225    current: &SemanticIndexFingerprint,
226) -> String {
227    let Some(cached) = cached else {
228        return format!(
229            "cached fingerprint missing; current backend kind={}, model={}, base_url host={}, dimension={}, chunking version={}",
230            current.backend,
231            current.model,
232            redacted_base_url_host(&current.base_url),
233            current.dimension,
234            current.chunking_version,
235        );
236    };
237
238    let mut diffs = Vec::new();
239    if cached.backend != current.backend {
240        diffs.push(format!(
241            "backend kind cached={} current={}",
242            cached.backend, current.backend
243        ));
244    }
245    if cached.model != current.model {
246        diffs.push(format!(
247            "model cached={} current={}",
248            cached.model, current.model
249        ));
250    }
251    if cached.base_url != current.base_url {
252        let cached_host = redacted_base_url_host(&cached.base_url);
253        let current_host = redacted_base_url_host(&current.base_url);
254        if cached_host == current_host {
255            diffs.push(format!(
256                "base_url host cached={} current={} (credentials/path redacted)",
257                cached_host, current_host
258            ));
259        } else {
260            diffs.push(format!(
261                "base_url host cached={} current={}",
262                cached_host, current_host
263            ));
264        }
265    }
266    if cached.dimension != current.dimension {
267        diffs.push(format!(
268            "dimension cached={} current={}",
269            cached.dimension, current.dimension
270        ));
271    }
272    if cached.chunking_version != current.chunking_version {
273        diffs.push(format!(
274            "chunking version cached={} current={}",
275            cached.chunking_version, current.chunking_version
276        ));
277    }
278
279    if diffs.is_empty() {
280        "fingerprint strings differ but parsed fields match".to_string()
281    } else {
282        diffs.join("; ")
283    }
284}
285
286fn log_fingerprint_mismatch(cached: Option<&SemanticIndexFingerprint>, expected: &str) {
287    match serde_json::from_str::<SemanticIndexFingerprint>(expected) {
288        Ok(current) => slog_warn!(
289            "cached semantic index fingerprint mismatch, rebuilding without deleting the shared artifact: {}",
290            format_fingerprint_mismatch_details(cached, &current)
291        ),
292        Err(error) => slog_warn!(
293            "cached semantic index fingerprint mismatch, rebuilding without deleting the shared artifact: could not parse current fingerprint: {}",
294            error
295        ),
296    }
297}
298
299enum SemanticEmbeddingEngine {
300    /// Local ONNX embedder (all-MiniLM-L6-v2 via raw `ort`). The config-facing
301    /// backend string stays "fastembed" for index-fingerprint compatibility.
302    Local(LocalEmbedder),
303    OpenAiCompatible {
304        client: Client,
305        model: String,
306        base_url: String,
307        api_key: Option<String>,
308    },
309    Ollama {
310        client: Client,
311        model: String,
312        base_url: String,
313    },
314}
315
316pub struct SemanticEmbeddingModel {
317    backend: SemanticBackend,
318    model: String,
319    base_url: Option<String>,
320    timeout_ms: u64,
321    max_batch_size: usize,
322    dimension: Option<usize>,
323    engine: SemanticEmbeddingEngine,
324    query_embedding_cache: HashMap<String, Vec<f32>>,
325    query_embedding_cache_order: VecDeque<String>,
326    query_embedding_cache_hits: u64,
327    query_embedding_cache_misses: u64,
328}
329
330pub type EmbeddingModel = SemanticEmbeddingModel;
331
332fn validate_embedding_batch(
333    vectors: &[Vec<f32>],
334    expected_count: usize,
335    context: &str,
336) -> Result<(), String> {
337    if expected_count > 0 && vectors.is_empty() {
338        return Err(format!(
339            "{context} returned no vectors for {expected_count} inputs"
340        ));
341    }
342
343    if vectors.len() != expected_count {
344        return Err(format!(
345            "{context} returned {} vectors for {} inputs",
346            vectors.len(),
347            expected_count
348        ));
349    }
350
351    let Some(first_vector) = vectors.first() else {
352        return Ok(());
353    };
354    let expected_dimension = first_vector.len();
355    validate_embedding_dimension(expected_dimension)
356        .map_err(|error| format!("{context} returned {error}"))?;
357    for (index, vector) in vectors.iter().enumerate() {
358        if vector.len() != expected_dimension {
359            return Err(format!(
360                "{context} returned inconsistent embedding dimensions: vector 0 has length {expected_dimension}, vector {index} has length {}",
361                vector.len()
362            ));
363        }
364    }
365
366    Ok(())
367}
368
369fn validate_embedding_dimension(dimension: usize) -> Result<(), String> {
370    if dimension == 0 || dimension > MAX_DIMENSION {
371        return Err(format!(
372            "invalid embedding dimension: {dimension}; supported range is 1..={MAX_DIMENSION}"
373        ));
374    }
375
376    Ok(())
377}
378
379/// Normalize a base URL: validate scheme and strip trailing slash.
380/// Does NOT perform SSRF/private-IP validation — call
381/// `validate_base_url_no_ssrf` separately when processing user-supplied config.
382fn normalize_base_url(raw: &str) -> Result<String, String> {
383    let parsed = Url::parse(raw).map_err(|error| format!("invalid base_url '{raw}': {error}"))?;
384    let scheme = parsed.scheme();
385    if scheme != "http" && scheme != "https" {
386        return Err(format!(
387            "unsupported URL scheme '{}' — only http:// and https:// are allowed",
388            scheme
389        ));
390    }
391    Ok(parsed.to_string().trim_end_matches('/').to_string())
392}
393
394/// Validate that a base URL does not point to a private/loopback address.
395/// Call this on user-supplied config (at configure time) to prevent SSRF.
396/// Not called for programmatically constructed configs (e.g. tests).
397///
398/// **Loopback is allowed.** Self-hosted embedding backends (e.g. Ollama at
399/// `http://127.0.0.1:11434`) are a primary use case for `aft_search`. Loopback
400/// addresses by definition cannot be exploited as SSRF targets — they only
401/// reach services on the same machine. Allowing loopback unblocks Ollama at its
402/// default config without opening up SSRF to LAN/intranet services, which
403/// remain rejected.
404///
405/// **mDNS `.local` is rejected.** mDNS hostnames typically resolve to LAN
406/// devices (printers, homelab servers); rejecting them before DNS lookup keeps
407/// the SSRF guard meaningful for non-loopback private networks.
408pub fn validate_base_url_no_ssrf(raw: &str) -> Result<(), String> {
409    use std::net::{IpAddr, ToSocketAddrs};
410
411    let parsed = Url::parse(raw).map_err(|error| format!("invalid base_url '{raw}': {error}"))?;
412
413    let host = parsed.host_str().unwrap_or("");
414
415    // Loopback hostnames are explicitly allowed. RFC 6761 mandates that
416    // `localhost` and `*.localhost` resolve to loopback;
417    // `localhost.localdomain` is a historical alias used on some Linux
418    // distros. Self-hosted backends like Ollama use these by default.
419    let is_loopback_host =
420        host == "localhost" || host == "localhost.localdomain" || host.ends_with(".localhost");
421    if is_loopback_host {
422        return Ok(());
423    }
424
425    // mDNS hostnames are typically LAN devices, not loopback. Reject before
426    // DNS lookup so users get a clear error rather than a private-IP error.
427    if host.ends_with(".local") {
428        return Err(format!(
429            "base_url host '{host}' is an mDNS name — only loopback (localhost / 127.0.0.1) and public endpoints are allowed"
430        ));
431    }
432
433    // Resolve the hostname. Reject private/link-local/CGNAT IPs but NOT
434    // loopback (which is by definition same-machine and not an SSRF target).
435    let port = parsed.port_or_known_default().unwrap_or(443);
436    let addr_str = format!("{host}:{port}");
437    let addrs: Vec<IpAddr> = addr_str
438        .to_socket_addrs()
439        .map(|iter| iter.map(|sa| sa.ip()).collect())
440        .unwrap_or_default();
441    for ip in &addrs {
442        if is_private_non_loopback_ip(ip) {
443            return Err(format!(
444                "base_url '{raw}' resolves to a private/reserved IP — only loopback (127.0.0.1) and public endpoints are allowed"
445            ));
446        }
447    }
448
449    Ok(())
450}
451
452/// Returns true for IPv4/IPv6 addresses in private/link-local/CGNAT/benchmark/
453/// multicast/reserved ranges, EXCLUDING loopback (127.0.0.0/8 and ::1). Loopback
454/// is considered safe for SSRF purposes (same-machine, e.g. a local Ollama
455/// endpoint) — see [`validate_base_url_no_ssrf`] for rationale.
456///
457/// Delegates to [`crate::url_fetch::is_private_or_reserved_ip`] so there is one
458/// authoritative reserved-range list (the url_fetch copy is the maintained one;
459/// this used to be a drifting subset that missed e.g. 198.18.0.0/15 and the
460/// multicast/reserved blocks). We only re-add the loopback carve-out the
461/// url_fetch guard deliberately does not make.
462fn is_private_non_loopback_ip(ip: &std::net::IpAddr) -> bool {
463    // Canonicalize so an IPv4-mapped loopback (`::ffff:127.0.0.1`) is also
464    // recognized as loopback, matching the prior carve-out.
465    if ip.to_canonical().is_loopback() {
466        return false;
467    }
468    crate::url_fetch::is_private_or_reserved_ip(*ip)
469}
470
471fn build_openai_embeddings_endpoint(base_url: &str) -> String {
472    if base_url.ends_with("/v1") {
473        format!("{base_url}{DEFAULT_OPENAI_EMBEDDING_PATH}")
474    } else {
475        format!("{base_url}/v1{}", DEFAULT_OPENAI_EMBEDDING_PATH)
476    }
477}
478
479fn build_ollama_embeddings_endpoint(base_url: &str) -> String {
480    if base_url.ends_with("/api") {
481        format!("{base_url}/embed")
482    } else {
483        format!("{base_url}{DEFAULT_OLLAMA_EMBEDDING_PATH}")
484    }
485}
486
487fn normalize_api_key(value: Option<String>) -> Option<String> {
488    value.and_then(|token| {
489        let token = token.trim();
490        if token.is_empty() {
491            None
492        } else {
493            Some(token.to_string())
494        }
495    })
496}
497
498fn is_retryable_embedding_status(status: reqwest::StatusCode) -> bool {
499    status.is_server_error() || status == reqwest::StatusCode::TOO_MANY_REQUESTS
500}
501
502/// Local backends (LM Studio, Ollama, llama.cpp) can return a 4xx — usually
503/// 400/409 — while a model is loading or was just unloaded. Only narrowly known
504/// local-backend loading/unloaded payloads are classified transient; generic
505/// 4xx bodies that merely mention phrases like "loading model" remain
506/// permanent so misconfigurations do not retry forever.
507fn embedding_response_body_is_transient(status: reqwest::StatusCode, raw: &str) -> bool {
508    if !matches!(
509        status,
510        reqwest::StatusCode::BAD_REQUEST
511            | reqwest::StatusCode::CONFLICT
512            | reqwest::StatusCode::REQUEST_TIMEOUT
513            | reqwest::StatusCode::LOCKED
514            | reqwest::StatusCode::TOO_EARLY
515    ) {
516        return false;
517    }
518
519    let lower = raw.to_ascii_lowercase();
520    let normalized = lower.trim();
521
522    normalized.contains("model was unloaded while the request was still in queue")
523        || normalized == "model is loading"
524        || normalized.starts_with("model is loading,")
525        || normalized.contains(r#""error":"model is loading"#)
526        || normalized.contains(r#""message":"model is loading"#)
527        || normalized == "model not loaded"
528        || normalized.contains(r#""error":"model not loaded""#)
529        || normalized.contains(r#""message":"model not loaded""#)
530        || normalized == "loading model into memory"
531        || normalized.contains(r#""error":"loading model into memory""#)
532        || normalized.contains(r#""message":"loading model into memory""#)
533        || normalized == "model is being loaded"
534        || normalized.contains(r#""error":"model is being loaded""#)
535        || normalized.contains(r#""message":"model is being loaded""#)
536        || normalized == "model is currently loading"
537        || normalized.contains(r#""error":"model is currently loading""#)
538        || normalized.contains(r#""message":"model is currently loading""#)
539}
540
541fn is_retryable_embedding_error(error: &reqwest::Error) -> bool {
542    // Retryable == transient-at-send-stage: a backend that refused, timed
543    // out, or died mid-exchange deserves the same in-request retry ladder.
544    embedding_send_error_is_transient(error)
545}
546
547/// Whether a send-time error means the backend is *unreachable or temporarily
548/// failing* (vs. a real misconfiguration). Build requests retry both connection
549/// failures and timeouts; query requests use the same classification but have a
550/// one-attempt policy.
551fn embedding_send_error_is_transient(error: &reqwest::Error) -> bool {
552    // TLS trust failures are reported by reqwest as connect errors, but they
553    // cannot recover by retrying. Check the source chain before the broad
554    // connect/timeout classification so private-CA failures become terminal.
555    if embedding_error_is_certificate_trust_failure(error) {
556        return false;
557    }
558    if error.is_connect() || error.is_timeout() {
559        return true;
560    }
561    // A connection reset/abort mid-request is the backend dying between
562    // accept and response (local backends do this when they crash or restart
563    // under load) — the same "temporarily failing" class as a refused
564    // connection, just later in the exchange. reqwest surfaces it as a plain
565    // send error. Classify from the io source chain where one exists; hyper
566    // errors like IncompleteMessage ("connection closed before message
567    // completed") carry no io source, so fall back to known phrases in the
568    // chain's rendered messages.
569    let mut source = std::error::Error::source(error);
570    while let Some(inner) = source {
571        if let Some(io) = inner.downcast_ref::<std::io::Error>() {
572            if matches!(
573                io.kind(),
574                std::io::ErrorKind::ConnectionReset
575                    | std::io::ErrorKind::ConnectionAborted
576                    | std::io::ErrorKind::BrokenPipe
577                    | std::io::ErrorKind::UnexpectedEof
578            ) {
579                return true;
580            }
581        }
582        let rendered = inner.to_string().to_ascii_lowercase();
583        if rendered.contains("connection reset")
584            || rendered.contains("connection aborted")
585            || rendered.contains("connection closed")
586            || rendered.contains("broken pipe")
587            || rendered.contains("unexpected end of file")
588        {
589            return true;
590        }
591        source = std::error::Error::source(inner);
592    }
593    false
594}
595
596fn render_error_source_chain(error: &dyn Error) -> String {
597    let mut rendered = error.to_string();
598    let mut source = error.source();
599    while let Some(cause) = source {
600        rendered.push_str(": ");
601        rendered.push_str(&cause.to_string());
602        source = cause.source();
603    }
604    rendered
605}
606
607fn embedding_error_is_certificate_trust_failure(error: &reqwest::Error) -> bool {
608    let rendered = render_error_source_chain(error).to_ascii_lowercase();
609    [
610        "unknownissuer",
611        "unknown issuer",
612        "invalid peer certificate",
613        "certificate verify failed",
614        "certificate validation failed",
615        "certificate error",
616    ]
617    .iter()
618    .any(|marker| rendered.contains(marker))
619}
620
621fn embedding_response_read_error_is_transient(error: &reqwest::Error) -> bool {
622    embedding_send_error_is_transient(error) || error.is_body() || error.is_decode()
623}
624
625/// Returns the query-timeout marker for a request error when the active policy
626/// is a `Query(budget)` and reqwest classifies the error as a timeout. Returns
627/// an empty string otherwise — build-policy timeouts and non-timeout query
628/// errors carry no marker. This is the single site that decides whether a
629/// failure is "the configured query budget fired", so the fallback message can
630/// name the knob (`semantic.query_timeout_ms`) without re-parsing reqwest text.
631fn query_timeout_marker_for_error(
632    error: &reqwest::Error,
633    policy: EmbeddingRequestPolicy,
634) -> String {
635    match policy {
636        EmbeddingRequestPolicy::Query(budget) if error.is_timeout() => {
637            query_embedding_timeout_marker(budget.timeout_ms)
638        }
639        _ => String::new(),
640    }
641}
642
643/// Stable machine marker prefixed onto embedding error strings whose root cause
644/// is transient — the backend is down, timing out, or returning 5xx/429, not
645/// misconfigured. The build and corpus-refresh layers key retry-vs-give-up on
646/// this marker (see [`embedding_failure_is_transient`]) instead of re-parsing
647/// error text, so transience stays authoritative at the one site that knows it.
648/// Stripped before any user-facing display via [`strip_transient_embedding_marker`].
649pub const TRANSIENT_EMBEDDING_MARKER: &str = "[transient] ";
650
651/// True when an embedding error carries the transient marker — i.e. retrying
652/// once the backend recovers is the right move, not surfacing a hard failure.
653pub fn embedding_failure_is_transient(error: &str) -> bool {
654    error.contains(TRANSIENT_EMBEDDING_MARKER)
655}
656
657/// Remove the machine transient marker so the message is clean for display.
658pub fn strip_transient_embedding_marker(error: &str) -> String {
659    error.replace(TRANSIENT_EMBEDDING_MARKER, "")
660}
661
662/// Stable machine marker prefixed onto a *query* embedding error string when
663/// the failure was a request timeout — i.e. reqwest's `is_timeout()` fired
664/// while running under a `Query(budget)` policy. The marker carries the budget
665/// that fired (`[query-timeout:{ms}]`) so the consumer can name both the
666/// mechanism and the knob (`semantic.query_timeout_ms`) without re-parsing
667/// reqwest's rendered error text, which varies by backend and locale.
668///
669/// Classification lives here — next to the one site that knows both the policy
670/// (Query with a budget) and the typed reqwest error — so it cannot drift from
671/// the error shape. Stripped before user-facing display via
672/// [`strip_query_embedding_timeout_marker`]; the budget is recovered via
673/// [`query_embedding_timeout_budget`].
674pub const QUERY_EMBEDDING_TIMEOUT_MARKER_PREFIX: &str = "[query-timeout:";
675pub const QUERY_EMBEDDING_TIMEOUT_MARKER_SUFFIX: &str = "]";
676
677/// Build the timeout marker for a given query budget. Kept here so the format
678/// and the parser below stay in lockstep. `pub(crate)` so the classification
679/// test in `semantic_search` can construct a marked error without duplicating
680/// the format string.
681pub(crate) fn query_embedding_timeout_marker(timeout_ms: u64) -> String {
682    format!("{QUERY_EMBEDDING_TIMEOUT_MARKER_PREFIX}{timeout_ms}{QUERY_EMBEDDING_TIMEOUT_MARKER_SUFFIX}")
683}
684
685/// Recover the timeout budget (ms) a query embedding error carries, or `None`
686/// when the failure was not a query timeout. This is the single authoritative
687/// way to detect the timeout case — never substring-match on reqwest's text.
688pub fn query_embedding_timeout_budget(error: &str) -> Option<u64> {
689    let start = error.find(QUERY_EMBEDDING_TIMEOUT_MARKER_PREFIX)?;
690    let rest = &error[start + QUERY_EMBEDDING_TIMEOUT_MARKER_PREFIX.len()..];
691    let end = rest.find(QUERY_EMBEDDING_TIMEOUT_MARKER_SUFFIX)?;
692    rest[..end].parse::<u64>().ok()
693}
694
695/// Remove the query-timeout marker so the message is clean for display. The
696/// budget is recovered separately via [`query_embedding_timeout_budget`] before
697/// stripping.
698pub fn strip_query_embedding_timeout_marker(error: &str) -> String {
699    if let (Some(start), Some(budget)) = (
700        error.find(QUERY_EMBEDDING_TIMEOUT_MARKER_PREFIX),
701        query_embedding_timeout_budget(error),
702    ) {
703        let marker = query_embedding_timeout_marker(budget);
704        let end = start + marker.len();
705        let mut cleaned = error.to_string();
706        cleaned.replace_range(start..end, "");
707        cleaned
708    } else {
709        error.to_string()
710    }
711}
712
713fn sleep_before_embedding_retry(attempt_index: usize) {
714    if let Some(delay_ms) = EMBEDDING_REQUEST_BACKOFF_MS.get(attempt_index) {
715        std::thread::sleep(Duration::from_millis(*delay_ms));
716    }
717}
718
719fn send_embedding_request<F>(
720    mut make_request: F,
721    backend_label: &str,
722    policy: EmbeddingRequestPolicy,
723) -> Result<String, String>
724where
725    F: FnMut() -> reqwest::blocking::RequestBuilder,
726{
727    let max_attempts = policy.max_attempts();
728    for attempt_index in 0..max_attempts {
729        let last_attempt = attempt_index + 1 == max_attempts;
730        let mut request = make_request();
731        if let Some(timeout) = policy.request_timeout() {
732            request = request.timeout(timeout);
733        }
734
735        let response = match request.send() {
736            Ok(response) => response,
737            Err(error) => {
738                if !last_attempt && is_retryable_embedding_error(&error) {
739                    sleep_before_embedding_retry(attempt_index);
740                    continue;
741                }
742                // Connect/timeout failures mean the backend is unreachable or
743                // cold-loading — mark transient so the build layer rides it out
744                // and self-heals instead of parking the index in `Failed`.
745                let marker = if embedding_send_error_is_transient(&error) {
746                    TRANSIENT_EMBEDDING_MARKER
747                } else {
748                    ""
749                };
750                // A query-timeout is a distinct, actionable failure: the
751                // configured `semantic.query_timeout_ms` budget fired. Tag it
752                // here — the only site that has both the typed reqwest error
753                // and the Query budget — so the fallback can name the knob
754                // without guessing at reqwest's rendered text.
755                let timeout_marker = query_timeout_marker_for_error(&error, policy);
756                return Err(format!(
757                    "{timeout_marker}{marker}{backend_label} request failed: {}",
758                    render_error_source_chain(&error)
759                ));
760            }
761        };
762
763        let status = response.status();
764        let raw = match response.text() {
765            Ok(raw) => raw,
766            Err(error) => {
767                if !last_attempt && embedding_response_read_error_is_transient(&error) {
768                    sleep_before_embedding_retry(attempt_index);
769                    continue;
770                }
771                let marker = if embedding_response_read_error_is_transient(&error) {
772                    TRANSIENT_EMBEDDING_MARKER
773                } else {
774                    ""
775                };
776                // A body-read timeout under a Query policy is the same budget
777                // firing mid-exchange; tag it identically to the send case.
778                let timeout_marker = query_timeout_marker_for_error(&error, policy);
779                return Err(format!(
780                    "{timeout_marker}{marker}{backend_label} response read failed: {}",
781                    render_error_source_chain(&error)
782                ));
783            }
784        };
785
786        if status.is_success() {
787            return Ok(raw);
788        }
789
790        // A 4xx whose body says the model is loading/unloaded is transient on
791        // local backends (LM Studio/Ollama), so treat it like a retryable
792        // status: ride it out at both the in-request and build-retry layers.
793        let body_transient = embedding_response_body_is_transient(status, &raw);
794        if !last_attempt && (is_retryable_embedding_status(status) || body_transient) {
795            sleep_before_embedding_retry(attempt_index);
796            continue;
797        }
798
799        // 5xx / 429 are server-side and transient — the backend is overloaded
800        // or briefly unavailable, not misconfigured. A 4xx whose body indicates
801        // the model is (un)loading is also transient (local backend mid-swap).
802        // Other 4xx (auth, bad request, model-not-found) is a real error the
803        // user must fix; no marker.
804        let marker = if is_retryable_embedding_status(status) || body_transient {
805            TRANSIENT_EMBEDDING_MARKER
806        } else {
807            ""
808        };
809        return Err(format!(
810            "{marker}{backend_label} request failed (HTTP {}): {}",
811            status, raw
812        ));
813    }
814
815    unreachable!("embedding request retries exhausted without returning")
816}
817
818fn configured_embedding_timeout_ms(config: &SemanticBackendConfig) -> u64 {
819    if config.timeout_ms == 0 {
820        DEFAULT_OPENAI_EMBEDDING_TIMEOUT_MS
821    } else {
822        config.timeout_ms
823    }
824}
825
826impl SemanticEmbeddingModel {
827    pub fn from_config(config: &SemanticBackendConfig) -> Result<Self, String> {
828        Self::from_config_with_timeout_ms(config, configured_embedding_timeout_ms(config))
829    }
830
831    pub fn from_config_for_query(config: &SemanticBackendConfig) -> Result<Self, String> {
832        // The model may later be reused by a background build, so retain the build
833        // client's timeout. QueryBudget overrides each interactive HTTP request.
834        Self::from_config(config)
835    }
836
837    fn from_config_with_timeout_ms(
838        config: &SemanticBackendConfig,
839        timeout_ms: u64,
840    ) -> Result<Self, String> {
841        let max_batch_size = if config.max_batch_size == 0 {
842            DEFAULT_MAX_BATCH_SIZE
843        } else {
844            config.max_batch_size
845        };
846
847        let api_key_env = normalize_api_key(config.api_key_env.clone());
848        let model = config.model.clone();
849
850        let tls_config = crate::platform_tls::client_config()
851            .map_err(|error| format!("failed to configure embedding client TLS: {error}"))?;
852        let client = Client::builder()
853            .timeout(Duration::from_millis(timeout_ms))
854            .redirect(reqwest::redirect::Policy::none())
855            .use_preconfigured_tls(tls_config)
856            .build()
857            .map_err(|error| format!("failed to configure embedding client: {error}"))?;
858
859        let engine = match config.backend {
860            SemanticBackend::Fastembed => {
861                SemanticEmbeddingEngine::Local(LocalEmbedder::new(&model)?)
862            }
863            SemanticBackend::OpenAiCompatible => {
864                let raw = config.base_url.as_ref().ok_or_else(|| {
865                    "base_url is required for openai_compatible backend".to_string()
866                })?;
867                let base_url = normalize_base_url(raw)?;
868
869                let api_key = match api_key_env {
870                    Some(var_name) => Some(env::var(&var_name).map_err(|_| {
871                        format!("missing api_key_env '{var_name}' for openai_compatible backend")
872                    })?),
873                    None => None,
874                };
875
876                SemanticEmbeddingEngine::OpenAiCompatible {
877                    client,
878                    model,
879                    base_url,
880                    api_key,
881                }
882            }
883            SemanticBackend::Ollama => {
884                let raw = config
885                    .base_url
886                    .as_ref()
887                    .ok_or_else(|| "base_url is required for ollama backend".to_string())?;
888                let base_url = normalize_base_url(raw)?;
889
890                SemanticEmbeddingEngine::Ollama {
891                    client,
892                    model,
893                    base_url,
894                }
895            }
896        };
897
898        Ok(Self {
899            backend: config.backend,
900            model: config.model.clone(),
901            base_url: config.base_url.clone(),
902            timeout_ms,
903            max_batch_size,
904            dimension: None,
905            engine,
906            query_embedding_cache: HashMap::new(),
907            query_embedding_cache_order: VecDeque::new(),
908            query_embedding_cache_hits: 0,
909            query_embedding_cache_misses: 0,
910        })
911    }
912
913    pub fn backend(&self) -> SemanticBackend {
914        self.backend
915    }
916
917    pub fn model(&self) -> &str {
918        &self.model
919    }
920
921    pub fn base_url(&self) -> Option<&str> {
922        self.base_url.as_deref()
923    }
924
925    pub fn max_batch_size(&self) -> usize {
926        self.max_batch_size
927    }
928
929    pub fn timeout_ms(&self) -> u64 {
930        self.timeout_ms
931    }
932
933    pub fn fingerprint(
934        &mut self,
935        config: &SemanticBackendConfig,
936    ) -> Result<SemanticIndexFingerprint, String> {
937        let dimension = self.dimension()?;
938        Ok(SemanticIndexFingerprint::from_config(config, dimension))
939    }
940
941    pub fn dimension(&mut self) -> Result<usize, String> {
942        if let Some(dimension) = self.dimension {
943            return Ok(dimension);
944        }
945
946        let dimension = match &mut self.engine {
947            SemanticEmbeddingEngine::Local(model) => {
948                let vectors = model.embed(&["semantic index fingerprint probe".to_string()])?;
949                vectors
950                    .first()
951                    .map(|v| v.len())
952                    .ok_or_else(|| "embedding backend returned no vectors".to_string())?
953            }
954            SemanticEmbeddingEngine::OpenAiCompatible { .. } => {
955                let vectors = self.embed_texts(
956                    vec!["semantic index fingerprint probe".to_string()],
957                    EmbeddingRequestPolicy::Build,
958                )?;
959                vectors
960                    .first()
961                    .map(|v| v.len())
962                    .ok_or_else(|| "embedding backend returned no vectors".to_string())?
963            }
964            SemanticEmbeddingEngine::Ollama { .. } => {
965                let vectors = self.embed_texts(
966                    vec!["semantic index fingerprint probe".to_string()],
967                    EmbeddingRequestPolicy::Build,
968                )?;
969                vectors
970                    .first()
971                    .map(|v| v.len())
972                    .ok_or_else(|| "embedding backend returned no vectors".to_string())?
973            }
974        };
975
976        self.dimension = Some(dimension);
977        Ok(dimension)
978    }
979
980    pub fn embed(&mut self, texts: Vec<String>) -> Result<Vec<Vec<f32>>, String> {
981        self.embed_texts(texts, EmbeddingRequestPolicy::Build)
982    }
983
984    pub fn embed_query_cached(
985        &mut self,
986        query: &str,
987        budget: QueryBudget,
988    ) -> Result<Vec<f32>, String> {
989        if let Some(vector) = self.query_embedding_cache.get(query) {
990            self.query_embedding_cache_hits += 1;
991            return Ok(vector.clone());
992        }
993
994        self.query_embedding_cache_misses += 1;
995        let embeddings = self.embed_texts(
996            vec![query.to_string()],
997            EmbeddingRequestPolicy::Query(budget),
998        )?;
999        let vector = embeddings
1000            .first()
1001            .cloned()
1002            .ok_or_else(|| "embedding model returned no query vector".to_string())?;
1003
1004        if self.query_embedding_cache.len() >= QUERY_EMBEDDING_CACHE_CAP {
1005            if let Some(oldest) = self.query_embedding_cache_order.pop_front() {
1006                self.query_embedding_cache.remove(&oldest);
1007            }
1008        }
1009        self.query_embedding_cache
1010            .insert(query.to_string(), vector.clone());
1011        self.query_embedding_cache_order
1012            .push_back(query.to_string());
1013
1014        Ok(vector)
1015    }
1016
1017    pub fn query_embedding_cache_stats(&self) -> (u64, u64, usize) {
1018        (
1019            self.query_embedding_cache_hits,
1020            self.query_embedding_cache_misses,
1021            self.query_embedding_cache.len(),
1022        )
1023    }
1024
1025    fn embed_texts(
1026        &mut self,
1027        texts: Vec<String>,
1028        policy: EmbeddingRequestPolicy,
1029    ) -> Result<Vec<Vec<f32>>, String> {
1030        match &mut self.engine {
1031            SemanticEmbeddingEngine::Local(model) => model
1032                .embed(&texts)
1033                .map_err(|error| format!("failed to embed batch: {error}")),
1034            SemanticEmbeddingEngine::OpenAiCompatible {
1035                client,
1036                model,
1037                base_url,
1038                api_key,
1039            } => {
1040                let expected_text_count = texts.len();
1041                let endpoint = build_openai_embeddings_endpoint(base_url);
1042                let body = serde_json::json!({
1043                    "input": texts,
1044                    "model": model,
1045                });
1046
1047                let raw = send_embedding_request(
1048                    || {
1049                        // `.json(&body)` sets Content-Type: application/json
1050                        // automatically. Do NOT add `.header("Content-Type",
1051                        // "application/json")` afterwards — RequestBuilder::header()
1052                        // calls HeaderMap::append, which produces TWO Content-Type
1053                        // headers on the wire. OpenAI's /v1/embeddings endpoint
1054                        // treats duplicate Content-Type as malformed and rejects
1055                        // the body with 400 "you must provide a model parameter"
1056                        // even when `model` is set. Verified end-to-end against
1057                        // api.openai.com. See issue #36.
1058                        let mut request = client.post(&endpoint).json(&body);
1059
1060                        if let Some(api_key) = api_key {
1061                            request = request.header("Authorization", format!("Bearer {api_key}"));
1062                        }
1063
1064                        request
1065                    },
1066                    "openai compatible",
1067                    policy,
1068                )?;
1069
1070                #[derive(Deserialize)]
1071                struct OpenAiResponse {
1072                    data: Vec<OpenAiEmbeddingResult>,
1073                }
1074
1075                #[derive(Deserialize)]
1076                struct OpenAiEmbeddingResult {
1077                    embedding: Vec<f32>,
1078                    index: Option<u32>,
1079                }
1080
1081                let parsed: OpenAiResponse = serde_json::from_str(&raw)
1082                    .map_err(|error| format!("invalid openai compatible response: {error}"))?;
1083                if parsed.data.len() != expected_text_count {
1084                    return Err(format!(
1085                        "openai compatible response returned {} embeddings for {} inputs",
1086                        parsed.data.len(),
1087                        expected_text_count
1088                    ));
1089                }
1090
1091                let mut vectors = vec![Vec::new(); parsed.data.len()];
1092                for (i, item) in parsed.data.into_iter().enumerate() {
1093                    let index = item.index.unwrap_or(i as u32) as usize;
1094                    if index >= vectors.len() {
1095                        return Err(
1096                            "openai compatible response contains invalid vector index".to_string()
1097                        );
1098                    }
1099                    vectors[index] = item.embedding;
1100                }
1101
1102                for vector in &vectors {
1103                    if vector.is_empty() {
1104                        return Err(
1105                            "openai compatible response contained missing vectors".to_string()
1106                        );
1107                    }
1108                }
1109
1110                self.dimension = vectors.first().map(Vec::len);
1111                Ok(vectors)
1112            }
1113            SemanticEmbeddingEngine::Ollama {
1114                client,
1115                model,
1116                base_url,
1117            } => {
1118                let expected_text_count = texts.len();
1119                let endpoint = build_ollama_embeddings_endpoint(base_url);
1120
1121                #[derive(Serialize)]
1122                struct OllamaPayload<'a> {
1123                    model: &'a str,
1124                    input: Vec<String>,
1125                }
1126
1127                let payload = OllamaPayload {
1128                    model,
1129                    input: texts,
1130                };
1131
1132                let raw = send_embedding_request(
1133                    || {
1134                        // `.json(&payload)` sets Content-Type automatically.
1135                        // Same duplicate-header trap as the OpenAI branch above
1136                        // — most Ollama servers tolerate it, but the
1137                        // single-Content-Type form is the correct one.
1138                        client.post(&endpoint).json(&payload)
1139                    },
1140                    "ollama",
1141                    policy,
1142                )?;
1143
1144                #[derive(Deserialize)]
1145                struct OllamaResponse {
1146                    embeddings: Vec<Vec<f32>>,
1147                }
1148
1149                let parsed: OllamaResponse = serde_json::from_str(&raw)
1150                    .map_err(|error| format!("invalid ollama response: {error}"))?;
1151                if parsed.embeddings.is_empty() {
1152                    return Err("ollama response returned no embeddings".to_string());
1153                }
1154                if parsed.embeddings.len() != expected_text_count {
1155                    return Err(format!(
1156                        "ollama response returned {} embeddings for {} inputs",
1157                        parsed.embeddings.len(),
1158                        expected_text_count
1159                    ));
1160                }
1161
1162                let vectors = parsed.embeddings;
1163                for vector in &vectors {
1164                    if vector.is_empty() {
1165                        return Err("ollama response contained empty embeddings".to_string());
1166                    }
1167                }
1168
1169                self.dimension = vectors.first().map(Vec::len);
1170                Ok(vectors)
1171            }
1172        }
1173    }
1174}
1175
1176/// Platform library filename for the plugin-managed ONNX Runtime.
1177///
1178/// Mirrors `ORT_PLATFORM_MAP` in packages/aft-bridge/src/onnx-runtime.ts. A
1179/// layout change on either side must update both — the plugin downloads the
1180/// runtime into `<storage_dir>/onnxruntime/<version>/` and this resolver must
1181/// find it at the same path.
1182#[cfg(target_os = "linux")]
1183const MANAGED_ORT_LIB_NAME: &str = "libonnxruntime.so";
1184#[cfg(target_os = "macos")]
1185const MANAGED_ORT_LIB_NAME: &str = "libonnxruntime.dylib";
1186#[cfg(target_os = "windows")]
1187const MANAGED_ORT_LIB_NAME: &str = "onnxruntime.dll";
1188
1189/// Minimum managed ONNX Runtime minor version this resolver will accept.
1190///
1191/// Mirrors the `REQUIRED_ORT_MIN_MINOR` floor in onnx-runtime.ts and the 1.20
1192/// floor `pre_validate_onnx_runtime` enforces. A managed install below this
1193/// would be handed to ort and rejected there, so the resolver must skip it.
1194const MANAGED_ORT_MIN_MINOR: u32 = 20;
1195
1196/// Resolve the plugin-managed ONNX Runtime under the ACTIVE storage dir and
1197/// export it as `ORT_DYLIB_PATH` for the process.
1198///
1199/// The plugin (packages/aft-bridge/src/onnx-runtime.ts) downloads the runtime
1200/// to `<storage_dir>/onnxruntime/<version>/<libname>` and exports ORT_DYLIB_PATH
1201/// into the child env. A bare `aft` binary has no such step: without this
1202/// resolver, `pre_validate_onnx_runtime` dlopens the bare soname, which only
1203/// works with a system-installed runtime. This makes the standalone binary pick
1204/// up the runtime the plugin already downloaded.
1205///
1206/// Resolution order:
1207///   1. If `ORT_DYLIB_PATH` is already set (an explicit user override, or the
1208///      plugin already exported it), do nothing — the caller's choice wins and
1209///      the resolver must not run at all.
1210///   2. Enumerate `<storage_dir>/onnxruntime/` version directories, keep only
1211///      parseable `1.x.y` with x >= 20, pick the highest, and if its library
1212///      file exists set `ORT_DYLIB_PATH` to it.
1213///   3. Otherwise leave the env untouched; `pre_validate_onnx_runtime` falls
1214///      back to the bare soname + doctor hint as before.
1215///
1216/// # Process-global env mutation
1217/// This sets a process-wide env var and must run ONCE at startup, before any
1218/// worker threads spawn (the warmup CLI main and the standalone main's semantic
1219/// init path). Setting it lazily from a worker thread would race ort's own
1220/// dlopen and other threads reading the env. The function is idempotent: once
1221/// `ORT_DYLIB_PATH` is set, subsequent calls short-circuit.
1222pub fn resolve_managed_onnx_runtime(storage_dir: &Path) {
1223    if std::env::var_os("ORT_DYLIB_PATH").is_some() {
1224        return;
1225    }
1226    let Some(lib_path) = find_managed_onnx_runtime(storage_dir) else {
1227        return;
1228    };
1229    std::env::set_var("ORT_DYLIB_PATH", &lib_path);
1230    slog_info!(
1231        "using plugin-managed ONNX Runtime at {}",
1232        lib_path.display()
1233    );
1234}
1235
1236/// Find the highest compatible managed ONNX Runtime library under
1237/// `<storage_dir>/onnxruntime/`, or None when absent/incompatible.
1238///
1239/// Mirrors the plugin's `resolveCachedOnnxRuntimeDir`: the library may live at
1240/// the version root (the plugin's own flattened install) or under a `lib/`
1241/// subdir (manual Microsoft-archive installs, issue #71).
1242fn find_managed_onnx_runtime(storage_dir: &Path) -> Option<PathBuf> {
1243    let base = storage_dir.join("onnxruntime");
1244    let entries = std::fs::read_dir(&base).ok()?;
1245    #[cfg(test)]
1246    {
1247        // Test-only probe: counts how many times the resolver actually reads
1248        // the storage tree. Lets a negative-control test assert that a pre-set
1249        // ORT_DYLIB_PATH short-circuits the resolver without touching the tree.
1250        MANAGED_ORT_PROBE_READS.fetch_add(1, Ordering::Relaxed);
1251    }
1252    let mut best: Option<(u32, u32, PathBuf)> = None;
1253    for entry in entries.flatten() {
1254        let path = entry.path();
1255        if !path.is_dir() {
1256            continue;
1257        }
1258        let Some((major, minor)) = parse_managed_ort_version(&entry.file_name().to_string_lossy())
1259        else {
1260            continue;
1261        };
1262        if major != 1 || minor < MANAGED_ORT_MIN_MINOR {
1263            continue;
1264        }
1265        let Some(lib_path) = managed_ort_lib_in_version_dir(&path) else {
1266            continue;
1267        };
1268        if best
1269            .as_ref()
1270            .is_none_or(|(best_major, best_minor, _)| (major, minor) > (*best_major, *best_minor))
1271        {
1272            best = Some((major, minor, lib_path));
1273        }
1274    }
1275    best.map(|(_, _, path)| path)
1276}
1277
1278/// Locate the library file inside one `<version>` directory, preferring the
1279/// version root over a `lib/` subdir (mirrors `resolveCachedOnnxRuntimeDir`).
1280fn managed_ort_lib_in_version_dir(version_dir: &Path) -> Option<PathBuf> {
1281    let root = version_dir.join(MANAGED_ORT_LIB_NAME);
1282    if root.is_file() {
1283        return Some(root);
1284    }
1285    let lib_subdir = version_dir.join("lib").join(MANAGED_ORT_LIB_NAME);
1286    if lib_subdir.is_file() {
1287        return Some(lib_subdir);
1288    }
1289    None
1290}
1291
1292/// Parse a `major.minor.patch` triple from a version directory name. Returns
1293/// None for anything that is not exactly a three-part numeric version (so
1294/// non-version dirs and malformed names are ignored).
1295fn parse_managed_ort_version(name: &str) -> Option<(u32, u32)> {
1296    let mut parts = name.split('.');
1297    let major = parts.next()?.parse::<u32>().ok()?;
1298    let minor = parts.next()?.parse::<u32>().ok()?;
1299    let _patch = parts.next()?.parse::<u32>().ok()?;
1300    // Reject trailing junk like "1.24.4.tmp" or "1.24.4.5".
1301    if parts.next().is_some() {
1302        return None;
1303    }
1304    Some((major, minor))
1305}
1306
1307/// Pre-validate ONNX Runtime by attempting a raw dlopen before ort touches it.
1308/// This catches broken/incompatible .so files without risking a panic in the ort crate.
1309/// Also checks the runtime version via OrtGetApiBase if available.
1310pub fn pre_validate_onnx_runtime() -> Result<(), String> {
1311    let dylib_path = std::env::var("ORT_DYLIB_PATH").ok();
1312
1313    #[cfg(any(target_os = "linux", target_os = "macos"))]
1314    {
1315        #[cfg(target_os = "linux")]
1316        let default_name = "libonnxruntime.so";
1317        #[cfg(target_os = "macos")]
1318        let default_name = "libonnxruntime.dylib";
1319
1320        let lib_name = dylib_path.as_deref().unwrap_or(default_name);
1321
1322        unsafe {
1323            let c_name = std::ffi::CString::new(lib_name)
1324                .map_err(|e| format!("invalid library path: {}", e))?;
1325            let handle = libc::dlopen(c_name.as_ptr(), libc::RTLD_NOW);
1326            if handle.is_null() {
1327                let err = libc::dlerror();
1328                let msg = if err.is_null() {
1329                    "unknown dlopen error".to_string()
1330                } else {
1331                    std::ffi::CStr::from_ptr(err).to_string_lossy().into_owned()
1332                };
1333                return Err(format!(
1334                    "ONNX Runtime not found. dlopen('{}') failed: {}. \
1335                     Run `npx @cortexkit/aft doctor` to diagnose.",
1336                    lib_name, msg
1337                ));
1338            }
1339
1340            // Try to detect the runtime version from the actual loaded library
1341            // path first. A bare dlopen("libonnxruntime.so") may resolve to an
1342            // older system ORT through loader search paths; checking only the
1343            // caller-supplied soname would miss that and let ort fail opaquely.
1344            let (detected_version, version_source) =
1345                detect_ort_version_from_loaded_library(handle, lib_name);
1346
1347            libc::dlclose(handle);
1348
1349            // Check version compatibility — we need 1.20+.
1350            if let Some(ref version) = detected_version {
1351                let parts: Vec<&str> = version.split('.').collect();
1352                if let (Some(major), Some(minor)) = (
1353                    parts.first().and_then(|s| s.parse::<u32>().ok()),
1354                    parts.get(1).and_then(|s| s.parse::<u32>().ok()),
1355                ) {
1356                    if major != 1 || minor < 20 {
1357                        return Err(format_ort_version_mismatch(version, &version_source));
1358                    }
1359                }
1360            }
1361        }
1362    }
1363
1364    #[cfg(target_os = "windows")]
1365    {
1366        // Validate ONNX Runtime availability on Windows by loading the DLL
1367        // via LoadLibraryExW before the ort crate attempts its own LoadLibrary.
1368        // This way we can produce a friendly error (with installation hints)
1369        // instead of a raw LoadLibrary failure from deep inside fastembed.
1370        let lib_name = dylib_path.as_deref().unwrap_or("onnxruntime.dll");
1371
1372        // Use kernel32 LoadLibraryExW for the validation — built-in, no
1373        // crate dependency required. GetModuleFileNameW resolves the loaded
1374        // DLL path for version probing via the version.dll API.
1375        #[link(name = "kernel32")]
1376        extern "system" {
1377            fn LoadLibraryExW(
1378                lpLibFileName: *const u16,
1379                hFile: *mut std::ffi::c_void,
1380                dwFlags: u32,
1381            ) -> *mut std::ffi::c_void;
1382            fn FreeLibrary(hLibModule: *mut std::ffi::c_void) -> i32;
1383            fn GetModuleFileNameW(
1384                hModule: *mut std::ffi::c_void,
1385                lpFilename: *mut u16,
1386                nSize: u32,
1387            ) -> u32;
1388        }
1389
1390        #[link(name = "version")]
1391        extern "system" {
1392            fn GetFileVersionInfoSizeW(lptstrFilename: *const u16, lpdwHandle: *mut u32) -> u32;
1393            fn GetFileVersionInfoW(
1394                lptstrFilename: *const u16,
1395                dwHandle: u32,
1396                dwLen: u32,
1397                lpData: *mut std::ffi::c_void,
1398            ) -> i32;
1399            fn VerQueryValueW(
1400                pBlock: *mut std::ffi::c_void,
1401                lpSubBlock: *const u16,
1402                lplpBuffer: *mut *mut std::ffi::c_void,
1403                puLen: *mut u32,
1404            ) -> i32;
1405        }
1406
1407        #[repr(C)]
1408        struct VS_FIXEDFILEINFO {
1409            dw_signature: u32,
1410            dw_struc_version: u32,
1411            dw_file_version_ms: u32, // HIWORD major, LOWORD minor
1412            dw_file_version_ls: u32, // HIWORD build, LOWORD revision
1413            dw_product_version_ms: u32,
1414            dw_product_version_ls: u32,
1415            dw_file_flags_mask: u32,
1416            dw_file_flags: u32,
1417            dw_file_os: u32,
1418            dw_file_type: u32,
1419            dw_file_subtype: u32,
1420            dw_file_date_ms: u32,
1421            dw_file_date_ls: u32,
1422        }
1423
1424        unsafe {
1425            use std::os::windows::ffi::OsStrExt;
1426            let wide: Vec<u16> = std::ffi::OsStr::new(lib_name)
1427                .encode_wide()
1428                .chain(std::iter::once(0))
1429                .collect();
1430
1431            let handle = LoadLibraryExW(wide.as_ptr(), std::ptr::null_mut(), 0);
1432            if handle.is_null() {
1433                let err = std::io::Error::last_os_error();
1434                return Err(format!(
1435                    "ONNX Runtime not found. LoadLibraryExW('{}') failed: {}. \
1436                     Run `npx @cortexkit/aft doctor` to diagnose.",
1437                    lib_name, err
1438                ));
1439            }
1440
1441            // Probe the file version from PE resources so we can reject
1442            // outdated DLLs (e.g. v1.9.x) before the ort crate panics.
1443            let mut detected_major: u32 = 0;
1444            let mut detected_minor: u32 = 0;
1445            // Use MAX_UNICODEPATH (32767) so deeply nested ORT paths (e.g.
1446            // long NuGet package paths under %USERPROFILE%) never truncate.
1447            // GetModuleFileNameW truncates silently when the buffer is too
1448            // small, which causes version probing to fail and the version
1449            // check to be bypassed — better to allocate generously.
1450            let mut path_buf = [0u16; 32767];
1451            let path_len = GetModuleFileNameW(handle, path_buf.as_mut_ptr(), 32767);
1452            if path_len > 0 {
1453                let mut dummy_handle: u32 = 0;
1454                let info_size = GetFileVersionInfoSizeW(path_buf.as_ptr(), &mut dummy_handle);
1455                if info_size > 0 {
1456                    let mut info = vec![0u8; info_size as usize];
1457                    if GetFileVersionInfoW(
1458                        path_buf.as_ptr(),
1459                        0,
1460                        info_size,
1461                        info.as_mut_ptr() as *mut std::ffi::c_void,
1462                    ) != 0
1463                    {
1464                        let sub_block = "\\\0".encode_utf16().collect::<Vec<u16>>();
1465                        let mut vs_info: *mut std::ffi::c_void = std::ptr::null_mut();
1466                        let mut vs_len: u32 = 0;
1467                        if VerQueryValueW(
1468                            info.as_mut_ptr() as *mut std::ffi::c_void,
1469                            sub_block.as_ptr(),
1470                            &mut vs_info,
1471                            &mut vs_len,
1472                        ) != 0
1473                            && !vs_info.is_null()
1474                        {
1475                            let fixed = vs_info as *const VS_FIXEDFILEINFO;
1476                            detected_major = (*fixed).dw_file_version_ms >> 16;
1477                            detected_minor = (*fixed).dw_file_version_ms & 0xFFFF;
1478                        }
1479                    }
1480                }
1481            }
1482
1483            FreeLibrary(handle);
1484
1485            // Version compatibility check (mirrors the Linux/macOS path).
1486            // If version could not be detected (detected_major == 0) we let
1487            // the load succeed — the ort crate will diagnose further.
1488            if detected_major != 0 && (detected_major != 1 || detected_minor < 20) {
1489                let ver = format!("{}.{}", detected_major, detected_minor);
1490                return Err(format_ort_version_mismatch(&ver, lib_name));
1491            }
1492        }
1493    }
1494
1495    Ok(())
1496}
1497
1498#[cfg(any(target_os = "linux", target_os = "macos"))]
1499unsafe fn loaded_library_path_from_handle(handle: *mut std::ffi::c_void) -> Option<String> {
1500    let symbol_name = std::ffi::CString::new("OrtGetApiBase").ok()?;
1501    let symbol = unsafe { libc::dlsym(handle, symbol_name.as_ptr()) };
1502    if symbol.is_null() {
1503        return None;
1504    }
1505
1506    let mut info = std::mem::MaybeUninit::<libc::Dl_info>::uninit();
1507    if unsafe { libc::dladdr(symbol, info.as_mut_ptr()) } == 0 {
1508        return None;
1509    }
1510
1511    let info = unsafe { info.assume_init() };
1512    if info.dli_fname.is_null() {
1513        return None;
1514    }
1515
1516    Some(
1517        unsafe { std::ffi::CStr::from_ptr(info.dli_fname) }
1518            .to_string_lossy()
1519            .into_owned(),
1520    )
1521}
1522
1523#[cfg(any(target_os = "linux", target_os = "macos"))]
1524fn detect_ort_version_from_resolved_or_requested(
1525    resolved_path: Option<String>,
1526    requested_lib_name: &str,
1527) -> (Option<String>, String) {
1528    if let Some(path) = resolved_path {
1529        if let Some(version) = detect_ort_version_from_path(&path) {
1530            return (Some(version), path);
1531        }
1532        return (detect_ort_version_from_path(requested_lib_name), path);
1533    }
1534
1535    (
1536        detect_ort_version_from_path(requested_lib_name),
1537        requested_lib_name.to_string(),
1538    )
1539}
1540
1541#[cfg(any(target_os = "linux", target_os = "macos"))]
1542fn detect_ort_version_from_loaded_library(
1543    handle: *mut std::ffi::c_void,
1544    requested_lib_name: &str,
1545) -> (Option<String>, String) {
1546    detect_ort_version_from_resolved_or_requested(
1547        unsafe { loaded_library_path_from_handle(handle) },
1548        requested_lib_name,
1549    )
1550}
1551
1552/// Try to extract the ORT version from the library filename or resolved symlink.
1553/// Examples: "libonnxruntime.so.1.19.0" → "1.19.0", "libonnxruntime.1.24.4.dylib" → "1.24.4"
1554#[cfg(any(target_os = "linux", target_os = "macos"))]
1555fn detect_ort_version_from_path(lib_path: &str) -> Option<String> {
1556    let path = std::path::Path::new(lib_path);
1557
1558    // Try the path as given, then follow symlinks
1559    for candidate in [Some(path.to_path_buf()), std::fs::canonicalize(path).ok()]
1560        .into_iter()
1561        .flatten()
1562    {
1563        if let Some(name) = candidate.file_name().and_then(|n| n.to_str()) {
1564            if let Some(version) = extract_version_from_filename(name) {
1565                return Some(version);
1566            }
1567        }
1568    }
1569
1570    // Also check for versioned siblings in the same directory
1571    if let Some(parent) = path.parent() {
1572        if let Ok(entries) = std::fs::read_dir(parent) {
1573            for entry in entries.flatten() {
1574                if let Some(name) = entry.file_name().to_str() {
1575                    if name.starts_with("libonnxruntime") {
1576                        if let Some(version) = extract_version_from_filename(name) {
1577                            return Some(version);
1578                        }
1579                    }
1580                }
1581            }
1582        }
1583    }
1584
1585    None
1586}
1587
1588/// Extract version from filenames like "libonnxruntime.so.1.19.0" or "libonnxruntime.1.24.4.dylib"
1589#[cfg(any(target_os = "linux", target_os = "macos"))]
1590fn extract_version_from_filename(name: &str) -> Option<String> {
1591    // Match patterns: .so.X.Y.Z or .X.Y.Z.dylib or .X.Y.Z.so
1592    let re = regex::Regex::new(r"(\d+\.\d+\.\d+)").ok()?;
1593    re.find(name).map(|m| m.as_str().to_string())
1594}
1595
1596fn suggest_removal_command(lib_path: &str) -> String {
1597    if lib_path.starts_with("/usr/local/lib")
1598        || lib_path == "libonnxruntime.so"
1599        || lib_path == "libonnxruntime.dylib"
1600    {
1601        #[cfg(target_os = "linux")]
1602        return "   sudo rm /usr/local/lib/libonnxruntime* && sudo ldconfig".to_string();
1603        #[cfg(target_os = "macos")]
1604        return "   sudo rm /usr/local/lib/libonnxruntime*".to_string();
1605    }
1606    format!("   rm '{}'", lib_path)
1607}
1608
1609/// Build the user-facing error message for an incompatible ONNX Runtime
1610/// install. Extracted as a pure helper so we can unit-test the wording
1611/// stability — the auto-fix recommendation must always come first because
1612/// it's the only safe option, and the system-rm step must remain present
1613/// because some users prefer the system-wide cleanup path.
1614pub(crate) fn format_ort_version_mismatch(version: &str, lib_name: &str) -> String {
1615    format!(
1616        "ONNX Runtime version mismatch: found v{} at '{}', but AFT requires v1.20+. \
1617         Solutions:\n\
1618         1. Auto-fix (recommended): run `npx @cortexkit/aft doctor --fix`. \
1619         This downloads AFT-managed ONNX Runtime v1.24 into AFT's storage and \
1620         configures the bridge to load it instead of the system library — no \
1621         changes to '{}'.\n\
1622         2. Remove the old library and restart (AFT auto-downloads the correct version on next start):\n\
1623         {}\n\
1624         3. Or install ONNX Runtime 1.24 system-wide: https://github.com/microsoft/onnxruntime/releases/tag/v1.24.0\n\
1625         4. Run `npx @cortexkit/aft doctor` for full diagnostics.",
1626        version,
1627        lib_name,
1628        lib_name,
1629        suggest_removal_command(lib_name),
1630    )
1631}
1632
1633pub fn is_onnx_runtime_unavailable(message: &str) -> bool {
1634    if message.trim_start().starts_with("ONNX Runtime not found.") {
1635        return true;
1636    }
1637
1638    let message = message.to_ascii_lowercase();
1639    let mentions_onnx_runtime = ["onnx runtime", "onnxruntime", "libonnxruntime"]
1640        .iter()
1641        .any(|pattern| message.contains(pattern));
1642    let mentions_dynamic_load_failure = [
1643        "shared library",
1644        "dynamic library",
1645        "failed to load",
1646        "could not load",
1647        "unable to load",
1648        "dlopen",
1649        "loadlibrary",
1650        "no such file",
1651        "not found",
1652    ]
1653    .iter()
1654    .any(|pattern| message.contains(pattern));
1655
1656    mentions_onnx_runtime && mentions_dynamic_load_failure
1657}
1658
1659pub fn format_embedding_init_error(error: impl Display) -> String {
1660    let message = error.to_string();
1661
1662    if is_onnx_runtime_unavailable(&message) {
1663        return format!("{ONNX_RUNTIME_INSTALL_HINT} Original error: {message}");
1664    }
1665
1666    format!("failed to initialize semantic embedding model: {message}")
1667}
1668
1669/// A chunk of code ready for embedding — derived from a Symbol with context enrichment
1670#[derive(Debug, Clone)]
1671pub struct SemanticChunk {
1672    /// Absolute file path
1673    pub file: PathBuf,
1674    /// Symbol name
1675    pub name: String,
1676    /// Fully-qualified symbol name, when known from the outline scope chain.
1677    pub qualified_name: Option<String>,
1678    /// Symbol kind (function, class, struct, etc.)
1679    pub kind: SymbolKind,
1680    /// Line range (0-based internally, inclusive)
1681    pub start_line: u32,
1682    pub end_line: u32,
1683    /// Whether the symbol is exported
1684    pub exported: bool,
1685    /// The enriched text that gets embedded (name + file + kind + signature + body snippet)
1686    pub embed_text: String,
1687    /// Short code snippet for display in results
1688    pub snippet: String,
1689}
1690
1691/// A stored embedding entry — chunk metadata + vector
1692#[derive(Debug, Clone)]
1693pub struct EmbeddingEntry {
1694    chunk: SemanticChunk,
1695    vector: Vec<f32>,
1696    /// Cached L2 norm so searches only recompute the query norm. Remote embedding
1697    /// backends do not guarantee unit vectors, so keep the actual norm instead of
1698    /// assuming it is 1.0.
1699    norm: f32,
1700}
1701
1702impl EmbeddingEntry {
1703    fn new(chunk: SemanticChunk, vector: Vec<f32>) -> Self {
1704        let norm = vector_norm(&vector);
1705        Self {
1706            chunk,
1707            vector,
1708            norm,
1709        }
1710    }
1711}
1712
1713#[derive(Debug)]
1714struct SharedSemanticBase {
1715    entries: Vec<EmbeddingEntry>,
1716    file_mtimes: HashMap<PathBuf, SystemTime>,
1717    file_sizes: HashMap<PathBuf, u64>,
1718    any_missing_sizes: bool,
1719    file_hashes: HashMap<PathBuf, blake3::Hash>,
1720    dimension: usize,
1721    fingerprint: Option<SemanticIndexFingerprint>,
1722    deferred_files: HashSet<PathBuf>,
1723}
1724
1725#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1726struct SharedSemanticBaseKey {
1727    artifact_cache_key: String,
1728    fingerprint: String,
1729    artifact_content_hash: blake3::Hash,
1730}
1731
1732type SharedSemanticBaseRegistry = HashMap<SharedSemanticBaseKey, Weak<SharedSemanticBase>>;
1733
1734fn shared_semantic_bases() -> &'static Mutex<SharedSemanticBaseRegistry> {
1735    static REGISTRY: OnceLock<Mutex<SharedSemanticBaseRegistry>> = OnceLock::new();
1736    REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
1737}
1738
1739static SHARED_SEMANTIC_BASE_LOADS: AtomicUsize = AtomicUsize::new(0);
1740static SHARED_SEMANTIC_BASE_HITS: AtomicUsize = AtomicUsize::new(0);
1741
1742impl SharedSemanticBase {
1743    fn estimated_memory(&self) -> crate::memory::MemoryEstimate {
1744        let vector_bytes = self.entries.iter().fold(0u64, |bytes, entry| {
1745            bytes.saturating_add(
1746                crate::memory::usize_to_u64(entry.vector.len())
1747                    .saturating_mul(std::mem::size_of::<f32>() as u64),
1748            )
1749        });
1750        let text_bytes = self.entries.iter().fold(0u64, |bytes, entry| {
1751            bytes
1752                .saturating_add(crate::memory::path_bytes(&entry.chunk.file))
1753                .saturating_add(crate::memory::usize_to_u64(entry.chunk.name.len()))
1754                .saturating_add(
1755                    entry
1756                        .chunk
1757                        .qualified_name
1758                        .as_ref()
1759                        .map(|name| crate::memory::usize_to_u64(name.len()))
1760                        .unwrap_or(0),
1761                )
1762                .saturating_add(crate::memory::usize_to_u64(entry.chunk.embed_text.len()))
1763                .saturating_add(crate::memory::usize_to_u64(entry.chunk.snippet.len()))
1764        });
1765        let metadata_bytes = crate::memory::usize_to_u64(self.entries.len())
1766            .saturating_mul(std::mem::size_of::<EmbeddingEntry>() as u64)
1767            .saturating_add(
1768                self.file_mtimes
1769                    .keys()
1770                    .chain(self.file_sizes.keys())
1771                    .chain(self.file_hashes.keys())
1772                    .chain(self.deferred_files.iter())
1773                    .map(|path| crate::memory::path_bytes(path))
1774                    .fold(0u64, u64::saturating_add),
1775            )
1776            .saturating_add(
1777                crate::memory::usize_to_u64(self.file_mtimes.len())
1778                    .saturating_mul(std::mem::size_of::<SystemTime>() as u64),
1779            )
1780            .saturating_add(
1781                crate::memory::usize_to_u64(self.file_sizes.len())
1782                    .saturating_mul(std::mem::size_of::<u64>() as u64),
1783            )
1784            .saturating_add(
1785                crate::memory::usize_to_u64(self.file_hashes.len())
1786                    .saturating_mul(std::mem::size_of::<blake3::Hash>() as u64),
1787            );
1788        crate::memory::MemoryEstimate::estimated(
1789            vector_bytes
1790                .saturating_add(text_bytes)
1791                .saturating_add(metadata_bytes),
1792        )
1793        .count("entries", self.entries.len())
1794        .count("indexed_files", self.file_mtimes.len())
1795        .count_u64("vector_bytes", vector_bytes)
1796        .count_u64("text_bytes", text_bytes)
1797        .count_u64("metadata_bytes", metadata_bytes)
1798    }
1799}
1800
1801pub(crate) fn shared_semantic_bases_memory() -> crate::memory::MemoryEstimate {
1802    let mut registry = shared_semantic_bases()
1803        .lock()
1804        .unwrap_or_else(std::sync::PoisonError::into_inner);
1805    registry.retain(|_, base| base.strong_count() > 0);
1806    let bases = registry
1807        .values()
1808        .filter_map(Weak::upgrade)
1809        .collect::<Vec<_>>();
1810    let estimates = bases
1811        .iter()
1812        .map(|base| base.estimated_memory())
1813        .collect::<Vec<_>>();
1814    let bytes = estimates.iter().fold(0u64, |sum, estimate| {
1815        sum.saturating_add(estimate.estimated_bytes.unwrap_or(0))
1816    });
1817    let count_bytes = |name: &str| {
1818        estimates.iter().fold(0u64, |sum, estimate| {
1819            sum.saturating_add(estimate.counts.get(name).copied().unwrap_or(0))
1820        })
1821    };
1822    crate::memory::MemoryEstimate::estimated(bytes)
1823        .count("bases", bases.len())
1824        .count("entries", bases.iter().map(|base| base.entries.len()).sum())
1825        .count_u64("vector_bytes", count_bytes("vector_bytes"))
1826        .count_u64("text_bytes", count_bytes("text_bytes"))
1827        .count_u64("metadata_bytes", count_bytes("metadata_bytes"))
1828        .count_u64(
1829            "loads",
1830            SHARED_SEMANTIC_BASE_LOADS.load(Ordering::Relaxed) as u64,
1831        )
1832        .count_u64(
1833            "hits",
1834            SHARED_SEMANTIC_BASE_HITS.load(Ordering::Relaxed) as u64,
1835        )
1836}
1837
1838fn borrowed_artifact_identity(data_path: &Path) -> Result<(String, blake3::Hash), String> {
1839    let mut file = fs::File::open(data_path).map_err(|error| error.to_string())?;
1840    let mut hasher = blake3::Hasher::new();
1841    hasher
1842        .update_reader(&mut file)
1843        .map_err(|error| error.to_string())?;
1844    let artifact_content_hash = hasher.finalize();
1845
1846    let mut header = BufReader::new(fs::File::open(data_path).map_err(|error| error.to_string())?);
1847    let mut fixed = [0u8; HEADER_BYTES_V2];
1848    header
1849        .read_exact(&mut fixed)
1850        .map_err(|error| error.to_string())?;
1851    if fixed[0] != SEMANTIC_INDEX_VERSION_V6 && fixed[0] != SEMANTIC_INDEX_VERSION_V7 {
1852        return Err(format!(
1853            "unsupported semantic artifact version {}",
1854            fixed[0]
1855        ));
1856    }
1857    let fingerprint_len = u32::from_le_bytes(fixed[9..13].try_into().unwrap()) as usize;
1858    if fingerprint_len == 0 || fingerprint_len > 64 * 1024 {
1859        return Err("semantic artifact fingerprint is missing or oversized".to_string());
1860    }
1861    let mut fingerprint = vec![0u8; fingerprint_len];
1862    header
1863        .read_exact(&mut fingerprint)
1864        .map_err(|error| error.to_string())?;
1865    let fingerprint = String::from_utf8(fingerprint).map_err(|error| error.to_string())?;
1866    Ok((fingerprint, artifact_content_hash))
1867}
1868
1869/// The semantic index — stores embeddings for all symbols in a project.
1870/// Borrow-only roots retain only a root path plus an Arc to immutable relative data.
1871#[derive(Debug, Clone)]
1872pub struct SemanticIndex {
1873    entries: Vec<EmbeddingEntry>,
1874    /// Track which files are indexed and their mtime for staleness detection
1875    file_mtimes: HashMap<PathBuf, SystemTime>,
1876    /// Track indexed file sizes alongside mtimes for staleness detection
1877    file_sizes: HashMap<PathBuf, u64>,
1878    /// Avoid walking every indexed path on warm refreshes once size metadata is complete.
1879    any_missing_sizes: bool,
1880    file_hashes: HashMap<PathBuf, blake3::Hash>,
1881    /// Embedding dimension (384 for MiniLM-L6-v2)
1882    dimension: usize,
1883    fingerprint: Option<SemanticIndexFingerprint>,
1884    project_root: PathBuf,
1885    deferred_files: HashSet<PathBuf>,
1886    shared_base: Option<Arc<SharedSemanticBase>>,
1887    #[cfg(test)]
1888    removal_retain_passes: usize,
1889}
1890
1891#[derive(Debug, Clone, Copy)]
1892struct IndexedFileMetadata {
1893    mtime: SystemTime,
1894    size: u64,
1895    content_hash: blake3::Hash,
1896}
1897
1898#[derive(Debug, Default, Clone, Copy)]
1899struct SemanticCollectPhaseTimings {
1900    sched: Duration,
1901    read_hash: Duration,
1902    parse: Duration,
1903    extract: Duration,
1904    build: Duration,
1905}
1906
1907impl SemanticCollectPhaseTimings {
1908    fn add_assign(&mut self, other: Self) {
1909        self.sched += other.sched;
1910        self.read_hash += other.read_hash;
1911        self.parse += other.parse;
1912        self.extract += other.extract;
1913        self.build += other.build;
1914    }
1915}
1916
1917type CollectedSemanticFile = (
1918    PathBuf,
1919    Result<(IndexedFileMetadata, Vec<SemanticChunk>), String>,
1920    SemanticCollectPhaseTimings,
1921);
1922
1923/// Result of an incremental refresh of the semantic index. Counts are file
1924/// counts; `total_processed` is the number of current/deleted files considered.
1925#[derive(Debug, Default, Clone, Copy)]
1926pub struct RefreshSummary {
1927    pub changed: usize,
1928    pub added: usize,
1929    pub deleted: usize,
1930    pub total_processed: usize,
1931}
1932
1933impl RefreshSummary {
1934    /// True when no files were touched.
1935    pub fn is_noop(&self) -> bool {
1936        self.changed == 0 && self.added == 0 && self.deleted == 0
1937    }
1938}
1939
1940#[derive(Debug, Default)]
1941pub struct InvalidatedFilesRefresh {
1942    /// Full replacement entries for `completed_paths`, not just newly embedded
1943    /// chunks. `apply_refresh_update` removes completed paths before extending
1944    /// this set, so reused chunks must travel in this delta too.
1945    pub added_entries: Vec<EmbeddingEntry>,
1946    pub updated_metadata: Vec<(PathBuf, FileFreshness)>,
1947    pub completed_paths: Vec<PathBuf>,
1948    pub summary: RefreshSummary,
1949}
1950
1951#[derive(Debug, Clone)]
1952struct ReusableEmbedding {
1953    embed_text: String,
1954    vector: Vec<f32>,
1955}
1956
1957type ChunkReuseMap = HashMap<PathBuf, HashMap<blake3::Hash, Vec<ReusableEmbedding>>>;
1958
1959/// Search result from a semantic query
1960#[derive(Debug, Clone)]
1961pub struct SemanticResult {
1962    pub file: PathBuf,
1963    pub name: String,
1964    pub qualified_name: Option<String>,
1965    pub kind: SymbolKind,
1966    pub start_line: u32,
1967    pub end_line: u32,
1968    pub exported: bool,
1969    pub snippet: String,
1970    pub score: f32,
1971    pub rank_score: f32,
1972    pub cap_protected: bool,
1973    pub source: &'static str,
1974}
1975
1976fn relativize_semantic_map<T>(
1977    project_root: &Path,
1978    map: HashMap<PathBuf, T>,
1979) -> Option<HashMap<PathBuf, T>> {
1980    map.into_iter()
1981        .map(|(path, value)| cache_relative_path(project_root, &path).map(|path| (path, value)))
1982        .collect()
1983}
1984
1985impl SemanticIndex {
1986    fn from_shared_base(project_root: PathBuf, shared_base: Arc<SharedSemanticBase>) -> Self {
1987        debug_assert!(project_root.is_absolute());
1988        Self {
1989            entries: Vec::new(),
1990            file_mtimes: HashMap::new(),
1991            file_sizes: HashMap::new(),
1992            any_missing_sizes: false,
1993            file_hashes: HashMap::new(),
1994            dimension: shared_base.dimension,
1995            fingerprint: shared_base.fingerprint.clone(),
1996            project_root,
1997            deferred_files: HashSet::new(),
1998            shared_base: Some(shared_base),
1999            #[cfg(test)]
2000            removal_retain_passes: 0,
2001        }
2002    }
2003
2004    fn into_shared_base(mut self) -> Option<SharedSemanticBase> {
2005        for entry in &mut self.entries {
2006            entry.chunk.file = cache_relative_path(&self.project_root, &entry.chunk.file)?;
2007        }
2008        let deferred_files = self
2009            .deferred_files
2010            .into_iter()
2011            .map(|path| cache_relative_path(&self.project_root, &path))
2012            .collect::<Option<HashSet<_>>>()?;
2013        Some(SharedSemanticBase {
2014            entries: self.entries,
2015            file_mtimes: relativize_semantic_map(&self.project_root, self.file_mtimes)?,
2016            file_sizes: relativize_semantic_map(&self.project_root, self.file_sizes)?,
2017            any_missing_sizes: self.any_missing_sizes,
2018            file_hashes: relativize_semantic_map(&self.project_root, self.file_hashes)?,
2019            dimension: self.dimension,
2020            fingerprint: self.fingerprint,
2021            deferred_files,
2022        })
2023    }
2024
2025    fn materialize_shared_base(&mut self) {
2026        let Some(base) = self.shared_base.take() else {
2027            return;
2028        };
2029        self.entries = base
2030            .entries
2031            .iter()
2032            .cloned()
2033            .map(|mut entry| {
2034                entry.chunk.file = self.project_root.join(&entry.chunk.file);
2035                entry
2036            })
2037            .collect();
2038        self.file_mtimes = base
2039            .file_mtimes
2040            .iter()
2041            .map(|(path, value)| (self.project_root.join(path), *value))
2042            .collect();
2043        self.file_sizes = base
2044            .file_sizes
2045            .iter()
2046            .map(|(path, value)| (self.project_root.join(path), *value))
2047            .collect();
2048        self.any_missing_sizes = base.any_missing_sizes;
2049        self.file_hashes = base
2050            .file_hashes
2051            .iter()
2052            .map(|(path, value)| (self.project_root.join(path), *value))
2053            .collect();
2054        self.dimension = base.dimension;
2055        self.fingerprint = base.fingerprint.clone();
2056        self.deferred_files = base
2057            .deferred_files
2058            .iter()
2059            .map(|path| self.project_root.join(path))
2060            .collect();
2061    }
2062
2063    pub fn new(project_root: PathBuf, dimension: usize) -> Self {
2064        debug_assert!(project_root.is_absolute());
2065        Self {
2066            entries: Vec::new(),
2067            file_mtimes: HashMap::new(),
2068            file_sizes: HashMap::new(),
2069            any_missing_sizes: false,
2070            file_hashes: HashMap::new(),
2071            dimension,
2072            fingerprint: None,
2073            project_root,
2074            deferred_files: HashSet::new(),
2075            shared_base: None,
2076            #[cfg(test)]
2077            removal_retain_passes: 0,
2078        }
2079    }
2080
2081    /// Number of embedded symbol entries.
2082    pub fn entry_count(&self) -> usize {
2083        self.shared_base
2084            .as_ref()
2085            .map(|base| base.entries.len())
2086            .unwrap_or_else(|| self.entries.len())
2087    }
2088
2089    /// Estimate resident semantic-index bytes from the vectors and metadata
2090    /// actually held by each entry. This intentionally excludes allocator and
2091    /// hash-table bucket overhead, which are not cheaply observable.
2092    pub fn estimated_memory(&self) -> crate::memory::MemoryEstimate {
2093        if let Some(base) = &self.shared_base {
2094            return crate::memory::MemoryEstimate::estimated(0)
2095                .count("entries", base.entries.len())
2096                .count("dimensions", base.dimension)
2097                .count("indexed_files", base.file_mtimes.len())
2098                .count("shared_base_entries", base.entries.len())
2099                .count("overlay_entries", 0)
2100                .count_u64("vector_bytes", 0)
2101                .count_u64("text_bytes", 0)
2102                .count_u64("metadata_bytes", 0);
2103        }
2104        if self.entries.is_empty()
2105            && self.file_mtimes.is_empty()
2106            && self.file_sizes.is_empty()
2107            && self.file_hashes.is_empty()
2108            && self.deferred_files.is_empty()
2109        {
2110            return crate::memory::MemoryEstimate::estimated(0)
2111                .count("entries", 0)
2112                .count("dimensions", self.dimension)
2113                .count("indexed_files", 0)
2114                .count_u64("vector_bytes", 0)
2115                .count_u64("text_bytes", 0)
2116                .count_u64("metadata_bytes", 0)
2117                .count_u64("average_text_bytes", 0)
2118                .count_u64("average_metadata_bytes", 0);
2119        }
2120        let vector_bytes = self.entries.iter().fold(0u64, |bytes, entry| {
2121            bytes.saturating_add(
2122                crate::memory::usize_to_u64(entry.vector.len())
2123                    .saturating_mul(std::mem::size_of::<f32>() as u64),
2124            )
2125        });
2126        let text_bytes = self.entries.iter().fold(0u64, |bytes, entry| {
2127            let chunk = &entry.chunk;
2128            bytes
2129                .saturating_add(crate::memory::path_bytes(&chunk.file))
2130                .saturating_add(crate::memory::usize_to_u64(chunk.name.len()))
2131                .saturating_add(
2132                    chunk
2133                        .qualified_name
2134                        .as_ref()
2135                        .map(|name| crate::memory::usize_to_u64(name.len()))
2136                        .unwrap_or(0),
2137                )
2138                .saturating_add(crate::memory::usize_to_u64(chunk.embed_text.len()))
2139                .saturating_add(crate::memory::usize_to_u64(chunk.snippet.len()))
2140        });
2141        let entry_metadata_bytes = crate::memory::usize_to_u64(self.entries.len())
2142            .saturating_mul(std::mem::size_of::<EmbeddingEntry>() as u64);
2143        let file_metadata_bytes = self
2144            .file_mtimes
2145            .keys()
2146            .chain(self.file_sizes.keys())
2147            .chain(self.file_hashes.keys())
2148            .chain(self.deferred_files.iter())
2149            .map(|path| crate::memory::path_bytes(path))
2150            .fold(0u64, u64::saturating_add)
2151            .saturating_add(
2152                crate::memory::usize_to_u64(self.file_mtimes.len())
2153                    .saturating_mul(std::mem::size_of::<SystemTime>() as u64),
2154            )
2155            .saturating_add(
2156                crate::memory::usize_to_u64(self.file_sizes.len())
2157                    .saturating_mul(std::mem::size_of::<u64>() as u64),
2158            )
2159            .saturating_add(
2160                crate::memory::usize_to_u64(self.file_hashes.len())
2161                    .saturating_mul(std::mem::size_of::<blake3::Hash>() as u64),
2162            );
2163        let index_metadata_bytes = crate::memory::path_bytes(&self.project_root).saturating_add(
2164            self.fingerprint
2165                .as_ref()
2166                .map(|fingerprint| {
2167                    crate::memory::usize_to_u64(fingerprint.backend.len())
2168                        .saturating_add(crate::memory::usize_to_u64(fingerprint.model.len()))
2169                        .saturating_add(crate::memory::usize_to_u64(fingerprint.base_url.len()))
2170                })
2171                .unwrap_or(0),
2172        );
2173        let metadata_bytes = entry_metadata_bytes
2174            .saturating_add(file_metadata_bytes)
2175            .saturating_add(index_metadata_bytes);
2176        let entry_count = crate::memory::usize_to_u64(self.entries.len());
2177        crate::memory::MemoryEstimate::estimated(
2178            vector_bytes
2179                .saturating_add(text_bytes)
2180                .saturating_add(metadata_bytes),
2181        )
2182        .count("entries", self.entries.len())
2183        .count("dimensions", self.dimension)
2184        .count("indexed_files", self.file_mtimes.len())
2185        .count_u64("vector_bytes", vector_bytes)
2186        .count_u64("text_bytes", text_bytes)
2187        .count_u64("metadata_bytes", metadata_bytes)
2188        .count_u64(
2189            "average_text_bytes",
2190            text_bytes.checked_div(entry_count).unwrap_or(0),
2191        )
2192        .count_u64(
2193            "average_metadata_bytes",
2194            metadata_bytes.checked_div(entry_count).unwrap_or(0),
2195        )
2196    }
2197
2198    /// Number of files currently tracked by the semantic index.
2199    pub fn indexed_file_count(&self) -> usize {
2200        self.shared_base
2201            .as_ref()
2202            .map(|base| base.file_mtimes.len())
2203            .unwrap_or_else(|| self.file_mtimes.len())
2204    }
2205
2206    /// Human-readable status label for the index.
2207    pub fn status_label(&self) -> &'static str {
2208        if self.entry_count() == 0 {
2209            "empty"
2210        } else {
2211            "ready"
2212        }
2213    }
2214
2215    fn collect_chunks(
2216        project_root: &Path,
2217        files: &[PathBuf],
2218    ) -> (Vec<SemanticChunk>, HashMap<PathBuf, IndexedFileMetadata>) {
2219        let collect_started = Instant::now();
2220        let collect_one = |file: &Path, sched: Duration| {
2221            let mut phases = SemanticCollectPhaseTimings {
2222                sched,
2223                ..SemanticCollectPhaseTimings::default()
2224            };
2225            let result = collect_semantic_file(project_root, file, &mut phases);
2226            (file.to_path_buf(), result, phases)
2227        };
2228        let per_file: Vec<CollectedSemanticFile> = if files.len() <= 2 {
2229            files
2230                .iter()
2231                .map(|file| collect_one(file, Duration::ZERO))
2232                .collect()
2233        } else {
2234            files
2235                .par_iter()
2236                .map(|file| collect_one(file, collect_started.elapsed()))
2237                .collect()
2238        };
2239
2240        let mut chunks: Vec<SemanticChunk> = Vec::new();
2241        let mut file_metadata: HashMap<PathBuf, IndexedFileMetadata> = HashMap::new();
2242        let mut phases = SemanticCollectPhaseTimings::default();
2243
2244        for (file, result, file_phases) in per_file {
2245            phases.add_assign(file_phases);
2246            match result {
2247                Ok((metadata, file_chunks)) => {
2248                    file_metadata.insert(file, metadata);
2249                    chunks.extend(file_chunks);
2250                }
2251                Err(error) => {
2252                    // "unsupported file extension" is expected for non-code files
2253                    // (json, xml, .gitignore, etc.) that get included in the
2254                    // project walk. Pre-fix this was swallowed by .unwrap_or_default();
2255                    // we now skip silently to keep the log clean. Only real read/parse
2256                    // errors are worth surfacing.
2257                    if error == "unsupported file extension" {
2258                        continue;
2259                    }
2260                    slog_warn!(
2261                        "failed to collect semantic chunks for {}: {}",
2262                        file.display(),
2263                        error
2264                    );
2265                }
2266            }
2267        }
2268
2269        let collect_ms = collect_started
2270            .elapsed()
2271            .as_millis()
2272            .min(u128::from(u64::MAX)) as u64;
2273        crate::logging::note_semantic_collect(chunks.len(), file_metadata.len(), collect_ms);
2274        slog_info!(
2275            "semantic collect: {} chunks from {} files in {} ms",
2276            chunks.len(),
2277            file_metadata.len(),
2278            collect_ms
2279        );
2280        if collect_ms > 50 {
2281            slog_info!(
2282                "semantic collect phases: sched={}ms read_hash={}ms parse={}ms extract={}ms build={}ms",
2283                phases.sched.as_millis(),
2284                phases.read_hash.as_millis(),
2285                phases.parse.as_millis(),
2286                phases.extract.as_millis(),
2287                phases.build.as_millis(),
2288            );
2289        }
2290
2291        (chunks, file_metadata)
2292    }
2293
2294    fn build_chunk_reuse_map(&self, files: &[PathBuf]) -> ChunkReuseMap {
2295        let requested: HashSet<&Path> = files.iter().map(PathBuf::as_path).collect();
2296        let mut reuse_map: ChunkReuseMap = HashMap::new();
2297
2298        for entry in &self.entries {
2299            if !requested.contains(entry.chunk.file.as_path()) {
2300                continue;
2301            }
2302
2303            // `embed_text` is already persisted in the current on-disk format,
2304            // so refresh-time reuse can hash it in memory and confirm the exact
2305            // string without bumping `SEMANTIC_INDEX_VERSION` and forcing every
2306            // user through a full rebuild.
2307            let hash = blake3::hash(entry.chunk.embed_text.as_bytes());
2308            reuse_map
2309                .entry(entry.chunk.file.clone())
2310                .or_default()
2311                .entry(hash)
2312                .or_default()
2313                .push(ReusableEmbedding {
2314                    embed_text: entry.chunk.embed_text.clone(),
2315                    vector: entry.vector.clone(),
2316                });
2317        }
2318
2319        reuse_map
2320    }
2321
2322    fn reusable_vector_for_chunk(
2323        reuse_map: &ChunkReuseMap,
2324        chunk: &SemanticChunk,
2325    ) -> Option<Vec<f32>> {
2326        let hash = blake3::hash(chunk.embed_text.as_bytes());
2327        reuse_map
2328            .get(&chunk.file)?
2329            .get(&hash)?
2330            .iter()
2331            .find(|candidate| candidate.embed_text == chunk.embed_text)
2332            .map(|candidate| candidate.vector.clone())
2333    }
2334
2335    fn entries_for_chunks_with_reuse<F, P>(
2336        chunks: Vec<SemanticChunk>,
2337        reuse_map: &ChunkReuseMap,
2338        embed_fn: &mut F,
2339        max_batch_size: usize,
2340        initial_observed_dimension: Option<usize>,
2341        refresh_label: &str,
2342        progress: &mut P,
2343    ) -> Result<(Vec<EmbeddingEntry>, Option<usize>), String>
2344    where
2345        F: FnMut(Vec<String>) -> Result<Vec<Vec<f32>>, String>,
2346        P: FnMut(usize, usize),
2347    {
2348        let total_chunks = chunks.len();
2349        progress(0, total_chunks);
2350
2351        let mut entries_by_chunk: Vec<Option<EmbeddingEntry>> = vec![None; total_chunks];
2352        let mut misses: Vec<(usize, SemanticChunk)> = Vec::new();
2353
2354        for (chunk_index, chunk) in chunks.into_iter().enumerate() {
2355            if let Some(vector) = Self::reusable_vector_for_chunk(reuse_map, &chunk) {
2356                entries_by_chunk[chunk_index] = Some(EmbeddingEntry::new(chunk, vector));
2357            } else {
2358                misses.push((chunk_index, chunk));
2359            }
2360        }
2361
2362        let mut completed = total_chunks.saturating_sub(misses.len());
2363        if completed > 0 {
2364            progress(completed, total_chunks);
2365        }
2366
2367        let batch_size = max_batch_size.max(1);
2368        let mut observed_dimension = initial_observed_dimension;
2369
2370        for batch_start in (0..misses.len()).step_by(batch_size) {
2371            let batch_end = (batch_start + batch_size).min(misses.len());
2372            let batch_texts: Vec<String> = misses[batch_start..batch_end]
2373                .iter()
2374                .map(|(_, chunk)| chunk.embed_text.clone())
2375                .collect();
2376
2377            let vectors = embed_fn(batch_texts)?;
2378            validate_embedding_batch(&vectors, batch_end - batch_start, "embedding backend")?;
2379
2380            if let Some(dim) = vectors.first().map(|vector| vector.len()) {
2381                match observed_dimension {
2382                    None => observed_dimension = Some(dim),
2383                    Some(expected) if dim != expected => {
2384                        return Err(format!(
2385                            "embedding dimension changed during {refresh_label}: \
2386                             cached index uses {expected}, new vectors use {dim}"
2387                        ));
2388                    }
2389                    _ => {}
2390                }
2391            }
2392
2393            for (i, vector) in vectors.into_iter().enumerate() {
2394                let (chunk_index, chunk) = misses[batch_start + i].clone();
2395                entries_by_chunk[chunk_index] = Some(EmbeddingEntry::new(chunk, vector));
2396            }
2397
2398            completed += batch_end - batch_start;
2399            progress(completed, total_chunks);
2400        }
2401
2402        let entries = entries_by_chunk
2403            .into_iter()
2404            .map(|entry| entry.expect("semantic refresh accounted for every chunk"))
2405            .collect();
2406
2407        Ok((entries, observed_dimension))
2408    }
2409
2410    fn build_from_chunks<F, P>(
2411        project_root: &Path,
2412        chunks: Vec<SemanticChunk>,
2413        file_metadata: HashMap<PathBuf, IndexedFileMetadata>,
2414        embed_fn: &mut F,
2415        max_batch_size: usize,
2416        mut progress: Option<&mut P>,
2417    ) -> Result<Self, String>
2418    where
2419        F: FnMut(Vec<String>) -> Result<Vec<Vec<f32>>, String>,
2420        P: FnMut(usize, usize),
2421    {
2422        debug_assert!(project_root.is_absolute());
2423        let total_chunks = chunks.len();
2424
2425        if chunks.is_empty() {
2426            return Ok(Self {
2427                entries: Vec::new(),
2428                file_mtimes: file_metadata
2429                    .iter()
2430                    .map(|(path, metadata)| (path.clone(), metadata.mtime))
2431                    .collect(),
2432                file_sizes: file_metadata
2433                    .iter()
2434                    .map(|(path, metadata)| (path.clone(), metadata.size))
2435                    .collect(),
2436                any_missing_sizes: false,
2437                file_hashes: file_metadata
2438                    .into_iter()
2439                    .map(|(path, metadata)| (path, metadata.content_hash))
2440                    .collect(),
2441                dimension: DEFAULT_DIMENSION,
2442                fingerprint: None,
2443                project_root: project_root.to_path_buf(),
2444                deferred_files: HashSet::new(),
2445                shared_base: None,
2446                #[cfg(test)]
2447                removal_retain_passes: 0,
2448            });
2449        }
2450
2451        // Embed in batches
2452        let mut entries: Vec<EmbeddingEntry> = Vec::with_capacity(chunks.len());
2453        let mut expected_dimension: Option<usize> = None;
2454        let batch_size = max_batch_size.max(1);
2455        let embed_started = std::time::Instant::now();
2456        let batch_count = total_chunks.div_ceil(batch_size);
2457        for batch_start in (0..chunks.len()).step_by(batch_size) {
2458            let batch_end = (batch_start + batch_size).min(chunks.len());
2459            let batch_texts: Vec<String> = chunks[batch_start..batch_end]
2460                .iter()
2461                .map(|c| c.embed_text.clone())
2462                .collect();
2463
2464            let vectors = embed_fn(batch_texts)?;
2465            validate_embedding_batch(&vectors, batch_end - batch_start, "embedding backend")?;
2466
2467            // Track consistent dimension across all batches
2468            if let Some(dim) = vectors.first().map(|v| v.len()) {
2469                match expected_dimension {
2470                    None => expected_dimension = Some(dim),
2471                    Some(expected) if dim != expected => {
2472                        return Err(format!(
2473                            "embedding dimension changed across batches: expected {expected}, got {dim}"
2474                        ));
2475                    }
2476                    _ => {}
2477                }
2478            }
2479
2480            for (i, vector) in vectors.into_iter().enumerate() {
2481                let chunk_idx = batch_start + i;
2482                entries.push(EmbeddingEntry::new(chunks[chunk_idx].clone(), vector));
2483            }
2484
2485            if let Some(callback) = progress.as_mut() {
2486                callback(entries.len(), total_chunks);
2487            }
2488        }
2489
2490        let embed_ms = embed_started.elapsed().as_millis();
2491        let rate = (total_chunks as u128 * 1000)
2492            .checked_div(embed_ms)
2493            .unwrap_or(0) as u64;
2494        slog_info!(
2495            "semantic embed: {} chunks in {} batches, {} ms ({} chunks/s)",
2496            total_chunks,
2497            batch_count,
2498            embed_ms,
2499            rate
2500        );
2501
2502        let dimension = entries
2503            .first()
2504            .map(|e| e.vector.len())
2505            .unwrap_or(DEFAULT_DIMENSION);
2506
2507        Ok(Self {
2508            entries,
2509            file_mtimes: file_metadata
2510                .iter()
2511                .map(|(path, metadata)| (path.clone(), metadata.mtime))
2512                .collect(),
2513            file_sizes: file_metadata
2514                .iter()
2515                .map(|(path, metadata)| (path.clone(), metadata.size))
2516                .collect(),
2517            any_missing_sizes: false,
2518            file_hashes: file_metadata
2519                .into_iter()
2520                .map(|(path, metadata)| (path, metadata.content_hash))
2521                .collect(),
2522            dimension,
2523            fingerprint: None,
2524            project_root: project_root.to_path_buf(),
2525            deferred_files: HashSet::new(),
2526            shared_base: None,
2527            #[cfg(test)]
2528            removal_retain_passes: 0,
2529        })
2530    }
2531
2532    /// Build the semantic index from a set of files using the provided embedding function.
2533    /// `embed_fn` takes a batch of texts and returns a batch of embedding vectors.
2534    pub fn build<F>(
2535        project_root: &Path,
2536        files: &[PathBuf],
2537        embed_fn: &mut F,
2538        max_batch_size: usize,
2539    ) -> Result<Self, String>
2540    where
2541        F: FnMut(Vec<String>) -> Result<Vec<Vec<f32>>, String>,
2542    {
2543        let (chunks, file_mtimes) = Self::collect_chunks(project_root, files);
2544        Self::build_from_chunks(
2545            project_root,
2546            chunks,
2547            file_mtimes,
2548            embed_fn,
2549            max_batch_size,
2550            Option::<&mut fn(usize, usize)>::None,
2551        )
2552    }
2553
2554    /// Build the semantic index and report embedding progress using entry counts.
2555    pub fn build_with_progress<F, P>(
2556        project_root: &Path,
2557        files: &[PathBuf],
2558        embed_fn: &mut F,
2559        max_batch_size: usize,
2560        progress: &mut P,
2561    ) -> Result<Self, String>
2562    where
2563        F: FnMut(Vec<String>) -> Result<Vec<Vec<f32>>, String>,
2564        P: FnMut(usize, usize),
2565    {
2566        let (chunks, file_mtimes) = Self::collect_chunks(project_root, files);
2567        let total_chunks = chunks.len();
2568        progress(0, total_chunks);
2569        Self::build_from_chunks(
2570            project_root,
2571            chunks,
2572            file_mtimes,
2573            embed_fn,
2574            max_batch_size,
2575            Some(progress),
2576        )
2577    }
2578
2579    /// Incrementally refresh entries for changed/new files only, preserving cached
2580    /// embeddings for unchanged files. Used when loading the index from disk and
2581    /// finding that a small fraction of files have moved on, deleted, or appeared.
2582    ///
2583    /// Returns `RefreshSummary` describing what changed. On success, `self` is
2584    /// mutated in place and remains a valid index.
2585    ///
2586    /// `current_files` is the full set of files the project considers indexable
2587    /// (typically `walk_project_files(...)`). Files in the cache that are no
2588    /// longer in this set are treated as deleted.
2589    pub fn refresh_stale_files<F, P>(
2590        &mut self,
2591        project_root: &Path,
2592        current_files: &[PathBuf],
2593        embed_fn: &mut F,
2594        max_batch_size: usize,
2595        progress: &mut P,
2596    ) -> Result<RefreshSummary, String>
2597    where
2598        F: FnMut(Vec<String>) -> Result<Vec<Vec<f32>>, String>,
2599        P: FnMut(usize, usize),
2600    {
2601        self.refresh_stale_files_with_strategy(
2602            project_root,
2603            current_files,
2604            embed_fn,
2605            max_batch_size,
2606            progress,
2607            cache_freshness::VerifyStrategy::Strict,
2608        )
2609    }
2610
2611    pub(crate) fn refresh_stale_files_with_strategy<F, P>(
2612        &mut self,
2613        project_root: &Path,
2614        current_files: &[PathBuf],
2615        embed_fn: &mut F,
2616        max_batch_size: usize,
2617        progress: &mut P,
2618        verify_strategy: cache_freshness::VerifyStrategy,
2619    ) -> Result<RefreshSummary, String>
2620    where
2621        F: FnMut(Vec<String>) -> Result<Vec<Vec<f32>>, String>,
2622        P: FnMut(usize, usize),
2623    {
2624        self.materialize_shared_base();
2625        self.backfill_missing_file_sizes();
2626
2627        // 1. Bucket files into deleted / changed / added.
2628        let current_set: HashSet<&Path> = current_files.iter().map(PathBuf::as_path).collect();
2629        self.deferred_files
2630            .retain(|path| current_set.contains(path.as_path()));
2631        let total_processed = current_set.len() + self.file_mtimes.len()
2632            - self
2633                .file_mtimes
2634                .keys()
2635                .filter(|path| current_set.contains(path.as_path()))
2636                .count();
2637
2638        // Files in cache that disappeared from disk OR are no longer in the
2639        // walked set. Both cases need their entries dropped.
2640        enum IndexedFileCheck {
2641            Deleted(PathBuf),
2642            MissingMetadata(PathBuf),
2643            Verified(PathBuf, FreshnessVerdict),
2644        }
2645
2646        let mut deleted: Vec<PathBuf> = Vec::new();
2647        let mut changed: Vec<PathBuf> = Vec::new();
2648        let indexed_paths: Vec<PathBuf> = self.file_mtimes.keys().cloned().collect();
2649        let mut checks: Vec<Option<IndexedFileCheck>> = Vec::with_capacity(indexed_paths.len());
2650        let mut strict_verify_inputs: Vec<(usize, PathBuf, FileFreshness)> = Vec::new();
2651
2652        for indexed_path in indexed_paths {
2653            let check_index = checks.len();
2654            if !current_set.contains(indexed_path.as_path()) {
2655                checks.push(Some(IndexedFileCheck::Deleted(indexed_path)));
2656                continue;
2657            }
2658            let cached = match (
2659                self.file_mtimes.get(&indexed_path),
2660                self.file_sizes.get(&indexed_path),
2661                self.file_hashes.get(&indexed_path),
2662            ) {
2663                (Some(mtime), Some(size), Some(hash)) => Some(FileFreshness {
2664                    mtime: *mtime,
2665                    size: *size,
2666                    content_hash: *hash,
2667                }),
2668                _ => None,
2669            };
2670            if let Some(freshness) = cached {
2671                strict_verify_inputs.push((check_index, indexed_path, freshness));
2672                checks.push(None);
2673            } else {
2674                checks.push(Some(IndexedFileCheck::MissingMetadata(indexed_path)));
2675            }
2676        }
2677
2678        let verified = match verify_strategy {
2679            cache_freshness::VerifyStrategy::StatFirst => cache_freshness::verify_files_bounded(
2680                strict_verify_inputs,
2681                cache_freshness::VerifyStrategy::StatFirst,
2682            ),
2683            cache_freshness::VerifyStrategy::Strict => {
2684                cache_freshness::verify_files_strict_bounded(strict_verify_inputs)
2685            }
2686        };
2687        for (check_index, path, verdict) in verified {
2688            checks[check_index] = Some(IndexedFileCheck::Verified(path, verdict));
2689        }
2690
2691        for check in checks {
2692            match check.expect("freshness check should be populated") {
2693                IndexedFileCheck::Deleted(path) => deleted.push(path),
2694                IndexedFileCheck::MissingMetadata(path) => changed.push(path),
2695                IndexedFileCheck::Verified(_path, FreshnessVerdict::HotFresh) => {}
2696                IndexedFileCheck::Verified(
2697                    path,
2698                    FreshnessVerdict::ContentFresh {
2699                        new_mtime,
2700                        new_size,
2701                    },
2702                ) => {
2703                    self.file_mtimes.insert(path.clone(), new_mtime);
2704                    self.file_sizes.insert(path, new_size);
2705                }
2706                IndexedFileCheck::Verified(
2707                    path,
2708                    FreshnessVerdict::Stale | FreshnessVerdict::Deleted,
2709                ) => {
2710                    changed.push(path);
2711                }
2712            }
2713        }
2714
2715        // Files in walk that were never indexed.
2716        let mut added: Vec<PathBuf> = Vec::new();
2717        for path in current_files {
2718            if !self.file_mtimes.contains_key(path) {
2719                added.push(path.clone());
2720            }
2721        }
2722
2723        // Fast path: nothing to do.
2724        if deleted.is_empty() && changed.is_empty() && added.is_empty() {
2725            progress(0, 0);
2726            return Ok(RefreshSummary {
2727                total_processed,
2728                ..RefreshSummary::default()
2729            });
2730        }
2731
2732        // 2. Drop entries for deleted files immediately. Changed files are only
2733        //    replaced after successful re-extraction + embedding so transient
2734        //    read/parse errors keep the stale-but-valid cache entry.
2735        if !deleted.is_empty() {
2736            self.remove_indexed_files(&deleted);
2737        }
2738
2739        // 3. Embed the changed + added set, if any.
2740        let mut to_embed: Vec<PathBuf> = Vec::with_capacity(changed.len() + added.len());
2741        to_embed.extend(changed.iter().cloned());
2742        to_embed.extend(added.iter().cloned());
2743
2744        if to_embed.is_empty() {
2745            // Only deletions happened.
2746            progress(0, 0);
2747            return Ok(RefreshSummary {
2748                changed: 0,
2749                added: 0,
2750                deleted: deleted.len(),
2751                total_processed,
2752            });
2753        }
2754
2755        let reuse_map = self.build_chunk_reuse_map(&changed);
2756        let (chunks, fresh_metadata) = Self::collect_chunks(project_root, &to_embed);
2757        let changed_set: HashSet<&Path> = changed.iter().map(PathBuf::as_path).collect();
2758        let vanished = to_embed
2759            .iter()
2760            .filter(|path| {
2761                changed_set.contains(path.as_path())
2762                    && !fresh_metadata.contains_key(*path)
2763                    && !path.exists()
2764            })
2765            .cloned()
2766            .collect::<Vec<_>>();
2767        if !vanished.is_empty() {
2768            self.remove_indexed_files(&vanished);
2769            deleted.extend(vanished);
2770        }
2771
2772        if chunks.is_empty() {
2773            progress(0, 0);
2774            let successful_files: HashSet<PathBuf> = fresh_metadata.keys().cloned().collect();
2775            for file in &successful_files {
2776                self.deferred_files.remove(file);
2777            }
2778            if !successful_files.is_empty() {
2779                self.entries
2780                    .retain(|entry| !successful_files.contains(&entry.chunk.file));
2781            }
2782            let changed_count = changed
2783                .iter()
2784                .filter(|path| successful_files.contains(*path))
2785                .count();
2786            let added_count = added
2787                .iter()
2788                .filter(|path| successful_files.contains(*path))
2789                .count();
2790            for (file, metadata) in fresh_metadata {
2791                self.file_mtimes.insert(file.clone(), metadata.mtime);
2792                self.file_sizes.insert(file.clone(), metadata.size);
2793                self.file_hashes.insert(file.clone(), metadata.content_hash);
2794            }
2795            return Ok(RefreshSummary {
2796                changed: changed_count,
2797                added: added_count,
2798                deleted: deleted.len(),
2799                total_processed,
2800            });
2801        }
2802
2803        // 4. Build the full replacement set, reusing cached vectors for chunks
2804        //    whose embed_text is unchanged and embedding only cache misses.
2805        let existing_dimension = if self.entries.is_empty() {
2806            None
2807        } else {
2808            Some(self.dimension)
2809        };
2810        let (new_entries, observed_dimension) = Self::entries_for_chunks_with_reuse(
2811            chunks,
2812            &reuse_map,
2813            embed_fn,
2814            max_batch_size,
2815            existing_dimension,
2816            "incremental refresh",
2817            progress,
2818        )?;
2819
2820        let successful_files: HashSet<PathBuf> = fresh_metadata.keys().cloned().collect();
2821        for file in &successful_files {
2822            self.deferred_files.remove(file);
2823        }
2824        if !successful_files.is_empty() {
2825            self.entries
2826                .retain(|entry| !successful_files.contains(&entry.chunk.file));
2827        }
2828
2829        self.entries.extend(new_entries);
2830        for (file, metadata) in fresh_metadata {
2831            self.file_mtimes.insert(file.clone(), metadata.mtime);
2832            self.file_sizes.insert(file.clone(), metadata.size);
2833            self.file_hashes.insert(file, metadata.content_hash);
2834        }
2835        if let Some(dim) = observed_dimension {
2836            self.dimension = dim;
2837        }
2838
2839        Ok(RefreshSummary {
2840            changed: changed
2841                .iter()
2842                .filter(|path| successful_files.contains(*path))
2843                .count(),
2844            added: added
2845                .iter()
2846                .filter(|path| successful_files.contains(*path))
2847                .count(),
2848            deleted: deleted.len(),
2849            total_processed,
2850        })
2851    }
2852
2853    /// Refresh exactly the files invalidated by the live watcher, without
2854    /// treating the provided path list as the whole project. This is the
2855    /// watcher-side counterpart to `refresh_stale_files`: it drops any stale
2856    /// entries for the requested paths from this in-memory index, re-extracts
2857    /// whatever still exists on disk, embeds those chunks, and returns the
2858    /// delta needed for another in-memory index to apply the same update.
2859    pub fn refresh_invalidated_files<F, P>(
2860        &mut self,
2861        project_root: &Path,
2862        paths: &[PathBuf],
2863        embed_fn: &mut F,
2864        max_batch_size: usize,
2865        max_files: usize,
2866        progress: &mut P,
2867    ) -> Result<InvalidatedFilesRefresh, String>
2868    where
2869        F: FnMut(Vec<String>) -> Result<Vec<Vec<f32>>, String>,
2870        P: FnMut(usize, usize),
2871    {
2872        self.materialize_shared_base();
2873        self.backfill_missing_file_sizes();
2874
2875        self.deferred_files.retain(|path| path.exists());
2876        let mut requested_paths = paths.to_vec();
2877        requested_paths.extend(self.deferred_files.iter().cloned());
2878        requested_paths.sort();
2879        requested_paths.dedup();
2880        let total_processed = requested_paths.len();
2881
2882        if requested_paths.is_empty() {
2883            progress(0, 0);
2884            return Ok(InvalidatedFilesRefresh {
2885                summary: RefreshSummary {
2886                    total_processed,
2887                    ..RefreshSummary::default()
2888                },
2889                ..InvalidatedFilesRefresh::default()
2890            });
2891        }
2892
2893        let previously_indexed: HashSet<PathBuf> = requested_paths
2894            .iter()
2895            .filter(|path| self.file_mtimes.contains_key(*path))
2896            .cloned()
2897            .collect();
2898        let reuse_map = self.build_chunk_reuse_map(&requested_paths);
2899
2900        // The watcher path has already invalidated these files in the request
2901        // thread's live index. Mirror that behavior here before inserting any
2902        // fresh chunks so parse/read failures do not resurrect stale entries.
2903        self.remove_indexed_files(&requested_paths);
2904
2905        let existing_paths = requested_paths
2906            .iter()
2907            .filter(|path| path.exists())
2908            .cloned()
2909            .collect::<Vec<_>>();
2910        let deleted = requested_paths
2911            .iter()
2912            .filter(|path| !path.exists() && previously_indexed.contains(path.as_path()))
2913            .count();
2914
2915        if existing_paths.is_empty() {
2916            for path in &requested_paths {
2917                if !path.exists() {
2918                    self.deferred_files.remove(path);
2919                }
2920            }
2921            progress(0, 0);
2922            return Ok(InvalidatedFilesRefresh {
2923                completed_paths: requested_paths,
2924                summary: RefreshSummary {
2925                    deleted,
2926                    total_processed,
2927                    ..RefreshSummary::default()
2928                },
2929                ..InvalidatedFilesRefresh::default()
2930            });
2931        }
2932
2933        let (mut chunks, mut fresh_metadata) = Self::collect_chunks(project_root, &existing_paths);
2934
2935        let retained_file_count = self.file_mtimes.len();
2936        let changed_successful_count = existing_paths
2937            .iter()
2938            .filter(|path| {
2939                previously_indexed.contains(path.as_path()) && fresh_metadata.contains_key(*path)
2940            })
2941            .count();
2942        let available_new_files =
2943            max_files.saturating_sub(retained_file_count.saturating_add(changed_successful_count));
2944        let new_successful_files = existing_paths
2945            .iter()
2946            .filter(|path| {
2947                !previously_indexed.contains(path.as_path()) && fresh_metadata.contains_key(*path)
2948            })
2949            .cloned()
2950            .collect::<Vec<_>>();
2951        if new_successful_files.len() > available_new_files {
2952            let allowed_new_files = new_successful_files
2953                .iter()
2954                .take(available_new_files)
2955                .cloned()
2956                .collect::<HashSet<_>>();
2957            let deferred_new_files = new_successful_files
2958                .into_iter()
2959                .filter(|path| !allowed_new_files.contains(path))
2960                .collect::<HashSet<_>>();
2961
2962            fresh_metadata.retain(|file, _| {
2963                previously_indexed.contains(file.as_path()) || allowed_new_files.contains(file)
2964            });
2965            chunks.retain(|chunk| !deferred_new_files.contains(&chunk.file));
2966
2967            if !deferred_new_files.is_empty() {
2968                for path in &deferred_new_files {
2969                    self.deferred_files.insert(path.clone());
2970                }
2971                slog_warn!(
2972                    "semantic refresh deferred {} new file(s): indexed-file cap {} is reached",
2973                    deferred_new_files.len(),
2974                    max_files
2975                );
2976            }
2977        }
2978
2979        let successful_files: HashSet<PathBuf> = fresh_metadata.keys().cloned().collect();
2980        for file in &successful_files {
2981            self.deferred_files.remove(file);
2982        }
2983        let changed = successful_files
2984            .iter()
2985            .filter(|path| previously_indexed.contains(path.as_path()))
2986            .count();
2987        let added = successful_files.len().saturating_sub(changed);
2988        let mut updated_metadata = Vec::with_capacity(fresh_metadata.len());
2989
2990        if chunks.is_empty() {
2991            progress(0, 0);
2992            for (file, metadata) in fresh_metadata {
2993                let freshness = FileFreshness {
2994                    mtime: metadata.mtime,
2995                    size: metadata.size,
2996                    content_hash: metadata.content_hash,
2997                };
2998                self.file_mtimes.insert(file.clone(), freshness.mtime);
2999                self.file_sizes.insert(file.clone(), freshness.size);
3000                self.file_hashes
3001                    .insert(file.clone(), freshness.content_hash);
3002                updated_metadata.push((file, freshness));
3003            }
3004
3005            return Ok(InvalidatedFilesRefresh {
3006                updated_metadata,
3007                completed_paths: requested_paths,
3008                summary: RefreshSummary {
3009                    changed,
3010                    added,
3011                    deleted,
3012                    total_processed,
3013                },
3014                ..InvalidatedFilesRefresh::default()
3015            });
3016        }
3017
3018        let initial_observed_dimension = if self.entries.is_empty() && previously_indexed.is_empty()
3019        {
3020            None
3021        } else {
3022            Some(self.dimension)
3023        };
3024        let (new_entries, observed_dimension) = Self::entries_for_chunks_with_reuse(
3025            chunks,
3026            &reuse_map,
3027            embed_fn,
3028            max_batch_size,
3029            initial_observed_dimension,
3030            "invalidated-file refresh",
3031            progress,
3032        )?;
3033
3034        let added_entries = new_entries.clone();
3035        self.entries.extend(new_entries);
3036        for (file, metadata) in fresh_metadata {
3037            let freshness = FileFreshness {
3038                mtime: metadata.mtime,
3039                size: metadata.size,
3040                content_hash: metadata.content_hash,
3041            };
3042            self.file_mtimes.insert(file.clone(), freshness.mtime);
3043            self.file_sizes.insert(file.clone(), freshness.size);
3044            self.file_hashes
3045                .insert(file.clone(), freshness.content_hash);
3046            updated_metadata.push((file, freshness));
3047        }
3048        if let Some(dim) = observed_dimension {
3049            self.dimension = dim;
3050        }
3051
3052        Ok(InvalidatedFilesRefresh {
3053            added_entries,
3054            updated_metadata,
3055            completed_paths: requested_paths,
3056            summary: RefreshSummary {
3057                changed,
3058                added,
3059                deleted,
3060                total_processed,
3061            },
3062        })
3063    }
3064
3065    pub fn apply_refresh_update(
3066        &mut self,
3067        added_entries: Vec<EmbeddingEntry>,
3068        updated_metadata: Vec<(PathBuf, FileFreshness)>,
3069        completed_paths: &[PathBuf],
3070    ) {
3071        self.materialize_shared_base();
3072        // `added_entries` is the complete replacement set for completed paths:
3073        // freshly embedded misses plus reused chunks carrying refreshed metadata.
3074        // Removing first is safe only because producers include both kinds.
3075        self.remove_indexed_files(completed_paths);
3076
3077        let observed_dimension = added_entries.first().map(|entry| entry.vector.len());
3078        self.entries.extend(added_entries);
3079        for (file, freshness) in updated_metadata {
3080            self.file_mtimes.insert(file.clone(), freshness.mtime);
3081            self.file_sizes.insert(file.clone(), freshness.size);
3082            self.file_hashes.insert(file, freshness.content_hash);
3083        }
3084        if let Some(dim) = observed_dimension {
3085            self.dimension = dim;
3086        }
3087    }
3088
3089    fn remove_indexed_file_keys(
3090        &mut self,
3091        entry_files: &HashSet<PathBuf>,
3092        metadata_files: &[PathBuf],
3093    ) {
3094        #[cfg(test)]
3095        {
3096            self.removal_retain_passes += 1;
3097        }
3098        self.entries
3099            .retain(|entry| !entry_files.contains(&entry.chunk.file));
3100        for path in metadata_files {
3101            self.file_mtimes.remove(path);
3102            self.file_sizes.remove(path);
3103            self.file_hashes.remove(path);
3104        }
3105    }
3106
3107    fn remove_indexed_files(&mut self, files: &[PathBuf]) {
3108        let deleted_set = files.iter().cloned().collect();
3109        self.remove_indexed_file_keys(&deleted_set, files);
3110    }
3111
3112    /// Search the index with a query embedding, returning top-K results sorted by relevance
3113    pub fn search(&self, query_vector: &[f32], top_k: usize) -> Vec<SemanticResult> {
3114        let (entries, dimension) = self
3115            .shared_base
3116            .as_ref()
3117            .map(|base| (base.entries.as_slice(), base.dimension))
3118            .unwrap_or_else(|| (self.entries.as_slice(), self.dimension));
3119        if entries.is_empty() || query_vector.len() != dimension {
3120            return Vec::new();
3121        }
3122
3123        // Query norms are shared by every entry; entry norms are cached because
3124        // remote embedding backends may return non-normalized vectors.
3125        let query_norm = vector_norm(query_vector);
3126        let mut scored: Vec<(f32, usize)> = entries
3127            .iter()
3128            .enumerate()
3129            .map(|(i, entry)| {
3130                let dot = if query_vector.len() == entry.vector.len() {
3131                    dot_product(query_vector, &entry.vector)
3132                } else {
3133                    0.0
3134                };
3135                let denom = query_norm * entry.norm;
3136                let mut score = if denom == 0.0 { 0.0 } else { dot / denom };
3137                if entry.chunk.exported {
3138                    score *= 1.1;
3139                }
3140                (score, i)
3141            })
3142            .collect();
3143
3144        let keep = top_k.min(scored.len());
3145        if keep == 0 {
3146            return Vec::new();
3147        }
3148
3149        if keep < scored.len() {
3150            scored.select_nth_unstable_by(keep, semantic_score_order);
3151            scored.truncate(keep);
3152        }
3153        scored.sort_by(semantic_score_order);
3154
3155        scored
3156            .into_iter()
3157            // Keep the selected best-first slice mapped without reintroducing the
3158            // old `> 0.0` floor: top_k has already been selected, and zero-score
3159            // tail entries remain observable when requested.
3160            .map(|(score, idx)| {
3161                let entry = &entries[idx];
3162                SemanticResult {
3163                    file: if self.shared_base.is_some() {
3164                        self.project_root.join(&entry.chunk.file)
3165                    } else {
3166                        entry.chunk.file.clone()
3167                    },
3168                    name: entry.chunk.name.clone(),
3169                    qualified_name: entry.chunk.qualified_name.clone(),
3170                    kind: entry.chunk.kind.clone(),
3171                    start_line: entry.chunk.start_line,
3172                    end_line: entry.chunk.end_line,
3173                    exported: entry.chunk.exported,
3174                    snippet: entry.chunk.snippet.clone(),
3175                    score,
3176                    rank_score: score,
3177                    cap_protected: false,
3178                    source: "semantic",
3179                }
3180            })
3181            .collect()
3182    }
3183
3184    /// Number of indexed entries
3185    pub fn len(&self) -> usize {
3186        self.entry_count()
3187    }
3188
3189    /// Check if a file needs re-indexing based on mtime/size
3190    pub fn is_file_stale(&self, file: &Path) -> bool {
3191        let relative;
3192        let (file_mtimes, file_sizes, file_hashes, lookup) = if let Some(base) = &self.shared_base {
3193            relative = file
3194                .strip_prefix(&self.project_root)
3195                .unwrap_or(file)
3196                .to_path_buf();
3197            (
3198                &base.file_mtimes,
3199                &base.file_sizes,
3200                &base.file_hashes,
3201                relative.as_path(),
3202            )
3203        } else {
3204            (&self.file_mtimes, &self.file_sizes, &self.file_hashes, file)
3205        };
3206        let Some(stored_mtime) = file_mtimes.get(lookup) else {
3207            return true;
3208        };
3209        let Some(stored_size) = file_sizes.get(lookup) else {
3210            return true;
3211        };
3212        let Some(stored_hash) = file_hashes.get(lookup) else {
3213            return true;
3214        };
3215        let cached = FileFreshness {
3216            mtime: *stored_mtime,
3217            size: *stored_size,
3218            content_hash: *stored_hash,
3219        };
3220        match cache_freshness::verify_file_strict(file, &cached) {
3221            FreshnessVerdict::HotFresh => false,
3222            FreshnessVerdict::ContentFresh { .. } => false,
3223            FreshnessVerdict::Stale | FreshnessVerdict::Deleted => true,
3224        }
3225    }
3226
3227    fn backfill_missing_file_sizes(&mut self) {
3228        if !self.any_missing_sizes {
3229            return;
3230        }
3231
3232        for path in self.file_mtimes.keys() {
3233            if self.file_sizes.contains_key(path) {
3234                continue;
3235            }
3236            if let Ok(metadata) = fs::metadata(path) {
3237                self.file_sizes.insert(path.clone(), metadata.len());
3238                if let Ok(Some(hash)) = cache_freshness::hash_file_if_small(path, metadata.len()) {
3239                    self.file_hashes.insert(path.clone(), hash);
3240                }
3241            }
3242        }
3243        self.any_missing_sizes = self
3244            .file_mtimes
3245            .keys()
3246            .any(|path| !self.file_sizes.contains_key(path));
3247    }
3248
3249    /// Remove entries for a specific file.
3250    pub fn remove_file(&mut self, file: &Path) {
3251        self.invalidate_file(file);
3252    }
3253
3254    pub fn invalidate_file(&mut self, file: &Path) {
3255        let file = file.to_path_buf();
3256        self.invalidate_files(std::slice::from_ref(&file));
3257    }
3258
3259    pub fn invalidate_files(&mut self, files: &[PathBuf]) {
3260        if files.is_empty() {
3261            return;
3262        }
3263        self.materialize_shared_base();
3264
3265        // Watchers may report a symlinked spelling while persisted metadata uses
3266        // the canonical spelling (or vice versa), so both keys must be removed.
3267        let mut invalidated = HashSet::with_capacity(files.len().saturating_mul(2));
3268        let mut metadata_keys = Vec::with_capacity(files.len().saturating_mul(2));
3269        for file in files {
3270            metadata_keys.push(file.clone());
3271            invalidated.insert(file.clone());
3272            let canonical = canonicalize_existing_or_deleted_path(file);
3273            if canonical != *file {
3274                metadata_keys.push(canonical.clone());
3275                invalidated.insert(canonical);
3276            }
3277        }
3278        self.remove_indexed_file_keys(&invalidated, &metadata_keys);
3279    }
3280
3281    #[cfg(test)]
3282    pub(crate) fn removal_retain_passes_for_test(&self) -> usize {
3283        self.removal_retain_passes
3284    }
3285
3286    /// Get the embedding dimension
3287    pub fn dimension(&self) -> usize {
3288        self.shared_base
3289            .as_ref()
3290            .map(|base| base.dimension)
3291            .unwrap_or(self.dimension)
3292    }
3293
3294    pub fn fingerprint(&self) -> Option<&SemanticIndexFingerprint> {
3295        self.shared_base
3296            .as_ref()
3297            .and_then(|base| base.fingerprint.as_ref())
3298            .or(self.fingerprint.as_ref())
3299    }
3300
3301    pub fn backend_label(&self) -> Option<&str> {
3302        self.fingerprint().map(|f| f.backend.as_str())
3303    }
3304
3305    pub fn model_label(&self) -> Option<&str> {
3306        self.fingerprint().map(|f| f.model.as_str())
3307    }
3308
3309    pub fn set_fingerprint(&mut self, fingerprint: SemanticIndexFingerprint) {
3310        self.materialize_shared_base();
3311        self.fingerprint = Some(fingerprint);
3312    }
3313
3314    /// Write the semantic index to disk using atomic temp+rename pattern.
3315    /// Empty indexes are persisted too so a completed rebuild cannot leave an
3316    /// older non-empty snapshot visible to the next process.
3317    pub fn write_to_disk(&self, storage_dir: &Path, project_key: &str) -> bool {
3318        if self.shared_base.is_some() {
3319            let mut private = self.clone();
3320            private.materialize_shared_base();
3321            return private.write_to_disk(storage_dir, project_key);
3322        }
3323        let dir = storage_dir.join("semantic").join(project_key);
3324        let data_path = dir.join("semantic.bin");
3325        let access = crate::root_cache::ArtifactAccess::for_root(&self.project_root);
3326        if !access.allows_write(project_key, &data_path) {
3327            return false;
3328        }
3329        if let Err(e) = fs::create_dir_all(&dir) {
3330            slog_warn!("failed to create semantic cache dir: {}", e);
3331            return false;
3332        }
3333        let tmp_path = dir.join(format!(
3334            "semantic.bin.tmp.{}.{}",
3335            std::process::id(),
3336            SystemTime::now()
3337                .duration_since(SystemTime::UNIX_EPOCH)
3338                .unwrap_or(Duration::ZERO)
3339                .as_nanos()
3340        ));
3341        let write_result = (|| -> io::Result<usize> {
3342            let file = fs::File::create(&tmp_path)?;
3343            let mut writer = BufWriter::new(file);
3344            let bytes_written = self.write_to_writer(&mut writer)?;
3345            writer.flush()?;
3346            writer.get_ref().sync_all()?;
3347            Ok(bytes_written)
3348        })();
3349        let bytes_written = match write_result {
3350            Ok(bytes_written) => bytes_written,
3351            Err(e) => {
3352                slog_warn!("failed to write semantic index: {}", e);
3353                let _ = fs::remove_file(&tmp_path);
3354                return false;
3355            }
3356        };
3357        if let Err(e) = crate::fs_lock::rename_over(&tmp_path, &data_path) {
3358            slog_warn!("failed to rename semantic index: {}", e);
3359            let _ = fs::remove_file(&tmp_path);
3360            return false;
3361        }
3362        slog_info!(
3363            "semantic index persisted: {} entries, {:.1} KB",
3364            self.entries.len(),
3365            bytes_written as f64 / 1024.0
3366        );
3367        true
3368    }
3369
3370    /// Read the semantic index from disk
3371    pub fn read_from_disk(
3372        storage_dir: &Path,
3373        project_key: &str,
3374        current_canonical_root: &Path,
3375        is_worktree_bridge: bool,
3376        expected_fingerprint: Option<&str>,
3377    ) -> Option<Self> {
3378        debug_assert!(current_canonical_root.is_absolute());
3379        let data_path = storage_dir
3380            .join("semantic")
3381            .join(project_key)
3382            .join("semantic.bin");
3383        let file = fs::File::open(&data_path).ok()?;
3384        let file_len = usize::try_from(file.metadata().ok()?.len()).ok()?;
3385        if file_len < HEADER_BYTES_V1 {
3386            slog_warn!(
3387                "corrupt semantic index (too small: {} bytes), removing",
3388                file_len
3389            );
3390            if !is_worktree_bridge {
3391                let _ = fs::remove_file(&data_path);
3392            }
3393            return None;
3394        }
3395
3396        let mut reader = BufReader::new(file);
3397        let mut version_buf = [0u8; 1];
3398        reader.read_exact(&mut version_buf).ok()?;
3399        let version = version_buf[0];
3400        if version != SEMANTIC_INDEX_VERSION_V6 && version != SEMANTIC_INDEX_VERSION_V7 {
3401            slog_info!(
3402            "cached semantic index version {} is not compatible with {}, rebuilding without deleting the shared artifact",
3403            version,
3404            SEMANTIC_INDEX_VERSION_V7
3405        );
3406            return None;
3407        }
3408        match Self::from_reader_after_version(
3409            reader,
3410            version,
3411            current_canonical_root,
3412            Some(file_len),
3413            1,
3414        ) {
3415            Ok(index) => {
3416                if let Some(expected) = expected_fingerprint {
3417                    let matches = index
3418                        .fingerprint()
3419                        .map(|fingerprint| fingerprint.matches_expected(expected))
3420                        .unwrap_or(false);
3421                    if !matches {
3422                        log_fingerprint_mismatch(index.fingerprint(), expected);
3423                        return None;
3424                    }
3425                }
3426                slog_info!(
3427                    "loaded semantic index from disk: {} entries",
3428                    index.entries.len()
3429                );
3430                Some(index)
3431            }
3432            Err(e) => {
3433                slog_warn!("corrupt semantic index, rebuilding: {}", e);
3434                if !is_worktree_bridge {
3435                    let _ = fs::remove_file(&data_path);
3436                }
3437                None
3438            }
3439        }
3440    }
3441
3442    pub(crate) fn read_from_disk_borrow_tolerant(
3443        storage_dir: &Path,
3444        project_key: &str,
3445        current_canonical_root: &Path,
3446    ) -> Option<Self> {
3447        let data_path = storage_dir
3448            .join("semantic")
3449            .join(project_key)
3450            .join("semantic.bin");
3451        let (fingerprint, artifact_content_hash) = match borrowed_artifact_identity(&data_path) {
3452            Ok(identity) => identity,
3453            Err(error) => {
3454                slog_warn!(
3455                    "semantic shared-base identity unavailable ({}); loading a private borrowed copy",
3456                    error
3457                );
3458                return Self::read_from_disk(
3459                    storage_dir,
3460                    project_key,
3461                    current_canonical_root,
3462                    true,
3463                    None,
3464                );
3465            }
3466        };
3467        let key = SharedSemanticBaseKey {
3468            artifact_cache_key: project_key.to_string(),
3469            fingerprint,
3470            artifact_content_hash,
3471        };
3472
3473        {
3474            let mut registry = shared_semantic_bases()
3475                .lock()
3476                .unwrap_or_else(std::sync::PoisonError::into_inner);
3477            registry.retain(|_, base| base.strong_count() > 0);
3478            if let Some(base) = registry.get(&key).and_then(Weak::upgrade) {
3479                SHARED_SEMANTIC_BASE_HITS.fetch_add(1, Ordering::Relaxed);
3480                return Some(Self::from_shared_base(
3481                    current_canonical_root.to_path_buf(),
3482                    base,
3483                ));
3484            }
3485            if registry.keys().any(|existing| {
3486                existing.artifact_cache_key == key.artifact_cache_key && existing != &key
3487            }) {
3488                slog_warn!(
3489                    "semantic shared-base fingerprint or artifact hash changed for key {}; loading a private borrowed copy",
3490                    project_key
3491                );
3492                return Self::read_from_disk(
3493                    storage_dir,
3494                    project_key,
3495                    current_canonical_root,
3496                    true,
3497                    None,
3498                );
3499            }
3500        }
3501
3502        let private = Self::read_from_disk(
3503            storage_dir,
3504            project_key,
3505            current_canonical_root,
3506            true,
3507            Some(&key.fingerprint),
3508        )?;
3509        let Some(base) = private.clone().into_shared_base() else {
3510            slog_warn!(
3511                "semantic shared-base paths could not be normalized for key {}; loading a private borrowed copy",
3512                project_key
3513            );
3514            return Some(private);
3515        };
3516        let base = Arc::new(base);
3517
3518        let mut registry = shared_semantic_bases()
3519            .lock()
3520            .unwrap_or_else(std::sync::PoisonError::into_inner);
3521        registry.retain(|_, base| base.strong_count() > 0);
3522        if let Some(existing) = registry.get(&key).and_then(Weak::upgrade) {
3523            SHARED_SEMANTIC_BASE_HITS.fetch_add(1, Ordering::Relaxed);
3524            return Some(Self::from_shared_base(
3525                current_canonical_root.to_path_buf(),
3526                existing,
3527            ));
3528        }
3529        if registry.keys().any(|existing| {
3530            existing.artifact_cache_key == key.artifact_cache_key && existing != &key
3531        }) {
3532            slog_warn!(
3533                "semantic shared-base identity changed while loading key {}; retaining a private borrowed copy",
3534                project_key
3535            );
3536            return Some(private);
3537        }
3538        registry.insert(key, Arc::downgrade(&base));
3539        SHARED_SEMANTIC_BASE_LOADS.fetch_add(1, Ordering::Relaxed);
3540        Some(Self::from_shared_base(
3541            current_canonical_root.to_path_buf(),
3542            base,
3543        ))
3544    }
3545
3546    /// Serialize the index to bytes for disk persistence
3547    pub fn to_bytes(&self) -> Vec<u8> {
3548        if self.shared_base.is_some() {
3549            let mut private = self.clone();
3550            private.materialize_shared_base();
3551            return private.to_bytes();
3552        }
3553        let mut buf = Vec::new();
3554        self.write_to_writer(&mut buf)
3555            .expect("writing semantic index to Vec cannot fail");
3556        buf
3557    }
3558
3559    fn write_to_writer<W: Write>(&self, writer: &mut W) -> io::Result<usize> {
3560        let mut bytes_written = 0usize;
3561        let fingerprint = self.fingerprint.as_ref().and_then(|fingerprint| {
3562            let encoded = fingerprint.as_string();
3563            if encoded.is_empty() {
3564                None
3565            } else {
3566                Some(encoded)
3567            }
3568        });
3569        let fp_bytes_ref = fingerprint.as_deref().map(str::as_bytes).unwrap_or(&[]);
3570        let file_mtime_count = self
3571            .file_mtimes
3572            .iter()
3573            .filter(|(path, _)| cache_relative_path(&self.project_root, path).is_some())
3574            .count();
3575        let entry_count = self
3576            .entries
3577            .iter()
3578            .filter(|entry| cache_relative_path(&self.project_root, &entry.chunk.file).is_some())
3579            .count();
3580
3581        // Header: version(1) + dimension(4) + entry_count(4) + fingerprint_len(4) + fingerprint
3582        //
3583        // V7 is the single write format. Layout extends V6 with per-entry
3584        // qualified_name metadata while preserving the embedding fingerprint:
3585        //   - fingerprint is always represented (absent ⇒ fingerprint_len=0,
3586        //     no bytes follow). Uniform format simplifies the reader.
3587        //   - paths are relative to project_root.
3588        //   - file metadata stored as secs(u64) + subsec_nanos(u32) + size(u64) + blake3(32).
3589        //     Preserves full APFS/ext4/NTFS precision and catches mtime ties.
3590        //
3591        // V1/V2 remain readable for backward compatibility (see from_bytes).
3592        // V3/V4 load as compatible formats but are rejected on disk so snippets
3593        // and file sizes are rebuilt once. V6 remains accepted on disk and
3594        // yields qualified_name=None until the next V7 write.
3595        let version = SEMANTIC_INDEX_VERSION_V7;
3596        write_counted(writer, &[version], &mut bytes_written)?;
3597        write_counted(
3598            writer,
3599            &(self.dimension as u32).to_le_bytes(),
3600            &mut bytes_written,
3601        )?;
3602        write_counted(
3603            writer,
3604            &(entry_count as u32).to_le_bytes(),
3605            &mut bytes_written,
3606        )?;
3607        write_counted(
3608            writer,
3609            &(fp_bytes_ref.len() as u32).to_le_bytes(),
3610            &mut bytes_written,
3611        )?;
3612        write_counted(writer, fp_bytes_ref, &mut bytes_written)?;
3613
3614        // File mtime table: count(4) + entries
3615        // V3 layout per entry: path_len(4) + path + secs(8) + subsec_nanos(4)
3616        write_counted(
3617            writer,
3618            &(file_mtime_count as u32).to_le_bytes(),
3619            &mut bytes_written,
3620        )?;
3621        for (path, mtime) in &self.file_mtimes {
3622            let Some(relative) = cache_relative_path(&self.project_root, path) else {
3623                continue;
3624            };
3625            let relative = relative.to_string_lossy();
3626            let path_bytes = relative.as_bytes();
3627            write_counted(
3628                writer,
3629                &(path_bytes.len() as u32).to_le_bytes(),
3630                &mut bytes_written,
3631            )?;
3632            write_counted(writer, path_bytes, &mut bytes_written)?;
3633            let duration = mtime
3634                .duration_since(SystemTime::UNIX_EPOCH)
3635                .unwrap_or_default();
3636            write_counted(
3637                writer,
3638                &duration.as_secs().to_le_bytes(),
3639                &mut bytes_written,
3640            )?;
3641            write_counted(
3642                writer,
3643                &duration.subsec_nanos().to_le_bytes(),
3644                &mut bytes_written,
3645            )?;
3646            let size = self.file_sizes.get(path).copied().unwrap_or_default();
3647            write_counted(writer, &size.to_le_bytes(), &mut bytes_written)?;
3648            let hash = self
3649                .file_hashes
3650                .get(path)
3651                .copied()
3652                .unwrap_or_else(cache_freshness::zero_hash);
3653            write_counted(writer, hash.as_bytes(), &mut bytes_written)?;
3654        }
3655
3656        // Entries: each is metadata + vector
3657        for entry in &self.entries {
3658            let Some(relative) = cache_relative_path(&self.project_root, &entry.chunk.file) else {
3659                continue;
3660            };
3661            let c = &entry.chunk;
3662
3663            // File path
3664            let relative = relative.to_string_lossy();
3665            let file_bytes = relative.as_bytes();
3666            write_counted(
3667                writer,
3668                &(file_bytes.len() as u32).to_le_bytes(),
3669                &mut bytes_written,
3670            )?;
3671            write_counted(writer, file_bytes, &mut bytes_written)?;
3672
3673            // Name
3674            let name_bytes = c.name.as_bytes();
3675            write_counted(
3676                writer,
3677                &(name_bytes.len() as u32).to_le_bytes(),
3678                &mut bytes_written,
3679            )?;
3680            write_counted(writer, name_bytes, &mut bytes_written)?;
3681
3682            // Qualified name (V7 metadata; absent is encoded as length 0)
3683            let qualified_name_bytes = c.qualified_name.as_deref().unwrap_or_default().as_bytes();
3684            write_counted(
3685                writer,
3686                &(qualified_name_bytes.len() as u32).to_le_bytes(),
3687                &mut bytes_written,
3688            )?;
3689            write_counted(writer, qualified_name_bytes, &mut bytes_written)?;
3690
3691            // Kind (1 byte)
3692            write_counted(writer, &[symbol_kind_to_u8(&c.kind)], &mut bytes_written)?;
3693
3694            // Lines + exported
3695            write_counted(
3696                writer,
3697                &(c.start_line as u32).to_le_bytes(),
3698                &mut bytes_written,
3699            )?;
3700            write_counted(
3701                writer,
3702                &(c.end_line as u32).to_le_bytes(),
3703                &mut bytes_written,
3704            )?;
3705            write_counted(writer, &[c.exported as u8], &mut bytes_written)?;
3706
3707            // Snippet
3708            let snippet_bytes = c.snippet.as_bytes();
3709            write_counted(
3710                writer,
3711                &(snippet_bytes.len() as u32).to_le_bytes(),
3712                &mut bytes_written,
3713            )?;
3714            write_counted(writer, snippet_bytes, &mut bytes_written)?;
3715
3716            // Embed text
3717            let embed_bytes = c.embed_text.as_bytes();
3718            write_counted(
3719                writer,
3720                &(embed_bytes.len() as u32).to_le_bytes(),
3721                &mut bytes_written,
3722            )?;
3723            write_counted(writer, embed_bytes, &mut bytes_written)?;
3724
3725            // Vector (f32 array)
3726            for &val in &entry.vector {
3727                write_counted(writer, &val.to_le_bytes(), &mut bytes_written)?;
3728            }
3729        }
3730
3731        Ok(bytes_written)
3732    }
3733
3734    /// Deserialize the index from bytes
3735    pub fn from_bytes(data: &[u8], current_canonical_root: &Path) -> Result<Self, String> {
3736        debug_assert!(current_canonical_root.is_absolute());
3737        if data.len() < HEADER_BYTES_V1 {
3738            return Err("data too short".to_string());
3739        }
3740
3741        Self::from_reader_after_version(
3742            Cursor::new(&data[1..]),
3743            data[0],
3744            current_canonical_root,
3745            Some(data.len()),
3746            1,
3747        )
3748    }
3749
3750    fn from_reader_after_version<R: Read>(
3751        reader: R,
3752        version: u8,
3753        current_canonical_root: &Path,
3754        total_len: Option<usize>,
3755        bytes_read: usize,
3756    ) -> Result<Self, String> {
3757        debug_assert!(current_canonical_root.is_absolute());
3758        let mut reader = CountingReader::with_bytes_read(reader, bytes_read);
3759
3760        if version != SEMANTIC_INDEX_VERSION_V1
3761            && version != SEMANTIC_INDEX_VERSION_V2
3762            && version != SEMANTIC_INDEX_VERSION_V3
3763            && version != SEMANTIC_INDEX_VERSION_V4
3764            && version != SEMANTIC_INDEX_VERSION_V5
3765            && version != SEMANTIC_INDEX_VERSION_V6
3766            && version != SEMANTIC_INDEX_VERSION_V7
3767        {
3768            return Err(format!("unsupported version: {}", version));
3769        }
3770        // V2 and newer share the same header layout (V3/V4/V5 only differ from
3771        // V2 in the per-mtime entry layout): version(1) + dimension(4) +
3772        // entry_count(4) + fingerprint_len(4) + fingerprint bytes.
3773        if (version == SEMANTIC_INDEX_VERSION_V2
3774            || version == SEMANTIC_INDEX_VERSION_V3
3775            || version == SEMANTIC_INDEX_VERSION_V4
3776            || version == SEMANTIC_INDEX_VERSION_V5
3777            || version == SEMANTIC_INDEX_VERSION_V6
3778            || version == SEMANTIC_INDEX_VERSION_V7)
3779            && total_len.is_some_and(|len| len < HEADER_BYTES_V2)
3780        {
3781            return Err("data too short for semantic index v2/v3/v4/v5/v6/v7 header".to_string());
3782        }
3783
3784        let dimension = read_u32_stream(&mut reader)? as usize;
3785        let entry_count = read_u32_stream(&mut reader)? as usize;
3786        validate_embedding_dimension(dimension)?;
3787        if entry_count > MAX_ENTRIES {
3788            return Err(format!("too many semantic index entries: {}", entry_count));
3789        }
3790
3791        // Fingerprint handling:
3792        //   - V1: no fingerprint field at all.
3793        //   - V2: fingerprint_len + fingerprint bytes; always present (writer
3794        //     only emitted V2 when fingerprint was Some).
3795        //   - V3+: fingerprint_len always present; fingerprint_len==0 ⇒ None.
3796        let has_fingerprint_field = version == SEMANTIC_INDEX_VERSION_V2
3797            || version == SEMANTIC_INDEX_VERSION_V3
3798            || version == SEMANTIC_INDEX_VERSION_V4
3799            || version == SEMANTIC_INDEX_VERSION_V5
3800            || version == SEMANTIC_INDEX_VERSION_V6
3801            || version == SEMANTIC_INDEX_VERSION_V7;
3802        let fingerprint = if has_fingerprint_field {
3803            let fingerprint_len = read_u32_stream(&mut reader)? as usize;
3804            if total_len
3805                .is_some_and(|len| reader.bytes_read().saturating_add(fingerprint_len) > len)
3806            {
3807                return Err("unexpected end of data reading fingerprint".to_string());
3808            }
3809            if fingerprint_len == 0 {
3810                None
3811            } else {
3812                let mut raw = vec![0u8; fingerprint_len];
3813                read_exact_stream(
3814                    &mut reader,
3815                    &mut raw,
3816                    "unexpected end of data reading fingerprint",
3817                )?;
3818                let raw = String::from_utf8_lossy(&raw).to_string();
3819                Some(
3820                    serde_json::from_str::<SemanticIndexFingerprint>(&raw)
3821                        .map_err(|error| format!("invalid semantic fingerprint: {error}"))?,
3822                )
3823            }
3824        } else {
3825            None
3826        };
3827
3828        // File mtimes
3829        let mtime_count = read_u32_stream(&mut reader)? as usize;
3830        if mtime_count > MAX_ENTRIES {
3831            return Err(format!("too many semantic file mtimes: {}", mtime_count));
3832        }
3833
3834        let vector_bytes = entry_count
3835            .checked_mul(dimension)
3836            .and_then(|count| count.checked_mul(F32_BYTES))
3837            .ok_or_else(|| "semantic vector allocation overflow".to_string())?;
3838        if total_len.is_some_and(|len| vector_bytes > len.saturating_sub(reader.bytes_read())) {
3839            return Err("semantic index vectors exceed available data".to_string());
3840        }
3841
3842        let mut file_mtimes = HashMap::with_capacity(mtime_count);
3843        let mut file_sizes = HashMap::with_capacity(mtime_count);
3844        let mut file_hashes = HashMap::with_capacity(mtime_count);
3845        for _ in 0..mtime_count {
3846            let path = read_string_stream(&mut reader, total_len)?;
3847            let secs = read_u64_stream(&mut reader)?;
3848            // V3+ persists subsec_nanos alongside secs so staleness checks
3849            // survive restart round-trips. V1/V2 load with 0 nanos, which
3850            // causes one rebuild on upgrade (they never matched live APFS
3851            // mtimes anyway — the bug v0.15.2 fixes). After that rebuild,
3852            // the cache is persisted as V3 and stabilises.
3853            let nanos = if version == SEMANTIC_INDEX_VERSION_V3
3854                || version == SEMANTIC_INDEX_VERSION_V4
3855                || version == SEMANTIC_INDEX_VERSION_V5
3856                || version == SEMANTIC_INDEX_VERSION_V6
3857                || version == SEMANTIC_INDEX_VERSION_V7
3858            {
3859                read_u32_stream(&mut reader)?
3860            } else {
3861                0
3862            };
3863            let size = if version == SEMANTIC_INDEX_VERSION_V5
3864                || version == SEMANTIC_INDEX_VERSION_V6
3865                || version == SEMANTIC_INDEX_VERSION_V7
3866            {
3867                read_u64_stream(&mut reader)?
3868            } else {
3869                0
3870            };
3871            let content_hash =
3872                if version == SEMANTIC_INDEX_VERSION_V6 || version == SEMANTIC_INDEX_VERSION_V7 {
3873                    let mut hash_bytes = [0u8; 32];
3874                    read_exact_stream(
3875                        &mut reader,
3876                        &mut hash_bytes,
3877                        "unexpected end of data reading content hash",
3878                    )?;
3879                    blake3::Hash::from_bytes(hash_bytes)
3880                } else {
3881                    cache_freshness::zero_hash()
3882                };
3883            // Hardening against corrupt / maliciously crafted cache files
3884            // (v0.15.2). `Duration::new(secs, nanos)` can panic when the
3885            // nanosecond carry overflows the second counter, and
3886            // `SystemTime + Duration` can panic on carry past the platform's
3887            // upper bound. Explicit validation keeps a corrupted semantic.bin
3888            // from taking down the whole aft process.
3889            if nanos >= 1_000_000_000 {
3890                return Err(format!(
3891                    "invalid semantic mtime: nanos {} >= 1_000_000_000",
3892                    nanos
3893                ));
3894            }
3895            let duration = std::time::Duration::new(secs, nanos);
3896            let mtime = SystemTime::UNIX_EPOCH
3897                .checked_add(duration)
3898                .ok_or_else(|| {
3899                    format!(
3900                        "invalid semantic mtime: secs={} nanos={} overflows SystemTime",
3901                        secs, nanos
3902                    )
3903                })?;
3904            let path = if version == SEMANTIC_INDEX_VERSION_V6
3905                || version == SEMANTIC_INDEX_VERSION_V7
3906            {
3907                cached_path_under_root(current_canonical_root, &PathBuf::from(path))
3908                    .ok_or_else(|| "cached semantic mtime path escapes project root".to_string())?
3909            } else {
3910                PathBuf::from(path)
3911            };
3912            file_mtimes.insert(path.clone(), mtime);
3913            file_sizes.insert(path.clone(), size);
3914            file_hashes.insert(path, content_hash);
3915        }
3916
3917        // Entries
3918        let mut entries = Vec::with_capacity(entry_count);
3919        for _ in 0..entry_count {
3920            let raw_file = PathBuf::from(read_string_stream(&mut reader, total_len)?);
3921            let file = if version == SEMANTIC_INDEX_VERSION_V6
3922                || version == SEMANTIC_INDEX_VERSION_V7
3923            {
3924                cached_path_under_root(current_canonical_root, &raw_file)
3925                    .ok_or_else(|| "cached semantic entry path escapes project root".to_string())?
3926            } else {
3927                raw_file
3928            };
3929            let name = read_string_stream(&mut reader, total_len)?;
3930            let qualified_name = if version == SEMANTIC_INDEX_VERSION_V7 {
3931                let qualified_name = read_string_stream(&mut reader, total_len)?;
3932                if qualified_name.is_empty() {
3933                    None
3934                } else {
3935                    Some(qualified_name)
3936                }
3937            } else {
3938                None
3939            };
3940
3941            let kind = u8_to_symbol_kind(read_u8_stream(&mut reader, "unexpected end of data")?);
3942
3943            let start_line = read_u32_stream(&mut reader)?;
3944            let end_line = read_u32_stream(&mut reader)?;
3945
3946            let exported = read_u8_stream(&mut reader, "unexpected end of data")? != 0;
3947
3948            let snippet = read_string_stream(&mut reader, total_len)?;
3949            let embed_text = read_string_stream(&mut reader, total_len)?;
3950
3951            // Vector
3952            let vec_bytes = dimension
3953                .checked_mul(F32_BYTES)
3954                .ok_or_else(|| "semantic vector allocation overflow".to_string())?;
3955            if total_len.is_some_and(|len| reader.bytes_read().saturating_add(vec_bytes) > len) {
3956                return Err("unexpected end of data reading vector".to_string());
3957            }
3958            let mut vector = Vec::with_capacity(dimension);
3959            for _ in 0..dimension {
3960                let mut bytes = [0u8; F32_BYTES];
3961                read_exact_stream(
3962                    &mut reader,
3963                    &mut bytes,
3964                    "unexpected end of data reading vector",
3965                )?;
3966                vector.push(f32::from_le_bytes(bytes));
3967            }
3968
3969            entries.push(EmbeddingEntry::new(
3970                SemanticChunk {
3971                    file,
3972                    name,
3973                    qualified_name,
3974                    kind,
3975                    start_line,
3976                    end_line,
3977                    exported,
3978                    embed_text,
3979                    snippet,
3980                },
3981                vector,
3982            ));
3983        }
3984
3985        if entries.len() != entry_count {
3986            return Err(format!(
3987                "semantic cache entry count drift: header={} decoded={}",
3988                entry_count,
3989                entries.len()
3990            ));
3991        }
3992        for entry in &entries {
3993            if !file_mtimes.contains_key(&entry.chunk.file) {
3994                return Err(format!(
3995                    "semantic cache metadata missing for entry file {}",
3996                    entry.chunk.file.display()
3997                ));
3998            }
3999        }
4000
4001        let any_missing_sizes = file_mtimes
4002            .keys()
4003            .any(|path| !file_sizes.contains_key(path));
4004        Ok(Self {
4005            entries,
4006            file_mtimes,
4007            file_sizes,
4008            any_missing_sizes,
4009            file_hashes,
4010            dimension,
4011            fingerprint,
4012            project_root: current_canonical_root.to_path_buf(),
4013            deferred_files: HashSet::new(),
4014            shared_base: None,
4015            #[cfg(test)]
4016            removal_retain_passes: 0,
4017        })
4018    }
4019}
4020
4021fn write_counted<W: Write>(
4022    writer: &mut W,
4023    bytes: &[u8],
4024    bytes_written: &mut usize,
4025) -> io::Result<()> {
4026    writer.write_all(bytes)?;
4027    *bytes_written = bytes_written.saturating_add(bytes.len());
4028    Ok(())
4029}
4030
4031struct CountingReader<R> {
4032    inner: R,
4033    bytes_read: usize,
4034}
4035
4036impl<R> CountingReader<R> {
4037    fn with_bytes_read(inner: R, bytes_read: usize) -> Self {
4038        Self { inner, bytes_read }
4039    }
4040
4041    fn bytes_read(&self) -> usize {
4042        self.bytes_read
4043    }
4044}
4045
4046impl<R: Read> Read for CountingReader<R> {
4047    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
4048        let read = self.inner.read(buf)?;
4049        self.bytes_read = self.bytes_read.saturating_add(read);
4050        Ok(read)
4051    }
4052}
4053
4054fn read_exact_stream<R: Read>(
4055    reader: &mut CountingReader<R>,
4056    buf: &mut [u8],
4057    eof_message: &'static str,
4058) -> Result<(), String> {
4059    reader.read_exact(buf).map_err(|error| {
4060        if error.kind() == io::ErrorKind::UnexpectedEof {
4061            eof_message.to_string()
4062        } else {
4063            format!("{eof_message}: {error}")
4064        }
4065    })
4066}
4067
4068fn read_u8_stream<R: Read>(
4069    reader: &mut CountingReader<R>,
4070    eof_message: &'static str,
4071) -> Result<u8, String> {
4072    let mut bytes = [0u8; 1];
4073    read_exact_stream(reader, &mut bytes, eof_message)?;
4074    Ok(bytes[0])
4075}
4076
4077fn read_u32_stream<R: Read>(reader: &mut CountingReader<R>) -> Result<u32, String> {
4078    let mut bytes = [0u8; 4];
4079    read_exact_stream(reader, &mut bytes, "unexpected end of data reading u32")?;
4080    Ok(u32::from_le_bytes(bytes))
4081}
4082
4083fn read_u64_stream<R: Read>(reader: &mut CountingReader<R>) -> Result<u64, String> {
4084    let mut bytes = [0u8; 8];
4085    read_exact_stream(reader, &mut bytes, "unexpected end of data reading u64")?;
4086    Ok(u64::from_le_bytes(bytes))
4087}
4088
4089fn read_string_stream<R: Read>(
4090    reader: &mut CountingReader<R>,
4091    total_len: Option<usize>,
4092) -> Result<String, String> {
4093    let len = read_u32_stream(reader)? as usize;
4094    if total_len.is_some_and(|total_len| reader.bytes_read().saturating_add(len) > total_len) {
4095        return Err("unexpected end of data reading string".to_string());
4096    }
4097    let mut bytes = vec![0u8; len];
4098    read_exact_stream(reader, &mut bytes, "unexpected end of data reading string")?;
4099    Ok(String::from_utf8_lossy(&bytes).to_string())
4100}
4101
4102struct SourceLineCache<'a> {
4103    lines: Vec<&'a str>,
4104    line_starts: Vec<usize>,
4105}
4106
4107impl<'a> SourceLineCache<'a> {
4108    fn new(source: &'a str) -> Self {
4109        let lines: Vec<&'a str> = source.lines().collect();
4110        let mut line_starts = Vec::with_capacity(lines.len());
4111        let bytes = source.as_bytes();
4112        let mut offset = 0usize;
4113        for line in &lines {
4114            line_starts.push(offset);
4115            offset += line.len();
4116            if bytes.get(offset) == Some(&b'\r') && bytes.get(offset + 1) == Some(&b'\n') {
4117                offset += 2;
4118            } else if bytes.get(offset) == Some(&b'\n') {
4119                offset += 1;
4120            }
4121        }
4122        Self { lines, line_starts }
4123    }
4124
4125    fn len(&self) -> usize {
4126        debug_assert_eq!(self.lines.len(), self.line_starts.len());
4127        self.line_starts.len()
4128    }
4129}
4130
4131/// Build enriched embedding text from a symbol with cAST-style context
4132fn build_embed_text_with_lines(
4133    symbol: &Symbol,
4134    line_cache: &SourceLineCache<'_>,
4135    file: &Path,
4136    project_root: &Path,
4137) -> String {
4138    let relative = file
4139        .strip_prefix(project_root)
4140        .unwrap_or(file)
4141        .to_string_lossy();
4142
4143    let kind_label = match &symbol.kind {
4144        SymbolKind::Function => "function",
4145        SymbolKind::Class => "class",
4146        SymbolKind::Method => "method",
4147        SymbolKind::Struct => "struct",
4148        SymbolKind::Interface => "interface",
4149        SymbolKind::Enum => "enum",
4150        SymbolKind::TypeAlias => "type",
4151        SymbolKind::Variable => "variable",
4152        SymbolKind::Heading => "heading",
4153        SymbolKind::FileSummary => "file-summary",
4154    };
4155
4156    // Build: "file:relative/path kind:function name:validateAuth signature:fn validateAuth(token: &str) -> bool"
4157    let name = &symbol.name;
4158    let mut text = format!(
4159        "name:{name} file:{} kind:{} name:{name}",
4160        relative, kind_label
4161    );
4162
4163    if let Some(sig) = &symbol.signature {
4164        // Cap the signature: structured parsers (e.g. YAML/Kubernetes) pack
4165        // entire inline scripts (CronJob/Job `command:` bodies, multi-KB) into
4166        // the signature. Appending it unbounded produces a single embed_text
4167        // that overflows the embedding backend's physical batch (e.g. a
4168        // llama.cpp server's 512-token cap), aborting the whole index build
4169        // and silently degrading every search to lexical. 400 chars keeps the
4170        // identifying head of the signature without blowing the budget.
4171        text.push_str(&format!(" signature:{}", truncate_chars(sig, 400)));
4172    }
4173
4174    // Add body snippet (first ~300 chars of symbol body)
4175    let start = (symbol.range.start_line as usize).min(line_cache.len());
4176    // range.end_line is inclusive 0-based; +1 makes it an exclusive slice bound.
4177    let end = (symbol.range.end_line as usize + 1).min(line_cache.len());
4178    if start < end {
4179        let body: String = line_cache.lines[start..end]
4180            .iter()
4181            .take(15) // max 15 lines
4182            .copied()
4183            .collect::<Vec<&str>>()
4184            .join("\n");
4185        let snippet = if body.len() > 300 {
4186            format!("{}...", &body[..body.floor_char_boundary(300)])
4187        } else {
4188            body
4189        };
4190        text.push_str(&format!(" body:{}", snippet));
4191    }
4192
4193    // Final defense-in-depth clamp: no single embed_text may exceed the
4194    // backend's per-input budget regardless of which field grew. Most
4195    // backends cap a physical batch around 512 tokens; ~1600 chars stays
4196    // comfortably under that for typical English/code (≈4 chars/token).
4197    truncate_chars(&text, MAX_EMBED_TEXT_CHARS)
4198}
4199
4200#[cfg(test)]
4201fn build_embed_text(symbol: &Symbol, source: &str, file: &Path, project_root: &Path) -> String {
4202    let line_cache = SourceLineCache::new(source);
4203    build_embed_text_with_lines(symbol, &line_cache, file, project_root)
4204}
4205
4206/// Upper bound on characters in a single chunk's `embed_text`. Keeps any one
4207/// input below typical embedding-backend physical batch limits (~512 tokens)
4208/// so an oversized symbol cannot abort the whole index build.
4209const MAX_EMBED_TEXT_CHARS: usize = 1600;
4210
4211fn truncate_chars(value: &str, max_chars: usize) -> String {
4212    value.chars().take(max_chars).collect()
4213}
4214
4215fn first_leading_doc_comment(line_cache: &SourceLineCache<'_>) -> String {
4216    let Some((start, first)) = line_cache
4217        .lines
4218        .iter()
4219        .enumerate()
4220        .find(|(_, line)| !line.trim().is_empty())
4221    else {
4222        return String::new();
4223    };
4224
4225    let trimmed = first.trim_start();
4226    if trimmed.starts_with("/**") {
4227        let mut comment = Vec::new();
4228        for line in line_cache.lines.iter().skip(start) {
4229            comment.push(*line);
4230            if line.contains("*/") {
4231                break;
4232            }
4233        }
4234        return truncate_chars(&comment.join("\n"), 200);
4235    }
4236
4237    if trimmed.starts_with("///") || trimmed.starts_with("//!") {
4238        let comment = line_cache
4239            .lines
4240            .iter()
4241            .skip(start)
4242            .take_while(|line| {
4243                let trimmed = line.trim_start();
4244                trimmed.starts_with("///") || trimmed.starts_with("//!")
4245            })
4246            .copied()
4247            .collect::<Vec<_>>()
4248            .join("\n");
4249        return truncate_chars(&comment, 200);
4250    }
4251
4252    String::new()
4253}
4254
4255pub fn build_file_summary_chunk(
4256    file: &Path,
4257    project_root: &Path,
4258    source: &str,
4259    top_exports: &[&str],
4260    top_export_signatures: &[Option<&str>],
4261) -> SemanticChunk {
4262    let line_cache = SourceLineCache::new(source);
4263    build_file_summary_chunk_with_lines(
4264        file,
4265        project_root,
4266        &line_cache,
4267        top_exports,
4268        top_export_signatures,
4269    )
4270}
4271
4272fn build_file_summary_chunk_with_lines(
4273    file: &Path,
4274    project_root: &Path,
4275    line_cache: &SourceLineCache<'_>,
4276    top_exports: &[&str],
4277    top_export_signatures: &[Option<&str>],
4278) -> SemanticChunk {
4279    let relative = file.strip_prefix(project_root).unwrap_or(file);
4280    let rel_path = relative.to_string_lossy();
4281    let parent_dir = relative
4282        .parent()
4283        .map(|parent| parent.to_string_lossy().to_string())
4284        .unwrap_or_default();
4285    let name = file
4286        .file_stem()
4287        .map(|stem| stem.to_string_lossy().to_string())
4288        .unwrap_or_default();
4289    let doc = first_leading_doc_comment(line_cache);
4290    let exports = top_exports
4291        .iter()
4292        .take(5)
4293        .copied()
4294        .collect::<Vec<_>>()
4295        .join(",");
4296    let snippet = if doc.is_empty() {
4297        top_export_signatures
4298            .first()
4299            .and_then(|signature| signature.as_deref())
4300            .map(|signature| truncate_chars(signature, 200))
4301            .unwrap_or_default()
4302    } else {
4303        doc.clone()
4304    };
4305
4306    SemanticChunk {
4307        file: file.to_path_buf(),
4308        name,
4309        qualified_name: None,
4310        kind: SymbolKind::FileSummary,
4311        start_line: 0,
4312        end_line: 0,
4313        exported: false,
4314        embed_text: truncate_chars(
4315            &format!(
4316                "file:{rel_path} kind:file-summary name:{} parent:{parent_dir} doc:{doc} exports:{exports}",
4317                file.file_stem()
4318                    .map(|stem| stem.to_string_lossy().to_string())
4319                    .unwrap_or_default()
4320            ),
4321            MAX_EMBED_TEXT_CHARS,
4322        ),
4323        snippet,
4324    }
4325}
4326
4327pub fn is_semantic_indexed_extension(path: &Path) -> bool {
4328    if path.file_name().and_then(|name| name.to_str()) == Some("Jenkinsfile") {
4329        return true;
4330    }
4331
4332    matches!(
4333        path.extension().and_then(|extension| extension.to_str()),
4334        Some(
4335            "ts" | "tsx"
4336                | "js"
4337                | "jsx"
4338                | "py"
4339                | "rs"
4340                | "go"
4341                | "c"
4342                | "h"
4343                | "cc"
4344                | "cpp"
4345                | "cxx"
4346                | "hpp"
4347                | "hh"
4348                | "zig"
4349                | "cs"
4350                | "sh"
4351                | "bash"
4352                | "zsh"
4353                | "inc"
4354                | "php"
4355                | "sol"
4356                | "scss"
4357                | "vue"
4358                | "yaml"
4359                | "yml"
4360                | "pas"
4361                | "pp"
4362                | "dpr"
4363                | "dpk"
4364                | "lpr"
4365                | "java"
4366                | "kt"
4367                | "kts"
4368                | "rb"
4369                | "swift"
4370                | "scala"
4371                | "sc"
4372                | "lua"
4373                | "pl"
4374                | "pm"
4375                | "t"
4376                | "r"
4377                | "R"
4378                | "groovy"
4379                | "gvy"
4380                | "gy"
4381                | "gsh"
4382                | "gradle"
4383                | "m"
4384                | "mm",
4385        )
4386    )
4387}
4388
4389fn canonicalize_existing_or_deleted_path(path: &Path) -> PathBuf {
4390    if let Ok(canonical) = fs::canonicalize(path) {
4391        return canonical;
4392    }
4393
4394    let Some(parent) = path.parent() else {
4395        return path.to_path_buf();
4396    };
4397    let Some(file_name) = path.file_name() else {
4398        return path.to_path_buf();
4399    };
4400
4401    fs::canonicalize(parent)
4402        .map(|canonical_parent| canonical_parent.join(file_name))
4403        .unwrap_or_else(|_| path.to_path_buf())
4404}
4405
4406/// Files larger than this are skipped for semantic chunking. The read +
4407/// tree-sitter parse is transiently O(file size) (tree-sitter can use several×
4408/// the source bytes), and `par_iter` collection parses many files at once, so an
4409/// unbounded read here is an OOM vector on a repo with a few multi-MB generated/
4410/// vendored/minified files. A file this large yields almost no useful embedding
4411/// anyway (each chunk's embed_text is clamped to MAX_EMBED_TEXT_CHARS), so we
4412/// track it (0 chunks) instead of reading it — freshness then skips it on later
4413/// refreshes. 4 MiB keeps essentially all hand-written source while capping the
4414/// pathological tail.
4415const MAX_SEMANTIC_FILE_BYTES: u64 = 4 * 1024 * 1024;
4416
4417fn collect_semantic_file(
4418    project_root: &Path,
4419    file: &Path,
4420    phases: &mut SemanticCollectPhaseTimings,
4421) -> Result<(IndexedFileMetadata, Vec<SemanticChunk>), String> {
4422    let read_hash_started = Instant::now();
4423    let read_result = (|| {
4424        let metadata = fs::metadata(file).map_err(|error| error.to_string())?;
4425        if !metadata.is_file() {
4426            return Err("not a regular file".to_string());
4427        }
4428        let mtime = metadata.modified().map_err(|error| error.to_string())?;
4429        let size = metadata.len();
4430
4431        if !is_semantic_indexed_extension(file) {
4432            return Err("unsupported file extension".to_string());
4433        }
4434        let lang = detect_language(file).ok_or_else(|| "unsupported file extension".to_string())?;
4435
4436        let mut indexed_metadata = IndexedFileMetadata {
4437            mtime,
4438            size,
4439            content_hash: cache_freshness::zero_hash(),
4440        };
4441
4442        // OOM backstop: skip oversized files before the read + parse (tracked with
4443        // zero chunks by the caller, so freshness won't re-read them every refresh).
4444        if size > MAX_SEMANTIC_FILE_BYTES {
4445            return Ok((indexed_metadata, lang, None));
4446        }
4447
4448        let source = fs::read_to_string(file).map_err(|error| error.to_string())?;
4449        indexed_metadata.content_hash = if size <= cache_freshness::CONTENT_HASH_SIZE_CAP {
4450            cache_freshness::hash_bytes(source.as_bytes())
4451        } else {
4452            cache_freshness::zero_hash()
4453        };
4454        Ok((indexed_metadata, lang, Some(source)))
4455    })();
4456    phases.read_hash += read_hash_started.elapsed();
4457    let (indexed_metadata, lang, source) = read_result?;
4458    let Some(source) = source else {
4459        return Ok((indexed_metadata, Vec::new()));
4460    };
4461
4462    let chunks = collect_file_chunks_from_source_timed(project_root, file, lang, &source, phases)?;
4463    Ok((indexed_metadata, chunks))
4464}
4465
4466#[cfg(test)]
4467fn collect_file_chunks(project_root: &Path, file: &Path) -> Result<Vec<SemanticChunk>, String> {
4468    if !is_semantic_indexed_extension(file) {
4469        return Err("unsupported file extension".to_string());
4470    }
4471    let lang = detect_language(file).ok_or_else(|| "unsupported file extension".to_string())?;
4472    // OOM backstop: skip oversized files before the read + parse (tracked with
4473    // zero chunks by the caller, so freshness won't re-read them every refresh).
4474    if fs::metadata(file).is_ok_and(|m| m.len() > MAX_SEMANTIC_FILE_BYTES) {
4475        return Ok(Vec::new());
4476    }
4477    let source = fs::read_to_string(file).map_err(|error| error.to_string())?;
4478    collect_file_chunks_from_source(project_root, file, lang, &source)
4479}
4480
4481#[cfg(test)]
4482fn collect_file_chunks_from_source(
4483    project_root: &Path,
4484    file: &Path,
4485    lang: crate::parser::LangId,
4486    source: &str,
4487) -> Result<Vec<SemanticChunk>, String> {
4488    collect_file_chunks_from_source_timed(
4489        project_root,
4490        file,
4491        lang,
4492        source,
4493        &mut SemanticCollectPhaseTimings::default(),
4494    )
4495}
4496
4497fn collect_file_chunks_from_source_timed(
4498    project_root: &Path,
4499    file: &Path,
4500    lang: crate::parser::LangId,
4501    source: &str,
4502    phases: &mut SemanticCollectPhaseTimings,
4503) -> Result<Vec<SemanticChunk>, String> {
4504    let parse_started = Instant::now();
4505    let tree_result =
4506        parse_source_with_cached_parser(file, source, lang).map_err(|error| error.to_string());
4507    phases.parse += parse_started.elapsed();
4508    let tree = tree_result?;
4509
4510    let extract_started = Instant::now();
4511    let symbols_result =
4512        extract_symbols_from_tree(source, &tree, lang).map_err(|error| error.to_string());
4513    phases.extract += extract_started.elapsed();
4514    let symbols = symbols_result?;
4515
4516    let build_started = Instant::now();
4517    let chunks = symbols_to_chunks(file, &symbols, source, project_root);
4518    phases.build += build_started.elapsed();
4519    Ok(chunks)
4520}
4521
4522/// Build a display snippet from a symbol's source
4523fn build_snippet_with_lines(symbol: &Symbol, line_cache: &SourceLineCache<'_>) -> String {
4524    let start = (symbol.range.start_line as usize).min(line_cache.len());
4525    // range.end_line is inclusive 0-based; +1 makes it an exclusive slice bound.
4526    let end = (symbol.range.end_line as usize + 1).min(line_cache.len());
4527    if start < end {
4528        let snippet_lines: Vec<&str> = line_cache.lines[start..end]
4529            .iter()
4530            .take(5)
4531            .copied()
4532            .collect();
4533        let mut snippet = snippet_lines.join("\n");
4534        if end - start > 5 {
4535            snippet.push_str("\n  ...");
4536        }
4537        if snippet.len() > 300 {
4538            snippet = format!("{}...", &snippet[..snippet.floor_char_boundary(300)]);
4539        }
4540        snippet
4541    } else {
4542        String::new()
4543    }
4544}
4545
4546#[cfg(test)]
4547fn build_snippet(symbol: &Symbol, source: &str) -> String {
4548    let line_cache = SourceLineCache::new(source);
4549    build_snippet_with_lines(symbol, &line_cache)
4550}
4551
4552fn qualified_name_for_symbol(symbol: &Symbol) -> Option<String> {
4553    let mut parts = symbol
4554        .scope_chain
4555        .iter()
4556        .filter(|part| !part.is_empty())
4557        .cloned()
4558        .collect::<Vec<_>>();
4559    if !symbol.name.is_empty() {
4560        parts.push(symbol.name.clone());
4561    }
4562    (!parts.is_empty()).then(|| parts.join("."))
4563}
4564
4565/// Convert symbols to semantic chunks with enriched context
4566fn symbols_to_chunks(
4567    file: &Path,
4568    symbols: &[Symbol],
4569    source: &str,
4570    project_root: &Path,
4571) -> Vec<SemanticChunk> {
4572    let line_cache = SourceLineCache::new(source);
4573    let mut chunks = Vec::new();
4574    let top_exports_with_signatures = symbols
4575        .iter()
4576        .filter(|symbol| {
4577            symbol.exported
4578                && symbol.parent.is_none()
4579                && !matches!(symbol.kind, SymbolKind::Heading)
4580        })
4581        .map(|symbol| (symbol.name.as_str(), symbol.signature.as_deref()))
4582        .collect::<Vec<_>>();
4583
4584    let has_only_headings = !symbols.is_empty()
4585        && symbols
4586            .iter()
4587            .all(|symbol| matches!(symbol.kind, SymbolKind::Heading));
4588    if top_exports_with_signatures.len() <= 2 && !has_only_headings {
4589        let top_exports = top_exports_with_signatures
4590            .iter()
4591            .map(|(name, _)| *name)
4592            .collect::<Vec<_>>();
4593        let top_export_signatures = top_exports_with_signatures
4594            .iter()
4595            .map(|(_, signature)| *signature)
4596            .collect::<Vec<_>>();
4597        chunks.push(build_file_summary_chunk_with_lines(
4598            file,
4599            project_root,
4600            &line_cache,
4601            &top_exports,
4602            &top_export_signatures,
4603        ));
4604    }
4605
4606    for symbol in symbols {
4607        // Skip Markdown / HTML heading chunks: empirically they dominate result
4608        // lists even for code-shaped queries because heading prose embeds well.
4609        // Agents querying for code lose the actual matches under doc noise.
4610        // README/docs queries are still served by grep on the same files.
4611        if matches!(symbol.kind, SymbolKind::Heading) {
4612            continue;
4613        }
4614
4615        // Skip very small symbols (single-line variables, etc.)
4616        let line_count = symbol
4617            .range
4618            .end_line
4619            .saturating_sub(symbol.range.start_line)
4620            + 1;
4621        if line_count < 2 && !matches!(symbol.kind, SymbolKind::Variable) {
4622            continue;
4623        }
4624
4625        let embed_text = build_embed_text_with_lines(symbol, &line_cache, file, project_root);
4626        let snippet = build_snippet_with_lines(symbol, &line_cache);
4627
4628        chunks.push(SemanticChunk {
4629            file: file.to_path_buf(),
4630            name: symbol.name.clone(),
4631            qualified_name: qualified_name_for_symbol(symbol),
4632            kind: symbol.kind.clone(),
4633            start_line: symbol.range.start_line,
4634            end_line: symbol.range.end_line,
4635            exported: symbol.exported,
4636            embed_text,
4637            snippet,
4638        });
4639
4640        // Note: Nested symbols are handled separately by the outline system
4641        // Each symbol is indexed individually
4642    }
4643
4644    chunks
4645}
4646
4647fn semantic_score_order(a: &(f32, usize), b: &(f32, usize)) -> std::cmp::Ordering {
4648    b.0.partial_cmp(&a.0)
4649        .unwrap_or(std::cmp::Ordering::Equal)
4650        .then_with(|| a.1.cmp(&b.1))
4651}
4652
4653/// Compute an embedding's L2 norm for its in-memory search cache.
4654fn vector_norm(vector: &[f32]) -> f32 {
4655    vector.iter().map(|value| value * value).sum::<f32>().sqrt()
4656}
4657
4658fn dot_product(a: &[f32], b: &[f32]) -> f32 {
4659    a.iter().zip(b).map(|(a, b)| a * b).sum::<f32>()
4660}
4661
4662/// Cosine similarity reference retained for focused unit tests.
4663#[cfg(test)]
4664fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
4665    if a.len() != b.len() {
4666        return 0.0;
4667    }
4668
4669    let mut dot = 0.0f32;
4670    let mut norm_a = 0.0f32;
4671    let mut norm_b = 0.0f32;
4672
4673    for i in 0..a.len() {
4674        dot += a[i] * b[i];
4675        norm_a += a[i] * a[i];
4676        norm_b += b[i] * b[i];
4677    }
4678
4679    let denom = norm_a.sqrt() * norm_b.sqrt();
4680    if denom == 0.0 {
4681        0.0
4682    } else {
4683        dot / denom
4684    }
4685}
4686
4687// Serialization helpers
4688fn symbol_kind_to_u8(kind: &SymbolKind) -> u8 {
4689    match kind {
4690        SymbolKind::Function => 0,
4691        SymbolKind::Class => 1,
4692        SymbolKind::Method => 2,
4693        SymbolKind::Struct => 3,
4694        SymbolKind::Interface => 4,
4695        SymbolKind::Enum => 5,
4696        SymbolKind::TypeAlias => 6,
4697        SymbolKind::Variable => 7,
4698        SymbolKind::Heading => 8,
4699        SymbolKind::FileSummary => 9,
4700    }
4701}
4702
4703fn u8_to_symbol_kind(v: u8) -> SymbolKind {
4704    match v {
4705        0 => SymbolKind::Function,
4706        1 => SymbolKind::Class,
4707        2 => SymbolKind::Method,
4708        3 => SymbolKind::Struct,
4709        4 => SymbolKind::Interface,
4710        5 => SymbolKind::Enum,
4711        6 => SymbolKind::TypeAlias,
4712        7 => SymbolKind::Variable,
4713        8 => SymbolKind::Heading,
4714        9 => SymbolKind::FileSummary,
4715        _ => SymbolKind::Heading,
4716    }
4717}
4718
4719#[cfg(test)]
4720mod tests {
4721    use super::*;
4722    use crate::config::{SemanticBackend, SemanticBackendConfig};
4723    use crate::parser::FileParser;
4724    use std::io::{Read, Write};
4725    use std::net::TcpListener;
4726    use std::process::Command;
4727    use std::thread;
4728    use tempfile::NamedTempFile;
4729
4730    // Only the unix-gated baseline test consumes these (see its comment for
4731    // why Windows cannot reproduce the hash); keep Windows -D warnings clean.
4732    #[cfg(unix)]
4733    const RUST_QUERY_BASELINE_OUTPUT_HASH: &str =
4734        "36315439db74ed8e186076f79ed261079b2b13a4443ed4272861a2518c78d98b";
4735
4736    #[cfg(unix)]
4737    fn rust_fixture_semantic_output_fingerprint(project_root: &Path) -> (usize, usize, String) {
4738        let fixture_root = project_root.join("tests/fixtures");
4739        // Re-materialize the fixtures with LF bytes before collecting: Windows
4740        // checkouts (core.autocrlf) hand collect_chunks CRLF sources, and the
4741        // extra byte per line shifts snippet/embed-text cap boundaries — so
4742        // post-hoc \r stripping cannot reproduce the LF-computed baseline.
4743        let lf_root = tempfile::tempdir().expect("lf fixture root");
4744        let fixture_files = [
4745            "imports_rs.rs",
4746            "member_rs.rs",
4747            "sample.rs",
4748            "structure_rs.rs",
4749        ]
4750        .map(|name| {
4751            let source = std::fs::read_to_string(fixture_root.join(name))
4752                .expect("read fixture")
4753                .replace("\r\n", "\n");
4754            // Preserve the tests/fixtures/<name> layout: chunk identity fields
4755            // (relative path, qualified name, embed-text header) derive from the
4756            // path relative to the project root, so a flat layout re-keys them.
4757            let path = lf_root.path().join("tests/fixtures").join(name);
4758            std::fs::create_dir_all(path.parent().unwrap()).expect("fixture dirs");
4759            std::fs::write(&path, source).expect("write LF fixture");
4760            path
4761        });
4762        let project_root = lf_root.path();
4763        let (chunks, _) = SemanticIndex::collect_chunks(project_root, &fixture_files);
4764        let normalized = chunks
4765            .iter()
4766            .map(|chunk| {
4767                (
4768                    chunk
4769                        .file
4770                        .strip_prefix(project_root)
4771                        .unwrap()
4772                        .to_string_lossy()
4773                        .replace('\\', "/"),
4774                    &chunk.name,
4775                    &chunk.qualified_name,
4776                    &chunk.kind,
4777                    chunk.start_line,
4778                    chunk.end_line,
4779                    chunk.exported,
4780                    &chunk.embed_text,
4781                    &chunk.snippet,
4782                )
4783            })
4784            .collect::<Vec<_>>();
4785        let output = format!("{normalized:#?}");
4786        (
4787            chunks.len(),
4788            output.len(),
4789            blake3::hash(output.as_bytes()).to_hex().to_string(),
4790        )
4791    }
4792
4793    // Unix-only: chunk embed text bakes the OS-native relative path into its
4794    // header (file-summary chunks), so a Windows run hashes "tests\fixtures\…"
4795    // and can never reproduce the unix-captured baseline even with LF-forced
4796    // sources. The property under test — the query-free Rust walk reproduces
4797    // the old RS_QUERY output byte-for-byte — is platform-independent and is
4798    // pinned where the baseline was captured.
4799    #[cfg(unix)]
4800    #[test]
4801    fn rust_semantic_fixture_output_matches_query_baseline() {
4802        let project_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
4803        let (_, _, output_hash) = rust_fixture_semantic_output_fingerprint(&project_root);
4804        assert_eq!(output_hash, RUST_QUERY_BASELINE_OUTPUT_HASH);
4805    }
4806
4807    #[test]
4808    #[ignore = "manual single-file semantic collect phase benchmark"]
4809    fn profile_rust_single_file_semantic_collect() {
4810        let crate_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
4811        let workspace_root = crate_root
4812            .parent()
4813            .and_then(Path::parent)
4814            .expect("workspace root");
4815        let files = [
4816            workspace_root.join("crates/aft/src/bash_background/registry.rs"),
4817            workspace_root.join("crates/aft-tokenizer/src/claude_data.rs"),
4818        ];
4819
4820        for file in files {
4821            let source = fs::read_to_string(&file).expect("read benchmark source");
4822            for run in 1..=5 {
4823                let mut phases = SemanticCollectPhaseTimings::default();
4824                let started = Instant::now();
4825                let chunks = collect_file_chunks_from_source_timed(
4826                    workspace_root,
4827                    &file,
4828                    crate::parser::LangId::Rust,
4829                    &source,
4830                    &mut phases,
4831                )
4832                .unwrap();
4833                eprintln!(
4834                    "semantic single-file file={} bytes={} run={run}: total={:?} parse={:?} extract={:?} build={:?} chunks={}",
4835                    file.strip_prefix(workspace_root).unwrap().display(),
4836                    source.len(),
4837                    started.elapsed(),
4838                    phases.parse,
4839                    phases.extract,
4840                    phases.build,
4841                    chunks.len()
4842                );
4843            }
4844        }
4845    }
4846
4847    #[test]
4848    fn semantic_index_includes_php_inc_and_scss_extensions() {
4849        for file in ["partial.inc", "index.php", "styles.scss"] {
4850            assert!(
4851                is_semantic_indexed_extension(Path::new(file)),
4852                "{file} should be semantic-index eligible"
4853            );
4854        }
4855    }
4856
4857    #[test]
4858    fn semantic_index_includes_groovy_extensions_and_jenkinsfile() {
4859        for file in [
4860            "script.groovy",
4861            "script.gvy",
4862            "script.gy",
4863            "shell.gsh",
4864            "build.gradle",
4865            "Jenkinsfile",
4866        ] {
4867            assert!(
4868                is_semantic_indexed_extension(Path::new(file)),
4869                "{file} should be semantic-index eligible"
4870            );
4871        }
4872        assert!(is_semantic_indexed_extension(Path::new("build.gradle.kts")));
4873    }
4874
4875    #[test]
4876    fn transient_marker_round_trips_and_classifies() {
4877        // A marked transient error is recognized and the marker is stripped for
4878        // display, leaving a clean message.
4879        let marked = format!("{TRANSIENT_EMBEDDING_MARKER}openai compatible request failed: error sending request for url (http://localhost:1234/v1/embeddings)");
4880        assert!(embedding_failure_is_transient(&marked));
4881        let clean = strip_transient_embedding_marker(&marked);
4882        assert!(!clean.contains(TRANSIENT_EMBEDDING_MARKER));
4883        assert!(clean.starts_with("openai compatible request failed:"));
4884
4885        // Permanent errors (HTTP 4xx, dimension mismatch) carry no marker and
4886        // are not classified transient — they must fail fast.
4887        for permanent in [
4888            "openai compatible request failed (HTTP 401): Unauthorized",
4889            "embedding dimension mismatch: index has 384, model returned 768",
4890            "too many files (>20000) for semantic indexing (max 20000)",
4891        ] {
4892            assert!(
4893                !embedding_failure_is_transient(permanent),
4894                "{permanent:?} must not be transient"
4895            );
4896            // Stripping a marker-free string is a no-op.
4897            assert_eq!(strip_transient_embedding_marker(permanent), permanent);
4898        }
4899    }
4900
4901    #[test]
4902    fn send_error_transience_separates_connect_timeout_from_4xx() {
4903        // 5xx / 429 are transient; other client errors are not.
4904        assert!(is_retryable_embedding_status(
4905            reqwest::StatusCode::INTERNAL_SERVER_ERROR
4906        ));
4907        assert!(is_retryable_embedding_status(
4908            reqwest::StatusCode::TOO_MANY_REQUESTS
4909        ));
4910        assert!(!is_retryable_embedding_status(
4911            reqwest::StatusCode::UNAUTHORIZED
4912        ));
4913        assert!(!is_retryable_embedding_status(
4914            reqwest::StatusCode::BAD_REQUEST
4915        ));
4916    }
4917
4918    #[test]
4919    fn query_timeout_marker_round_trips_and_classifies() {
4920        // A query-timeout error carries the budget that fired; the budget is
4921        // recoverable and the marker strips cleanly for display.
4922        let marked = format!(
4923            "{}openai compatible request failed: operation timed out",
4924            query_embedding_timeout_marker(3_000)
4925        );
4926        assert_eq!(query_embedding_timeout_budget(&marked), Some(3_000));
4927        let clean = strip_query_embedding_timeout_marker(&marked);
4928        assert!(!clean.contains(QUERY_EMBEDDING_TIMEOUT_MARKER_PREFIX));
4929        assert!(clean.starts_with("openai compatible request failed:"));
4930
4931        // Non-timeout errors carry no marker and no budget — they must not be
4932        // misclassified as timeouts.
4933        for permanent in [
4934            "openai compatible request failed (HTTP 401): Unauthorized",
4935            "failed to embed query: embedding model was not initialized",
4936            "openai compatible request failed: connection refused",
4937        ] {
4938            assert_eq!(
4939                query_embedding_timeout_budget(permanent),
4940                None,
4941                "{permanent:?} must not classify as a query timeout"
4942            );
4943            assert_eq!(
4944                strip_query_embedding_timeout_marker(permanent),
4945                permanent,
4946                "stripping a marker-free string is a no-op"
4947            );
4948        }
4949    }
4950
4951    fn install_test_crypto_provider() {
4952        // Reqwest and the direct test-server dependency enable different rustls
4953        // providers, so select one explicitly before either side builds TLS.
4954        let _ = rustls::crypto::ring::default_provider().install_default();
4955    }
4956
4957    fn start_platform_verifier_tls_server() -> (String, NamedTempFile, thread::JoinHandle<()>) {
4958        install_test_crypto_provider();
4959        let ca_key = rcgen::KeyPair::generate().expect("generate test CA key");
4960        let mut ca_params = rcgen::CertificateParams::default();
4961        ca_params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
4962        ca_params.key_usages = vec![
4963            rcgen::KeyUsagePurpose::KeyCertSign,
4964            rcgen::KeyUsagePurpose::DigitalSignature,
4965        ];
4966        let ca_cert = ca_params
4967            .self_signed(&ca_key)
4968            .expect("generate test CA certificate");
4969
4970        let leaf_key = rcgen::KeyPair::generate().expect("generate test leaf key");
4971        let mut leaf_params = rcgen::CertificateParams::new(vec!["localhost".to_string()])
4972            .expect("generate leaf parameters");
4973        leaf_params.key_usages = vec![rcgen::KeyUsagePurpose::DigitalSignature];
4974        leaf_params.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ServerAuth];
4975        let leaf_cert = leaf_params
4976            .signed_by(&leaf_key, &ca_cert, &ca_key)
4977            .expect("sign test leaf certificate");
4978
4979        let mut ca_file = NamedTempFile::new().expect("create test CA file");
4980        ca_file
4981            .write_all(ca_cert.pem().as_bytes())
4982            .expect("write test CA certificate");
4983
4984        let server_config = Arc::new(
4985            rustls::ServerConfig::builder()
4986                .with_no_client_auth()
4987                .with_single_cert(
4988                    vec![rustls::pki_types::CertificateDer::from(
4989                        leaf_cert.der().to_vec(),
4990                    )],
4991                    rustls::pki_types::PrivateKeyDer::Pkcs8(
4992                        rustls::pki_types::PrivatePkcs8KeyDer::from(leaf_key.serialize_der()),
4993                    ),
4994                )
4995                .expect("build test TLS server configuration"),
4996        );
4997        let listener = TcpListener::bind(("127.0.0.1", 0)).expect("bind test TLS server");
4998        let address = listener.local_addr().expect("read test TLS server address");
4999        let url = format!("https://localhost:{}/v1/embeddings", address.port());
5000        let handle = thread::spawn(move || {
5001            // Linux exercises both trust paths: the first handshake fails with
5002            // UnknownIssuer, and the second succeeds after SSL_CERT_FILE supplies
5003            // the throwaway CA. Other platforms only exercise the failure path;
5004            // their platform verifiers do not consult SSL_CERT_FILE.
5005            let expected_connections = if cfg!(target_os = "linux") { 2 } else { 1 };
5006            for _ in 0..expected_connections {
5007                let (stream, _) = listener.accept().expect("accept test TLS connection");
5008                stream
5009                    .set_read_timeout(Some(Duration::from_secs(10)))
5010                    .expect("set test TLS read timeout");
5011                let connection = rustls::ServerConnection::new(server_config.clone())
5012                    .expect("create test TLS server connection");
5013                let mut tls_stream = rustls::StreamOwned::new(connection, stream);
5014                let mut request = [0_u8; 4096];
5015                if tls_stream.read(&mut request).is_ok() {
5016                    let body = r#"{"data":[],"model":"test","object":"list"}"#;
5017                    let response = format!(
5018                        "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
5019                        body.len(), body
5020                    );
5021                    let _ = tls_stream.write_all(response.as_bytes());
5022                    tls_stream.conn.send_close_notify();
5023                    let _ = tls_stream.flush();
5024                }
5025            }
5026        });
5027
5028        (url, ca_file, handle)
5029    }
5030
5031    fn run_platform_verifier_tls_child() {
5032        install_test_crypto_provider();
5033        let url = env::var("AFT_PLATFORM_VERIFIER_TLS_URL").expect("test TLS URL");
5034        let tls_config = crate::platform_tls::client_config().expect("build platform TLS config");
5035        // This test asserts the ERROR CLASS (certificate trust failure), not
5036        // latency, so the budget must be unreachable by keychain slowness: on
5037        // macOS the first evaluation of an untrusted chain walks user trust
5038        // settings (trustd), which a pathological keychain entry plus machine
5039        // load has stretched past 120s — at which point the request surfaces a
5040        // transient "operation timed out" BEFORE the certificate verdict
5041        // exists and the assertion fails on the wrong error class. 120s was
5042        // tried twice and breached twice (485s observed once under load ~100).
5043        // Clean keychains answer in milliseconds; this budget only ever costs
5044        // time on machines with hostile trust settings, where a slow correct
5045        // verdict beats a fast wrong one.
5046        let client = Client::builder()
5047            .timeout(Duration::from_secs(600))
5048            .use_preconfigured_tls(tls_config)
5049            .build()
5050            .expect("build test embedding client");
5051        let result = send_embedding_request(
5052            || client.post(&url).body("{}"),
5053            "openai compatible",
5054            EmbeddingRequestPolicy::Query(QueryBudget {
5055                timeout_ms: 600_000,
5056            }),
5057        );
5058
5059        #[cfg(target_os = "linux")]
5060        if env::var_os("SSL_CERT_FILE").is_some() {
5061            let body = result.expect("SSL_CERT_FILE should make the private CA trusted");
5062            assert!(
5063                body.contains("\"data\""),
5064                "unexpected embedding response: {body}"
5065            );
5066            return;
5067        }
5068
5069        let error = result.expect_err("the private CA must not be trusted on this path");
5070        let lower = error.to_ascii_lowercase();
5071        assert!(
5072            ["certificate", "unknownissuer", "unknown issuer", "trust"]
5073                .iter()
5074                .any(|marker| lower.contains(marker)),
5075            "the rendered source chain must include a certificate trust failure: {error}"
5076        );
5077        assert!(
5078            !embedding_failure_is_transient(&error),
5079            "certificate trust failures must not be retried: {error}"
5080        );
5081    }
5082
5083    #[test]
5084    fn platform_verifier_tls_client_subprocess() {
5085        if env::var_os("AFT_PLATFORM_VERIFIER_TLS_CHILD").is_some() {
5086            run_platform_verifier_tls_child();
5087            return;
5088        }
5089
5090        // Run each trust configuration in a fresh process because the
5091        // TLS/platform-verifier configuration caches CA settings; SSL_CERT_FILE
5092        // must be set before that configuration is initialized for Linux CA
5093        // discovery to use it. The process-env lock prevents this test from
5094        // racing other tests that modify environment variables. macOS and Windows
5095        // exercise only the untrusted path because their platform verifiers do
5096        // not consult SSL_CERT_FILE.
5097        let _env_lock = crate::test_env::process_env_lock();
5098        let (url, _ca_file, server_handle) = start_platform_verifier_tls_server();
5099        let test_name = "semantic_index::tests::platform_verifier_tls_client_subprocess";
5100        #[cfg(target_os = "linux")]
5101        let ca_paths: &[Option<&Path>] = &[None, Some(_ca_file.path())];
5102        #[cfg(not(target_os = "linux"))]
5103        let ca_paths: &[Option<&Path>] = &[None];
5104
5105        for ca_path in ca_paths {
5106            let mut command = Command::new(env::current_exe().expect("test executable"));
5107            command
5108                .args(["--exact", test_name, "--nocapture"])
5109                .env("AFT_PLATFORM_VERIFIER_TLS_CHILD", "1")
5110                .env("AFT_PLATFORM_VERIFIER_TLS_URL", &url)
5111                .env_remove("SSL_CERT_FILE")
5112                .env_remove("SSL_CERT_DIR");
5113            if let Some(ca_path) = ca_path {
5114                command.env("SSL_CERT_FILE", ca_path);
5115            }
5116            let output = command.output().expect("run TLS child test");
5117            // Name the exit status and any terminating signal in the failure:
5118            // under heavy machine load this child has died with EMPTY output,
5119            // and a blind "child failed" leaves nothing to diagnose with.
5120            #[cfg(unix)]
5121            let signal = std::os::unix::process::ExitStatusExt::signal(&output.status);
5122            #[cfg(not(unix))]
5123            let signal: Option<i32> = None;
5124            assert!(
5125                output.status.success(),
5126                "TLS child failed: status={:?} code={:?} signal={:?}\nstdout:\n{}\nstderr:\n{}",
5127                output.status,
5128                output.status.code(),
5129                signal,
5130                String::from_utf8_lossy(&output.stdout),
5131                String::from_utf8_lossy(&output.stderr)
5132            );
5133        }
5134
5135        server_handle.join().expect("join test TLS server");
5136    }
5137
5138    #[test]
5139    fn local_backend_model_loading_body_is_transient() {
5140        // LM Studio / Ollama return a 4xx with a loading/unloaded message while
5141        // the model swaps; these must classify transient so the build self-heals.
5142        for body in [
5143            r#"{"error":"Model was unloaded while the request was still in queue.."}"#,
5144            r#"{"error":"model is loading, please wait"}"#,
5145            r#"{"error":"Model not loaded"}"#,
5146            "Loading model into memory",
5147        ] {
5148            assert!(
5149                embedding_response_body_is_transient(reqwest::StatusCode::BAD_REQUEST, body),
5150                "{body:?} should be body-transient"
5151            );
5152        }
5153
5154        // A genuine 4xx misconfiguration body must NOT be treated as transient,
5155        // even when it happens to contain generic words from the old broad
5156        // substring matcher.
5157        for body in [
5158            r#"{"error":"invalid api key"}"#,
5159            r#"{"error":"model 'foo' not found"}"#,
5160            "Bad Request: unknown field",
5161            "Bad Request: invalid loading model option",
5162            r#"{"error":"unauthorized while model is being loaded by another account"}"#,
5163        ] {
5164            assert!(
5165                !embedding_response_body_is_transient(reqwest::StatusCode::BAD_REQUEST, body),
5166                "{body:?} must not be body-transient"
5167            );
5168        }
5169
5170        assert!(
5171            !embedding_response_body_is_transient(
5172                reqwest::StatusCode::UNAUTHORIZED,
5173                r#"{"error":"model is loading, please wait"}"#
5174            ),
5175            "permanent auth failures must not become transient because of body text"
5176        );
5177    }
5178
5179    fn start_slow_embedding_server(
5180        expected_requests: usize,
5181        response_delay: Duration,
5182    ) -> (String, Arc<AtomicUsize>, thread::JoinHandle<()>) {
5183        let listener = TcpListener::bind("127.0.0.1:0").expect("bind slow embedding server");
5184        listener
5185            .set_nonblocking(true)
5186            .expect("set slow server nonblocking");
5187        let addr = listener.local_addr().expect("slow embedding server addr");
5188        let requests = Arc::new(AtomicUsize::new(0));
5189        let requests_for_thread = Arc::clone(&requests);
5190        let handle = thread::spawn(move || {
5191            let deadline = Instant::now() + Duration::from_secs(10);
5192            let mut handlers = Vec::new();
5193            while requests_for_thread.load(Ordering::SeqCst) < expected_requests
5194                && Instant::now() < deadline
5195            {
5196                match listener.accept() {
5197                    Ok((mut stream, _)) => {
5198                        requests_for_thread.fetch_add(1, Ordering::SeqCst);
5199                        handlers.push(thread::spawn(move || {
5200                            let mut request = [0u8; 4096];
5201                            let _ = stream.read(&mut request);
5202                            thread::sleep(response_delay);
5203                            let body =
5204                                r#"{"data":[{"embedding":[0.1,0.2,0.3],"index":0}]}"#;
5205                            let response = format!(
5206                                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
5207                                body.len(),
5208                                body
5209                            );
5210                            let _ = stream.write_all(response.as_bytes());
5211                        }));
5212                    }
5213                    Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
5214                        thread::sleep(Duration::from_millis(5));
5215                    }
5216                    Err(error) => panic!("accept slow embedding request: {error}"),
5217                }
5218            }
5219            for handler in handlers {
5220                handler.join().expect("slow embedding handler");
5221            }
5222        });
5223
5224        (format!("http://{addr}"), requests, handle)
5225    }
5226
5227    fn start_mock_http_server<F>(handler: F) -> (String, thread::JoinHandle<()>)
5228    where
5229        F: Fn(String, String, String) -> String + Send + 'static,
5230    {
5231        let listener = TcpListener::bind("127.0.0.1:0").expect("bind test server");
5232        let addr = listener.local_addr().expect("local addr");
5233        let handle = thread::spawn(move || {
5234            let (mut stream, _) = listener.accept().expect("accept request");
5235            let mut buf = Vec::new();
5236            let mut chunk = [0u8; 4096];
5237            let mut header_end = None;
5238            let mut content_length = 0usize;
5239            loop {
5240                let n = stream.read(&mut chunk).expect("read request");
5241                if n == 0 {
5242                    break;
5243                }
5244                buf.extend_from_slice(&chunk[..n]);
5245                if header_end.is_none() {
5246                    if let Some(pos) = buf.windows(4).position(|window| window == b"\r\n\r\n") {
5247                        header_end = Some(pos + 4);
5248                        let headers = String::from_utf8_lossy(&buf[..pos + 4]);
5249                        for line in headers.lines() {
5250                            if let Some(value) = line.strip_prefix("Content-Length:") {
5251                                content_length = value.trim().parse::<usize>().unwrap_or(0);
5252                            }
5253                        }
5254                    }
5255                }
5256                if let Some(end) = header_end {
5257                    if buf.len() >= end + content_length {
5258                        break;
5259                    }
5260                }
5261            }
5262
5263            let end = header_end.expect("header terminator");
5264            let request = String::from_utf8_lossy(&buf[..end]).to_string();
5265            let body = String::from_utf8_lossy(&buf[end..end + content_length]).to_string();
5266            let mut lines = request.lines();
5267            let request_line = lines.next().expect("request line").to_string();
5268            let path = request_line
5269                .split_whitespace()
5270                .nth(1)
5271                .expect("request path")
5272                .to_string();
5273            let response_body = handler(request_line, path, body);
5274            let response = format!(
5275                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
5276                response_body.len(),
5277                response_body
5278            );
5279            stream
5280                .write_all(response.as_bytes())
5281                .expect("write response");
5282        });
5283
5284        (format!("http://{}", addr), handle)
5285    }
5286
5287    fn start_truncated_body_server(attempts: usize) -> (String, thread::JoinHandle<()>) {
5288        let listener = TcpListener::bind("127.0.0.1:0").expect("bind truncated test server");
5289        listener
5290            .set_nonblocking(true)
5291            .expect("nonblocking listener");
5292        let addr = listener.local_addr().expect("local addr");
5293        let handle = thread::spawn(move || {
5294            // The deadline is only a hang-backstop for the case where the client
5295            // makes FEWER than `attempts` connections. It MUST comfortably exceed
5296            // the client's full retry budget (3 attempts: 3x250ms read-timeouts +
5297            // 500ms + 1000ms backoffs ~= 2.25s) so the last connect is always
5298            // accepted — otherwise the 3rd connect lands after a too-short
5299            // deadline, the server thread is already gone, and the client gets a
5300            // connect error ("request failed") instead of the body-read error the
5301            // test asserts. Under loaded CI (esp. Windows) thread scheduling
5302            // drifts the connects later, so this needs generous headroom.
5303            let deadline = std::time::Instant::now() + Duration::from_secs(30);
5304            let mut accepted = 0usize;
5305            while accepted < attempts && std::time::Instant::now() < deadline {
5306                match listener.accept() {
5307                    Ok((mut stream, _)) => {
5308                        accepted += 1;
5309                        let mut buf = [0u8; 4096];
5310                        // The client (under test) uses a 250ms timeout and drops
5311                        // the connection when the truncated body never completes.
5312                        // On Windows that disconnect surfaces as a hard socket
5313                        // error (WSAECONNRESET) on these read/write calls, where
5314                        // Unix returns a clean EOF. Tolerate both: the mock does
5315                        // not need the request bytes, and a write to an
5316                        // already-hung-up client is expected.
5317                        let _ = stream.read(&mut buf);
5318                        let response = "HTTP/1.1 200 OK
5319Content-Type: application/json
5320Content-Length: 128
5321Connection: close
5322
5323{";
5324                        let _ = stream.write_all(response.as_bytes());
5325                    }
5326                    Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
5327                        thread::sleep(Duration::from_millis(10));
5328                    }
5329                    Err(error) => panic!("accept request: {error}"),
5330                }
5331            }
5332        });
5333
5334        (format!("http://{}", addr), handle)
5335    }
5336
5337    #[test]
5338    fn response_body_read_failures_are_marked_transient() {
5339        let (url, handle) = start_truncated_body_server(EMBEDDING_REQUEST_MAX_ATTEMPTS);
5340        // Generous client timeout: this test classifies BODY-TRUNCATION errors,
5341        // and a tight budget flips the failure into a connect/send timeout on a
5342        // loaded machine, changing which error string the assertions see.
5343        let client = Client::builder()
5344            .timeout(Duration::from_secs(5))
5345            .build()
5346            .expect("client");
5347
5348        let error = send_embedding_request(
5349            || client.post(&url).body("{}"),
5350            "test backend",
5351            EmbeddingRequestPolicy::Build,
5352        )
5353        .expect_err("truncated body should fail");
5354
5355        handle.join().unwrap();
5356        assert!(
5357            embedding_failure_is_transient(&error),
5358            "body read failures should be transient-marked: {error}"
5359        );
5360        // The mock closes the socket after writing a truncated body. Whether
5361        // the client observes that as a body-read EOF or as a send-stage
5362        // connection reset is an OS-level race (Windows sends RST when the
5363        // socket closes with unread request bytes, and under load the mock's
5364        // single read can return early). Both shapes are the backend dying
5365        // mid-exchange and both must carry the transient marker; the message
5366        // prefix differs by stage.
5367        assert!(
5368            error.contains("response read failed") || error.contains("request failed"),
5369            "unexpected error shape: {error}"
5370        );
5371    }
5372
5373    fn test_vector_for_texts(texts: Vec<String>) -> Result<Vec<Vec<f32>>, String> {
5374        Ok(texts.iter().map(|_| vec![1.0, 0.0, 0.0]).collect())
5375    }
5376
5377    fn write_rust_file(path: &Path, function_name: &str) {
5378        fs::write(
5379            path,
5380            format!("pub fn {function_name}() -> bool {{\n    true\n}}\n"),
5381        )
5382        .unwrap();
5383    }
5384
5385    fn build_test_index(project_root: &Path, files: &[PathBuf]) -> SemanticIndex {
5386        let mut embed = test_vector_for_texts;
5387        SemanticIndex::build(project_root, files, &mut embed, 8).unwrap()
5388    }
5389
5390    fn test_project_root() -> PathBuf {
5391        std::env::current_dir().unwrap()
5392    }
5393
5394    #[test]
5395    fn empty_snapshot_replaces_nonempty_and_loads_as_valid_tombstone() {
5396        let project = tempfile::tempdir().expect("create project");
5397        let storage = tempfile::tempdir().expect("create storage");
5398        let source = project.path().join("lib.rs");
5399        write_rust_file(&source, "persisted_symbol");
5400        let populated = build_test_index(project.path(), std::slice::from_ref(&source));
5401        assert!(populated.write_to_disk(storage.path(), "project"));
5402
5403        let data_path = storage.path().join("semantic/project/semantic.bin");
5404        let populated_bytes = fs::read(&data_path).expect("read populated snapshot");
5405        let empty = SemanticIndex::new(project.path().to_path_buf(), populated.dimension());
5406        assert!(empty.write_to_disk(storage.path(), "project"));
5407        let empty_bytes = fs::read(&data_path).expect("read explicit empty snapshot");
5408        assert_ne!(empty_bytes, populated_bytes);
5409        let decoded = SemanticIndex::from_bytes(&empty_bytes, project.path())
5410            .expect("decode explicit empty snapshot");
5411        assert_eq!(decoded.entry_count(), 0);
5412        for _ in 0..2 {
5413            let loaded = SemanticIndex::read_from_disk(
5414                storage.path(),
5415                "project",
5416                project.path(),
5417                false,
5418                None,
5419            )
5420            .expect("explicit empty snapshot remains loadable");
5421            assert_eq!(loaded.entry_count(), 0);
5422        }
5423    }
5424
5425    #[test]
5426    fn persistence_failure_is_reported_to_caller() {
5427        let project = tempfile::tempdir().expect("create project");
5428        let storage_parent = tempfile::tempdir().expect("create storage parent");
5429        let storage_file = storage_parent.path().join("not-a-directory");
5430        fs::write(&storage_file, b"occupied").expect("create blocking file");
5431        let empty = SemanticIndex::new(project.path().to_path_buf(), 3);
5432
5433        assert!(!empty.write_to_disk(&storage_file, "project"));
5434    }
5435
5436    #[test]
5437    fn semantic_memory_estimate_is_zero_when_empty_and_scales_with_entries() {
5438        let root = test_project_root();
5439        let mut index = SemanticIndex::new(root.clone(), 3);
5440        assert_eq!(index.estimated_memory().estimated_bytes, Some(0));
5441
5442        let entry = |name: &str| EmbeddingEntry {
5443            chunk: SemanticChunk {
5444                file: root.join(format!("{name}.rs")),
5445                name: name.to_string(),
5446                qualified_name: Some(format!("module::{name}")),
5447                kind: SymbolKind::Function,
5448                start_line: 0,
5449                end_line: 1,
5450                exported: true,
5451                embed_text: format!("function {name} body"),
5452                snippet: format!("fn {name}() {{}}"),
5453            },
5454            norm: vector_norm(&[1.0, 2.0, 3.0]),
5455            vector: vec![1.0, 2.0, 3.0],
5456        };
5457        index.entries.push(entry("one"));
5458        let one_entry = index.estimated_memory().estimated_bytes.unwrap();
5459        assert!(one_entry > 0);
5460        index.entries.push(entry("two"));
5461        let two_entries = index.estimated_memory().estimated_bytes.unwrap();
5462        assert!(two_entries > one_entry);
5463    }
5464
5465    fn set_file_metadata(index: &mut SemanticIndex, file: &Path, mtime: SystemTime, size: u64) {
5466        index.file_mtimes.insert(file.to_path_buf(), mtime);
5467        index.file_sizes.insert(file.to_path_buf(), size);
5468        index
5469            .file_hashes
5470            .insert(file.to_path_buf(), cache_freshness::zero_hash());
5471    }
5472
5473    fn legacy_semantic_index_bytes(index: &SemanticIndex) -> Vec<u8> {
5474        let mut buf = Vec::new();
5475        let fingerprint_bytes = index.fingerprint.as_ref().and_then(|fingerprint| {
5476            let encoded = fingerprint.as_string();
5477            if encoded.is_empty() {
5478                None
5479            } else {
5480                Some(encoded.into_bytes())
5481            }
5482        });
5483        let file_mtimes: Vec<_> = index
5484            .file_mtimes
5485            .iter()
5486            .filter_map(|(path, mtime)| {
5487                cache_relative_path(&index.project_root, path)
5488                    .map(|relative| (relative, path, mtime))
5489            })
5490            .collect();
5491        let entries: Vec<_> = index
5492            .entries
5493            .iter()
5494            .filter_map(|entry| {
5495                cache_relative_path(&index.project_root, &entry.chunk.file)
5496                    .map(|relative| (relative, entry))
5497            })
5498            .collect();
5499
5500        buf.push(SEMANTIC_INDEX_VERSION_V6);
5501        buf.extend_from_slice(&(index.dimension as u32).to_le_bytes());
5502        buf.extend_from_slice(&(entries.len() as u32).to_le_bytes());
5503        let fp_bytes_ref: &[u8] = fingerprint_bytes.as_deref().unwrap_or(&[]);
5504        buf.extend_from_slice(&(fp_bytes_ref.len() as u32).to_le_bytes());
5505        buf.extend_from_slice(fp_bytes_ref);
5506
5507        buf.extend_from_slice(&(file_mtimes.len() as u32).to_le_bytes());
5508        for (relative, path, mtime) in &file_mtimes {
5509            let path_bytes = relative.to_string_lossy().as_bytes().to_vec();
5510            buf.extend_from_slice(&(path_bytes.len() as u32).to_le_bytes());
5511            buf.extend_from_slice(&path_bytes);
5512            let duration = mtime
5513                .duration_since(SystemTime::UNIX_EPOCH)
5514                .unwrap_or_default();
5515            buf.extend_from_slice(&duration.as_secs().to_le_bytes());
5516            buf.extend_from_slice(&duration.subsec_nanos().to_le_bytes());
5517            let size = index.file_sizes.get(*path).copied().unwrap_or_default();
5518            buf.extend_from_slice(&size.to_le_bytes());
5519            let hash = index
5520                .file_hashes
5521                .get(*path)
5522                .copied()
5523                .unwrap_or_else(cache_freshness::zero_hash);
5524            buf.extend_from_slice(hash.as_bytes());
5525        }
5526
5527        for (relative, entry) in &entries {
5528            let c = &entry.chunk;
5529            let file_bytes = relative.to_string_lossy().as_bytes().to_vec();
5530            buf.extend_from_slice(&(file_bytes.len() as u32).to_le_bytes());
5531            buf.extend_from_slice(&file_bytes);
5532
5533            let name_bytes = c.name.as_bytes();
5534            buf.extend_from_slice(&(name_bytes.len() as u32).to_le_bytes());
5535            buf.extend_from_slice(name_bytes);
5536
5537            buf.push(symbol_kind_to_u8(&c.kind));
5538            buf.extend_from_slice(&(c.start_line as u32).to_le_bytes());
5539            buf.extend_from_slice(&(c.end_line as u32).to_le_bytes());
5540            buf.push(c.exported as u8);
5541
5542            let snippet_bytes = c.snippet.as_bytes();
5543            buf.extend_from_slice(&(snippet_bytes.len() as u32).to_le_bytes());
5544            buf.extend_from_slice(snippet_bytes);
5545
5546            let embed_bytes = c.embed_text.as_bytes();
5547            buf.extend_from_slice(&(embed_bytes.len() as u32).to_le_bytes());
5548            buf.extend_from_slice(embed_bytes);
5549
5550            for &val in &entry.vector {
5551                buf.extend_from_slice(&val.to_le_bytes());
5552            }
5553        }
5554
5555        buf
5556    }
5557
5558    #[derive(Default)]
5559    struct RecordingEmbedder {
5560        calls: Vec<Vec<String>>,
5561    }
5562
5563    impl RecordingEmbedder {
5564        fn embed(&mut self, texts: Vec<String>) -> Result<Vec<Vec<f32>>, String> {
5565            let vectors = texts
5566                .iter()
5567                .map(|text| deterministic_test_vector(text))
5568                .collect();
5569            self.calls.push(texts);
5570            Ok(vectors)
5571        }
5572
5573        fn total_embedded_texts(&self) -> usize {
5574            self.calls.iter().map(Vec::len).sum()
5575        }
5576
5577        fn embedded_texts(&self) -> Vec<&str> {
5578            self.calls
5579                .iter()
5580                .flat_map(|batch| batch.iter().map(String::as_str))
5581                .collect()
5582        }
5583    }
5584
5585    fn deterministic_test_vector(text: &str) -> Vec<f32> {
5586        let hash = blake3::hash(text.as_bytes());
5587        let bytes = hash.as_bytes();
5588        vec![
5589            1.0,
5590            bytes[0] as f32 / 255.0,
5591            bytes[1] as f32 / 255.0,
5592            bytes[2] as f32 / 255.0,
5593        ]
5594    }
5595
5596    fn build_recorded_test_index(project_root: &Path, files: &[PathBuf]) -> SemanticIndex {
5597        let mut embedder = RecordingEmbedder::default();
5598        let mut embed = |texts: Vec<String>| embedder.embed(texts);
5599        SemanticIndex::build(project_root, files, &mut embed, 16).unwrap()
5600    }
5601
5602    fn force_stale(index: &mut SemanticIndex, file: &Path) {
5603        set_file_metadata(index, file, SystemTime::UNIX_EPOCH, 0);
5604    }
5605
5606    fn write_source(path: &Path, source: &str) {
5607        if let Some(parent) = path.parent() {
5608            fs::create_dir_all(parent).unwrap();
5609        }
5610        fs::write(path, source).unwrap();
5611    }
5612
5613    fn entries_for_file<'a>(index: &'a SemanticIndex, file: &Path) -> Vec<&'a EmbeddingEntry> {
5614        index
5615            .entries
5616            .iter()
5617            .filter(|entry| entry.chunk.file == file)
5618            .collect()
5619    }
5620
5621    fn entry_by_name<'a>(index: &'a SemanticIndex, file: &Path, name: &str) -> &'a EmbeddingEntry {
5622        index
5623            .entries
5624            .iter()
5625            .find(|entry| entry.chunk.file == file && entry.chunk.name == name)
5626            .unwrap_or_else(|| panic!("missing semantic entry {name} in {}", file.display()))
5627    }
5628
5629    fn file_summary_entry<'a>(index: &'a SemanticIndex, file: &Path) -> &'a EmbeddingEntry {
5630        index
5631            .entries
5632            .iter()
5633            .find(|entry| entry.chunk.file == file && entry.chunk.kind == SymbolKind::FileSummary)
5634            .unwrap_or_else(|| panic!("missing file-summary entry in {}", file.display()))
5635    }
5636
5637    #[test]
5638    fn borrowed_snapshots_deserialize_once_share_memory_and_drop_with_last_holder() {
5639        let owner = tempfile::tempdir().unwrap();
5640        let storage = tempfile::tempdir().unwrap();
5641        let borrower_a = tempfile::tempdir().unwrap();
5642        let borrower_b = tempfile::tempdir().unwrap();
5643        let relative = Path::new("src/lib.rs");
5644        for root in [owner.path(), borrower_a.path(), borrower_b.path()] {
5645            let file = root.join(relative);
5646            fs::create_dir_all(file.parent().unwrap()).unwrap();
5647            fs::write(&file, "pub fn shared_symbol() -> bool { true }\n").unwrap();
5648        }
5649        let owner_file = owner.path().join(relative);
5650        let metadata = fs::metadata(&owner_file).unwrap();
5651        let mut index = SemanticIndex::new(owner.path().to_path_buf(), 3);
5652        index.entries.push(EmbeddingEntry {
5653            chunk: SemanticChunk {
5654                file: owner_file.clone(),
5655                name: "shared_symbol".to_string(),
5656                qualified_name: None,
5657                kind: SymbolKind::Function,
5658                start_line: 0,
5659                end_line: 0,
5660                exported: true,
5661                embed_text: "shared symbol".to_string(),
5662                snippet: "pub fn shared_symbol() -> bool { true }".to_string(),
5663            },
5664            norm: vector_norm(&[1.0, 0.0, 0.0]),
5665            vector: vec![1.0, 0.0, 0.0],
5666        });
5667        index.file_mtimes.insert(
5668            owner_file.clone(),
5669            metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH),
5670        );
5671        index.file_sizes.insert(owner_file.clone(), metadata.len());
5672        index.file_hashes.insert(
5673            owner_file,
5674            blake3::hash(b"pub fn shared_symbol() -> bool { true }\n"),
5675        );
5676        index.set_fingerprint(SemanticIndexFingerprint {
5677            backend: "test".to_string(),
5678            model: "shared-base".to_string(),
5679            base_url: FALLBACK_BACKEND.to_string(),
5680            dimension: 3,
5681            chunking_version: default_chunking_version(),
5682        });
5683        assert!(index.shared_base.is_none(), "owner indexes stay private");
5684
5685        let project_key = format!(
5686            "shared-base-{}",
5687            blake3::hash(owner.path().as_os_str().as_encoded_bytes()).to_hex()
5688        );
5689        let dir = storage.path().join("semantic").join(&project_key);
5690        fs::create_dir_all(&dir).unwrap();
5691        fs::write(dir.join("semantic.bin"), index.to_bytes()).unwrap();
5692        let loads_before = SHARED_SEMANTIC_BASE_LOADS.load(Ordering::Relaxed);
5693        let hits_before = SHARED_SEMANTIC_BASE_HITS.load(Ordering::Relaxed);
5694        let a = SemanticIndex::read_from_disk_borrow_tolerant(
5695            storage.path(),
5696            &project_key,
5697            borrower_a.path(),
5698        )
5699        .unwrap();
5700        let b = SemanticIndex::read_from_disk_borrow_tolerant(
5701            storage.path(),
5702            &project_key,
5703            borrower_b.path(),
5704        )
5705        .unwrap();
5706        let a_base = a.shared_base.as_ref().unwrap();
5707        let b_base = b.shared_base.as_ref().unwrap();
5708        assert!(Arc::ptr_eq(a_base, b_base));
5709        assert!(SHARED_SEMANTIC_BASE_LOADS.load(Ordering::Relaxed) > loads_before);
5710        assert!(SHARED_SEMANTIC_BASE_HITS.load(Ordering::Relaxed) > hits_before);
5711        assert_eq!(
5712            a.search(&[1.0, 0.0, 0.0], 1)[0].file,
5713            borrower_a.path().join(relative)
5714        );
5715        assert_eq!(
5716            b.search(&[1.0, 0.0, 0.0], 1)[0].file,
5717            borrower_b.path().join(relative)
5718        );
5719        assert_eq!(a.estimated_memory().estimated_bytes, Some(0));
5720        assert!(shared_semantic_bases_memory().estimated_bytes.unwrap_or(0) > 0);
5721
5722        let weak = Arc::downgrade(a_base);
5723        let ctx = crate::context::AppContext::new(
5724            Box::new(crate::parser::TreeSitterProvider::new()),
5725            crate::config::Config {
5726                project_root: Some(borrower_a.path().to_path_buf()),
5727                ..crate::config::Config::default()
5728            },
5729        );
5730        *ctx.semantic_index()
5731            .write()
5732            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(a);
5733        assert!(ctx.evict_idle_artifacts());
5734        assert!(
5735            weak.upgrade().is_some(),
5736            "the second borrower keeps the base live"
5737        );
5738        drop(b);
5739        assert!(
5740            weak.upgrade().is_none(),
5741            "the last borrower releases the base"
5742        );
5743    }
5744
5745    #[test]
5746    fn borrowed_snapshot_hash_change_falls_back_to_private_copy() {
5747        let owner = tempfile::tempdir().unwrap();
5748        let storage = tempfile::tempdir().unwrap();
5749        let borrower_a = tempfile::tempdir().unwrap();
5750        let borrower_b = tempfile::tempdir().unwrap();
5751        let relative = Path::new("src/lib.rs");
5752        for root in [owner.path(), borrower_a.path(), borrower_b.path()] {
5753            let file = root.join(relative);
5754            fs::create_dir_all(file.parent().unwrap()).unwrap();
5755            fs::write(&file, "pub fn hash_guard() {}\n").unwrap();
5756        }
5757        let owner_file = owner.path().join(relative);
5758        let metadata = fs::metadata(&owner_file).unwrap();
5759        let mut index = SemanticIndex::new(owner.path().to_path_buf(), 2);
5760        index.entries.push(EmbeddingEntry {
5761            chunk: SemanticChunk {
5762                file: owner_file.clone(),
5763                name: "hash_guard".to_string(),
5764                qualified_name: None,
5765                kind: SymbolKind::Function,
5766                start_line: 0,
5767                end_line: 0,
5768                exported: true,
5769                embed_text: "hash guard".to_string(),
5770                snippet: "pub fn hash_guard() {}".to_string(),
5771            },
5772            norm: vector_norm(&[1.0, 0.0]),
5773            vector: vec![1.0, 0.0],
5774        });
5775        index.file_mtimes.insert(
5776            owner_file.clone(),
5777            metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH),
5778        );
5779        index.file_sizes.insert(owner_file.clone(), metadata.len());
5780        index
5781            .file_hashes
5782            .insert(owner_file, blake3::hash(b"pub fn hash_guard() {}\n"));
5783        index.set_fingerprint(SemanticIndexFingerprint {
5784            backend: "test".to_string(),
5785            model: "hash-guard".to_string(),
5786            base_url: FALLBACK_BACKEND.to_string(),
5787            dimension: 2,
5788            chunking_version: default_chunking_version(),
5789        });
5790        let project_key = format!(
5791            "hash-fallback-{}",
5792            blake3::hash(owner.path().as_os_str().as_encoded_bytes()).to_hex()
5793        );
5794        let dir = storage.path().join("semantic").join(&project_key);
5795        fs::create_dir_all(&dir).unwrap();
5796        fs::write(dir.join("semantic.bin"), index.to_bytes()).unwrap();
5797        let shared = SemanticIndex::read_from_disk_borrow_tolerant(
5798            storage.path(),
5799            &project_key,
5800            borrower_a.path(),
5801        )
5802        .unwrap();
5803        assert!(shared.shared_base.is_some());
5804
5805        let changed_vector = vec![0.0, 1.0];
5806        index.entries[0].norm = vector_norm(&changed_vector);
5807        index.entries[0].vector = changed_vector;
5808        fs::write(dir.join("semantic.bin"), index.to_bytes()).unwrap();
5809        let fallback = SemanticIndex::read_from_disk_borrow_tolerant(
5810            storage.path(),
5811            &project_key,
5812            borrower_b.path(),
5813        )
5814        .unwrap();
5815        assert!(
5816            fallback.shared_base.is_none(),
5817            "a different byte identity must not join the live shared generation"
5818        );
5819        drop(shared);
5820    }
5821
5822    #[test]
5823    fn borrow_only_root_skips_semantic_lock_and_persist() {
5824        let project = tempfile::tempdir().expect("project");
5825        let source = project.path().join("lib.rs");
5826        write_rust_file(&source, "borrow_only_symbol");
5827        let project_key = "shared-artifact-key".to_string();
5828        let storage = tempfile::tempdir().expect("storage");
5829        crate::root_cache::configure_artifact_access(project.path(), &project_key, true);
5830
5831        let _lock = SemanticIndexLock::acquire(storage.path(), &project_key, project.path())
5832            .expect("borrow-only lock downgrade");
5833        let cache_dir = storage.path().join("semantic").join(&project_key);
5834        assert!(!cache_dir.join("cache.lock").exists());
5835
5836        let index = build_test_index(project.path(), &[source]);
5837        index.write_to_disk(storage.path(), &project_key);
5838
5839        assert!(!cache_dir.join("semantic.bin").exists());
5840        assert!(!cache_dir.exists());
5841    }
5842
5843    #[test]
5844    fn refresh_stale_line_shift_reuses_all_chunks_and_retains_entries() {
5845        let temp = tempfile::tempdir().unwrap();
5846        let project_root = temp.path();
5847        let file = project_root.join("src/lib.rs");
5848        let original = "pub fn alpha() -> i32 {\n    1\n}\n\npub fn beta() -> i32 {\n    2\n}\n";
5849        write_source(&file, original);
5850
5851        let mut index = build_recorded_test_index(project_root, std::slice::from_ref(&file));
5852        let original_entry_count = index.entries.len();
5853        let original_alpha_vector = entry_by_name(&index, &file, "alpha").vector.clone();
5854
5855        write_source(&file, &format!("\n{original}"));
5856        force_stale(&mut index, &file);
5857
5858        let mut embedder = RecordingEmbedder::default();
5859        let mut embed = |texts: Vec<String>| embedder.embed(texts);
5860        let mut progress = |_done: usize, _total: usize| {};
5861        let summary = index
5862            .refresh_stale_files(
5863                project_root,
5864                std::slice::from_ref(&file),
5865                &mut embed,
5866                16,
5867                &mut progress,
5868            )
5869            .unwrap();
5870
5871        assert_eq!(summary.changed, 1);
5872        assert_eq!(embedder.total_embedded_texts(), 0);
5873        assert_eq!(index.entries.len(), original_entry_count);
5874        let shifted_alpha = entry_by_name(&index, &file, "alpha");
5875        assert_eq!(shifted_alpha.chunk.start_line, 1);
5876        assert_eq!(shifted_alpha.vector, original_alpha_vector);
5877    }
5878
5879    #[test]
5880    fn refresh_invalidated_line_shift_emits_full_replacement_delta_for_apply() {
5881        let temp = tempfile::tempdir().unwrap();
5882        let project_root = temp.path();
5883        let file = project_root.join("src/lib.rs");
5884        let original = "pub fn alpha() -> i32 {\n    1\n}\n\npub fn beta() -> i32 {\n    2\n}\n";
5885        write_source(&file, original);
5886
5887        let mut worker_index = build_recorded_test_index(project_root, std::slice::from_ref(&file));
5888        let mut serving_index = worker_index.clone();
5889        let original_entry_count = worker_index.entries.len();
5890
5891        write_source(&file, &format!("\n{original}"));
5892
5893        let mut embedder = RecordingEmbedder::default();
5894        let mut embed = |texts: Vec<String>| embedder.embed(texts);
5895        let mut progress = |_done: usize, _total: usize| {};
5896        let update = worker_index
5897            .refresh_invalidated_files(
5898                project_root,
5899                std::slice::from_ref(&file),
5900                &mut embed,
5901                16,
5902                100,
5903                &mut progress,
5904            )
5905            .unwrap();
5906
5907        assert_eq!(embedder.total_embedded_texts(), 0);
5908        assert_eq!(update.added_entries.len(), original_entry_count);
5909        assert_eq!(worker_index.entries.len(), original_entry_count);
5910
5911        serving_index.apply_refresh_update(
5912            update.added_entries,
5913            update.updated_metadata,
5914            &update.completed_paths,
5915        );
5916
5917        assert_eq!(serving_index.entries.len(), original_entry_count);
5918        assert_eq!(
5919            entries_for_file(&serving_index, &file).len(),
5920            original_entry_count
5921        );
5922        assert_eq!(
5923            entry_by_name(&serving_index, &file, "alpha")
5924                .chunk
5925                .start_line,
5926            1
5927        );
5928    }
5929
5930    #[test]
5931    fn refresh_invalidated_one_symbol_edit_embeds_only_changed_symbol() {
5932        let temp = tempfile::tempdir().unwrap();
5933        let project_root = temp.path();
5934        let file = project_root.join("src/lib.rs");
5935        write_source(
5936            &file,
5937            "pub fn alpha() -> i32 {\n    1\n}\n\npub fn beta() -> i32 {\n    2\n}\n",
5938        );
5939
5940        let mut index = build_recorded_test_index(project_root, std::slice::from_ref(&file));
5941        let original_entry_count = index.entries.len();
5942        let beta_vector = entry_by_name(&index, &file, "beta").vector.clone();
5943
5944        write_source(
5945            &file,
5946            "pub fn alpha() -> i32 {\n    10\n}\n\npub fn beta() -> i32 {\n    2\n}\n",
5947        );
5948
5949        let mut embedder = RecordingEmbedder::default();
5950        let mut embed = |texts: Vec<String>| embedder.embed(texts);
5951        let mut progress = |_done: usize, _total: usize| {};
5952        let update = index
5953            .refresh_invalidated_files(
5954                project_root,
5955                std::slice::from_ref(&file),
5956                &mut embed,
5957                16,
5958                100,
5959                &mut progress,
5960            )
5961            .unwrap();
5962
5963        assert_eq!(embedder.total_embedded_texts(), 1);
5964        assert!(embedder.embedded_texts()[0].contains("name:alpha"));
5965        assert_eq!(update.added_entries.len(), original_entry_count);
5966        assert_eq!(entry_by_name(&index, &file, "beta").vector, beta_vector);
5967    }
5968
5969    #[test]
5970    fn refresh_reuses_one_old_vector_for_two_byte_identical_symbols() {
5971        let temp = tempfile::tempdir().unwrap();
5972        let project_root = temp.path();
5973        let file = project_root.join("src/dupe.js");
5974        let one_duplicate = "function duplicate() {\n  return 1;\n}\n";
5975        write_source(&file, one_duplicate);
5976
5977        let mut index = build_recorded_test_index(project_root, std::slice::from_ref(&file));
5978        let original_vector = entry_by_name(&index, &file, "duplicate").vector.clone();
5979
5980        write_source(&file, &format!("{one_duplicate}\n{one_duplicate}"));
5981
5982        let mut embedder = RecordingEmbedder::default();
5983        let mut embed = |texts: Vec<String>| embedder.embed(texts);
5984        let mut progress = |_done: usize, _total: usize| {};
5985        index
5986            .refresh_invalidated_files(
5987                project_root,
5988                std::slice::from_ref(&file),
5989                &mut embed,
5990                16,
5991                100,
5992                &mut progress,
5993            )
5994            .unwrap();
5995
5996        let duplicate_entries = index
5997            .entries
5998            .iter()
5999            .filter(|entry| entry.chunk.file == file && entry.chunk.name == "duplicate")
6000            .collect::<Vec<_>>();
6001        assert_eq!(duplicate_entries.len(), 2);
6002        assert_eq!(embedder.total_embedded_texts(), 0);
6003        assert_eq!(duplicate_entries[0].vector, original_vector);
6004        assert_eq!(duplicate_entries[1].vector, original_vector);
6005    }
6006
6007    #[test]
6008    fn file_summary_reuses_on_body_edit_and_misses_on_leading_doc_edit() {
6009        let temp = tempfile::tempdir().unwrap();
6010        let project_root = temp.path();
6011        let file = project_root.join("src/lib.rs");
6012        write_source(
6013            &file,
6014            "//! module docs v1\n\npub fn alpha() -> i32 {\n    1\n}\n",
6015        );
6016
6017        let mut index = build_recorded_test_index(project_root, std::slice::from_ref(&file));
6018        let summary_before = file_summary_entry(&index, &file).vector.clone();
6019
6020        write_source(
6021            &file,
6022            "//! module docs v1\n\npub fn alpha() -> i32 {\n    2\n}\n",
6023        );
6024        let mut body_embedder = RecordingEmbedder::default();
6025        let mut body_embed = |texts: Vec<String>| body_embedder.embed(texts);
6026        let mut progress = |_done: usize, _total: usize| {};
6027        index
6028            .refresh_invalidated_files(
6029                project_root,
6030                std::slice::from_ref(&file),
6031                &mut body_embed,
6032                16,
6033                100,
6034                &mut progress,
6035            )
6036            .unwrap();
6037        assert_eq!(body_embedder.total_embedded_texts(), 1);
6038        assert!(body_embedder.embedded_texts()[0].contains("name:alpha"));
6039        assert_eq!(file_summary_entry(&index, &file).vector, summary_before);
6040
6041        write_source(
6042            &file,
6043            "//! module docs v2\n\npub fn alpha() -> i32 {\n    2\n}\n",
6044        );
6045        let mut doc_embedder = RecordingEmbedder::default();
6046        let mut doc_embed = |texts: Vec<String>| doc_embedder.embed(texts);
6047        index
6048            .refresh_invalidated_files(
6049                project_root,
6050                std::slice::from_ref(&file),
6051                &mut doc_embed,
6052                16,
6053                100,
6054                &mut progress,
6055            )
6056            .unwrap();
6057
6058        assert_eq!(doc_embedder.total_embedded_texts(), 1);
6059        assert!(doc_embedder.embedded_texts()[0].contains("kind:file-summary"));
6060        assert_ne!(file_summary_entry(&index, &file).vector, summary_before);
6061    }
6062
6063    #[test]
6064    fn refresh_invalidated_deleted_file_drops_entries_without_embedding() {
6065        let temp = tempfile::tempdir().unwrap();
6066        let project_root = temp.path();
6067        let file = project_root.join("src/lib.rs");
6068        write_source(&file, "pub fn alpha() -> i32 {\n    1\n}\n");
6069
6070        let mut worker_index = build_recorded_test_index(project_root, std::slice::from_ref(&file));
6071        let mut serving_index = worker_index.clone();
6072        fs::remove_file(&file).unwrap();
6073
6074        let mut embedder = RecordingEmbedder::default();
6075        let mut embed = |texts: Vec<String>| embedder.embed(texts);
6076        let mut progress = |_done: usize, _total: usize| {};
6077        let update = worker_index
6078            .refresh_invalidated_files(
6079                project_root,
6080                std::slice::from_ref(&file),
6081                &mut embed,
6082                16,
6083                100,
6084                &mut progress,
6085            )
6086            .unwrap();
6087
6088        assert_eq!(update.summary.deleted, 1);
6089        assert_eq!(embedder.total_embedded_texts(), 0);
6090        assert!(worker_index.entries.is_empty());
6091
6092        serving_index.apply_refresh_update(
6093            update.added_entries,
6094            update.updated_metadata,
6095            &update.completed_paths,
6096        );
6097        assert!(serving_index.entries.is_empty());
6098    }
6099
6100    #[test]
6101    fn watcher_collect_failure_does_not_resurrect_stale_entries() {
6102        let temp = tempfile::tempdir().unwrap();
6103        let project_root = temp.path();
6104        let file = project_root.join("src/lib.rs");
6105        write_source(&file, "pub fn alpha() -> i32 {\n    1\n}\n");
6106
6107        let mut worker_index = build_recorded_test_index(project_root, std::slice::from_ref(&file));
6108        let mut serving_index = worker_index.clone();
6109        fs::write(&file, [0xff, 0xfe, 0xfd]).unwrap();
6110
6111        let mut embedder = RecordingEmbedder::default();
6112        let mut embed = |texts: Vec<String>| embedder.embed(texts);
6113        let mut progress = |_done: usize, _total: usize| {};
6114        let update = worker_index
6115            .refresh_invalidated_files(
6116                project_root,
6117                std::slice::from_ref(&file),
6118                &mut embed,
6119                16,
6120                100,
6121                &mut progress,
6122            )
6123            .unwrap();
6124
6125        assert_eq!(embedder.total_embedded_texts(), 0);
6126        assert!(update.added_entries.is_empty());
6127        assert!(worker_index.entries.is_empty());
6128        assert!(!worker_index.file_mtimes.contains_key(&file));
6129
6130        serving_index.apply_refresh_update(
6131            update.added_entries,
6132            update.updated_metadata,
6133            &update.completed_paths,
6134        );
6135        assert!(serving_index.entries.is_empty());
6136        assert!(!serving_index.file_mtimes.contains_key(&file));
6137    }
6138
6139    #[test]
6140    fn refresh_invalidated_cap_deferral_remains_file_count_based() {
6141        let temp = tempfile::tempdir().unwrap();
6142        let project_root = temp.path();
6143        let indexed = project_root.join("src/a.rs");
6144        let deferred = project_root.join("src/b.rs");
6145        write_source(&indexed, "pub fn alpha() -> i32 {\n    1\n}\n");
6146        write_source(&deferred, "pub fn beta() -> i32 {\n    2\n}\n");
6147
6148        let mut index = build_recorded_test_index(project_root, std::slice::from_ref(&indexed));
6149        let mut embedder = RecordingEmbedder::default();
6150        let mut embed = |texts: Vec<String>| embedder.embed(texts);
6151        let mut progress = |_done: usize, _total: usize| {};
6152        let update = index
6153            .refresh_invalidated_files(
6154                project_root,
6155                std::slice::from_ref(&deferred),
6156                &mut embed,
6157                16,
6158                1,
6159                &mut progress,
6160            )
6161            .unwrap();
6162
6163        assert_eq!(update.summary.total_processed, 1);
6164        assert_eq!(update.summary.added, 0);
6165        assert_eq!(embedder.total_embedded_texts(), 0);
6166        assert_eq!(index.indexed_file_count(), 1);
6167        assert!(index.deferred_files.contains(&deferred));
6168        assert!(entries_for_file(&index, &deferred).is_empty());
6169    }
6170
6171    #[test]
6172    fn semantic_cache_serialization_skips_paths_outside_project_root() {
6173        let dir = tempfile::tempdir().expect("create temp dir");
6174        let project = fs::canonicalize(dir.path()).expect("canonical project");
6175        let outside = project.join("..").join("outside.rs");
6176        let mut index = SemanticIndex::new(project.clone(), 3);
6177        index
6178            .file_mtimes
6179            .insert(outside.clone(), SystemTime::UNIX_EPOCH);
6180        index.file_sizes.insert(outside.clone(), 1);
6181        index
6182            .file_hashes
6183            .insert(outside.clone(), cache_freshness::zero_hash());
6184        index.entries.push(EmbeddingEntry {
6185            chunk: SemanticChunk {
6186                file: outside,
6187                name: "outside".to_string(),
6188                qualified_name: None,
6189                kind: SymbolKind::Function,
6190                start_line: 0,
6191                end_line: 0,
6192                exported: false,
6193                embed_text: "outside".to_string(),
6194                snippet: "outside".to_string(),
6195            },
6196            norm: vector_norm(&[1.0, 0.0, 0.0]),
6197            vector: vec![1.0, 0.0, 0.0],
6198        });
6199
6200        let bytes = index.to_bytes();
6201        let loaded = SemanticIndex::from_bytes(&bytes, &project).expect("load serialized index");
6202        assert_eq!(loaded.entries.len(), 0);
6203        assert!(loaded.file_mtimes.is_empty());
6204    }
6205
6206    #[test]
6207    fn semantic_search_bounded_top_k_matches_reference_full_sort() {
6208        let project_root = test_project_root();
6209        let file = project_root.join("src/lib.rs");
6210        let mut index = SemanticIndex::new(project_root, 2);
6211        let entries = [
6212            ("alpha", vec![2.0, 0.0], false),
6213            ("beta", vec![0.0, 3.0], false),
6214            ("gamma", vec![4.0, 0.0], false),
6215            ("delta", vec![1.0, 1.0], true),
6216            ("epsilon", vec![-5.0, 0.0], false),
6217        ];
6218        for (line, (name, vector, exported)) in entries.into_iter().enumerate() {
6219            index.entries.push(EmbeddingEntry {
6220                chunk: SemanticChunk {
6221                    file: file.clone(),
6222                    name: name.to_string(),
6223                    qualified_name: None,
6224                    kind: SymbolKind::Function,
6225                    start_line: line as u32 + 1,
6226                    end_line: line as u32 + 1,
6227                    exported,
6228                    embed_text: name.to_string(),
6229                    snippet: format!("fn {name}() {{}}"),
6230                },
6231                norm: vector_norm(&vector),
6232                vector,
6233            });
6234        }
6235
6236        let query = vec![2.0, 0.0];
6237        let top_k = 4;
6238        let mut reference: Vec<(f32, usize)> = index
6239            .entries
6240            .iter()
6241            .enumerate()
6242            .map(|(idx, entry)| {
6243                // Recompute both norms for every entry as the reference
6244                // implementation, so cached norms cannot change ranking or scores.
6245                let mut dot = 0.0f32;
6246                let mut query_squared_norm = 0.0f32;
6247                let mut entry_squared_norm = 0.0f32;
6248                for i in 0..query.len() {
6249                    dot += query[i] * entry.vector[i];
6250                    query_squared_norm += query[i] * query[i];
6251                    entry_squared_norm += entry.vector[i] * entry.vector[i];
6252                }
6253                let denom = query_squared_norm.sqrt() * entry_squared_norm.sqrt();
6254                let mut score = if denom == 0.0 { 0.0 } else { dot / denom };
6255                if entry.chunk.exported {
6256                    score *= 1.1;
6257                }
6258                (score, idx)
6259            })
6260            .collect();
6261        reference.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
6262        let expected: Vec<(String, f32)> = reference
6263            .into_iter()
6264            .take(top_k)
6265            .map(|(score, idx)| (index.entries[idx].chunk.name.clone(), score))
6266            .collect();
6267
6268        let actual: Vec<(String, f32)> = index
6269            .search(&query, top_k)
6270            .into_iter()
6271            .map(|result| (result.name, result.score))
6272            .collect();
6273
6274        assert_eq!(
6275            actual.iter().map(|(name, _)| name).collect::<Vec<_>>(),
6276            expected.iter().map(|(name, _)| name).collect::<Vec<_>>()
6277        );
6278        for ((_, actual_score), (_, expected_score)) in actual.iter().zip(expected.iter()) {
6279            assert!((actual_score - expected_score).abs() < 1e-6);
6280        }
6281        assert_eq!(actual[0].0, "alpha");
6282        assert_eq!(actual[1].0, "gamma", "equal scores keep insertion order");
6283        assert!(index.search(&query, 0).is_empty());
6284    }
6285
6286    #[test]
6287    fn test_cosine_similarity_identical() {
6288        let a = vec![1.0, 0.0, 0.0];
6289        let b = vec![1.0, 0.0, 0.0];
6290        assert!((cosine_similarity(&a, &b) - 1.0).abs() < 0.001);
6291    }
6292
6293    #[test]
6294    fn test_cosine_similarity_orthogonal() {
6295        let a = vec![1.0, 0.0, 0.0];
6296        let b = vec![0.0, 1.0, 0.0];
6297        assert!(cosine_similarity(&a, &b).abs() < 0.001);
6298    }
6299
6300    #[test]
6301    fn test_cosine_similarity_opposite() {
6302        let a = vec![1.0, 0.0, 0.0];
6303        let b = vec![-1.0, 0.0, 0.0];
6304        assert!((cosine_similarity(&a, &b) + 1.0).abs() < 0.001);
6305    }
6306
6307    #[test]
6308    fn test_serialization_roundtrip() {
6309        let project_root = test_project_root();
6310        let file = project_root.join("src/main.rs");
6311        let mut index = SemanticIndex::new(project_root.clone(), DEFAULT_DIMENSION);
6312        index.entries.push(EmbeddingEntry {
6313            chunk: SemanticChunk {
6314                file: file.clone(),
6315                name: "handle_request".to_string(),
6316                qualified_name: None,
6317                kind: SymbolKind::Function,
6318                start_line: 10,
6319                end_line: 25,
6320                exported: true,
6321                embed_text: "file:src/main.rs kind:function name:handle_request".to_string(),
6322                snippet: "fn handle_request() {\n  // ...\n}".to_string(),
6323            },
6324            norm: vector_norm(&[0.1, 0.2, 0.3, 0.4]),
6325            vector: vec![0.1, 0.2, 0.3, 0.4],
6326        });
6327        index.dimension = 4;
6328        index
6329            .file_mtimes
6330            .insert(file.clone(), SystemTime::UNIX_EPOCH);
6331        index.file_sizes.insert(file, 0);
6332        index.set_fingerprint(SemanticIndexFingerprint {
6333            backend: "fastembed".to_string(),
6334            model: "all-MiniLM-L6-v2".to_string(),
6335            base_url: FALLBACK_BACKEND.to_string(),
6336            dimension: 4,
6337            chunking_version: default_chunking_version(),
6338        });
6339
6340        let bytes = index.to_bytes();
6341        let restored = SemanticIndex::from_bytes(&bytes, &project_root).unwrap();
6342
6343        assert_eq!(restored.entries.len(), 1);
6344        assert_eq!(restored.entries[0].chunk.name, "handle_request");
6345        assert_eq!(restored.entries[0].vector, vec![0.1, 0.2, 0.3, 0.4]);
6346        assert_eq!(
6347            restored.entries[0].norm,
6348            vector_norm(&restored.entries[0].vector)
6349        );
6350        assert_eq!(restored.dimension, 4);
6351        assert_eq!(restored.backend_label(), Some("fastembed"));
6352        assert_eq!(restored.model_label(), Some("all-MiniLM-L6-v2"));
6353    }
6354
6355    #[test]
6356    fn semantic_cache_v6_loads_and_v7_round_trips_qualified_names() {
6357        let storage = tempfile::tempdir().expect("create storage dir");
6358        let project = storage.path().join("project");
6359        fs::create_dir_all(project.join("src")).expect("create project src");
6360        let file = project.join("src/lib.rs");
6361        fs::write(&file, "pub fn alpha() {}\npub fn beta() {}\n").expect("write source");
6362        let project_root = fs::canonicalize(&project).expect("canonical project");
6363        let file = fs::canonicalize(&file).expect("canonical file");
6364
6365        let mut index = SemanticIndex::new(project_root.clone(), 3);
6366        let mtime = SystemTime::UNIX_EPOCH + Duration::new(123, 456);
6367        index.file_mtimes.insert(file.clone(), mtime);
6368        index.file_sizes.insert(file.clone(), 42);
6369        index
6370            .file_hashes
6371            .insert(file.clone(), cache_freshness::zero_hash());
6372        index.entries.push(EmbeddingEntry {
6373            chunk: SemanticChunk {
6374                file: file.clone(),
6375                name: "alpha".to_string(),
6376                qualified_name: Some("Service.alpha".to_string()),
6377                kind: SymbolKind::Function,
6378                start_line: 0,
6379                end_line: 0,
6380                exported: true,
6381                embed_text: "file:src/lib.rs kind:function name:alpha".to_string(),
6382                snippet: "pub fn alpha() {}".to_string(),
6383            },
6384            norm: vector_norm(&[0.1, 0.2, 0.3]),
6385            vector: vec![0.1, 0.2, 0.3],
6386        });
6387        index.entries.push(EmbeddingEntry {
6388            chunk: SemanticChunk {
6389                file: file.clone(),
6390                name: "beta".to_string(),
6391                qualified_name: Some("Service.beta".to_string()),
6392                kind: SymbolKind::Function,
6393                start_line: 1,
6394                end_line: 1,
6395                exported: true,
6396                embed_text: "file:src/lib.rs kind:function name:beta".to_string(),
6397                snippet: "pub fn beta() {}".to_string(),
6398            },
6399            norm: vector_norm(&[0.4, 0.5, 0.6]),
6400            vector: vec![0.4, 0.5, 0.6],
6401        });
6402        let fingerprint = SemanticIndexFingerprint {
6403            backend: "fastembed".to_string(),
6404            model: "all-MiniLM-L6-v2".to_string(),
6405            base_url: FALLBACK_BACKEND.to_string(),
6406            dimension: 3,
6407            chunking_version: default_chunking_version(),
6408        };
6409        let fingerprint_before = fingerprint.as_string();
6410        index.set_fingerprint(fingerprint.clone());
6411
6412        let legacy_bytes = legacy_semantic_index_bytes(&index);
6413        assert_eq!(legacy_bytes[0], SEMANTIC_INDEX_VERSION_V6);
6414        let legacy_dir = storage.path().join("semantic/legacy-proj");
6415        fs::create_dir_all(&legacy_dir).expect("create legacy semantic dir");
6416        let legacy_path = legacy_dir.join("semantic.bin");
6417        fs::write(&legacy_path, &legacy_bytes).expect("write legacy semantic.bin");
6418        let legacy_loaded = SemanticIndex::read_from_disk(
6419            storage.path(),
6420            "legacy-proj",
6421            &project_root,
6422            false,
6423            Some(&fingerprint_before),
6424        )
6425        .expect("load v6 semantic index");
6426        assert!(
6427            legacy_path.exists(),
6428            "compatible V6 cache must not be deleted"
6429        );
6430        assert!(legacy_loaded
6431            .entries
6432            .iter()
6433            .all(|entry| entry.chunk.qualified_name.is_none()));
6434        assert_eq!(
6435            legacy_loaded.fingerprint().unwrap().as_string(),
6436            fingerprint_before
6437        );
6438
6439        let v7_bytes = index.to_bytes();
6440        assert_eq!(v7_bytes[0], SEMANTIC_INDEX_VERSION_V7);
6441        assert_ne!(v7_bytes, legacy_bytes);
6442        let restored = SemanticIndex::from_bytes(&v7_bytes, &project_root).unwrap();
6443        assert_eq!(
6444            restored.entries[0].chunk.qualified_name.as_deref(),
6445            Some("Service.alpha")
6446        );
6447        assert_eq!(
6448            restored.entries[1].chunk.qualified_name.as_deref(),
6449            Some("Service.beta")
6450        );
6451        assert_eq!(
6452            restored.fingerprint().unwrap().as_string(),
6453            fingerprint_before
6454        );
6455
6456        index.write_to_disk(storage.path(), "proj");
6457        let data_path = storage.path().join("semantic/proj/semantic.bin");
6458        let persisted = fs::read(&data_path).expect("read semantic.bin");
6459        assert_eq!(persisted[0], SEMANTIC_INDEX_VERSION_V7);
6460
6461        let loaded = SemanticIndex::read_from_disk(
6462            storage.path(),
6463            "proj",
6464            &project_root,
6465            false,
6466            Some(&fingerprint_before),
6467        )
6468        .expect("load semantic index");
6469        assert_eq!(loaded.entries.len(), index.entries.len());
6470        assert_eq!(loaded.dimension, index.dimension);
6471        assert_eq!(
6472            loaded.fingerprint().unwrap().as_string(),
6473            fingerprint_before
6474        );
6475        assert_eq!(loaded.file_mtimes.get(&file), Some(&mtime));
6476        assert_eq!(loaded.file_sizes.get(&file), Some(&42));
6477        assert_eq!(
6478            loaded.file_hashes.get(&file),
6479            Some(&cache_freshness::zero_hash())
6480        );
6481        for (actual, expected) in loaded.entries.iter().zip(index.entries.iter()) {
6482            assert_eq!(actual.chunk.file, expected.chunk.file);
6483            assert_eq!(actual.chunk.name, expected.chunk.name);
6484            assert_eq!(actual.chunk.qualified_name, expected.chunk.qualified_name);
6485            assert_eq!(actual.chunk.kind, expected.chunk.kind);
6486            assert_eq!(actual.chunk.start_line, expected.chunk.start_line);
6487            assert_eq!(actual.chunk.end_line, expected.chunk.end_line);
6488            assert_eq!(actual.chunk.exported, expected.chunk.exported);
6489            assert_eq!(actual.chunk.embed_text, expected.chunk.embed_text);
6490            assert_eq!(actual.chunk.snippet, expected.chunk.snippet);
6491            assert_eq!(actual.vector, expected.vector);
6492        }
6493        assert_eq!(loaded.to_bytes(), persisted);
6494        assert_eq!(fingerprint.as_string(), fingerprint_before);
6495    }
6496
6497    #[test]
6498    fn symbol_kind_serialization_roundtrip_includes_file_summary_variant() {
6499        let cases = [
6500            (SymbolKind::Function, 0),
6501            (SymbolKind::Class, 1),
6502            (SymbolKind::Method, 2),
6503            (SymbolKind::Struct, 3),
6504            (SymbolKind::Interface, 4),
6505            (SymbolKind::Enum, 5),
6506            (SymbolKind::TypeAlias, 6),
6507            (SymbolKind::Variable, 7),
6508            (SymbolKind::Heading, 8),
6509            (SymbolKind::FileSummary, 9),
6510        ];
6511
6512        for (kind, encoded) in cases {
6513            assert_eq!(symbol_kind_to_u8(&kind), encoded);
6514            assert_eq!(u8_to_symbol_kind(encoded), kind);
6515        }
6516    }
6517
6518    #[test]
6519    fn test_search_top_k() {
6520        let mut index = SemanticIndex::new(test_project_root(), DEFAULT_DIMENSION);
6521        index.dimension = 3;
6522
6523        // Add entries with known vectors
6524        for (i, name) in ["auth", "database", "handler"].iter().enumerate() {
6525            let mut vec = vec![0.0f32; 3];
6526            vec[i] = 1.0; // orthogonal vectors
6527            index.entries.push(EmbeddingEntry {
6528                chunk: SemanticChunk {
6529                    file: PathBuf::from("/src/lib.rs"),
6530                    name: name.to_string(),
6531                    qualified_name: None,
6532                    kind: SymbolKind::Function,
6533                    start_line: (i * 10 + 1) as u32,
6534                    end_line: (i * 10 + 5) as u32,
6535                    exported: true,
6536                    embed_text: format!("kind:function name:{}", name),
6537                    snippet: format!("fn {}() {{}}", name),
6538                },
6539                norm: vector_norm(&vec),
6540                vector: vec,
6541            });
6542        }
6543
6544        // Query aligned with "auth" (index 0)
6545        let query = vec![0.9, 0.1, 0.0];
6546        let results = index.search(&query, 2);
6547
6548        assert_eq!(results.len(), 2);
6549        assert_eq!(results[0].name, "auth"); // highest score
6550        assert!(results[0].score > results[1].score);
6551    }
6552
6553    #[test]
6554    fn test_empty_index_search() {
6555        let index = SemanticIndex::new(test_project_root(), DEFAULT_DIMENSION);
6556        let results = index.search(&[0.1, 0.2, 0.3], 10);
6557        assert!(results.is_empty());
6558    }
6559
6560    #[test]
6561    fn single_line_symbol_builds_non_empty_snippet() {
6562        let symbol = Symbol {
6563            name: "answer".to_string(),
6564            kind: SymbolKind::Variable,
6565            range: crate::symbols::Range {
6566                start_line: 0,
6567                start_col: 0,
6568                end_line: 0,
6569                end_col: 24,
6570            },
6571            signature: Some("const answer = 42".to_string()),
6572            scope_chain: Vec::new(),
6573            exported: true,
6574            parent: None,
6575        };
6576        let source = "export const answer = 42;\n";
6577
6578        let snippet = build_snippet(&symbol, source);
6579
6580        assert_eq!(snippet, "export const answer = 42;");
6581    }
6582
6583    #[test]
6584    fn optimized_file_chunk_collection_matches_file_parser_path() {
6585        let project_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
6586        let file = project_root.join("src/semantic_index.rs");
6587        let source = std::fs::read_to_string(&file).unwrap();
6588
6589        let mut legacy_parser = FileParser::new();
6590        let legacy_symbols = legacy_parser.extract_symbols(&file).unwrap();
6591        let legacy_chunks = symbols_to_chunks(&file, &legacy_symbols, &source, &project_root);
6592
6593        let optimized_chunks = collect_file_chunks(&project_root, &file).unwrap();
6594
6595        assert_eq!(
6596            chunk_fingerprint(&optimized_chunks),
6597            chunk_fingerprint(&legacy_chunks)
6598        );
6599    }
6600
6601    #[test]
6602    fn collect_file_chunks_indexes_java_symbols() {
6603        let dir = tempfile::tempdir().unwrap();
6604        let file = dir.path().join("Greeter.java");
6605        std::fs::write(
6606            &file,
6607            r#"package example;
6608
6609public class Greeter {
6610    public String greet(String name) {
6611        return "Hello, " + name;
6612    }
6613}
6614"#,
6615        )
6616        .unwrap();
6617
6618        let chunks = collect_file_chunks(dir.path(), &file).unwrap();
6619
6620        assert!(
6621            !chunks.is_empty(),
6622            "Java file should produce semantic chunks"
6623        );
6624        assert!(
6625            chunks
6626                .iter()
6627                .any(|chunk| chunk.name == "Greeter" && chunk.kind == SymbolKind::Class),
6628            "Java class symbol should be chunked: {chunks:?}"
6629        );
6630        assert!(
6631            chunks
6632                .iter()
6633                .any(|chunk| chunk.name == "greet" && chunk.kind == SymbolKind::Method),
6634            "Java method symbol should be chunked: {chunks:?}"
6635        );
6636    }
6637
6638    fn chunk_fingerprint(
6639        chunks: &[SemanticChunk],
6640    ) -> Vec<(String, SymbolKind, u32, u32, bool, String, String)> {
6641        chunks
6642            .iter()
6643            .map(|chunk| {
6644                (
6645                    chunk.name.clone(),
6646                    chunk.kind.clone(),
6647                    chunk.start_line,
6648                    chunk.end_line,
6649                    chunk.exported,
6650                    chunk.embed_text.clone(),
6651                    chunk.snippet.clone(),
6652                )
6653            })
6654            .collect()
6655    }
6656
6657    #[test]
6658    fn collect_file_chunks_skips_oversized_file() {
6659        let dir = tempfile::tempdir().unwrap();
6660        let big = dir.path().join("huge.ts");
6661        // Just over the cap: a valid TS file that would otherwise yield chunks.
6662        let filler = "export const x = 1;\n"
6663            .repeat(((MAX_SEMANTIC_FILE_BYTES as usize) / "export const x = 1;\n".len()) + 16);
6664        std::fs::write(&big, &filler).unwrap();
6665        assert!(big.metadata().unwrap().len() > MAX_SEMANTIC_FILE_BYTES);
6666
6667        // Oversized → tracked with zero chunks, NOT an error (so the caller keeps
6668        // the file in metadata and freshness skips re-reading it).
6669        let chunks = collect_file_chunks(dir.path(), &big).unwrap();
6670        assert!(chunks.is_empty(), "oversized file must yield no chunks");
6671
6672        // A small file of the same language still produces chunks.
6673        let small = dir.path().join("small.ts");
6674        std::fs::write(&small, "export function foo() { return 1; }\n").unwrap();
6675        let small_chunks = collect_file_chunks(dir.path(), &small).unwrap();
6676        assert!(!small_chunks.is_empty(), "small file should still chunk");
6677    }
6678
6679    #[test]
6680    fn rejects_oversized_dimension_during_deserialization() {
6681        let mut bytes = Vec::new();
6682        bytes.push(1u8);
6683        bytes.extend_from_slice(&((MAX_DIMENSION as u32) + 1).to_le_bytes());
6684        bytes.extend_from_slice(&0u32.to_le_bytes());
6685        bytes.extend_from_slice(&0u32.to_le_bytes());
6686
6687        assert!(SemanticIndex::from_bytes(&bytes, &test_project_root()).is_err());
6688    }
6689
6690    #[test]
6691    fn rejects_oversized_entry_count_during_deserialization() {
6692        let mut bytes = Vec::new();
6693        bytes.push(1u8);
6694        bytes.extend_from_slice(&(DEFAULT_DIMENSION as u32).to_le_bytes());
6695        bytes.extend_from_slice(&((MAX_ENTRIES as u32) + 1).to_le_bytes());
6696        bytes.extend_from_slice(&0u32.to_le_bytes());
6697
6698        assert!(SemanticIndex::from_bytes(&bytes, &test_project_root()).is_err());
6699    }
6700
6701    fn add_invalidation_fixture_entry(index: &mut SemanticIndex, file: PathBuf, ordinal: u64) {
6702        index.entries.push(EmbeddingEntry::new(
6703            SemanticChunk {
6704                file: file.clone(),
6705                name: format!("symbol_{ordinal}"),
6706                qualified_name: None,
6707                kind: SymbolKind::Function,
6708                start_line: ordinal as u32,
6709                end_line: ordinal as u32 + 1,
6710                exported: false,
6711                embed_text: format!("symbol {ordinal}"),
6712                snippet: format!("fn symbol_{ordinal}() {{}}"),
6713            },
6714            vec![ordinal as f32 + 1.0, 1.0],
6715        ));
6716        let mtime = SystemTime::UNIX_EPOCH + Duration::from_secs(ordinal + 1);
6717        index.file_mtimes.insert(file.clone(), mtime);
6718        index.file_sizes.insert(file.clone(), ordinal + 10);
6719        index
6720            .file_hashes
6721            .insert(file, blake3::hash(&ordinal.to_le_bytes()));
6722    }
6723
6724    #[test]
6725    fn batch_invalidation_matches_sequential_calls_with_one_retain_pass() {
6726        let temp = tempfile::tempdir().unwrap();
6727        let project_root = temp.path().canonicalize().unwrap();
6728        let mut source = SemanticIndex::new(project_root.clone(), 2);
6729        let files = (0..8)
6730            .map(|ordinal| {
6731                let file = project_root.join(format!("file_{ordinal}.rs"));
6732                fs::write(&file, format!("fn symbol_{ordinal}() {{}}\n")).unwrap();
6733                add_invalidation_fixture_entry(&mut source, file.clone(), ordinal);
6734                file
6735            })
6736            .collect::<Vec<_>>();
6737        let invalidated = vec![files[1].clone(), files[3].clone(), files[6].clone()];
6738
6739        let shared = Arc::new(source.into_shared_base().unwrap());
6740        let mut shared_batched =
6741            SemanticIndex::from_shared_base(project_root.clone(), Arc::clone(&shared));
6742        shared_batched.invalidate_files(&invalidated);
6743        let mut source = SemanticIndex::from_shared_base(project_root, shared);
6744        source.materialize_shared_base();
6745        let mut sequential = source.clone();
6746        let mut batched = source;
6747        for file in &invalidated {
6748            sequential.invalidate_file(file);
6749        }
6750        batched.invalidate_files(&invalidated);
6751
6752        assert!(sequential.shared_base.is_none());
6753        assert!(batched.shared_base.is_none());
6754        assert!(shared_batched.shared_base.is_none());
6755        assert_eq!(batched.to_bytes(), sequential.to_bytes());
6756        assert_eq!(shared_batched.file_mtimes, batched.file_mtimes);
6757        assert_eq!(shared_batched.file_sizes, batched.file_sizes);
6758        assert_eq!(shared_batched.file_hashes, batched.file_hashes);
6759        assert_eq!(
6760            format!("{:?}", shared_batched.entries),
6761            format!("{:?}", batched.entries)
6762        );
6763        assert_eq!(
6764            sequential.removal_retain_passes_for_test(),
6765            invalidated.len()
6766        );
6767        assert_eq!(batched.removal_retain_passes_for_test(), 1);
6768        assert_eq!(shared_batched.removal_retain_passes_for_test(), 1);
6769    }
6770
6771    #[cfg(unix)]
6772    #[test]
6773    fn batch_invalidation_removes_raw_and_canonical_alias_metadata() {
6774        use std::os::unix::fs::symlink;
6775
6776        let temp = tempfile::tempdir().unwrap();
6777        let project_root = temp.path().canonicalize().unwrap();
6778        let real_dir = project_root.join("real");
6779        let alias_dir = project_root.join("alias");
6780        fs::create_dir(&real_dir).unwrap();
6781        symlink(&real_dir, &alias_dir).unwrap();
6782        let real_file = real_dir.join("lib.rs");
6783        let alias_file = alias_dir.join("lib.rs");
6784        let untouched = project_root.join("untouched.rs");
6785        fs::write(&real_file, "fn aliased() {}\n").unwrap();
6786        fs::write(&untouched, "fn untouched() {}\n").unwrap();
6787        assert_eq!(fs::canonicalize(&alias_file).unwrap(), real_file);
6788
6789        let mut index = SemanticIndex::new(project_root, 2);
6790        add_invalidation_fixture_entry(&mut index, alias_file.clone(), 1);
6791        add_invalidation_fixture_entry(&mut index, real_file.clone(), 2);
6792        add_invalidation_fixture_entry(&mut index, untouched.clone(), 3);
6793        let mut sequential = index.clone();
6794        sequential.invalidate_file(&alias_file);
6795        index.invalidate_files(std::slice::from_ref(&alias_file));
6796
6797        assert_eq!(index.to_bytes(), sequential.to_bytes());
6798        assert!(index
6799            .entries
6800            .iter()
6801            .all(|entry| entry.chunk.file != alias_file && entry.chunk.file != real_file));
6802        assert!(!index.file_mtimes.contains_key(&alias_file));
6803        assert!(!index.file_mtimes.contains_key(&real_file));
6804        assert!(index.file_mtimes.contains_key(&untouched));
6805        assert!(!index.file_sizes.contains_key(&alias_file));
6806        assert!(!index.file_sizes.contains_key(&real_file));
6807        assert!(index.file_sizes.contains_key(&untouched));
6808        assert!(!index.file_hashes.contains_key(&alias_file));
6809        assert!(!index.file_hashes.contains_key(&real_file));
6810        assert!(index.file_hashes.contains_key(&untouched));
6811        assert_eq!(index.removal_retain_passes_for_test(), 1);
6812    }
6813
6814    #[test]
6815    fn invalidate_file_removes_entries_and_mtime() {
6816        let target = PathBuf::from("/src/main.rs");
6817        let mut index = SemanticIndex::new(test_project_root(), DEFAULT_DIMENSION);
6818        index.entries.push(EmbeddingEntry {
6819            chunk: SemanticChunk {
6820                file: target.clone(),
6821                name: "main".to_string(),
6822                qualified_name: None,
6823                kind: SymbolKind::Function,
6824                start_line: 0,
6825                end_line: 1,
6826                exported: false,
6827                embed_text: "main".to_string(),
6828                snippet: "fn main() {}".to_string(),
6829            },
6830            norm: vector_norm(&[1.0; DEFAULT_DIMENSION]),
6831            vector: vec![1.0; DEFAULT_DIMENSION],
6832        });
6833        index
6834            .file_mtimes
6835            .insert(target.clone(), SystemTime::UNIX_EPOCH);
6836        index.file_sizes.insert(target.clone(), 0);
6837
6838        index.invalidate_file(&target);
6839
6840        assert!(index.entries.is_empty());
6841        assert!(!index.file_mtimes.contains_key(&target));
6842        assert!(!index.file_sizes.contains_key(&target));
6843    }
6844
6845    #[test]
6846    fn refresh_missing_changed_file_is_purged_after_collect() {
6847        let temp = tempfile::tempdir().unwrap();
6848        let project_root = temp.path();
6849        let file = project_root.join("src/lib.rs");
6850        fs::create_dir_all(file.parent().unwrap()).unwrap();
6851        write_rust_file(&file, "vanished_symbol");
6852
6853        let mut index = build_test_index(project_root, std::slice::from_ref(&file));
6854        let original_size = *index.file_sizes.get(&file).unwrap();
6855        set_file_metadata(&mut index, &file, SystemTime::UNIX_EPOCH, original_size + 1);
6856        fs::remove_file(&file).unwrap();
6857
6858        let mut embed = test_vector_for_texts;
6859        let mut progress = |_done: usize, _total: usize| {};
6860        let summary = index
6861            .refresh_stale_files(
6862                project_root,
6863                std::slice::from_ref(&file),
6864                &mut embed,
6865                8,
6866                &mut progress,
6867            )
6868            .unwrap();
6869
6870        assert_eq!(summary.changed, 0);
6871        assert_eq!(summary.added, 0);
6872        assert_eq!(summary.deleted, 1);
6873        assert!(index.entries.is_empty());
6874        assert!(!index.file_mtimes.contains_key(&file));
6875        assert!(!index.file_sizes.contains_key(&file));
6876        assert!(!index.file_hashes.contains_key(&file));
6877    }
6878
6879    #[test]
6880    fn refresh_collect_error_for_existing_path_preserves_cached_entry() {
6881        let temp = tempfile::tempdir().unwrap();
6882        let project_root = temp.path();
6883        let file = project_root.join("src/lib.rs");
6884        fs::create_dir_all(file.parent().unwrap()).unwrap();
6885        write_rust_file(&file, "kept_symbol");
6886
6887        let mut index = build_test_index(project_root, std::slice::from_ref(&file));
6888        let original_entry_count = index.entries.len();
6889        let original_mtime = *index.file_mtimes.get(&file).unwrap();
6890        let original_size = *index.file_sizes.get(&file).unwrap();
6891
6892        let stale_mtime = SystemTime::UNIX_EPOCH;
6893        set_file_metadata(&mut index, &file, stale_mtime, original_size + 1);
6894        fs::remove_file(&file).unwrap();
6895        fs::create_dir(&file).unwrap();
6896
6897        let mut embed = test_vector_for_texts;
6898        let mut progress = |_done: usize, _total: usize| {};
6899        let summary = index
6900            .refresh_stale_files(
6901                project_root,
6902                std::slice::from_ref(&file),
6903                &mut embed,
6904                8,
6905                &mut progress,
6906            )
6907            .unwrap();
6908
6909        assert_eq!(summary.changed, 0);
6910        assert_eq!(summary.added, 0);
6911        assert_eq!(summary.deleted, 0);
6912        assert_eq!(index.entries.len(), original_entry_count);
6913        assert!(index
6914            .entries
6915            .iter()
6916            .any(|entry| entry.chunk.name == "kept_symbol"));
6917        assert_eq!(index.file_mtimes.get(&file), Some(&stale_mtime));
6918        assert_ne!(index.file_mtimes.get(&file), Some(&original_mtime));
6919        assert_eq!(index.file_sizes.get(&file), Some(&(original_size + 1)));
6920    }
6921
6922    #[test]
6923    fn refresh_never_indexed_file_error_does_not_record_mtime() {
6924        let temp = tempfile::tempdir().unwrap();
6925        let project_root = temp.path();
6926        let missing = project_root.join("src/missing.rs");
6927        fs::create_dir_all(missing.parent().unwrap()).unwrap();
6928
6929        let mut index = SemanticIndex::new(test_project_root(), DEFAULT_DIMENSION);
6930        let mut embed = test_vector_for_texts;
6931        let mut progress = |_done: usize, _total: usize| {};
6932        let summary = index
6933            .refresh_stale_files(
6934                project_root,
6935                std::slice::from_ref(&missing),
6936                &mut embed,
6937                8,
6938                &mut progress,
6939            )
6940            .unwrap();
6941
6942        assert_eq!(summary.added, 0);
6943        assert_eq!(summary.changed, 0);
6944        assert_eq!(summary.deleted, 0);
6945        assert!(!index.file_mtimes.contains_key(&missing));
6946        assert!(!index.file_sizes.contains_key(&missing));
6947        assert!(index.entries.is_empty());
6948    }
6949
6950    #[test]
6951    fn refresh_reports_added_for_new_files() {
6952        let temp = tempfile::tempdir().unwrap();
6953        let project_root = temp.path();
6954        let existing = project_root.join("src/lib.rs");
6955        let added = project_root.join("src/new.rs");
6956        fs::create_dir_all(existing.parent().unwrap()).unwrap();
6957        write_rust_file(&existing, "existing_symbol");
6958        write_rust_file(&added, "added_symbol");
6959
6960        let mut index = build_test_index(project_root, std::slice::from_ref(&existing));
6961        let mut embed = test_vector_for_texts;
6962        let mut progress = |_done: usize, _total: usize| {};
6963        let summary = index
6964            .refresh_stale_files(
6965                project_root,
6966                &[existing.clone(), added.clone()],
6967                &mut embed,
6968                8,
6969                &mut progress,
6970            )
6971            .unwrap();
6972
6973        assert_eq!(summary.added, 1);
6974        assert_eq!(summary.changed, 0);
6975        assert_eq!(summary.deleted, 0);
6976        assert_eq!(summary.total_processed, 2);
6977        assert!(index.file_mtimes.contains_key(&added));
6978        assert!(index.entries.iter().any(|entry| entry.chunk.file == added));
6979    }
6980
6981    #[test]
6982    fn refresh_reports_deleted_for_removed_files() {
6983        let temp = tempfile::tempdir().unwrap();
6984        let project_root = temp.path();
6985        let deleted = project_root.join("src/deleted.rs");
6986        fs::create_dir_all(deleted.parent().unwrap()).unwrap();
6987        write_rust_file(&deleted, "deleted_symbol");
6988
6989        let mut index = build_test_index(project_root, std::slice::from_ref(&deleted));
6990        fs::remove_file(&deleted).unwrap();
6991
6992        let mut embed = test_vector_for_texts;
6993        let mut progress = |_done: usize, _total: usize| {};
6994        let summary = index
6995            .refresh_stale_files(project_root, &[], &mut embed, 8, &mut progress)
6996            .unwrap();
6997
6998        assert_eq!(summary.deleted, 1);
6999        assert_eq!(summary.changed, 0);
7000        assert_eq!(summary.added, 0);
7001        assert_eq!(summary.total_processed, 1);
7002        assert!(!index.file_mtimes.contains_key(&deleted));
7003        assert!(index.entries.is_empty());
7004    }
7005
7006    #[test]
7007    fn refresh_reports_changed_for_modified_files() {
7008        let temp = tempfile::tempdir().unwrap();
7009        let project_root = temp.path();
7010        let file = project_root.join("src/lib.rs");
7011        fs::create_dir_all(file.parent().unwrap()).unwrap();
7012        write_rust_file(&file, "old_symbol");
7013
7014        let mut index = build_test_index(project_root, std::slice::from_ref(&file));
7015        set_file_metadata(&mut index, &file, SystemTime::UNIX_EPOCH, 0);
7016        write_rust_file(&file, "new_symbol");
7017
7018        let mut embed = test_vector_for_texts;
7019        let mut progress = |_done: usize, _total: usize| {};
7020        let summary = index
7021            .refresh_stale_files(
7022                project_root,
7023                std::slice::from_ref(&file),
7024                &mut embed,
7025                8,
7026                &mut progress,
7027            )
7028            .unwrap();
7029
7030        assert_eq!(summary.changed, 1);
7031        assert_eq!(summary.added, 0);
7032        assert_eq!(summary.deleted, 0);
7033        assert_eq!(summary.total_processed, 1);
7034        assert!(index
7035            .entries
7036            .iter()
7037            .any(|entry| entry.chunk.name == "new_symbol"));
7038        assert!(!index
7039            .entries
7040            .iter()
7041            .any(|entry| entry.chunk.name == "old_symbol"));
7042    }
7043
7044    #[test]
7045    fn refresh_all_clean_reports_zero_counts_and_no_embedding_work() {
7046        let temp = tempfile::tempdir().unwrap();
7047        let project_root = temp.path();
7048        let file = project_root.join("src/lib.rs");
7049        fs::create_dir_all(file.parent().unwrap()).unwrap();
7050        write_rust_file(&file, "clean_symbol");
7051
7052        let mut index = build_test_index(project_root, std::slice::from_ref(&file));
7053        let original_entries = index.entries.len();
7054        let mut embed_called = false;
7055        let mut embed = |texts: Vec<String>| {
7056            embed_called = true;
7057            test_vector_for_texts(texts)
7058        };
7059        let mut progress = |_done: usize, _total: usize| {};
7060        let summary = index
7061            .refresh_stale_files(
7062                project_root,
7063                std::slice::from_ref(&file),
7064                &mut embed,
7065                8,
7066                &mut progress,
7067            )
7068            .unwrap();
7069
7070        assert!(summary.is_noop());
7071        assert_eq!(summary.total_processed, 1);
7072        assert!(!embed_called);
7073        assert_eq!(index.entries.len(), original_entries);
7074    }
7075
7076    #[test]
7077    fn detects_missing_onnx_runtime_from_dynamic_load_error() {
7078        let message = "Failed to load ONNX Runtime shared library libonnxruntime.dylib via dlopen: no such file";
7079
7080        assert!(is_onnx_runtime_unavailable(message));
7081    }
7082
7083    #[test]
7084    fn formats_missing_onnx_runtime_with_install_hint() {
7085        let message = format_embedding_init_error(
7086            "Failed to load ONNX Runtime shared library libonnxruntime.so via dlopen: no such file",
7087        );
7088
7089        assert!(message.starts_with("ONNX Runtime not found. Install via:"));
7090        assert!(message.contains("Original error:"));
7091    }
7092
7093    #[test]
7094    fn interactive_query_budget_is_independent_from_build_timeout() {
7095        let mut config = SemanticBackendConfig {
7096            backend: SemanticBackend::OpenAiCompatible,
7097            model: "test-embedding".to_string(),
7098            base_url: Some("http://127.0.0.1:9".to_string()),
7099            api_key_env: None,
7100            timeout_ms: 0,
7101            query_timeout_ms: 0,
7102            max_batch_size: 64,
7103            max_files: 20_000,
7104        };
7105
7106        let build_model = SemanticEmbeddingModel::from_config(&config).unwrap();
7107        let query_model = SemanticEmbeddingModel::from_config_for_query(&config).unwrap();
7108        assert_eq!(
7109            build_model.timeout_ms(),
7110            DEFAULT_OPENAI_EMBEDDING_TIMEOUT_MS,
7111            "background build keeps the longer default embedding timeout"
7112        );
7113        assert_eq!(
7114            query_model.timeout_ms(),
7115            DEFAULT_OPENAI_EMBEDDING_TIMEOUT_MS,
7116            "a query-created model remains safe for later background build reuse"
7117        );
7118        assert_eq!(
7119            QueryBudget::from_config(&config).timeout_ms(),
7120            DEFAULT_SEMANTIC_QUERY_TIMEOUT_MS
7121        );
7122
7123        config.timeout_ms = 60_000;
7124        assert_eq!(
7125            QueryBudget::from_config(&config).timeout_ms(),
7126            DEFAULT_SEMANTIC_QUERY_TIMEOUT_MS,
7127            "the build timeout must not affect interactive requests"
7128        );
7129
7130        config.query_timeout_ms = 700;
7131        assert_eq!(QueryBudget::from_config(&config).timeout_ms(), 700);
7132    }
7133
7134    #[test]
7135    fn background_build_embedding_keeps_retry_ladder() {
7136        let (base_url, requests, handle) =
7137            start_slow_embedding_server(EMBEDDING_REQUEST_MAX_ATTEMPTS, Duration::from_millis(300));
7138        let config = SemanticBackendConfig {
7139            backend: SemanticBackend::OpenAiCompatible,
7140            model: "test-embedding".to_string(),
7141            base_url: Some(base_url),
7142            api_key_env: None,
7143            timeout_ms: 100,
7144            query_timeout_ms: DEFAULT_SEMANTIC_QUERY_TIMEOUT_MS,
7145            max_batch_size: 64,
7146            max_files: 20_000,
7147        };
7148        let mut model = SemanticEmbeddingModel::from_config(&config).unwrap();
7149
7150        let error = model
7151            .embed(vec!["slow build batch".to_string()])
7152            .expect_err("all slow build attempts should time out");
7153        handle.join().expect("slow embedding server");
7154
7155        assert!(embedding_failure_is_transient(&error), "error: {error}");
7156        assert_eq!(
7157            requests.load(Ordering::SeqCst),
7158            EMBEDDING_REQUEST_MAX_ATTEMPTS,
7159            "background builds must retain the existing retry ladder"
7160        );
7161    }
7162
7163    #[test]
7164    fn openai_compatible_backend_embeds_with_mock_server() {
7165        let (base_url, handle) = start_mock_http_server(|request_line, path, _body| {
7166            assert!(request_line.starts_with("POST "));
7167            assert_eq!(path, "/v1/embeddings");
7168            "{\"data\":[{\"embedding\":[0.1,0.2,0.3],\"index\":0},{\"embedding\":[0.4,0.5,0.6],\"index\":1}]}".to_string()
7169        });
7170
7171        let config = SemanticBackendConfig {
7172            backend: SemanticBackend::OpenAiCompatible,
7173            model: "test-embedding".to_string(),
7174            base_url: Some(base_url),
7175            api_key_env: None,
7176            timeout_ms: 5_000,
7177            query_timeout_ms: DEFAULT_SEMANTIC_QUERY_TIMEOUT_MS,
7178            max_batch_size: 64,
7179            max_files: 20_000,
7180        };
7181
7182        let mut model = SemanticEmbeddingModel::from_config(&config).unwrap();
7183        let vectors = model
7184            .embed(vec!["hello".to_string(), "world".to_string()])
7185            .unwrap();
7186
7187        assert_eq!(vectors, vec![vec![0.1, 0.2, 0.3], vec![0.4, 0.5, 0.6]]);
7188        handle.join().unwrap();
7189    }
7190
7191    /// Regression for issue #36: AFT was sending TWO Content-Type headers
7192    /// on the OpenAI embeddings request — once implicitly via `.json(&body)`
7193    /// and again explicitly via `.header("Content-Type", "application/json")`.
7194    /// reqwest's `.header()` calls `HeaderMap::append`, which produces two
7195    /// headers on the wire. OpenAI's /v1/embeddings endpoint rejects that
7196    /// with `HTTP 400 "you must provide a model parameter"` even though the
7197    /// body actually contains `model`. The fix is to drop the explicit
7198    /// `.header("Content-Type", ...)` call. This test pins that we send
7199    /// exactly one Content-Type header.
7200    #[test]
7201    fn openai_compatible_request_has_single_content_type_header() {
7202        use std::sync::{Arc, Mutex};
7203        let captured: Arc<Mutex<Vec<u8>>> = Arc::new(Mutex::new(Vec::new()));
7204        let captured_for_thread = Arc::clone(&captured);
7205
7206        let listener = TcpListener::bind("127.0.0.1:0").expect("bind test server");
7207        let addr = listener.local_addr().expect("local addr");
7208        let handle = thread::spawn(move || {
7209            let (mut stream, _) = listener.accept().expect("accept");
7210            let mut buf = Vec::new();
7211            let mut chunk = [0u8; 4096];
7212            let mut header_end = None;
7213            let mut content_length = 0usize;
7214            loop {
7215                let n = stream.read(&mut chunk).expect("read");
7216                if n == 0 {
7217                    break;
7218                }
7219                buf.extend_from_slice(&chunk[..n]);
7220                if header_end.is_none() {
7221                    if let Some(pos) = buf.windows(4).position(|window| window == b"\r\n\r\n") {
7222                        header_end = Some(pos + 4);
7223                        for line in String::from_utf8_lossy(&buf[..pos + 4]).lines() {
7224                            if let Some(value) = line.strip_prefix("Content-Length:") {
7225                                content_length = value.trim().parse::<usize>().unwrap_or(0);
7226                            }
7227                        }
7228                    }
7229                }
7230                if let Some(end) = header_end {
7231                    if buf.len() >= end + content_length {
7232                        break;
7233                    }
7234                }
7235            }
7236            *captured_for_thread.lock().unwrap() = buf;
7237            let body = "{\"data\":[{\"embedding\":[0.1,0.2,0.3],\"index\":0}]}";
7238            let response = format!(
7239                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
7240                body.len(),
7241                body
7242            );
7243            let _ = stream.write_all(response.as_bytes());
7244        });
7245
7246        let config = SemanticBackendConfig {
7247            backend: SemanticBackend::OpenAiCompatible,
7248            model: "text-embedding-3-small".to_string(),
7249            base_url: Some(format!("http://{}", addr)),
7250            api_key_env: None,
7251            timeout_ms: 5_000,
7252            query_timeout_ms: DEFAULT_SEMANTIC_QUERY_TIMEOUT_MS,
7253            max_batch_size: 64,
7254            max_files: 20_000,
7255        };
7256        let mut model = SemanticEmbeddingModel::from_config(&config).unwrap();
7257        let _ = model.embed(vec!["probe".to_string()]).unwrap();
7258        handle.join().unwrap();
7259
7260        let bytes = captured.lock().unwrap().clone();
7261        let request = String::from_utf8_lossy(&bytes);
7262
7263        // Lowercase line counts because HTTP headers are case-insensitive
7264        // and reqwest may emit `content-type` in lowercase under HTTP/2.
7265        let content_type_lines = request
7266            .lines()
7267            .filter(|line| {
7268                let lower = line.to_ascii_lowercase();
7269                lower.starts_with("content-type:")
7270            })
7271            .count();
7272        assert_eq!(
7273            content_type_lines, 1,
7274            "expected exactly one Content-Type header but found {content_type_lines}; full request:\n{request}",
7275        );
7276
7277        // The body must still include the model field — pin this so a future
7278        // change can't accidentally drop `model` while fixing duplicate headers.
7279        assert!(
7280            request.contains(r#""model":"text-embedding-3-small""#),
7281            "request body should contain model field; full request:\n{request}",
7282        );
7283    }
7284
7285    #[test]
7286    fn ollama_backend_embeds_with_mock_server() {
7287        let (base_url, handle) = start_mock_http_server(|request_line, path, _body| {
7288            assert!(request_line.starts_with("POST "));
7289            assert_eq!(path, "/api/embed");
7290            "{\"embeddings\":[[0.7,0.8,0.9],[1.0,1.1,1.2]]}".to_string()
7291        });
7292
7293        let config = SemanticBackendConfig {
7294            backend: SemanticBackend::Ollama,
7295            model: "embeddinggemma".to_string(),
7296            base_url: Some(base_url),
7297            api_key_env: None,
7298            timeout_ms: 5_000,
7299            query_timeout_ms: DEFAULT_SEMANTIC_QUERY_TIMEOUT_MS,
7300            max_batch_size: 64,
7301            max_files: 20_000,
7302        };
7303
7304        let mut model = SemanticEmbeddingModel::from_config(&config).unwrap();
7305        let vectors = model
7306            .embed(vec!["hello".to_string(), "world".to_string()])
7307            .unwrap();
7308
7309        assert_eq!(vectors, vec![vec![0.7, 0.8, 0.9], vec![1.0, 1.1, 1.2]]);
7310        handle.join().unwrap();
7311    }
7312
7313    #[test]
7314    fn read_from_disk_rejects_fingerprint_mismatch() {
7315        let storage = tempfile::tempdir().unwrap();
7316        let project_key = "proj";
7317
7318        let project_root = test_project_root();
7319        let file = project_root.join("src/main.rs");
7320        let mut index = SemanticIndex::new(project_root.clone(), DEFAULT_DIMENSION);
7321        index.entries.push(EmbeddingEntry {
7322            chunk: SemanticChunk {
7323                file: file.clone(),
7324                name: "handle_request".to_string(),
7325                qualified_name: None,
7326                kind: SymbolKind::Function,
7327                start_line: 10,
7328                end_line: 25,
7329                exported: true,
7330                embed_text: "file:src/main.rs kind:function name:handle_request".to_string(),
7331                snippet: "fn handle_request() {}".to_string(),
7332            },
7333            norm: vector_norm(&[0.1, 0.2, 0.3]),
7334            vector: vec![0.1, 0.2, 0.3],
7335        });
7336        index.dimension = 3;
7337        index
7338            .file_mtimes
7339            .insert(file.clone(), SystemTime::UNIX_EPOCH);
7340        index.file_sizes.insert(file, 0);
7341        index.set_fingerprint(SemanticIndexFingerprint {
7342            backend: "openai_compatible".to_string(),
7343            model: "test-embedding".to_string(),
7344            base_url: "http://127.0.0.1:1234/v1".to_string(),
7345            dimension: 3,
7346            chunking_version: default_chunking_version(),
7347        });
7348        index.write_to_disk(storage.path(), project_key);
7349
7350        let data_path = storage
7351            .path()
7352            .join("semantic")
7353            .join(project_key)
7354            .join("semantic.bin");
7355        let before = fs::read(&data_path).unwrap();
7356
7357        let matching = index.fingerprint().unwrap().as_string();
7358        assert!(SemanticIndex::read_from_disk(
7359            storage.path(),
7360            project_key,
7361            &project_root,
7362            false,
7363            Some(&matching),
7364        )
7365        .is_some());
7366
7367        let mismatched = SemanticIndexFingerprint {
7368            backend: "ollama".to_string(),
7369            model: "embeddinggemma".to_string(),
7370            base_url: "http://127.0.0.1:11434".to_string(),
7371            dimension: 3,
7372            chunking_version: default_chunking_version(),
7373        }
7374        .as_string();
7375        assert!(SemanticIndex::read_from_disk(
7376            storage.path(),
7377            project_key,
7378            &project_root,
7379            false,
7380            Some(&mismatched),
7381        )
7382        .is_none());
7383        assert_eq!(fs::read(&data_path).unwrap(), before);
7384    }
7385
7386    #[test]
7387    fn fingerprint_mismatch_details_redact_base_url_and_list_changed_fields() {
7388        let cached = SemanticIndexFingerprint {
7389            backend: "openai_compatible".to_string(),
7390            model: "cached-model".to_string(),
7391            base_url: "https://user:secret@example.com/v1/embeddings".to_string(),
7392            dimension: 3,
7393            chunking_version: 2,
7394        };
7395        let current = SemanticIndexFingerprint {
7396            backend: "ollama".to_string(),
7397            model: "current-model".to_string(),
7398            base_url: "https://example.org/api/embed".to_string(),
7399            dimension: 4,
7400            chunking_version: 3,
7401        };
7402
7403        let details = format_fingerprint_mismatch_details(Some(&cached), &current);
7404
7405        assert!(details.contains("backend kind cached=openai_compatible current=ollama"));
7406        assert!(details.contains("model cached=cached-model current=current-model"));
7407        assert!(details.contains("base_url host cached=example.com current=example.org"));
7408        assert!(details.contains("dimension cached=3 current=4"));
7409        assert!(details.contains("chunking version cached=2 current=3"));
7410        assert!(!details.contains("secret"));
7411        assert!(!details.contains("/v1/embeddings"));
7412        assert!(!details.contains("/api/embed"));
7413    }
7414
7415    #[test]
7416    fn read_from_disk_rejects_v3_cache_for_snippet_rebuild() {
7417        let storage = tempfile::tempdir().unwrap();
7418        let project_key = "proj-v3";
7419        let dir = storage.path().join("semantic").join(project_key);
7420        fs::create_dir_all(&dir).unwrap();
7421
7422        let mut index = SemanticIndex::new(test_project_root(), DEFAULT_DIMENSION);
7423        index.entries.push(EmbeddingEntry {
7424            chunk: SemanticChunk {
7425                file: PathBuf::from("/src/main.rs"),
7426                name: "handle_request".to_string(),
7427                qualified_name: None,
7428                kind: SymbolKind::Function,
7429                start_line: 0,
7430                end_line: 0,
7431                exported: true,
7432                embed_text: "file:src/main.rs kind:function name:handle_request".to_string(),
7433                snippet: "fn handle_request() {}".to_string(),
7434            },
7435            norm: vector_norm(&[0.1, 0.2, 0.3]),
7436            vector: vec![0.1, 0.2, 0.3],
7437        });
7438        index.dimension = 3;
7439        index
7440            .file_mtimes
7441            .insert(PathBuf::from("/src/main.rs"), SystemTime::UNIX_EPOCH);
7442        index.file_sizes.insert(PathBuf::from("/src/main.rs"), 0);
7443        let fingerprint = SemanticIndexFingerprint {
7444            backend: "fastembed".to_string(),
7445            model: "test".to_string(),
7446            base_url: FALLBACK_BACKEND.to_string(),
7447            dimension: 3,
7448            chunking_version: default_chunking_version(),
7449        };
7450        index.set_fingerprint(fingerprint.clone());
7451
7452        let mut bytes = index.to_bytes();
7453        bytes[0] = SEMANTIC_INDEX_VERSION_V3;
7454        let data_path = dir.join("semantic.bin");
7455        fs::write(&data_path, &bytes).unwrap();
7456
7457        assert!(SemanticIndex::read_from_disk(
7458            storage.path(),
7459            project_key,
7460            &test_project_root(),
7461            false,
7462            Some(&fingerprint.as_string())
7463        )
7464        .is_none());
7465        assert_eq!(fs::read(&data_path).unwrap(), bytes);
7466    }
7467
7468    fn make_symbol(kind: SymbolKind, name: &str, start: u32, end: u32) -> crate::symbols::Symbol {
7469        crate::symbols::Symbol {
7470            name: name.to_string(),
7471            kind,
7472            range: crate::symbols::Range {
7473                start_line: start,
7474                start_col: 0,
7475                end_line: end,
7476                end_col: 0,
7477            },
7478            signature: None,
7479            scope_chain: Vec::new(),
7480            exported: false,
7481            parent: None,
7482        }
7483    }
7484
7485    #[test]
7486    fn symbols_to_chunks_sets_qualified_name_without_changing_embed_text() {
7487        let project_root = PathBuf::from("/proj");
7488        let file = project_root.join("src/engine.ts");
7489        let source = "class Index {\n}\n";
7490        let mut symbol = make_symbol(SymbolKind::Class, "Index", 0, 1);
7491        symbol.scope_chain = vec!["Engine".to_string()];
7492        symbol.signature = Some("class Index".to_string());
7493        let embed_text = build_embed_text(&symbol, source, &file, &project_root);
7494
7495        let chunks = symbols_to_chunks(&file, &[symbol], source, &project_root);
7496        let chunk = chunks
7497            .iter()
7498            .find(|chunk| chunk.name == "Index")
7499            .expect("class chunk");
7500
7501        assert_eq!(chunk.name, "Index");
7502        assert_eq!(chunk.qualified_name.as_deref(), Some("Engine.Index"));
7503        assert_eq!(chunk.embed_text, embed_text);
7504        assert!(!chunk.embed_text.contains("Engine.Index"));
7505    }
7506
7507    /// Heading symbols (Markdown / HTML headings) must NOT be indexed —
7508    /// they overwhelmingly dominated semantic results even on code-shaped
7509    /// queries because heading prose embeds far more strongly than code
7510    /// chunks. Skipping headings keeps aft_search a code-finder.
7511    #[test]
7512    fn symbols_to_chunks_skips_heading_symbols() {
7513        let project_root = PathBuf::from("/proj");
7514        let file = project_root.join("README.md");
7515        let source = "# Title\n\nbody text\n\n## Section\n\nmore text\n";
7516
7517        let symbols = vec![
7518            make_symbol(SymbolKind::Heading, "Title", 0, 2),
7519            make_symbol(SymbolKind::Heading, "Section", 4, 6),
7520        ];
7521
7522        let chunks = symbols_to_chunks(&file, &symbols, source, &project_root);
7523        assert!(
7524            chunks.is_empty(),
7525            "Heading symbols must be filtered out before embedding; got {} chunk(s)",
7526            chunks.len()
7527        );
7528    }
7529
7530    /// A symbol with an enormous signature (e.g. a YAML/Kubernetes CronJob
7531    /// whose inline `command:` script is parsed into the signature) must not
7532    /// produce an embed_text that overflows the embedding backend's physical
7533    /// batch. Before the clamp, the unbounded `signature:` append created a
7534    /// multi-KB input that aborted the whole index build and degraded every
7535    /// search to lexical-only.
7536    #[test]
7537    fn build_embed_text_clamps_oversized_signature() {
7538        let project_root = PathBuf::from("/proj");
7539        let file = project_root.join("cronjob.yaml");
7540        let huge_sig = "kubectl ".repeat(2000); // ~16 KB
7541        let source = "apiVersion: batch/v1\nkind: CronJob\n";
7542
7543        let mut symbol = make_symbol(SymbolKind::Class, "cluster-janitor", 0, 1);
7544        symbol.signature = Some(huge_sig);
7545
7546        let text = build_embed_text(&symbol, source, &file, &project_root);
7547        assert!(
7548            text.chars().count() <= MAX_EMBED_TEXT_CHARS,
7549            "embed_text must be clamped to {} chars, got {}",
7550            MAX_EMBED_TEXT_CHARS,
7551            text.chars().count()
7552        );
7553    }
7554
7555    /// Code symbols (functions, classes, methods, structs, etc.) must still
7556    /// be indexed alongside the heading skip — otherwise we'd starve the
7557    /// index entirely.
7558    #[test]
7559    fn symbols_to_chunks_keeps_code_symbols_alongside_skipped_headings() {
7560        let project_root = PathBuf::from("/proj");
7561        let file = project_root.join("src/lib.rs");
7562        let source = "pub fn handle_request() -> bool {\n    true\n}\n";
7563
7564        let symbols = vec![
7565            // A heading mixed in (e.g. from a doc comment block elsewhere).
7566            make_symbol(SymbolKind::Heading, "doc heading", 0, 1),
7567            make_symbol(SymbolKind::Function, "handle_request", 0, 2),
7568            make_symbol(SymbolKind::Struct, "AuthService", 4, 6),
7569        ];
7570
7571        let chunks = symbols_to_chunks(&file, &symbols, source, &project_root);
7572        assert_eq!(
7573            chunks.len(),
7574            3,
7575            "Expected file-summary + 2 code chunks (Function + Struct), got {}",
7576            chunks.len()
7577        );
7578        let names: Vec<&str> = chunks.iter().map(|c| c.name.as_str()).collect();
7579        assert!(chunks
7580            .iter()
7581            .any(|chunk| matches!(chunk.kind, SymbolKind::FileSummary)));
7582        assert!(names.contains(&"handle_request"));
7583        assert!(names.contains(&"AuthService"));
7584        assert!(
7585            !names.contains(&"doc heading"),
7586            "Heading symbol leaked into chunks: {names:?}"
7587        );
7588    }
7589
7590    #[test]
7591    fn validate_ssrf_allows_loopback_hostnames() {
7592        // Loopback hostnames are explicitly allowed so self-hosted backends
7593        // (Ollama at http://localhost:11434) work at their default config.
7594        for host in &[
7595            "http://localhost",
7596            "http://localhost:8080",
7597            "http://localhost:11434", // Ollama default
7598            "http://localhost.localdomain",
7599            "http://foo.localhost",
7600        ] {
7601            assert!(
7602                validate_base_url_no_ssrf(host).is_ok(),
7603                "Expected {host} to be allowed (loopback), got: {:?}",
7604                validate_base_url_no_ssrf(host)
7605            );
7606        }
7607    }
7608
7609    #[test]
7610    fn validate_ssrf_allows_loopback_ips() {
7611        // 127.0.0.0/8 is loopback — by definition same-machine and not an
7612        // SSRF target. Allow it so Ollama at http://127.0.0.1:11434 works.
7613        for url in &[
7614            "http://127.0.0.1",
7615            "http://127.0.0.1:11434", // Ollama default
7616            "http://127.0.0.1:8080",
7617            "http://127.1.2.3",
7618        ] {
7619            let result = validate_base_url_no_ssrf(url);
7620            assert!(
7621                result.is_ok(),
7622                "Expected {url} to be allowed (loopback), got: {:?}",
7623                result
7624            );
7625        }
7626    }
7627
7628    #[test]
7629    fn validate_ssrf_rejects_private_non_loopback_ips() {
7630        // Non-loopback private/reserved IPs remain rejected — homelab/intranet
7631        // services on LAN IPs are real SSRF targets even though the user
7632        // configured them. Users who want this can opt in by binding the
7633        // service to a public-routable address.
7634        for url in &[
7635            "http://192.168.1.1",
7636            "http://10.0.0.1",
7637            "http://172.16.0.1",
7638            "http://169.254.169.254",
7639            "http://100.64.0.1",
7640        ] {
7641            let result = validate_base_url_no_ssrf(url);
7642            assert!(
7643                result.is_err(),
7644                "Expected {url} to be rejected (non-loopback private), got: {:?}",
7645                result
7646            );
7647        }
7648    }
7649
7650    #[test]
7651    fn validate_ssrf_rejects_mdns_local_hostnames() {
7652        // mDNS .local hostnames typically resolve to LAN devices, not
7653        // loopback. Rejecting them before DNS lookup gives a clearer error.
7654        for host in &[
7655            "http://printer.local",
7656            "http://nas.local:8080",
7657            "http://homelab.local",
7658        ] {
7659            let result = validate_base_url_no_ssrf(host);
7660            assert!(
7661                result.is_err(),
7662                "Expected {host} to be rejected (mDNS), got: {:?}",
7663                result
7664            );
7665        }
7666    }
7667
7668    #[test]
7669    fn normalize_base_url_allows_localhost_for_tests() {
7670        // normalize_base_url itself should NOT block localhost — only
7671        // validate_base_url_no_ssrf does. Tests construct backends directly.
7672        assert!(normalize_base_url("http://127.0.0.1:9999").is_ok());
7673        assert!(normalize_base_url("http://localhost:8080").is_ok());
7674    }
7675
7676    #[test]
7677    fn ssrf_guard_blocks_reserved_ranges_but_allows_loopback() {
7678        use std::net::IpAddr;
7679        let blocked = |s: &str| is_private_non_loopback_ip(&s.parse::<IpAddr>().unwrap());
7680
7681        // Private / link-local / CGNAT — blocked (unchanged behavior).
7682        assert!(blocked("10.0.0.1"));
7683        assert!(blocked("192.168.1.1"));
7684        assert!(blocked("169.254.0.1"));
7685        assert!(blocked("100.64.0.1"));
7686        // Newly covered by delegating to url_fetch's complete list:
7687        assert!(
7688            blocked("198.18.0.1"),
7689            "RFC2544 benchmark range must be blocked"
7690        );
7691        assert!(blocked("224.0.0.1"), "multicast must be blocked");
7692        assert!(blocked("fc00::1"), "IPv6 ULA must be blocked");
7693        assert!(blocked("fe80::1"), "IPv6 link-local must be blocked");
7694
7695        // Loopback — allowed (local Ollama endpoint), incl. IPv4-mapped form.
7696        assert!(!blocked("127.0.0.1"), "loopback must stay allowed");
7697        assert!(!blocked("::1"), "IPv6 loopback must stay allowed");
7698        assert!(
7699            !blocked("::ffff:127.0.0.1"),
7700            "IPv4-mapped loopback must stay allowed (matches prior carve-out)"
7701        );
7702
7703        // A public address must NOT be flagged.
7704        assert!(!blocked("8.8.8.8"));
7705    }
7706
7707    /// Pin the user-facing wording of the ONNX version-mismatch error.
7708    /// The auto-fix path MUST be listed first because it's the only safe
7709    /// option that doesn't require sudo or risk breaking other apps that
7710    /// link the system library. Regression of any of these strings would
7711    /// either mislead users (system rm before auto-fix) or break the
7712    /// `aft doctor --fix` discovery path.
7713    #[test]
7714    fn ort_mismatch_message_recommends_auto_fix_first() {
7715        let msg =
7716            format_ort_version_mismatch("1.9.0", "/usr/lib/x86_64-linux-gnu/libonnxruntime.so");
7717
7718        // The reported version and path must appear verbatim.
7719        assert!(
7720            msg.contains("v1.9.0"),
7721            "should report detected version: {msg}"
7722        );
7723        assert!(
7724            msg.contains("/usr/lib/x86_64-linux-gnu/libonnxruntime.so"),
7725            "should report system path: {msg}"
7726        );
7727        assert!(msg.contains("v1.20+"), "should state requirement: {msg}");
7728
7729        // Solution ordering: auto-fix is #1, system rm is #2, install is #3.
7730        let auto_fix_pos = msg
7731            .find("Auto-fix")
7732            .expect("Auto-fix solution missing — users won't discover --fix");
7733        let remove_pos = msg
7734            .find("Remove the old library")
7735            .expect("system-rm solution missing");
7736        assert!(
7737            auto_fix_pos < remove_pos,
7738            "Auto-fix must come before manual rm — see PR comment thread"
7739        );
7740
7741        // The auto-fix command must be runnable as-is on a fresh system.
7742        assert!(
7743            msg.contains("npx @cortexkit/aft doctor --fix"),
7744            "auto-fix command must be present and copy-pasteable: {msg}"
7745        );
7746    }
7747
7748    #[cfg(any(target_os = "linux", target_os = "macos"))]
7749    #[test]
7750    fn loaded_ort_version_detection_prefers_actual_loaded_library_path() {
7751        let requested = "libonnxruntime.so";
7752        let actual = "/usr/local/lib/libonnxruntime.so.1.19.0";
7753
7754        assert_eq!(detect_ort_version_from_path(requested), None);
7755        let (version, source) =
7756            detect_ort_version_from_resolved_or_requested(Some(actual.to_string()), requested);
7757
7758        assert_eq!(version, Some("1.19.0".to_string()));
7759        assert_eq!(source, actual);
7760
7761        let msg = format_ort_version_mismatch(&version.unwrap(), &source);
7762        assert!(msg.contains("v1.19.0"));
7763        assert!(msg.contains(actual));
7764    }
7765
7766    /// macOS dylib paths must not produce a malformed message when the
7767    /// system path lacks a trailing slash. This is a regression guard
7768    /// for the "{}\n{}" format string contract.
7769    #[test]
7770    fn ort_mismatch_message_handles_macos_dylib_path() {
7771        let msg = format_ort_version_mismatch("1.9.0", "/opt/homebrew/lib/libonnxruntime.dylib");
7772        assert!(msg.contains("v1.9.0"));
7773        assert!(msg.contains("/opt/homebrew/lib/libonnxruntime.dylib"));
7774        // The dylib path must appear in the auto-fix paragraph (single
7775        // quotes around it) AND in the manual-rm paragraph; verify
7776        // both placements survived the format string.
7777        assert!(
7778            msg.contains("'/opt/homebrew/lib/libonnxruntime.dylib'"),
7779            "system path should be quoted in the auto-fix sentence: {msg}"
7780        );
7781    }
7782
7783    // ── managed ONNX Runtime resolver tests ──────────────────────────────────
7784
7785    /// Build a fake `<storage>/onnxruntime/<version>/<libname>` tree. Returns
7786    /// the storage root. `lib_name` is the platform library filename the
7787    /// resolver looks for.
7788    fn fake_managed_ort_tree(storage: &std::path::Path, lib_name: &str, versions: &[(&str, bool)]) {
7789        for (version, has_lib) in versions {
7790            let dir = storage.join("onnxruntime").join(version);
7791            std::fs::create_dir_all(&dir).unwrap();
7792            if *has_lib {
7793                std::fs::write(dir.join(lib_name), b"fake-ort").unwrap();
7794            }
7795        }
7796    }
7797
7798    #[test]
7799    fn managed_ort_resolver_picks_highest_compatible_version() {
7800        let _env_lock = crate::test_env::process_env_lock();
7801        let storage = tempfile::tempdir().unwrap();
7802        fake_managed_ort_tree(
7803            storage.path(),
7804            MANAGED_ORT_LIB_NAME,
7805            &[
7806                ("1.19.0", true), // below the 1.20 floor — must be ignored
7807                ("1.20.1", true),
7808                ("1.24.4", true), // highest compatible — must win
7809                ("1.23.0", true),
7810            ],
7811        );
7812        let found = find_managed_onnx_runtime(storage.path()).expect("resolver finds a runtime");
7813        assert_eq!(
7814            found,
7815            storage
7816                .path()
7817                .join("onnxruntime")
7818                .join("1.24.4")
7819                .join(MANAGED_ORT_LIB_NAME)
7820        );
7821    }
7822
7823    #[test]
7824    fn managed_ort_resolver_ignores_non_version_and_pre_120_dirs() {
7825        let _env_lock = crate::test_env::process_env_lock();
7826        let storage = tempfile::tempdir().unwrap();
7827        fake_managed_ort_tree(
7828            storage.path(),
7829            MANAGED_ORT_LIB_NAME,
7830            &[
7831                ("1.19.0", true),     // pre-1.20 — ignored
7832                ("1.24.4.tmp", true), // not a parseable version — ignored
7833                ("latest", true),     // not a version — ignored
7834                ("1.24.4", false),    // compatible but no library file — ignored
7835            ],
7836        );
7837        assert_eq!(
7838            find_managed_onnx_runtime(storage.path()),
7839            None,
7840            "no compatible version with a library file should resolve"
7841        );
7842    }
7843
7844    #[test]
7845    fn managed_ort_resolver_absent_tree_falls_through() {
7846        let _env_lock = crate::test_env::process_env_lock();
7847        let storage = tempfile::tempdir().unwrap();
7848        // No onnxruntime/ dir at all.
7849        assert_eq!(find_managed_onnx_runtime(storage.path()), None);
7850        // Empty onnxruntime/ dir.
7851        std::fs::create_dir_all(storage.path().join("onnxruntime")).unwrap();
7852        assert_eq!(find_managed_onnx_runtime(storage.path()), None);
7853    }
7854
7855    #[test]
7856    fn managed_ort_resolver_prefers_version_root_over_lib_subdir() {
7857        let _env_lock = crate::test_env::process_env_lock();
7858        let storage = tempfile::tempdir().unwrap();
7859        let version_dir = storage.path().join("onnxruntime").join("1.24.4");
7860        std::fs::create_dir_all(version_dir.join("lib")).unwrap();
7861        // Both the version root and the lib/ subdir hold the library; the root
7862        // must win (mirrors resolveCachedOnnxRuntimeDir).
7863        std::fs::write(version_dir.join(MANAGED_ORT_LIB_NAME), b"root").unwrap();
7864        std::fs::write(version_dir.join("lib").join(MANAGED_ORT_LIB_NAME), b"lib").unwrap();
7865        let found = find_managed_onnx_runtime(storage.path()).expect("resolver finds a runtime");
7866        assert_eq!(found, version_dir.join(MANAGED_ORT_LIB_NAME));
7867    }
7868
7869    #[test]
7870    fn managed_ort_resolver_accepts_lib_subdir_only() {
7871        let _env_lock = crate::test_env::process_env_lock();
7872        let storage = tempfile::tempdir().unwrap();
7873        let version_dir = storage.path().join("onnxruntime").join("1.24.4");
7874        std::fs::create_dir_all(version_dir.join("lib")).unwrap();
7875        // Library only under lib/ (manual Microsoft-archive install, #71).
7876        std::fs::write(version_dir.join("lib").join(MANAGED_ORT_LIB_NAME), b"lib").unwrap();
7877        let found = find_managed_onnx_runtime(storage.path()).expect("resolver finds a runtime");
7878        assert_eq!(found, version_dir.join("lib").join(MANAGED_ORT_LIB_NAME));
7879    }
7880
7881    #[test]
7882    fn managed_ort_resolver_pre_set_env_short_circuits_without_reading_tree() {
7883        let _env_lock = crate::test_env::process_env_lock();
7884        let storage = tempfile::tempdir().unwrap();
7885        // Plant a poison dir that would panic the resolver if it were read:
7886        // a version dir whose name is a valid version but whose library file is
7887        // a directory (so `is_file()` would be false) — harmless, but the point
7888        // is the resolver must never even look.
7889        let poison = storage.path().join("onnxruntime").join("1.24.4");
7890        std::fs::create_dir_all(poison.join(MANAGED_ORT_LIB_NAME)).unwrap();
7891
7892        let before = MANAGED_ORT_PROBE_READS.load(Ordering::Relaxed);
7893        // Pre-set ORT_DYLIB_PATH — the resolver must not run at all.
7894        std::env::set_var("ORT_DYLIB_PATH", "/explicit/override/libonnxruntime.so");
7895        resolve_managed_onnx_runtime(storage.path());
7896        std::env::remove_var("ORT_DYLIB_PATH");
7897        assert_eq!(
7898            MANAGED_ORT_PROBE_READS.load(Ordering::Relaxed),
7899            before,
7900            "resolver must not read the storage tree when ORT_DYLIB_PATH is pre-set"
7901        );
7902    }
7903
7904    #[test]
7905    fn managed_ort_resolver_sets_env_when_found() {
7906        let _env_lock = crate::test_env::process_env_lock();
7907        let storage = tempfile::tempdir().unwrap();
7908        fake_managed_ort_tree(storage.path(), MANAGED_ORT_LIB_NAME, &[("1.24.4", true)]);
7909        std::env::remove_var("ORT_DYLIB_PATH");
7910        resolve_managed_onnx_runtime(storage.path());
7911        let set = std::env::var_os("ORT_DYLIB_PATH").expect("resolver sets ORT_DYLIB_PATH");
7912        assert_eq!(
7913            PathBuf::from(set),
7914            storage
7915                .path()
7916                .join("onnxruntime")
7917                .join("1.24.4")
7918                .join(MANAGED_ORT_LIB_NAME)
7919        );
7920        std::env::remove_var("ORT_DYLIB_PATH");
7921    }
7922}