pixie-pi 0.1.0

pixie-pi — an AI coding agent (read/write/edit/bash/grep/find/ls tools) for the command line and an interactive REPL.
Documentation
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
//! `grep` tool — search file contents (gitignore-aware, in-process).

use std::collections::HashSet;
use std::path::{Path, PathBuf};

use async_trait::async_trait;
use serde::Deserialize;
use serde_json::{json, Value};
use tokio_util::sync::CancellationToken;

use crate::agent::tool::{AgentTool, ToolResult};
use crate::tools::truncate::{
    format_size, truncate_head, truncate_line, DEFAULT_MAX_BYTES, GREP_MAX_LINE_LENGTH,
};
use crate::tools::util::{display_path, resolve_to_cwd};

const DEFAULT_MATCH_LIMIT: usize = 100;

pub struct GrepTool {
    pub cwd: PathBuf,
}

#[derive(Debug, Deserialize)]
struct GrepInput {
    pattern: String,
    #[serde(default)]
    path: Option<String>,
    #[serde(default)]
    glob: Option<String>,
    #[serde(default)]
    ignore_case: Option<bool>,
    #[serde(default)]
    literal: Option<bool>,
    #[serde(default)]
    context: Option<usize>,
    #[serde(default)]
    limit: Option<usize>,
}

