geg 0.3.0

Geg Embeds Gemma: offline semantic grep with EmbeddingGemma 2 and persistent vector caching
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! Offline semantic grep with a local EmbeddingGemma GGUF model.
mod cache;
mod cache_management;
mod candidates;
mod cli;
mod codegraph;
mod config;
mod embedding;
mod hybrid;
mod index;
mod input;
mod mcp;
mod pretty;
mod progress;
mod search;
mod tui;
mod watch;

use std::{
    io::{self, BufRead, IsTerminal, Read, Write},
    path::PathBuf,
    process::ExitCode,
};

use anyhow::{Context, Result, ensure};
use clap::{CommandFactory, FromArgMatches};
use directories::ProjectDirs;

use crate::{
    cache::Cache,
    cli::{Args, Command},
    search::Searcher,
};

fn cache_dir() -> Result<PathBuf> {
    Ok(ProjectDirs::from("", "", "geg")
        .context("cannot locate user cache directory; set --cache and --model")?
        .cache_dir()
        .to_owned())
}

fn run(args: &mut Args, matches: &clap::ArgMatches) -> Result<u8> {
    if !matches!(args.command, Some(Command::Skill)) {
        config::apply(args, matches)?;
    }
    normalize_args(args)?;
    if matches!(args.command, Some(Command::Skill)) {
        io::stdout()
            .lock()
            .write_all(include_str!("../skills/geg/SKILL.md").as_bytes())?;
        return Ok(0);
    }
    if args.command.is_none() && args.query.is_none() && !args.tui && !args.interactive {
        writeln!(
            io::stdout().lock(),
            "geg uses grep-style syntax: geg [OPTIONS] QUERY [FILE...]\nExample: geg --code 'retry logic' src/\nQueries use semantic similarity, not regular expressions. Run geg --help for options.\nIn an interactive terminal, run geg without a query to open the finder."
        )?;
        return Ok(0);
    }
    ensure!(
        args.threshold.is_finite() && (-1.0..=1.0).contains(&args.threshold),
        "--threshold must be finite and between -1 and 1"
    );
    let defaults = cache_dir()?;
    let model = args
        .model
        .clone()
        .unwrap_or_else(|| defaults.join("models/embeddinggemma-2-UD-Q4_K_XL.gguf"));
    let cache_path = args
        .cache
        .clone()
        .unwrap_or_else(|| defaults.join("vectors.sqlite3"));
    if let Some(Command::Mcp { paths, index }) = args.command.clone() {
        let index = index.unwrap_or(index::default_path()?);
        args.index_path = Some(index.clone());
        args.quiet = true;
        args.no_messages = true;
        args.no_progress = true;
        return mcp::run(args, &paths, &index, model, cache_path);
    }
    if let Some(Command::Watch {
        index: Some(path), ..
    }) = args.command.clone()
    {
        args.index_path = Some(path);
    } else if matches!(args.command, Some(Command::Watch { .. })) {
        args.index_path = Some(index::default_path()?);
    }
    if let Some(Command::Cache { action }) = &args.command {
        let stdout = io::stdout();
        let mut out = io::BufWriter::new(stdout.lock());
        cache_management::run(action, &defaults, &cache_path, args, &mut out)?;
        out.flush()?;
        return Ok(0);
    }
    if args.tui {
        let selected = tui::run(args, model, cache_path)?;
        if let Some(hit) = selected {
            let counts = std::collections::BTreeMap::from([(hit.path.clone(), 1)]);
            let response = search::Response {
                query: String::new(),
                hits: vec![hit],
                counts,
                stats: search::Stats::default(),
            };
            let mut out = io::BufWriter::new(io::stdout().lock());
            print_response(&mut out, &response, args)?;
            out.flush()?;
            return Ok(0);
        }
        return Ok(1);
    }
    let cache = Cache::open(if args.no_cache {
        None
    } else {
        Some(&cache_path)
    })?;
    let mut searcher = Searcher::new(args, model, cache)?;
    let stdout = io::stdout();
    let mut out = io::BufWriter::new(stdout.lock());
    if let Some(command) = &args.command {
        return match command {
            Command::Skill | Command::Cache { .. } => {
                unreachable!("command handled before model setup")
            }
            Command::Index { paths, output } => {
                let path = if let Some(path) = output {
                    path.clone()
                } else {
                    index::default_path()?
                };
                let stats = searcher.build_index(paths, &path)?;
                serde_json::to_writer(
                    &mut out,
                    &serde_json::json!({"index": path, "stats": stats}),
                )?;
                writeln!(out)?;
                out.flush()?;
                Ok(0)
            }
            Command::Query { query, index } => {
                let response = searcher.search_index(query, index)?;
                let matched = response.matched(args);
                print_response(&mut out, &response, args)?;
                out.flush()?;
                Ok(u8::from(!matched))
            }
            Command::Watch { paths, index } => {
                let paths = if paths.is_empty() {
                    vec![PathBuf::from(".")]
                } else {
                    paths.clone()
                };
                let index = args
                    .index_path
                    .clone()
                    .or_else(|| index.clone())
                    .unwrap_or(index::default_path()?);
                let initial = searcher.build_index(&paths, &index)?;
                if !args.quiet {
                    serde_json::to_writer(
                        &mut out,
                        &serde_json::json!({"index": index, "stats": initial}),
                    )?;
                    writeln!(out)?;
                    out.flush()?;
                }
                for changed in watch::spawn(&paths, &index)? {
                    match changed.and_then(|_| searcher.build_index(&paths, &index)) {
                        Ok(stats) if !args.quiet => {
                            serde_json::to_writer(
                                &mut out,
                                &serde_json::json!({"index": index, "stats": stats}),
                            )?;
                            writeln!(out)?;
                            out.flush()?;
                        }
                        Ok(_) => {}
                        Err(error) => eprintln!("geg watch: incremental reindex failed: {error:#}"),
                    }
                }
                Ok(0)
            }
            Command::Mcp { .. } => unreachable!("mcp handled before model setup"),
        };
    }
    if args.interactive {
        ensure!(
            !args.paths.is_empty() && args.paths.iter().all(|p| p != std::path::Path::new("-")),
            "--interactive requires file/directory paths after '--'"
        );
        let mut reader = io::stdin().lock();
        let mut line = Vec::new();
        loop {
            line.clear();
            // Bound protocol frames too, not just file chunks.
            let n = std::io::Read::by_ref(&mut reader)
                .take(1026)
                .read_until(b'\n', &mut line)?;
            if n == 0 {
                break;
            }
            ensure!(n <= 1025, "interactive query line exceeds 1024 bytes");
            let query = std::str::from_utf8(&line)?.trim_end_matches(['\n', '\r']);
            match searcher.search(query) {
                Ok(response) => serde_json::to_writer(&mut out, &response)?,
                Err(error) => serde_json::to_writer(
                    &mut out,
                    &serde_json::json!({"query": query, "error": format!("{error:#}")}),
                )?,
            }
            writeln!(out)?;
            out.flush()?;
        }
        return Ok(0);
    }
    let query = args
        .query
        .as_deref()
        .context("provide a query or a subcommand (see --help)")?;
    let response = searcher.search(query)?;
    let matched = response.matched(args);
    print_response(&mut out, &response, args)?;
    out.flush()?;
    Ok(u8::from(!matched))
}

