feat(tools): upgrade host file, edit, glob, and grep primitives with image reads and streaming bounds

This commit is contained in:
Sycun 2026-11-29 22:29:37 +08:00
parent 0677d5fa87
commit 5212870e9c
3 changed files with 562 additions and 30 deletions

View File

@ -318,7 +318,7 @@ func TestPiDeepSeekEconomyDiscoversToolsAndReadsFullEvidence(t *testing.T) {
t.Logf("tool result bytes: full=%d preview=%d", len(full)+1, len(preview))
piReply(w, "read_file", "read", map[string]any{"path": originalPath, "offset": 151, "limit": 1}, "")
case 4:
if got := body.Messages[len(body.Messages)-1].Content; got != "MIDDLE_EVIDENCE" {
if got, _ := body.Messages[len(body.Messages)-1].Content.(string); !strings.Contains(got, "MIDDLE_EVIDENCE") {
t.Errorf("evidence readback=%q", got)
}
piReply(w, "", "", nil, "verified middle evidence")

View File

@ -1,11 +1,18 @@
package multiagent
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"io"
"io/fs"
"net/http"
"os"
"os/exec"
"path/filepath"
@ -20,6 +27,9 @@ import (
"cyberstrike-ai/internal/security"
"cyberstrike-ai/internal/skillpackage"
"cyberstrike-ai/internal/tooloutput"
"github.com/disintegration/imaging"
_ "golang.org/x/image/webp"
)
// piLocalCatalog is explicit host registration: Pi never receives default host filesystem tools.
@ -53,12 +63,12 @@ func (r *piRun) piLocalCatalog(ctx context.Context) ([]agentruntime.Tool, map[st
}
if r.cfg.MultiAgent.Skills.FilesystemToolsEffective() && !localToolPermissionDenied(ctx, "execute") {
for _, t := range []agentruntime.Tool{
{Name: "read_file", Description: "Read a text file, optionally selecting a 1-based line offset and line limit", Parameters: piToolSchema(map[string]any{"path": str, "offset": map[string]any{"type": "integer", "minimum": 1}, "limit": map[string]any{"type": "integer", "minimum": 1}}, "path")},
{Name: "write_file", Description: "Write UTF-8 text to a file", Parameters: piToolSchema(map[string]any{"path": str, "content": str}, "path", "content")},
{Name: "edit_file", Description: "Replace one exact occurrence in a text file; ambiguous matches fail", Parameters: piToolSchema(map[string]any{"path": str, "old_text": str, "new_text": str}, "path", "old_text", "new_text")},
{Name: "read_file", Description: "Read a text file with 1-based line offset/limit pagination, or return a supported image (png/jpeg/gif/webp) for vision models", Parameters: piToolSchema(map[string]any{"path": str, "offset": map[string]any{"type": "integer", "minimum": 1}, "limit": map[string]any{"type": "integer", "minimum": 1, "maximum": 2000}}, "path")},
{Name: "write_file", Description: "Write UTF-8 text to a file, creating parent directories as needed", Parameters: piToolSchema(map[string]any{"path": str, "content": str}, "path", "content")},
{Name: "edit_file", Description: "Replace exact text in a file; supports one old_text/new_text pair or a batch edits array, preserves CRLF, and returns a change summary", Parameters: piToolSchema(map[string]any{"path": str, "old_text": str, "new_text": str, "edits": map[string]any{"type": "array", "items": map[string]any{"type": "object", "properties": map[string]any{"old_text": str, "new_text": str}, "required": []string{"old_text", "new_text"}}}}, "path")},
{Name: "ls", Description: "List directory entries", Parameters: piToolSchema(map[string]any{"path": str}, "path")},
{Name: "glob", Description: "Find files recursively by a filename glob under a directory", Parameters: piToolSchema(map[string]any{"path": str, "pattern": str}, "path", "pattern")},
{Name: "grep", Description: "Search UTF-8 files recursively with a regular expression", Parameters: piToolSchema(map[string]any{"path": str, "pattern": str}, "path", "pattern")},
{Name: "glob", Description: "Find files recursively by glob; supports filename patterns and path patterns with ** and subdirectory wildcards", Parameters: piToolSchema(map[string]any{"path": str, "pattern": str}, "path", "pattern")},
{Name: "grep", Description: "Search UTF-8 files recursively with a regular expression; skips binary files and truncates long lines", Parameters: piToolSchema(map[string]any{"path": str, "pattern": str, "include": str}, "path", "pattern")},
{Name: "execute", Description: "Execute a shell command in the host task context with bounded output and process-tree cancellation", Parameters: piToolSchema(map[string]any{"command": str, "cwd": str}, "command")},
} {
tools = append(tools, t)
@ -251,31 +261,60 @@ func (r *piRun) executePiLocal(ctx context.Context, call agentruntime.ToolCall)
if !st.Mode().IsRegular() {
return result, fmt.Errorf("not a regular file")
}
b, err := io.ReadAll(io.LimitReader(f, 2*1024*1024+1))
if err != nil {
return result, err
if img, ok, err := readPiLocalImage(path, f, st.Size()); ok {
return img, err
}
if len(b) > 2*1024*1024 {
return result, fmt.Errorf("file exceeds 2 MiB; use execute to select a smaller region")
}
lines := strings.Split(string(b), "\n")
offset, limit := 1, 1000
if n, ok := call.Arguments["offset"].(float64); ok && n >= 1 {
offset = int(n)
}
if n, ok := call.Arguments["limit"].(float64); ok && n > 0 && n < 10000 {
if n, ok := call.Arguments["limit"].(float64); ok && n > 0 {
limit = int(n)
if limit > 2000 {
limit = 2000
}
}
if offset > len(lines) {
reader := bufio.NewReaderSize(f, 64*1024)
var out strings.Builder
lineNo, emitted, budget := 0, 0, 64*1024
anyTrunc, hitBudget := false, false
for {
line, trunc, err := readPiCappedLine(reader, 4096)
if err == io.EOF {
break
}
if err != nil {
return result, err
}
lineNo++
if lineNo < offset || emitted >= limit || hitBudget {
continue
}
text := line
if trunc {
text += " [line truncated]"
anyTrunc = true
}
if out.Len()+len(text)+1 > budget {
hitBudget = true
continue
}
if emitted > 0 {
out.WriteByte('\n')
}
out.WriteString(text)
emitted++
}
if emitted == 0 {
return result, nil
}
end := offset - 1 + limit
if end > len(lines) {
end = len(lines)
if anyTrunc || hitBudget || offset+emitted-1 < lineNo {
out.WriteString(fmt.Sprintf("\n[lines %d-%d of %d; next offset %d]", offset, offset+emitted-1, lineNo, offset+emitted))
}
result.Content = strings.Join(lines[offset-1:end], "\n")
result.Content = out.String()
case "write_file", "edit_file":
content := arg("content")
unlock := lockPiFilePath(path)
defer unlock()
mode := os.FileMode(0o600)
if st, err := os.Stat(path); err == nil {
if !st.Mode().IsRegular() {
@ -283,21 +322,26 @@ func (r *piRun) executePiLocal(ctx context.Context, call agentruntime.ToolCall)
}
mode = st.Mode().Perm()
}
var content string
if call.Name == "edit_file" {
b, err := os.ReadFile(path)
updated, summary, err := applyPiFileEdits(path, call.Arguments)
if err != nil {
return result, err
}
old := arg("old_text")
if old == "" || strings.Count(string(b), old) != 1 {
return result, fmt.Errorf("old_text must match exactly once")
content = updated
result.Content = summary
} else {
content = arg("content")
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return result, err
}
content = strings.Replace(string(b), old, arg("new_text"), 1)
}
if err := os.WriteFile(path, []byte(content), mode); err != nil {
return result, err
}
result.Content = "Updated " + path
if call.Name == "write_file" {
result.Content = "Updated " + path
}
case "ls":
entries, err := os.ReadDir(path)
if err != nil {
@ -322,6 +366,9 @@ func (r *piRun) executePiLocal(ctx context.Context, call agentruntime.ToolCall)
return result, err
}
}
include := arg("include")
globPattern := strings.TrimPrefix(pattern, "./")
globByPath := strings.Contains(globPattern, "/")
var hits []string
err := filepath.WalkDir(path, func(p string, d fs.DirEntry, err error) error {
if ctx.Err() != nil {
@ -343,15 +390,34 @@ func (r *piRun) executePiLocal(ctx context.Context, call agentruntime.ToolCall)
return nil
}
if call.Name == "glob" {
matched, e := filepath.Match(pattern, d.Name())
if e != nil {
return e
var matched bool
if globByPath {
rel, e := filepath.Rel(path, p)
if e != nil {
return e
}
matched = piGlobMatchPath(globPattern, filepath.ToSlash(rel))
} else {
var e error
matched, e = filepath.Match(globPattern, d.Name())
if e != nil {
return e
}
}
if matched {
hits = append(hits, p)
}
return nil
}
if include != "" {
ok, e := filepath.Match(include, d.Name())
if e != nil {
return e
}
if !ok {
return nil
}
}
st, e := d.Info()
if e != nil || !st.Mode().IsRegular() || st.Size() > 2*1024*1024 {
return nil
@ -360,9 +426,12 @@ func (r *piRun) executePiLocal(ctx context.Context, call agentruntime.ToolCall)
if e != nil {
return e
}
if bytes.IndexByte(b[:min(512, len(b))], 0) >= 0 {
return nil
}
for i, line := range strings.Split(string(b), "\n") {
if re.MatchString(line) {
hits = append(hits, fmt.Sprintf("%s:%d:%s", p, i+1, line))
hits = append(hits, fmt.Sprintf("%s:%d:%s", p, i+1, truncatePiRunes(line, 500)))
if len(hits) >= 1000 {
break
}
@ -380,3 +449,250 @@ func (r *piRun) executePiLocal(ctx context.Context, call agentruntime.ToolCall)
result.ExecutionID = r.ag.FinishLocalToolExecution(ctx, "", call.Name, call.Arguments, result.Content, nil)
return result, nil
}
var piFileLocks sync.Map
func lockPiFilePath(path string) func() {
v, _ := piFileLocks.LoadOrStore(path, &sync.Mutex{})
mu := v.(*sync.Mutex)
mu.Lock()
return mu.Unlock
}
func readPiCappedLine(r *bufio.Reader, cap int) (string, bool, error) {
var parts []byte
trunc := false
for {
frag, isPrefix, err := r.ReadLine()
if err != nil {
return "", false, err
}
if !trunc {
room := cap - len(parts)
if len(frag) <= room {
parts = append(parts, frag...)
} else {
if room > 0 {
parts = append(parts, frag[:room]...)
}
trunc = true
}
}
if !isPrefix {
return string(parts), trunc, nil
}
}
}
func readPiLocalImage(path string, f *os.File, size int64) (agentruntime.ToolResult, bool, error) {
header := make([]byte, 512)
n, _ := io.ReadFull(f, header)
mime := http.DetectContentType(header[:n])
if _, err := f.Seek(0, io.SeekStart); err != nil {
return agentruntime.ToolResult{}, false, err
}
switch mime {
case "image/png", "image/jpeg", "image/gif", "image/webp":
default:
return agentruntime.ToolResult{}, false, nil
}
if size > 10*1024*1024 {
return agentruntime.ToolResult{}, true, fmt.Errorf("image exceeds 10 MiB")
}
cfg, _, err := image.DecodeConfig(f)
if err != nil {
return agentruntime.ToolResult{}, true, fmt.Errorf("decode image: %w", err)
}
if _, err := f.Seek(0, io.SeekStart); err != nil {
return agentruntime.ToolResult{}, true, err
}
raw, err := io.ReadAll(io.LimitReader(f, 10*1024*1024+1))
if err != nil {
return agentruntime.ToolResult{}, true, err
}
out, outMIME := raw, mime
if len(raw) > 4*1024*1024 || cfg.Width > 4096 || cfg.Height > 4096 {
compressed, err := compressPiImage(raw)
if err != nil {
return agentruntime.ToolResult{}, true, err
}
out, outMIME = compressed, "image/jpeg"
}
return agentruntime.ToolResult{
Content: fmt.Sprintf("[Image %s (%s, %d bytes)]", path, outMIME, len(out)),
Images: []agentruntime.Image{{MIMEType: outMIME, Data: out}},
}, true, nil
}
func compressPiImage(raw []byte) ([]byte, error) {
src, err := imaging.Decode(bytes.NewReader(raw))
if err != nil {
return nil, err
}
dim := 2048
dst := imaging.Fit(src, dim, dim, imaging.Lanczos)
for attempt := 0; attempt < 6; attempt++ {
if attempt > 0 {
dim = int(float64(dim) * 0.85)
if dim < 256 {
dim = 256
}
dst = imaging.Fit(src, dim, dim, imaging.Lanczos)
}
for q := 85; q >= 55; q -= 10 {
var buf bytes.Buffer
if err := imaging.Encode(&buf, dst, imaging.JPEG, imaging.JPEGQuality(q)); err != nil {
return nil, err
}
if buf.Len() <= 4*1024*1024 {
return buf.Bytes(), nil
}
}
}
return nil, fmt.Errorf("could not compress image under 4 MiB")
}
func applyPiFileEdits(path string, args map[string]any) (string, string, error) {
b, err := os.ReadFile(path)
if err != nil {
return "", "", err
}
orig := string(b)
crlf := strings.Contains(orig, "\r\n")
norm := strings.ReplaceAll(orig, "\r\n", "\n")
type piEdit struct{ old, new string }
var edits []piEdit
if raw, ok := args["edits"].([]any); ok && len(raw) > 0 {
for _, item := range raw {
m, ok := item.(map[string]any)
if !ok {
return "", "", fmt.Errorf("edits entries must be objects")
}
o, _ := m["old_text"].(string)
n, _ := m["new_text"].(string)
edits = append(edits, piEdit{o, n})
}
} else {
o, _ := args["old_text"].(string)
n, _ := args["new_text"].(string)
edits = append(edits, piEdit{o, n})
}
current := norm
for _, e := range edits {
oldNorm := strings.ReplaceAll(e.old, "\r\n", "\n")
newNorm := strings.ReplaceAll(e.new, "\r\n", "\n")
if oldNorm == "" {
return "", "", fmt.Errorf("old_text must not be empty")
}
current, err = replacePiUnique(current, oldNorm, newNorm)
if err != nil {
return "", "", err
}
}
final := current
if crlf {
final = strings.ReplaceAll(current, "\n", "\r\n")
}
return final, piEditSummary(path, norm, current), nil
}
func replacePiUnique(content, old, new string) (string, error) {
if strings.Count(content, old) == 1 {
return strings.Replace(content, old, new, 1), nil
}
lines := strings.Split(old, "\n")
parts := make([]string, len(lines))
for i, l := range lines {
parts[i] = regexp.QuoteMeta(strings.TrimRight(l, " \t"))
}
re, err := regexp.Compile(strings.Join(parts, "[ \t]*\n") + "[ \t]*")
if err != nil {
return "", err
}
locs := re.FindAllStringIndex(content, -1)
if len(locs) != 1 {
return "", fmt.Errorf("old_text must match exactly once (found %d)", len(locs))
}
loc := locs[0]
return content[:loc[0]] + new + content[loc[1]:], nil
}
func piEditSummary(path, oldNorm, newNorm string) string {
if oldNorm == newNorm {
return "Updated " + path + " (no line changes)"
}
oldLines := strings.Split(oldNorm, "\n")
newLines := strings.Split(newNorm, "\n")
prefix := 0
for prefix < len(oldLines) && prefix < len(newLines) && oldLines[prefix] == newLines[prefix] {
prefix++
}
suffix := 0
for suffix < len(oldLines)-prefix && suffix < len(newLines)-prefix && oldLines[len(oldLines)-1-suffix] == newLines[len(newLines)-1-suffix] {
suffix++
}
var b strings.Builder
fmt.Fprintf(&b, "Updated %s (first changed line %d)\n", path, prefix+1)
ctxStart := prefix - 2
if ctxStart < 0 {
ctxStart = 0
}
for i := ctxStart; i < prefix; i++ {
b.WriteString(" " + oldLines[i] + "\n")
}
oldMid := oldLines[prefix : len(oldLines)-suffix]
newMid := newLines[prefix : len(newLines)-suffix]
for i, l := range oldMid {
if i >= 16 {
b.WriteString("-...\n")
break
}
b.WriteString("-" + l + "\n")
}
for i, l := range newMid {
if i >= 16 {
b.WriteString("+...\n")
break
}
b.WriteString("+" + l + "\n")
}
afterStart := len(newLines) - suffix
for i := afterStart; i < afterStart+2 && i < len(newLines); i++ {
b.WriteString(" " + newLines[i] + "\n")
}
return strings.TrimRight(b.String(), "\n")
}
func piGlobMatchPath(pattern, rel string) bool {
return piMatchSegments(strings.Split(pattern, "/"), strings.Split(rel, "/"))
}
func piMatchSegments(pat, path []string) bool {
if len(pat) == 0 {
return len(path) == 0
}
if pat[0] == "**" {
for i := 0; i <= len(path); i++ {
if piMatchSegments(pat[1:], path[i:]) {
return true
}
}
return false
}
if len(path) == 0 {
return false
}
ok, err := filepath.Match(pat[0], path[0])
if err != nil || !ok {
return false
}
return piMatchSegments(pat[1:], path[1:])
}
func truncatePiRunes(s string, n int) string {
r := []rune(s)
if len(r) <= n {
return s
}
return string(r[:n]) + "... [truncated]"
}

View File

@ -0,0 +1,216 @@
package multiagent
import (
"bytes"
"context"
"image"
"image/png"
"os"
"path/filepath"
"strings"
"testing"
"cyberstrike-ai/internal/agent"
"cyberstrike-ai/internal/agentruntime"
"cyberstrike-ai/internal/config"
"cyberstrike-ai/internal/mcp"
"go.uber.org/zap"
)
func localToolsFixture(t *testing.T) *piRun {
t.Helper()
cfg := &config.Config{}
srv := mcp.NewServer(zap.NewNop())
ag := agent.NewAgent(&cfg.OpenAI, &cfg.Agent, srv, nil, zap.NewNop(), 2)
return &piRun{cfg: cfg, ag: ag, conversationID: "local-tools"}
}
func callLocal(t *testing.T, r *piRun, name string, args map[string]any) agentruntime.ToolResult {
t.Helper()
res, err := r.executePiLocal(context.Background(), agentruntime.ToolCall{Name: name, Arguments: args})
if err != nil {
t.Fatalf("%s: %v", name, err)
}
return res
}
func TestPiReadFileReturnsImageForVisionModels(t *testing.T) {
r := localToolsFixture(t)
dir := t.TempDir()
img := image.NewRGBA(image.Rect(0, 0, 4, 4))
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
t.Fatal(err)
}
path := filepath.Join(dir, "pic.png")
if err := os.WriteFile(path, buf.Bytes(), 0o600); err != nil {
t.Fatal(err)
}
res := callLocal(t, r, "read_file", map[string]any{"path": path})
if len(res.Images) != 1 {
t.Fatalf("expected one image, got %+v", res)
}
if res.Images[0].MIMEType != "image/png" || !bytes.Equal(res.Images[0].Data, buf.Bytes()) {
t.Fatalf("image payload mismatch: mime=%s bytes=%d", res.Images[0].MIMEType, len(res.Images[0].Data))
}
if !strings.Contains(res.Content, "[Image ") || !strings.Contains(res.Content, "image/png") {
t.Fatalf("content summary missing: %q", res.Content)
}
fake := filepath.Join(dir, "fake.png")
if err := os.WriteFile(fake, []byte("just text, not an image"), 0o600); err != nil {
t.Fatal(err)
}
textRes := callLocal(t, r, "read_file", map[string]any{"path": fake})
if len(textRes.Images) != 0 || textRes.Content != "just text, not an image" {
t.Fatalf("disguised text must read as text: %+v", textRes)
}
}
func TestPiReadFileStreamsLargeLogWithOffsetAndTruncatesLongLine(t *testing.T) {
r := localToolsFixture(t)
dir := t.TempDir()
path := filepath.Join(dir, "big.log")
var body strings.Builder
for i := 1; i <= 30000; i++ {
if i == 100 {
body.WriteString(strings.Repeat("x", 8000) + "\n")
continue
}
body.WriteString("log entry " + strings.Repeat("y", 120) + "\n")
}
if err := os.WriteFile(path, []byte(body.String()), 0o600); err != nil {
t.Fatal(err)
}
if st, _ := os.Stat(path); st.Size() <= 3*1024*1024 {
t.Fatalf("fixture must exceed 3 MiB, got %d", st.Size())
}
res := callLocal(t, r, "read_file", map[string]any{"path": path, "offset": float64(95), "limit": float64(20)})
if !strings.Contains(res.Content, "[line truncated]") {
t.Fatalf("long line was not truncated: %d bytes", len(res.Content))
}
if !strings.Contains(res.Content, "next offset 115") {
t.Fatalf("pagination hint missing: %q", res.Content[max(0, len(res.Content)-120):])
}
if len(res.Content) > 64*1024+256 {
t.Fatalf("output exceeded 64 KiB bound: %d", len(res.Content))
}
if strings.Contains(res.Content, strings.Repeat("x", 5000)) {
t.Fatal("full long line leaked into output")
}
}
func TestPiWriteFileCreatesParentsAndEditFilePreservesCRLFAndBatches(t *testing.T) {
r := localToolsFixture(t)
dir := t.TempDir()
nested := filepath.Join(dir, "a", "b", "c", "file.txt")
callLocal(t, r, "write_file", map[string]any{"path": nested, "content": "hi"})
if b, err := os.ReadFile(nested); err != nil || string(b) != "hi" {
t.Fatalf("nested write failed: %q %v", b, err)
}
crlfPath := filepath.Join(dir, "crlf.txt")
if err := os.WriteFile(crlfPath, []byte("alpha\r\nbeta\r\ngamma\r\n"), 0o600); err != nil {
t.Fatal(err)
}
res := callLocal(t, r, "edit_file", map[string]any{"path": crlfPath, "old_text": "beta", "new_text": "BETA"})
if !strings.Contains(res.Content, "first changed line 2") {
t.Fatalf("change summary missing line number: %q", res.Content)
}
if b, _ := os.ReadFile(crlfPath); string(b) != "alpha\r\nBETA\r\ngamma\r\n" {
t.Fatalf("CRLF not preserved: %q", b)
}
batchPath := filepath.Join(dir, "batch.txt")
if err := os.WriteFile(batchPath, []byte("one\ntwo\nthree\n"), 0o600); err != nil {
t.Fatal(err)
}
callLocal(t, r, "edit_file", map[string]any{"path": batchPath, "edits": []any{
map[string]any{"old_text": "one", "new_text": "ONE"},
map[string]any{"old_text": "three", "new_text": "THREE"},
}})
if b, _ := os.ReadFile(batchPath); string(b) != "ONE\ntwo\nTHREE\n" {
t.Fatalf("batch edits failed: %q", b)
}
wsPath := filepath.Join(dir, "ws.txt")
if err := os.WriteFile(wsPath, []byte("a \nb\n"), 0o600); err != nil {
t.Fatal(err)
}
callLocal(t, r, "edit_file", map[string]any{"path": wsPath, "old_text": "a\nb", "new_text": "X\nY"})
if b, _ := os.ReadFile(wsPath); string(b) != "X\nY\n" {
t.Fatalf("whitespace-tolerant match failed: %q", b)
}
dupPath := filepath.Join(dir, "dup.txt")
if err := os.WriteFile(dupPath, []byte("dup\ndup\n"), 0o600); err != nil {
t.Fatal(err)
}
if _, err := r.executePiLocal(context.Background(), agentruntime.ToolCall{Name: "edit_file", Arguments: map[string]any{"path": dupPath, "old_text": "dup", "new_text": "x"}}); err == nil {
t.Fatal("ambiguous match must fail")
}
}
func TestPiGlobRecursivePatternsAndGrepBinarySkipAndTruncation(t *testing.T) {
r := localToolsFixture(t)
dir := t.TempDir()
files := map[string]string{
"a.go": "package a\n",
"sub/b.go": "package b\n",
"sub/deep/c.go": "package c\n",
"sub/d.txt": "text d\n",
"sub/e.txt": "text e\n",
}
for rel, content := range files {
p := filepath.Join(dir, rel)
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
}
goHits := callLocal(t, r, "glob", map[string]any{"path": dir, "pattern": "**/*.go"})
if n := len(strings.Split(strings.TrimSpace(goHits.Content), "\n")); n != 3 {
t.Fatalf("**/*.go matched %d, want 3: %q", n, goHits.Content)
}
txtHits := callLocal(t, r, "glob", map[string]any{"path": dir, "pattern": "./sub/*.txt"})
if n := len(strings.Split(strings.TrimSpace(txtHits.Content), "\n")); n != 2 {
t.Fatalf("./sub/*.txt matched %d, want 2: %q", n, txtHits.Content)
}
longLine := "NEEDLE " + strings.Repeat("z", 900)
if err := os.WriteFile(filepath.Join(dir, "code.go"), []byte("short\n"+longLine+"\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "bin.dat"), []byte("NEEDLE\x00binary payload"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "note.txt"), []byte("NEEDLE short line\n"), 0o600); err != nil {
t.Fatal(err)
}
grepRes := callLocal(t, r, "grep", map[string]any{"path": dir, "pattern": "NEEDLE"})
if strings.Contains(grepRes.Content, "bin.dat") {
t.Fatalf("binary file was not skipped: %q", grepRes.Content)
}
if !strings.Contains(grepRes.Content, "... [truncated]") {
t.Fatalf("long grep line not truncated: %q", grepRes.Content)
}
if strings.Contains(grepRes.Content, strings.Repeat("z", 600)) {
t.Fatal("full long grep line leaked")
}
for _, line := range strings.Split(grepRes.Content, "\n") {
if strings.HasSuffix(line, "... [truncated]") {
body := strings.TrimSuffix(line, "... [truncated]")
if idx := strings.LastIndex(body, ":"); idx >= 0 {
if runes := len([]rune(body[idx+1:])); runes > 500 {
t.Fatalf("truncated line still %d runes", runes)
}
}
}
}
includeRes := callLocal(t, r, "grep", map[string]any{"path": dir, "pattern": "NEEDLE", "include": "*.txt"})
if strings.Contains(includeRes.Content, "code.go") || !strings.Contains(includeRes.Content, "note.txt") {
t.Fatalf("include filter failed: %q", includeRes.Content)
}
}