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        // Generous budgets: on macOS the FIRST evaluation of an untrusted chain
5036        // can take >10s when the keychain holds a pathological trust-settings
5037        // entry (trustd walks user trust settings and storms signature checks),
5038        // and >45s when the parallel lib-test fan-out loads the machine on top
5039        // of that. The verifier still rejects correctly; a short timeout would
5040        // surface a transient "operation timed out" before the certificate
5041        // error exists. Clean keychains answer in milliseconds, so this budget
5042        // only ever costs time on machines with hostile trust settings.
5043        let client = Client::builder()
5044            .timeout(Duration::from_secs(120))
5045            .use_preconfigured_tls(tls_config)
5046            .build()
5047            .expect("build test embedding client");
5048        let result = send_embedding_request(
5049            || client.post(&url).body("{}"),
5050            "openai compatible",
5051            EmbeddingRequestPolicy::Query(QueryBudget {
5052                timeout_ms: 120_000,
5053            }),
5054        );
5055
5056        #[cfg(target_os = "linux")]
5057        if env::var_os("SSL_CERT_FILE").is_some() {
5058            let body = result.expect("SSL_CERT_FILE should make the private CA trusted");
5059            assert!(
5060                body.contains("\"data\""),
5061                "unexpected embedding response: {body}"
5062            );
5063            return;
5064        }
5065
5066        let error = result.expect_err("the private CA must not be trusted on this path");
5067        let lower = error.to_ascii_lowercase();
5068        assert!(
5069            ["certificate", "unknownissuer", "unknown issuer", "trust"]
5070                .iter()
5071                .any(|marker| lower.contains(marker)),
5072            "the rendered source chain must include a certificate trust failure: {error}"
5073        );
5074        assert!(
5075            !embedding_failure_is_transient(&error),
5076            "certificate trust failures must not be retried: {error}"
5077        );
5078    }
5079
5080    #[test]
5081    fn platform_verifier_tls_client_subprocess() {
5082        if env::var_os("AFT_PLATFORM_VERIFIER_TLS_CHILD").is_some() {
5083            run_platform_verifier_tls_child();
5084            return;
5085        }
5086
5087        // Run each trust configuration in a fresh process because the
5088        // TLS/platform-verifier configuration caches CA settings; SSL_CERT_FILE
5089        // must be set before that configuration is initialized for Linux CA
5090        // discovery to use it. The process-env lock prevents this test from
5091        // racing other tests that modify environment variables. macOS and Windows
5092        // exercise only the untrusted path because their platform verifiers do
5093        // not consult SSL_CERT_FILE.
5094        let _env_lock = crate::test_env::process_env_lock();
5095        let (url, _ca_file, server_handle) = start_platform_verifier_tls_server();
5096        let test_name = "semantic_index::tests::platform_verifier_tls_client_subprocess";
5097        #[cfg(target_os = "linux")]
5098        let ca_paths: &[Option<&Path>] = &[None, Some(_ca_file.path())];
5099        #[cfg(not(target_os = "linux"))]
5100        let ca_paths: &[Option<&Path>] = &[None];
5101
5102        for ca_path in ca_paths {
5103            let mut command = Command::new(env::current_exe().expect("test executable"));
5104            command
5105                .args(["--exact", test_name, "--nocapture"])
5106                .env("AFT_PLATFORM_VERIFIER_TLS_CHILD", "1")
5107                .env("AFT_PLATFORM_VERIFIER_TLS_URL", &url)
5108                .env_remove("SSL_CERT_FILE")
5109                .env_remove("SSL_CERT_DIR");
5110            if let Some(ca_path) = ca_path {
5111                command.env("SSL_CERT_FILE", ca_path);
5112            }
5113            let output = command.output().expect("run TLS child test");
5114            assert!(
5115                output.status.success(),
5116                "TLS child failed:\n{}\n{}",
5117                String::from_utf8_lossy(&output.stdout),
5118                String::from_utf8_lossy(&output.stderr)
5119            );
5120        }
5121
5122        server_handle.join().expect("join test TLS server");
5123    }
5124
5125    #[test]
5126    fn local_backend_model_loading_body_is_transient() {
5127        // LM Studio / Ollama return a 4xx with a loading/unloaded message while
5128        // the model swaps; these must classify transient so the build self-heals.
5129        for body in [
5130            r#"{"error":"Model was unloaded while the request was still in queue.."}"#,
5131            r#"{"error":"model is loading, please wait"}"#,
5132            r#"{"error":"Model not loaded"}"#,
5133            "Loading model into memory",
5134        ] {
5135            assert!(
5136                embedding_response_body_is_transient(reqwest::StatusCode::BAD_REQUEST, body),
5137                "{body:?} should be body-transient"
5138            );
5139        }
5140
5141        // A genuine 4xx misconfiguration body must NOT be treated as transient,
5142        // even when it happens to contain generic words from the old broad
5143        // substring matcher.
5144        for body in [
5145            r#"{"error":"invalid api key"}"#,
5146            r#"{"error":"model 'foo' not found"}"#,
5147            "Bad Request: unknown field",
5148            "Bad Request: invalid loading model option",
5149            r#"{"error":"unauthorized while model is being loaded by another account"}"#,
5150        ] {
5151            assert!(
5152                !embedding_response_body_is_transient(reqwest::StatusCode::BAD_REQUEST, body),
5153                "{body:?} must not be body-transient"
5154            );
5155        }
5156
5157        assert!(
5158            !embedding_response_body_is_transient(
5159                reqwest::StatusCode::UNAUTHORIZED,
5160                r#"{"error":"model is loading, please wait"}"#
5161            ),
5162            "permanent auth failures must not become transient because of body text"
5163        );
5164    }
5165
5166    fn start_slow_embedding_server(
5167        expected_requests: usize,
5168        response_delay: Duration,
5169    ) -> (String, Arc<AtomicUsize>, thread::JoinHandle<()>) {
5170        let listener = TcpListener::bind("127.0.0.1:0").expect("bind slow embedding server");
5171        listener
5172            .set_nonblocking(true)
5173            .expect("set slow server nonblocking");
5174        let addr = listener.local_addr().expect("slow embedding server addr");
5175        let requests = Arc::new(AtomicUsize::new(0));
5176        let requests_for_thread = Arc::clone(&requests);
5177        let handle = thread::spawn(move || {
5178            let deadline = Instant::now() + Duration::from_secs(10);
5179            let mut handlers = Vec::new();
5180            while requests_for_thread.load(Ordering::SeqCst) < expected_requests
5181                && Instant::now() < deadline
5182            {
5183                match listener.accept() {
5184                    Ok((mut stream, _)) => {
5185                        requests_for_thread.fetch_add(1, Ordering::SeqCst);
5186                        handlers.push(thread::spawn(move || {
5187                            let mut request = [0u8; 4096];
5188                            let _ = stream.read(&mut request);
5189                            thread::sleep(response_delay);
5190                            let body =
5191                                r#"{"data":[{"embedding":[0.1,0.2,0.3],"index":0}]}"#;
5192                            let response = format!(
5193                                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
5194                                body.len(),
5195                                body
5196                            );
5197                            let _ = stream.write_all(response.as_bytes());
5198                        }));
5199                    }
5200                    Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
5201                        thread::sleep(Duration::from_millis(5));
5202                    }
5203                    Err(error) => panic!("accept slow embedding request: {error}"),
5204                }
5205            }
5206            for handler in handlers {
5207                handler.join().expect("slow embedding handler");
5208            }
5209        });
5210
5211        (format!("http://{addr}"), requests, handle)
5212    }
5213
5214    fn start_mock_http_server<F>(handler: F) -> (String, thread::JoinHandle<()>)
5215    where
5216        F: Fn(String, String, String) -> String + Send + 'static,
5217    {
5218        let listener = TcpListener::bind("127.0.0.1:0").expect("bind test server");
5219        let addr = listener.local_addr().expect("local addr");
5220        let handle = thread::spawn(move || {
5221            let (mut stream, _) = listener.accept().expect("accept request");
5222            let mut buf = Vec::new();
5223            let mut chunk = [0u8; 4096];
5224            let mut header_end = None;
5225            let mut content_length = 0usize;
5226            loop {
5227                let n = stream.read(&mut chunk).expect("read request");
5228                if n == 0 {
5229                    break;
5230                }
5231                buf.extend_from_slice(&chunk[..n]);
5232                if header_end.is_none() {
5233                    if let Some(pos) = buf.windows(4).position(|window| window == b"\r\n\r\n") {
5234                        header_end = Some(pos + 4);
5235                        let headers = String::from_utf8_lossy(&buf[..pos + 4]);
5236                        for line in headers.lines() {
5237                            if let Some(value) = line.strip_prefix("Content-Length:") {
5238                                content_length = value.trim().parse::<usize>().unwrap_or(0);
5239                            }
5240                        }
5241                    }
5242                }
5243                if let Some(end) = header_end {
5244                    if buf.len() >= end + content_length {
5245                        break;
5246                    }
5247                }
5248            }
5249
5250            let end = header_end.expect("header terminator");
5251            let request = String::from_utf8_lossy(&buf[..end]).to_string();
5252            let body = String::from_utf8_lossy(&buf[end..end + content_length]).to_string();
5253            let mut lines = request.lines();
5254            let request_line = lines.next().expect("request line").to_string();
5255            let path = request_line
5256                .split_whitespace()
5257                .nth(1)
5258                .expect("request path")
5259                .to_string();
5260            let response_body = handler(request_line, path, body);
5261            let response = format!(
5262                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
5263                response_body.len(),
5264                response_body
5265            );
5266            stream
5267                .write_all(response.as_bytes())
5268                .expect("write response");
5269        });
5270
5271        (format!("http://{}", addr), handle)
5272    }
5273
5274    fn start_truncated_body_server(attempts: usize) -> (String, thread::JoinHandle<()>) {
5275        let listener = TcpListener::bind("127.0.0.1:0").expect("bind truncated test server");
5276        listener
5277            .set_nonblocking(true)
5278            .expect("nonblocking listener");
5279        let addr = listener.local_addr().expect("local addr");
5280        let handle = thread::spawn(move || {
5281            // The deadline is only a hang-backstop for the case where the client
5282            // makes FEWER than `attempts` connections. It MUST comfortably exceed
5283            // the client's full retry budget (3 attempts: 3x250ms read-timeouts +
5284            // 500ms + 1000ms backoffs ~= 2.25s) so the last connect is always
5285            // accepted — otherwise the 3rd connect lands after a too-short
5286            // deadline, the server thread is already gone, and the client gets a
5287            // connect error ("request failed") instead of the body-read error the
5288            // test asserts. Under loaded CI (esp. Windows) thread scheduling
5289            // drifts the connects later, so this needs generous headroom.
5290            let deadline = std::time::Instant::now() + Duration::from_secs(30);
5291            let mut accepted = 0usize;
5292            while accepted < attempts && std::time::Instant::now() < deadline {
5293                match listener.accept() {
5294                    Ok((mut stream, _)) => {
5295                        accepted += 1;
5296                        let mut buf = [0u8; 4096];
5297                        // The client (under test) uses a 250ms timeout and drops
5298                        // the connection when the truncated body never completes.
5299                        // On Windows that disconnect surfaces as a hard socket
5300                        // error (WSAECONNRESET) on these read/write calls, where
5301                        // Unix returns a clean EOF. Tolerate both: the mock does
5302                        // not need the request bytes, and a write to an
5303                        // already-hung-up client is expected.
5304                        let _ = stream.read(&mut buf);
5305                        let response = "HTTP/1.1 200 OK
5306Content-Type: application/json
5307Content-Length: 128
5308Connection: close
5309
5310{";
5311                        let _ = stream.write_all(response.as_bytes());
5312                    }
5313                    Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
5314                        thread::sleep(Duration::from_millis(10));
5315                    }
5316                    Err(error) => panic!("accept request: {error}"),
5317                }
5318            }
5319        });
5320
5321        (format!("http://{}", addr), handle)
5322    }
5323
5324    #[test]
5325    fn response_body_read_failures_are_marked_transient() {
5326        let (url, handle) = start_truncated_body_server(EMBEDDING_REQUEST_MAX_ATTEMPTS);
5327        // Generous client timeout: this test classifies BODY-TRUNCATION errors,
5328        // and a tight budget flips the failure into a connect/send timeout on a
5329        // loaded machine, changing which error string the assertions see.
5330        let client = Client::builder()
5331            .timeout(Duration::from_secs(5))
5332            .build()
5333            .expect("client");
5334
5335        let error = send_embedding_request(
5336            || client.post(&url).body("{}"),
5337            "test backend",
5338            EmbeddingRequestPolicy::Build,
5339        )
5340        .expect_err("truncated body should fail");
5341
5342        handle.join().unwrap();
5343        assert!(
5344            embedding_failure_is_transient(&error),
5345            "body read failures should be transient-marked: {error}"
5346        );
5347        // The mock closes the socket after writing a truncated body. Whether
5348        // the client observes that as a body-read EOF or as a send-stage
5349        // connection reset is an OS-level race (Windows sends RST when the
5350        // socket closes with unread request bytes, and under load the mock's
5351        // single read can return early). Both shapes are the backend dying
5352        // mid-exchange and both must carry the transient marker; the message
5353        // prefix differs by stage.
5354        assert!(
5355            error.contains("response read failed") || error.contains("request failed"),
5356            "unexpected error shape: {error}"
5357        );
5358    }
5359
5360    fn test_vector_for_texts(texts: Vec<String>) -> Result<Vec<Vec<f32>>, String> {
5361        Ok(texts.iter().map(|_| vec![1.0, 0.0, 0.0]).collect())
5362    }
5363
5364    fn write_rust_file(path: &Path, function_name: &str) {
5365        fs::write(
5366            path,
5367            format!("pub fn {function_name}() -> bool {{\n    true\n}}\n"),
5368        )
5369        .unwrap();
5370    }
5371
5372    fn build_test_index(project_root: &Path, files: &[PathBuf]) -> SemanticIndex {
5373        let mut embed = test_vector_for_texts;
5374        SemanticIndex::build(project_root, files, &mut embed, 8).unwrap()
5375    }
5376
5377    fn test_project_root() -> PathBuf {
5378        std::env::current_dir().unwrap()
5379    }
5380
5381    #[test]
5382    fn empty_snapshot_replaces_nonempty_and_loads_as_valid_tombstone() {
5383        let project = tempfile::tempdir().expect("create project");
5384        let storage = tempfile::tempdir().expect("create storage");
5385        let source = project.path().join("lib.rs");
5386        write_rust_file(&source, "persisted_symbol");
5387        let populated = build_test_index(project.path(), std::slice::from_ref(&source));
5388        assert!(populated.write_to_disk(storage.path(), "project"));
5389
5390        let data_path = storage.path().join("semantic/project/semantic.bin");
5391        let populated_bytes = fs::read(&data_path).expect("read populated snapshot");
5392        let empty = SemanticIndex::new(project.path().to_path_buf(), populated.dimension());
5393        assert!(empty.write_to_disk(storage.path(), "project"));
5394        let empty_bytes = fs::read(&data_path).expect("read explicit empty snapshot");
5395        assert_ne!(empty_bytes, populated_bytes);
5396        let decoded = SemanticIndex::from_bytes(&empty_bytes, project.path())
5397            .expect("decode explicit empty snapshot");
5398        assert_eq!(decoded.entry_count(), 0);
5399        for _ in 0..2 {
5400            let loaded = SemanticIndex::read_from_disk(
5401                storage.path(),
5402                "project",
5403                project.path(),
5404                false,
5405                None,
5406            )
5407            .expect("explicit empty snapshot remains loadable");
5408            assert_eq!(loaded.entry_count(), 0);
5409        }
5410    }
5411
5412    #[test]
5413    fn persistence_failure_is_reported_to_caller() {
5414        let project = tempfile::tempdir().expect("create project");
5415        let storage_parent = tempfile::tempdir().expect("create storage parent");
5416        let storage_file = storage_parent.path().join("not-a-directory");
5417        fs::write(&storage_file, b"occupied").expect("create blocking file");
5418        let empty = SemanticIndex::new(project.path().to_path_buf(), 3);
5419
5420        assert!(!empty.write_to_disk(&storage_file, "project"));
5421    }
5422
5423    #[test]
5424    fn semantic_memory_estimate_is_zero_when_empty_and_scales_with_entries() {
5425        let root = test_project_root();
5426        let mut index = SemanticIndex::new(root.clone(), 3);
5427        assert_eq!(index.estimated_memory().estimated_bytes, Some(0));
5428
5429        let entry = |name: &str| EmbeddingEntry {
5430            chunk: SemanticChunk {
5431                file: root.join(format!("{name}.rs")),
5432                name: name.to_string(),
5433                qualified_name: Some(format!("module::{name}")),
5434                kind: SymbolKind::Function,
5435                start_line: 0,
5436                end_line: 1,
5437                exported: true,
5438                embed_text: format!("function {name} body"),
5439                snippet: format!("fn {name}() {{}}"),
5440            },
5441            norm: vector_norm(&[1.0, 2.0, 3.0]),
5442            vector: vec![1.0, 2.0, 3.0],
5443        };
5444        index.entries.push(entry("one"));
5445        let one_entry = index.estimated_memory().estimated_bytes.unwrap();
5446        assert!(one_entry > 0);
5447        index.entries.push(entry("two"));
5448        let two_entries = index.estimated_memory().estimated_bytes.unwrap();
5449        assert!(two_entries > one_entry);
5450    }
5451
5452    fn set_file_metadata(index: &mut SemanticIndex, file: &Path, mtime: SystemTime, size: u64) {
5453        index.file_mtimes.insert(file.to_path_buf(), mtime);
5454        index.file_sizes.insert(file.to_path_buf(), size);
5455        index
5456            .file_hashes
5457            .insert(file.to_path_buf(), cache_freshness::zero_hash());
5458    }
5459
5460    fn legacy_semantic_index_bytes(index: &SemanticIndex) -> Vec<u8> {
5461        let mut buf = Vec::new();
5462        let fingerprint_bytes = index.fingerprint.as_ref().and_then(|fingerprint| {
5463            let encoded = fingerprint.as_string();
5464            if encoded.is_empty() {
5465                None
5466            } else {
5467                Some(encoded.into_bytes())
5468            }
5469        });
5470        let file_mtimes: Vec<_> = index
5471            .file_mtimes
5472            .iter()
5473            .filter_map(|(path, mtime)| {
5474                cache_relative_path(&index.project_root, path)
5475                    .map(|relative| (relative, path, mtime))
5476            })
5477            .collect();
5478        let entries: Vec<_> = index
5479            .entries
5480            .iter()
5481            .filter_map(|entry| {
5482                cache_relative_path(&index.project_root, &entry.chunk.file)
5483                    .map(|relative| (relative, entry))
5484            })
5485            .collect();
5486
5487        buf.push(SEMANTIC_INDEX_VERSION_V6);
5488        buf.extend_from_slice(&(index.dimension as u32).to_le_bytes());
5489        buf.extend_from_slice(&(entries.len() as u32).to_le_bytes());
5490        let fp_bytes_ref: &[u8] = fingerprint_bytes.as_deref().unwrap_or(&[]);
5491        buf.extend_from_slice(&(fp_bytes_ref.len() as u32).to_le_bytes());
5492        buf.extend_from_slice(fp_bytes_ref);
5493
5494        buf.extend_from_slice(&(file_mtimes.len() as u32).to_le_bytes());
5495        for (relative, path, mtime) in &file_mtimes {
5496            let path_bytes = relative.to_string_lossy().as_bytes().to_vec();
5497            buf.extend_from_slice(&(path_bytes.len() as u32).to_le_bytes());
5498            buf.extend_from_slice(&path_bytes);
5499            let duration = mtime
5500                .duration_since(SystemTime::UNIX_EPOCH)
5501                .unwrap_or_default();
5502            buf.extend_from_slice(&duration.as_secs().to_le_bytes());
5503            buf.extend_from_slice(&duration.subsec_nanos().to_le_bytes());
5504            let size = index.file_sizes.get(*path).copied().unwrap_or_default();
5505            buf.extend_from_slice(&size.to_le_bytes());
5506            let hash = index
5507                .file_hashes
5508                .get(*path)
5509                .copied()
5510                .unwrap_or_else(cache_freshness::zero_hash);
5511            buf.extend_from_slice(hash.as_bytes());
5512        }
5513
5514        for (relative, entry) in &entries {
5515            let c = &entry.chunk;
5516            let file_bytes = relative.to_string_lossy().as_bytes().to_vec();
5517            buf.extend_from_slice(&(file_bytes.len() as u32).to_le_bytes());
5518            buf.extend_from_slice(&file_bytes);
5519
5520            let name_bytes = c.name.as_bytes();
5521            buf.extend_from_slice(&(name_bytes.len() as u32).to_le_bytes());
5522            buf.extend_from_slice(name_bytes);
5523
5524            buf.push(symbol_kind_to_u8(&c.kind));
5525            buf.extend_from_slice(&(c.start_line as u32).to_le_bytes());
5526            buf.extend_from_slice(&(c.end_line as u32).to_le_bytes());
5527            buf.push(c.exported as u8);
5528
5529            let snippet_bytes = c.snippet.as_bytes();
5530            buf.extend_from_slice(&(snippet_bytes.len() as u32).to_le_bytes());
5531            buf.extend_from_slice(snippet_bytes);
5532
5533            let embed_bytes = c.embed_text.as_bytes();
5534            buf.extend_from_slice(&(embed_bytes.len() as u32).to_le_bytes());
5535            buf.extend_from_slice(embed_bytes);
5536
5537            for &val in &entry.vector {
5538                buf.extend_from_slice(&val.to_le_bytes());
5539            }
5540        }
5541
5542        buf
5543    }
5544
5545    #[derive(Default)]
5546    struct RecordingEmbedder {
5547        calls: Vec<Vec<String>>,
5548    }
5549
5550    impl RecordingEmbedder {
5551        fn embed(&mut self, texts: Vec<String>) -> Result<Vec<Vec<f32>>, String> {
5552            let vectors = texts
5553                .iter()
5554                .map(|text| deterministic_test_vector(text))
5555                .collect();
5556            self.calls.push(texts);
5557            Ok(vectors)
5558        }
5559
5560        fn total_embedded_texts(&self) -> usize {
5561            self.calls.iter().map(Vec::len).sum()
5562        }
5563
5564        fn embedded_texts(&self) -> Vec<&str> {
5565            self.calls
5566                .iter()
5567                .flat_map(|batch| batch.iter().map(String::as_str))
5568                .collect()
5569        }
5570    }
5571
5572    fn deterministic_test_vector(text: &str) -> Vec<f32> {
5573        let hash = blake3::hash(text.as_bytes());
5574        let bytes = hash.as_bytes();
5575        vec![
5576            1.0,
5577            bytes[0] as f32 / 255.0,
5578            bytes[1] as f32 / 255.0,
5579            bytes[2] as f32 / 255.0,
5580        ]
5581    }
5582
5583    fn build_recorded_test_index(project_root: &Path, files: &[PathBuf]) -> SemanticIndex {
5584        let mut embedder = RecordingEmbedder::default();
5585        let mut embed = |texts: Vec<String>| embedder.embed(texts);
5586        SemanticIndex::build(project_root, files, &mut embed, 16).unwrap()
5587    }
5588
5589    fn force_stale(index: &mut SemanticIndex, file: &Path) {
5590        set_file_metadata(index, file, SystemTime::UNIX_EPOCH, 0);
5591    }
5592
5593    fn write_source(path: &Path, source: &str) {
5594        if let Some(parent) = path.parent() {
5595            fs::create_dir_all(parent).unwrap();
5596        }
5597        fs::write(path, source).unwrap();
5598    }
5599
5600    fn entries_for_file<'a>(index: &'a SemanticIndex, file: &Path) -> Vec<&'a EmbeddingEntry> {
5601        index
5602            .entries
5603            .iter()
5604            .filter(|entry| entry.chunk.file == file)
5605            .collect()
5606    }
5607
5608    fn entry_by_name<'a>(index: &'a SemanticIndex, file: &Path, name: &str) -> &'a EmbeddingEntry {
5609        index
5610            .entries
5611            .iter()
5612            .find(|entry| entry.chunk.file == file && entry.chunk.name == name)
5613            .unwrap_or_else(|| panic!("missing semantic entry {name} in {}", file.display()))
5614    }
5615
5616    fn file_summary_entry<'a>(index: &'a SemanticIndex, file: &Path) -> &'a EmbeddingEntry {
5617        index
5618            .entries
5619            .iter()
5620            .find(|entry| entry.chunk.file == file && entry.chunk.kind == SymbolKind::FileSummary)
5621            .unwrap_or_else(|| panic!("missing file-summary entry in {}", file.display()))
5622    }
5623
5624    #[test]
5625    fn borrowed_snapshots_deserialize_once_share_memory_and_drop_with_last_holder() {
5626        let owner = tempfile::tempdir().unwrap();
5627        let storage = tempfile::tempdir().unwrap();
5628        let borrower_a = tempfile::tempdir().unwrap();
5629        let borrower_b = tempfile::tempdir().unwrap();
5630        let relative = Path::new("src/lib.rs");
5631        for root in [owner.path(), borrower_a.path(), borrower_b.path()] {
5632            let file = root.join(relative);
5633            fs::create_dir_all(file.parent().unwrap()).unwrap();
5634            fs::write(&file, "pub fn shared_symbol() -> bool { true }\n").unwrap();
5635        }
5636        let owner_file = owner.path().join(relative);
5637        let metadata = fs::metadata(&owner_file).unwrap();
5638        let mut index = SemanticIndex::new(owner.path().to_path_buf(), 3);
5639        index.entries.push(EmbeddingEntry {
5640            chunk: SemanticChunk {
5641                file: owner_file.clone(),
5642                name: "shared_symbol".to_string(),
5643                qualified_name: None,
5644                kind: SymbolKind::Function,
5645                start_line: 0,
5646                end_line: 0,
5647                exported: true,
5648                embed_text: "shared symbol".to_string(),
5649                snippet: "pub fn shared_symbol() -> bool { true }".to_string(),
5650            },
5651            norm: vector_norm(&[1.0, 0.0, 0.0]),
5652            vector: vec![1.0, 0.0, 0.0],
5653        });
5654        index.file_mtimes.insert(
5655            owner_file.clone(),
5656            metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH),
5657        );
5658        index.file_sizes.insert(owner_file.clone(), metadata.len());
5659        index.file_hashes.insert(
5660            owner_file,
5661            blake3::hash(b"pub fn shared_symbol() -> bool { true }\n"),
5662        );
5663        index.set_fingerprint(SemanticIndexFingerprint {
5664            backend: "test".to_string(),
5665            model: "shared-base".to_string(),
5666            base_url: FALLBACK_BACKEND.to_string(),
5667            dimension: 3,
5668            chunking_version: default_chunking_version(),
5669        });
5670        assert!(index.shared_base.is_none(), "owner indexes stay private");
5671
5672        let project_key = format!(
5673            "shared-base-{}",
5674            blake3::hash(owner.path().as_os_str().as_encoded_bytes()).to_hex()
5675        );
5676        let dir = storage.path().join("semantic").join(&project_key);
5677        fs::create_dir_all(&dir).unwrap();
5678        fs::write(dir.join("semantic.bin"), index.to_bytes()).unwrap();
5679        let loads_before = SHARED_SEMANTIC_BASE_LOADS.load(Ordering::Relaxed);
5680        let hits_before = SHARED_SEMANTIC_BASE_HITS.load(Ordering::Relaxed);
5681        let a = SemanticIndex::read_from_disk_borrow_tolerant(
5682            storage.path(),
5683            &project_key,
5684            borrower_a.path(),
5685        )
5686        .unwrap();
5687        let b = SemanticIndex::read_from_disk_borrow_tolerant(
5688            storage.path(),
5689            &project_key,
5690            borrower_b.path(),
5691        )
5692        .unwrap();
5693        let a_base = a.shared_base.as_ref().unwrap();
5694        let b_base = b.shared_base.as_ref().unwrap();
5695        assert!(Arc::ptr_eq(a_base, b_base));
5696        assert!(SHARED_SEMANTIC_BASE_LOADS.load(Ordering::Relaxed) > loads_before);
5697        assert!(SHARED_SEMANTIC_BASE_HITS.load(Ordering::Relaxed) > hits_before);
5698        assert_eq!(
5699            a.search(&[1.0, 0.0, 0.0], 1)[0].file,
5700            borrower_a.path().join(relative)
5701        );
5702        assert_eq!(
5703            b.search(&[1.0, 0.0, 0.0], 1)[0].file,
5704            borrower_b.path().join(relative)
5705        );
5706        assert_eq!(a.estimated_memory().estimated_bytes, Some(0));
5707        assert!(shared_semantic_bases_memory().estimated_bytes.unwrap_or(0) > 0);
5708
5709        let weak = Arc::downgrade(a_base);
5710        let ctx = crate::context::AppContext::new(
5711            Box::new(crate::parser::TreeSitterProvider::new()),
5712            crate::config::Config {
5713                project_root: Some(borrower_a.path().to_path_buf()),
5714                ..crate::config::Config::default()
5715            },
5716        );
5717        *ctx.semantic_index()
5718            .write()
5719            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(a);
5720        assert!(ctx.evict_idle_artifacts());
5721        assert!(
5722            weak.upgrade().is_some(),
5723            "the second borrower keeps the base live"
5724        );
5725        drop(b);
5726        assert!(
5727            weak.upgrade().is_none(),
5728            "the last borrower releases the base"
5729        );
5730    }
5731
5732    #[test]
5733    fn borrowed_snapshot_hash_change_falls_back_to_private_copy() {
5734        let owner = tempfile::tempdir().unwrap();
5735        let storage = tempfile::tempdir().unwrap();
5736        let borrower_a = tempfile::tempdir().unwrap();
5737        let borrower_b = tempfile::tempdir().unwrap();
5738        let relative = Path::new("src/lib.rs");
5739        for root in [owner.path(), borrower_a.path(), borrower_b.path()] {
5740            let file = root.join(relative);
5741            fs::create_dir_all(file.parent().unwrap()).unwrap();
5742            fs::write(&file, "pub fn hash_guard() {}\n").unwrap();
5743        }
5744        let owner_file = owner.path().join(relative);
5745        let metadata = fs::metadata(&owner_file).unwrap();
5746        let mut index = SemanticIndex::new(owner.path().to_path_buf(), 2);
5747        index.entries.push(EmbeddingEntry {
5748            chunk: SemanticChunk {
5749                file: owner_file.clone(),
5750                name: "hash_guard".to_string(),
5751                qualified_name: None,
5752                kind: SymbolKind::Function,
5753                start_line: 0,
5754                end_line: 0,
5755                exported: true,
5756                embed_text: "hash guard".to_string(),
5757                snippet: "pub fn hash_guard() {}".to_string(),
5758            },
5759            norm: vector_norm(&[1.0, 0.0]),
5760            vector: vec![1.0, 0.0],
5761        });
5762        index.file_mtimes.insert(
5763            owner_file.clone(),
5764            metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH),
5765        );
5766        index.file_sizes.insert(owner_file.clone(), metadata.len());
5767        index
5768            .file_hashes
5769            .insert(owner_file, blake3::hash(b"pub fn hash_guard() {}\n"));
5770        index.set_fingerprint(SemanticIndexFingerprint {
5771            backend: "test".to_string(),
5772            model: "hash-guard".to_string(),
5773            base_url: FALLBACK_BACKEND.to_string(),
5774            dimension: 2,
5775            chunking_version: default_chunking_version(),
5776        });
5777        let project_key = format!(
5778            "hash-fallback-{}",
5779            blake3::hash(owner.path().as_os_str().as_encoded_bytes()).to_hex()
5780        );
5781        let dir = storage.path().join("semantic").join(&project_key);
5782        fs::create_dir_all(&dir).unwrap();
5783        fs::write(dir.join("semantic.bin"), index.to_bytes()).unwrap();
5784        let shared = SemanticIndex::read_from_disk_borrow_tolerant(
5785            storage.path(),
5786            &project_key,
5787            borrower_a.path(),
5788        )
5789        .unwrap();
5790        assert!(shared.shared_base.is_some());
5791
5792        let changed_vector = vec![0.0, 1.0];
5793        index.entries[0].norm = vector_norm(&changed_vector);
5794        index.entries[0].vector = changed_vector;
5795        fs::write(dir.join("semantic.bin"), index.to_bytes()).unwrap();
5796        let fallback = SemanticIndex::read_from_disk_borrow_tolerant(
5797            storage.path(),
5798            &project_key,
5799            borrower_b.path(),
5800        )
5801        .unwrap();
5802        assert!(
5803            fallback.shared_base.is_none(),
5804            "a different byte identity must not join the live shared generation"
5805        );
5806        drop(shared);
5807    }
5808
5809    #[test]
5810    fn borrow_only_root_skips_semantic_lock_and_persist() {
5811        let project = tempfile::tempdir().expect("project");
5812        let source = project.path().join("lib.rs");
5813        write_rust_file(&source, "borrow_only_symbol");
5814        let project_key = "shared-artifact-key".to_string();
5815        let storage = tempfile::tempdir().expect("storage");
5816        crate::root_cache::configure_artifact_access(project.path(), &project_key, true);
5817
5818        let _lock = SemanticIndexLock::acquire(storage.path(), &project_key, project.path())
5819            .expect("borrow-only lock downgrade");
5820        let cache_dir = storage.path().join("semantic").join(&project_key);
5821        assert!(!cache_dir.join("cache.lock").exists());
5822
5823        let index = build_test_index(project.path(), &[source]);
5824        index.write_to_disk(storage.path(), &project_key);
5825
5826        assert!(!cache_dir.join("semantic.bin").exists());
5827        assert!(!cache_dir.exists());
5828    }
5829
5830    #[test]
5831    fn refresh_stale_line_shift_reuses_all_chunks_and_retains_entries() {
5832        let temp = tempfile::tempdir().unwrap();
5833        let project_root = temp.path();
5834        let file = project_root.join("src/lib.rs");
5835        let original = "pub fn alpha() -> i32 {\n    1\n}\n\npub fn beta() -> i32 {\n    2\n}\n";
5836        write_source(&file, original);
5837
5838        let mut index = build_recorded_test_index(project_root, std::slice::from_ref(&file));
5839        let original_entry_count = index.entries.len();
5840        let original_alpha_vector = entry_by_name(&index, &file, "alpha").vector.clone();
5841
5842        write_source(&file, &format!("\n{original}"));
5843        force_stale(&mut index, &file);
5844
5845        let mut embedder = RecordingEmbedder::default();
5846        let mut embed = |texts: Vec<String>| embedder.embed(texts);
5847        let mut progress = |_done: usize, _total: usize| {};
5848        let summary = index
5849            .refresh_stale_files(
5850                project_root,
5851                std::slice::from_ref(&file),
5852                &mut embed,
5853                16,
5854                &mut progress,
5855            )
5856            .unwrap();
5857
5858        assert_eq!(summary.changed, 1);
5859        assert_eq!(embedder.total_embedded_texts(), 0);
5860        assert_eq!(index.entries.len(), original_entry_count);
5861        let shifted_alpha = entry_by_name(&index, &file, "alpha");
5862        assert_eq!(shifted_alpha.chunk.start_line, 1);
5863        assert_eq!(shifted_alpha.vector, original_alpha_vector);
5864    }
5865
5866    #[test]
5867    fn refresh_invalidated_line_shift_emits_full_replacement_delta_for_apply() {
5868        let temp = tempfile::tempdir().unwrap();
5869        let project_root = temp.path();
5870        let file = project_root.join("src/lib.rs");
5871        let original = "pub fn alpha() -> i32 {\n    1\n}\n\npub fn beta() -> i32 {\n    2\n}\n";
5872        write_source(&file, original);
5873
5874        let mut worker_index = build_recorded_test_index(project_root, std::slice::from_ref(&file));
5875        let mut serving_index = worker_index.clone();
5876        let original_entry_count = worker_index.entries.len();
5877
5878        write_source(&file, &format!("\n{original}"));
5879
5880        let mut embedder = RecordingEmbedder::default();
5881        let mut embed = |texts: Vec<String>| embedder.embed(texts);
5882        let mut progress = |_done: usize, _total: usize| {};
5883        let update = worker_index
5884            .refresh_invalidated_files(
5885                project_root,
5886                std::slice::from_ref(&file),
5887                &mut embed,
5888                16,
5889                100,
5890                &mut progress,
5891            )
5892            .unwrap();
5893
5894        assert_eq!(embedder.total_embedded_texts(), 0);
5895        assert_eq!(update.added_entries.len(), original_entry_count);
5896        assert_eq!(worker_index.entries.len(), original_entry_count);
5897
5898        serving_index.apply_refresh_update(
5899            update.added_entries,
5900            update.updated_metadata,
5901            &update.completed_paths,
5902        );
5903
5904        assert_eq!(serving_index.entries.len(), original_entry_count);
5905        assert_eq!(
5906            entries_for_file(&serving_index, &file).len(),
5907            original_entry_count
5908        );
5909        assert_eq!(
5910            entry_by_name(&serving_index, &file, "alpha")
5911                .chunk
5912                .start_line,
5913            1
5914        );
5915    }
5916
5917    #[test]
5918    fn refresh_invalidated_one_symbol_edit_embeds_only_changed_symbol() {
5919        let temp = tempfile::tempdir().unwrap();
5920        let project_root = temp.path();
5921        let file = project_root.join("src/lib.rs");
5922        write_source(
5923            &file,
5924            "pub fn alpha() -> i32 {\n    1\n}\n\npub fn beta() -> i32 {\n    2\n}\n",
5925        );
5926
5927        let mut index = build_recorded_test_index(project_root, std::slice::from_ref(&file));
5928        let original_entry_count = index.entries.len();
5929        let beta_vector = entry_by_name(&index, &file, "beta").vector.clone();
5930
5931        write_source(
5932            &file,
5933            "pub fn alpha() -> i32 {\n    10\n}\n\npub fn beta() -> i32 {\n    2\n}\n",
5934        );
5935
5936        let mut embedder = RecordingEmbedder::default();
5937        let mut embed = |texts: Vec<String>| embedder.embed(texts);
5938        let mut progress = |_done: usize, _total: usize| {};
5939        let update = index
5940            .refresh_invalidated_files(
5941                project_root,
5942                std::slice::from_ref(&file),
5943                &mut embed,
5944                16,
5945                100,
5946                &mut progress,
5947            )
5948            .unwrap();
5949
5950        assert_eq!(embedder.total_embedded_texts(), 1);
5951        assert!(embedder.embedded_texts()[0].contains("name:alpha"));
5952        assert_eq!(update.added_entries.len(), original_entry_count);
5953        assert_eq!(entry_by_name(&index, &file, "beta").vector, beta_vector);
5954    }
5955
5956    #[test]
5957    fn refresh_reuses_one_old_vector_for_two_byte_identical_symbols() {
5958        let temp = tempfile::tempdir().unwrap();
5959        let project_root = temp.path();
5960        let file = project_root.join("src/dupe.js");
5961        let one_duplicate = "function duplicate() {\n  return 1;\n}\n";
5962        write_source(&file, one_duplicate);
5963
5964        let mut index = build_recorded_test_index(project_root, std::slice::from_ref(&file));
5965        let original_vector = entry_by_name(&index, &file, "duplicate").vector.clone();
5966
5967        write_source(&file, &format!("{one_duplicate}\n{one_duplicate}"));
5968
5969        let mut embedder = RecordingEmbedder::default();
5970        let mut embed = |texts: Vec<String>| embedder.embed(texts);
5971        let mut progress = |_done: usize, _total: usize| {};
5972        index
5973            .refresh_invalidated_files(
5974                project_root,
5975                std::slice::from_ref(&file),
5976                &mut embed,
5977                16,
5978                100,
5979                &mut progress,
5980            )
5981            .unwrap();
5982
5983        let duplicate_entries = index
5984            .entries
5985            .iter()
5986            .filter(|entry| entry.chunk.file == file && entry.chunk.name == "duplicate")
5987            .collect::<Vec<_>>();
5988        assert_eq!(duplicate_entries.len(), 2);
5989        assert_eq!(embedder.total_embedded_texts(), 0);
5990        assert_eq!(duplicate_entries[0].vector, original_vector);
5991        assert_eq!(duplicate_entries[1].vector, original_vector);
5992    }
5993
5994    #[test]
5995    fn file_summary_reuses_on_body_edit_and_misses_on_leading_doc_edit() {
5996        let temp = tempfile::tempdir().unwrap();
5997        let project_root = temp.path();
5998        let file = project_root.join("src/lib.rs");
5999        write_source(
6000            &file,
6001            "//! module docs v1\n\npub fn alpha() -> i32 {\n    1\n}\n",
6002        );
6003
6004        let mut index = build_recorded_test_index(project_root, std::slice::from_ref(&file));
6005        let summary_before = file_summary_entry(&index, &file).vector.clone();
6006
6007        write_source(
6008            &file,
6009            "//! module docs v1\n\npub fn alpha() -> i32 {\n    2\n}\n",
6010        );
6011        let mut body_embedder = RecordingEmbedder::default();
6012        let mut body_embed = |texts: Vec<String>| body_embedder.embed(texts);
6013        let mut progress = |_done: usize, _total: usize| {};
6014        index
6015            .refresh_invalidated_files(
6016                project_root,
6017                std::slice::from_ref(&file),
6018                &mut body_embed,
6019                16,
6020                100,
6021                &mut progress,
6022            )
6023            .unwrap();
6024        assert_eq!(body_embedder.total_embedded_texts(), 1);
6025        assert!(body_embedder.embedded_texts()[0].contains("name:alpha"));
6026        assert_eq!(file_summary_entry(&index, &file).vector, summary_before);
6027
6028        write_source(
6029            &file,
6030            "//! module docs v2\n\npub fn alpha() -> i32 {\n    2\n}\n",
6031        );
6032        let mut doc_embedder = RecordingEmbedder::default();
6033        let mut doc_embed = |texts: Vec<String>| doc_embedder.embed(texts);
6034        index
6035            .refresh_invalidated_files(
6036                project_root,
6037                std::slice::from_ref(&file),
6038                &mut doc_embed,
6039                16,
6040                100,
6041                &mut progress,
6042            )
6043            .unwrap();
6044
6045        assert_eq!(doc_embedder.total_embedded_texts(), 1);
6046        assert!(doc_embedder.embedded_texts()[0].contains("kind:file-summary"));
6047        assert_ne!(file_summary_entry(&index, &file).vector, summary_before);
6048    }
6049
6050    #[test]
6051    fn refresh_invalidated_deleted_file_drops_entries_without_embedding() {
6052        let temp = tempfile::tempdir().unwrap();
6053        let project_root = temp.path();
6054        let file = project_root.join("src/lib.rs");
6055        write_source(&file, "pub fn alpha() -> i32 {\n    1\n}\n");
6056
6057        let mut worker_index = build_recorded_test_index(project_root, std::slice::from_ref(&file));
6058        let mut serving_index = worker_index.clone();
6059        fs::remove_file(&file).unwrap();
6060
6061        let mut embedder = RecordingEmbedder::default();
6062        let mut embed = |texts: Vec<String>| embedder.embed(texts);
6063        let mut progress = |_done: usize, _total: usize| {};
6064        let update = worker_index
6065            .refresh_invalidated_files(
6066                project_root,
6067                std::slice::from_ref(&file),
6068                &mut embed,
6069                16,
6070                100,
6071                &mut progress,
6072            )
6073            .unwrap();
6074
6075        assert_eq!(update.summary.deleted, 1);
6076        assert_eq!(embedder.total_embedded_texts(), 0);
6077        assert!(worker_index.entries.is_empty());
6078
6079        serving_index.apply_refresh_update(
6080            update.added_entries,
6081            update.updated_metadata,
6082            &update.completed_paths,
6083        );
6084        assert!(serving_index.entries.is_empty());
6085    }
6086
6087    #[test]
6088    fn watcher_collect_failure_does_not_resurrect_stale_entries() {
6089        let temp = tempfile::tempdir().unwrap();
6090        let project_root = temp.path();
6091        let file = project_root.join("src/lib.rs");
6092        write_source(&file, "pub fn alpha() -> i32 {\n    1\n}\n");
6093
6094        let mut worker_index = build_recorded_test_index(project_root, std::slice::from_ref(&file));
6095        let mut serving_index = worker_index.clone();
6096        fs::write(&file, [0xff, 0xfe, 0xfd]).unwrap();
6097
6098        let mut embedder = RecordingEmbedder::default();
6099        let mut embed = |texts: Vec<String>| embedder.embed(texts);
6100        let mut progress = |_done: usize, _total: usize| {};
6101        let update = worker_index
6102            .refresh_invalidated_files(
6103                project_root,
6104                std::slice::from_ref(&file),
6105                &mut embed,
6106                16,
6107                100,
6108                &mut progress,
6109            )
6110            .unwrap();
6111
6112        assert_eq!(embedder.total_embedded_texts(), 0);
6113        assert!(update.added_entries.is_empty());
6114        assert!(worker_index.entries.is_empty());
6115        assert!(!worker_index.file_mtimes.contains_key(&file));
6116
6117        serving_index.apply_refresh_update(
6118            update.added_entries,
6119            update.updated_metadata,
6120            &update.completed_paths,
6121        );
6122        assert!(serving_index.entries.is_empty());
6123        assert!(!serving_index.file_mtimes.contains_key(&file));
6124    }
6125
6126    #[test]
6127    fn refresh_invalidated_cap_deferral_remains_file_count_based() {
6128        let temp = tempfile::tempdir().unwrap();
6129        let project_root = temp.path();
6130        let indexed = project_root.join("src/a.rs");
6131        let deferred = project_root.join("src/b.rs");
6132        write_source(&indexed, "pub fn alpha() -> i32 {\n    1\n}\n");
6133        write_source(&deferred, "pub fn beta() -> i32 {\n    2\n}\n");
6134
6135        let mut index = build_recorded_test_index(project_root, std::slice::from_ref(&indexed));
6136        let mut embedder = RecordingEmbedder::default();
6137        let mut embed = |texts: Vec<String>| embedder.embed(texts);
6138        let mut progress = |_done: usize, _total: usize| {};
6139        let update = index
6140            .refresh_invalidated_files(
6141                project_root,
6142                std::slice::from_ref(&deferred),
6143                &mut embed,
6144                16,
6145                1,
6146                &mut progress,
6147            )
6148            .unwrap();
6149
6150        assert_eq!(update.summary.total_processed, 1);
6151        assert_eq!(update.summary.added, 0);
6152        assert_eq!(embedder.total_embedded_texts(), 0);
6153        assert_eq!(index.indexed_file_count(), 1);
6154        assert!(index.deferred_files.contains(&deferred));
6155        assert!(entries_for_file(&index, &deferred).is_empty());
6156    }
6157
6158    #[test]
6159    fn semantic_cache_serialization_skips_paths_outside_project_root() {
6160        let dir = tempfile::tempdir().expect("create temp dir");
6161        let project = fs::canonicalize(dir.path()).expect("canonical project");
6162        let outside = project.join("..").join("outside.rs");
6163        let mut index = SemanticIndex::new(project.clone(), 3);
6164        index
6165            .file_mtimes
6166            .insert(outside.clone(), SystemTime::UNIX_EPOCH);
6167        index.file_sizes.insert(outside.clone(), 1);
6168        index
6169            .file_hashes
6170            .insert(outside.clone(), cache_freshness::zero_hash());
6171        index.entries.push(EmbeddingEntry {
6172            chunk: SemanticChunk {
6173                file: outside,
6174                name: "outside".to_string(),
6175                qualified_name: None,
6176                kind: SymbolKind::Function,
6177                start_line: 0,
6178                end_line: 0,
6179                exported: false,
6180                embed_text: "outside".to_string(),
6181                snippet: "outside".to_string(),
6182            },
6183            norm: vector_norm(&[1.0, 0.0, 0.0]),
6184            vector: vec![1.0, 0.0, 0.0],
6185        });
6186
6187        let bytes = index.to_bytes();
6188        let loaded = SemanticIndex::from_bytes(&bytes, &project).expect("load serialized index");
6189        assert_eq!(loaded.entries.len(), 0);
6190        assert!(loaded.file_mtimes.is_empty());
6191    }
6192
6193    #[test]
6194    fn semantic_search_bounded_top_k_matches_reference_full_sort() {
6195        let project_root = test_project_root();
6196        let file = project_root.join("src/lib.rs");
6197        let mut index = SemanticIndex::new(project_root, 2);
6198        let entries = [
6199            ("alpha", vec![2.0, 0.0], false),
6200            ("beta", vec![0.0, 3.0], false),
6201            ("gamma", vec![4.0, 0.0], false),
6202            ("delta", vec![1.0, 1.0], true),
6203            ("epsilon", vec![-5.0, 0.0], false),
6204        ];
6205        for (line, (name, vector, exported)) in entries.into_iter().enumerate() {
6206            index.entries.push(EmbeddingEntry {
6207                chunk: SemanticChunk {
6208                    file: file.clone(),
6209                    name: name.to_string(),
6210                    qualified_name: None,
6211                    kind: SymbolKind::Function,
6212                    start_line: line as u32 + 1,
6213                    end_line: line as u32 + 1,
6214                    exported,
6215                    embed_text: name.to_string(),
6216                    snippet: format!("fn {name}() {{}}"),
6217                },
6218                norm: vector_norm(&vector),
6219                vector,
6220            });
6221        }
6222
6223        let query = vec![2.0, 0.0];
6224        let top_k = 4;
6225        let mut reference: Vec<(f32, usize)> = index
6226            .entries
6227            .iter()
6228            .enumerate()
6229            .map(|(idx, entry)| {
6230                // Recompute both norms for every entry as the reference
6231                // implementation, so cached norms cannot change ranking or scores.
6232                let mut dot = 0.0f32;
6233                let mut query_squared_norm = 0.0f32;
6234                let mut entry_squared_norm = 0.0f32;
6235                for i in 0..query.len() {
6236                    dot += query[i] * entry.vector[i];
6237                    query_squared_norm += query[i] * query[i];
6238                    entry_squared_norm += entry.vector[i] * entry.vector[i];
6239                }
6240                let denom = query_squared_norm.sqrt() * entry_squared_norm.sqrt();
6241                let mut score = if denom == 0.0 { 0.0 } else { dot / denom };
6242                if entry.chunk.exported {
6243                    score *= 1.1;
6244                }
6245                (score, idx)
6246            })
6247            .collect();
6248        reference.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
6249        let expected: Vec<(String, f32)> = reference
6250            .into_iter()
6251            .take(top_k)
6252            .map(|(score, idx)| (index.entries[idx].chunk.name.clone(), score))
6253            .collect();
6254
6255        let actual: Vec<(String, f32)> = index
6256            .search(&query, top_k)
6257            .into_iter()
6258            .map(|result| (result.name, result.score))
6259            .collect();
6260
6261        assert_eq!(
6262            actual.iter().map(|(name, _)| name).collect::<Vec<_>>(),
6263            expected.iter().map(|(name, _)| name).collect::<Vec<_>>()
6264        );
6265        for ((_, actual_score), (_, expected_score)) in actual.iter().zip(expected.iter()) {
6266            assert!((actual_score - expected_score).abs() < 1e-6);
6267        }
6268        assert_eq!(actual[0].0, "alpha");
6269        assert_eq!(actual[1].0, "gamma", "equal scores keep insertion order");
6270        assert!(index.search(&query, 0).is_empty());
6271    }
6272
6273    #[test]
6274    fn test_cosine_similarity_identical() {
6275        let a = vec![1.0, 0.0, 0.0];
6276        let b = vec![1.0, 0.0, 0.0];
6277        assert!((cosine_similarity(&a, &b) - 1.0).abs() < 0.001);
6278    }
6279
6280    #[test]
6281    fn test_cosine_similarity_orthogonal() {
6282        let a = vec![1.0, 0.0, 0.0];
6283        let b = vec![0.0, 1.0, 0.0];
6284        assert!(cosine_similarity(&a, &b).abs() < 0.001);
6285    }
6286
6287    #[test]
6288    fn test_cosine_similarity_opposite() {
6289        let a = vec![1.0, 0.0, 0.0];
6290        let b = vec![-1.0, 0.0, 0.0];
6291        assert!((cosine_similarity(&a, &b) + 1.0).abs() < 0.001);
6292    }
6293
6294    #[test]
6295    fn test_serialization_roundtrip() {
6296        let project_root = test_project_root();
6297        let file = project_root.join("src/main.rs");
6298        let mut index = SemanticIndex::new(project_root.clone(), DEFAULT_DIMENSION);
6299        index.entries.push(EmbeddingEntry {
6300            chunk: SemanticChunk {
6301                file: file.clone(),
6302                name: "handle_request".to_string(),
6303                qualified_name: None,
6304                kind: SymbolKind::Function,
6305                start_line: 10,
6306                end_line: 25,
6307                exported: true,
6308                embed_text: "file:src/main.rs kind:function name:handle_request".to_string(),
6309                snippet: "fn handle_request() {\n  // ...\n}".to_string(),
6310            },
6311            norm: vector_norm(&[0.1, 0.2, 0.3, 0.4]),
6312            vector: vec![0.1, 0.2, 0.3, 0.4],
6313        });
6314        index.dimension = 4;
6315        index
6316            .file_mtimes
6317            .insert(file.clone(), SystemTime::UNIX_EPOCH);
6318        index.file_sizes.insert(file, 0);
6319        index.set_fingerprint(SemanticIndexFingerprint {
6320            backend: "fastembed".to_string(),
6321            model: "all-MiniLM-L6-v2".to_string(),
6322            base_url: FALLBACK_BACKEND.to_string(),
6323            dimension: 4,
6324            chunking_version: default_chunking_version(),
6325        });
6326
6327        let bytes = index.to_bytes();
6328        let restored = SemanticIndex::from_bytes(&bytes, &project_root).unwrap();
6329
6330        assert_eq!(restored.entries.len(), 1);
6331        assert_eq!(restored.entries[0].chunk.name, "handle_request");
6332        assert_eq!(restored.entries[0].vector, vec![0.1, 0.2, 0.3, 0.4]);
6333        assert_eq!(
6334            restored.entries[0].norm,
6335            vector_norm(&restored.entries[0].vector)
6336        );
6337        assert_eq!(restored.dimension, 4);
6338        assert_eq!(restored.backend_label(), Some("fastembed"));
6339        assert_eq!(restored.model_label(), Some("all-MiniLM-L6-v2"));
6340    }
6341
6342    #[test]
6343    fn semantic_cache_v6_loads_and_v7_round_trips_qualified_names() {
6344        let storage = tempfile::tempdir().expect("create storage dir");
6345        let project = storage.path().join("project");
6346        fs::create_dir_all(project.join("src")).expect("create project src");
6347        let file = project.join("src/lib.rs");
6348        fs::write(&file, "pub fn alpha() {}\npub fn beta() {}\n").expect("write source");
6349        let project_root = fs::canonicalize(&project).expect("canonical project");
6350        let file = fs::canonicalize(&file).expect("canonical file");
6351
6352        let mut index = SemanticIndex::new(project_root.clone(), 3);
6353        let mtime = SystemTime::UNIX_EPOCH + Duration::new(123, 456);
6354        index.file_mtimes.insert(file.clone(), mtime);
6355        index.file_sizes.insert(file.clone(), 42);
6356        index
6357            .file_hashes
6358            .insert(file.clone(), cache_freshness::zero_hash());
6359        index.entries.push(EmbeddingEntry {
6360            chunk: SemanticChunk {
6361                file: file.clone(),
6362                name: "alpha".to_string(),
6363                qualified_name: Some("Service.alpha".to_string()),
6364                kind: SymbolKind::Function,
6365                start_line: 0,
6366                end_line: 0,
6367                exported: true,
6368                embed_text: "file:src/lib.rs kind:function name:alpha".to_string(),
6369                snippet: "pub fn alpha() {}".to_string(),
6370            },
6371            norm: vector_norm(&[0.1, 0.2, 0.3]),
6372            vector: vec![0.1, 0.2, 0.3],
6373        });
6374        index.entries.push(EmbeddingEntry {
6375            chunk: SemanticChunk {
6376                file: file.clone(),
6377                name: "beta".to_string(),
6378                qualified_name: Some("Service.beta".to_string()),
6379                kind: SymbolKind::Function,
6380                start_line: 1,
6381                end_line: 1,
6382                exported: true,
6383                embed_text: "file:src/lib.rs kind:function name:beta".to_string(),
6384                snippet: "pub fn beta() {}".to_string(),
6385            },
6386            norm: vector_norm(&[0.4, 0.5, 0.6]),
6387            vector: vec![0.4, 0.5, 0.6],
6388        });
6389        let fingerprint = SemanticIndexFingerprint {
6390            backend: "fastembed".to_string(),
6391            model: "all-MiniLM-L6-v2".to_string(),
6392            base_url: FALLBACK_BACKEND.to_string(),
6393            dimension: 3,
6394            chunking_version: default_chunking_version(),
6395        };
6396        let fingerprint_before = fingerprint.as_string();
6397        index.set_fingerprint(fingerprint.clone());
6398
6399        let legacy_bytes = legacy_semantic_index_bytes(&index);
6400        assert_eq!(legacy_bytes[0], SEMANTIC_INDEX_VERSION_V6);
6401        let legacy_dir = storage.path().join("semantic/legacy-proj");
6402        fs::create_dir_all(&legacy_dir).expect("create legacy semantic dir");
6403        let legacy_path = legacy_dir.join("semantic.bin");
6404        fs::write(&legacy_path, &legacy_bytes).expect("write legacy semantic.bin");
6405        let legacy_loaded = SemanticIndex::read_from_disk(
6406            storage.path(),
6407            "legacy-proj",
6408            &project_root,
6409            false,
6410            Some(&fingerprint_before),
6411        )
6412        .expect("load v6 semantic index");
6413        assert!(
6414            legacy_path.exists(),
6415            "compatible V6 cache must not be deleted"
6416        );
6417        assert!(legacy_loaded
6418            .entries
6419            .iter()
6420            .all(|entry| entry.chunk.qualified_name.is_none()));
6421        assert_eq!(
6422            legacy_loaded.fingerprint().unwrap().as_string(),
6423            fingerprint_before
6424        );
6425
6426        let v7_bytes = index.to_bytes();
6427        assert_eq!(v7_bytes[0], SEMANTIC_INDEX_VERSION_V7);
6428        assert_ne!(v7_bytes, legacy_bytes);
6429        let restored = SemanticIndex::from_bytes(&v7_bytes, &project_root).unwrap();
6430        assert_eq!(
6431            restored.entries[0].chunk.qualified_name.as_deref(),
6432            Some("Service.alpha")
6433        );
6434        assert_eq!(
6435            restored.entries[1].chunk.qualified_name.as_deref(),
6436            Some("Service.beta")
6437        );
6438        assert_eq!(
6439            restored.fingerprint().unwrap().as_string(),
6440            fingerprint_before
6441        );
6442
6443        index.write_to_disk(storage.path(), "proj");
6444        let data_path = storage.path().join("semantic/proj/semantic.bin");
6445        let persisted = fs::read(&data_path).expect("read semantic.bin");
6446        assert_eq!(persisted[0], SEMANTIC_INDEX_VERSION_V7);
6447
6448        let loaded = SemanticIndex::read_from_disk(
6449            storage.path(),
6450            "proj",
6451            &project_root,
6452            false,
6453            Some(&fingerprint_before),
6454        )
6455        .expect("load semantic index");
6456        assert_eq!(loaded.entries.len(), index.entries.len());
6457        assert_eq!(loaded.dimension, index.dimension);
6458        assert_eq!(
6459            loaded.fingerprint().unwrap().as_string(),
6460            fingerprint_before
6461        );
6462        assert_eq!(loaded.file_mtimes.get(&file), Some(&mtime));
6463        assert_eq!(loaded.file_sizes.get(&file), Some(&42));
6464        assert_eq!(
6465            loaded.file_hashes.get(&file),
6466            Some(&cache_freshness::zero_hash())
6467        );
6468        for (actual, expected) in loaded.entries.iter().zip(index.entries.iter()) {
6469            assert_eq!(actual.chunk.file, expected.chunk.file);
6470            assert_eq!(actual.chunk.name, expected.chunk.name);
6471            assert_eq!(actual.chunk.qualified_name, expected.chunk.qualified_name);
6472            assert_eq!(actual.chunk.kind, expected.chunk.kind);
6473            assert_eq!(actual.chunk.start_line, expected.chunk.start_line);
6474            assert_eq!(actual.chunk.end_line, expected.chunk.end_line);
6475            assert_eq!(actual.chunk.exported, expected.chunk.exported);
6476            assert_eq!(actual.chunk.embed_text, expected.chunk.embed_text);
6477            assert_eq!(actual.chunk.snippet, expected.chunk.snippet);
6478            assert_eq!(actual.vector, expected.vector);
6479        }
6480        assert_eq!(loaded.to_bytes(), persisted);
6481        assert_eq!(fingerprint.as_string(), fingerprint_before);
6482    }
6483
6484    #[test]
6485    fn symbol_kind_serialization_roundtrip_includes_file_summary_variant() {
6486        let cases = [
6487            (SymbolKind::Function, 0),
6488            (SymbolKind::Class, 1),
6489            (SymbolKind::Method, 2),
6490            (SymbolKind::Struct, 3),
6491            (SymbolKind::Interface, 4),
6492            (SymbolKind::Enum, 5),
6493            (SymbolKind::TypeAlias, 6),
6494            (SymbolKind::Variable, 7),
6495            (SymbolKind::Heading, 8),
6496            (SymbolKind::FileSummary, 9),
6497        ];
6498
6499        for (kind, encoded) in cases {
6500            assert_eq!(symbol_kind_to_u8(&kind), encoded);
6501            assert_eq!(u8_to_symbol_kind(encoded), kind);
6502        }
6503    }
6504
6505    #[test]
6506    fn test_search_top_k() {
6507        let mut index = SemanticIndex::new(test_project_root(), DEFAULT_DIMENSION);
6508        index.dimension = 3;
6509
6510        // Add entries with known vectors
6511        for (i, name) in ["auth", "database", "handler"].iter().enumerate() {
6512            let mut vec = vec![0.0f32; 3];
6513            vec[i] = 1.0; // orthogonal vectors
6514            index.entries.push(EmbeddingEntry {
6515                chunk: SemanticChunk {
6516                    file: PathBuf::from("/src/lib.rs"),
6517                    name: name.to_string(),
6518                    qualified_name: None,
6519                    kind: SymbolKind::Function,
6520                    start_line: (i * 10 + 1) as u32,
6521                    end_line: (i * 10 + 5) as u32,
6522                    exported: true,
6523                    embed_text: format!("kind:function name:{}", name),
6524                    snippet: format!("fn {}() {{}}", name),
6525                },
6526                norm: vector_norm(&vec),
6527                vector: vec,
6528            });
6529        }
6530
6531        // Query aligned with "auth" (index 0)
6532        let query = vec![0.9, 0.1, 0.0];
6533        let results = index.search(&query, 2);
6534
6535        assert_eq!(results.len(), 2);
6536        assert_eq!(results[0].name, "auth"); // highest score
6537        assert!(results[0].score > results[1].score);
6538    }
6539
6540    #[test]
6541    fn test_empty_index_search() {
6542        let index = SemanticIndex::new(test_project_root(), DEFAULT_DIMENSION);
6543        let results = index.search(&[0.1, 0.2, 0.3], 10);
6544        assert!(results.is_empty());
6545    }
6546
6547    #[test]
6548    fn single_line_symbol_builds_non_empty_snippet() {
6549        let symbol = Symbol {
6550            name: "answer".to_string(),
6551            kind: SymbolKind::Variable,
6552            range: crate::symbols::Range {
6553                start_line: 0,
6554                start_col: 0,
6555                end_line: 0,
6556                end_col: 24,
6557            },
6558            signature: Some("const answer = 42".to_string()),
6559            scope_chain: Vec::new(),
6560            exported: true,
6561            parent: None,
6562        };
6563        let source = "export const answer = 42;\n";
6564
6565        let snippet = build_snippet(&symbol, source);
6566
6567        assert_eq!(snippet, "export const answer = 42;");
6568    }
6569
6570    #[test]
6571    fn optimized_file_chunk_collection_matches_file_parser_path() {
6572        let project_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
6573        let file = project_root.join("src/semantic_index.rs");
6574        let source = std::fs::read_to_string(&file).unwrap();
6575
6576        let mut legacy_parser = FileParser::new();
6577        let legacy_symbols = legacy_parser.extract_symbols(&file).unwrap();
6578        let legacy_chunks = symbols_to_chunks(&file, &legacy_symbols, &source, &project_root);
6579
6580        let optimized_chunks = collect_file_chunks(&project_root, &file).unwrap();
6581
6582        assert_eq!(
6583            chunk_fingerprint(&optimized_chunks),
6584            chunk_fingerprint(&legacy_chunks)
6585        );
6586    }
6587
6588    #[test]
6589    fn collect_file_chunks_indexes_java_symbols() {
6590        let dir = tempfile::tempdir().unwrap();
6591        let file = dir.path().join("Greeter.java");
6592        std::fs::write(
6593            &file,
6594            r#"package example;
6595
6596public class Greeter {
6597    public String greet(String name) {
6598        return "Hello, " + name;
6599    }
6600}
6601"#,
6602        )
6603        .unwrap();
6604
6605        let chunks = collect_file_chunks(dir.path(), &file).unwrap();
6606
6607        assert!(
6608            !chunks.is_empty(),
6609            "Java file should produce semantic chunks"
6610        );
6611        assert!(
6612            chunks
6613                .iter()
6614                .any(|chunk| chunk.name == "Greeter" && chunk.kind == SymbolKind::Class),
6615            "Java class symbol should be chunked: {chunks:?}"
6616        );
6617        assert!(
6618            chunks
6619                .iter()
6620                .any(|chunk| chunk.name == "greet" && chunk.kind == SymbolKind::Method),
6621            "Java method symbol should be chunked: {chunks:?}"
6622        );
6623    }
6624
6625    fn chunk_fingerprint(
6626        chunks: &[SemanticChunk],
6627    ) -> Vec<(String, SymbolKind, u32, u32, bool, String, String)> {
6628        chunks
6629            .iter()
6630            .map(|chunk| {
6631                (
6632                    chunk.name.clone(),
6633                    chunk.kind.clone(),
6634                    chunk.start_line,
6635                    chunk.end_line,
6636                    chunk.exported,
6637                    chunk.embed_text.clone(),
6638                    chunk.snippet.clone(),
6639                )
6640            })
6641            .collect()
6642    }
6643
6644    #[test]
6645    fn collect_file_chunks_skips_oversized_file() {
6646        let dir = tempfile::tempdir().unwrap();
6647        let big = dir.path().join("huge.ts");
6648        // Just over the cap: a valid TS file that would otherwise yield chunks.
6649        let filler = "export const x = 1;\n"
6650            .repeat(((MAX_SEMANTIC_FILE_BYTES as usize) / "export const x = 1;\n".len()) + 16);
6651        std::fs::write(&big, &filler).unwrap();
6652        assert!(big.metadata().unwrap().len() > MAX_SEMANTIC_FILE_BYTES);
6653
6654        // Oversized → tracked with zero chunks, NOT an error (so the caller keeps
6655        // the file in metadata and freshness skips re-reading it).
6656        let chunks = collect_file_chunks(dir.path(), &big).unwrap();
6657        assert!(chunks.is_empty(), "oversized file must yield no chunks");
6658
6659        // A small file of the same language still produces chunks.
6660        let small = dir.path().join("small.ts");
6661        std::fs::write(&small, "export function foo() { return 1; }\n").unwrap();
6662        let small_chunks = collect_file_chunks(dir.path(), &small).unwrap();
6663        assert!(!small_chunks.is_empty(), "small file should still chunk");
6664    }
6665
6666    #[test]
6667    fn rejects_oversized_dimension_during_deserialization() {
6668        let mut bytes = Vec::new();
6669        bytes.push(1u8);
6670        bytes.extend_from_slice(&((MAX_DIMENSION as u32) + 1).to_le_bytes());
6671        bytes.extend_from_slice(&0u32.to_le_bytes());
6672        bytes.extend_from_slice(&0u32.to_le_bytes());
6673
6674        assert!(SemanticIndex::from_bytes(&bytes, &test_project_root()).is_err());
6675    }
6676
6677    #[test]
6678    fn rejects_oversized_entry_count_during_deserialization() {
6679        let mut bytes = Vec::new();
6680        bytes.push(1u8);
6681        bytes.extend_from_slice(&(DEFAULT_DIMENSION as u32).to_le_bytes());
6682        bytes.extend_from_slice(&((MAX_ENTRIES as u32) + 1).to_le_bytes());
6683        bytes.extend_from_slice(&0u32.to_le_bytes());
6684
6685        assert!(SemanticIndex::from_bytes(&bytes, &test_project_root()).is_err());
6686    }
6687
6688    fn add_invalidation_fixture_entry(index: &mut SemanticIndex, file: PathBuf, ordinal: u64) {
6689        index.entries.push(EmbeddingEntry::new(
6690            SemanticChunk {
6691                file: file.clone(),
6692                name: format!("symbol_{ordinal}"),
6693                qualified_name: None,
6694                kind: SymbolKind::Function,
6695                start_line: ordinal as u32,
6696                end_line: ordinal as u32 + 1,
6697                exported: false,
6698                embed_text: format!("symbol {ordinal}"),
6699                snippet: format!("fn symbol_{ordinal}() {{}}"),
6700            },
6701            vec![ordinal as f32 + 1.0, 1.0],
6702        ));
6703        let mtime = SystemTime::UNIX_EPOCH + Duration::from_secs(ordinal + 1);
6704        index.file_mtimes.insert(file.clone(), mtime);
6705        index.file_sizes.insert(file.clone(), ordinal + 10);
6706        index
6707            .file_hashes
6708            .insert(file, blake3::hash(&ordinal.to_le_bytes()));
6709    }
6710
6711    #[test]
6712    fn batch_invalidation_matches_sequential_calls_with_one_retain_pass() {
6713        let temp = tempfile::tempdir().unwrap();
6714        let project_root = temp.path().canonicalize().unwrap();
6715        let mut source = SemanticIndex::new(project_root.clone(), 2);
6716        let files = (0..8)
6717            .map(|ordinal| {
6718                let file = project_root.join(format!("file_{ordinal}.rs"));
6719                fs::write(&file, format!("fn symbol_{ordinal}() {{}}\n")).unwrap();
6720                add_invalidation_fixture_entry(&mut source, file.clone(), ordinal);
6721                file
6722            })
6723            .collect::<Vec<_>>();
6724        let invalidated = vec![files[1].clone(), files[3].clone(), files[6].clone()];
6725
6726        let shared = Arc::new(source.into_shared_base().unwrap());
6727        let mut shared_batched =
6728            SemanticIndex::from_shared_base(project_root.clone(), Arc::clone(&shared));
6729        shared_batched.invalidate_files(&invalidated);
6730        let mut source = SemanticIndex::from_shared_base(project_root, shared);
6731        source.materialize_shared_base();
6732        let mut sequential = source.clone();
6733        let mut batched = source;
6734        for file in &invalidated {
6735            sequential.invalidate_file(file);
6736        }
6737        batched.invalidate_files(&invalidated);
6738
6739        assert!(sequential.shared_base.is_none());
6740        assert!(batched.shared_base.is_none());
6741        assert!(shared_batched.shared_base.is_none());
6742        assert_eq!(batched.to_bytes(), sequential.to_bytes());
6743        assert_eq!(shared_batched.file_mtimes, batched.file_mtimes);
6744        assert_eq!(shared_batched.file_sizes, batched.file_sizes);
6745        assert_eq!(shared_batched.file_hashes, batched.file_hashes);
6746        assert_eq!(
6747            format!("{:?}", shared_batched.entries),
6748            format!("{:?}", batched.entries)
6749        );
6750        assert_eq!(
6751            sequential.removal_retain_passes_for_test(),
6752            invalidated.len()
6753        );
6754        assert_eq!(batched.removal_retain_passes_for_test(), 1);
6755        assert_eq!(shared_batched.removal_retain_passes_for_test(), 1);
6756    }
6757
6758    #[cfg(unix)]
6759    #[test]
6760    fn batch_invalidation_removes_raw_and_canonical_alias_metadata() {
6761        use std::os::unix::fs::symlink;
6762
6763        let temp = tempfile::tempdir().unwrap();
6764        let project_root = temp.path().canonicalize().unwrap();
6765        let real_dir = project_root.join("real");
6766        let alias_dir = project_root.join("alias");
6767        fs::create_dir(&real_dir).unwrap();
6768        symlink(&real_dir, &alias_dir).unwrap();
6769        let real_file = real_dir.join("lib.rs");
6770        let alias_file = alias_dir.join("lib.rs");
6771        let untouched = project_root.join("untouched.rs");
6772        fs::write(&real_file, "fn aliased() {}\n").unwrap();
6773        fs::write(&untouched, "fn untouched() {}\n").unwrap();
6774        assert_eq!(fs::canonicalize(&alias_file).unwrap(), real_file);
6775
6776        let mut index = SemanticIndex::new(project_root, 2);
6777        add_invalidation_fixture_entry(&mut index, alias_file.clone(), 1);
6778        add_invalidation_fixture_entry(&mut index, real_file.clone(), 2);
6779        add_invalidation_fixture_entry(&mut index, untouched.clone(), 3);
6780        let mut sequential = index.clone();
6781        sequential.invalidate_file(&alias_file);
6782        index.invalidate_files(std::slice::from_ref(&alias_file));
6783
6784        assert_eq!(index.to_bytes(), sequential.to_bytes());
6785        assert!(index
6786            .entries
6787            .iter()
6788            .all(|entry| entry.chunk.file != alias_file && entry.chunk.file != real_file));
6789        assert!(!index.file_mtimes.contains_key(&alias_file));
6790        assert!(!index.file_mtimes.contains_key(&real_file));
6791        assert!(index.file_mtimes.contains_key(&untouched));
6792        assert!(!index.file_sizes.contains_key(&alias_file));
6793        assert!(!index.file_sizes.contains_key(&real_file));
6794        assert!(index.file_sizes.contains_key(&untouched));
6795        assert!(!index.file_hashes.contains_key(&alias_file));
6796        assert!(!index.file_hashes.contains_key(&real_file));
6797        assert!(index.file_hashes.contains_key(&untouched));
6798        assert_eq!(index.removal_retain_passes_for_test(), 1);
6799    }
6800
6801    #[test]
6802    fn invalidate_file_removes_entries_and_mtime() {
6803        let target = PathBuf::from("/src/main.rs");
6804        let mut index = SemanticIndex::new(test_project_root(), DEFAULT_DIMENSION);
6805        index.entries.push(EmbeddingEntry {
6806            chunk: SemanticChunk {
6807                file: target.clone(),
6808                name: "main".to_string(),
6809                qualified_name: None,
6810                kind: SymbolKind::Function,
6811                start_line: 0,
6812                end_line: 1,
6813                exported: false,
6814                embed_text: "main".to_string(),
6815                snippet: "fn main() {}".to_string(),
6816            },
6817            norm: vector_norm(&[1.0; DEFAULT_DIMENSION]),
6818            vector: vec![1.0; DEFAULT_DIMENSION],
6819        });
6820        index
6821            .file_mtimes
6822            .insert(target.clone(), SystemTime::UNIX_EPOCH);
6823        index.file_sizes.insert(target.clone(), 0);
6824
6825        index.invalidate_file(&target);
6826
6827        assert!(index.entries.is_empty());
6828        assert!(!index.file_mtimes.contains_key(&target));
6829        assert!(!index.file_sizes.contains_key(&target));
6830    }
6831
6832    #[test]
6833    fn refresh_missing_changed_file_is_purged_after_collect() {
6834        let temp = tempfile::tempdir().unwrap();
6835        let project_root = temp.path();
6836        let file = project_root.join("src/lib.rs");
6837        fs::create_dir_all(file.parent().unwrap()).unwrap();
6838        write_rust_file(&file, "vanished_symbol");
6839
6840        let mut index = build_test_index(project_root, std::slice::from_ref(&file));
6841        let original_size = *index.file_sizes.get(&file).unwrap();
6842        set_file_metadata(&mut index, &file, SystemTime::UNIX_EPOCH, original_size + 1);
6843        fs::remove_file(&file).unwrap();
6844
6845        let mut embed = test_vector_for_texts;
6846        let mut progress = |_done: usize, _total: usize| {};
6847        let summary = index
6848            .refresh_stale_files(
6849                project_root,
6850                std::slice::from_ref(&file),
6851                &mut embed,
6852                8,
6853                &mut progress,
6854            )
6855            .unwrap();
6856
6857        assert_eq!(summary.changed, 0);
6858        assert_eq!(summary.added, 0);
6859        assert_eq!(summary.deleted, 1);
6860        assert!(index.entries.is_empty());
6861        assert!(!index.file_mtimes.contains_key(&file));
6862        assert!(!index.file_sizes.contains_key(&file));
6863        assert!(!index.file_hashes.contains_key(&file));
6864    }
6865
6866    #[test]
6867    fn refresh_collect_error_for_existing_path_preserves_cached_entry() {
6868        let temp = tempfile::tempdir().unwrap();
6869        let project_root = temp.path();
6870        let file = project_root.join("src/lib.rs");
6871        fs::create_dir_all(file.parent().unwrap()).unwrap();
6872        write_rust_file(&file, "kept_symbol");
6873
6874        let mut index = build_test_index(project_root, std::slice::from_ref(&file));
6875        let original_entry_count = index.entries.len();
6876        let original_mtime = *index.file_mtimes.get(&file).unwrap();
6877        let original_size = *index.file_sizes.get(&file).unwrap();
6878
6879        let stale_mtime = SystemTime::UNIX_EPOCH;
6880        set_file_metadata(&mut index, &file, stale_mtime, original_size + 1);
6881        fs::remove_file(&file).unwrap();
6882        fs::create_dir(&file).unwrap();
6883
6884        let mut embed = test_vector_for_texts;
6885        let mut progress = |_done: usize, _total: usize| {};
6886        let summary = index
6887            .refresh_stale_files(
6888                project_root,
6889                std::slice::from_ref(&file),
6890                &mut embed,
6891                8,
6892                &mut progress,
6893            )
6894            .unwrap();
6895
6896        assert_eq!(summary.changed, 0);
6897        assert_eq!(summary.added, 0);
6898        assert_eq!(summary.deleted, 0);
6899        assert_eq!(index.entries.len(), original_entry_count);
6900        assert!(index
6901            .entries
6902            .iter()
6903            .any(|entry| entry.chunk.name == "kept_symbol"));
6904        assert_eq!(index.file_mtimes.get(&file), Some(&stale_mtime));
6905        assert_ne!(index.file_mtimes.get(&file), Some(&original_mtime));
6906        assert_eq!(index.file_sizes.get(&file), Some(&(original_size + 1)));
6907    }
6908
6909    #[test]
6910    fn refresh_never_indexed_file_error_does_not_record_mtime() {
6911        let temp = tempfile::tempdir().unwrap();
6912        let project_root = temp.path();
6913        let missing = project_root.join("src/missing.rs");
6914        fs::create_dir_all(missing.parent().unwrap()).unwrap();
6915
6916        let mut index = SemanticIndex::new(test_project_root(), DEFAULT_DIMENSION);
6917        let mut embed = test_vector_for_texts;
6918        let mut progress = |_done: usize, _total: usize| {};
6919        let summary = index
6920            .refresh_stale_files(
6921                project_root,
6922                std::slice::from_ref(&missing),
6923                &mut embed,
6924                8,
6925                &mut progress,
6926            )
6927            .unwrap();
6928
6929        assert_eq!(summary.added, 0);
6930        assert_eq!(summary.changed, 0);
6931        assert_eq!(summary.deleted, 0);
6932        assert!(!index.file_mtimes.contains_key(&missing));
6933        assert!(!index.file_sizes.contains_key(&missing));
6934        assert!(index.entries.is_empty());
6935    }
6936
6937    #[test]
6938    fn refresh_reports_added_for_new_files() {
6939        let temp = tempfile::tempdir().unwrap();
6940        let project_root = temp.path();
6941        let existing = project_root.join("src/lib.rs");
6942        let added = project_root.join("src/new.rs");
6943        fs::create_dir_all(existing.parent().unwrap()).unwrap();
6944        write_rust_file(&existing, "existing_symbol");
6945        write_rust_file(&added, "added_symbol");
6946
6947        let mut index = build_test_index(project_root, std::slice::from_ref(&existing));
6948        let mut embed = test_vector_for_texts;
6949        let mut progress = |_done: usize, _total: usize| {};
6950        let summary = index
6951            .refresh_stale_files(
6952                project_root,
6953                &[existing.clone(), added.clone()],
6954                &mut embed,
6955                8,
6956                &mut progress,
6957            )
6958            .unwrap();
6959
6960        assert_eq!(summary.added, 1);
6961        assert_eq!(summary.changed, 0);
6962        assert_eq!(summary.deleted, 0);
6963        assert_eq!(summary.total_processed, 2);
6964        assert!(index.file_mtimes.contains_key(&added));
6965        assert!(index.entries.iter().any(|entry| entry.chunk.file == added));
6966    }
6967
6968    #[test]
6969    fn refresh_reports_deleted_for_removed_files() {
6970        let temp = tempfile::tempdir().unwrap();
6971        let project_root = temp.path();
6972        let deleted = project_root.join("src/deleted.rs");
6973        fs::create_dir_all(deleted.parent().unwrap()).unwrap();
6974        write_rust_file(&deleted, "deleted_symbol");
6975
6976        let mut index = build_test_index(project_root, std::slice::from_ref(&deleted));
6977        fs::remove_file(&deleted).unwrap();
6978
6979        let mut embed = test_vector_for_texts;
6980        let mut progress = |_done: usize, _total: usize| {};
6981        let summary = index
6982            .refresh_stale_files(project_root, &[], &mut embed, 8, &mut progress)
6983            .unwrap();
6984
6985        assert_eq!(summary.deleted, 1);
6986        assert_eq!(summary.changed, 0);
6987        assert_eq!(summary.added, 0);
6988        assert_eq!(summary.total_processed, 1);
6989        assert!(!index.file_mtimes.contains_key(&deleted));
6990        assert!(index.entries.is_empty());
6991    }
6992
6993    #[test]
6994    fn refresh_reports_changed_for_modified_files() {
6995        let temp = tempfile::tempdir().unwrap();
6996        let project_root = temp.path();
6997        let file = project_root.join("src/lib.rs");
6998        fs::create_dir_all(file.parent().unwrap()).unwrap();
6999        write_rust_file(&file, "old_symbol");
7000
7001        let mut index = build_test_index(project_root, std::slice::from_ref(&file));
7002        set_file_metadata(&mut index, &file, SystemTime::UNIX_EPOCH, 0);
7003        write_rust_file(&file, "new_symbol");
7004
7005        let mut embed = test_vector_for_texts;
7006        let mut progress = |_done: usize, _total: usize| {};
7007        let summary = index
7008            .refresh_stale_files(
7009                project_root,
7010                std::slice::from_ref(&file),
7011                &mut embed,
7012                8,
7013                &mut progress,
7014            )
7015            .unwrap();
7016
7017        assert_eq!(summary.changed, 1);
7018        assert_eq!(summary.added, 0);
7019        assert_eq!(summary.deleted, 0);
7020        assert_eq!(summary.total_processed, 1);
7021        assert!(index
7022            .entries
7023            .iter()
7024            .any(|entry| entry.chunk.name == "new_symbol"));
7025        assert!(!index
7026            .entries
7027            .iter()
7028            .any(|entry| entry.chunk.name == "old_symbol"));
7029    }
7030
7031    #[test]
7032    fn refresh_all_clean_reports_zero_counts_and_no_embedding_work() {
7033        let temp = tempfile::tempdir().unwrap();
7034        let project_root = temp.path();
7035        let file = project_root.join("src/lib.rs");
7036        fs::create_dir_all(file.parent().unwrap()).unwrap();
7037        write_rust_file(&file, "clean_symbol");
7038
7039        let mut index = build_test_index(project_root, std::slice::from_ref(&file));
7040        let original_entries = index.entries.len();
7041        let mut embed_called = false;
7042        let mut embed = |texts: Vec<String>| {
7043            embed_called = true;
7044            test_vector_for_texts(texts)
7045        };
7046        let mut progress = |_done: usize, _total: usize| {};
7047        let summary = index
7048            .refresh_stale_files(
7049                project_root,
7050                std::slice::from_ref(&file),
7051                &mut embed,
7052                8,
7053                &mut progress,
7054            )
7055            .unwrap();
7056
7057        assert!(summary.is_noop());
7058        assert_eq!(summary.total_processed, 1);
7059        assert!(!embed_called);
7060        assert_eq!(index.entries.len(), original_entries);
7061    }
7062
7063    #[test]
7064    fn detects_missing_onnx_runtime_from_dynamic_load_error() {
7065        let message = "Failed to load ONNX Runtime shared library libonnxruntime.dylib via dlopen: no such file";
7066
7067        assert!(is_onnx_runtime_unavailable(message));
7068    }
7069
7070    #[test]
7071    fn formats_missing_onnx_runtime_with_install_hint() {
7072        let message = format_embedding_init_error(
7073            "Failed to load ONNX Runtime shared library libonnxruntime.so via dlopen: no such file",
7074        );
7075
7076        assert!(message.starts_with("ONNX Runtime not found. Install via:"));
7077        assert!(message.contains("Original error:"));
7078    }
7079
7080    #[test]
7081    fn interactive_query_budget_is_independent_from_build_timeout() {
7082        let mut config = SemanticBackendConfig {
7083            backend: SemanticBackend::OpenAiCompatible,
7084            model: "test-embedding".to_string(),
7085            base_url: Some("http://127.0.0.1:9".to_string()),
7086            api_key_env: None,
7087            timeout_ms: 0,
7088            query_timeout_ms: 0,
7089            max_batch_size: 64,
7090            max_files: 20_000,
7091        };
7092
7093        let build_model = SemanticEmbeddingModel::from_config(&config).unwrap();
7094        let query_model = SemanticEmbeddingModel::from_config_for_query(&config).unwrap();
7095        assert_eq!(
7096            build_model.timeout_ms(),
7097            DEFAULT_OPENAI_EMBEDDING_TIMEOUT_MS,
7098            "background build keeps the longer default embedding timeout"
7099        );
7100        assert_eq!(
7101            query_model.timeout_ms(),
7102            DEFAULT_OPENAI_EMBEDDING_TIMEOUT_MS,
7103            "a query-created model remains safe for later background build reuse"
7104        );
7105        assert_eq!(
7106            QueryBudget::from_config(&config).timeout_ms(),
7107            DEFAULT_SEMANTIC_QUERY_TIMEOUT_MS
7108        );
7109
7110        config.timeout_ms = 60_000;
7111        assert_eq!(
7112            QueryBudget::from_config(&config).timeout_ms(),
7113            DEFAULT_SEMANTIC_QUERY_TIMEOUT_MS,
7114            "the build timeout must not affect interactive requests"
7115        );
7116
7117        config.query_timeout_ms = 700;
7118        assert_eq!(QueryBudget::from_config(&config).timeout_ms(), 700);
7119    }
7120
7121    #[test]
7122    fn background_build_embedding_keeps_retry_ladder() {
7123        let (base_url, requests, handle) =
7124            start_slow_embedding_server(EMBEDDING_REQUEST_MAX_ATTEMPTS, Duration::from_millis(300));
7125        let config = SemanticBackendConfig {
7126            backend: SemanticBackend::OpenAiCompatible,
7127            model: "test-embedding".to_string(),
7128            base_url: Some(base_url),
7129            api_key_env: None,
7130            timeout_ms: 100,
7131            query_timeout_ms: DEFAULT_SEMANTIC_QUERY_TIMEOUT_MS,
7132            max_batch_size: 64,
7133            max_files: 20_000,
7134        };
7135        let mut model = SemanticEmbeddingModel::from_config(&config).unwrap();
7136
7137        let error = model
7138            .embed(vec!["slow build batch".to_string()])
7139            .expect_err("all slow build attempts should time out");
7140        handle.join().expect("slow embedding server");
7141
7142        assert!(embedding_failure_is_transient(&error), "error: {error}");
7143        assert_eq!(
7144            requests.load(Ordering::SeqCst),
7145            EMBEDDING_REQUEST_MAX_ATTEMPTS,
7146            "background builds must retain the existing retry ladder"
7147        );
7148    }
7149
7150    #[test]
7151    fn openai_compatible_backend_embeds_with_mock_server() {
7152        let (base_url, handle) = start_mock_http_server(|request_line, path, _body| {
7153            assert!(request_line.starts_with("POST "));
7154            assert_eq!(path, "/v1/embeddings");
7155            "{\"data\":[{\"embedding\":[0.1,0.2,0.3],\"index\":0},{\"embedding\":[0.4,0.5,0.6],\"index\":1}]}".to_string()
7156        });
7157
7158        let config = SemanticBackendConfig {
7159            backend: SemanticBackend::OpenAiCompatible,
7160            model: "test-embedding".to_string(),
7161            base_url: Some(base_url),
7162            api_key_env: None,
7163            timeout_ms: 5_000,
7164            query_timeout_ms: DEFAULT_SEMANTIC_QUERY_TIMEOUT_MS,
7165            max_batch_size: 64,
7166            max_files: 20_000,
7167        };
7168
7169        let mut model = SemanticEmbeddingModel::from_config(&config).unwrap();
7170        let vectors = model
7171            .embed(vec!["hello".to_string(), "world".to_string()])
7172            .unwrap();
7173
7174        assert_eq!(vectors, vec![vec![0.1, 0.2, 0.3], vec![0.4, 0.5, 0.6]]);
7175        handle.join().unwrap();
7176    }
7177
7178    /// Regression for issue #36: AFT was sending TWO Content-Type headers
7179    /// on the OpenAI embeddings request — once implicitly via `.json(&body)`
7180    /// and again explicitly via `.header("Content-Type", "application/json")`.
7181    /// reqwest's `.header()` calls `HeaderMap::append`, which produces two
7182    /// headers on the wire. OpenAI's /v1/embeddings endpoint rejects that
7183    /// with `HTTP 400 "you must provide a model parameter"` even though the
7184    /// body actually contains `model`. The fix is to drop the explicit
7185    /// `.header("Content-Type", ...)` call. This test pins that we send
7186    /// exactly one Content-Type header.
7187    #[test]
7188    fn openai_compatible_request_has_single_content_type_header() {
7189        use std::sync::{Arc, Mutex};
7190        let captured: Arc<Mutex<Vec<u8>>> = Arc::new(Mutex::new(Vec::new()));
7191        let captured_for_thread = Arc::clone(&captured);
7192
7193        let listener = TcpListener::bind("127.0.0.1:0").expect("bind test server");
7194        let addr = listener.local_addr().expect("local addr");
7195        let handle = thread::spawn(move || {
7196            let (mut stream, _) = listener.accept().expect("accept");
7197            let mut buf = Vec::new();
7198            let mut chunk = [0u8; 4096];
7199            let mut header_end = None;
7200            let mut content_length = 0usize;
7201            loop {
7202                let n = stream.read(&mut chunk).expect("read");
7203                if n == 0 {
7204                    break;
7205                }
7206                buf.extend_from_slice(&chunk[..n]);
7207                if header_end.is_none() {
7208                    if let Some(pos) = buf.windows(4).position(|window| window == b"\r\n\r\n") {
7209                        header_end = Some(pos + 4);
7210                        for line in String::from_utf8_lossy(&buf[..pos + 4]).lines() {
7211                            if let Some(value) = line.strip_prefix("Content-Length:") {
7212                                content_length = value.trim().parse::<usize>().unwrap_or(0);
7213                            }
7214                        }
7215                    }
7216                }
7217                if let Some(end) = header_end {
7218                    if buf.len() >= end + content_length {
7219                        break;
7220                    }
7221                }
7222            }
7223            *captured_for_thread.lock().unwrap() = buf;
7224            let body = "{\"data\":[{\"embedding\":[0.1,0.2,0.3],\"index\":0}]}";
7225            let response = format!(
7226                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
7227                body.len(),
7228                body
7229            );
7230            let _ = stream.write_all(response.as_bytes());
7231        });
7232
7233        let config = SemanticBackendConfig {
7234            backend: SemanticBackend::OpenAiCompatible,
7235            model: "text-embedding-3-small".to_string(),
7236            base_url: Some(format!("http://{}", addr)),
7237            api_key_env: None,
7238            timeout_ms: 5_000,
7239            query_timeout_ms: DEFAULT_SEMANTIC_QUERY_TIMEOUT_MS,
7240            max_batch_size: 64,
7241            max_files: 20_000,
7242        };
7243        let mut model = SemanticEmbeddingModel::from_config(&config).unwrap();
7244        let _ = model.embed(vec!["probe".to_string()]).unwrap();
7245        handle.join().unwrap();
7246
7247        let bytes = captured.lock().unwrap().clone();
7248        let request = String::from_utf8_lossy(&bytes);
7249
7250        // Lowercase line counts because HTTP headers are case-insensitive
7251        // and reqwest may emit `content-type` in lowercase under HTTP/2.
7252        let content_type_lines = request
7253            .lines()
7254            .filter(|line| {
7255                let lower = line.to_ascii_lowercase();
7256                lower.starts_with("content-type:")
7257            })
7258            .count();
7259        assert_eq!(
7260            content_type_lines, 1,
7261            "expected exactly one Content-Type header but found {content_type_lines}; full request:\n{request}",
7262        );
7263
7264        // The body must still include the model field — pin this so a future
7265        // change can't accidentally drop `model` while fixing duplicate headers.
7266        assert!(
7267            request.contains(r#""model":"text-embedding-3-small""#),
7268            "request body should contain model field; full request:\n{request}",
7269        );
7270    }
7271
7272    #[test]
7273    fn ollama_backend_embeds_with_mock_server() {
7274        let (base_url, handle) = start_mock_http_server(|request_line, path, _body| {
7275            assert!(request_line.starts_with("POST "));
7276            assert_eq!(path, "/api/embed");
7277            "{\"embeddings\":[[0.7,0.8,0.9],[1.0,1.1,1.2]]}".to_string()
7278        });
7279
7280        let config = SemanticBackendConfig {
7281            backend: SemanticBackend::Ollama,
7282            model: "embeddinggemma".to_string(),
7283            base_url: Some(base_url),
7284            api_key_env: None,
7285            timeout_ms: 5_000,
7286            query_timeout_ms: DEFAULT_SEMANTIC_QUERY_TIMEOUT_MS,
7287            max_batch_size: 64,
7288            max_files: 20_000,
7289        };
7290
7291        let mut model = SemanticEmbeddingModel::from_config(&config).unwrap();
7292        let vectors = model
7293            .embed(vec!["hello".to_string(), "world".to_string()])
7294            .unwrap();
7295
7296        assert_eq!(vectors, vec![vec![0.7, 0.8, 0.9], vec![1.0, 1.1, 1.2]]);
7297        handle.join().unwrap();
7298    }
7299
7300    #[test]
7301    fn read_from_disk_rejects_fingerprint_mismatch() {
7302        let storage = tempfile::tempdir().unwrap();
7303        let project_key = "proj";
7304
7305        let project_root = test_project_root();
7306        let file = project_root.join("src/main.rs");
7307        let mut index = SemanticIndex::new(project_root.clone(), DEFAULT_DIMENSION);
7308        index.entries.push(EmbeddingEntry {
7309            chunk: SemanticChunk {
7310                file: file.clone(),
7311                name: "handle_request".to_string(),
7312                qualified_name: None,
7313                kind: SymbolKind::Function,
7314                start_line: 10,
7315                end_line: 25,
7316                exported: true,
7317                embed_text: "file:src/main.rs kind:function name:handle_request".to_string(),
7318                snippet: "fn handle_request() {}".to_string(),
7319            },
7320            norm: vector_norm(&[0.1, 0.2, 0.3]),
7321            vector: vec![0.1, 0.2, 0.3],
7322        });
7323        index.dimension = 3;
7324        index
7325            .file_mtimes
7326            .insert(file.clone(), SystemTime::UNIX_EPOCH);
7327        index.file_sizes.insert(file, 0);
7328        index.set_fingerprint(SemanticIndexFingerprint {
7329            backend: "openai_compatible".to_string(),
7330            model: "test-embedding".to_string(),
7331            base_url: "http://127.0.0.1:1234/v1".to_string(),
7332            dimension: 3,
7333            chunking_version: default_chunking_version(),
7334        });
7335        index.write_to_disk(storage.path(), project_key);
7336
7337        let data_path = storage
7338            .path()
7339            .join("semantic")
7340            .join(project_key)
7341            .join("semantic.bin");
7342        let before = fs::read(&data_path).unwrap();
7343
7344        let matching = index.fingerprint().unwrap().as_string();
7345        assert!(SemanticIndex::read_from_disk(
7346            storage.path(),
7347            project_key,
7348            &project_root,
7349            false,
7350            Some(&matching),
7351        )
7352        .is_some());
7353
7354        let mismatched = SemanticIndexFingerprint {
7355            backend: "ollama".to_string(),
7356            model: "embeddinggemma".to_string(),
7357            base_url: "http://127.0.0.1:11434".to_string(),
7358            dimension: 3,
7359            chunking_version: default_chunking_version(),
7360        }
7361        .as_string();
7362        assert!(SemanticIndex::read_from_disk(
7363            storage.path(),
7364            project_key,
7365            &project_root,
7366            false,
7367            Some(&mismatched),
7368        )
7369        .is_none());
7370        assert_eq!(fs::read(&data_path).unwrap(), before);
7371    }
7372
7373    #[test]
7374    fn fingerprint_mismatch_details_redact_base_url_and_list_changed_fields() {
7375        let cached = SemanticIndexFingerprint {
7376            backend: "openai_compatible".to_string(),
7377            model: "cached-model".to_string(),
7378            base_url: "https://user:secret@example.com/v1/embeddings".to_string(),
7379            dimension: 3,
7380            chunking_version: 2,
7381        };
7382        let current = SemanticIndexFingerprint {
7383            backend: "ollama".to_string(),
7384            model: "current-model".to_string(),
7385            base_url: "https://example.org/api/embed".to_string(),
7386            dimension: 4,
7387            chunking_version: 3,
7388        };
7389
7390        let details = format_fingerprint_mismatch_details(Some(&cached), &current);
7391
7392        assert!(details.contains("backend kind cached=openai_compatible current=ollama"));
7393        assert!(details.contains("model cached=cached-model current=current-model"));
7394        assert!(details.contains("base_url host cached=example.com current=example.org"));
7395        assert!(details.contains("dimension cached=3 current=4"));
7396        assert!(details.contains("chunking version cached=2 current=3"));
7397        assert!(!details.contains("secret"));
7398        assert!(!details.contains("/v1/embeddings"));
7399        assert!(!details.contains("/api/embed"));
7400    }
7401
7402    #[test]
7403    fn read_from_disk_rejects_v3_cache_for_snippet_rebuild() {
7404        let storage = tempfile::tempdir().unwrap();
7405        let project_key = "proj-v3";
7406        let dir = storage.path().join("semantic").join(project_key);
7407        fs::create_dir_all(&dir).unwrap();
7408
7409        let mut index = SemanticIndex::new(test_project_root(), DEFAULT_DIMENSION);
7410        index.entries.push(EmbeddingEntry {
7411            chunk: SemanticChunk {
7412                file: PathBuf::from("/src/main.rs"),
7413                name: "handle_request".to_string(),
7414                qualified_name: None,
7415                kind: SymbolKind::Function,
7416                start_line: 0,
7417                end_line: 0,
7418                exported: true,
7419                embed_text: "file:src/main.rs kind:function name:handle_request".to_string(),
7420                snippet: "fn handle_request() {}".to_string(),
7421            },
7422            norm: vector_norm(&[0.1, 0.2, 0.3]),
7423            vector: vec![0.1, 0.2, 0.3],
7424        });
7425        index.dimension = 3;
7426        index
7427            .file_mtimes
7428            .insert(PathBuf::from("/src/main.rs"), SystemTime::UNIX_EPOCH);
7429        index.file_sizes.insert(PathBuf::from("/src/main.rs"), 0);
7430        let fingerprint = SemanticIndexFingerprint {
7431            backend: "fastembed".to_string(),
7432            model: "test".to_string(),
7433            base_url: FALLBACK_BACKEND.to_string(),
7434            dimension: 3,
7435            chunking_version: default_chunking_version(),
7436        };
7437        index.set_fingerprint(fingerprint.clone());
7438
7439        let mut bytes = index.to_bytes();
7440        bytes[0] = SEMANTIC_INDEX_VERSION_V3;
7441        let data_path = dir.join("semantic.bin");
7442        fs::write(&data_path, &bytes).unwrap();
7443
7444        assert!(SemanticIndex::read_from_disk(
7445            storage.path(),
7446            project_key,
7447            &test_project_root(),
7448            false,
7449            Some(&fingerprint.as_string())
7450        )
7451        .is_none());
7452        assert_eq!(fs::read(&data_path).unwrap(), bytes);
7453    }
7454
7455    fn make_symbol(kind: SymbolKind, name: &str, start: u32, end: u32) -> crate::symbols::Symbol {
7456        crate::symbols::Symbol {
7457            name: name.to_string(),
7458            kind,
7459            range: crate::symbols::Range {
7460                start_line: start,
7461                start_col: 0,
7462                end_line: end,
7463                end_col: 0,
7464            },
7465            signature: None,
7466            scope_chain: Vec::new(),
7467            exported: false,
7468            parent: None,
7469        }
7470    }
7471
7472    #[test]
7473    fn symbols_to_chunks_sets_qualified_name_without_changing_embed_text() {
7474        let project_root = PathBuf::from("/proj");
7475        let file = project_root.join("src/engine.ts");
7476        let source = "class Index {\n}\n";
7477        let mut symbol = make_symbol(SymbolKind::Class, "Index", 0, 1);
7478        symbol.scope_chain = vec!["Engine".to_string()];
7479        symbol.signature = Some("class Index".to_string());
7480        let embed_text = build_embed_text(&symbol, source, &file, &project_root);
7481
7482        let chunks = symbols_to_chunks(&file, &[symbol], source, &project_root);
7483        let chunk = chunks
7484            .iter()
7485            .find(|chunk| chunk.name == "Index")
7486            .expect("class chunk");
7487
7488        assert_eq!(chunk.name, "Index");
7489        assert_eq!(chunk.qualified_name.as_deref(), Some("Engine.Index"));
7490        assert_eq!(chunk.embed_text, embed_text);
7491        assert!(!chunk.embed_text.contains("Engine.Index"));
7492    }
7493
7494    /// Heading symbols (Markdown / HTML headings) must NOT be indexed —
7495    /// they overwhelmingly dominated semantic results even on code-shaped
7496    /// queries because heading prose embeds far more strongly than code
7497    /// chunks. Skipping headings keeps aft_search a code-finder.
7498    #[test]
7499    fn symbols_to_chunks_skips_heading_symbols() {
7500        let project_root = PathBuf::from("/proj");
7501        let file = project_root.join("README.md");
7502        let source = "# Title\n\nbody text\n\n## Section\n\nmore text\n";
7503
7504        let symbols = vec![
7505            make_symbol(SymbolKind::Heading, "Title", 0, 2),
7506            make_symbol(SymbolKind::Heading, "Section", 4, 6),
7507        ];
7508
7509        let chunks = symbols_to_chunks(&file, &symbols, source, &project_root);
7510        assert!(
7511            chunks.is_empty(),
7512            "Heading symbols must be filtered out before embedding; got {} chunk(s)",
7513            chunks.len()
7514        );
7515    }
7516
7517    /// A symbol with an enormous signature (e.g. a YAML/Kubernetes CronJob
7518    /// whose inline `command:` script is parsed into the signature) must not
7519    /// produce an embed_text that overflows the embedding backend's physical
7520    /// batch. Before the clamp, the unbounded `signature:` append created a
7521    /// multi-KB input that aborted the whole index build and degraded every
7522    /// search to lexical-only.
7523    #[test]
7524    fn build_embed_text_clamps_oversized_signature() {
7525        let project_root = PathBuf::from("/proj");
7526        let file = project_root.join("cronjob.yaml");
7527        let huge_sig = "kubectl ".repeat(2000); // ~16 KB
7528        let source = "apiVersion: batch/v1\nkind: CronJob\n";
7529
7530        let mut symbol = make_symbol(SymbolKind::Class, "cluster-janitor", 0, 1);
7531        symbol.signature = Some(huge_sig);
7532
7533        let text = build_embed_text(&symbol, source, &file, &project_root);
7534        assert!(
7535            text.chars().count() <= MAX_EMBED_TEXT_CHARS,
7536            "embed_text must be clamped to {} chars, got {}",
7537            MAX_EMBED_TEXT_CHARS,
7538            text.chars().count()
7539        );
7540    }
7541
7542    /// Code symbols (functions, classes, methods, structs, etc.) must still
7543    /// be indexed alongside the heading skip — otherwise we'd starve the
7544    /// index entirely.
7545    #[test]
7546    fn symbols_to_chunks_keeps_code_symbols_alongside_skipped_headings() {
7547        let project_root = PathBuf::from("/proj");
7548        let file = project_root.join("src/lib.rs");
7549        let source = "pub fn handle_request() -> bool {\n    true\n}\n";
7550
7551        let symbols = vec![
7552            // A heading mixed in (e.g. from a doc comment block elsewhere).
7553            make_symbol(SymbolKind::Heading, "doc heading", 0, 1),
7554            make_symbol(SymbolKind::Function, "handle_request", 0, 2),
7555            make_symbol(SymbolKind::Struct, "AuthService", 4, 6),
7556        ];
7557
7558        let chunks = symbols_to_chunks(&file, &symbols, source, &project_root);
7559        assert_eq!(
7560            chunks.len(),
7561            3,
7562            "Expected file-summary + 2 code chunks (Function + Struct), got {}",
7563            chunks.len()
7564        );
7565        let names: Vec<&str> = chunks.iter().map(|c| c.name.as_str()).collect();
7566        assert!(chunks
7567            .iter()
7568            .any(|chunk| matches!(chunk.kind, SymbolKind::FileSummary)));
7569        assert!(names.contains(&"handle_request"));
7570        assert!(names.contains(&"AuthService"));
7571        assert!(
7572            !names.contains(&"doc heading"),
7573            "Heading symbol leaked into chunks: {names:?}"
7574        );
7575    }
7576
7577    #[test]
7578    fn validate_ssrf_allows_loopback_hostnames() {
7579        // Loopback hostnames are explicitly allowed so self-hosted backends
7580        // (Ollama at http://localhost:11434) work at their default config.
7581        for host in &[
7582            "http://localhost",
7583            "http://localhost:8080",
7584            "http://localhost:11434", // Ollama default
7585            "http://localhost.localdomain",
7586            "http://foo.localhost",
7587        ] {
7588            assert!(
7589                validate_base_url_no_ssrf(host).is_ok(),
7590                "Expected {host} to be allowed (loopback), got: {:?}",
7591                validate_base_url_no_ssrf(host)
7592            );
7593        }
7594    }
7595
7596    #[test]
7597    fn validate_ssrf_allows_loopback_ips() {
7598        // 127.0.0.0/8 is loopback — by definition same-machine and not an
7599        // SSRF target. Allow it so Ollama at http://127.0.0.1:11434 works.
7600        for url in &[
7601            "http://127.0.0.1",
7602            "http://127.0.0.1:11434", // Ollama default
7603            "http://127.0.0.1:8080",
7604            "http://127.1.2.3",
7605        ] {
7606            let result = validate_base_url_no_ssrf(url);
7607            assert!(
7608                result.is_ok(),
7609                "Expected {url} to be allowed (loopback), got: {:?}",
7610                result
7611            );
7612        }
7613    }
7614
7615    #[test]
7616    fn validate_ssrf_rejects_private_non_loopback_ips() {
7617        // Non-loopback private/reserved IPs remain rejected — homelab/intranet
7618        // services on LAN IPs are real SSRF targets even though the user
7619        // configured them. Users who want this can opt in by binding the
7620        // service to a public-routable address.
7621        for url in &[
7622            "http://192.168.1.1",
7623            "http://10.0.0.1",
7624            "http://172.16.0.1",
7625            "http://169.254.169.254",
7626            "http://100.64.0.1",
7627        ] {
7628            let result = validate_base_url_no_ssrf(url);
7629            assert!(
7630                result.is_err(),
7631                "Expected {url} to be rejected (non-loopback private), got: {:?}",
7632                result
7633            );
7634        }
7635    }
7636
7637    #[test]
7638    fn validate_ssrf_rejects_mdns_local_hostnames() {
7639        // mDNS .local hostnames typically resolve to LAN devices, not
7640        // loopback. Rejecting them before DNS lookup gives a clearer error.
7641        for host in &[
7642            "http://printer.local",
7643            "http://nas.local:8080",
7644            "http://homelab.local",
7645        ] {
7646            let result = validate_base_url_no_ssrf(host);
7647            assert!(
7648                result.is_err(),
7649                "Expected {host} to be rejected (mDNS), got: {:?}",
7650                result
7651            );
7652        }
7653    }
7654
7655    #[test]
7656    fn normalize_base_url_allows_localhost_for_tests() {
7657        // normalize_base_url itself should NOT block localhost — only
7658        // validate_base_url_no_ssrf does. Tests construct backends directly.
7659        assert!(normalize_base_url("http://127.0.0.1:9999").is_ok());
7660        assert!(normalize_base_url("http://localhost:8080").is_ok());
7661    }
7662
7663    #[test]
7664    fn ssrf_guard_blocks_reserved_ranges_but_allows_loopback() {
7665        use std::net::IpAddr;
7666        let blocked = |s: &str| is_private_non_loopback_ip(&s.parse::<IpAddr>().unwrap());
7667
7668        // Private / link-local / CGNAT — blocked (unchanged behavior).
7669        assert!(blocked("10.0.0.1"));
7670        assert!(blocked("192.168.1.1"));
7671        assert!(blocked("169.254.0.1"));
7672        assert!(blocked("100.64.0.1"));
7673        // Newly covered by delegating to url_fetch's complete list:
7674        assert!(
7675            blocked("198.18.0.1"),
7676            "RFC2544 benchmark range must be blocked"
7677        );
7678        assert!(blocked("224.0.0.1"), "multicast must be blocked");
7679        assert!(blocked("fc00::1"), "IPv6 ULA must be blocked");
7680        assert!(blocked("fe80::1"), "IPv6 link-local must be blocked");
7681
7682        // Loopback — allowed (local Ollama endpoint), incl. IPv4-mapped form.
7683        assert!(!blocked("127.0.0.1"), "loopback must stay allowed");
7684        assert!(!blocked("::1"), "IPv6 loopback must stay allowed");
7685        assert!(
7686            !blocked("::ffff:127.0.0.1"),
7687            "IPv4-mapped loopback must stay allowed (matches prior carve-out)"
7688        );
7689
7690        // A public address must NOT be flagged.
7691        assert!(!blocked("8.8.8.8"));
7692    }
7693
7694    /// Pin the user-facing wording of the ONNX version-mismatch error.
7695    /// The auto-fix path MUST be listed first because it's the only safe
7696    /// option that doesn't require sudo or risk breaking other apps that
7697    /// link the system library. Regression of any of these strings would
7698    /// either mislead users (system rm before auto-fix) or break the
7699    /// `aft doctor --fix` discovery path.
7700    #[test]
7701    fn ort_mismatch_message_recommends_auto_fix_first() {
7702        let msg =
7703            format_ort_version_mismatch("1.9.0", "/usr/lib/x86_64-linux-gnu/libonnxruntime.so");
7704
7705        // The reported version and path must appear verbatim.
7706        assert!(
7707            msg.contains("v1.9.0"),
7708            "should report detected version: {msg}"
7709        );
7710        assert!(
7711            msg.contains("/usr/lib/x86_64-linux-gnu/libonnxruntime.so"),
7712            "should report system path: {msg}"
7713        );
7714        assert!(msg.contains("v1.20+"), "should state requirement: {msg}");
7715
7716        // Solution ordering: auto-fix is #1, system rm is #2, install is #3.
7717        let auto_fix_pos = msg
7718            .find("Auto-fix")
7719            .expect("Auto-fix solution missing — users won't discover --fix");
7720        let remove_pos = msg
7721            .find("Remove the old library")
7722            .expect("system-rm solution missing");
7723        assert!(
7724            auto_fix_pos < remove_pos,
7725            "Auto-fix must come before manual rm — see PR comment thread"
7726        );
7727
7728        // The auto-fix command must be runnable as-is on a fresh system.
7729        assert!(
7730            msg.contains("npx @cortexkit/aft doctor --fix"),
7731            "auto-fix command must be present and copy-pasteable: {msg}"
7732        );
7733    }
7734
7735    #[cfg(any(target_os = "linux", target_os = "macos"))]
7736    #[test]
7737    fn loaded_ort_version_detection_prefers_actual_loaded_library_path() {
7738        let requested = "libonnxruntime.so";
7739        let actual = "/usr/local/lib/libonnxruntime.so.1.19.0";
7740
7741        assert_eq!(detect_ort_version_from_path(requested), None);
7742        let (version, source) =
7743            detect_ort_version_from_resolved_or_requested(Some(actual.to_string()), requested);
7744
7745        assert_eq!(version, Some("1.19.0".to_string()));
7746        assert_eq!(source, actual);
7747
7748        let msg = format_ort_version_mismatch(&version.unwrap(), &source);
7749        assert!(msg.contains("v1.19.0"));
7750        assert!(msg.contains(actual));
7751    }
7752
7753    /// macOS dylib paths must not produce a malformed message when the
7754    /// system path lacks a trailing slash. This is a regression guard
7755    /// for the "{}\n{}" format string contract.
7756    #[test]
7757    fn ort_mismatch_message_handles_macos_dylib_path() {
7758        let msg = format_ort_version_mismatch("1.9.0", "/opt/homebrew/lib/libonnxruntime.dylib");
7759        assert!(msg.contains("v1.9.0"));
7760        assert!(msg.contains("/opt/homebrew/lib/libonnxruntime.dylib"));
7761        // The dylib path must appear in the auto-fix paragraph (single
7762        // quotes around it) AND in the manual-rm paragraph; verify
7763        // both placements survived the format string.
7764        assert!(
7765            msg.contains("'/opt/homebrew/lib/libonnxruntime.dylib'"),
7766            "system path should be quoted in the auto-fix sentence: {msg}"
7767        );
7768    }
7769
7770    // ── managed ONNX Runtime resolver tests ──────────────────────────────────
7771
7772    /// Build a fake `<storage>/onnxruntime/<version>/<libname>` tree. Returns
7773    /// the storage root. `lib_name` is the platform library filename the
7774    /// resolver looks for.
7775    fn fake_managed_ort_tree(storage: &std::path::Path, lib_name: &str, versions: &[(&str, bool)]) {
7776        for (version, has_lib) in versions {
7777            let dir = storage.join("onnxruntime").join(version);
7778            std::fs::create_dir_all(&dir).unwrap();
7779            if *has_lib {
7780                std::fs::write(dir.join(lib_name), b"fake-ort").unwrap();
7781            }
7782        }
7783    }
7784
7785    #[test]
7786    fn managed_ort_resolver_picks_highest_compatible_version() {
7787        let _env_lock = crate::test_env::process_env_lock();
7788        let storage = tempfile::tempdir().unwrap();
7789        fake_managed_ort_tree(
7790            storage.path(),
7791            MANAGED_ORT_LIB_NAME,
7792            &[
7793                ("1.19.0", true), // below the 1.20 floor — must be ignored
7794                ("1.20.1", true),
7795                ("1.24.4", true), // highest compatible — must win
7796                ("1.23.0", true),
7797            ],
7798        );
7799        let found = find_managed_onnx_runtime(storage.path()).expect("resolver finds a runtime");
7800        assert_eq!(
7801            found,
7802            storage
7803                .path()
7804                .join("onnxruntime")
7805                .join("1.24.4")
7806                .join(MANAGED_ORT_LIB_NAME)
7807        );
7808    }
7809
7810    #[test]
7811    fn managed_ort_resolver_ignores_non_version_and_pre_120_dirs() {
7812        let _env_lock = crate::test_env::process_env_lock();
7813        let storage = tempfile::tempdir().unwrap();
7814        fake_managed_ort_tree(
7815            storage.path(),
7816            MANAGED_ORT_LIB_NAME,
7817            &[
7818                ("1.19.0", true),     // pre-1.20 — ignored
7819                ("1.24.4.tmp", true), // not a parseable version — ignored
7820                ("latest", true),     // not a version — ignored
7821                ("1.24.4", false),    // compatible but no library file — ignored
7822            ],
7823        );
7824        assert_eq!(
7825            find_managed_onnx_runtime(storage.path()),
7826            None,
7827            "no compatible version with a library file should resolve"
7828        );
7829    }
7830
7831    #[test]
7832    fn managed_ort_resolver_absent_tree_falls_through() {
7833        let _env_lock = crate::test_env::process_env_lock();
7834        let storage = tempfile::tempdir().unwrap();
7835        // No onnxruntime/ dir at all.
7836        assert_eq!(find_managed_onnx_runtime(storage.path()), None);
7837        // Empty onnxruntime/ dir.
7838        std::fs::create_dir_all(storage.path().join("onnxruntime")).unwrap();
7839        assert_eq!(find_managed_onnx_runtime(storage.path()), None);
7840    }
7841
7842    #[test]
7843    fn managed_ort_resolver_prefers_version_root_over_lib_subdir() {
7844        let _env_lock = crate::test_env::process_env_lock();
7845        let storage = tempfile::tempdir().unwrap();
7846        let version_dir = storage.path().join("onnxruntime").join("1.24.4");
7847        std::fs::create_dir_all(version_dir.join("lib")).unwrap();
7848        // Both the version root and the lib/ subdir hold the library; the root
7849        // must win (mirrors resolveCachedOnnxRuntimeDir).
7850        std::fs::write(version_dir.join(MANAGED_ORT_LIB_NAME), b"root").unwrap();
7851        std::fs::write(version_dir.join("lib").join(MANAGED_ORT_LIB_NAME), b"lib").unwrap();
7852        let found = find_managed_onnx_runtime(storage.path()).expect("resolver finds a runtime");
7853        assert_eq!(found, version_dir.join(MANAGED_ORT_LIB_NAME));
7854    }
7855
7856    #[test]
7857    fn managed_ort_resolver_accepts_lib_subdir_only() {
7858        let _env_lock = crate::test_env::process_env_lock();
7859        let storage = tempfile::tempdir().unwrap();
7860        let version_dir = storage.path().join("onnxruntime").join("1.24.4");
7861        std::fs::create_dir_all(version_dir.join("lib")).unwrap();
7862        // Library only under lib/ (manual Microsoft-archive install, #71).
7863        std::fs::write(version_dir.join("lib").join(MANAGED_ORT_LIB_NAME), b"lib").unwrap();
7864        let found = find_managed_onnx_runtime(storage.path()).expect("resolver finds a runtime");
7865        assert_eq!(found, version_dir.join("lib").join(MANAGED_ORT_LIB_NAME));
7866    }
7867
7868    #[test]
7869    fn managed_ort_resolver_pre_set_env_short_circuits_without_reading_tree() {
7870        let _env_lock = crate::test_env::process_env_lock();
7871        let storage = tempfile::tempdir().unwrap();
7872        // Plant a poison dir that would panic the resolver if it were read:
7873        // a version dir whose name is a valid version but whose library file is
7874        // a directory (so `is_file()` would be false) — harmless, but the point
7875        // is the resolver must never even look.
7876        let poison = storage.path().join("onnxruntime").join("1.24.4");
7877        std::fs::create_dir_all(poison.join(MANAGED_ORT_LIB_NAME)).unwrap();
7878
7879        let before = MANAGED_ORT_PROBE_READS.load(Ordering::Relaxed);
7880        // Pre-set ORT_DYLIB_PATH — the resolver must not run at all.
7881        std::env::set_var("ORT_DYLIB_PATH", "/explicit/override/libonnxruntime.so");
7882        resolve_managed_onnx_runtime(storage.path());
7883        std::env::remove_var("ORT_DYLIB_PATH");
7884        assert_eq!(
7885            MANAGED_ORT_PROBE_READS.load(Ordering::Relaxed),
7886            before,
7887            "resolver must not read the storage tree when ORT_DYLIB_PATH is pre-set"
7888        );
7889    }
7890
7891    #[test]
7892    fn managed_ort_resolver_sets_env_when_found() {
7893        let _env_lock = crate::test_env::process_env_lock();
7894        let storage = tempfile::tempdir().unwrap();
7895        fake_managed_ort_tree(storage.path(), MANAGED_ORT_LIB_NAME, &[("1.24.4", true)]);
7896        std::env::remove_var("ORT_DYLIB_PATH");
7897        resolve_managed_onnx_runtime(storage.path());
7898        let set = std::env::var_os("ORT_DYLIB_PATH").expect("resolver sets ORT_DYLIB_PATH");
7899        assert_eq!(
7900            PathBuf::from(set),
7901            storage
7902                .path()
7903                .join("onnxruntime")
7904                .join("1.24.4")
7905                .join(MANAGED_ORT_LIB_NAME)
7906        );
7907        std::env::remove_var("ORT_DYLIB_PATH");
7908    }
7909}