fn print_response(out: &mut impl Write, response: &search::Response, args: &Args) -> Result<()> {
    if args.quiet {
        return Ok(());
    }
    let filename = args.with_filename || (!args.no_filename && response.counts.len() > 1);
    if args.files_with_matches || args.files_without_match || args.count {
        for (path, &count) in &response.counts {
            if args.files_with_matches || args.files_without_match {
                if (args.files_with_matches && count > 0)
                    || (args.files_without_match && count == 0)
                {
                    writeln!(out, "{}", safe_text(path))?;
                }
            } else if filename {
                writeln!(out, "{}:{count}", safe_text(path))?;
            } else {
                writeln!(out, "{count}")?;
            }
        }
        return Ok(());
    }
    if !args.json && (args.pretty || args.format == "pretty") {
        return pretty::print(out, response, args);
    }
    if !args.json && args.format == "md" {
        if !response.hits.is_empty() {
            writeln!(out, "| path | line | symbol | score | text |")?;
            writeln!(out, "| --- | ---: | --- | ---: | --- |")?;
            for hit in &response.hits {
                writeln!(
                    out,
                    "| {} | {} | {} | {:.4} | {} |",
                    markdown_cell(&hit.path),
                    hit.line,
                    markdown_cell(&hit.symbol),
                    hit.score,
                    markdown_cell(hit.text.trim_end())
                )?;
                if args.line_buffered {
                    out.flush()?;
                }
            }
        }
        return Ok(());
    }
    for hit in &response.hits {
        if args.json {
            serde_json::to_writer(&mut *out, hit)?;
            writeln!(out)?;
            if args.line_buffered {
                out.flush()?;
            }
        } else {
            for (offset, line) in hit.text.lines().enumerate() {
                if filename {
                    write!(out, "{}:", safe_text(&hit.path))?;
                }
                if args.line_number {
                    write!(out, "{}:", hit.line + offset as u64)?;
                }
                if args.score {
                    write!(out, "{:.4}:", hit.score)?;
                }
                writeln!(out, "{}", safe_text(line))?;
                if args.line_buffered {
                    out.flush()?;
                }
            }
        }
    }
    Ok(())
}

