CyberStrikeAI/internal/multiagent/pi_local_tools_test.go

242 lines
8.8 KiB
Go

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)
}
if strings.TrimSpace(res.ExecutionID) == "" {
t.Fatalf("image read_file skipped local execution receipt: %+v", res)
}
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)
}
// GIF89a polyglot payloads sniff as image/gif via magic bytes and must fall back to text.
polyglotBody := "GIF89a; <?php echo 'polyglot-check'; ?>"
for _, ext := range []string{".php", ".gif"} {
poly := filepath.Join(dir, "sample"+ext)
if err := os.WriteFile(poly, []byte(polyglotBody), 0o600); err != nil {
t.Fatal(err)
}
polyRes := callLocal(t, r, "read_file", map[string]any{"path": poly})
if len(polyRes.Images) != 0 || polyRes.Content != polyglotBody {
t.Fatalf("GIF89a polyglot (%s) did not fall back to text: %+v", ext, polyRes)
}
}
}
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")
}
// Over-buffer (>64 KiB) final line without a trailing newline must not be dropped at EOF.
noNL := filepath.Join(dir, "no-trailing-newline.txt")
if err := os.WriteFile(noNL, []byte(strings.Repeat("Q", 64*1024)), 0o600); err != nil {
t.Fatal(err)
}
eofRes := callLocal(t, r, "read_file", map[string]any{"path": noNL})
if !strings.HasPrefix(eofRes.Content, strings.Repeat("Q", 4096)+" [line truncated]") {
t.Fatalf("64 KiB line without newline lost at EOF: len=%d", len(eofRes.Content))
}
}
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)
}
}