#[async_trait]
impl AgentTool for GrepTool {
    fn name(&self) -> &str {
        "grep"
    }
    fn description(&self) -> &str {
        "Search file contents for a pattern. Returns matching lines with file paths and line numbers. Respects .gitignore. Output is truncated to 100 matches or 50KB (whichever is hit first). Long lines are truncated to 500 chars."
    }
    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "pattern": { "type": "string", "description": "Search pattern (regex or literal string)" },
                "path": { "type": "string", "description": "Directory or file to search (default: current directory)" },
                "glob": { "type": "string", "description": "Filter files by glob pattern, e.g. '*.ts' or '**/*.spec.ts'" },
                "ignoreCase": { "type": "boolean", "description": "Case-insensitive search (default: false)" },
                "literal": { "type": "boolean", "description": "Treat pattern as a literal string instead of regex (default: false)" },
                "context": { "type": "number", "description": "Number of lines to show before and after each match (default: 0)" },
                "limit": { "type": "number", "description": "Maximum number of matches to return (default: 100)" }
            },
            "required": ["pattern"]
        })
    }

    async fn execute(&self, args: Value, _cancel: CancellationToken) -> anyhow::Result<ToolResult> {
        let input: GrepInput = serde_json::from_value(args)?;
        let effective_limit = input.limit.unwrap_or(DEFAULT_MATCH_LIMIT).max(1);
        let context = input.context.unwrap_or(0);

        let pattern = if input.literal.unwrap_or(false) {
            regex::escape(&input.pattern)
        } else {
            input.pattern.clone()
        };
        let re = regex::RegexBuilder::new(&pattern)
            .case_insensitive(input.ignore_case.unwrap_or(false))
            .build()
            .map_err(|e| anyhow::anyhow!("Invalid regex pattern: {e}"))?;

        let search_path = resolve_to_cwd(input.path.as_deref().unwrap_or("."), &self.cwd);
        if !search_path.exists() {
            anyhow::bail!("Path not found: {}", display_path(input.path.as_deref().unwrap_or("."), &self.cwd));
        }
        let is_dir = search_path.is_dir();

        let glob_matcher = match input.glob.as_deref() {
            Some(g) => Some(
                globset::Glob::new(g)
                    .map_err(|e| anyhow::anyhow!("Invalid glob: {e}"))?
                    .compile_matcher(),
            ),
            None => None,
        };

        let files = collect_files(&search_path);
        let mut out_lines: Vec<String> = Vec::new();
        let mut match_count = 0usize;
        let mut match_limit_reached = false;
        let mut lines_truncated = false;

        'outer: for file in files {
            if let Some(gm) = &glob_matcher {
                let rel = file.strip_prefix(&search_path).unwrap_or(&file).to_string_lossy().to_string();
                let base = file
                    .file_name()
                    .map(|n| n.to_string_lossy().to_string())
                    .unwrap_or_default();
                if !gm.is_match(&rel) && !gm.is_match(&base) {
                    continue;
                }
            }
            let Ok(text) = std::fs::read_to_string(&file) else {
                continue;
            };
            let normalized = text.replace("\r\n", "\n").replace('\r', "\n");
            let lines: Vec<&str> = normalized.split('\n').collect();
            let display = display_for(&file, &search_path, is_dir);

            // Collect this file's matching line indices first (honoring the
            // global match limit) so context lines are emitted only once even
            // when matches are close together. The previous per-match loop
            // re-emitted overlapping context lines — and even re-emitted a
            // shared match line — whenever two matches sat within `2*context`
            // lines of each other.
            let mut match_indices: Vec<usize> = Vec::new();
            for (i, line) in lines.iter().enumerate() {
                if re.is_match(line) {
                    match_count += 1;
                    match_indices.push(i);
                    if match_count > effective_limit {
                        match_limit_reached = true;
                        break;
                    }
                }
            }

            // We probe one match past the limit so "exactly N matches" is
            // distinguishable from "more than N" (the limit notice must not fire
            // when nothing was actually held back). That extra match lands in
            // `match_indices`; if it pushed us over the global limit, drop it —
            // and any surplus in this file — so exactly `effective_limit` matches
            // are emitted total. `match_count - match_indices.len()` is the number
            // of matches already emitted from earlier files.
            if match_limit_reached {
                let emitted_before = match_count - match_indices.len();
                match_indices.truncate(effective_limit.saturating_sub(emitted_before));
            }

            if context == 0 {
                for &i in &match_indices {
                    let (truncated, was) = truncate_line(lines[i], None);
                    if was {
                        lines_truncated = true;
                    }
                    out_lines.push(format!("{}:{}: {}", display, i + 1, truncated));
                }
            } else if !match_indices.is_empty() {
                let is_match: HashSet<usize> = match_indices.iter().copied().collect();
                let n = lines.len();
                // Merge the [i-context, i+context] windows around each match
                // into maximal disjoint runs (overlapping or adjacent windows
                // coalesce), mirroring `grep -C`. Emit each covered line once —
                // matches with ':', context with '-' — with a "--" separator
                // between disjoint groups.
                let mut groups: Vec<(usize, usize)> = Vec::new();
                for &i in &match_indices {
                    let start = i.saturating_sub(context);
                    let end = (i + context).min(n.saturating_sub(1));
                    match groups.last_mut() {
                        Some((_, prev_end)) if start <= *prev_end + 1 => {
                            *prev_end = (*prev_end).max(end);
                        }
                        _ => groups.push((start, end)),
                    }
                }
                for (gi, (start, end)) in groups.iter().enumerate() {
                    if gi > 0 {
                        out_lines.push("--".to_string());
                    }
                    for (offset, line) in lines[*start..=*end].iter().enumerate() {
                        let c = start + offset;
                        let (truncated, was) = truncate_line(line, None);
                        if was {
                            lines_truncated = true;
                        }
                        if is_match.contains(&c) {
                            out_lines.push(format!("{}:{}: {}", display, c + 1, truncated));
                        } else {
                            out_lines.push(format!("{}-{}- {}", display, c + 1, truncated));
                        }
                    }
                }
            }

            if match_limit_reached {
                break 'outer;
            }
        }

        if match_count == 0 {
            return Ok(ToolResult::text("No matches found"));
        }

        let raw = out_lines.join("\n");
        let trunc = truncate_head(&raw, None, None);
        let mut output = trunc.content;
        let mut notices: Vec<String> = Vec::new();
        if match_limit_reached {
            notices.push(format!(
                "{effective_limit} matches limit reached. Use limit={} for more, or refine pattern",
                effective_limit * 2
            ));
        }
        if trunc.truncated {
            notices.push(format!("{} limit reached", format_size(DEFAULT_MAX_BYTES)));
        }
        if lines_truncated {
            notices.push(format!(
                "Some lines truncated to {GREP_MAX_LINE_LENGTH} chars. Use read tool to see full lines"
            ));
        }
        if !notices.is_empty() {
            output.push_str(&format!("\n\n[{}]", notices.join(". ")));
        }

        Ok(ToolResult::text(output))
    }
}

/// Walk `root` (gitignore-aware, including hidden files) and return file paths.
fn collect_files(root: &Path) -> Vec<PathBuf> {
    let mut files = Vec::new();
    if root.is_file() {
        files.push(root.to_path_buf());
        return files;
    }
    let walker = ignore::WalkBuilder::new(root)
        .hidden(false)
        .git_ignore(true)
        .git_global(true)
        .parents(true)
        .build();
    for entry in walker.flatten() {
        if entry.file_type().map(|t| t.is_file()).unwrap_or(false) {
            files.push(entry.into_path());
        }
    }
    files
}