fn markdown_cell(text: &str) -> String {
    let mut escaped = String::with_capacity(text.len());
    for c in text.chars() {
        match c {
            '&' => escaped.push_str("&amp;"),
            '<' => escaped.push_str("&lt;"),
            '>' => escaped.push_str("&gt;"),
            '|' => escaped.push_str("&#124;"),
            '`' => escaped.push_str("&#96;"),
            '\\' => escaped.push_str("&#92;"),
            '*' => escaped.push_str("&#42;"),
            '_' => escaped.push_str("&#95;"),
            '[' => escaped.push_str("&#91;"),
            ']' => escaped.push_str("&#93;"),
            '\n' => escaped.push_str("<br>"),
            '\r' => {}
            '\t' => escaped.push_str("    "),
            c if c.is_control() => escaped.extend(c.escape_default()),
            c => escaped.push(c),
        }
    }
    escaped
}

fn safe_text(text: &str) -> String {
    let mut escaped = String::with_capacity(text.len());
    for c in text.chars() {
        if c.is_control() && c != '\t' {
            escaped.extend(c.escape_default());
        } else {
            escaped.push(c);
        }
    }
    escaped
}

fn normalize_args(args: &mut Args) -> Result<()> {
    if args.command.is_some() {
        return Ok(());
    }
    if args.query.is_none()
        && args.paths.is_empty()
        && !args.interactive
        && args.patterns.is_empty()
        && args.pattern_files.is_empty()
        && io::stdin().is_terminal()
        && io::stderr().is_terminal()
        && !args.quiet
        && !args.count
        && !args.files_with_matches
        && !args.files_without_match
    {
        args.tui = true;
        args.paths.push(PathBuf::from("."));
    }
    if args.interactive {
        ensure!(
            args.patterns.is_empty() && args.pattern_files.is_empty(),
            "--interactive cannot be combined with -e/-f"
        );
        if let Some(path) = args.query.take() {
            args.paths.insert(0, PathBuf::from(path));
        }
    } else if !args.patterns.is_empty() || !args.pattern_files.is_empty() {
        if let Some(path) = args.query.take() {
            args.paths.insert(0, PathBuf::from(path));
        }
        let mut patterns = args.patterns.clone();
        for path in &args.pattern_files {
            let mut text = String::new();
            if path == std::path::Path::new("-") {
                io::Read::take(io::stdin().lock(), 65537).read_to_string(&mut text)?;
            } else {
                io::Read::take(std::fs::File::open(path)?, 65537).read_to_string(&mut text)?;
            }
            ensure!(text.len() <= 65536, "query file exceeds 64 KiB");
            patterns.extend(text.lines().map(str::to_owned));
        }
        args.query = Some(patterns.join("\n"));
    }
    if args.paths.is_empty() && (args.recursive || args.dereference_recursive) {
        args.paths.push(PathBuf::from("."));
    }
    Ok(())
}

fn main() -> ExitCode {
    let matches = Args::command().get_matches();
    let mut args = match Args::from_arg_matches(&matches) {
        Ok(args) => args,
        Err(error) => error.exit(),
    };
    let result = run(&mut args, &matches);
    if result.is_ok()
        && (args.query.is_some() || args.command.is_some() || args.tui || args.interactive)
        && !matches!(
            args.command,
            Some(Command::Skill | Command::Mcp { .. } | Command::Watch { .. })
        )
        && let Ok(root) = cache_dir()
    {
        let path = args
            .cache
            .clone()
            .unwrap_or_else(|| root.join("vectors.sqlite3"));
        cache_management::warn(&root, &path, &args);
    }
    match result {
        Ok(code) => ExitCode::from(code),
        Err(error)
            if error
                .downcast_ref::<io::Error>()
                .is_some_and(|e| e.kind() == io::ErrorKind::BrokenPipe) =>
        {
            ExitCode::SUCCESS
        }
        Err(error) => {
            if !args.no_messages {
                eprintln!("geg: {error:#}");
            }
            ExitCode::from(2)
        }
    }
}