geg 0.3.0

Geg Embeds Gemma: offline semantic grep with EmbeddingGemma 2 and persistent vector caching
use std::{
    fs::File,
    io::{BufRead, BufReader, Read},
    path::{Path, PathBuf},
    process::{Command, Stdio},
    thread,
    time::{Duration, Instant},
};

use serde::Deserialize;

const QUERY_LIMIT: usize = 64;
const QUERY_TIMEOUT: Duration = Duration::from_secs(2);
const MAX_EXCERPT_BYTES: usize = 1024 * 1024;

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Symbol {
    pub(crate) source: PathBuf,
    pub(crate) path: String,
    pub(crate) start_line: u64,
    pub(crate) end_line: u64,
    pub(crate) name: String,
}

pub(crate) struct Chunk {
    pub(crate) line: u64,
    pub(crate) text: String,
}

#[derive(Debug, Deserialize)]
struct QueryResult {
    node: Node,
}

#[derive(Debug, Deserialize)]
struct Node {
    kind: String,
    name: String,
    #[serde(rename = "filePath")]
    file_path: String,
    #[serde(rename = "startLine")]
    start_line: u64,
    #[serde(rename = "endLine")]
    end_line: u64,
}

fn parse_query_output(output: &[u8]) -> Vec<(String, String, u64, u64)> {
    let Ok(results) = serde_json::from_slice::<Vec<QueryResult>>(output) else {
        return Vec::new();
    };
    results
        .into_iter()
        .filter_map(|result| {
            let node = result.node;
            (node.kind != "file"
                && !node.name.is_empty()
                && !node.file_path.is_empty()
                && node.start_line > 0
                && node.end_line >= node.start_line)
                .then_some((node.file_path, node.name, node.start_line, node.end_line))
        })
        .collect()
}

fn indexed_root(path: &Path) -> Option<PathBuf> {
    let absolute = std::fs::canonicalize(path).ok()?;
    let start = if absolute.is_file() {
        absolute.parent()?
    } else {
        absolute.as_path()
    };
    start.ancestors().find_map(|ancestor| {
        ancestor
            .join(".codegraph/codegraph.db")
            .is_file()
            .then(|| ancestor.to_owned())
    })
}

fn query(root: &Path, terms: &[String]) -> Vec<(String, String, u64, u64)> {
    if terms.is_empty() {
        return Vec::new();
    }
    let mut child = match Command::new("codegraph")
        .arg("query")
        .arg(terms.join(" "))
        .arg("--json")
        .arg("--limit")
        .arg(QUERY_LIMIT.to_string())
        .arg("--path")
        .arg(root)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .env("NO_COLOR", "1")
        .spawn()
    {
        Ok(child) => child,
        Err(_) => return Vec::new(),
    };
    let deadline = Instant::now() + QUERY_TIMEOUT;
    let status = loop {
        match child.try_wait() {
            Ok(Some(status)) => break status,
            Ok(None) if Instant::now() < deadline => thread::sleep(Duration::from_millis(10)),
            _ => {
                let _ = child.kill();
                let _ = child.wait();
                return Vec::new();
            }
        }
    };
    if !status.success() {
        return Vec::new();
    }
    let mut output = Vec::new();
    if child
        .stdout
        .take()
        .is_none_or(|mut stdout| stdout.read_to_end(&mut output).is_err())
    {
        return Vec::new();
    }
    parse_query_output(&output)
}

fn display_path(search_path: &Path, scope: &Path, source: &Path) -> Option<String> {
    if scope.is_file() {
        return (scope == source).then(|| search_path.to_string_lossy().into_owned());
    }
    source
        .strip_prefix(scope)
        .ok()
        .map(|relative| search_path.join(relative).to_string_lossy().into_owned())
}