fn display_for(file: &Path, search_root: &Path, is_dir: bool) -> String {
    if is_dir {
        if let Ok(rel) = file.strip_prefix(search_root) {
            let s = rel.to_string_lossy().replace('\\', "/");
            if s.is_empty() {
                return file
                    .file_name()
                    .map(|n| n.to_string_lossy().to_string())
                    .unwrap_or_default();
            }
            return s;
        }
    }
    file.file_name()
        .map(|n| n.to_string_lossy().to_string())
        .unwrap_or_default()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::tool::AgentTool;
    use tokio_util::sync::CancellationToken;

    fn scratch_dir(label: &str) -> PathBuf {
        let dir = std::env::temp_dir()
            .join(format!("pi-grep-test-{label}-{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    async fn run_grep(cwd: PathBuf, args: serde_json::Value) -> String {
        let tool = GrepTool { cwd };
        let res = tool.execute(args, CancellationToken::new()).await.unwrap();
        match res.content.into_iter().next() {
            Some(crate::ai::types::ToolResultContent::Text { text }) => text,
            _ => panic!("expected text tool result"),
        }
    }

    #[tokio::test]
    async fn context_merges_overlapping_windows_no_duplicates() {
        // Two matches on adjacent lines; with context=1 their windows overlap.
        // The previous per-match loop emitted each covered line twice (a match
        // line re-appeared as a "-" context line for its neighbor). The merged
        // output must list every line exactly once.
        let dir = scratch_dir("adjacent");
        std::fs::write(dir.join("f.txt"), "a\nb\nMATCH\nMATCH\nc\nd\n").unwrap();

        let out = run_grep(
            dir.clone(),
            serde_json::json!({ "pattern": "MATCH", "path": dir.to_string_lossy(), "context": 1 }),
        )
        .await;

        let body: Vec<&str> = out.lines().filter(|l| !l.is_empty()).collect();
        assert_eq!(
            body,
            vec![
                "f.txt-2- b",
                "f.txt:3: MATCH",
                "f.txt:4: MATCH",
                "f.txt-5- c",
            ],
            "adjacent matches should merge into one group with no duplicates"
        );
        // Coalesced groups carry no separator.
        assert!(!out.contains("\n--\n"));

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[tokio::test]
    async fn context_separates_disjoint_groups() {
        // Two matches far apart produce two disjoint groups joined by "--",
        // each line emitted once.
        let dir = scratch_dir("disjoint");
        std::fs::write(dir.join("f.txt"), "MATCH\nx\nx\nx\nx\nx\nx\nx\nMATCH\n").unwrap();

        let out = run_grep(
            dir.clone(),
            serde_json::json!({ "pattern": "MATCH", "path": dir.to_string_lossy(), "context": 1 }),
        )
        .await;

        assert!(
            out.contains("\n--\n"),
            "disjoint groups should be separated by --\n{out}"
        );
        // Each match line appears exactly once.
        assert_eq!(out.matches(":1:").count(), 1);
        assert_eq!(out.matches(":9:").count(), 1);

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[tokio::test]
    async fn limit_not_reported_when_matches_equal_limit_exactly() {
        // Exactly `limit` matches exist → all are shown, and the "limit reached"
        // notice must NOT fire (nothing was held back).
        let dir = scratch_dir("at-limit");
        std::fs::write(dir.join("f.txt"), "MATCH\nMATCH\nMATCH\n").unwrap();

        let out = run_grep(
            dir.clone(),
            serde_json::json!({ "pattern": "MATCH", "path": dir.to_string_lossy(), "limit": 3 }),
        )
        .await;

        assert_eq!(out.matches("f.txt:").count(), 3, "all 3 matches shown");
        assert!(
            !out.contains("limit reached"),
            "no false-positive limit notice\n{out}"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[tokio::test]
    async fn limit_reported_and_capped_when_matches_exceed_limit() {
        // One more match than the limit → notice fires and exactly `limit`
        // matches are emitted (no off-by-one in the straddling file).
        let dir = scratch_dir("over-limit");
        std::fs::write(dir.join("f.txt"), "MATCH\nMATCH\nMATCH\nMATCH\n").unwrap();

        let out = run_grep(
            dir.clone(),
            serde_json::json!({ "pattern": "MATCH", "path": dir.to_string_lossy(), "limit": 3 }),
        )
        .await;

        assert_eq!(out.matches("f.txt:").count(), 3, "exactly 3 matches shown");
        assert!(
            out.contains("limit reached"),
            "truncation notice present\n{out}"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[tokio::test]
    async fn limit_straddling_two_files_emits_exactly_limit() {
        // The limit is crossed inside the second file. Exactly `limit` matches
        // must be emitted across both files — this is the case the per-file
        // truncation math is really for.
        let dir = scratch_dir("straddle");
        std::fs::write(dir.join("a.txt"), "MATCH\nMATCH\n").unwrap();
        std::fs::write(dir.join("b.txt"), "MATCH\nMATCH\n").unwrap();

        let out = run_grep(
            dir.clone(),
            serde_json::json!({ "pattern": "MATCH", "path": dir.to_string_lossy(), "limit": 3 }),
        )
        .await;

        assert_eq!(
            out.matches(".txt:").count(),
            3,
            "exactly 3 matches across both files\n{out}"
        );
        assert!(
            out.contains("limit reached"),
            "truncation notice present\n{out}"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }
}