pub(crate) fn lookup(search_paths: &[PathBuf], terms: &[String]) -> Vec<Symbol> {
    let mut roots: Vec<(PathBuf, Vec<(PathBuf, PathBuf)>)> = Vec::new();
    for search_path in search_paths {
        let Ok(scope) = std::fs::canonicalize(search_path) else {
            continue;
        };
        let Some(root) = indexed_root(search_path) else {
            continue;
        };
        if let Some((_, scopes)) = roots.iter_mut().find(|(known, _)| known == &root) {
            scopes.push((search_path.clone(), scope));
        } else {
            roots.push((root, vec![(search_path.clone(), scope)]));
        }
    }

    let mut symbols = Vec::new();
    for (root, scopes) in roots {
        for (file_path, name, start_line, end_line) in query(&root, terms) {
            let source = root.join(file_path);
            let Ok(source) = std::fs::canonicalize(source) else {
                continue;
            };
            let Some(path) = scopes
                .iter()
                .find_map(|(search_path, scope)| display_path(search_path, scope, &source))
            else {
                continue;
            };
            symbols.push(Symbol {
                source,
                path,
                start_line,
                end_line,
                name,
            });
        }
    }
    symbols.sort_unstable_by(|a, b| {
        (a.path.as_str(), a.start_line, a.end_line, a.name.as_str()).cmp(&(
            b.path.as_str(),
            b.start_line,
            b.end_line,
            b.name.as_str(),
        ))
    });
    symbols.dedup();
    symbols
}

pub(crate) fn symbol_at<'a>(symbols: &'a [Symbol], path: &str, line: u64) -> Option<&'a str> {
    symbols
        .iter()
        .filter(|symbol| {
            symbol.path == path && symbol.start_line <= line && line <= symbol.end_line
        })
        .min_by_key(|symbol| {
            (
                symbol.end_line - symbol.start_line,
                std::cmp::Reverse(symbol.start_line),
            )
        })
        .map(|symbol| symbol.name.as_str())
}

pub(crate) fn chunks(symbol: &Symbol, chunk_lines: u32) -> Vec<Chunk> {
    let Ok(file) = File::open(&symbol.source) else {
        return Vec::new();
    };
    let reader = BufReader::new(file);
    let mut excerpt = String::new();
    for (index, line) in reader.lines().enumerate() {
        let line_number = index as u64 + 1;
        if line_number > symbol.end_line || excerpt.len() > MAX_EXCERPT_BYTES {
            break;
        }
        let Ok(line) = line else {
            return Vec::new();
        };
        if line_number >= symbol.start_line {
            excerpt.push_str(&line);
            excerpt.push('\n');
            if excerpt.len() > MAX_EXCERPT_BYTES {
                return Vec::new();
            }
        }
    }
    let mut chunks = Vec::new();
    let _ = crate::input::chunks(excerpt.as_bytes(), chunk_lines, |line, text, _| {
        chunks.push(Chunk {
            line: symbol.start_line + line - 1,
            text: text.to_owned(),
        });
        Ok(())
    });
    chunks
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use super::{Symbol, parse_query_output, symbol_at};

    #[test]
    fn parses_captured_codegraph_json_and_ignores_file_nodes() {
        let output = br#"[
          {
            "node": {
              "id": "method:abc",
              "kind": "method",
              "name": "search_candidates",
              "qualifiedName": "Searcher::search_candidates",
              "filePath": "src/candidates.rs",
              "language": "rust",
              "startLine": 374,
              "endLine": 496
            },
            "score": 114.0
          },
          {
            "node": {
              "kind": "file",
              "name": "candidates.rs",
              "filePath": "src/candidates.rs",
              "startLine": 1,
              "endLine": 750
            },
            "score": 20.0
          }
        ]"#;
        assert_eq!(
            parse_query_output(output),
            vec![(
                "src/candidates.rs".into(),
                "search_candidates".into(),
                374,
                496
            )]
        );
    }

    #[test]
    fn malformed_and_invalid_codegraph_output_is_empty() {
        assert!(parse_query_output(b"not json").is_empty());
        assert!(
            parse_query_output(
                br#"[{"node":{"kind":"function","name":"x","filePath":"x.rs","startLine":8,"endLine":2}}]"#
            )
            .is_empty()
        );
    }

    #[test]
    fn symbol_lookup_prefers_the_innermost_range() {
        let symbols = [
            Symbol {
                source: PathBuf::from("src/lib.rs"),
                path: "src/lib.rs".into(),
                start_line: 1,
                end_line: 20,
                name: "Outer".into(),
            },
            Symbol {
                source: PathBuf::from("src/lib.rs"),
                path: "src/lib.rs".into(),
                start_line: 5,
                end_line: 12,
                name: "inner".into(),
            },
        ];
        assert_eq!(symbol_at(&symbols, "src/lib.rs", 8), Some("inner"));
    }
}